matroskadec: allow uint and float elements with length = 0
[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     uint64_t flag_forced;
143     MatroskaTrackVideo video;
144     MatroskaTrackAudio audio;
145     EbmlList encodings;
146
147     AVStream *stream;
148     int64_t end_timecode;
149     int ms_compat;
150 } MatroskaTrack;
151
152 typedef struct {
153     uint64_t uid;
154     char *filename;
155     char *mime;
156     EbmlBin bin;
157
158     AVStream *stream;
159 } MatroskaAttachement;
160
161 typedef struct {
162     uint64_t start;
163     uint64_t end;
164     uint64_t uid;
165     char    *title;
166
167     AVChapter *chapter;
168 } MatroskaChapter;
169
170 typedef struct {
171     uint64_t track;
172     uint64_t pos;
173 } MatroskaIndexPos;
174
175 typedef struct {
176     uint64_t time;
177     EbmlList pos;
178 } MatroskaIndex;
179
180 typedef struct {
181     char *name;
182     char *string;
183     char *lang;
184     uint64_t def;
185     EbmlList sub;
186 } MatroskaTag;
187
188 typedef struct {
189     char    *type;
190     uint64_t typevalue;
191     uint64_t trackuid;
192     uint64_t chapteruid;
193     uint64_t attachuid;
194 } MatroskaTagTarget;
195
196 typedef struct {
197     MatroskaTagTarget target;
198     EbmlList tag;
199 } MatroskaTags;
200
201 typedef struct {
202     uint64_t id;
203     uint64_t pos;
204 } MatroskaSeekhead;
205
206 typedef struct {
207     uint64_t start;
208     uint64_t length;
209 } MatroskaLevel;
210
211 typedef struct {
212     AVFormatContext *ctx;
213
214     /* EBML stuff */
215     int num_levels;
216     MatroskaLevel levels[EBML_MAX_DEPTH];
217     int level_up;
218     uint32_t current_id;
219
220     uint64_t time_scale;
221     double   duration;
222     char    *title;
223     EbmlList tracks;
224     EbmlList attachments;
225     EbmlList chapters;
226     EbmlList index;
227     EbmlList tags;
228     EbmlList seekhead;
229
230     /* byte position of the segment inside the stream */
231     int64_t segment_start;
232
233     /* the packet queue */
234     AVPacket **packets;
235     int num_packets;
236     AVPacket *prev_pkt;
237
238     int done;
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_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
341     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
342     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
343     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
344     { MATROSKA_ID_TRACKFLAGENABLED,     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 },
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 || matroska->current_id) {
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 read = 1, n = 1;
542     uint64_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     read = 8 - ff_log2_tab[total];
560     if (read > max_size) {
561         int64_t pos = url_ftell(pb) - 1;
562         av_log(matroska->ctx, AV_LOG_ERROR,
563                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
564                (uint8_t) total, pos, pos);
565         return AVERROR_INVALIDDATA;
566     }
567
568     /* read out length */
569     total ^= 1 << ff_log2_tab[total];
570     while (n++ < read)
571         total = (total << 8) | get_byte(pb);
572
573     *number = total;
574
575     return read;
576 }
577
578 /*
579  * Read the next element as an unsigned int.
580  * 0 is success, < 0 is failure.
581  */
582 static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
583 {
584     int n = 0;
585
586     if (size > 8)
587         return AVERROR_INVALIDDATA;
588
589     /* big-endian ordering; build up number */
590     *num = 0;
591     while (n++ < size)
592         *num = (*num << 8) | get_byte(pb);
593
594     return 0;
595 }
596
597 /*
598  * Read the next element as a float.
599  * 0 is success, < 0 is failure.
600  */
601 static int ebml_read_float(ByteIOContext *pb, int size, double *num)
602 {
603     if (size == 0) {
604         *num = 0;
605     } else 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     if (pkt_size >= 10000000)
904         return -1;
905
906     switch (encodings[0].compression.algo) {
907     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
908         return encodings[0].compression.settings.size;
909     case MATROSKA_TRACK_ENCODING_COMP_LZO:
910         do {
911             olen = pkt_size *= 3;
912             pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
913             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
914         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
915         if (result)
916             goto failed;
917         pkt_size -= olen;
918         break;
919 #if CONFIG_ZLIB
920     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
921         z_stream zstream = {0};
922         if (inflateInit(&zstream) != Z_OK)
923             return -1;
924         zstream.next_in = data;
925         zstream.avail_in = isize;
926         do {
927             pkt_size *= 3;
928             pkt_data = av_realloc(pkt_data, pkt_size);
929             zstream.avail_out = pkt_size - zstream.total_out;
930             zstream.next_out = pkt_data + zstream.total_out;
931             result = inflate(&zstream, Z_NO_FLUSH);
932         } while (result==Z_OK && pkt_size<10000000);
933         pkt_size = zstream.total_out;
934         inflateEnd(&zstream);
935         if (result != Z_STREAM_END)
936             goto failed;
937         break;
938     }
939 #endif
940 #if CONFIG_BZLIB
941     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
942         bz_stream bzstream = {0};
943         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
944             return -1;
945         bzstream.next_in = data;
946         bzstream.avail_in = isize;
947         do {
948             pkt_size *= 3;
949             pkt_data = av_realloc(pkt_data, pkt_size);
950             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
951             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
952             result = BZ2_bzDecompress(&bzstream);
953         } while (result==BZ_OK && pkt_size<10000000);
954         pkt_size = bzstream.total_out_lo32;
955         BZ2_bzDecompressEnd(&bzstream);
956         if (result != BZ_STREAM_END)
957             goto failed;
958         break;
959     }
960 #endif
961     default:
962         return -1;
963     }
964
965     *buf = pkt_data;
966     *buf_size = pkt_size;
967     return 0;
968  failed:
969     av_free(pkt_data);
970     return -1;
971 }
972
973 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
974                                     AVPacket *pkt, uint64_t display_duration)
975 {
976     char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
977     for (; *ptr!=',' && ptr<end-1; ptr++);
978     if (*ptr == ',')
979         layer = ++ptr;
980     for (; *ptr!=',' && ptr<end-1; ptr++);
981     if (*ptr == ',') {
982         int64_t end_pts = pkt->pts + display_duration;
983         int sc = matroska->time_scale * pkt->pts / 10000000;
984         int ec = matroska->time_scale * end_pts  / 10000000;
985         int sh, sm, ss, eh, em, es, len;
986         sh = sc/360000;  sc -= 360000*sh;
987         sm = sc/  6000;  sc -=   6000*sm;
988         ss = sc/   100;  sc -=    100*ss;
989         eh = ec/360000;  ec -= 360000*eh;
990         em = ec/  6000;  ec -=   6000*em;
991         es = ec/   100;  ec -=    100*es;
992         *ptr++ = '\0';
993         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
994         if (!(line = av_malloc(len)))
995             return;
996         snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
997                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
998         av_free(pkt->data);
999         pkt->data = line;
1000         pkt->size = strlen(line);
1001     }
1002 }
1003
1004 static void matroska_merge_packets(AVPacket *out, AVPacket *in)
1005 {
1006     out->data = av_realloc(out->data, out->size+in->size);
1007     memcpy(out->data+out->size, in->data, in->size);
1008     out->size += in->size;
1009     av_destruct_packet(in);
1010     av_free(in);
1011 }
1012
1013 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1014                                  AVMetadata **metadata, char *prefix)
1015 {
1016     MatroskaTag *tags = list->elem;
1017     char key[1024];
1018     int i;
1019
1020     for (i=0; i < list->nb_elem; i++) {
1021         const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1022         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1023         else         av_strlcpy(key, tags[i].name, sizeof(key));
1024         if (tags[i].def || !lang) {
1025         av_metadata_set2(metadata, key, tags[i].string, 0);
1026         if (tags[i].sub.nb_elem)
1027             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1028         }
1029         if (lang) {
1030             av_strlcat(key, "-", sizeof(key));
1031             av_strlcat(key, lang, sizeof(key));
1032             av_metadata_set2(metadata, key, tags[i].string, 0);
1033             if (tags[i].sub.nb_elem)
1034                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1035         }
1036     }
1037 }
1038
1039 static void matroska_convert_tags(AVFormatContext *s)
1040 {
1041     MatroskaDemuxContext *matroska = s->priv_data;
1042     MatroskaTags *tags = matroska->tags.elem;
1043     int i, j;
1044
1045     for (i=0; i < matroska->tags.nb_elem; i++) {
1046         if (tags[i].target.attachuid) {
1047             MatroskaAttachement *attachment = matroska->attachments.elem;
1048             for (j=0; j<matroska->attachments.nb_elem; j++)
1049                 if (attachment[j].uid == tags[i].target.attachuid)
1050                     matroska_convert_tag(s, &tags[i].tag,
1051                                          &attachment[j].stream->metadata, NULL);
1052         } else if (tags[i].target.chapteruid) {
1053             MatroskaChapter *chapter = matroska->chapters.elem;
1054             for (j=0; j<matroska->chapters.nb_elem; j++)
1055                 if (chapter[j].uid == tags[i].target.chapteruid)
1056                     matroska_convert_tag(s, &tags[i].tag,
1057                                          &chapter[j].chapter->metadata, NULL);
1058         } else if (tags[i].target.trackuid) {
1059             MatroskaTrack *track = matroska->tracks.elem;
1060             for (j=0; j<matroska->tracks.nb_elem; j++)
1061                 if (track[j].uid == tags[i].target.trackuid)
1062                     matroska_convert_tag(s, &tags[i].tag,
1063                                          &track[j].stream->metadata, NULL);
1064         } else {
1065             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1066                                  tags[i].target.type);
1067         }
1068     }
1069 }
1070
1071 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1072 {
1073     EbmlList *seekhead_list = &matroska->seekhead;
1074     MatroskaSeekhead *seekhead = seekhead_list->elem;
1075     uint32_t level_up = matroska->level_up;
1076     int64_t before_pos = url_ftell(matroska->ctx->pb);
1077     uint32_t saved_id = matroska->current_id;
1078     MatroskaLevel level;
1079     int i;
1080
1081     // we should not do any seeking in the streaming case
1082     if (url_is_streamed(matroska->ctx->pb) ||
1083         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1084         return;
1085
1086     for (i=0; i<seekhead_list->nb_elem; i++) {
1087         int64_t offset = seekhead[i].pos + matroska->segment_start;
1088
1089         if (seekhead[i].pos <= before_pos
1090             || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1091             || seekhead[i].id == MATROSKA_ID_CLUSTER)
1092             continue;
1093
1094         /* seek */
1095         if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1096             continue;
1097
1098         /* We don't want to lose our seekhead level, so we add
1099          * a dummy. This is a crude hack. */
1100         if (matroska->num_levels == EBML_MAX_DEPTH) {
1101             av_log(matroska->ctx, AV_LOG_INFO,
1102                    "Max EBML element depth (%d) reached, "
1103                    "cannot parse further.\n", EBML_MAX_DEPTH);
1104             break;
1105         }
1106
1107         level.start = 0;
1108         level.length = (uint64_t)-1;
1109         matroska->levels[matroska->num_levels] = level;
1110         matroska->num_levels++;
1111         matroska->current_id = 0;
1112
1113         ebml_parse(matroska, matroska_segment, matroska);
1114
1115         /* remove dummy level */
1116         while (matroska->num_levels) {
1117             uint64_t length = matroska->levels[--matroska->num_levels].length;
1118             if (length == (uint64_t)-1)
1119                 break;
1120         }
1121     }
1122
1123     /* seek back */
1124     url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1125     matroska->level_up = level_up;
1126     matroska->current_id = saved_id;
1127 }
1128
1129 static int matroska_aac_profile(char *codec_id)
1130 {
1131     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1132     int profile;
1133
1134     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1135         if (strstr(codec_id, aac_profiles[profile]))
1136             break;
1137     return profile + 1;
1138 }
1139
1140 static int matroska_aac_sri(int samplerate)
1141 {
1142     int sri;
1143
1144     for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1145         if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1146             break;
1147     return sri;
1148 }
1149
1150 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1151 {
1152     MatroskaDemuxContext *matroska = s->priv_data;
1153     EbmlList *attachements_list = &matroska->attachments;
1154     MatroskaAttachement *attachements;
1155     EbmlList *chapters_list = &matroska->chapters;
1156     MatroskaChapter *chapters;
1157     MatroskaTrack *tracks;
1158     EbmlList *index_list;
1159     MatroskaIndex *index;
1160     int index_scale = 1;
1161     uint64_t max_start = 0;
1162     Ebml ebml = { 0 };
1163     AVStream *st;
1164     int i, j, res;
1165
1166     matroska->ctx = s;
1167
1168     /* First read the EBML header. */
1169     if (ebml_parse(matroska, ebml_syntax, &ebml)
1170         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1171         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1172         av_log(matroska->ctx, AV_LOG_ERROR,
1173                "EBML header using unsupported features\n"
1174                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1175                ebml.version, ebml.doctype, ebml.doctype_version);
1176         ebml_free(ebml_syntax, &ebml);
1177         return AVERROR_PATCHWELCOME;
1178     }
1179     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1180         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1181             break;
1182     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1183         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1184     }
1185     ebml_free(ebml_syntax, &ebml);
1186
1187     /* The next thing is a segment. */
1188     if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1189         return res;
1190     matroska_execute_seekhead(matroska);
1191
1192     if (!matroska->time_scale)
1193         matroska->time_scale = 1000000;
1194     if (matroska->duration)
1195         matroska->ctx->duration = matroska->duration * matroska->time_scale
1196                                   * 1000 / AV_TIME_BASE;
1197     av_metadata_set2(&s->metadata, "title", matroska->title, 0);
1198
1199     tracks = matroska->tracks.elem;
1200     for (i=0; i < matroska->tracks.nb_elem; i++) {
1201         MatroskaTrack *track = &tracks[i];
1202         enum CodecID codec_id = CODEC_ID_NONE;
1203         EbmlList *encodings_list = &tracks->encodings;
1204         MatroskaTrackEncoding *encodings = encodings_list->elem;
1205         uint8_t *extradata = NULL;
1206         int extradata_size = 0;
1207         int extradata_offset = 0;
1208         ByteIOContext b;
1209
1210         /* Apply some sanity checks. */
1211         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1212             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1213             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1214             av_log(matroska->ctx, AV_LOG_INFO,
1215                    "Unknown or unsupported track type %"PRIu64"\n",
1216                    track->type);
1217             continue;
1218         }
1219         if (track->codec_id == NULL)
1220             continue;
1221
1222         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1223             if (!track->default_duration)
1224                 track->default_duration = 1000000000/track->video.frame_rate;
1225             if (!track->video.display_width)
1226                 track->video.display_width = track->video.pixel_width;
1227             if (!track->video.display_height)
1228                 track->video.display_height = track->video.pixel_height;
1229         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1230             if (!track->audio.out_samplerate)
1231                 track->audio.out_samplerate = track->audio.samplerate;
1232         }
1233         if (encodings_list->nb_elem > 1) {
1234             av_log(matroska->ctx, AV_LOG_ERROR,
1235                    "Multiple combined encodings no supported");
1236         } else if (encodings_list->nb_elem == 1) {
1237             if (encodings[0].type ||
1238                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1239 #if CONFIG_ZLIB
1240                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1241 #endif
1242 #if CONFIG_BZLIB
1243                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1244 #endif
1245                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1246                 encodings[0].scope = 0;
1247                 av_log(matroska->ctx, AV_LOG_ERROR,
1248                        "Unsupported encoding type");
1249             } else if (track->codec_priv.size && encodings[0].scope&2) {
1250                 uint8_t *codec_priv = track->codec_priv.data;
1251                 int offset = matroska_decode_buffer(&track->codec_priv.data,
1252                                                     &track->codec_priv.size,
1253                                                     track);
1254                 if (offset < 0) {
1255                     track->codec_priv.data = NULL;
1256                     track->codec_priv.size = 0;
1257                     av_log(matroska->ctx, AV_LOG_ERROR,
1258                            "Failed to decode codec private data\n");
1259                 } else if (offset > 0) {
1260                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1261                     memcpy(track->codec_priv.data,
1262                            encodings[0].compression.settings.data, offset);
1263                     memcpy(track->codec_priv.data+offset, codec_priv,
1264                            track->codec_priv.size);
1265                     track->codec_priv.size += offset;
1266                 }
1267                 if (codec_priv != track->codec_priv.data)
1268                     av_free(codec_priv);
1269             }
1270         }
1271
1272         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1273             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1274                         strlen(ff_mkv_codec_tags[j].str))){
1275                 codec_id= ff_mkv_codec_tags[j].id;
1276                 break;
1277             }
1278         }
1279
1280         st = track->stream = av_new_stream(s, 0);
1281         if (st == NULL)
1282             return AVERROR(ENOMEM);
1283
1284         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1285             && track->codec_priv.size >= 40
1286             && track->codec_priv.data != NULL) {
1287             track->ms_compat = 1;
1288             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1289             codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1290             extradata_offset = 40;
1291         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1292                    && track->codec_priv.size >= 14
1293                    && track->codec_priv.data != NULL) {
1294             init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
1295                           URL_RDONLY, NULL, NULL, NULL, NULL);
1296             ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1297             codec_id = st->codec->codec_id;
1298             extradata_offset = FFMIN(track->codec_priv.size, 18);
1299         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1300                    && (track->codec_priv.size >= 86)
1301                    && (track->codec_priv.data != NULL)) {
1302             track->video.fourcc = AV_RL32(track->codec_priv.data);
1303             codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
1304         } else if (codec_id == CODEC_ID_PCM_S16BE) {
1305             switch (track->audio.bitdepth) {
1306             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1307             case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1308             case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1309             }
1310         } else if (codec_id == CODEC_ID_PCM_S16LE) {
1311             switch (track->audio.bitdepth) {
1312             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1313             case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1314             case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1315             }
1316         } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1317             codec_id = CODEC_ID_PCM_F64LE;
1318         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1319             int profile = matroska_aac_profile(track->codec_id);
1320             int sri = matroska_aac_sri(track->audio.samplerate);
1321             extradata = av_malloc(5);
1322             if (extradata == NULL)
1323                 return AVERROR(ENOMEM);
1324             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1325             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1326             if (strstr(track->codec_id, "SBR")) {
1327                 sri = matroska_aac_sri(track->audio.out_samplerate);
1328                 extradata[2] = 0x56;
1329                 extradata[3] = 0xE5;
1330                 extradata[4] = 0x80 | (sri<<3);
1331                 extradata_size = 5;
1332             } else
1333                 extradata_size = 2;
1334         } else if (codec_id == CODEC_ID_TTA) {
1335             extradata_size = 30;
1336             extradata = av_mallocz(extradata_size);
1337             if (extradata == NULL)
1338                 return AVERROR(ENOMEM);
1339             init_put_byte(&b, extradata, extradata_size, 1,
1340                           NULL, NULL, NULL, NULL);
1341             put_buffer(&b, "TTA1", 4);
1342             put_le16(&b, 1);
1343             put_le16(&b, track->audio.channels);
1344             put_le16(&b, track->audio.bitdepth);
1345             put_le32(&b, track->audio.out_samplerate);
1346             put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1347         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1348                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1349             extradata_offset = 26;
1350         } else if (codec_id == CODEC_ID_RA_144) {
1351             track->audio.out_samplerate = 8000;
1352             track->audio.channels = 1;
1353         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1354                    codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1355             int flavor;
1356             init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1357                           0, NULL, NULL, NULL, NULL);
1358             url_fskip(&b, 22);
1359             flavor                       = get_be16(&b);
1360             track->audio.coded_framesize = get_be32(&b);
1361             url_fskip(&b, 12);
1362             track->audio.sub_packet_h    = get_be16(&b);
1363             track->audio.frame_size      = get_be16(&b);
1364             track->audio.sub_packet_size = get_be16(&b);
1365             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1366             if (codec_id == CODEC_ID_RA_288) {
1367                 st->codec->block_align = track->audio.coded_framesize;
1368                 track->codec_priv.size = 0;
1369             } else {
1370                 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1371                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1372                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1373                     st->codec->bit_rate = sipr_bit_rate[flavor];
1374                 }
1375                 st->codec->block_align = track->audio.sub_packet_size;
1376                 extradata_offset = 78;
1377             }
1378         }
1379         track->codec_priv.size -= extradata_offset;
1380
1381         if (codec_id == CODEC_ID_NONE)
1382             av_log(matroska->ctx, AV_LOG_INFO,
1383                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
1384
1385         if (track->time_scale < 0.01)
1386             track->time_scale = 1.0;
1387         av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1388
1389         st->codec->codec_id = codec_id;
1390         st->start_time = 0;
1391         if (strcmp(track->language, "und"))
1392             av_metadata_set2(&st->metadata, "language", track->language, 0);
1393         av_metadata_set2(&st->metadata, "title", track->name, 0);
1394
1395         if (track->flag_default)
1396             st->disposition |= AV_DISPOSITION_DEFAULT;
1397         if (track->flag_forced)
1398             st->disposition |= AV_DISPOSITION_FORCED;
1399
1400         if (track->default_duration)
1401             av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1402                       track->default_duration, 1000000000, 30000);
1403
1404         if (!st->codec->extradata) {
1405             if(extradata){
1406                 st->codec->extradata = extradata;
1407                 st->codec->extradata_size = extradata_size;
1408             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1409                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1410                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1411                 if(st->codec->extradata == NULL)
1412                     return AVERROR(ENOMEM);
1413                 st->codec->extradata_size = track->codec_priv.size;
1414                 memcpy(st->codec->extradata,
1415                        track->codec_priv.data + extradata_offset,
1416                        track->codec_priv.size);
1417             }
1418         }
1419
1420         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1421             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1422             st->codec->codec_tag  = track->video.fourcc;
1423             st->codec->width  = track->video.pixel_width;
1424             st->codec->height = track->video.pixel_height;
1425             av_reduce(&st->sample_aspect_ratio.num,
1426                       &st->sample_aspect_ratio.den,
1427                       st->codec->height * track->video.display_width,
1428                       st->codec-> width * track->video.display_height,
1429                       255);
1430             if (st->codec->codec_id != CODEC_ID_H264)
1431             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1432             if (track->default_duration)
1433                 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1434         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1435             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1436             st->codec->sample_rate = track->audio.out_samplerate;
1437             st->codec->channels = track->audio.channels;
1438             if (st->codec->codec_id != CODEC_ID_AAC)
1439             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1440         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1441             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1442         }
1443     }
1444
1445     attachements = attachements_list->elem;
1446     for (j=0; j<attachements_list->nb_elem; j++) {
1447         if (!(attachements[j].filename && attachements[j].mime &&
1448               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1449             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1450         } else {
1451             AVStream *st = av_new_stream(s, 0);
1452             if (st == NULL)
1453                 break;
1454             av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
1455             st->codec->codec_id = CODEC_ID_NONE;
1456             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1457             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1458             if(st->codec->extradata == NULL)
1459                 break;
1460             st->codec->extradata_size = attachements[j].bin.size;
1461             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1462
1463             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1464                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1465                              strlen(ff_mkv_mime_tags[i].str))) {
1466                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1467                     break;
1468                 }
1469             }
1470             attachements[j].stream = st;
1471         }
1472     }
1473
1474     chapters = chapters_list->elem;
1475     for (i=0; i<chapters_list->nb_elem; i++)
1476         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1477             && (max_start==0 || chapters[i].start > max_start)) {
1478             chapters[i].chapter =
1479             ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1480                            chapters[i].start, chapters[i].end,
1481                            chapters[i].title);
1482             av_metadata_set2(&chapters[i].chapter->metadata,
1483                              "title", chapters[i].title, 0);
1484             max_start = chapters[i].start;
1485         }
1486
1487     index_list = &matroska->index;
1488     index = index_list->elem;
1489     if (index_list->nb_elem
1490         && index[0].time > 100000000000000/matroska->time_scale) {
1491         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1492         index_scale = matroska->time_scale;
1493     }
1494     for (i=0; i<index_list->nb_elem; i++) {
1495         EbmlList *pos_list = &index[i].pos;
1496         MatroskaIndexPos *pos = pos_list->elem;
1497         for (j=0; j<pos_list->nb_elem; j++) {
1498             MatroskaTrack *track = matroska_find_track_by_num(matroska,
1499                                                               pos[j].track);
1500             if (track && track->stream)
1501                 av_add_index_entry(track->stream,
1502                                    pos[j].pos + matroska->segment_start,
1503                                    index[i].time/index_scale, 0, 0,
1504                                    AVINDEX_KEYFRAME);
1505         }
1506     }
1507
1508     matroska_convert_tags(s);
1509
1510     return 0;
1511 }
1512
1513 /*
1514  * Put one packet in an application-supplied AVPacket struct.
1515  * Returns 0 on success or -1 on failure.
1516  */
1517 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1518                                    AVPacket *pkt)
1519 {
1520     if (matroska->num_packets > 0) {
1521         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1522         av_free(matroska->packets[0]);
1523         if (matroska->num_packets > 1) {
1524             memmove(&matroska->packets[0], &matroska->packets[1],
1525                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1526             matroska->packets =
1527                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1528                            sizeof(AVPacket *));
1529         } else {
1530             av_freep(&matroska->packets);
1531         }
1532         matroska->num_packets--;
1533         return 0;
1534     }
1535
1536     return -1;
1537 }
1538
1539 /*
1540  * Free all packets in our internal queue.
1541  */
1542 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1543 {
1544     if (matroska->packets) {
1545         int n;
1546         for (n = 0; n < matroska->num_packets; n++) {
1547             av_free_packet(matroska->packets[n]);
1548             av_free(matroska->packets[n]);
1549         }
1550         av_freep(&matroska->packets);
1551         matroska->num_packets = 0;
1552     }
1553 }
1554
1555 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1556                                 int size, int64_t pos, uint64_t cluster_time,
1557                                 uint64_t duration, int is_keyframe,
1558                                 int64_t cluster_pos)
1559 {
1560     uint64_t timecode = AV_NOPTS_VALUE;
1561     MatroskaTrack *track;
1562     int res = 0;
1563     AVStream *st;
1564     AVPacket *pkt;
1565     int16_t block_time;
1566     uint32_t *lace_size = NULL;
1567     int n, flags, laces = 0;
1568     uint64_t num;
1569
1570     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1571         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1572         return res;
1573     }
1574     data += n;
1575     size -= n;
1576
1577     track = matroska_find_track_by_num(matroska, num);
1578     if (size <= 3 || !track || !track->stream) {
1579         av_log(matroska->ctx, AV_LOG_INFO,
1580                "Invalid stream %"PRIu64" or size %u\n", num, size);
1581         return res;
1582     }
1583     st = track->stream;
1584     if (st->discard >= AVDISCARD_ALL)
1585         return res;
1586     if (duration == AV_NOPTS_VALUE)
1587         duration = track->default_duration / matroska->time_scale;
1588
1589     block_time = AV_RB16(data);
1590     data += 2;
1591     flags = *data++;
1592     size -= 3;
1593     if (is_keyframe == -1)
1594         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1595
1596     if (cluster_time != (uint64_t)-1
1597         && (block_time >= 0 || cluster_time >= -block_time)) {
1598         timecode = cluster_time + block_time;
1599         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1600             && timecode < track->end_timecode)
1601             is_keyframe = 0;  /* overlapping subtitles are not key frame */
1602         if (is_keyframe)
1603             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1604         track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1605     }
1606
1607     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1608         if (!is_keyframe || timecode < matroska->skip_to_timecode)
1609             return res;
1610         matroska->skip_to_keyframe = 0;
1611     }
1612
1613     switch ((flags & 0x06) >> 1) {
1614         case 0x0: /* no lacing */
1615             laces = 1;
1616             lace_size = av_mallocz(sizeof(int));
1617             lace_size[0] = size;
1618             break;
1619
1620         case 0x1: /* Xiph lacing */
1621         case 0x2: /* fixed-size lacing */
1622         case 0x3: /* EBML lacing */
1623             assert(size>0); // size <=3 is checked before size-=3 above
1624             laces = (*data) + 1;
1625             data += 1;
1626             size -= 1;
1627             lace_size = av_mallocz(laces * sizeof(int));
1628
1629             switch ((flags & 0x06) >> 1) {
1630                 case 0x1: /* Xiph lacing */ {
1631                     uint8_t temp;
1632                     uint32_t total = 0;
1633                     for (n = 0; res == 0 && n < laces - 1; n++) {
1634                         while (1) {
1635                             if (size == 0) {
1636                                 res = -1;
1637                                 break;
1638                             }
1639                             temp = *data;
1640                             lace_size[n] += temp;
1641                             data += 1;
1642                             size -= 1;
1643                             if (temp != 0xff)
1644                                 break;
1645                         }
1646                         total += lace_size[n];
1647                     }
1648                     lace_size[n] = size - total;
1649                     break;
1650                 }
1651
1652                 case 0x2: /* fixed-size lacing */
1653                     for (n = 0; n < laces; n++)
1654                         lace_size[n] = size / laces;
1655                     break;
1656
1657                 case 0x3: /* EBML lacing */ {
1658                     uint32_t total;
1659                     n = matroska_ebmlnum_uint(matroska, data, size, &num);
1660                     if (n < 0) {
1661                         av_log(matroska->ctx, AV_LOG_INFO,
1662                                "EBML block data error\n");
1663                         break;
1664                     }
1665                     data += n;
1666                     size -= n;
1667                     total = lace_size[0] = num;
1668                     for (n = 1; res == 0 && n < laces - 1; n++) {
1669                         int64_t snum;
1670                         int r;
1671                         r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1672                         if (r < 0) {
1673                             av_log(matroska->ctx, AV_LOG_INFO,
1674                                    "EBML block data error\n");
1675                             break;
1676                         }
1677                         data += r;
1678                         size -= r;
1679                         lace_size[n] = lace_size[n - 1] + snum;
1680                         total += lace_size[n];
1681                     }
1682                     lace_size[n] = size - total;
1683                     break;
1684                 }
1685             }
1686             break;
1687     }
1688
1689     if (res == 0) {
1690         for (n = 0; n < laces; n++) {
1691             if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1692                  st->codec->codec_id == CODEC_ID_COOK ||
1693                  st->codec->codec_id == CODEC_ID_SIPR ||
1694                  st->codec->codec_id == CODEC_ID_ATRAC3) &&
1695                  st->codec->block_align && track->audio.sub_packet_size) {
1696                 int a = st->codec->block_align;
1697                 int sps = track->audio.sub_packet_size;
1698                 int cfs = track->audio.coded_framesize;
1699                 int h = track->audio.sub_packet_h;
1700                 int y = track->audio.sub_packet_cnt;
1701                 int w = track->audio.frame_size;
1702                 int x;
1703
1704                 if (!track->audio.pkt_cnt) {
1705                     if (st->codec->codec_id == CODEC_ID_RA_288)
1706                         for (x=0; x<h/2; x++)
1707                             memcpy(track->audio.buf+x*2*w+y*cfs,
1708                                    data+x*cfs, cfs);
1709                     else if (st->codec->codec_id == CODEC_ID_SIPR)
1710                         memcpy(track->audio.buf + y*w, data, w);
1711                     else
1712                         for (x=0; x<w/sps; x++)
1713                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1714
1715                     if (++track->audio.sub_packet_cnt >= h) {
1716                         if (st->codec->codec_id == CODEC_ID_SIPR)
1717                             ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1718                         track->audio.sub_packet_cnt = 0;
1719                         track->audio.pkt_cnt = h*w / a;
1720                     }
1721                 }
1722                 while (track->audio.pkt_cnt) {
1723                     pkt = av_mallocz(sizeof(AVPacket));
1724                     av_new_packet(pkt, a);
1725                     memcpy(pkt->data, track->audio.buf
1726                            + a * (h*w / a - track->audio.pkt_cnt--), a);
1727                     pkt->pos = pos;
1728                     pkt->stream_index = st->index;
1729                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1730                 }
1731             } else {
1732                 MatroskaTrackEncoding *encodings = track->encodings.elem;
1733                 int offset = 0, pkt_size = lace_size[n];
1734                 uint8_t *pkt_data = data;
1735
1736                 if (pkt_size > size) {
1737                     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1738                     break;
1739                 }
1740
1741                 if (encodings && encodings->scope & 1) {
1742                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1743                     if (offset < 0)
1744                         continue;
1745                 }
1746
1747                 pkt = av_mallocz(sizeof(AVPacket));
1748                 /* XXX: prevent data copy... */
1749                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1750                     av_free(pkt);
1751                     res = AVERROR(ENOMEM);
1752                     break;
1753                 }
1754                 if (offset)
1755                     memcpy (pkt->data, encodings->compression.settings.data, offset);
1756                 memcpy (pkt->data+offset, pkt_data, pkt_size);
1757
1758                 if (pkt_data != data)
1759                     av_free(pkt_data);
1760
1761                 if (n == 0)
1762                     pkt->flags = is_keyframe;
1763                 pkt->stream_index = st->index;
1764
1765                 if (track->ms_compat)
1766                     pkt->dts = timecode;
1767                 else
1768                     pkt->pts = timecode;
1769                 pkt->pos = pos;
1770                 if (st->codec->codec_id == CODEC_ID_TEXT)
1771                     pkt->convergence_duration = duration;
1772                 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1773                     pkt->duration = duration;
1774
1775                 if (st->codec->codec_id == CODEC_ID_SSA)
1776                     matroska_fix_ass_packet(matroska, pkt, duration);
1777
1778                 if (matroska->prev_pkt &&
1779                     timecode != AV_NOPTS_VALUE &&
1780                     matroska->prev_pkt->pts == timecode &&
1781                     matroska->prev_pkt->stream_index == st->index &&
1782                     st->codec->codec_id == CODEC_ID_SSA)
1783                     matroska_merge_packets(matroska->prev_pkt, pkt);
1784                 else {
1785                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1786                     matroska->prev_pkt = pkt;
1787                 }
1788             }
1789
1790             if (timecode != AV_NOPTS_VALUE)
1791                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1792             data += lace_size[n];
1793             size -= lace_size[n];
1794         }
1795     }
1796
1797     av_free(lace_size);
1798     return res;
1799 }
1800
1801 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1802 {
1803     MatroskaCluster cluster = { 0 };
1804     EbmlList *blocks_list;
1805     MatroskaBlock *blocks;
1806     int i, res;
1807     int64_t pos = url_ftell(matroska->ctx->pb);
1808     matroska->prev_pkt = NULL;
1809     if (matroska->current_id)
1810         pos -= 4;  /* sizeof the ID which was already read */
1811     res = ebml_parse(matroska, matroska_clusters, &cluster);
1812     blocks_list = &cluster.blocks;
1813     blocks = blocks_list->elem;
1814     for (i=0; i<blocks_list->nb_elem; i++)
1815         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1816             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1817             res=matroska_parse_block(matroska,
1818                                      blocks[i].bin.data, blocks[i].bin.size,
1819                                      blocks[i].bin.pos,  cluster.timecode,
1820                                      blocks[i].duration, is_keyframe,
1821                                      pos);
1822         }
1823     ebml_free(matroska_cluster, &cluster);
1824     if (res < 0)  matroska->done = 1;
1825     return res;
1826 }
1827
1828 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1829 {
1830     MatroskaDemuxContext *matroska = s->priv_data;
1831
1832     while (matroska_deliver_packet(matroska, pkt)) {
1833         if (matroska->done)
1834             return AVERROR_EOF;
1835         matroska_parse_cluster(matroska);
1836     }
1837
1838     return 0;
1839 }
1840
1841 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1842                               int64_t timestamp, int flags)
1843 {
1844     MatroskaDemuxContext *matroska = s->priv_data;
1845     MatroskaTrack *tracks = matroska->tracks.elem;
1846     AVStream *st = s->streams[stream_index];
1847     int i, index, index_sub, index_min;
1848
1849     if (!st->nb_index_entries)
1850         return 0;
1851     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1852
1853     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1854         url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1855         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1856             matroska_clear_queue(matroska);
1857             if (matroska_parse_cluster(matroska) < 0)
1858                 break;
1859         }
1860     }
1861
1862     matroska_clear_queue(matroska);
1863     if (index < 0)
1864         return 0;
1865
1866     index_min = index;
1867     for (i=0; i < matroska->tracks.nb_elem; i++) {
1868         tracks[i].end_timecode = 0;
1869         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1870             && !tracks[i].stream->discard != AVDISCARD_ALL) {
1871             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1872             if (index_sub >= 0
1873                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1874                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1875                 index_min = index_sub;
1876         }
1877     }
1878
1879     url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1880     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1881     matroska->skip_to_timecode = st->index_entries[index].timestamp;
1882     matroska->done = 0;
1883     av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1884     return 0;
1885 }
1886
1887 static int matroska_read_close(AVFormatContext *s)
1888 {
1889     MatroskaDemuxContext *matroska = s->priv_data;
1890     MatroskaTrack *tracks = matroska->tracks.elem;
1891     int n;
1892
1893     matroska_clear_queue(matroska);
1894
1895     for (n=0; n < matroska->tracks.nb_elem; n++)
1896         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1897             av_free(tracks[n].audio.buf);
1898     ebml_free(matroska_segment, matroska);
1899
1900     return 0;
1901 }
1902
1903 AVInputFormat matroska_demuxer = {
1904     "matroska,webm",
1905     NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
1906     sizeof(MatroskaDemuxContext),
1907     matroska_probe,
1908     matroska_read_header,
1909     matroska_read_packet,
1910     matroska_read_close,
1911     matroska_read_seek,
1912     .metadata_conv = ff_mkv_metadata_conv,
1913 };