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