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