9c11c71e1f9a412ca76001c5140b84c546f87d18
[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                     && attachment[j].stream)
1089                     matroska_convert_tag(s, &tags[i].tag,
1090                                          &attachment[j].stream->metadata, NULL);
1091         } else if (tags[i].target.chapteruid) {
1092             MatroskaChapter *chapter = matroska->chapters.elem;
1093             for (j=0; j<matroska->chapters.nb_elem; j++)
1094                 if (chapter[j].uid == tags[i].target.chapteruid
1095                     && chapter[j].chapter)
1096                     matroska_convert_tag(s, &tags[i].tag,
1097                                          &chapter[j].chapter->metadata, NULL);
1098         } else if (tags[i].target.trackuid) {
1099             MatroskaTrack *track = matroska->tracks.elem;
1100             for (j=0; j<matroska->tracks.nb_elem; j++)
1101                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1102                     matroska_convert_tag(s, &tags[i].tag,
1103                                          &track[j].stream->metadata, NULL);
1104         } else {
1105             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1106                                  tags[i].target.type);
1107         }
1108     }
1109 }
1110
1111 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1112 {
1113     EbmlList *seekhead_list = &matroska->seekhead;
1114     MatroskaSeekhead *seekhead = seekhead_list->elem;
1115     uint32_t level_up = matroska->level_up;
1116     int64_t before_pos = avio_tell(matroska->ctx->pb);
1117     uint32_t saved_id = matroska->current_id;
1118     MatroskaLevel level;
1119     int i;
1120
1121     // we should not do any seeking in the streaming case
1122     if (!matroska->ctx->pb->seekable ||
1123         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1124         return;
1125
1126     for (i=0; i<seekhead_list->nb_elem; i++) {
1127         int64_t offset = seekhead[i].pos + matroska->segment_start;
1128
1129         if (seekhead[i].pos <= before_pos
1130             || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1131             || seekhead[i].id == MATROSKA_ID_CLUSTER)
1132             continue;
1133
1134         /* seek */
1135         if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1136             continue;
1137
1138         /* We don't want to lose our seekhead level, so we add
1139          * a dummy. This is a crude hack. */
1140         if (matroska->num_levels == EBML_MAX_DEPTH) {
1141             av_log(matroska->ctx, AV_LOG_INFO,
1142                    "Max EBML element depth (%d) reached, "
1143                    "cannot parse further.\n", EBML_MAX_DEPTH);
1144             break;
1145         }
1146
1147         level.start = 0;
1148         level.length = (uint64_t)-1;
1149         matroska->levels[matroska->num_levels] = level;
1150         matroska->num_levels++;
1151         matroska->current_id = 0;
1152
1153         ebml_parse(matroska, matroska_segment, matroska);
1154
1155         /* remove dummy level */
1156         while (matroska->num_levels) {
1157             uint64_t length = matroska->levels[--matroska->num_levels].length;
1158             if (length == (uint64_t)-1)
1159                 break;
1160         }
1161     }
1162
1163     /* seek back */
1164     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1165     matroska->level_up = level_up;
1166     matroska->current_id = saved_id;
1167 }
1168
1169 static int matroska_aac_profile(char *codec_id)
1170 {
1171     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1172     int profile;
1173
1174     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1175         if (strstr(codec_id, aac_profiles[profile]))
1176             break;
1177     return profile + 1;
1178 }
1179
1180 static int matroska_aac_sri(int samplerate)
1181 {
1182     int sri;
1183
1184     for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1185         if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1186             break;
1187     return sri;
1188 }
1189
1190 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1191 {
1192     MatroskaDemuxContext *matroska = s->priv_data;
1193     EbmlList *attachements_list = &matroska->attachments;
1194     MatroskaAttachement *attachements;
1195     EbmlList *chapters_list = &matroska->chapters;
1196     MatroskaChapter *chapters;
1197     MatroskaTrack *tracks;
1198     EbmlList *index_list;
1199     MatroskaIndex *index;
1200     int index_scale = 1;
1201     uint64_t max_start = 0;
1202     Ebml ebml = { 0 };
1203     AVStream *st;
1204     int i, j, res;
1205
1206     matroska->ctx = s;
1207
1208     /* First read the EBML header. */
1209     if (ebml_parse(matroska, ebml_syntax, &ebml)
1210         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1211         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1212         av_log(matroska->ctx, AV_LOG_ERROR,
1213                "EBML header using unsupported features\n"
1214                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1215                ebml.version, ebml.doctype, ebml.doctype_version);
1216         ebml_free(ebml_syntax, &ebml);
1217         return AVERROR_PATCHWELCOME;
1218     }
1219     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1220         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1221             break;
1222     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1223         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1224     }
1225     ebml_free(ebml_syntax, &ebml);
1226
1227     /* The next thing is a segment. */
1228     if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1229         return res;
1230     matroska_execute_seekhead(matroska);
1231
1232     if (!matroska->time_scale)
1233         matroska->time_scale = 1000000;
1234     if (matroska->duration)
1235         matroska->ctx->duration = matroska->duration * matroska->time_scale
1236                                   * 1000 / AV_TIME_BASE;
1237     av_metadata_set2(&s->metadata, "title", matroska->title, 0);
1238
1239     tracks = matroska->tracks.elem;
1240     for (i=0; i < matroska->tracks.nb_elem; i++) {
1241         MatroskaTrack *track = &tracks[i];
1242         enum CodecID codec_id = CODEC_ID_NONE;
1243         EbmlList *encodings_list = &tracks->encodings;
1244         MatroskaTrackEncoding *encodings = encodings_list->elem;
1245         uint8_t *extradata = NULL;
1246         int extradata_size = 0;
1247         int extradata_offset = 0;
1248         AVIOContext b;
1249
1250         /* Apply some sanity checks. */
1251         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1252             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1253             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1254             av_log(matroska->ctx, AV_LOG_INFO,
1255                    "Unknown or unsupported track type %"PRIu64"\n",
1256                    track->type);
1257             continue;
1258         }
1259         if (track->codec_id == NULL)
1260             continue;
1261
1262         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1263             if (!track->default_duration)
1264                 track->default_duration = 1000000000/track->video.frame_rate;
1265             if (!track->video.display_width)
1266                 track->video.display_width = track->video.pixel_width;
1267             if (!track->video.display_height)
1268                 track->video.display_height = track->video.pixel_height;
1269         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1270             if (!track->audio.out_samplerate)
1271                 track->audio.out_samplerate = track->audio.samplerate;
1272         }
1273         if (encodings_list->nb_elem > 1) {
1274             av_log(matroska->ctx, AV_LOG_ERROR,
1275                    "Multiple combined encodings no supported");
1276         } else if (encodings_list->nb_elem == 1) {
1277             if (encodings[0].type ||
1278                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1279 #if CONFIG_ZLIB
1280                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1281 #endif
1282 #if CONFIG_BZLIB
1283                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1284 #endif
1285                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1286                 encodings[0].scope = 0;
1287                 av_log(matroska->ctx, AV_LOG_ERROR,
1288                        "Unsupported encoding type");
1289             } else if (track->codec_priv.size && encodings[0].scope&2) {
1290                 uint8_t *codec_priv = track->codec_priv.data;
1291                 int offset = matroska_decode_buffer(&track->codec_priv.data,
1292                                                     &track->codec_priv.size,
1293                                                     track);
1294                 if (offset < 0) {
1295                     track->codec_priv.data = NULL;
1296                     track->codec_priv.size = 0;
1297                     av_log(matroska->ctx, AV_LOG_ERROR,
1298                            "Failed to decode codec private data\n");
1299                 } else if (offset > 0) {
1300                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1301                     memcpy(track->codec_priv.data,
1302                            encodings[0].compression.settings.data, offset);
1303                     memcpy(track->codec_priv.data+offset, codec_priv,
1304                            track->codec_priv.size);
1305                     track->codec_priv.size += offset;
1306                 }
1307                 if (codec_priv != track->codec_priv.data)
1308                     av_free(codec_priv);
1309             }
1310         }
1311
1312         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1313             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1314                         strlen(ff_mkv_codec_tags[j].str))){
1315                 codec_id= ff_mkv_codec_tags[j].id;
1316                 break;
1317             }
1318         }
1319
1320         st = track->stream = av_new_stream(s, 0);
1321         if (st == NULL)
1322             return AVERROR(ENOMEM);
1323
1324         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1325             && track->codec_priv.size >= 40
1326             && track->codec_priv.data != NULL) {
1327             track->ms_compat = 1;
1328             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1329             codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1330             extradata_offset = 40;
1331         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1332                    && track->codec_priv.size >= 14
1333                    && track->codec_priv.data != NULL) {
1334             int ret;
1335             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1336                           AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
1337             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1338             if (ret < 0)
1339                 return ret;
1340             codec_id = st->codec->codec_id;
1341             extradata_offset = FFMIN(track->codec_priv.size, 18);
1342         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1343                    && (track->codec_priv.size >= 86)
1344                    && (track->codec_priv.data != NULL)) {
1345             track->video.fourcc = AV_RL32(track->codec_priv.data);
1346             codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
1347         } else if (codec_id == CODEC_ID_PCM_S16BE) {
1348             switch (track->audio.bitdepth) {
1349             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1350             case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1351             case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1352             }
1353         } else if (codec_id == CODEC_ID_PCM_S16LE) {
1354             switch (track->audio.bitdepth) {
1355             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1356             case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1357             case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1358             }
1359         } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1360             codec_id = CODEC_ID_PCM_F64LE;
1361         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1362             int profile = matroska_aac_profile(track->codec_id);
1363             int sri = matroska_aac_sri(track->audio.samplerate);
1364             extradata = av_malloc(5);
1365             if (extradata == NULL)
1366                 return AVERROR(ENOMEM);
1367             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1368             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1369             if (strstr(track->codec_id, "SBR")) {
1370                 sri = matroska_aac_sri(track->audio.out_samplerate);
1371                 extradata[2] = 0x56;
1372                 extradata[3] = 0xE5;
1373                 extradata[4] = 0x80 | (sri<<3);
1374                 extradata_size = 5;
1375             } else
1376                 extradata_size = 2;
1377         } else if (codec_id == CODEC_ID_TTA) {
1378             extradata_size = 30;
1379             extradata = av_mallocz(extradata_size);
1380             if (extradata == NULL)
1381                 return AVERROR(ENOMEM);
1382             ffio_init_context(&b, extradata, extradata_size, 1,
1383                           NULL, NULL, NULL, NULL);
1384             avio_write(&b, "TTA1", 4);
1385             avio_wl16(&b, 1);
1386             avio_wl16(&b, track->audio.channels);
1387             avio_wl16(&b, track->audio.bitdepth);
1388             avio_wl32(&b, track->audio.out_samplerate);
1389             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1390         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1391                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1392             extradata_offset = 26;
1393         } else if (codec_id == CODEC_ID_RA_144) {
1394             track->audio.out_samplerate = 8000;
1395             track->audio.channels = 1;
1396         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1397                    codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1398             int flavor;
1399             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1400                           0, NULL, NULL, NULL, NULL);
1401             avio_skip(&b, 22);
1402             flavor                       = avio_rb16(&b);
1403             track->audio.coded_framesize = avio_rb32(&b);
1404             avio_skip(&b, 12);
1405             track->audio.sub_packet_h    = avio_rb16(&b);
1406             track->audio.frame_size      = avio_rb16(&b);
1407             track->audio.sub_packet_size = avio_rb16(&b);
1408             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1409             if (codec_id == CODEC_ID_RA_288) {
1410                 st->codec->block_align = track->audio.coded_framesize;
1411                 track->codec_priv.size = 0;
1412             } else {
1413                 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1414                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1415                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1416                     st->codec->bit_rate = sipr_bit_rate[flavor];
1417                 }
1418                 st->codec->block_align = track->audio.sub_packet_size;
1419                 extradata_offset = 78;
1420             }
1421         }
1422         track->codec_priv.size -= extradata_offset;
1423
1424         if (codec_id == CODEC_ID_NONE)
1425             av_log(matroska->ctx, AV_LOG_INFO,
1426                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
1427
1428         if (track->time_scale < 0.01)
1429             track->time_scale = 1.0;
1430         av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1431
1432         st->codec->codec_id = codec_id;
1433         st->start_time = 0;
1434         if (strcmp(track->language, "und"))
1435             av_metadata_set2(&st->metadata, "language", track->language, 0);
1436         av_metadata_set2(&st->metadata, "title", track->name, 0);
1437
1438         if (track->flag_default)
1439             st->disposition |= AV_DISPOSITION_DEFAULT;
1440         if (track->flag_forced)
1441             st->disposition |= AV_DISPOSITION_FORCED;
1442
1443         if (track->default_duration)
1444             av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1445                       track->default_duration, 1000000000, 30000);
1446
1447         if (!st->codec->extradata) {
1448             if(extradata){
1449                 st->codec->extradata = extradata;
1450                 st->codec->extradata_size = extradata_size;
1451             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1452                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1453                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1454                 if(st->codec->extradata == NULL)
1455                     return AVERROR(ENOMEM);
1456                 st->codec->extradata_size = track->codec_priv.size;
1457                 memcpy(st->codec->extradata,
1458                        track->codec_priv.data + extradata_offset,
1459                        track->codec_priv.size);
1460             }
1461         }
1462
1463         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1464             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1465             st->codec->codec_tag  = track->video.fourcc;
1466             st->codec->width  = track->video.pixel_width;
1467             st->codec->height = track->video.pixel_height;
1468             av_reduce(&st->sample_aspect_ratio.num,
1469                       &st->sample_aspect_ratio.den,
1470                       st->codec->height * track->video.display_width,
1471                       st->codec-> width * track->video.display_height,
1472                       255);
1473             if (st->codec->codec_id != CODEC_ID_H264)
1474             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1475             if (track->default_duration)
1476                 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1477         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1478             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1479             st->codec->sample_rate = track->audio.out_samplerate;
1480             st->codec->channels = track->audio.channels;
1481             if (st->codec->codec_id != CODEC_ID_AAC)
1482             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1483         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1484             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1485         }
1486     }
1487
1488     attachements = attachements_list->elem;
1489     for (j=0; j<attachements_list->nb_elem; j++) {
1490         if (!(attachements[j].filename && attachements[j].mime &&
1491               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1492             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1493         } else {
1494             AVStream *st = av_new_stream(s, 0);
1495             if (st == NULL)
1496                 break;
1497             av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
1498             st->codec->codec_id = CODEC_ID_NONE;
1499             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1500             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1501             if(st->codec->extradata == NULL)
1502                 break;
1503             st->codec->extradata_size = attachements[j].bin.size;
1504             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1505
1506             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1507                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1508                              strlen(ff_mkv_mime_tags[i].str))) {
1509                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1510                     break;
1511                 }
1512             }
1513             attachements[j].stream = st;
1514         }
1515     }
1516
1517     chapters = chapters_list->elem;
1518     for (i=0; i<chapters_list->nb_elem; i++)
1519         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1520             && (max_start==0 || chapters[i].start > max_start)) {
1521             chapters[i].chapter =
1522             ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1523                            chapters[i].start, chapters[i].end,
1524                            chapters[i].title);
1525             av_metadata_set2(&chapters[i].chapter->metadata,
1526                              "title", chapters[i].title, 0);
1527             max_start = chapters[i].start;
1528         }
1529
1530     index_list = &matroska->index;
1531     index = index_list->elem;
1532     if (index_list->nb_elem
1533         && index[0].time > 100000000000000/matroska->time_scale) {
1534         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1535         index_scale = matroska->time_scale;
1536     }
1537     for (i=0; i<index_list->nb_elem; i++) {
1538         EbmlList *pos_list = &index[i].pos;
1539         MatroskaIndexPos *pos = pos_list->elem;
1540         for (j=0; j<pos_list->nb_elem; j++) {
1541             MatroskaTrack *track = matroska_find_track_by_num(matroska,
1542                                                               pos[j].track);
1543             if (track && track->stream)
1544                 av_add_index_entry(track->stream,
1545                                    pos[j].pos + matroska->segment_start,
1546                                    index[i].time/index_scale, 0, 0,
1547                                    AVINDEX_KEYFRAME);
1548         }
1549     }
1550
1551     matroska_convert_tags(s);
1552
1553     return 0;
1554 }
1555
1556 /*
1557  * Put one packet in an application-supplied AVPacket struct.
1558  * Returns 0 on success or -1 on failure.
1559  */
1560 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1561                                    AVPacket *pkt)
1562 {
1563     if (matroska->num_packets > 0) {
1564         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1565         av_free(matroska->packets[0]);
1566         if (matroska->num_packets > 1) {
1567             memmove(&matroska->packets[0], &matroska->packets[1],
1568                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1569             matroska->packets =
1570                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1571                            sizeof(AVPacket *));
1572         } else {
1573             av_freep(&matroska->packets);
1574         }
1575         matroska->num_packets--;
1576         return 0;
1577     }
1578
1579     return -1;
1580 }
1581
1582 /*
1583  * Free all packets in our internal queue.
1584  */
1585 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1586 {
1587     if (matroska->packets) {
1588         int n;
1589         for (n = 0; n < matroska->num_packets; n++) {
1590             av_free_packet(matroska->packets[n]);
1591             av_free(matroska->packets[n]);
1592         }
1593         av_freep(&matroska->packets);
1594         matroska->num_packets = 0;
1595     }
1596 }
1597
1598 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1599                                 int size, int64_t pos, uint64_t cluster_time,
1600                                 uint64_t duration, int is_keyframe,
1601                                 int64_t cluster_pos)
1602 {
1603     uint64_t timecode = AV_NOPTS_VALUE;
1604     MatroskaTrack *track;
1605     int res = 0;
1606     AVStream *st;
1607     AVPacket *pkt;
1608     int16_t block_time;
1609     uint32_t *lace_size = NULL;
1610     int n, flags, laces = 0;
1611     uint64_t num;
1612
1613     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1614         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1615         return res;
1616     }
1617     data += n;
1618     size -= n;
1619
1620     track = matroska_find_track_by_num(matroska, num);
1621     if (size <= 3 || !track || !track->stream) {
1622         av_log(matroska->ctx, AV_LOG_INFO,
1623                "Invalid stream %"PRIu64" or size %u\n", num, size);
1624         return res;
1625     }
1626     st = track->stream;
1627     if (st->discard >= AVDISCARD_ALL)
1628         return res;
1629     if (duration == AV_NOPTS_VALUE)
1630         duration = track->default_duration / matroska->time_scale;
1631
1632     block_time = AV_RB16(data);
1633     data += 2;
1634     flags = *data++;
1635     size -= 3;
1636     if (is_keyframe == -1)
1637         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1638
1639     if (cluster_time != (uint64_t)-1
1640         && (block_time >= 0 || cluster_time >= -block_time)) {
1641         timecode = cluster_time + block_time;
1642         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1643             && timecode < track->end_timecode)
1644             is_keyframe = 0;  /* overlapping subtitles are not key frame */
1645         if (is_keyframe)
1646             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1647         track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1648     }
1649
1650     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1651         if (!is_keyframe || timecode < matroska->skip_to_timecode)
1652             return res;
1653         matroska->skip_to_keyframe = 0;
1654     }
1655
1656     switch ((flags & 0x06) >> 1) {
1657         case 0x0: /* no lacing */
1658             laces = 1;
1659             lace_size = av_mallocz(sizeof(int));
1660             lace_size[0] = size;
1661             break;
1662
1663         case 0x1: /* Xiph lacing */
1664         case 0x2: /* fixed-size lacing */
1665         case 0x3: /* EBML lacing */
1666             assert(size>0); // size <=3 is checked before size-=3 above
1667             laces = (*data) + 1;
1668             data += 1;
1669             size -= 1;
1670             lace_size = av_mallocz(laces * sizeof(int));
1671
1672             switch ((flags & 0x06) >> 1) {
1673                 case 0x1: /* Xiph lacing */ {
1674                     uint8_t temp;
1675                     uint32_t total = 0;
1676                     for (n = 0; res == 0 && n < laces - 1; n++) {
1677                         while (1) {
1678                             if (size == 0) {
1679                                 res = -1;
1680                                 break;
1681                             }
1682                             temp = *data;
1683                             lace_size[n] += temp;
1684                             data += 1;
1685                             size -= 1;
1686                             if (temp != 0xff)
1687                                 break;
1688                         }
1689                         total += lace_size[n];
1690                     }
1691                     lace_size[n] = size - total;
1692                     break;
1693                 }
1694
1695                 case 0x2: /* fixed-size lacing */
1696                     for (n = 0; n < laces; n++)
1697                         lace_size[n] = size / laces;
1698                     break;
1699
1700                 case 0x3: /* EBML lacing */ {
1701                     uint32_t total;
1702                     n = matroska_ebmlnum_uint(matroska, data, size, &num);
1703                     if (n < 0) {
1704                         av_log(matroska->ctx, AV_LOG_INFO,
1705                                "EBML block data error\n");
1706                         break;
1707                     }
1708                     data += n;
1709                     size -= n;
1710                     total = lace_size[0] = num;
1711                     for (n = 1; res == 0 && n < laces - 1; n++) {
1712                         int64_t snum;
1713                         int r;
1714                         r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1715                         if (r < 0) {
1716                             av_log(matroska->ctx, AV_LOG_INFO,
1717                                    "EBML block data error\n");
1718                             break;
1719                         }
1720                         data += r;
1721                         size -= r;
1722                         lace_size[n] = lace_size[n - 1] + snum;
1723                         total += lace_size[n];
1724                     }
1725                     lace_size[n] = size - total;
1726                     break;
1727                 }
1728             }
1729             break;
1730     }
1731
1732     if (res == 0) {
1733         for (n = 0; n < laces; n++) {
1734             if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1735                  st->codec->codec_id == CODEC_ID_COOK ||
1736                  st->codec->codec_id == CODEC_ID_SIPR ||
1737                  st->codec->codec_id == CODEC_ID_ATRAC3) &&
1738                  st->codec->block_align && track->audio.sub_packet_size) {
1739                 int a = st->codec->block_align;
1740                 int sps = track->audio.sub_packet_size;
1741                 int cfs = track->audio.coded_framesize;
1742                 int h = track->audio.sub_packet_h;
1743                 int y = track->audio.sub_packet_cnt;
1744                 int w = track->audio.frame_size;
1745                 int x;
1746
1747                 if (!track->audio.pkt_cnt) {
1748                     if (st->codec->codec_id == CODEC_ID_RA_288)
1749                         for (x=0; x<h/2; x++)
1750                             memcpy(track->audio.buf+x*2*w+y*cfs,
1751                                    data+x*cfs, cfs);
1752                     else if (st->codec->codec_id == CODEC_ID_SIPR)
1753                         memcpy(track->audio.buf + y*w, data, w);
1754                     else
1755                         for (x=0; x<w/sps; x++)
1756                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1757
1758                     if (++track->audio.sub_packet_cnt >= h) {
1759                         if (st->codec->codec_id == CODEC_ID_SIPR)
1760                             ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1761                         track->audio.sub_packet_cnt = 0;
1762                         track->audio.pkt_cnt = h*w / a;
1763                     }
1764                 }
1765                 while (track->audio.pkt_cnt) {
1766                     pkt = av_mallocz(sizeof(AVPacket));
1767                     av_new_packet(pkt, a);
1768                     memcpy(pkt->data, track->audio.buf
1769                            + a * (h*w / a - track->audio.pkt_cnt--), a);
1770                     pkt->pos = pos;
1771                     pkt->stream_index = st->index;
1772                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1773                 }
1774             } else {
1775                 MatroskaTrackEncoding *encodings = track->encodings.elem;
1776                 int offset = 0, pkt_size = lace_size[n];
1777                 uint8_t *pkt_data = data;
1778
1779                 if (pkt_size > size) {
1780                     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1781                     break;
1782                 }
1783
1784                 if (encodings && encodings->scope & 1) {
1785                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1786                     if (offset < 0)
1787                         continue;
1788                 }
1789
1790                 pkt = av_mallocz(sizeof(AVPacket));
1791                 /* XXX: prevent data copy... */
1792                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1793                     av_free(pkt);
1794                     res = AVERROR(ENOMEM);
1795                     break;
1796                 }
1797                 if (offset)
1798                     memcpy (pkt->data, encodings->compression.settings.data, offset);
1799                 memcpy (pkt->data+offset, pkt_data, pkt_size);
1800
1801                 if (pkt_data != data)
1802                     av_free(pkt_data);
1803
1804                 if (n == 0)
1805                     pkt->flags = is_keyframe;
1806                 pkt->stream_index = st->index;
1807
1808                 if (track->ms_compat)
1809                     pkt->dts = timecode;
1810                 else
1811                     pkt->pts = timecode;
1812                 pkt->pos = pos;
1813                 if (st->codec->codec_id == CODEC_ID_TEXT)
1814                     pkt->convergence_duration = duration;
1815                 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1816                     pkt->duration = duration;
1817
1818                 if (st->codec->codec_id == CODEC_ID_SSA)
1819                     matroska_fix_ass_packet(matroska, pkt, duration);
1820
1821                 if (matroska->prev_pkt &&
1822                     timecode != AV_NOPTS_VALUE &&
1823                     matroska->prev_pkt->pts == timecode &&
1824                     matroska->prev_pkt->stream_index == st->index &&
1825                     st->codec->codec_id == CODEC_ID_SSA)
1826                     matroska_merge_packets(matroska->prev_pkt, pkt);
1827                 else {
1828                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1829                     matroska->prev_pkt = pkt;
1830                 }
1831             }
1832
1833             if (timecode != AV_NOPTS_VALUE)
1834                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1835             data += lace_size[n];
1836             size -= lace_size[n];
1837         }
1838     }
1839
1840     av_free(lace_size);
1841     return res;
1842 }
1843
1844 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1845 {
1846     MatroskaCluster cluster = { 0 };
1847     EbmlList *blocks_list;
1848     MatroskaBlock *blocks;
1849     int i, res;
1850     int64_t pos = avio_tell(matroska->ctx->pb);
1851     matroska->prev_pkt = NULL;
1852     if (matroska->current_id)
1853         pos -= 4;  /* sizeof the ID which was already read */
1854     res = ebml_parse(matroska, matroska_clusters, &cluster);
1855     blocks_list = &cluster.blocks;
1856     blocks = blocks_list->elem;
1857     for (i=0; i<blocks_list->nb_elem; i++)
1858         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1859             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1860             if (!blocks[i].non_simple)
1861                 blocks[i].duration = AV_NOPTS_VALUE;
1862             res=matroska_parse_block(matroska,
1863                                      blocks[i].bin.data, blocks[i].bin.size,
1864                                      blocks[i].bin.pos,  cluster.timecode,
1865                                      blocks[i].duration, is_keyframe,
1866                                      pos);
1867         }
1868     ebml_free(matroska_cluster, &cluster);
1869     if (res < 0)  matroska->done = 1;
1870     return res;
1871 }
1872
1873 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1874 {
1875     MatroskaDemuxContext *matroska = s->priv_data;
1876
1877     while (matroska_deliver_packet(matroska, pkt)) {
1878         if (matroska->done)
1879             return AVERROR_EOF;
1880         matroska_parse_cluster(matroska);
1881     }
1882
1883     return 0;
1884 }
1885
1886 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1887                               int64_t timestamp, int flags)
1888 {
1889     MatroskaDemuxContext *matroska = s->priv_data;
1890     MatroskaTrack *tracks = matroska->tracks.elem;
1891     AVStream *st = s->streams[stream_index];
1892     int i, index, index_sub, index_min;
1893
1894     if (!st->nb_index_entries)
1895         return 0;
1896     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1897
1898     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1899         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1900         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1901             matroska_clear_queue(matroska);
1902             if (matroska_parse_cluster(matroska) < 0)
1903                 break;
1904         }
1905     }
1906
1907     matroska_clear_queue(matroska);
1908     if (index < 0)
1909         return 0;
1910
1911     index_min = index;
1912     for (i=0; i < matroska->tracks.nb_elem; i++) {
1913         tracks[i].end_timecode = 0;
1914         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1915             && !tracks[i].stream->discard != AVDISCARD_ALL) {
1916             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1917             if (index_sub >= 0
1918                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1919                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1920                 index_min = index_sub;
1921         }
1922     }
1923
1924     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1925     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1926     matroska->skip_to_timecode = st->index_entries[index].timestamp;
1927     matroska->done = 0;
1928     av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1929     return 0;
1930 }
1931
1932 static int matroska_read_close(AVFormatContext *s)
1933 {
1934     MatroskaDemuxContext *matroska = s->priv_data;
1935     MatroskaTrack *tracks = matroska->tracks.elem;
1936     int n;
1937
1938     matroska_clear_queue(matroska);
1939
1940     for (n=0; n < matroska->tracks.nb_elem; n++)
1941         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1942             av_free(tracks[n].audio.buf);
1943     ebml_free(matroska_segment, matroska);
1944
1945     return 0;
1946 }
1947
1948 AVInputFormat ff_matroska_demuxer = {
1949     "matroska,webm",
1950     NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
1951     sizeof(MatroskaDemuxContext),
1952     matroska_probe,
1953     matroska_read_header,
1954     matroska_read_packet,
1955     matroska_read_close,
1956     matroska_read_seek,
1957 };