]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
pcmdec: change default of channels parameter to 1
[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     { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
504     { 0 }
505 };
506
507 static EbmlSyntax matroska_cluster[] = {
508     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
509     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
510     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
511     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
512     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
513     { 0 }
514 };
515
516 static EbmlSyntax matroska_clusters[] = {
517     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
518     { MATROSKA_ID_INFO,           EBML_NONE },
519     { MATROSKA_ID_CUES,           EBML_NONE },
520     { MATROSKA_ID_TAGS,           EBML_NONE },
521     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
522     { 0 }
523 };
524
525 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
526     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
527     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
528     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
529     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
530     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
531     { MATROSKA_ID_INFO,           EBML_NONE },
532     { MATROSKA_ID_CUES,           EBML_NONE },
533     { MATROSKA_ID_TAGS,           EBML_NONE },
534     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
535     { MATROSKA_ID_CLUSTER,        EBML_STOP },
536     { 0 }
537 };
538
539 static EbmlSyntax matroska_cluster_incremental[] = {
540     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
541     { MATROSKA_ID_BLOCKGROUP,     EBML_STOP },
542     { MATROSKA_ID_SIMPLEBLOCK,    EBML_STOP },
543     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
544     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
545     { 0 }
546 };
547
548 static EbmlSyntax matroska_clusters_incremental[] = {
549     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
550     { MATROSKA_ID_INFO,           EBML_NONE },
551     { MATROSKA_ID_CUES,           EBML_NONE },
552     { MATROSKA_ID_TAGS,           EBML_NONE },
553     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
554     { 0 }
555 };
556
557 static const char *const matroska_doctypes[] = { "matroska", "webm" };
558
559 /*
560  * Return: Whether we reached the end of a level in the hierarchy or not.
561  */
562 static int ebml_level_end(MatroskaDemuxContext *matroska)
563 {
564     AVIOContext *pb = matroska->ctx->pb;
565     int64_t pos = avio_tell(pb);
566
567     if (matroska->num_levels > 0) {
568         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
569         if (pos - level->start >= level->length || matroska->current_id) {
570             matroska->num_levels--;
571             return 1;
572         }
573     }
574     return 0;
575 }
576
577 /*
578  * Read: an "EBML number", which is defined as a variable-length
579  * array of bytes. The first byte indicates the length by giving a
580  * number of 0-bits followed by a one. The position of the first
581  * "one" bit inside the first byte indicates the length of this
582  * number.
583  * Returns: number of bytes read, < 0 on error
584  */
585 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
586                          int max_size, uint64_t *number)
587 {
588     int read = 1, n = 1;
589     uint64_t total = 0;
590
591     /* The first byte tells us the length in bytes - avio_r8() can normally
592      * return 0, but since that's not a valid first ebmlID byte, we can
593      * use it safely here to catch EOS. */
594     if (!(total = avio_r8(pb))) {
595         /* we might encounter EOS here */
596         if (!pb->eof_reached) {
597             int64_t pos = avio_tell(pb);
598             av_log(matroska->ctx, AV_LOG_ERROR,
599                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
600                    pos, pos);
601             return pb->error ? pb->error : AVERROR(EIO);
602         }
603         return AVERROR_EOF;
604     }
605
606     /* get the length of the EBML number */
607     read = 8 - ff_log2_tab[total];
608     if (read > max_size) {
609         int64_t pos = avio_tell(pb) - 1;
610         av_log(matroska->ctx, AV_LOG_ERROR,
611                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
612                (uint8_t) total, pos, pos);
613         return AVERROR_INVALIDDATA;
614     }
615
616     /* read out length */
617     total ^= 1 << ff_log2_tab[total];
618     while (n++ < read)
619         total = (total << 8) | avio_r8(pb);
620
621     *number = total;
622
623     return read;
624 }
625
626 /**
627  * Read a EBML length value.
628  * This needs special handling for the "unknown length" case which has multiple
629  * encodings.
630  */
631 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
632                             uint64_t *number)
633 {
634     int res = ebml_read_num(matroska, pb, 8, number);
635     if (res > 0 && *number + 1 == 1ULL << (7 * res))
636         *number = 0xffffffffffffffULL;
637     return res;
638 }
639
640 /*
641  * Read the next element as an unsigned int.
642  * 0 is success, < 0 is failure.
643  */
644 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
645 {
646     int n = 0;
647
648     if (size > 8)
649         return AVERROR_INVALIDDATA;
650
651     /* big-endian ordering; build up number */
652     *num = 0;
653     while (n++ < size)
654         *num = (*num << 8) | avio_r8(pb);
655
656     return 0;
657 }
658
659 /*
660  * Read the next element as a float.
661  * 0 is success, < 0 is failure.
662  */
663 static int ebml_read_float(AVIOContext *pb, int size, double *num)
664 {
665     if (size == 0) {
666         *num = 0;
667     } else if (size == 4) {
668         *num = av_int2float(avio_rb32(pb));
669     } else if (size == 8){
670         *num = av_int2double(avio_rb64(pb));
671     } else
672         return AVERROR_INVALIDDATA;
673
674     return 0;
675 }
676
677 /*
678  * Read the next element as an ASCII string.
679  * 0 is success, < 0 is failure.
680  */
681 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
682 {
683     char *res;
684
685     /* EBML strings are usually not 0-terminated, so we allocate one
686      * byte more, read the string and NULL-terminate it ourselves. */
687     if (!(res = av_malloc(size + 1)))
688         return AVERROR(ENOMEM);
689     if (avio_read(pb, (uint8_t *) res, size) != size) {
690         av_free(res);
691         return AVERROR(EIO);
692     }
693     (res)[size] = '\0';
694     av_free(*str);
695     *str = res;
696
697     return 0;
698 }
699
700 /*
701  * Read the next element as binary data.
702  * 0 is success, < 0 is failure.
703  */
704 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
705 {
706     av_free(bin->data);
707     if (!(bin->data = av_malloc(length)))
708         return AVERROR(ENOMEM);
709
710     bin->size = length;
711     bin->pos  = avio_tell(pb);
712     if (avio_read(pb, bin->data, length) != length) {
713         av_freep(&bin->data);
714         return AVERROR(EIO);
715     }
716
717     return 0;
718 }
719
720 /*
721  * Read the next element, but only the header. The contents
722  * are supposed to be sub-elements which can be read separately.
723  * 0 is success, < 0 is failure.
724  */
725 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
726 {
727     AVIOContext *pb = matroska->ctx->pb;
728     MatroskaLevel *level;
729
730     if (matroska->num_levels >= EBML_MAX_DEPTH) {
731         av_log(matroska->ctx, AV_LOG_ERROR,
732                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
733         return AVERROR(ENOSYS);
734     }
735
736     level = &matroska->levels[matroska->num_levels++];
737     level->start = avio_tell(pb);
738     level->length = length;
739
740     return 0;
741 }
742
743 /*
744  * Read signed/unsigned "EBML" numbers.
745  * Return: number of bytes processed, < 0 on error
746  */
747 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
748                                  uint8_t *data, uint32_t size, uint64_t *num)
749 {
750     AVIOContext pb;
751     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
752     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
753 }
754
755 /*
756  * Same as above, but signed.
757  */
758 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
759                                  uint8_t *data, uint32_t size, int64_t *num)
760 {
761     uint64_t unum;
762     int res;
763
764     /* read as unsigned number first */
765     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
766         return res;
767
768     /* make signed (weird way) */
769     *num = unum - ((1LL << (7*res - 1)) - 1);
770
771     return res;
772 }
773
774 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
775                            EbmlSyntax *syntax, void *data);
776
777 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
778                          uint32_t id, void *data)
779 {
780     int i;
781     for (i=0; syntax[i].id; i++)
782         if (id == syntax[i].id)
783             break;
784     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
785         matroska->num_levels > 0 &&
786         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
787         return 0;  // we reached the end of an unknown size cluster
788     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
789         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
790         if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
791             return AVERROR_INVALIDDATA;
792     }
793     return ebml_parse_elem(matroska, &syntax[i], data);
794 }
795
796 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
797                       void *data)
798 {
799     if (!matroska->current_id) {
800         uint64_t id;
801         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
802         if (res < 0)
803             return res;
804         matroska->current_id = id | 1 << 7*res;
805     }
806     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
807 }
808
809 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
810                            void *data)
811 {
812     int i, res = 0;
813
814     for (i=0; syntax[i].id; i++)
815         switch (syntax[i].type) {
816         case EBML_UINT:
817             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
818             break;
819         case EBML_FLOAT:
820             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
821             break;
822         case EBML_STR:
823         case EBML_UTF8:
824             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
825             break;
826         }
827
828     while (!res && !ebml_level_end(matroska))
829         res = ebml_parse(matroska, syntax, data);
830
831     return res;
832 }
833
834 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
835                            EbmlSyntax *syntax, void *data)
836 {
837     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
838         [EBML_UINT]  = 8,
839         [EBML_FLOAT] = 8,
840         // max. 16 MB for strings
841         [EBML_STR]   = 0x1000000,
842         [EBML_UTF8]  = 0x1000000,
843         // max. 256 MB for binary data
844         [EBML_BIN]   = 0x10000000,
845         // no limits for anything else
846     };
847     AVIOContext *pb = matroska->ctx->pb;
848     uint32_t id = syntax->id;
849     uint64_t length;
850     int res;
851     void *newelem;
852
853     data = (char *)data + syntax->data_offset;
854     if (syntax->list_elem_size) {
855         EbmlList *list = data;
856         newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
857         if (!newelem)
858             return AVERROR(ENOMEM);
859         list->elem = newelem;
860         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
861         memset(data, 0, syntax->list_elem_size);
862         list->nb_elem++;
863     }
864
865     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
866         matroska->current_id = 0;
867         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
868             return res;
869         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
870             av_log(matroska->ctx, AV_LOG_ERROR,
871                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
872                    length, max_lengths[syntax->type], syntax->type);
873             return AVERROR_INVALIDDATA;
874         }
875     }
876
877     switch (syntax->type) {
878     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
879     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
880     case EBML_STR:
881     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
882     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
883     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
884                          return res;
885                      if (id == MATROSKA_ID_SEGMENT)
886                          matroska->segment_start = avio_tell(matroska->ctx->pb);
887                      return ebml_parse_nest(matroska, syntax->def.n, data);
888     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
889     case EBML_STOP:  return 1;
890     default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
891     }
892     if (res == AVERROR_INVALIDDATA)
893         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
894     else if (res == AVERROR(EIO))
895         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
896     return res;
897 }
898
899 static void ebml_free(EbmlSyntax *syntax, void *data)
900 {
901     int i, j;
902     for (i=0; syntax[i].id; i++) {
903         void *data_off = (char *)data + syntax[i].data_offset;
904         switch (syntax[i].type) {
905         case EBML_STR:
906         case EBML_UTF8:  av_freep(data_off);                      break;
907         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
908         case EBML_NEST:
909             if (syntax[i].list_elem_size) {
910                 EbmlList *list = data_off;
911                 char *ptr = list->elem;
912                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
913                     ebml_free(syntax[i].def.n, ptr);
914                 av_free(list->elem);
915             } else
916                 ebml_free(syntax[i].def.n, data_off);
917         default:  break;
918         }
919     }
920 }
921
922
923 /*
924  * Autodetecting...
925  */
926 static int matroska_probe(AVProbeData *p)
927 {
928     uint64_t total = 0;
929     int len_mask = 0x80, size = 1, n = 1, i;
930
931     /* EBML header? */
932     if (AV_RB32(p->buf) != EBML_ID_HEADER)
933         return 0;
934
935     /* length of header */
936     total = p->buf[4];
937     while (size <= 8 && !(total & len_mask)) {
938         size++;
939         len_mask >>= 1;
940     }
941     if (size > 8)
942       return 0;
943     total &= (len_mask - 1);
944     while (n < size)
945         total = (total << 8) | p->buf[4 + n++];
946
947     /* Does the probe data contain the whole header? */
948     if (p->buf_size < 4 + size + total)
949       return 0;
950
951     /* The header should contain a known document type. For now,
952      * we don't parse the whole header but simply check for the
953      * availability of that array of characters inside the header.
954      * Not fully fool-proof, but good enough. */
955     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
956         int probelen = strlen(matroska_doctypes[i]);
957         if (total < probelen)
958             continue;
959         for (n = 4+size; n <= 4+size+total-probelen; n++)
960             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
961                 return AVPROBE_SCORE_MAX;
962     }
963
964     // probably valid EBML header but no recognized doctype
965     return AVPROBE_SCORE_MAX/2;
966 }
967
968 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
969                                                  int num)
970 {
971     MatroskaTrack *tracks = matroska->tracks.elem;
972     int i;
973
974     for (i=0; i < matroska->tracks.nb_elem; i++)
975         if (tracks[i].num == num)
976             return &tracks[i];
977
978     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
979     return NULL;
980 }
981
982 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
983                                   MatroskaTrack *track)
984 {
985     MatroskaTrackEncoding *encodings = track->encodings.elem;
986     uint8_t* data = *buf;
987     int isize = *buf_size;
988     uint8_t* pkt_data = NULL;
989     uint8_t av_unused *newpktdata;
990     int pkt_size = isize;
991     int result = 0;
992     int olen;
993
994     if (pkt_size >= 10000000)
995         return AVERROR_INVALIDDATA;
996
997     switch (encodings[0].compression.algo) {
998     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
999         int header_size = encodings[0].compression.settings.size;
1000         uint8_t *header = encodings[0].compression.settings.data;
1001
1002         if (!header_size)
1003             return 0;
1004
1005         pkt_size = isize + header_size;
1006         pkt_data = av_malloc(pkt_size);
1007         if (!pkt_data)
1008             return AVERROR(ENOMEM);
1009
1010         memcpy(pkt_data, header, header_size);
1011         memcpy(pkt_data + header_size, data, isize);
1012         break;
1013     }
1014 #if CONFIG_LZO
1015     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1016         do {
1017             olen = pkt_size *= 3;
1018             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1019             if (!newpktdata) {
1020                 result = AVERROR(ENOMEM);
1021                 goto failed;
1022             }
1023             pkt_data = newpktdata;
1024             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1025         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1026         if (result) {
1027             result = AVERROR_INVALIDDATA;
1028             goto failed;
1029         }
1030         pkt_size -= olen;
1031         break;
1032 #endif
1033 #if CONFIG_ZLIB
1034     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1035         z_stream zstream = {0};
1036         if (inflateInit(&zstream) != Z_OK)
1037             return -1;
1038         zstream.next_in = data;
1039         zstream.avail_in = isize;
1040         do {
1041             pkt_size *= 3;
1042             newpktdata = av_realloc(pkt_data, pkt_size);
1043             if (!newpktdata) {
1044                 inflateEnd(&zstream);
1045                 goto failed;
1046             }
1047             pkt_data = newpktdata;
1048             zstream.avail_out = pkt_size - zstream.total_out;
1049             zstream.next_out = pkt_data + zstream.total_out;
1050             result = inflate(&zstream, Z_NO_FLUSH);
1051         } while (result==Z_OK && pkt_size<10000000);
1052         pkt_size = zstream.total_out;
1053         inflateEnd(&zstream);
1054         if (result != Z_STREAM_END) {
1055             if (result == Z_MEM_ERROR)
1056                 result = AVERROR(ENOMEM);
1057             else
1058                 result = AVERROR_INVALIDDATA;
1059             goto failed;
1060         }
1061         break;
1062     }
1063 #endif
1064 #if CONFIG_BZLIB
1065     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1066         bz_stream bzstream = {0};
1067         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1068             return -1;
1069         bzstream.next_in = data;
1070         bzstream.avail_in = isize;
1071         do {
1072             pkt_size *= 3;
1073             newpktdata = av_realloc(pkt_data, pkt_size);
1074             if (!newpktdata) {
1075                 BZ2_bzDecompressEnd(&bzstream);
1076                 goto failed;
1077             }
1078             pkt_data = newpktdata;
1079             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1080             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1081             result = BZ2_bzDecompress(&bzstream);
1082         } while (result==BZ_OK && pkt_size<10000000);
1083         pkt_size = bzstream.total_out_lo32;
1084         BZ2_bzDecompressEnd(&bzstream);
1085         if (result != BZ_STREAM_END) {
1086             if (result == BZ_MEM_ERROR)
1087                 result = AVERROR(ENOMEM);
1088             else
1089                 result = AVERROR_INVALIDDATA;
1090             goto failed;
1091         }
1092         break;
1093     }
1094 #endif
1095     default:
1096         return AVERROR_INVALIDDATA;
1097     }
1098
1099     *buf = pkt_data;
1100     *buf_size = pkt_size;
1101     return 0;
1102  failed:
1103     av_free(pkt_data);
1104     return result;
1105 }
1106
1107 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1108                                     AVPacket *pkt, uint64_t display_duration)
1109 {
1110     char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1111     for (; *ptr!=',' && ptr<end-1; ptr++);
1112     if (*ptr == ',')
1113         layer = ++ptr;
1114     for (; *ptr!=',' && ptr<end-1; ptr++);
1115     if (*ptr == ',') {
1116         int64_t end_pts = pkt->pts + display_duration;
1117         int sc = matroska->time_scale * pkt->pts / 10000000;
1118         int ec = matroska->time_scale * end_pts  / 10000000;
1119         int sh, sm, ss, eh, em, es, len;
1120         sh = sc/360000;  sc -= 360000*sh;
1121         sm = sc/  6000;  sc -=   6000*sm;
1122         ss = sc/   100;  sc -=    100*ss;
1123         eh = ec/360000;  ec -= 360000*eh;
1124         em = ec/  6000;  ec -=   6000*em;
1125         es = ec/   100;  ec -=    100*es;
1126         *ptr++ = '\0';
1127         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1128         if (!(line = av_malloc(len)))
1129             return;
1130         snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1131                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1132         av_free(pkt->data);
1133         pkt->data = line;
1134         pkt->size = strlen(line);
1135     }
1136 }
1137
1138 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1139 {
1140     void *newdata = av_realloc(out->data, out->size+in->size);
1141     if (!newdata)
1142         return AVERROR(ENOMEM);
1143     out->data = newdata;
1144     memcpy(out->data+out->size, in->data, in->size);
1145     out->size += in->size;
1146     av_destruct_packet(in);
1147     av_free(in);
1148     return 0;
1149 }
1150
1151 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1152                                  AVDictionary **metadata, char *prefix)
1153 {
1154     MatroskaTag *tags = list->elem;
1155     char key[1024];
1156     int i;
1157
1158     for (i=0; i < list->nb_elem; i++) {
1159         const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1160
1161         if (!tags[i].name) {
1162             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1163             continue;
1164         }
1165         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1166         else         av_strlcpy(key, tags[i].name, sizeof(key));
1167         if (tags[i].def || !lang) {
1168         av_dict_set(metadata, key, tags[i].string, 0);
1169         if (tags[i].sub.nb_elem)
1170             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1171         }
1172         if (lang) {
1173             av_strlcat(key, "-", sizeof(key));
1174             av_strlcat(key, lang, sizeof(key));
1175             av_dict_set(metadata, key, tags[i].string, 0);
1176             if (tags[i].sub.nb_elem)
1177                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1178         }
1179     }
1180     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1181 }
1182
1183 static void matroska_convert_tags(AVFormatContext *s)
1184 {
1185     MatroskaDemuxContext *matroska = s->priv_data;
1186     MatroskaTags *tags = matroska->tags.elem;
1187     int i, j;
1188
1189     for (i=0; i < matroska->tags.nb_elem; i++) {
1190         if (tags[i].target.attachuid) {
1191             MatroskaAttachement *attachment = matroska->attachments.elem;
1192             for (j=0; j<matroska->attachments.nb_elem; j++)
1193                 if (attachment[j].uid == tags[i].target.attachuid
1194                     && attachment[j].stream)
1195                     matroska_convert_tag(s, &tags[i].tag,
1196                                          &attachment[j].stream->metadata, NULL);
1197         } else if (tags[i].target.chapteruid) {
1198             MatroskaChapter *chapter = matroska->chapters.elem;
1199             for (j=0; j<matroska->chapters.nb_elem; j++)
1200                 if (chapter[j].uid == tags[i].target.chapteruid
1201                     && chapter[j].chapter)
1202                     matroska_convert_tag(s, &tags[i].tag,
1203                                          &chapter[j].chapter->metadata, NULL);
1204         } else if (tags[i].target.trackuid) {
1205             MatroskaTrack *track = matroska->tracks.elem;
1206             for (j=0; j<matroska->tracks.nb_elem; j++)
1207                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1208                     matroska_convert_tag(s, &tags[i].tag,
1209                                          &track[j].stream->metadata, NULL);
1210         } else {
1211             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1212                                  tags[i].target.type);
1213         }
1214     }
1215 }
1216
1217 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1218 {
1219     EbmlList *seekhead_list = &matroska->seekhead;
1220     MatroskaSeekhead *seekhead = seekhead_list->elem;
1221     uint32_t level_up = matroska->level_up;
1222     int64_t before_pos = avio_tell(matroska->ctx->pb);
1223     uint32_t saved_id = matroska->current_id;
1224     MatroskaLevel level;
1225     int64_t offset;
1226     int ret = 0;
1227
1228     if (idx >= seekhead_list->nb_elem
1229             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1230             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1231         return 0;
1232
1233     /* seek */
1234     offset = seekhead[idx].pos + matroska->segment_start;
1235     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1236         /* We don't want to lose our seekhead level, so we add
1237          * a dummy. This is a crude hack. */
1238         if (matroska->num_levels == EBML_MAX_DEPTH) {
1239             av_log(matroska->ctx, AV_LOG_INFO,
1240                    "Max EBML element depth (%d) reached, "
1241                    "cannot parse further.\n", EBML_MAX_DEPTH);
1242             ret = AVERROR_INVALIDDATA;
1243         } else {
1244             level.start = 0;
1245             level.length = (uint64_t)-1;
1246             matroska->levels[matroska->num_levels] = level;
1247             matroska->num_levels++;
1248             matroska->current_id = 0;
1249
1250             ret = ebml_parse(matroska, matroska_segment, matroska);
1251
1252             /* remove dummy level */
1253             while (matroska->num_levels) {
1254                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1255                 if (length == (uint64_t)-1)
1256                     break;
1257             }
1258         }
1259     }
1260     /* seek back */
1261     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1262     matroska->level_up = level_up;
1263     matroska->current_id = saved_id;
1264
1265     return ret;
1266 }
1267
1268 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1269 {
1270     EbmlList *seekhead_list = &matroska->seekhead;
1271     int64_t before_pos = avio_tell(matroska->ctx->pb);
1272     int i;
1273
1274     // we should not do any seeking in the streaming case
1275     if (!matroska->ctx->pb->seekable ||
1276         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1277         return;
1278
1279     for (i = 0; i < seekhead_list->nb_elem; i++) {
1280         MatroskaSeekhead *seekhead = seekhead_list->elem;
1281         if (seekhead[i].pos <= before_pos)
1282             continue;
1283
1284         // defer cues parsing until we actually need cue data.
1285         if (seekhead[i].id == MATROSKA_ID_CUES) {
1286             matroska->cues_parsing_deferred = 1;
1287             continue;
1288         }
1289
1290         if (matroska_parse_seekhead_entry(matroska, i) < 0)
1291             break;
1292     }
1293 }
1294
1295 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1296     EbmlList *seekhead_list = &matroska->seekhead;
1297     MatroskaSeekhead *seekhead = seekhead_list->elem;
1298     EbmlList *index_list;
1299     MatroskaIndex *index;
1300     int index_scale = 1;
1301     int i, j;
1302
1303     for (i = 0; i < seekhead_list->nb_elem; i++)
1304         if (seekhead[i].id == MATROSKA_ID_CUES)
1305             break;
1306     assert(i <= seekhead_list->nb_elem);
1307
1308     matroska_parse_seekhead_entry(matroska, i);
1309
1310     index_list = &matroska->index;
1311     index = index_list->elem;
1312     if (index_list->nb_elem
1313         && index[0].time > 1E14/matroska->time_scale) {
1314         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1315         index_scale = matroska->time_scale;
1316     }
1317     for (i = 0; i < index_list->nb_elem; i++) {
1318         EbmlList *pos_list = &index[i].pos;
1319         MatroskaIndexPos *pos = pos_list->elem;
1320         for (j = 0; j < pos_list->nb_elem; j++) {
1321             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1322             if (track && track->stream)
1323                 av_add_index_entry(track->stream,
1324                                    pos[j].pos + matroska->segment_start,
1325                                    index[i].time/index_scale, 0, 0,
1326                                    AVINDEX_KEYFRAME);
1327         }
1328     }
1329 }
1330
1331 static int matroska_aac_profile(char *codec_id)
1332 {
1333     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1334     int profile;
1335
1336     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1337         if (strstr(codec_id, aac_profiles[profile]))
1338             break;
1339     return profile + 1;
1340 }
1341
1342 static int matroska_aac_sri(int samplerate)
1343 {
1344     int sri;
1345
1346     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1347         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1348             break;
1349     return sri;
1350 }
1351
1352 static int matroska_read_header(AVFormatContext *s)
1353 {
1354     MatroskaDemuxContext *matroska = s->priv_data;
1355     EbmlList *attachements_list = &matroska->attachments;
1356     MatroskaAttachement *attachements;
1357     EbmlList *chapters_list = &matroska->chapters;
1358     MatroskaChapter *chapters;
1359     MatroskaTrack *tracks;
1360     uint64_t max_start = 0;
1361     Ebml ebml = { 0 };
1362     AVStream *st;
1363     int i, j, res;
1364
1365     matroska->ctx = s;
1366
1367     /* First read the EBML header. */
1368     if (ebml_parse(matroska, ebml_syntax, &ebml)
1369         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1370         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1371         av_log(matroska->ctx, AV_LOG_ERROR,
1372                "EBML header using unsupported features\n"
1373                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1374                ebml.version, ebml.doctype, ebml.doctype_version);
1375         ebml_free(ebml_syntax, &ebml);
1376         return AVERROR_PATCHWELCOME;
1377     }
1378     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1379         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1380             break;
1381     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1382         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1383         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1384             ebml_free(ebml_syntax, &ebml);
1385             return AVERROR_INVALIDDATA;
1386         }
1387     }
1388     ebml_free(ebml_syntax, &ebml);
1389
1390     /* The next thing is a segment. */
1391     if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1392         return res;
1393     matroska_execute_seekhead(matroska);
1394
1395     if (!matroska->time_scale)
1396         matroska->time_scale = 1000000;
1397     if (matroska->duration)
1398         matroska->ctx->duration = matroska->duration * matroska->time_scale
1399                                   * 1000 / AV_TIME_BASE;
1400     av_dict_set(&s->metadata, "title", matroska->title, 0);
1401
1402     tracks = matroska->tracks.elem;
1403     for (i=0; i < matroska->tracks.nb_elem; i++) {
1404         MatroskaTrack *track = &tracks[i];
1405         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1406         EbmlList *encodings_list = &tracks->encodings;
1407         MatroskaTrackEncoding *encodings = encodings_list->elem;
1408         uint8_t *extradata = NULL;
1409         int extradata_size = 0;
1410         int extradata_offset = 0;
1411         AVIOContext b;
1412
1413         /* Apply some sanity checks. */
1414         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1415             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1416             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1417             av_log(matroska->ctx, AV_LOG_INFO,
1418                    "Unknown or unsupported track type %"PRIu64"\n",
1419                    track->type);
1420             continue;
1421         }
1422         if (track->codec_id == NULL)
1423             continue;
1424
1425         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1426             if (!track->default_duration && track->video.frame_rate > 0)
1427                 track->default_duration = 1000000000/track->video.frame_rate;
1428             if (!track->video.display_width)
1429                 track->video.display_width = track->video.pixel_width;
1430             if (!track->video.display_height)
1431                 track->video.display_height = track->video.pixel_height;
1432         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1433             if (!track->audio.out_samplerate)
1434                 track->audio.out_samplerate = track->audio.samplerate;
1435         }
1436         if (encodings_list->nb_elem > 1) {
1437             av_log(matroska->ctx, AV_LOG_ERROR,
1438                    "Multiple combined encodings not supported");
1439         } else if (encodings_list->nb_elem == 1) {
1440             if (encodings[0].type ||
1441                 (
1442 #if CONFIG_ZLIB
1443                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1444 #endif
1445 #if CONFIG_BZLIB
1446                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1447 #endif
1448 #if CONFIG_LZO
1449                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1450 #endif
1451                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
1452                 encodings[0].scope = 0;
1453                 av_log(matroska->ctx, AV_LOG_ERROR,
1454                        "Unsupported encoding type");
1455             } else if (track->codec_priv.size && encodings[0].scope&2) {
1456                 uint8_t *codec_priv = track->codec_priv.data;
1457                 int ret = matroska_decode_buffer(&track->codec_priv.data,
1458                                                  &track->codec_priv.size,
1459                                                  track);
1460                 if (ret < 0) {
1461                     track->codec_priv.data = NULL;
1462                     track->codec_priv.size = 0;
1463                     av_log(matroska->ctx, AV_LOG_ERROR,
1464                            "Failed to decode codec private data\n");
1465                 }
1466
1467                 if (codec_priv != track->codec_priv.data)
1468                     av_free(codec_priv);
1469             }
1470         }
1471
1472         for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1473             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1474                         strlen(ff_mkv_codec_tags[j].str))){
1475                 codec_id= ff_mkv_codec_tags[j].id;
1476                 break;
1477             }
1478         }
1479
1480         st = track->stream = avformat_new_stream(s, NULL);
1481         if (st == NULL)
1482             return AVERROR(ENOMEM);
1483
1484         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1485             && track->codec_priv.size >= 40
1486             && track->codec_priv.data != NULL) {
1487             track->ms_compat = 1;
1488             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1489             codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1490             extradata_offset = 40;
1491         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1492                    && track->codec_priv.size >= 14
1493                    && track->codec_priv.data != NULL) {
1494             int ret;
1495             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1496                           AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
1497             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1498             if (ret < 0)
1499                 return ret;
1500             codec_id = st->codec->codec_id;
1501             extradata_offset = FFMIN(track->codec_priv.size, 18);
1502         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1503                    && (track->codec_priv.size >= 86)
1504                    && (track->codec_priv.data != NULL)) {
1505             track->video.fourcc = AV_RL32(track->codec_priv.data);
1506             codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
1507         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1508             switch (track->audio.bitdepth) {
1509             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1510             case 24:  codec_id = AV_CODEC_ID_PCM_S24BE;  break;
1511             case 32:  codec_id = AV_CODEC_ID_PCM_S32BE;  break;
1512             }
1513         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1514             switch (track->audio.bitdepth) {
1515             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1516             case 24:  codec_id = AV_CODEC_ID_PCM_S24LE;  break;
1517             case 32:  codec_id = AV_CODEC_ID_PCM_S32LE;  break;
1518             }
1519         } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1520             codec_id = AV_CODEC_ID_PCM_F64LE;
1521         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1522             int profile = matroska_aac_profile(track->codec_id);
1523             int sri = matroska_aac_sri(track->audio.samplerate);
1524             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1525             if (extradata == NULL)
1526                 return AVERROR(ENOMEM);
1527             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1528             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1529             if (strstr(track->codec_id, "SBR")) {
1530                 sri = matroska_aac_sri(track->audio.out_samplerate);
1531                 extradata[2] = 0x56;
1532                 extradata[3] = 0xE5;
1533                 extradata[4] = 0x80 | (sri<<3);
1534                 extradata_size = 5;
1535             } else
1536                 extradata_size = 2;
1537         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
1538             /* Only ALAC's magic cookie is stored in Matroska's track headers.
1539                Create the "atom size", "tag", and "tag version" fields the
1540                decoder expects manually. */
1541             extradata_size = 12 + track->codec_priv.size;
1542             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1543             if (extradata == NULL)
1544                 return AVERROR(ENOMEM);
1545             AV_WB32(extradata, extradata_size);
1546             memcpy(&extradata[4], "alac", 4);
1547             AV_WB32(&extradata[8], 0);
1548             memcpy(&extradata[12], track->codec_priv.data,
1549                                    track->codec_priv.size);
1550         } else if (codec_id == AV_CODEC_ID_TTA) {
1551             extradata_size = 30;
1552             extradata = av_mallocz(extradata_size);
1553             if (extradata == NULL)
1554                 return AVERROR(ENOMEM);
1555             ffio_init_context(&b, extradata, extradata_size, 1,
1556                           NULL, NULL, NULL, NULL);
1557             avio_write(&b, "TTA1", 4);
1558             avio_wl16(&b, 1);
1559             avio_wl16(&b, track->audio.channels);
1560             avio_wl16(&b, track->audio.bitdepth);
1561             avio_wl32(&b, track->audio.out_samplerate);
1562             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1563         } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1564                    codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1565             extradata_offset = 26;
1566         } else if (codec_id == AV_CODEC_ID_RA_144) {
1567             track->audio.out_samplerate = 8000;
1568             track->audio.channels = 1;
1569         } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1570                    codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
1571             int flavor;
1572             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1573                           0, NULL, NULL, NULL, NULL);
1574             avio_skip(&b, 22);
1575             flavor                       = avio_rb16(&b);
1576             track->audio.coded_framesize = avio_rb32(&b);
1577             avio_skip(&b, 12);
1578             track->audio.sub_packet_h    = avio_rb16(&b);
1579             track->audio.frame_size      = avio_rb16(&b);
1580             track->audio.sub_packet_size = avio_rb16(&b);
1581             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1582             if (codec_id == AV_CODEC_ID_RA_288) {
1583                 st->codec->block_align = track->audio.coded_framesize;
1584                 track->codec_priv.size = 0;
1585             } else {
1586                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1587                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1588                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1589                     st->codec->bit_rate = sipr_bit_rate[flavor];
1590                 }
1591                 st->codec->block_align = track->audio.sub_packet_size;
1592                 extradata_offset = 78;
1593             }
1594         }
1595         track->codec_priv.size -= extradata_offset;
1596
1597         if (codec_id == AV_CODEC_ID_NONE)
1598             av_log(matroska->ctx, AV_LOG_INFO,
1599                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1600
1601         if (track->time_scale < 0.01)
1602             track->time_scale = 1.0;
1603         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1604
1605         st->codec->codec_id = codec_id;
1606         st->start_time = 0;
1607         if (strcmp(track->language, "und"))
1608             av_dict_set(&st->metadata, "language", track->language, 0);
1609         av_dict_set(&st->metadata, "title", track->name, 0);
1610
1611         if (track->flag_default)
1612             st->disposition |= AV_DISPOSITION_DEFAULT;
1613         if (track->flag_forced)
1614             st->disposition |= AV_DISPOSITION_FORCED;
1615
1616         if (!st->codec->extradata) {
1617             if(extradata){
1618                 st->codec->extradata = extradata;
1619                 st->codec->extradata_size = extradata_size;
1620             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1621                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1622                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1623                 if(st->codec->extradata == NULL)
1624                     return AVERROR(ENOMEM);
1625                 st->codec->extradata_size = track->codec_priv.size;
1626                 memcpy(st->codec->extradata,
1627                        track->codec_priv.data + extradata_offset,
1628                        track->codec_priv.size);
1629             }
1630         }
1631
1632         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1633             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1634             st->codec->codec_tag  = track->video.fourcc;
1635             st->codec->width  = track->video.pixel_width;
1636             st->codec->height = track->video.pixel_height;
1637             av_reduce(&st->sample_aspect_ratio.num,
1638                       &st->sample_aspect_ratio.den,
1639                       st->codec->height * track->video.display_width,
1640                       st->codec-> width * track->video.display_height,
1641                       255);
1642             if (st->codec->codec_id != AV_CODEC_ID_H264)
1643             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1644             if (track->default_duration) {
1645                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1646                           1000000000, track->default_duration, 30000);
1647 #if FF_API_R_FRAME_RATE
1648                 st->r_frame_rate = st->avg_frame_rate;
1649 #endif
1650             }
1651         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1652             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1653             st->codec->sample_rate = track->audio.out_samplerate;
1654             st->codec->channels = track->audio.channels;
1655             if (st->codec->codec_id != AV_CODEC_ID_AAC)
1656             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1657         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1658             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1659             if (st->codec->codec_id == AV_CODEC_ID_SSA)
1660                 matroska->contains_ssa = 1;
1661         }
1662     }
1663
1664     attachements = attachements_list->elem;
1665     for (j=0; j<attachements_list->nb_elem; j++) {
1666         if (!(attachements[j].filename && attachements[j].mime &&
1667               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1668             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1669         } else {
1670             AVStream *st = avformat_new_stream(s, NULL);
1671             if (st == NULL)
1672                 break;
1673             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1674             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1675             st->codec->codec_id = AV_CODEC_ID_NONE;
1676             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1677             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1678             if(st->codec->extradata == NULL)
1679                 break;
1680             st->codec->extradata_size = attachements[j].bin.size;
1681             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1682
1683             for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1684                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1685                              strlen(ff_mkv_mime_tags[i].str))) {
1686                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1687                     break;
1688                 }
1689             }
1690             attachements[j].stream = st;
1691         }
1692     }
1693
1694     chapters = chapters_list->elem;
1695     for (i=0; i<chapters_list->nb_elem; i++)
1696         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1697             && (max_start==0 || chapters[i].start > max_start)) {
1698             chapters[i].chapter =
1699             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1700                            chapters[i].start, chapters[i].end,
1701                            chapters[i].title);
1702             av_dict_set(&chapters[i].chapter->metadata,
1703                              "title", chapters[i].title, 0);
1704             max_start = chapters[i].start;
1705         }
1706
1707     matroska_convert_tags(s);
1708
1709     return 0;
1710 }
1711
1712 /*
1713  * Put one packet in an application-supplied AVPacket struct.
1714  * Returns 0 on success or -1 on failure.
1715  */
1716 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1717                                    AVPacket *pkt)
1718 {
1719     if (matroska->num_packets > 0) {
1720         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1721         av_free(matroska->packets[0]);
1722         if (matroska->num_packets > 1) {
1723             void *newpackets;
1724             memmove(&matroska->packets[0], &matroska->packets[1],
1725                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1726             newpackets = av_realloc(matroska->packets,
1727                             (matroska->num_packets - 1) * sizeof(AVPacket *));
1728             if (newpackets)
1729                 matroska->packets = newpackets;
1730         } else {
1731             av_freep(&matroska->packets);
1732             matroska->prev_pkt = NULL;
1733         }
1734         matroska->num_packets--;
1735         return 0;
1736     }
1737
1738     return -1;
1739 }
1740
1741 /*
1742  * Free all packets in our internal queue.
1743  */
1744 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1745 {
1746     if (matroska->packets) {
1747         int n;
1748         for (n = 0; n < matroska->num_packets; n++) {
1749             av_free_packet(matroska->packets[n]);
1750             av_free(matroska->packets[n]);
1751         }
1752         av_freep(&matroska->packets);
1753         matroska->num_packets = 0;
1754     }
1755 }
1756
1757 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
1758                                 int size, int type,
1759                                 uint32_t **lace_buf, int *laces)
1760 {
1761     int res = 0, n;
1762     uint8_t *data = *buf;
1763     uint32_t *lace_size;
1764
1765     if (!type) {
1766         *laces = 1;
1767         *lace_buf = av_mallocz(sizeof(int));
1768         if (!*lace_buf)
1769             return AVERROR(ENOMEM);
1770
1771         *lace_buf[0] = size;
1772         return 0;
1773     }
1774
1775     assert(size > 0);
1776     *laces = *data + 1;
1777     data += 1;
1778     size -= 1;
1779     lace_size = av_mallocz(*laces * sizeof(int));
1780     if (!lace_size)
1781         return AVERROR(ENOMEM);
1782
1783     switch (type) {
1784     case 0x1: /* Xiph lacing */ {
1785         uint8_t temp;
1786         uint32_t total = 0;
1787         for (n = 0; res == 0 && n < *laces - 1; n++) {
1788             while (1) {
1789                 if (size == 0) {
1790                     res = AVERROR_EOF;
1791                     break;
1792                 }
1793                 temp = *data;
1794                 lace_size[n] += temp;
1795                 data += 1;
1796                 size -= 1;
1797                 if (temp != 0xff)
1798                     break;
1799             }
1800             total += lace_size[n];
1801         }
1802         if (size <= total) {
1803             res = AVERROR_INVALIDDATA;
1804             break;
1805         }
1806
1807         lace_size[n] = size - total;
1808         break;
1809     }
1810
1811     case 0x2: /* fixed-size lacing */
1812         if (size % (*laces)) {
1813             res = AVERROR_INVALIDDATA;
1814             break;
1815         }
1816         for (n = 0; n < *laces; n++)
1817             lace_size[n] = size / *laces;
1818         break;
1819
1820     case 0x3: /* EBML lacing */ {
1821         uint64_t num;
1822         uint32_t total;
1823         n = matroska_ebmlnum_uint(matroska, data, size, &num);
1824         if (n < 0) {
1825             av_log(matroska->ctx, AV_LOG_INFO,
1826                    "EBML block data error\n");
1827             res = n;
1828             break;
1829         }
1830         data += n;
1831         size -= n;
1832         total = lace_size[0] = num;
1833         for (n = 1; res == 0 && n < *laces - 1; n++) {
1834             int64_t snum;
1835             int r;
1836             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1837             if (r < 0) {
1838                 av_log(matroska->ctx, AV_LOG_INFO,
1839                        "EBML block data error\n");
1840                 res = r;
1841                 break;
1842             }
1843             data += r;
1844             size -= r;
1845             lace_size[n] = lace_size[n - 1] + snum;
1846             total += lace_size[n];
1847         }
1848         if (size <= total) {
1849             res = AVERROR_INVALIDDATA;
1850             break;
1851         }
1852         lace_size[*laces - 1] = size - total;
1853         break;
1854     }
1855     }
1856
1857     *buf      = data;
1858     *lace_buf = lace_size;
1859
1860     return res;
1861 }
1862
1863 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
1864                                    MatroskaTrack *track,
1865                                    AVStream *st,
1866                                    uint8_t *data, int size,
1867                                    uint64_t timecode, uint64_t duration,
1868                                    int64_t pos)
1869 {
1870     int a = st->codec->block_align;
1871     int sps = track->audio.sub_packet_size;
1872     int cfs = track->audio.coded_framesize;
1873     int h = track->audio.sub_packet_h;
1874     int y = track->audio.sub_packet_cnt;
1875     int w = track->audio.frame_size;
1876     int x;
1877
1878     if (!track->audio.pkt_cnt) {
1879         if (track->audio.sub_packet_cnt == 0)
1880             track->audio.buf_timecode = timecode;
1881         if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
1882             if (size < cfs * h / 2) {
1883                 av_log(matroska->ctx, AV_LOG_ERROR,
1884                        "Corrupt int4 RM-style audio packet size\n");
1885                 return AVERROR_INVALIDDATA;
1886             }
1887             for (x=0; x<h/2; x++)
1888                 memcpy(track->audio.buf+x*2*w+y*cfs,
1889                        data+x*cfs, cfs);
1890         } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
1891             if (size < w) {
1892                 av_log(matroska->ctx, AV_LOG_ERROR,
1893                        "Corrupt sipr RM-style audio packet size\n");
1894                 return AVERROR_INVALIDDATA;
1895             }
1896             memcpy(track->audio.buf + y*w, data, w);
1897         } else {
1898             if (size < sps * w / sps) {
1899                 av_log(matroska->ctx, AV_LOG_ERROR,
1900                        "Corrupt generic RM-style audio packet size\n");
1901                 return AVERROR_INVALIDDATA;
1902             }
1903             for (x=0; x<w/sps; x++)
1904                 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1905         }
1906
1907         if (++track->audio.sub_packet_cnt >= h) {
1908             if (st->codec->codec_id == AV_CODEC_ID_SIPR)
1909                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1910             track->audio.sub_packet_cnt = 0;
1911             track->audio.pkt_cnt = h*w / a;
1912         }
1913     }
1914
1915     while (track->audio.pkt_cnt) {
1916         AVPacket *pkt = av_mallocz(sizeof(AVPacket));
1917         av_new_packet(pkt, a);
1918         memcpy(pkt->data, track->audio.buf
1919                + a * (h*w / a - track->audio.pkt_cnt--), a);
1920         pkt->pts = track->audio.buf_timecode;
1921         track->audio.buf_timecode = AV_NOPTS_VALUE;
1922         pkt->pos = pos;
1923         pkt->stream_index = st->index;
1924         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1925     }
1926
1927     return 0;
1928 }
1929 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
1930                                 MatroskaTrack *track,
1931                                 AVStream *st,
1932                                 uint8_t *data, int pkt_size,
1933                                 uint64_t timecode, uint64_t duration,
1934                                 int64_t pos, int is_keyframe)
1935 {
1936     MatroskaTrackEncoding *encodings = track->encodings.elem;
1937     uint8_t *pkt_data = data;
1938     int offset = 0, res;
1939     AVPacket *pkt;
1940
1941     if (encodings && encodings->scope & 1) {
1942         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
1943         if (res < 0)
1944             return res;
1945     }
1946
1947     if (st->codec->codec_id == AV_CODEC_ID_PRORES)
1948         offset = 8;
1949
1950     pkt = av_mallocz(sizeof(AVPacket));
1951     /* XXX: prevent data copy... */
1952     if (av_new_packet(pkt, pkt_size + offset) < 0) {
1953         av_free(pkt);
1954         return AVERROR(ENOMEM);
1955     }
1956
1957     if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
1958         uint8_t *buf = pkt->data;
1959         bytestream_put_be32(&buf, pkt_size);
1960         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
1961     }
1962
1963     memcpy(pkt->data + offset, pkt_data, pkt_size);
1964
1965     if (pkt_data != data)
1966         av_free(pkt_data);
1967
1968     pkt->flags = is_keyframe;
1969     pkt->stream_index = st->index;
1970
1971     if (track->ms_compat)
1972         pkt->dts = timecode;
1973     else
1974         pkt->pts = timecode;
1975     pkt->pos = pos;
1976     if (st->codec->codec_id == AV_CODEC_ID_TEXT)
1977         pkt->convergence_duration = duration;
1978     else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1979         pkt->duration = duration;
1980
1981     if (st->codec->codec_id == AV_CODEC_ID_SSA)
1982         matroska_fix_ass_packet(matroska, pkt, duration);
1983
1984     if (matroska->prev_pkt &&
1985         timecode != AV_NOPTS_VALUE &&
1986         matroska->prev_pkt->pts == timecode &&
1987         matroska->prev_pkt->stream_index == st->index &&
1988         st->codec->codec_id == AV_CODEC_ID_SSA)
1989         matroska_merge_packets(matroska->prev_pkt, pkt);
1990     else {
1991         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1992         matroska->prev_pkt = pkt;
1993     }
1994
1995     return 0;
1996 }
1997
1998 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1999                                 int size, int64_t pos, uint64_t cluster_time,
2000                                 uint64_t block_duration, int is_keyframe,
2001                                 int64_t cluster_pos)
2002 {
2003     uint64_t timecode = AV_NOPTS_VALUE;
2004     MatroskaTrack *track;
2005     int res = 0;
2006     AVStream *st;
2007     int16_t block_time;
2008     uint32_t *lace_size = NULL;
2009     int n, flags, laces = 0;
2010     uint64_t num, duration;
2011
2012     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2013         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2014         return n;
2015     }
2016     data += n;
2017     size -= n;
2018
2019     track = matroska_find_track_by_num(matroska, num);
2020     if (!track || !track->stream) {
2021         av_log(matroska->ctx, AV_LOG_INFO,
2022                "Invalid stream %"PRIu64" or size %u\n", num, size);
2023         return AVERROR_INVALIDDATA;
2024     } else if (size <= 3)
2025         return 0;
2026     st = track->stream;
2027     if (st->discard >= AVDISCARD_ALL)
2028         return res;
2029
2030     block_time = AV_RB16(data);
2031     data += 2;
2032     flags = *data++;
2033     size -= 3;
2034     if (is_keyframe == -1)
2035         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2036
2037     if (cluster_time != (uint64_t)-1
2038         && (block_time >= 0 || cluster_time >= -block_time)) {
2039         timecode = cluster_time + block_time;
2040         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2041             && timecode < track->end_timecode)
2042             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2043         if (is_keyframe)
2044             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2045     }
2046
2047     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2048         if (!is_keyframe || timecode < matroska->skip_to_timecode)
2049             return res;
2050         matroska->skip_to_keyframe = 0;
2051     }
2052
2053     res = matroska_parse_laces(matroska, &data, size, (flags & 0x06) >> 1,
2054                                &lace_size, &laces);
2055
2056     if (res)
2057         goto end;
2058
2059     if (block_duration != AV_NOPTS_VALUE) {
2060         duration = block_duration / laces;
2061         if (block_duration != duration * laces) {
2062             av_log(matroska->ctx, AV_LOG_WARNING,
2063                    "Incorrect block_duration, possibly corrupted container");
2064         }
2065     } else {
2066         duration = track->default_duration / matroska->time_scale;
2067         block_duration = duration * laces;
2068     }
2069
2070     if (timecode != AV_NOPTS_VALUE)
2071         track->end_timecode =
2072             FFMAX(track->end_timecode, timecode + block_duration);
2073
2074     for (n = 0; n < laces; n++) {
2075         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2076              st->codec->codec_id == AV_CODEC_ID_COOK ||
2077              st->codec->codec_id == AV_CODEC_ID_SIPR ||
2078              st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2079              st->codec->block_align && track->audio.sub_packet_size) {
2080
2081             res = matroska_parse_rm_audio(matroska, track, st, data, size,
2082                                           timecode, duration, pos);
2083             if (res)
2084                 goto end;
2085
2086         } else {
2087             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2088                                       timecode, duration,
2089                                       pos, !n? is_keyframe : 0);
2090             if (res)
2091                 goto end;
2092         }
2093
2094         if (timecode != AV_NOPTS_VALUE)
2095             timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2096         data += lace_size[n];
2097         size -= lace_size[n];
2098     }
2099
2100 end:
2101     av_free(lace_size);
2102     return res;
2103 }
2104
2105 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2106 {
2107     EbmlList *blocks_list;
2108     MatroskaBlock *blocks;
2109     int i, res;
2110     res = ebml_parse(matroska,
2111                      matroska_cluster_incremental_parsing,
2112                      &matroska->current_cluster);
2113     if (res == 1) {
2114         /* New Cluster */
2115         if (matroska->current_cluster_pos)
2116             ebml_level_end(matroska);
2117         ebml_free(matroska_cluster, &matroska->current_cluster);
2118         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2119         matroska->current_cluster_num_blocks = 0;
2120         matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2121         matroska->prev_pkt = NULL;
2122         /* sizeof the ID which was already read */
2123         if (matroska->current_id)
2124             matroska->current_cluster_pos -= 4;
2125         res = ebml_parse(matroska,
2126                          matroska_clusters_incremental,
2127                          &matroska->current_cluster);
2128         /* Try parsing the block again. */
2129         if (res == 1)
2130             res = ebml_parse(matroska,
2131                              matroska_cluster_incremental_parsing,
2132                              &matroska->current_cluster);
2133     }
2134
2135     if (!res &&
2136         matroska->current_cluster_num_blocks <
2137             matroska->current_cluster.blocks.nb_elem) {
2138         blocks_list = &matroska->current_cluster.blocks;
2139         blocks = blocks_list->elem;
2140
2141         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2142         i = blocks_list->nb_elem - 1;
2143         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2144             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2145             if (!blocks[i].non_simple)
2146                 blocks[i].duration = AV_NOPTS_VALUE;
2147             res = matroska_parse_block(matroska,
2148                                        blocks[i].bin.data, blocks[i].bin.size,
2149                                        blocks[i].bin.pos,
2150                                        matroska->current_cluster.timecode,
2151                                        blocks[i].duration, is_keyframe,
2152                                        matroska->current_cluster_pos);
2153         }
2154     }
2155
2156     if (res < 0)  matroska->done = 1;
2157     return res;
2158 }
2159
2160 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2161 {
2162     MatroskaCluster cluster = { 0 };
2163     EbmlList *blocks_list;
2164     MatroskaBlock *blocks;
2165     int i, res;
2166     int64_t pos;
2167     if (!matroska->contains_ssa)
2168         return matroska_parse_cluster_incremental(matroska);
2169     pos = avio_tell(matroska->ctx->pb);
2170     matroska->prev_pkt = NULL;
2171     if (matroska->current_id)
2172         pos -= 4;  /* sizeof the ID which was already read */
2173     res = ebml_parse(matroska, matroska_clusters, &cluster);
2174     blocks_list = &cluster.blocks;
2175     blocks = blocks_list->elem;
2176     for (i=0; i<blocks_list->nb_elem && !res; i++)
2177         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2178             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2179             if (!blocks[i].non_simple)
2180                 blocks[i].duration = AV_NOPTS_VALUE;
2181             res=matroska_parse_block(matroska,
2182                                      blocks[i].bin.data, blocks[i].bin.size,
2183                                      blocks[i].bin.pos,  cluster.timecode,
2184                                      blocks[i].duration, is_keyframe,
2185                                      pos);
2186         }
2187     ebml_free(matroska_cluster, &cluster);
2188     if (res < 0)  matroska->done = 1;
2189     return res;
2190 }
2191
2192 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2193 {
2194     MatroskaDemuxContext *matroska = s->priv_data;
2195     int ret = 0;
2196
2197     while (!ret && matroska_deliver_packet(matroska, pkt)) {
2198         if (matroska->done)
2199             return AVERROR_EOF;
2200         ret = matroska_parse_cluster(matroska);
2201     }
2202
2203     if (ret == AVERROR_INVALIDDATA && pkt->data) {
2204         pkt->flags |= AV_PKT_FLAG_CORRUPT;
2205         return 0;
2206     }
2207
2208     return ret;
2209 }
2210
2211 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2212                               int64_t timestamp, int flags)
2213 {
2214     MatroskaDemuxContext *matroska = s->priv_data;
2215     MatroskaTrack *tracks = matroska->tracks.elem;
2216     AVStream *st = s->streams[stream_index];
2217     int i, index, index_sub, index_min;
2218
2219     /* Parse the CUES now since we need the index data to seek. */
2220     if (matroska->cues_parsing_deferred) {
2221         matroska_parse_cues(matroska);
2222         matroska->cues_parsing_deferred = 0;
2223     }
2224
2225     if (!st->nb_index_entries)
2226         return 0;
2227     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2228
2229     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2230         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2231         matroska->current_id = 0;
2232         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2233             matroska->prev_pkt = NULL;
2234             matroska_clear_queue(matroska);
2235             if (matroska_parse_cluster(matroska) < 0)
2236                 break;
2237         }
2238     }
2239
2240     matroska_clear_queue(matroska);
2241     if (index < 0)
2242         return 0;
2243
2244     index_min = index;
2245     for (i=0; i < matroska->tracks.nb_elem; i++) {
2246         tracks[i].audio.pkt_cnt = 0;
2247         tracks[i].audio.sub_packet_cnt = 0;
2248         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2249         tracks[i].end_timecode = 0;
2250         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2251             && !tracks[i].stream->discard != AVDISCARD_ALL) {
2252             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2253             if (index_sub >= 0
2254                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2255                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2256                 index_min = index_sub;
2257         }
2258     }
2259
2260     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2261     matroska->current_id = 0;
2262     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2263     matroska->skip_to_timecode = st->index_entries[index].timestamp;
2264     matroska->done = 0;
2265     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2266     return 0;
2267 }
2268
2269 static int matroska_read_close(AVFormatContext *s)
2270 {
2271     MatroskaDemuxContext *matroska = s->priv_data;
2272     MatroskaTrack *tracks = matroska->tracks.elem;
2273     int n;
2274
2275     matroska_clear_queue(matroska);
2276
2277     for (n=0; n < matroska->tracks.nb_elem; n++)
2278         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2279             av_free(tracks[n].audio.buf);
2280     ebml_free(matroska_cluster, &matroska->current_cluster);
2281     ebml_free(matroska_segment, matroska);
2282
2283     return 0;
2284 }
2285
2286 AVInputFormat ff_matroska_demuxer = {
2287     .name           = "matroska,webm",
2288     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2289     .priv_data_size = sizeof(MatroskaDemuxContext),
2290     .read_probe     = matroska_probe,
2291     .read_header    = matroska_read_header,
2292     .read_packet    = matroska_read_packet,
2293     .read_close     = matroska_read_close,
2294     .read_seek      = matroska_read_seek,
2295 };