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