]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
lavf: preserve side data when parsing packets.
[ffmpeg] / libavformat / matroskadec.c
1 /*
2  * Matroska file demuxer
3  * Copyright (c) 2003-2008 The Libav Project
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Matroska file demuxer
25  * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28  * @see specs available on the Matroska project page: http://www.matroska.org/
29  */
30
31 #include <stdio.h>
32 #include "avformat.h"
33 #include "internal.h"
34 #include "avio_internal.h"
35 /* For ff_codec_get_id(). */
36 #include "riff.h"
37 #include "isom.h"
38 #include "rmsipr.h"
39 #include "matroska.h"
40 #include "libavcodec/bytestream.h"
41 #include "libavcodec/mpeg4audio.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/lzo.h"
46 #include "libavutil/dict.h"
47 #if CONFIG_ZLIB
48 #include <zlib.h>
49 #endif
50 #if CONFIG_BZLIB
51 #include <bzlib.h>
52 #endif
53
54 typedef enum {
55     EBML_NONE,
56     EBML_UINT,
57     EBML_FLOAT,
58     EBML_STR,
59     EBML_UTF8,
60     EBML_BIN,
61     EBML_NEST,
62     EBML_PASS,
63     EBML_STOP,
64     EBML_TYPE_COUNT
65 } EbmlType;
66
67 typedef const struct EbmlSyntax {
68     uint32_t id;
69     EbmlType type;
70     int list_elem_size;
71     int data_offset;
72     union {
73         uint64_t    u;
74         double      f;
75         const char *s;
76         const struct EbmlSyntax *n;
77     } def;
78 } EbmlSyntax;
79
80 typedef struct {
81     int nb_elem;
82     void *elem;
83 } EbmlList;
84
85 typedef struct {
86     int      size;
87     uint8_t *data;
88     int64_t  pos;
89 } EbmlBin;
90
91 typedef struct {
92     uint64_t version;
93     uint64_t max_size;
94     uint64_t id_length;
95     char    *doctype;
96     uint64_t doctype_version;
97 } Ebml;
98
99 typedef struct {
100     uint64_t algo;
101     EbmlBin  settings;
102 } MatroskaTrackCompression;
103
104 typedef struct {
105     uint64_t scope;
106     uint64_t type;
107     MatroskaTrackCompression compression;
108 } MatroskaTrackEncoding;
109
110 typedef struct {
111     double   frame_rate;
112     uint64_t display_width;
113     uint64_t display_height;
114     uint64_t pixel_width;
115     uint64_t pixel_height;
116     uint64_t fourcc;
117 } MatroskaTrackVideo;
118
119 typedef struct {
120     double   samplerate;
121     double   out_samplerate;
122     uint64_t bitdepth;
123     uint64_t channels;
124
125     /* real audio header (extracted from extradata) */
126     int      coded_framesize;
127     int      sub_packet_h;
128     int      frame_size;
129     int      sub_packet_size;
130     int      sub_packet_cnt;
131     int      pkt_cnt;
132     uint64_t buf_timecode;
133     uint8_t *buf;
134 } MatroskaTrackAudio;
135
136 typedef struct {
137     uint64_t num;
138     uint64_t uid;
139     uint64_t type;
140     char    *name;
141     char    *codec_id;
142     EbmlBin  codec_priv;
143     char    *language;
144     double time_scale;
145     uint64_t default_duration;
146     uint64_t flag_default;
147     uint64_t flag_forced;
148     MatroskaTrackVideo video;
149     MatroskaTrackAudio audio;
150     EbmlList encodings;
151
152     AVStream *stream;
153     int64_t end_timecode;
154     int ms_compat;
155 } MatroskaTrack;
156
157 typedef struct {
158     uint64_t uid;
159     char *filename;
160     char *mime;
161     EbmlBin bin;
162
163     AVStream *stream;
164 } MatroskaAttachement;
165
166 typedef struct {
167     uint64_t start;
168     uint64_t end;
169     uint64_t uid;
170     char    *title;
171
172     AVChapter *chapter;
173 } MatroskaChapter;
174
175 typedef struct {
176     uint64_t track;
177     uint64_t pos;
178 } MatroskaIndexPos;
179
180 typedef struct {
181     uint64_t time;
182     EbmlList pos;
183 } MatroskaIndex;
184
185 typedef struct {
186     char *name;
187     char *string;
188     char *lang;
189     uint64_t def;
190     EbmlList sub;
191 } MatroskaTag;
192
193 typedef struct {
194     char    *type;
195     uint64_t typevalue;
196     uint64_t trackuid;
197     uint64_t chapteruid;
198     uint64_t attachuid;
199 } MatroskaTagTarget;
200
201 typedef struct {
202     MatroskaTagTarget target;
203     EbmlList tag;
204 } MatroskaTags;
205
206 typedef struct {
207     uint64_t id;
208     uint64_t pos;
209 } MatroskaSeekhead;
210
211 typedef struct {
212     uint64_t start;
213     uint64_t length;
214 } MatroskaLevel;
215
216 typedef struct {
217     uint64_t timecode;
218     EbmlList blocks;
219 } MatroskaCluster;
220
221 typedef struct {
222     AVFormatContext *ctx;
223
224     /* EBML stuff */
225     int num_levels;
226     MatroskaLevel levels[EBML_MAX_DEPTH];
227     int level_up;
228     uint32_t current_id;
229
230     uint64_t time_scale;
231     double   duration;
232     char    *title;
233     EbmlList tracks;
234     EbmlList attachments;
235     EbmlList chapters;
236     EbmlList index;
237     EbmlList tags;
238     EbmlList seekhead;
239
240     /* byte position of the segment inside the stream */
241     int64_t segment_start;
242
243     /* the packet queue */
244     AVPacket **packets;
245     int num_packets;
246     AVPacket *prev_pkt;
247
248     int done;
249
250     /* What to skip before effectively reading a packet. */
251     int skip_to_keyframe;
252     uint64_t skip_to_timecode;
253
254     /* File has a CUES element, but we defer parsing until it is needed. */
255     int cues_parsing_deferred;
256
257     int current_cluster_num_blocks;
258     int64_t current_cluster_pos;
259     MatroskaCluster current_cluster;
260
261     /* File has SSA subtitles which prevent incremental cluster parsing. */
262     int contains_ssa;
263 } MatroskaDemuxContext;
264
265 typedef struct {
266     uint64_t duration;
267     int64_t  reference;
268     uint64_t non_simple;
269     EbmlBin  bin;
270 } MatroskaBlock;
271
272 static EbmlSyntax ebml_header[] = {
273     { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
274     { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
275     { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
276     { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
277     { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
278     { EBML_ID_EBMLVERSION,            EBML_NONE },
279     { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
280     { 0 }
281 };
282
283 static EbmlSyntax ebml_syntax[] = {
284     { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
285     { 0 }
286 };
287
288 static EbmlSyntax matroska_info[] = {
289     { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
290     { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
291     { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
292     { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
293     { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
294     { MATROSKA_ID_DATEUTC,            EBML_NONE },
295     { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
296     { 0 }
297 };
298
299 static EbmlSyntax matroska_track_video[] = {
300     { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
301     { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
302     { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
303     { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
304     { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
305     { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
306     { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
307     { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
308     { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
309     { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
310     { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
311     { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
312     { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
313     { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
314     { 0 }
315 };
316
317 static EbmlSyntax matroska_track_audio[] = {
318     { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
319     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
320     { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
321     { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
322     { 0 }
323 };
324
325 static EbmlSyntax matroska_track_encoding_compression[] = {
326     { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
327     { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
328     { 0 }
329 };
330
331 static EbmlSyntax matroska_track_encoding[] = {
332     { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
333     { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
334     { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
335     { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
336     { 0 }
337 };
338
339 static EbmlSyntax matroska_track_encodings[] = {
340     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
341     { 0 }
342 };
343
344 static EbmlSyntax matroska_track[] = {
345     { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
346     { MATROSKA_ID_TRACKNAME,            EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
347     { MATROSKA_ID_TRACKUID,             EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
348     { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
349     { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
350     { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
351     { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
352     { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
353     { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
354     { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
355     { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
356     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
357     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
358     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
359     { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
360     { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
361     { MATROSKA_ID_CODECNAME,            EBML_NONE },
362     { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
363     { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
364     { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
365     { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
366     { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
367     { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
368     { 0 }
369 };
370
371 static EbmlSyntax matroska_tracks[] = {
372     { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
373     { 0 }
374 };
375
376 static EbmlSyntax matroska_attachment[] = {
377     { MATROSKA_ID_FILEUID,            EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
378     { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
379     { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
380     { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
381     { MATROSKA_ID_FILEDESC,           EBML_NONE },
382     { 0 }
383 };
384
385 static EbmlSyntax matroska_attachments[] = {
386     { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
387     { 0 }
388 };
389
390 static EbmlSyntax matroska_chapter_display[] = {
391     { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
392     { MATROSKA_ID_CHAPLANG,           EBML_NONE },
393     { 0 }
394 };
395
396 static EbmlSyntax matroska_chapter_entry[] = {
397     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
398     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
399     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
400     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
401     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
402     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
403     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
404     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
405     { 0 }
406 };
407
408 static EbmlSyntax matroska_chapter[] = {
409     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
410     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
411     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
412     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
413     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
414     { 0 }
415 };
416
417 static EbmlSyntax matroska_chapters[] = {
418     { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
419     { 0 }
420 };
421
422 static EbmlSyntax matroska_index_pos[] = {
423     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
424     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
425     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
426     { 0 }
427 };
428
429 static EbmlSyntax matroska_index_entry[] = {
430     { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
431     { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
432     { 0 }
433 };
434
435 static EbmlSyntax matroska_index[] = {
436     { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
437     { 0 }
438 };
439
440 static EbmlSyntax matroska_simpletag[] = {
441     { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
442     { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
443     { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
444     { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
445     { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
446     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
447     { 0 }
448 };
449
450 static EbmlSyntax matroska_tagtargets[] = {
451     { MATROSKA_ID_TAGTARGETS_TYPE,      EBML_STR,  0, offsetof(MatroskaTagTarget,type) },
452     { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
453     { MATROSKA_ID_TAGTARGETS_TRACKUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
454     { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
455     { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
456     { 0 }
457 };
458
459 static EbmlSyntax matroska_tag[] = {
460     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
461     { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
462     { 0 }
463 };
464
465 static EbmlSyntax matroska_tags[] = {
466     { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
467     { 0 }
468 };
469
470 static EbmlSyntax matroska_seekhead_entry[] = {
471     { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
472     { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
473     { 0 }
474 };
475
476 static EbmlSyntax matroska_seekhead[] = {
477     { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
478     { 0 }
479 };
480
481 static EbmlSyntax matroska_segment[] = {
482     { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
483     { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
484     { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
485     { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
486     { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
487     { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
488     { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
489     { MATROSKA_ID_CLUSTER,        EBML_STOP },
490     { 0 }
491 };
492
493 static EbmlSyntax matroska_segments[] = {
494     { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
495     { 0 }
496 };
497
498 static EbmlSyntax matroska_blockgroup[] = {
499     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
500     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
501     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
502     { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
503     { MATROSKA_ID_CODECSTATE,     EBML_NONE },
504     { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
505     { 0 }
506 };
507
508 static EbmlSyntax matroska_cluster[] = {
509     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
510     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
511     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
512     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
513     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
514     { 0 }
515 };
516
517 static EbmlSyntax matroska_clusters[] = {
518     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
519     { MATROSKA_ID_INFO,           EBML_NONE },
520     { MATROSKA_ID_CUES,           EBML_NONE },
521     { MATROSKA_ID_TAGS,           EBML_NONE },
522     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
523     { 0 }
524 };
525
526 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
527     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
528     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
529     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
530     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
531     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
532     { MATROSKA_ID_INFO,           EBML_NONE },
533     { MATROSKA_ID_CUES,           EBML_NONE },
534     { MATROSKA_ID_TAGS,           EBML_NONE },
535     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
536     { MATROSKA_ID_CLUSTER,        EBML_STOP },
537     { 0 }
538 };
539
540 static EbmlSyntax matroska_cluster_incremental[] = {
541     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
542     { MATROSKA_ID_BLOCKGROUP,     EBML_STOP },
543     { MATROSKA_ID_SIMPLEBLOCK,    EBML_STOP },
544     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
545     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
546     { 0 }
547 };
548
549 static EbmlSyntax matroska_clusters_incremental[] = {
550     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
551     { MATROSKA_ID_INFO,           EBML_NONE },
552     { MATROSKA_ID_CUES,           EBML_NONE },
553     { MATROSKA_ID_TAGS,           EBML_NONE },
554     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
555     { 0 }
556 };
557
558 static const char *const matroska_doctypes[] = { "matroska", "webm" };
559
560 /*
561  * Return: Whether we reached the end of a level in the hierarchy or not.
562  */
563 static int ebml_level_end(MatroskaDemuxContext *matroska)
564 {
565     AVIOContext *pb = matroska->ctx->pb;
566     int64_t pos = avio_tell(pb);
567
568     if (matroska->num_levels > 0) {
569         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
570         if (pos - level->start >= level->length || matroska->current_id) {
571             matroska->num_levels--;
572             return 1;
573         }
574     }
575     return 0;
576 }
577
578 /*
579  * Read: an "EBML number", which is defined as a variable-length
580  * array of bytes. The first byte indicates the length by giving a
581  * number of 0-bits followed by a one. The position of the first
582  * "one" bit inside the first byte indicates the length of this
583  * number.
584  * Returns: number of bytes read, < 0 on error
585  */
586 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
587                          int max_size, uint64_t *number)
588 {
589     int read = 1, n = 1;
590     uint64_t total = 0;
591
592     /* The first byte tells us the length in bytes - avio_r8() can normally
593      * return 0, but since that's not a valid first ebmlID byte, we can
594      * use it safely here to catch EOS. */
595     if (!(total = avio_r8(pb))) {
596         /* we might encounter EOS here */
597         if (!pb->eof_reached) {
598             int64_t pos = avio_tell(pb);
599             av_log(matroska->ctx, AV_LOG_ERROR,
600                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
601                    pos, pos);
602             return pb->error ? pb->error : AVERROR(EIO);
603         }
604         return AVERROR_EOF;
605     }
606
607     /* get the length of the EBML number */
608     read = 8 - ff_log2_tab[total];
609     if (read > max_size) {
610         int64_t pos = avio_tell(pb) - 1;
611         av_log(matroska->ctx, AV_LOG_ERROR,
612                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
613                (uint8_t) total, pos, pos);
614         return AVERROR_INVALIDDATA;
615     }
616
617     /* read out length */
618     total ^= 1 << ff_log2_tab[total];
619     while (n++ < read)
620         total = (total << 8) | avio_r8(pb);
621
622     *number = total;
623
624     return read;
625 }
626
627 /**
628  * Read a EBML length value.
629  * This needs special handling for the "unknown length" case which has multiple
630  * encodings.
631  */
632 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
633                             uint64_t *number)
634 {
635     int res = ebml_read_num(matroska, pb, 8, number);
636     if (res > 0 && *number + 1 == 1ULL << (7 * res))
637         *number = 0xffffffffffffffULL;
638     return res;
639 }
640
641 /*
642  * Read the next element as an unsigned int.
643  * 0 is success, < 0 is failure.
644  */
645 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
646 {
647     int n = 0;
648
649     if (size > 8)
650         return AVERROR_INVALIDDATA;
651
652     /* big-endian ordering; build up number */
653     *num = 0;
654     while (n++ < size)
655         *num = (*num << 8) | avio_r8(pb);
656
657     return 0;
658 }
659
660 /*
661  * Read the next element as a float.
662  * 0 is success, < 0 is failure.
663  */
664 static int ebml_read_float(AVIOContext *pb, int size, double *num)
665 {
666     if (size == 0) {
667         *num = 0;
668     } else if (size == 4) {
669         *num = av_int2float(avio_rb32(pb));
670     } else if (size == 8){
671         *num = av_int2double(avio_rb64(pb));
672     } else
673         return AVERROR_INVALIDDATA;
674
675     return 0;
676 }
677
678 /*
679  * Read the next element as an ASCII string.
680  * 0 is success, < 0 is failure.
681  */
682 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
683 {
684     char *res;
685
686     /* EBML strings are usually not 0-terminated, so we allocate one
687      * byte more, read the string and NULL-terminate it ourselves. */
688     if (!(res = av_malloc(size + 1)))
689         return AVERROR(ENOMEM);
690     if (avio_read(pb, (uint8_t *) res, size) != size) {
691         av_free(res);
692         return AVERROR(EIO);
693     }
694     (res)[size] = '\0';
695     av_free(*str);
696     *str = res;
697
698     return 0;
699 }
700
701 /*
702  * Read the next element as binary data.
703  * 0 is success, < 0 is failure.
704  */
705 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
706 {
707     av_free(bin->data);
708     if (!(bin->data = av_malloc(length)))
709         return AVERROR(ENOMEM);
710
711     bin->size = length;
712     bin->pos  = avio_tell(pb);
713     if (avio_read(pb, bin->data, length) != length) {
714         av_freep(&bin->data);
715         return AVERROR(EIO);
716     }
717
718     return 0;
719 }
720
721 /*
722  * Read the next element, but only the header. The contents
723  * are supposed to be sub-elements which can be read separately.
724  * 0 is success, < 0 is failure.
725  */
726 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
727 {
728     AVIOContext *pb = matroska->ctx->pb;
729     MatroskaLevel *level;
730
731     if (matroska->num_levels >= EBML_MAX_DEPTH) {
732         av_log(matroska->ctx, AV_LOG_ERROR,
733                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
734         return AVERROR(ENOSYS);
735     }
736
737     level = &matroska->levels[matroska->num_levels++];
738     level->start = avio_tell(pb);
739     level->length = length;
740
741     return 0;
742 }
743
744 /*
745  * Read signed/unsigned "EBML" numbers.
746  * Return: number of bytes processed, < 0 on error
747  */
748 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
749                                  uint8_t *data, uint32_t size, uint64_t *num)
750 {
751     AVIOContext pb;
752     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
753     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
754 }
755
756 /*
757  * Same as above, but signed.
758  */
759 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
760                                  uint8_t *data, uint32_t size, int64_t *num)
761 {
762     uint64_t unum;
763     int res;
764
765     /* read as unsigned number first */
766     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
767         return res;
768
769     /* make signed (weird way) */
770     *num = unum - ((1LL << (7*res - 1)) - 1);
771
772     return res;
773 }
774
775 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
776                            EbmlSyntax *syntax, void *data);
777
778 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
779                          uint32_t id, void *data)
780 {
781     int i;
782     for (i=0; syntax[i].id; i++)
783         if (id == syntax[i].id)
784             break;
785     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
786         matroska->num_levels > 0 &&
787         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
788         return 0;  // we reached the end of an unknown size cluster
789     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
790         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
791         if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
792             return AVERROR_INVALIDDATA;
793     }
794     return ebml_parse_elem(matroska, &syntax[i], data);
795 }
796
797 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
798                       void *data)
799 {
800     if (!matroska->current_id) {
801         uint64_t id;
802         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
803         if (res < 0)
804             return res;
805         matroska->current_id = id | 1 << 7*res;
806     }
807     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
808 }
809
810 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
811                            void *data)
812 {
813     int i, res = 0;
814
815     for (i=0; syntax[i].id; i++)
816         switch (syntax[i].type) {
817         case EBML_UINT:
818             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
819             break;
820         case EBML_FLOAT:
821             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
822             break;
823         case EBML_STR:
824         case EBML_UTF8:
825             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
826             break;
827         }
828
829     while (!res && !ebml_level_end(matroska))
830         res = ebml_parse(matroska, syntax, data);
831
832     return res;
833 }
834
835 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
836                            EbmlSyntax *syntax, void *data)
837 {
838     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
839         [EBML_UINT]  = 8,
840         [EBML_FLOAT] = 8,
841         // max. 16 MB for strings
842         [EBML_STR]   = 0x1000000,
843         [EBML_UTF8]  = 0x1000000,
844         // max. 256 MB for binary data
845         [EBML_BIN]   = 0x10000000,
846         // no limits for anything else
847     };
848     AVIOContext *pb = matroska->ctx->pb;
849     uint32_t id = syntax->id;
850     uint64_t length;
851     int res;
852     void *newelem;
853
854     data = (char *)data + syntax->data_offset;
855     if (syntax->list_elem_size) {
856         EbmlList *list = data;
857         newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
858         if (!newelem)
859             return AVERROR(ENOMEM);
860         list->elem = newelem;
861         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
862         memset(data, 0, syntax->list_elem_size);
863         list->nb_elem++;
864     }
865
866     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
867         matroska->current_id = 0;
868         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
869             return res;
870         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
871             av_log(matroska->ctx, AV_LOG_ERROR,
872                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
873                    length, max_lengths[syntax->type], syntax->type);
874             return AVERROR_INVALIDDATA;
875         }
876     }
877
878     switch (syntax->type) {
879     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
880     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
881     case EBML_STR:
882     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
883     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
884     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
885                          return res;
886                      if (id == MATROSKA_ID_SEGMENT)
887                          matroska->segment_start = avio_tell(matroska->ctx->pb);
888                      return ebml_parse_nest(matroska, syntax->def.n, data);
889     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
890     case EBML_STOP:  return 1;
891     default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
892     }
893     if (res == AVERROR_INVALIDDATA)
894         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
895     else if (res == AVERROR(EIO))
896         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
897     return res;
898 }
899
900 static void ebml_free(EbmlSyntax *syntax, void *data)
901 {
902     int i, j;
903     for (i=0; syntax[i].id; i++) {
904         void *data_off = (char *)data + syntax[i].data_offset;
905         switch (syntax[i].type) {
906         case EBML_STR:
907         case EBML_UTF8:  av_freep(data_off);                      break;
908         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
909         case EBML_NEST:
910             if (syntax[i].list_elem_size) {
911                 EbmlList *list = data_off;
912                 char *ptr = list->elem;
913                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
914                     ebml_free(syntax[i].def.n, ptr);
915                 av_free(list->elem);
916             } else
917                 ebml_free(syntax[i].def.n, data_off);
918         default:  break;
919         }
920     }
921 }
922
923
924 /*
925  * Autodetecting...
926  */
927 static int matroska_probe(AVProbeData *p)
928 {
929     uint64_t total = 0;
930     int len_mask = 0x80, size = 1, n = 1, i;
931
932     /* EBML header? */
933     if (AV_RB32(p->buf) != EBML_ID_HEADER)
934         return 0;
935
936     /* length of header */
937     total = p->buf[4];
938     while (size <= 8 && !(total & len_mask)) {
939         size++;
940         len_mask >>= 1;
941     }
942     if (size > 8)
943       return 0;
944     total &= (len_mask - 1);
945     while (n < size)
946         total = (total << 8) | p->buf[4 + n++];
947
948     /* Does the probe data contain the whole header? */
949     if (p->buf_size < 4 + size + total)
950       return 0;
951
952     /* The header should contain a known document type. For now,
953      * we don't parse the whole header but simply check for the
954      * availability of that array of characters inside the header.
955      * Not fully fool-proof, but good enough. */
956     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
957         int probelen = strlen(matroska_doctypes[i]);
958         if (total < probelen)
959             continue;
960         for (n = 4+size; n <= 4+size+total-probelen; n++)
961             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
962                 return AVPROBE_SCORE_MAX;
963     }
964
965     // probably valid EBML header but no recognized doctype
966     return AVPROBE_SCORE_EXTENSION;
967 }
968
969 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
970                                                  int num)
971 {
972     MatroskaTrack *tracks = matroska->tracks.elem;
973     int i;
974
975     for (i=0; i < matroska->tracks.nb_elem; i++)
976         if (tracks[i].num == num)
977             return &tracks[i];
978
979     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
980     return NULL;
981 }
982
983 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
984                                   MatroskaTrack *track)
985 {
986     MatroskaTrackEncoding *encodings = track->encodings.elem;
987     uint8_t* data = *buf;
988     int isize = *buf_size;
989     uint8_t* pkt_data = NULL;
990     uint8_t av_unused *newpktdata;
991     int pkt_size = isize;
992     int result = 0;
993     int olen;
994
995     if (pkt_size >= 10000000)
996         return AVERROR_INVALIDDATA;
997
998     switch (encodings[0].compression.algo) {
999     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
1000         int header_size = encodings[0].compression.settings.size;
1001         uint8_t *header = encodings[0].compression.settings.data;
1002
1003         if (!header_size)
1004             return 0;
1005
1006         pkt_size = isize + header_size;
1007         pkt_data = av_malloc(pkt_size);
1008         if (!pkt_data)
1009             return AVERROR(ENOMEM);
1010
1011         memcpy(pkt_data, header, header_size);
1012         memcpy(pkt_data + header_size, data, isize);
1013         break;
1014     }
1015 #if CONFIG_LZO
1016     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1017         do {
1018             olen = pkt_size *= 3;
1019             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1020             if (!newpktdata) {
1021                 result = AVERROR(ENOMEM);
1022                 goto failed;
1023             }
1024             pkt_data = newpktdata;
1025             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1026         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1027         if (result) {
1028             result = AVERROR_INVALIDDATA;
1029             goto failed;
1030         }
1031         pkt_size -= olen;
1032         break;
1033 #endif
1034 #if CONFIG_ZLIB
1035     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1036         z_stream zstream = {0};
1037         if (inflateInit(&zstream) != Z_OK)
1038             return -1;
1039         zstream.next_in = data;
1040         zstream.avail_in = isize;
1041         do {
1042             pkt_size *= 3;
1043             newpktdata = av_realloc(pkt_data, pkt_size);
1044             if (!newpktdata) {
1045                 inflateEnd(&zstream);
1046                 goto failed;
1047             }
1048             pkt_data = newpktdata;
1049             zstream.avail_out = pkt_size - zstream.total_out;
1050             zstream.next_out = pkt_data + zstream.total_out;
1051             result = inflate(&zstream, Z_NO_FLUSH);
1052         } while (result==Z_OK && pkt_size<10000000);
1053         pkt_size = zstream.total_out;
1054         inflateEnd(&zstream);
1055         if (result != Z_STREAM_END) {
1056             if (result == Z_MEM_ERROR)
1057                 result = AVERROR(ENOMEM);
1058             else
1059                 result = AVERROR_INVALIDDATA;
1060             goto failed;
1061         }
1062         break;
1063     }
1064 #endif
1065 #if CONFIG_BZLIB
1066     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1067         bz_stream bzstream = {0};
1068         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1069             return -1;
1070         bzstream.next_in = data;
1071         bzstream.avail_in = isize;
1072         do {
1073             pkt_size *= 3;
1074             newpktdata = av_realloc(pkt_data, pkt_size);
1075             if (!newpktdata) {
1076                 BZ2_bzDecompressEnd(&bzstream);
1077                 goto failed;
1078             }
1079             pkt_data = newpktdata;
1080             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1081             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1082             result = BZ2_bzDecompress(&bzstream);
1083         } while (result==BZ_OK && pkt_size<10000000);
1084         pkt_size = bzstream.total_out_lo32;
1085         BZ2_bzDecompressEnd(&bzstream);
1086         if (result != BZ_STREAM_END) {
1087             if (result == BZ_MEM_ERROR)
1088                 result = AVERROR(ENOMEM);
1089             else
1090                 result = AVERROR_INVALIDDATA;
1091             goto failed;
1092         }
1093         break;
1094     }
1095 #endif
1096     default:
1097         return AVERROR_INVALIDDATA;
1098     }
1099
1100     *buf = pkt_data;
1101     *buf_size = pkt_size;
1102     return 0;
1103  failed:
1104     av_free(pkt_data);
1105     return result;
1106 }
1107
1108 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1109                                     AVPacket *pkt, uint64_t display_duration)
1110 {
1111     AVBufferRef *line;
1112     char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1113     for (; *ptr!=',' && ptr<end-1; ptr++);
1114     if (*ptr == ',')
1115         layer = ++ptr;
1116     for (; *ptr!=',' && ptr<end-1; ptr++);
1117     if (*ptr == ',') {
1118         int64_t end_pts = pkt->pts + display_duration;
1119         int sc = matroska->time_scale * pkt->pts / 10000000;
1120         int ec = matroska->time_scale * end_pts  / 10000000;
1121         int sh, sm, ss, eh, em, es, len;
1122         sh = sc/360000;  sc -= 360000*sh;
1123         sm = sc/  6000;  sc -=   6000*sm;
1124         ss = sc/   100;  sc -=    100*ss;
1125         eh = ec/360000;  ec -= 360000*eh;
1126         em = ec/  6000;  ec -=   6000*em;
1127         es = ec/   100;  ec -=    100*es;
1128         *ptr++ = '\0';
1129         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1130         if (!(line = av_buffer_alloc(len)))
1131             return;
1132         snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1133                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1134         av_buffer_unref(&pkt->buf);
1135         pkt->buf  = line;
1136         pkt->data = line->data;
1137         pkt->size = strlen(line->data);
1138     }
1139 }
1140
1141 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1142 {
1143     int old_size = out->size;
1144     int ret = av_grow_packet(out, in->size);
1145     if (ret < 0)
1146         return ret;
1147
1148     memcpy(out->data + old_size, in->data, in->size);
1149
1150     av_free_packet(in);
1151     av_free(in);
1152     return 0;
1153 }
1154
1155 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1156                                  AVDictionary **metadata, char *prefix)
1157 {
1158     MatroskaTag *tags = list->elem;
1159     char key[1024];
1160     int i;
1161
1162     for (i=0; i < list->nb_elem; i++) {
1163         const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1164
1165         if (!tags[i].name) {
1166             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1167             continue;
1168         }
1169         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1170         else         av_strlcpy(key, tags[i].name, sizeof(key));
1171         if (tags[i].def || !lang) {
1172         av_dict_set(metadata, key, tags[i].string, 0);
1173         if (tags[i].sub.nb_elem)
1174             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1175         }
1176         if (lang) {
1177             av_strlcat(key, "-", sizeof(key));
1178             av_strlcat(key, lang, sizeof(key));
1179             av_dict_set(metadata, key, tags[i].string, 0);
1180             if (tags[i].sub.nb_elem)
1181                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1182         }
1183     }
1184     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1185 }
1186
1187 static void matroska_convert_tags(AVFormatContext *s)
1188 {
1189     MatroskaDemuxContext *matroska = s->priv_data;
1190     MatroskaTags *tags = matroska->tags.elem;
1191     int i, j;
1192
1193     for (i=0; i < matroska->tags.nb_elem; i++) {
1194         if (tags[i].target.attachuid) {
1195             MatroskaAttachement *attachment = matroska->attachments.elem;
1196             for (j=0; j<matroska->attachments.nb_elem; j++)
1197                 if (attachment[j].uid == tags[i].target.attachuid
1198                     && attachment[j].stream)
1199                     matroska_convert_tag(s, &tags[i].tag,
1200                                          &attachment[j].stream->metadata, NULL);
1201         } else if (tags[i].target.chapteruid) {
1202             MatroskaChapter *chapter = matroska->chapters.elem;
1203             for (j=0; j<matroska->chapters.nb_elem; j++)
1204                 if (chapter[j].uid == tags[i].target.chapteruid
1205                     && chapter[j].chapter)
1206                     matroska_convert_tag(s, &tags[i].tag,
1207                                          &chapter[j].chapter->metadata, NULL);
1208         } else if (tags[i].target.trackuid) {
1209             MatroskaTrack *track = matroska->tracks.elem;
1210             for (j=0; j<matroska->tracks.nb_elem; j++)
1211                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1212                     matroska_convert_tag(s, &tags[i].tag,
1213                                          &track[j].stream->metadata, NULL);
1214         } else {
1215             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1216                                  tags[i].target.type);
1217         }
1218     }
1219 }
1220
1221 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1222 {
1223     EbmlList *seekhead_list = &matroska->seekhead;
1224     MatroskaSeekhead *seekhead = seekhead_list->elem;
1225     uint32_t level_up = matroska->level_up;
1226     int64_t before_pos = avio_tell(matroska->ctx->pb);
1227     uint32_t saved_id = matroska->current_id;
1228     MatroskaLevel level;
1229     int64_t offset;
1230     int ret = 0;
1231
1232     if (idx >= seekhead_list->nb_elem
1233             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1234             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1235         return 0;
1236
1237     /* seek */
1238     offset = seekhead[idx].pos + matroska->segment_start;
1239     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1240         /* We don't want to lose our seekhead level, so we add
1241          * a dummy. This is a crude hack. */
1242         if (matroska->num_levels == EBML_MAX_DEPTH) {
1243             av_log(matroska->ctx, AV_LOG_INFO,
1244                    "Max EBML element depth (%d) reached, "
1245                    "cannot parse further.\n", EBML_MAX_DEPTH);
1246             ret = AVERROR_INVALIDDATA;
1247         } else {
1248             level.start = 0;
1249             level.length = (uint64_t)-1;
1250             matroska->levels[matroska->num_levels] = level;
1251             matroska->num_levels++;
1252             matroska->current_id = 0;
1253
1254             ret = ebml_parse(matroska, matroska_segment, matroska);
1255
1256             /* remove dummy level */
1257             while (matroska->num_levels) {
1258                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1259                 if (length == (uint64_t)-1)
1260                     break;
1261             }
1262         }
1263     }
1264     /* seek back */
1265     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1266     matroska->level_up = level_up;
1267     matroska->current_id = saved_id;
1268
1269     return ret;
1270 }
1271
1272 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1273 {
1274     EbmlList *seekhead_list = &matroska->seekhead;
1275     int64_t before_pos = avio_tell(matroska->ctx->pb);
1276     int i;
1277
1278     // we should not do any seeking in the streaming case
1279     if (!matroska->ctx->pb->seekable ||
1280         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1281         return;
1282
1283     for (i = 0; i < seekhead_list->nb_elem; i++) {
1284         MatroskaSeekhead *seekhead = seekhead_list->elem;
1285         if (seekhead[i].pos <= before_pos)
1286             continue;
1287
1288         // defer cues parsing until we actually need cue data.
1289         if (seekhead[i].id == MATROSKA_ID_CUES) {
1290             matroska->cues_parsing_deferred = 1;
1291             continue;
1292         }
1293
1294         if (matroska_parse_seekhead_entry(matroska, i) < 0)
1295             break;
1296     }
1297 }
1298
1299 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1300     EbmlList *seekhead_list = &matroska->seekhead;
1301     MatroskaSeekhead *seekhead = seekhead_list->elem;
1302     EbmlList *index_list;
1303     MatroskaIndex *index;
1304     int index_scale = 1;
1305     int i, j;
1306
1307     for (i = 0; i < seekhead_list->nb_elem; i++)
1308         if (seekhead[i].id == MATROSKA_ID_CUES)
1309             break;
1310     assert(i <= seekhead_list->nb_elem);
1311
1312     matroska_parse_seekhead_entry(matroska, i);
1313
1314     index_list = &matroska->index;
1315     index = index_list->elem;
1316     if (index_list->nb_elem
1317         && index[0].time > 1E14/matroska->time_scale) {
1318         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1319         index_scale = matroska->time_scale;
1320     }
1321     for (i = 0; i < index_list->nb_elem; i++) {
1322         EbmlList *pos_list = &index[i].pos;
1323         MatroskaIndexPos *pos = pos_list->elem;
1324         for (j = 0; j < pos_list->nb_elem; j++) {
1325             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1326             if (track && track->stream)
1327                 av_add_index_entry(track->stream,
1328                                    pos[j].pos + matroska->segment_start,
1329                                    index[i].time/index_scale, 0, 0,
1330                                    AVINDEX_KEYFRAME);
1331         }
1332     }
1333 }
1334
1335 static int matroska_aac_profile(char *codec_id)
1336 {
1337     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1338     int profile;
1339
1340     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1341         if (strstr(codec_id, aac_profiles[profile]))
1342             break;
1343     return profile + 1;
1344 }
1345
1346 static int matroska_aac_sri(int samplerate)
1347 {
1348     int sri;
1349
1350     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1351         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1352             break;
1353     return sri;
1354 }
1355
1356 static int matroska_read_header(AVFormatContext *s)
1357 {
1358     MatroskaDemuxContext *matroska = s->priv_data;
1359     EbmlList *attachements_list = &matroska->attachments;
1360     MatroskaAttachement *attachements;
1361     EbmlList *chapters_list = &matroska->chapters;
1362     MatroskaChapter *chapters;
1363     MatroskaTrack *tracks;
1364     uint64_t max_start = 0;
1365     Ebml ebml = { 0 };
1366     AVStream *st;
1367     int i, j, res;
1368
1369     matroska->ctx = s;
1370
1371     /* First read the EBML header. */
1372     if (ebml_parse(matroska, ebml_syntax, &ebml)
1373         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1374         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1375         av_log(matroska->ctx, AV_LOG_ERROR,
1376                "EBML header using unsupported features\n"
1377                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1378                ebml.version, ebml.doctype, ebml.doctype_version);
1379         ebml_free(ebml_syntax, &ebml);
1380         return AVERROR_PATCHWELCOME;
1381     }
1382     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1383         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1384             break;
1385     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1386         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1387         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1388             ebml_free(ebml_syntax, &ebml);
1389             return AVERROR_INVALIDDATA;
1390         }
1391     }
1392     ebml_free(ebml_syntax, &ebml);
1393
1394     /* The next thing is a segment. */
1395     if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1396         return res;
1397     matroska_execute_seekhead(matroska);
1398
1399     if (!matroska->time_scale)
1400         matroska->time_scale = 1000000;
1401     if (matroska->duration)
1402         matroska->ctx->duration = matroska->duration * matroska->time_scale
1403                                   * 1000 / AV_TIME_BASE;
1404     av_dict_set(&s->metadata, "title", matroska->title, 0);
1405
1406     tracks = matroska->tracks.elem;
1407     for (i=0; i < matroska->tracks.nb_elem; i++) {
1408         MatroskaTrack *track = &tracks[i];
1409         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1410         EbmlList *encodings_list = &tracks->encodings;
1411         MatroskaTrackEncoding *encodings = encodings_list->elem;
1412         uint8_t *extradata = NULL;
1413         int extradata_size = 0;
1414         int extradata_offset = 0;
1415         AVIOContext b;
1416
1417         /* Apply some sanity checks. */
1418         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1419             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1420             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1421             av_log(matroska->ctx, AV_LOG_INFO,
1422                    "Unknown or unsupported track type %"PRIu64"\n",
1423                    track->type);
1424             continue;
1425         }
1426         if (track->codec_id == NULL)
1427             continue;
1428
1429         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1430             if (!track->default_duration && track->video.frame_rate > 0)
1431                 track->default_duration = 1000000000/track->video.frame_rate;
1432             if (!track->video.display_width)
1433                 track->video.display_width = track->video.pixel_width;
1434             if (!track->video.display_height)
1435                 track->video.display_height = track->video.pixel_height;
1436         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1437             if (!track->audio.out_samplerate)
1438                 track->audio.out_samplerate = track->audio.samplerate;
1439         }
1440         if (encodings_list->nb_elem > 1) {
1441             av_log(matroska->ctx, AV_LOG_ERROR,
1442                    "Multiple combined encodings not supported");
1443         } else if (encodings_list->nb_elem == 1) {
1444             if (encodings[0].type ||
1445                 (
1446 #if CONFIG_ZLIB
1447                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1448 #endif
1449 #if CONFIG_BZLIB
1450                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1451 #endif
1452 #if CONFIG_LZO
1453                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1454 #endif
1455                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
1456                 encodings[0].scope = 0;
1457                 av_log(matroska->ctx, AV_LOG_ERROR,
1458                        "Unsupported encoding type");
1459             } else if (track->codec_priv.size && encodings[0].scope&2) {
1460                 uint8_t *codec_priv = track->codec_priv.data;
1461                 int ret = matroska_decode_buffer(&track->codec_priv.data,
1462                                                  &track->codec_priv.size,
1463                                                  track);
1464                 if (ret < 0) {
1465                     track->codec_priv.data = NULL;
1466                     track->codec_priv.size = 0;
1467                     av_log(matroska->ctx, AV_LOG_ERROR,
1468                            "Failed to decode codec private data\n");
1469                 }
1470
1471                 if (codec_priv != track->codec_priv.data)
1472                     av_free(codec_priv);
1473             }
1474         }
1475
1476         for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1477             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1478                         strlen(ff_mkv_codec_tags[j].str))){
1479                 codec_id= ff_mkv_codec_tags[j].id;
1480                 break;
1481             }
1482         }
1483
1484         st = track->stream = avformat_new_stream(s, NULL);
1485         if (st == NULL)
1486             return AVERROR(ENOMEM);
1487
1488         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1489             && track->codec_priv.size >= 40
1490             && track->codec_priv.data != NULL) {
1491             track->ms_compat = 1;
1492             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1493             codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1494             extradata_offset = 40;
1495         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1496                    && track->codec_priv.size >= 14
1497                    && track->codec_priv.data != NULL) {
1498             int ret;
1499             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1500                               0, NULL, NULL, NULL, NULL);
1501             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1502             if (ret < 0)
1503                 return ret;
1504             codec_id = st->codec->codec_id;
1505             extradata_offset = FFMIN(track->codec_priv.size, 18);
1506         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1507                    && (track->codec_priv.size >= 86)
1508                    && (track->codec_priv.data != NULL)) {
1509             track->video.fourcc = AV_RL32(track->codec_priv.data);
1510             codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
1511         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1512             switch (track->audio.bitdepth) {
1513             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1514             case 24:  codec_id = AV_CODEC_ID_PCM_S24BE;  break;
1515             case 32:  codec_id = AV_CODEC_ID_PCM_S32BE;  break;
1516             }
1517         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1518             switch (track->audio.bitdepth) {
1519             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1520             case 24:  codec_id = AV_CODEC_ID_PCM_S24LE;  break;
1521             case 32:  codec_id = AV_CODEC_ID_PCM_S32LE;  break;
1522             }
1523         } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1524             codec_id = AV_CODEC_ID_PCM_F64LE;
1525         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1526             int profile = matroska_aac_profile(track->codec_id);
1527             int sri = matroska_aac_sri(track->audio.samplerate);
1528             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1529             if (extradata == NULL)
1530                 return AVERROR(ENOMEM);
1531             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1532             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1533             if (strstr(track->codec_id, "SBR")) {
1534                 sri = matroska_aac_sri(track->audio.out_samplerate);
1535                 extradata[2] = 0x56;
1536                 extradata[3] = 0xE5;
1537                 extradata[4] = 0x80 | (sri<<3);
1538                 extradata_size = 5;
1539             } else
1540                 extradata_size = 2;
1541         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
1542             /* Only ALAC's magic cookie is stored in Matroska's track headers.
1543                Create the "atom size", "tag", and "tag version" fields the
1544                decoder expects manually. */
1545             extradata_size = 12 + track->codec_priv.size;
1546             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1547             if (extradata == NULL)
1548                 return AVERROR(ENOMEM);
1549             AV_WB32(extradata, extradata_size);
1550             memcpy(&extradata[4], "alac", 4);
1551             AV_WB32(&extradata[8], 0);
1552             memcpy(&extradata[12], track->codec_priv.data,
1553                                    track->codec_priv.size);
1554         } else if (codec_id == AV_CODEC_ID_TTA) {
1555             extradata_size = 30;
1556             extradata = av_mallocz(extradata_size);
1557             if (extradata == NULL)
1558                 return AVERROR(ENOMEM);
1559             ffio_init_context(&b, extradata, extradata_size, 1,
1560                           NULL, NULL, NULL, NULL);
1561             avio_write(&b, "TTA1", 4);
1562             avio_wl16(&b, 1);
1563             avio_wl16(&b, track->audio.channels);
1564             avio_wl16(&b, track->audio.bitdepth);
1565             avio_wl32(&b, track->audio.out_samplerate);
1566             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1567         } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1568                    codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1569             extradata_offset = 26;
1570         } else if (codec_id == AV_CODEC_ID_RA_144) {
1571             track->audio.out_samplerate = 8000;
1572             track->audio.channels = 1;
1573         } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1574                    codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
1575             int flavor;
1576             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1577                           0, NULL, NULL, NULL, NULL);
1578             avio_skip(&b, 22);
1579             flavor                       = avio_rb16(&b);
1580             track->audio.coded_framesize = avio_rb32(&b);
1581             avio_skip(&b, 12);
1582             track->audio.sub_packet_h    = avio_rb16(&b);
1583             track->audio.frame_size      = avio_rb16(&b);
1584             track->audio.sub_packet_size = avio_rb16(&b);
1585             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1586             if (codec_id == AV_CODEC_ID_RA_288) {
1587                 st->codec->block_align = track->audio.coded_framesize;
1588                 track->codec_priv.size = 0;
1589             } else {
1590                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1591                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1592                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1593                     st->codec->bit_rate = sipr_bit_rate[flavor];
1594                 }
1595                 st->codec->block_align = track->audio.sub_packet_size;
1596                 extradata_offset = 78;
1597             }
1598         }
1599         track->codec_priv.size -= extradata_offset;
1600
1601         if (codec_id == AV_CODEC_ID_NONE)
1602             av_log(matroska->ctx, AV_LOG_INFO,
1603                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1604
1605         if (track->time_scale < 0.01)
1606             track->time_scale = 1.0;
1607         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1608
1609         st->codec->codec_id = codec_id;
1610         st->start_time = 0;
1611         if (strcmp(track->language, "und"))
1612             av_dict_set(&st->metadata, "language", track->language, 0);
1613         av_dict_set(&st->metadata, "title", track->name, 0);
1614
1615         if (track->flag_default)
1616             st->disposition |= AV_DISPOSITION_DEFAULT;
1617         if (track->flag_forced)
1618             st->disposition |= AV_DISPOSITION_FORCED;
1619
1620         if (!st->codec->extradata) {
1621             if(extradata){
1622                 st->codec->extradata = extradata;
1623                 st->codec->extradata_size = extradata_size;
1624             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1625                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1626                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1627                 if(st->codec->extradata == NULL)
1628                     return AVERROR(ENOMEM);
1629                 st->codec->extradata_size = track->codec_priv.size;
1630                 memcpy(st->codec->extradata,
1631                        track->codec_priv.data + extradata_offset,
1632                        track->codec_priv.size);
1633             }
1634         }
1635
1636         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1637             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1638             st->codec->codec_tag  = track->video.fourcc;
1639             st->codec->width  = track->video.pixel_width;
1640             st->codec->height = track->video.pixel_height;
1641             av_reduce(&st->sample_aspect_ratio.num,
1642                       &st->sample_aspect_ratio.den,
1643                       st->codec->height * track->video.display_width,
1644                       st->codec-> width * track->video.display_height,
1645                       255);
1646             if (st->codec->codec_id != AV_CODEC_ID_H264)
1647             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1648             if (track->default_duration) {
1649                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1650                           1000000000, track->default_duration, 30000);
1651             }
1652         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1653             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1654             st->codec->sample_rate = track->audio.out_samplerate;
1655             st->codec->channels = track->audio.channels;
1656             if (st->codec->codec_id != AV_CODEC_ID_AAC)
1657             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1658         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1659             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1660             if (st->codec->codec_id == AV_CODEC_ID_SSA)
1661                 matroska->contains_ssa = 1;
1662         }
1663     }
1664
1665     attachements = attachements_list->elem;
1666     for (j=0; j<attachements_list->nb_elem; j++) {
1667         if (!(attachements[j].filename && attachements[j].mime &&
1668               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1669             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1670         } else {
1671             AVStream *st = avformat_new_stream(s, NULL);
1672             if (st == NULL)
1673                 break;
1674             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1675             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1676             st->codec->codec_id = AV_CODEC_ID_NONE;
1677             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1678             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1679             if(st->codec->extradata == NULL)
1680                 break;
1681             st->codec->extradata_size = attachements[j].bin.size;
1682             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1683
1684             for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1685                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1686                              strlen(ff_mkv_mime_tags[i].str))) {
1687                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1688                     break;
1689                 }
1690             }
1691             attachements[j].stream = st;
1692         }
1693     }
1694
1695     chapters = chapters_list->elem;
1696     for (i=0; i<chapters_list->nb_elem; i++)
1697         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1698             && (max_start==0 || chapters[i].start > max_start)) {
1699             chapters[i].chapter =
1700             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1701                            chapters[i].start, chapters[i].end,
1702                            chapters[i].title);
1703             av_dict_set(&chapters[i].chapter->metadata,
1704                              "title", chapters[i].title, 0);
1705             max_start = chapters[i].start;
1706         }
1707
1708     matroska_convert_tags(s);
1709
1710     return 0;
1711 }
1712
1713 /*
1714  * Put one packet in an application-supplied AVPacket struct.
1715  * Returns 0 on success or -1 on failure.
1716  */
1717 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1718                                    AVPacket *pkt)
1719 {
1720     if (matroska->num_packets > 0) {
1721         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1722         av_free(matroska->packets[0]);
1723         if (matroska->num_packets > 1) {
1724             void *newpackets;
1725             memmove(&matroska->packets[0], &matroska->packets[1],
1726                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1727             newpackets = av_realloc(matroska->packets,
1728                             (matroska->num_packets - 1) * sizeof(AVPacket *));
1729             if (newpackets)
1730                 matroska->packets = newpackets;
1731         } else {
1732             av_freep(&matroska->packets);
1733             matroska->prev_pkt = NULL;
1734         }
1735         matroska->num_packets--;
1736         return 0;
1737     }
1738
1739     return -1;
1740 }
1741
1742 /*
1743  * Free all packets in our internal queue.
1744  */
1745 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1746 {
1747     matroska->prev_pkt = NULL;
1748     if (matroska->packets) {
1749         int n;
1750         for (n = 0; n < matroska->num_packets; n++) {
1751             av_free_packet(matroska->packets[n]);
1752             av_free(matroska->packets[n]);
1753         }
1754         av_freep(&matroska->packets);
1755         matroska->num_packets = 0;
1756     }
1757 }
1758
1759 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
1760                                 int* buf_size, int type,
1761                                 uint32_t **lace_buf, int *laces)
1762 {
1763     int res = 0, n, size = *buf_size;
1764     uint8_t *data = *buf;
1765     uint32_t *lace_size;
1766
1767     if (!type) {
1768         *laces = 1;
1769         *lace_buf = av_mallocz(sizeof(int));
1770         if (!*lace_buf)
1771             return AVERROR(ENOMEM);
1772
1773         *lace_buf[0] = size;
1774         return 0;
1775     }
1776
1777     assert(size > 0);
1778     *laces = *data + 1;
1779     data += 1;
1780     size -= 1;
1781     lace_size = av_mallocz(*laces * sizeof(int));
1782     if (!lace_size)
1783         return AVERROR(ENOMEM);
1784
1785     switch (type) {
1786     case 0x1: /* Xiph lacing */ {
1787         uint8_t temp;
1788         uint32_t total = 0;
1789         for (n = 0; res == 0 && n < *laces - 1; n++) {
1790             while (1) {
1791                 if (size == 0) {
1792                     res = AVERROR_EOF;
1793                     break;
1794                 }
1795                 temp = *data;
1796                 lace_size[n] += temp;
1797                 data += 1;
1798                 size -= 1;
1799                 if (temp != 0xff)
1800                     break;
1801             }
1802             total += lace_size[n];
1803         }
1804         if (size <= total) {
1805             res = AVERROR_INVALIDDATA;
1806             break;
1807         }
1808
1809         lace_size[n] = size - total;
1810         break;
1811     }
1812
1813     case 0x2: /* fixed-size lacing */
1814         if (size % (*laces)) {
1815             res = AVERROR_INVALIDDATA;
1816             break;
1817         }
1818         for (n = 0; n < *laces; n++)
1819             lace_size[n] = size / *laces;
1820         break;
1821
1822     case 0x3: /* EBML lacing */ {
1823         uint64_t num;
1824         uint64_t total;
1825         n = matroska_ebmlnum_uint(matroska, data, size, &num);
1826         if (n < 0) {
1827             av_log(matroska->ctx, AV_LOG_INFO,
1828                    "EBML block data error\n");
1829             res = n;
1830             break;
1831         }
1832         data += n;
1833         size -= n;
1834         total = lace_size[0] = num;
1835         for (n = 1; res == 0 && n < *laces - 1; n++) {
1836             int64_t snum;
1837             int r;
1838             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1839             if (r < 0) {
1840                 av_log(matroska->ctx, AV_LOG_INFO,
1841                        "EBML block data error\n");
1842                 res = r;
1843                 break;
1844             }
1845             data += r;
1846             size -= r;
1847             lace_size[n] = lace_size[n - 1] + snum;
1848             total += lace_size[n];
1849         }
1850         if (size <= total) {
1851             res = AVERROR_INVALIDDATA;
1852             break;
1853         }
1854         lace_size[*laces - 1] = size - total;
1855         break;
1856     }
1857     }
1858
1859     *buf      = data;
1860     *lace_buf = lace_size;
1861     *buf_size = size;
1862
1863     return res;
1864 }
1865
1866 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
1867                                    MatroskaTrack *track,
1868                                    AVStream *st,
1869                                    uint8_t *data, int size,
1870                                    uint64_t timecode, uint64_t duration,
1871                                    int64_t pos)
1872 {
1873     int a = st->codec->block_align;
1874     int sps = track->audio.sub_packet_size;
1875     int cfs = track->audio.coded_framesize;
1876     int h = track->audio.sub_packet_h;
1877     int y = track->audio.sub_packet_cnt;
1878     int w = track->audio.frame_size;
1879     int x;
1880
1881     if (!track->audio.pkt_cnt) {
1882         if (track->audio.sub_packet_cnt == 0)
1883             track->audio.buf_timecode = timecode;
1884         if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
1885             if (size < cfs * h / 2) {
1886                 av_log(matroska->ctx, AV_LOG_ERROR,
1887                        "Corrupt int4 RM-style audio packet size\n");
1888                 return AVERROR_INVALIDDATA;
1889             }
1890             for (x=0; x<h/2; x++)
1891                 memcpy(track->audio.buf+x*2*w+y*cfs,
1892                        data+x*cfs, cfs);
1893         } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
1894             if (size < w) {
1895                 av_log(matroska->ctx, AV_LOG_ERROR,
1896                        "Corrupt sipr RM-style audio packet size\n");
1897                 return AVERROR_INVALIDDATA;
1898             }
1899             memcpy(track->audio.buf + y*w, data, w);
1900         } else {
1901             if (size < sps * w / sps) {
1902                 av_log(matroska->ctx, AV_LOG_ERROR,
1903                        "Corrupt generic RM-style audio packet size\n");
1904                 return AVERROR_INVALIDDATA;
1905             }
1906             for (x=0; x<w/sps; x++)
1907                 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1908         }
1909
1910         if (++track->audio.sub_packet_cnt >= h) {
1911             if (st->codec->codec_id == AV_CODEC_ID_SIPR)
1912                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1913             track->audio.sub_packet_cnt = 0;
1914             track->audio.pkt_cnt = h*w / a;
1915         }
1916     }
1917
1918     while (track->audio.pkt_cnt) {
1919         AVPacket *pkt = av_mallocz(sizeof(AVPacket));
1920         av_new_packet(pkt, a);
1921         memcpy(pkt->data, track->audio.buf
1922                + a * (h*w / a - track->audio.pkt_cnt--), a);
1923         pkt->pts = track->audio.buf_timecode;
1924         track->audio.buf_timecode = AV_NOPTS_VALUE;
1925         pkt->pos = pos;
1926         pkt->stream_index = st->index;
1927         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1928     }
1929
1930     return 0;
1931 }
1932 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
1933                                 MatroskaTrack *track,
1934                                 AVStream *st,
1935                                 uint8_t *data, int pkt_size,
1936                                 uint64_t timecode, uint64_t duration,
1937                                 int64_t pos, int is_keyframe)
1938 {
1939     MatroskaTrackEncoding *encodings = track->encodings.elem;
1940     uint8_t *pkt_data = data;
1941     int offset = 0, res;
1942     AVPacket *pkt;
1943
1944     if (encodings && encodings->scope & 1) {
1945         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
1946         if (res < 0)
1947             return res;
1948     }
1949
1950     if (st->codec->codec_id == AV_CODEC_ID_PRORES)
1951         offset = 8;
1952
1953     pkt = av_mallocz(sizeof(AVPacket));
1954     /* XXX: prevent data copy... */
1955     if (av_new_packet(pkt, pkt_size + offset) < 0) {
1956         av_free(pkt);
1957         return AVERROR(ENOMEM);
1958     }
1959
1960     if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
1961         uint8_t *buf = pkt->data;
1962         bytestream_put_be32(&buf, pkt_size);
1963         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
1964     }
1965
1966     memcpy(pkt->data + offset, pkt_data, pkt_size);
1967
1968     if (pkt_data != data)
1969         av_free(pkt_data);
1970
1971     pkt->flags = is_keyframe;
1972     pkt->stream_index = st->index;
1973
1974     if (track->ms_compat)
1975         pkt->dts = timecode;
1976     else
1977         pkt->pts = timecode;
1978     pkt->pos = pos;
1979     if (st->codec->codec_id == AV_CODEC_ID_TEXT)
1980         pkt->convergence_duration = duration;
1981     else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1982         pkt->duration = duration;
1983
1984     if (st->codec->codec_id == AV_CODEC_ID_SSA)
1985         matroska_fix_ass_packet(matroska, pkt, duration);
1986
1987     if (matroska->prev_pkt &&
1988         timecode != AV_NOPTS_VALUE &&
1989         matroska->prev_pkt->pts == timecode &&
1990         matroska->prev_pkt->stream_index == st->index &&
1991         st->codec->codec_id == AV_CODEC_ID_SSA)
1992         matroska_merge_packets(matroska->prev_pkt, pkt);
1993     else {
1994         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1995         matroska->prev_pkt = pkt;
1996     }
1997
1998     return 0;
1999 }
2000
2001 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2002                                 int size, int64_t pos, uint64_t cluster_time,
2003                                 uint64_t block_duration, int is_keyframe,
2004                                 int64_t cluster_pos)
2005 {
2006     uint64_t timecode = AV_NOPTS_VALUE;
2007     MatroskaTrack *track;
2008     int res = 0;
2009     AVStream *st;
2010     int16_t block_time;
2011     uint32_t *lace_size = NULL;
2012     int n, flags, laces = 0;
2013     uint64_t num, duration;
2014
2015     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2016         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2017         return n;
2018     }
2019     data += n;
2020     size -= n;
2021
2022     track = matroska_find_track_by_num(matroska, num);
2023     if (!track || !track->stream) {
2024         av_log(matroska->ctx, AV_LOG_INFO,
2025                "Invalid stream %"PRIu64" or size %u\n", num, size);
2026         return AVERROR_INVALIDDATA;
2027     } else if (size <= 3)
2028         return 0;
2029     st = track->stream;
2030     if (st->discard >= AVDISCARD_ALL)
2031         return res;
2032
2033     block_time = AV_RB16(data);
2034     data += 2;
2035     flags = *data++;
2036     size -= 3;
2037     if (is_keyframe == -1)
2038         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2039
2040     if (cluster_time != (uint64_t)-1
2041         && (block_time >= 0 || cluster_time >= -block_time)) {
2042         timecode = cluster_time + block_time;
2043         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2044             && timecode < track->end_timecode)
2045             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2046         if (is_keyframe)
2047             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2048     }
2049
2050     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2051         if (!is_keyframe || timecode < matroska->skip_to_timecode)
2052             return res;
2053         matroska->skip_to_keyframe = 0;
2054     }
2055
2056     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2057                                &lace_size, &laces);
2058
2059     if (res)
2060         goto end;
2061
2062     if (block_duration != AV_NOPTS_VALUE) {
2063         duration = block_duration / laces;
2064         if (block_duration != duration * laces) {
2065             av_log(matroska->ctx, AV_LOG_WARNING,
2066                    "Incorrect block_duration, possibly corrupted container");
2067         }
2068     } else {
2069         duration = track->default_duration / matroska->time_scale;
2070         block_duration = duration * laces;
2071     }
2072
2073     if (timecode != AV_NOPTS_VALUE)
2074         track->end_timecode =
2075             FFMAX(track->end_timecode, timecode + block_duration);
2076
2077     for (n = 0; n < laces; n++) {
2078         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2079              st->codec->codec_id == AV_CODEC_ID_COOK ||
2080              st->codec->codec_id == AV_CODEC_ID_SIPR ||
2081              st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2082              st->codec->block_align && track->audio.sub_packet_size) {
2083
2084             res = matroska_parse_rm_audio(matroska, track, st, data,
2085                                           lace_size[n],
2086                                           timecode, duration, pos);
2087             if (res)
2088                 goto end;
2089
2090         } else {
2091             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2092                                       timecode, duration,
2093                                       pos, !n? is_keyframe : 0);
2094             if (res)
2095                 goto end;
2096         }
2097
2098         if (timecode != AV_NOPTS_VALUE)
2099             timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2100         data += lace_size[n];
2101     }
2102
2103 end:
2104     av_free(lace_size);
2105     return res;
2106 }
2107
2108 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2109 {
2110     EbmlList *blocks_list;
2111     MatroskaBlock *blocks;
2112     int i, res;
2113     res = ebml_parse(matroska,
2114                      matroska_cluster_incremental_parsing,
2115                      &matroska->current_cluster);
2116     if (res == 1) {
2117         /* New Cluster */
2118         if (matroska->current_cluster_pos)
2119             ebml_level_end(matroska);
2120         ebml_free(matroska_cluster, &matroska->current_cluster);
2121         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2122         matroska->current_cluster_num_blocks = 0;
2123         matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2124         matroska->prev_pkt = NULL;
2125         /* sizeof the ID which was already read */
2126         if (matroska->current_id)
2127             matroska->current_cluster_pos -= 4;
2128         res = ebml_parse(matroska,
2129                          matroska_clusters_incremental,
2130                          &matroska->current_cluster);
2131         /* Try parsing the block again. */
2132         if (res == 1)
2133             res = ebml_parse(matroska,
2134                              matroska_cluster_incremental_parsing,
2135                              &matroska->current_cluster);
2136     }
2137
2138     if (!res &&
2139         matroska->current_cluster_num_blocks <
2140             matroska->current_cluster.blocks.nb_elem) {
2141         blocks_list = &matroska->current_cluster.blocks;
2142         blocks = blocks_list->elem;
2143
2144         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2145         i = blocks_list->nb_elem - 1;
2146         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2147             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2148             if (!blocks[i].non_simple)
2149                 blocks[i].duration = AV_NOPTS_VALUE;
2150             res = matroska_parse_block(matroska,
2151                                        blocks[i].bin.data, blocks[i].bin.size,
2152                                        blocks[i].bin.pos,
2153                                        matroska->current_cluster.timecode,
2154                                        blocks[i].duration, is_keyframe,
2155                                        matroska->current_cluster_pos);
2156         }
2157     }
2158
2159     if (res < 0)  matroska->done = 1;
2160     return res;
2161 }
2162
2163 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2164 {
2165     MatroskaCluster cluster = { 0 };
2166     EbmlList *blocks_list;
2167     MatroskaBlock *blocks;
2168     int i, res;
2169     int64_t pos;
2170     if (!matroska->contains_ssa)
2171         return matroska_parse_cluster_incremental(matroska);
2172     pos = avio_tell(matroska->ctx->pb);
2173     matroska->prev_pkt = NULL;
2174     if (matroska->current_id)
2175         pos -= 4;  /* sizeof the ID which was already read */
2176     res = ebml_parse(matroska, matroska_clusters, &cluster);
2177     blocks_list = &cluster.blocks;
2178     blocks = blocks_list->elem;
2179     for (i=0; i<blocks_list->nb_elem && !res; i++)
2180         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2181             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2182             if (!blocks[i].non_simple)
2183                 blocks[i].duration = AV_NOPTS_VALUE;
2184             res=matroska_parse_block(matroska,
2185                                      blocks[i].bin.data, blocks[i].bin.size,
2186                                      blocks[i].bin.pos,  cluster.timecode,
2187                                      blocks[i].duration, is_keyframe,
2188                                      pos);
2189         }
2190     ebml_free(matroska_cluster, &cluster);
2191     if (res < 0)  matroska->done = 1;
2192     return res;
2193 }
2194
2195 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2196 {
2197     MatroskaDemuxContext *matroska = s->priv_data;
2198     int ret = 0;
2199
2200     while (!ret && matroska_deliver_packet(matroska, pkt)) {
2201         if (matroska->done)
2202             return AVERROR_EOF;
2203         ret = matroska_parse_cluster(matroska);
2204     }
2205
2206     if (ret == AVERROR_INVALIDDATA && pkt->data) {
2207         pkt->flags |= AV_PKT_FLAG_CORRUPT;
2208         return 0;
2209     }
2210
2211     return ret;
2212 }
2213
2214 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2215                               int64_t timestamp, int flags)
2216 {
2217     MatroskaDemuxContext *matroska = s->priv_data;
2218     MatroskaTrack *tracks = matroska->tracks.elem;
2219     AVStream *st = s->streams[stream_index];
2220     int i, index, index_sub, index_min;
2221
2222     /* Parse the CUES now since we need the index data to seek. */
2223     if (matroska->cues_parsing_deferred) {
2224         matroska_parse_cues(matroska);
2225         matroska->cues_parsing_deferred = 0;
2226     }
2227
2228     if (!st->nb_index_entries)
2229         return 0;
2230     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2231
2232     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2233         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2234         matroska->current_id = 0;
2235         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2236             matroska_clear_queue(matroska);
2237             if (matroska_parse_cluster(matroska) < 0)
2238                 break;
2239         }
2240     }
2241
2242     matroska_clear_queue(matroska);
2243     if (index < 0)
2244         return 0;
2245
2246     index_min = index;
2247     for (i=0; i < matroska->tracks.nb_elem; i++) {
2248         tracks[i].audio.pkt_cnt = 0;
2249         tracks[i].audio.sub_packet_cnt = 0;
2250         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2251         tracks[i].end_timecode = 0;
2252         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2253             && !tracks[i].stream->discard != AVDISCARD_ALL) {
2254             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2255             if (index_sub >= 0
2256                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2257                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2258                 index_min = index_sub;
2259         }
2260     }
2261
2262     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2263     matroska->current_id = 0;
2264     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2265     matroska->skip_to_timecode = st->index_entries[index].timestamp;
2266     matroska->done = 0;
2267     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2268     return 0;
2269 }
2270
2271 static int matroska_read_close(AVFormatContext *s)
2272 {
2273     MatroskaDemuxContext *matroska = s->priv_data;
2274     MatroskaTrack *tracks = matroska->tracks.elem;
2275     int n;
2276
2277     matroska_clear_queue(matroska);
2278
2279     for (n=0; n < matroska->tracks.nb_elem; n++)
2280         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2281             av_free(tracks[n].audio.buf);
2282     ebml_free(matroska_cluster, &matroska->current_cluster);
2283     ebml_free(matroska_segment, matroska);
2284
2285     return 0;
2286 }
2287
2288 AVInputFormat ff_matroska_demuxer = {
2289     .name           = "matroska,webm",
2290     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2291     .priv_data_size = sizeof(MatroskaDemuxContext),
2292     .read_probe     = matroska_probe,
2293     .read_header    = matroska_read_header,
2294     .read_packet    = matroska_read_packet,
2295     .read_close     = matroska_read_close,
2296     .read_seek      = matroska_read_seek,
2297 };