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