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