]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
224001396996674f50d210981fc12195a84dc051
[ffmpeg] / 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 Track {
92     MatroskaTrackType type;
93
94     /* Unique track number and track ID. stream_index is the index that
95      * the calling app uses for this track. */
96     uint32_t num;
97     uint32_t uid;
98
99     char *name;
100     char language[4];
101
102     char *codec_id;
103
104     unsigned char *codec_priv;
105     int codec_priv_size;
106
107     double time_scale;
108     uint64_t default_duration;
109     uint64_t flag_default;
110
111     int encoding_scope;
112     MatroskaTrackEncodingCompAlgo encoding_algo;
113     uint8_t *encoding_settings;
114     int encoding_settings_len;
115
116     AVStream *stream;
117 } MatroskaTrack;
118
119 typedef struct MatroskaVideoTrack {
120     MatroskaTrack track;
121
122     int pixel_width;
123     int pixel_height;
124     int display_width;
125     int display_height;
126
127     uint32_t fourcc;
128
129     //..
130 } MatroskaVideoTrack;
131
132 typedef struct MatroskaAudioTrack {
133     MatroskaTrack track;
134
135     int channels;
136     int bitdepth;
137     int internal_samplerate;
138     int samplerate;
139     int block_align;
140
141     /* real audio header */
142     int coded_framesize;
143     int sub_packet_h;
144     int frame_size;
145     int sub_packet_size;
146     int sub_packet_cnt;
147     int pkt_cnt;
148     uint8_t *buf;
149     //..
150 } MatroskaAudioTrack;
151
152 typedef struct MatroskaSubtitleTrack {
153     MatroskaTrack track;
154     //..
155 } MatroskaSubtitleTrack;
156
157 #define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
158                                     sizeof(MatroskaAudioTrack), \
159                                     sizeof(MatroskaSubtitleTrack)))
160
161 typedef struct {
162     char *filename;
163     char *mime;
164     EbmlBin bin;
165 } MatroskaAttachement;
166
167 typedef struct {
168     uint64_t start;
169     uint64_t end;
170     uint64_t uid;
171     char    *title;
172 } MatroskaChapter;
173
174 typedef struct {
175     uint64_t track;
176     uint64_t pos;
177 } MatroskaIndexPos;
178
179 typedef struct {
180     uint64_t time;
181     EbmlList pos;
182 } MatroskaIndex;
183
184 typedef struct MatroskaLevel {
185     uint64_t start;
186     uint64_t length;
187 } MatroskaLevel;
188
189 typedef struct MatroskaDemuxContext {
190     AVFormatContext *ctx;
191
192     /* ebml stuff */
193     int num_levels;
194     MatroskaLevel levels[EBML_MAX_DEPTH];
195     int level_up;
196
197     /* timescale in the file */
198     uint64_t time_scale;
199     double   duration;
200     char    *title;
201     EbmlList attachments;
202     EbmlList chapters;
203     EbmlList index;
204
205     /* num_streams is the number of streams that av_new_stream() was called
206      * for ( = that are available to the calling program). */
207     int num_tracks;
208     int num_streams;
209     MatroskaTrack *tracks[MAX_STREAMS];
210
211     /* cache for ID peeking */
212     uint32_t peek_id;
213
214     /* byte position of the segment inside the stream */
215     offset_t segment_start;
216
217     /* The packet queue. */
218     AVPacket **packets;
219     int num_packets;
220
221     /* have we already parse metadata/cues/clusters? */
222     int metadata_parsed;
223     int index_parsed;
224     int done;
225
226     /* What to skip before effectively reading a packet. */
227     int skip_to_keyframe;
228     AVStream *skip_to_stream;
229 } MatroskaDemuxContext;
230
231 #define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
232
233 static EbmlSyntax ebml_header[] = {
234     { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
235     { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
236     { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
237     { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
238     { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
239     { EBML_ID_EBMLVERSION,            EBML_NONE },
240     { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
241     { EBML_ID_VOID,                   EBML_NONE },
242     { 0 }
243 };
244
245 static EbmlSyntax ebml_syntax[] = {
246     { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
247     { 0 }
248 };
249
250 static EbmlSyntax matroska_info[] = {
251     { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
252     { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
253     { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
254     { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
255     { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
256     { MATROSKA_ID_DATEUTC,            EBML_NONE },
257     { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
258     { EBML_ID_VOID,                   EBML_NONE },
259     { 0 }
260 };
261
262 static EbmlSyntax matroska_attachment[] = {
263     { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
264     { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
265     { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
266     { MATROSKA_ID_FILEUID,            EBML_NONE },
267     { EBML_ID_VOID,                   EBML_NONE },
268     { 0 }
269 };
270
271 static EbmlSyntax matroska_attachments[] = {
272     { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
273     { EBML_ID_VOID,                   EBML_NONE },
274     { 0 }
275 };
276
277 static EbmlSyntax matroska_chapter_display[] = {
278     { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
279     { EBML_ID_VOID,                   EBML_NONE },
280     { 0 }
281 };
282
283 static EbmlSyntax matroska_chapter_entry[] = {
284     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
285     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
286     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
287     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
288     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
289     { EBML_ID_VOID,                   EBML_NONE },
290     { 0 }
291 };
292
293 static EbmlSyntax matroska_chapter[] = {
294     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
295     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
296     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
297     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
298     { EBML_ID_VOID,                   EBML_NONE },
299     { 0 }
300 };
301
302 static EbmlSyntax matroska_chapters[] = {
303     { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
304     { EBML_ID_VOID,                   EBML_NONE },
305     { 0 }
306 };
307
308 static EbmlSyntax matroska_index_pos[] = {
309     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
310     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
311     { EBML_ID_VOID,                   EBML_NONE },
312     { 0 }
313 };
314
315 static EbmlSyntax matroska_index_entry[] = {
316     { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
317     { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
318     { EBML_ID_VOID,                   EBML_NONE },
319     { 0 }
320 };
321
322 static EbmlSyntax matroska_index[] = {
323     { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
324     { EBML_ID_VOID,                   EBML_NONE },
325     { 0 }
326 };
327
328 static EbmlSyntax matroska_tags[] = {
329     { EBML_ID_VOID,                   EBML_NONE },
330     { 0 }
331 };
332
333 /*
334  * The first few functions handle EBML file parsing. The rest
335  * is the document interpretation. Matroska really just is a
336  * EBML file.
337  */
338
339 /*
340  * Return: the amount of levels in the hierarchy that the
341  * current element lies higher than the previous one.
342  * The opposite isn't done - that's auto-done using master
343  * element reading.
344  */
345
346 static int
347 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
348 {
349     ByteIOContext *pb = matroska->ctx->pb;
350     offset_t pos = url_ftell(pb);
351     int num = 0;
352
353     while (matroska->num_levels > 0) {
354         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
355
356         if (pos >= level->start + level->length) {
357             matroska->num_levels--;
358             num++;
359         } else {
360             break;
361         }
362     }
363
364     return num;
365 }
366
367 /*
368  * Read: an "EBML number", which is defined as a variable-length
369  * array of bytes. The first byte indicates the length by giving a
370  * number of 0-bits followed by a one. The position of the first
371  * "one" bit inside the first byte indicates the length of this
372  * number.
373  * Returns: num. of bytes read. < 0 on error.
374  */
375
376 static int
377 ebml_read_num (MatroskaDemuxContext *matroska,
378                int                   max_size,
379                uint64_t             *number)
380 {
381     ByteIOContext *pb = matroska->ctx->pb;
382     int len_mask = 0x80, read = 1, n = 1;
383     int64_t total = 0;
384
385     /* the first byte tells us the length in bytes - get_byte() can normally
386      * return 0, but since that's not a valid first ebmlID byte, we can
387      * use it safely here to catch EOS. */
388     if (!(total = get_byte(pb))) {
389         /* we might encounter EOS here */
390         if (!url_feof(pb)) {
391             offset_t pos = url_ftell(pb);
392             av_log(matroska->ctx, AV_LOG_ERROR,
393                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
394                    pos, pos);
395         }
396         return AVERROR(EIO); /* EOS or actual I/O error */
397     }
398
399     /* get the length of the EBML number */
400     while (read <= max_size && !(total & len_mask)) {
401         read++;
402         len_mask >>= 1;
403     }
404     if (read > max_size) {
405         offset_t pos = url_ftell(pb) - 1;
406         av_log(matroska->ctx, AV_LOG_ERROR,
407                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
408                (uint8_t) total, pos, pos);
409         return AVERROR_INVALIDDATA;
410     }
411
412     /* read out length */
413     total &= ~len_mask;
414     while (n++ < read)
415         total = (total << 8) | get_byte(pb);
416
417     *number = total;
418
419     return read;
420 }
421
422 /*
423  * Read: the element content data ID.
424  * Return: the number of bytes read or < 0 on error.
425  */
426
427 static int
428 ebml_read_element_id (MatroskaDemuxContext *matroska,
429                       uint32_t             *id,
430                       int                  *level_up)
431 {
432     int read;
433     uint64_t total;
434
435     /* if we re-call this, use our cached ID */
436     if (matroska->peek_id != 0) {
437         if (level_up)
438             *level_up = 0;
439         *id = matroska->peek_id;
440         return 0;
441     }
442
443     /* read out the "EBML number", include tag in ID */
444     if ((read = ebml_read_num(matroska, 4, &total)) < 0)
445         return read;
446     *id = matroska->peek_id  = total | (1 << (read * 7));
447
448     /* level tracking */
449     if (level_up)
450         *level_up = ebml_read_element_level_up(matroska);
451
452     return read;
453 }
454
455 /*
456  * Read: element content length.
457  * Return: the number of bytes read or < 0 on error.
458  */
459
460 static int
461 ebml_read_element_length (MatroskaDemuxContext *matroska,
462                           uint64_t             *length)
463 {
464     /* clear cache since we're now beyond that data point */
465     matroska->peek_id = 0;
466
467     /* read out the "EBML number", include tag in ID */
468     return ebml_read_num(matroska, 8, length);
469 }
470
471 /*
472  * Return: the ID of the next element, or 0 on error.
473  * Level_up contains the amount of levels that this
474  * next element lies higher than the previous one.
475  */
476
477 static uint32_t
478 ebml_peek_id (MatroskaDemuxContext *matroska,
479               int                  *level_up)
480 {
481     uint32_t id;
482
483     if (ebml_read_element_id(matroska, &id, level_up) < 0)
484         return 0;
485
486     return id;
487 }
488
489 /*
490  * Seek to a given offset.
491  * 0 is success, -1 is failure.
492  */
493
494 static int
495 ebml_read_seek (MatroskaDemuxContext *matroska,
496                 offset_t              offset)
497 {
498     ByteIOContext *pb = matroska->ctx->pb;
499
500     /* clear ID cache, if any */
501     matroska->peek_id = 0;
502
503     return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
504 }
505
506 /*
507  * Skip the next element.
508  * 0 is success, -1 is failure.
509  */
510
511 static int
512 ebml_read_skip (MatroskaDemuxContext *matroska)
513 {
514     ByteIOContext *pb = matroska->ctx->pb;
515     uint32_t id;
516     uint64_t length;
517     int res;
518
519     if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
520         (res = ebml_read_element_length(matroska, &length)) < 0)
521         return res;
522
523     url_fskip(pb, length);
524
525     return 0;
526 }
527
528 /*
529  * Read the next element as an unsigned int.
530  * 0 is success, < 0 is failure.
531  */
532
533 static int
534 ebml_read_uint (MatroskaDemuxContext *matroska,
535                 uint32_t             *id,
536                 uint64_t             *num)
537 {
538     ByteIOContext *pb = matroska->ctx->pb;
539     int n = 0, size, res;
540     uint64_t rlength;
541
542     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
543         (res = ebml_read_element_length(matroska, &rlength)) < 0)
544         return res;
545     size = rlength;
546     if (size < 1 || size > 8) {
547         offset_t pos = url_ftell(pb);
548         av_log(matroska->ctx, AV_LOG_ERROR,
549                "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
550                 size, pos, pos);
551         return AVERROR_INVALIDDATA;
552     }
553
554     /* big-endian ordening; build up number */
555     *num = 0;
556     while (n++ < size)
557         *num = (*num << 8) | get_byte(pb);
558
559     return 0;
560 }
561
562 /*
563  * Read the next element as a signed int.
564  * 0 is success, < 0 is failure.
565  */
566
567 static int
568 ebml_read_sint (MatroskaDemuxContext *matroska,
569                 uint32_t             *id,
570                 int64_t              *num)
571 {
572     ByteIOContext *pb = matroska->ctx->pb;
573     int size, n = 1, negative = 0, res;
574     uint64_t rlength;
575
576     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
577         (res = ebml_read_element_length(matroska, &rlength)) < 0)
578         return res;
579     size = rlength;
580     if (size < 1 || size > 8) {
581         offset_t pos = url_ftell(pb);
582         av_log(matroska->ctx, AV_LOG_ERROR,
583                "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
584                 size, pos, pos);
585         return AVERROR_INVALIDDATA;
586     }
587     if ((*num = get_byte(pb)) & 0x80) {
588         negative = 1;
589         *num &= ~0x80;
590     }
591     while (n++ < size)
592         *num = (*num << 8) | get_byte(pb);
593
594     /* make signed */
595     if (negative)
596         *num = *num - (1LL << ((8 * size) - 1));
597
598     return 0;
599 }
600
601 /*
602  * Read the next element as a float.
603  * 0 is success, < 0 is failure.
604  */
605
606 static int
607 ebml_read_float (MatroskaDemuxContext *matroska,
608                  uint32_t             *id,
609                  double               *num)
610 {
611     ByteIOContext *pb = matroska->ctx->pb;
612     int size, res;
613     uint64_t rlength;
614
615     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
616         (res = ebml_read_element_length(matroska, &rlength)) < 0)
617         return res;
618     size = rlength;
619
620     if (size == 4) {
621         *num= av_int2flt(get_be32(pb));
622     } else if(size==8){
623         *num= av_int2dbl(get_be64(pb));
624     } else{
625         offset_t pos = url_ftell(pb);
626         av_log(matroska->ctx, AV_LOG_ERROR,
627                "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
628                size, pos, pos);
629         return AVERROR_INVALIDDATA;
630     }
631
632     return 0;
633 }
634
635 /*
636  * Read the next element as an ASCII string.
637  * 0 is success, < 0 is failure.
638  */
639
640 static int
641 ebml_read_ascii (MatroskaDemuxContext *matroska,
642                  uint32_t             *id,
643                  char                **str)
644 {
645     ByteIOContext *pb = matroska->ctx->pb;
646     int size, res;
647     uint64_t rlength;
648
649     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
650         (res = ebml_read_element_length(matroska, &rlength)) < 0)
651         return res;
652     size = rlength;
653
654     /* ebml strings are usually not 0-terminated, so we allocate one
655      * byte more, read the string and NULL-terminate it ourselves. */
656     if (size < 0 || !(*str = av_malloc(size + 1))) {
657         av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
658         return AVERROR(ENOMEM);
659     }
660     if (get_buffer(pb, (uint8_t *) *str, size) != size) {
661         offset_t pos = url_ftell(pb);
662         av_log(matroska->ctx, AV_LOG_ERROR,
663                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
664         av_free(*str);
665         return AVERROR(EIO);
666     }
667     (*str)[size] = '\0';
668
669     return 0;
670 }
671
672 /*
673  * Read the next element as a UTF-8 string.
674  * 0 is success, < 0 is failure.
675  */
676
677 static int
678 ebml_read_utf8 (MatroskaDemuxContext *matroska,
679                 uint32_t             *id,
680                 char                **str)
681 {
682   return ebml_read_ascii(matroska, id, str);
683 }
684
685 /*
686  * Read the next element, but only the header. The contents
687  * are supposed to be sub-elements which can be read separately.
688  * 0 is success, < 0 is failure.
689  */
690
691 static int
692 ebml_read_master (MatroskaDemuxContext *matroska,
693                   uint32_t             *id)
694 {
695     ByteIOContext *pb = matroska->ctx->pb;
696     uint64_t length;
697     MatroskaLevel *level;
698     int res;
699
700     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
701         (res = ebml_read_element_length(matroska, &length)) < 0)
702         return res;
703
704     /* protect... (Heaven forbids that the '>' is true) */
705     if (matroska->num_levels >= EBML_MAX_DEPTH) {
706         av_log(matroska->ctx, AV_LOG_ERROR,
707                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
708         return AVERROR(ENOSYS);
709     }
710
711     /* remember level */
712     level = &matroska->levels[matroska->num_levels++];
713     level->start = url_ftell(pb);
714     level->length = length;
715
716     return 0;
717 }
718
719 /*
720  * Read the next element as binary data.
721  * 0 is success, < 0 is failure.
722  */
723
724 static int
725 ebml_read_binary (MatroskaDemuxContext *matroska,
726                   uint32_t             *id,
727                   uint8_t             **binary,
728                   int                  *size)
729 {
730     ByteIOContext *pb = matroska->ctx->pb;
731     uint64_t rlength;
732     int res;
733
734     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
735         (res = ebml_read_element_length(matroska, &rlength)) < 0)
736         return res;
737     *size = rlength;
738
739     if (!(*binary = av_malloc(*size))) {
740         av_log(matroska->ctx, AV_LOG_ERROR,
741                "Memory allocation error\n");
742         return AVERROR(ENOMEM);
743     }
744
745     if (get_buffer(pb, *binary, *size) != *size) {
746         offset_t pos = url_ftell(pb);
747         av_log(matroska->ctx, AV_LOG_ERROR,
748                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
749         return AVERROR(EIO);
750     }
751
752     return 0;
753 }
754
755 /*
756  * Read signed/unsigned "EBML" numbers.
757  * Return: number of bytes processed, < 0 on error.
758  * XXX: use ebml_read_num().
759  */
760
761 static int
762 matroska_ebmlnum_uint (uint8_t  *data,
763                        uint32_t  size,
764                        uint64_t *num)
765 {
766     int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
767     uint64_t total;
768
769     if (size <= 0)
770         return AVERROR_INVALIDDATA;
771
772     total = data[0];
773     while (read <= 8 && !(total & len_mask)) {
774         read++;
775         len_mask >>= 1;
776     }
777     if (read > 8)
778         return AVERROR_INVALIDDATA;
779
780     if ((total &= (len_mask - 1)) == len_mask - 1)
781         num_ffs++;
782     if (size < read)
783         return AVERROR_INVALIDDATA;
784     while (n < read) {
785         if (data[n] == 0xff)
786             num_ffs++;
787         total = (total << 8) | data[n];
788         n++;
789     }
790
791     if (read == num_ffs)
792         *num = (uint64_t)-1;
793     else
794         *num = total;
795
796     return read;
797 }
798
799 /*
800  * Same as above, but signed.
801  */
802
803 static int
804 matroska_ebmlnum_sint (uint8_t  *data,
805                        uint32_t  size,
806                        int64_t  *num)
807 {
808     uint64_t unum;
809     int res;
810
811     /* read as unsigned number first */
812     if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
813         return res;
814
815     /* make signed (weird way) */
816     if (unum == (uint64_t)-1)
817         *num = INT64_MAX;
818     else
819         *num = unum - ((1LL << ((7 * res) - 1)) - 1);
820
821     return res;
822 }
823
824
825 static MatroskaTrack *
826 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
827                             int                   num)
828 {
829     int i;
830
831     for (i = 0; i < matroska->num_tracks; i++)
832         if (matroska->tracks[i]->num == num)
833             return matroska->tracks[i];
834
835     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
836     return NULL;
837 }
838
839
840 /*
841  * Put one packet in an application-supplied AVPacket struct.
842  * Returns 0 on success or -1 on failure.
843  */
844
845 static int
846 matroska_deliver_packet (MatroskaDemuxContext *matroska,
847                          AVPacket             *pkt)
848 {
849     if (matroska->num_packets > 0) {
850         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
851         av_free(matroska->packets[0]);
852         if (matroska->num_packets > 1) {
853             memmove(&matroska->packets[0], &matroska->packets[1],
854                     (matroska->num_packets - 1) * sizeof(AVPacket *));
855             matroska->packets =
856                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
857                            sizeof(AVPacket *));
858         } else {
859             av_freep(&matroska->packets);
860         }
861         matroska->num_packets--;
862         return 0;
863     }
864
865     return -1;
866 }
867
868 /*
869  * Put a packet into our internal queue. Will be delivered to the
870  * user/application during the next get_packet() call.
871  */
872
873 static void
874 matroska_queue_packet (MatroskaDemuxContext *matroska,
875                        AVPacket             *pkt)
876 {
877     matroska->packets =
878         av_realloc(matroska->packets, (matroska->num_packets + 1) *
879                    sizeof(AVPacket *));
880     matroska->packets[matroska->num_packets] = pkt;
881     matroska->num_packets++;
882 }
883
884 /*
885  * Free all packets in our internal queue.
886  */
887 static void
888 matroska_clear_queue (MatroskaDemuxContext *matroska)
889 {
890     if (matroska->packets) {
891         int n;
892         for (n = 0; n < matroska->num_packets; n++) {
893             av_free_packet(matroska->packets[n]);
894             av_free(matroska->packets[n]);
895         }
896         av_free(matroska->packets);
897         matroska->packets = NULL;
898         matroska->num_packets = 0;
899     }
900 }
901
902
903 /*
904  * Autodetecting...
905  */
906
907 static int
908 matroska_probe (AVProbeData *p)
909 {
910     uint64_t total = 0;
911     int len_mask = 0x80, size = 1, n = 1;
912     uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
913
914     /* ebml header? */
915     if (AV_RB32(p->buf) != EBML_ID_HEADER)
916         return 0;
917
918     /* length of header */
919     total = p->buf[4];
920     while (size <= 8 && !(total & len_mask)) {
921         size++;
922         len_mask >>= 1;
923     }
924     if (size > 8)
925       return 0;
926     total &= (len_mask - 1);
927     while (n < size)
928         total = (total << 8) | p->buf[4 + n++];
929
930     /* does the probe data contain the whole header? */
931     if (p->buf_size < 4 + size + total)
932       return 0;
933
934     /* the header must contain the document type 'matroska'. For now,
935      * we don't parse the whole header but simply check for the
936      * availability of that array of characters inside the header.
937      * Not fully fool-proof, but good enough. */
938     for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
939         if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
940             return AVPROBE_SCORE_MAX;
941
942     return 0;
943 }
944
945 /*
946  * From here on, it's all XML-style DTD stuff... Needs no comments.
947  */
948
949 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
950                       void *data, uint32_t expected_id, int once);
951
952 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
953                            EbmlSyntax *syntax, void *data)
954 {
955     uint32_t id = syntax->id;
956     EbmlBin *bin;
957     int res;
958
959     data = (char *)data + syntax->data_offset;
960     if (syntax->list_elem_size) {
961         EbmlList *list = data;
962         list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
963         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
964         memset(data, 0, syntax->list_elem_size);
965         list->nb_elem++;
966     }
967     bin = data;
968
969     switch (syntax->type) {
970     case EBML_UINT:  return ebml_read_uint (matroska, &id, data);
971     case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
972     case EBML_STR:
973     case EBML_UTF8:  av_free(*(char **)data);
974                      return ebml_read_ascii(matroska, &id, data);
975     case EBML_BIN:   av_free(bin->data);
976                      bin->pos = url_ftell(matroska->ctx->pb);
977                      return ebml_read_binary(matroska, &id, &bin->data,
978                                                             &bin->size);
979     case EBML_NEST:  if ((res=ebml_read_master(matroska, &id)) < 0)
980                          return res;
981                      if (id == MATROSKA_ID_SEGMENT)
982                          matroska->segment_start = url_ftell(matroska->ctx->pb);
983                      return ebml_parse(matroska, syntax->def.n, data, 0, 0);
984     case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 0, 1);
985     case EBML_STOP:  *(int *)data = 1;      return 1;
986     default:         return ebml_read_skip(matroska);
987     }
988 }
989
990 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
991                          uint32_t id, void *data)
992 {
993     int i;
994     for (i=0; syntax[i].id; i++)
995         if (id == syntax[i].id)
996             break;
997     if (!syntax[i].id)
998         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
999     return ebml_parse_elem(matroska, &syntax[i], data);
1000 }
1001
1002 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1003                       void *data, uint32_t expected_id, int once)
1004 {
1005     int i, res = 0;
1006     uint32_t id = 0;
1007
1008     for (i=0; syntax[i].id; i++)
1009         switch (syntax[i].type) {
1010         case EBML_UINT:
1011             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1012             break;
1013         case EBML_FLOAT:
1014             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1015             break;
1016         case EBML_STR:
1017         case EBML_UTF8:
1018             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1019             break;
1020         }
1021
1022     if (expected_id) {
1023         res = ebml_read_master(matroska, &id);
1024         if (id != expected_id)
1025             return AVERROR_INVALIDDATA;
1026         if (id == MATROSKA_ID_SEGMENT)
1027             matroska->segment_start = url_ftell(matroska->ctx->pb);
1028     }
1029
1030     while (!res) {
1031         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1032             res = AVERROR(EIO);
1033             break;
1034         } else if (matroska->level_up) {
1035             matroska->level_up--;
1036             break;
1037         }
1038
1039         res = ebml_parse_id(matroska, syntax, id, data);
1040         if (once)
1041             break;
1042
1043
1044         if (matroska->level_up) {
1045             matroska->level_up--;
1046             break;
1047         }
1048     }
1049
1050     return res;
1051 }
1052
1053 static void ebml_free(EbmlSyntax *syntax, void *data)
1054 {
1055     int i, j;
1056     for (i=0; syntax[i].id; i++) {
1057         void *data_off = (char *)data + syntax[i].data_offset;
1058         switch (syntax[i].type) {
1059         case EBML_STR:
1060         case EBML_UTF8:  av_freep(data_off);                      break;
1061         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
1062         case EBML_NEST:
1063             if (syntax[i].list_elem_size) {
1064                 EbmlList *list = data_off;
1065                 char *ptr = list->elem;
1066                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1067                     ebml_free(syntax[i].def.n, ptr);
1068                 av_free(list->elem);
1069             } else
1070                 ebml_free(syntax[i].def.n, data_off);
1071         default:  break;
1072         }
1073     }
1074 }
1075
1076 static int
1077 matroska_parse_info (MatroskaDemuxContext *matroska)
1078 {
1079     int res = ebml_parse(matroska, matroska_info, matroska, MATROSKA_ID_INFO, 0);
1080
1081     if (matroska->duration)
1082         matroska->ctx->duration = matroska->duration * matroska->time_scale
1083                                   * 1000 / AV_TIME_BASE;
1084     if (matroska->title)
1085         strncpy(matroska->ctx->title, matroska->title,
1086                 sizeof(matroska->ctx->title)-1);
1087
1088     return res;
1089 }
1090
1091 static int
1092 matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1093 {
1094     uint8_t* data = *buf;
1095     int isize = *buf_size;
1096     uint8_t* pkt_data = NULL;
1097     int pkt_size = isize;
1098     int result = 0;
1099     int olen;
1100
1101     switch (track->encoding_algo) {
1102     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1103         return track->encoding_settings_len;
1104     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1105         do {
1106             olen = pkt_size *= 3;
1107             pkt_data = av_realloc(pkt_data,
1108                                   pkt_size+LZO_OUTPUT_PADDING);
1109             result = lzo1x_decode(pkt_data, &olen, data, &isize);
1110         } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1111         if (result)
1112             goto failed;
1113         pkt_size -= olen;
1114         break;
1115 #ifdef CONFIG_ZLIB
1116     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1117         z_stream zstream = {0};
1118         if (inflateInit(&zstream) != Z_OK)
1119             return -1;
1120         zstream.next_in = data;
1121         zstream.avail_in = isize;
1122         do {
1123             pkt_size *= 3;
1124             pkt_data = av_realloc(pkt_data, pkt_size);
1125             zstream.avail_out = pkt_size - zstream.total_out;
1126             zstream.next_out = pkt_data + zstream.total_out;
1127             result = inflate(&zstream, Z_NO_FLUSH);
1128         } while (result==Z_OK && pkt_size<10000000);
1129         pkt_size = zstream.total_out;
1130         inflateEnd(&zstream);
1131         if (result != Z_STREAM_END)
1132             goto failed;
1133         break;
1134     }
1135 #endif
1136 #ifdef CONFIG_BZLIB
1137     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1138         bz_stream bzstream = {0};
1139         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1140             return -1;
1141         bzstream.next_in = data;
1142         bzstream.avail_in = isize;
1143         do {
1144             pkt_size *= 3;
1145             pkt_data = av_realloc(pkt_data, pkt_size);
1146             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1147             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1148             result = BZ2_bzDecompress(&bzstream);
1149         } while (result==BZ_OK && pkt_size<10000000);
1150         pkt_size = bzstream.total_out_lo32;
1151         BZ2_bzDecompressEnd(&bzstream);
1152         if (result != BZ_STREAM_END)
1153             goto failed;
1154         break;
1155     }
1156 #endif
1157     }
1158
1159     *buf = pkt_data;
1160     *buf_size = pkt_size;
1161     return 0;
1162  failed:
1163     av_free(pkt_data);
1164     return -1;
1165 }
1166
1167 static int
1168 matroska_add_stream (MatroskaDemuxContext *matroska)
1169 {
1170     int res = 0;
1171     uint32_t id;
1172     MatroskaTrack *track;
1173
1174     /* start with the master */
1175     if ((res = ebml_read_master(matroska, &id)) < 0)
1176         return res;
1177
1178     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1179
1180     /* Allocate a generic track. */
1181     track = av_mallocz(MAX_TRACK_SIZE);
1182     track->time_scale = 1.0;
1183     strcpy(track->language, "eng");
1184
1185     /* try reading the trackentry headers */
1186     while (res == 0) {
1187         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1188             res = AVERROR(EIO);
1189             break;
1190         } else if (matroska->level_up > 0) {
1191             matroska->level_up--;
1192             break;
1193         }
1194
1195         switch (id) {
1196             /* track number (unique stream ID) */
1197             case MATROSKA_ID_TRACKNUMBER: {
1198                 uint64_t num;
1199                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1200                     break;
1201                 track->num = num;
1202                 break;
1203             }
1204
1205             /* track UID (unique identifier) */
1206             case MATROSKA_ID_TRACKUID: {
1207                 uint64_t num;
1208                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1209                     break;
1210                 track->uid = num;
1211                 break;
1212             }
1213
1214             /* track type (video, audio, combined, subtitle, etc.) */
1215             case MATROSKA_ID_TRACKTYPE: {
1216                 uint64_t num;
1217                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1218                     break;
1219                 if (track->type && track->type != num) {
1220                     av_log(matroska->ctx, AV_LOG_INFO,
1221                            "More than one tracktype in an entry - skip\n");
1222                     break;
1223                 }
1224                 track->type = num;
1225
1226                 switch (track->type) {
1227                     case MATROSKA_TRACK_TYPE_VIDEO:
1228                     case MATROSKA_TRACK_TYPE_AUDIO:
1229                     case MATROSKA_TRACK_TYPE_SUBTITLE:
1230                         break;
1231                     case MATROSKA_TRACK_TYPE_COMPLEX:
1232                     case MATROSKA_TRACK_TYPE_LOGO:
1233                     case MATROSKA_TRACK_TYPE_CONTROL:
1234                     default:
1235                         av_log(matroska->ctx, AV_LOG_INFO,
1236                                "Unknown or unsupported track type 0x%x\n",
1237                                track->type);
1238                         track->type = MATROSKA_TRACK_TYPE_NONE;
1239                         break;
1240                 }
1241                 break;
1242             }
1243
1244             /* tracktype specific stuff for video */
1245             case MATROSKA_ID_TRACKVIDEO: {
1246                 MatroskaVideoTrack *videotrack;
1247                 if (!track->type)
1248                     track->type = MATROSKA_TRACK_TYPE_VIDEO;
1249                 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1250                     av_log(matroska->ctx, AV_LOG_INFO,
1251                            "video data in non-video track - ignoring\n");
1252                     res = AVERROR_INVALIDDATA;
1253                     break;
1254                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1255                     break;
1256                 videotrack = (MatroskaVideoTrack *)track;
1257
1258                 while (res == 0) {
1259                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1260                         res = AVERROR(EIO);
1261                         break;
1262                     } else if (matroska->level_up > 0) {
1263                         matroska->level_up--;
1264                         break;
1265                     }
1266
1267                     switch (id) {
1268                         /* fixme, this should be one-up, but I get it here */
1269                         case MATROSKA_ID_TRACKDEFAULTDURATION: {
1270                             uint64_t num;
1271                             if ((res = ebml_read_uint (matroska, &id,
1272                                                        &num)) < 0)
1273                                 break;
1274                             track->default_duration = num;
1275                             break;
1276                         }
1277
1278                         /* video framerate */
1279                         case MATROSKA_ID_VIDEOFRAMERATE: {
1280                             double num;
1281                             if ((res = ebml_read_float(matroska, &id,
1282                                                        &num)) < 0)
1283                                 break;
1284                             if (!track->default_duration)
1285                                 track->default_duration = 1000000000/num;
1286                             break;
1287                         }
1288
1289                         /* width of the size to display the video at */
1290                         case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1291                             uint64_t num;
1292                             if ((res = ebml_read_uint(matroska, &id,
1293                                                       &num)) < 0)
1294                                 break;
1295                             videotrack->display_width = num;
1296                             break;
1297                         }
1298
1299                         /* height of the size to display the video at */
1300                         case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1301                             uint64_t num;
1302                             if ((res = ebml_read_uint(matroska, &id,
1303                                                       &num)) < 0)
1304                                 break;
1305                             videotrack->display_height = num;
1306                             break;
1307                         }
1308
1309                         /* width of the video in the file */
1310                         case MATROSKA_ID_VIDEOPIXELWIDTH: {
1311                             uint64_t num;
1312                             if ((res = ebml_read_uint(matroska, &id,
1313                                                       &num)) < 0)
1314                                 break;
1315                             videotrack->pixel_width = num;
1316                             break;
1317                         }
1318
1319                         /* height of the video in the file */
1320                         case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1321                             uint64_t num;
1322                             if ((res = ebml_read_uint(matroska, &id,
1323                                                       &num)) < 0)
1324                                 break;
1325                             videotrack->pixel_height = num;
1326                             break;
1327                         }
1328
1329                         /* whether the video is interlaced */
1330                         case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1331                             uint64_t num;
1332                             if ((res = ebml_read_uint(matroska, &id,
1333                                                       &num)) < 0)
1334                                 break;
1335                             break;
1336                         }
1337
1338                         /* colorspace (only matters for raw video)
1339                          * fourcc */
1340                         case MATROSKA_ID_VIDEOCOLORSPACE: {
1341                             uint64_t num;
1342                             if ((res = ebml_read_uint(matroska, &id,
1343                                                       &num)) < 0)
1344                                 break;
1345                             videotrack->fourcc = num;
1346                             break;
1347                         }
1348
1349                         default:
1350                             av_log(matroska->ctx, AV_LOG_INFO,
1351                                    "Unknown video track header entry "
1352                                    "0x%x - ignoring\n", id);
1353                             /* pass-through */
1354
1355                         case MATROSKA_ID_VIDEOSTEREOMODE:
1356                         case MATROSKA_ID_VIDEOASPECTRATIO:
1357                         case EBML_ID_VOID:
1358                             res = ebml_read_skip(matroska);
1359                             break;
1360                     }
1361
1362                     if (matroska->level_up) {
1363                         matroska->level_up--;
1364                         break;
1365                     }
1366                 }
1367                 break;
1368             }
1369
1370             /* tracktype specific stuff for audio */
1371             case MATROSKA_ID_TRACKAUDIO: {
1372                 MatroskaAudioTrack *audiotrack;
1373                 if (!track->type)
1374                     track->type = MATROSKA_TRACK_TYPE_AUDIO;
1375                 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1376                     av_log(matroska->ctx, AV_LOG_INFO,
1377                            "audio data in non-audio track - ignoring\n");
1378                     res = AVERROR_INVALIDDATA;
1379                     break;
1380                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1381                     break;
1382                 audiotrack = (MatroskaAudioTrack *)track;
1383                 audiotrack->channels = 1;
1384                 audiotrack->samplerate = 8000;
1385
1386                 while (res == 0) {
1387                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1388                         res = AVERROR(EIO);
1389                         break;
1390                     } else if (matroska->level_up > 0) {
1391                         matroska->level_up--;
1392                         break;
1393                     }
1394
1395                     switch (id) {
1396                         /* samplerate */
1397                         case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1398                             double num;
1399                             if ((res = ebml_read_float(matroska, &id,
1400                                                        &num)) < 0)
1401                                 break;
1402                             audiotrack->internal_samplerate =
1403                             audiotrack->samplerate = num;
1404                             break;
1405                         }
1406
1407                         case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1408                             double num;
1409                             if ((res = ebml_read_float(matroska, &id,
1410                                                        &num)) < 0)
1411                                 break;
1412                             audiotrack->samplerate = num;
1413                             break;
1414                         }
1415
1416                             /* bitdepth */
1417                         case MATROSKA_ID_AUDIOBITDEPTH: {
1418                             uint64_t num;
1419                             if ((res = ebml_read_uint(matroska, &id,
1420                                                       &num)) < 0)
1421                                 break;
1422                             audiotrack->bitdepth = num;
1423                             break;
1424                         }
1425
1426                             /* channels */
1427                         case MATROSKA_ID_AUDIOCHANNELS: {
1428                             uint64_t num;
1429                             if ((res = ebml_read_uint(matroska, &id,
1430                                                       &num)) < 0)
1431                                 break;
1432                             audiotrack->channels = num;
1433                             break;
1434                         }
1435
1436                         default:
1437                             av_log(matroska->ctx, AV_LOG_INFO,
1438                                    "Unknown audio track header entry "
1439                                    "0x%x - ignoring\n", id);
1440                             /* pass-through */
1441
1442                         case EBML_ID_VOID:
1443                             res = ebml_read_skip(matroska);
1444                             break;
1445                     }
1446
1447                     if (matroska->level_up) {
1448                         matroska->level_up--;
1449                         break;
1450                     }
1451                 }
1452                 break;
1453             }
1454
1455                 /* codec identifier */
1456             case MATROSKA_ID_CODECID: {
1457                 char *text;
1458                 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1459                     break;
1460                 track->codec_id = text;
1461                 break;
1462             }
1463
1464                 /* codec private data */
1465             case MATROSKA_ID_CODECPRIVATE: {
1466                 uint8_t *data;
1467                 int size;
1468                 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1469                     break;
1470                 track->codec_priv = data;
1471                 track->codec_priv_size = size;
1472                 break;
1473             }
1474
1475                 /* name of this track */
1476             case MATROSKA_ID_TRACKNAME: {
1477                 char *text;
1478                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1479                     break;
1480                 track->name = text;
1481                 break;
1482             }
1483
1484                 /* language (matters for audio/subtitles, mostly) */
1485             case MATROSKA_ID_TRACKLANGUAGE: {
1486                 char *text, *end;
1487                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1488                     break;
1489                 if ((end = strchr(text, '-')))
1490                     *end = '\0';
1491                 if (strlen(text) == 3)
1492                     strcpy(track->language, text);
1493                 av_free(text);
1494                 break;
1495             }
1496
1497                 /* whether this is actually used */
1498             case MATROSKA_ID_TRACKFLAGENABLED: {
1499                 uint64_t num;
1500                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1501                     break;
1502                 break;
1503             }
1504
1505                 /* whether it's the default for this track type */
1506             case MATROSKA_ID_TRACKFLAGDEFAULT: {
1507                 uint64_t num;
1508                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1509                     break;
1510                 track->flag_default = num;
1511                 break;
1512             }
1513
1514                 /* lacing (like MPEG, where blocks don't end/start on frame
1515                  * boundaries) */
1516             case MATROSKA_ID_TRACKFLAGLACING: {
1517                 uint64_t num;
1518                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1519                     break;
1520                 break;
1521             }
1522
1523                 /* default length (in time) of one data block in this track */
1524             case MATROSKA_ID_TRACKDEFAULTDURATION: {
1525                 uint64_t num;
1526                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1527                     break;
1528                 track->default_duration = num;
1529                 break;
1530             }
1531
1532             case MATROSKA_ID_TRACKCONTENTENCODINGS: {
1533                 if ((res = ebml_read_master(matroska, &id)) < 0)
1534                     break;
1535
1536                 while (res == 0) {
1537                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1538                         res = AVERROR(EIO);
1539                         break;
1540                     } else if (matroska->level_up > 0) {
1541                         matroska->level_up--;
1542                         break;
1543                     }
1544
1545                     switch (id) {
1546                         case MATROSKA_ID_TRACKCONTENTENCODING: {
1547                             int encoding_scope = 1;
1548                             if ((res = ebml_read_master(matroska, &id)) < 0)
1549                                 break;
1550
1551                             while (res == 0) {
1552                                 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1553                                     res = AVERROR(EIO);
1554                                     break;
1555                                 } else if (matroska->level_up > 0) {
1556                                     matroska->level_up--;
1557                                     break;
1558                                 }
1559
1560                                 switch (id) {
1561                                     case MATROSKA_ID_ENCODINGSCOPE: {
1562                                         uint64_t num;
1563                                         if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1564                                             break;
1565                                         encoding_scope = num;
1566                                         break;
1567                                     }
1568
1569                                     case MATROSKA_ID_ENCODINGTYPE: {
1570                                         uint64_t num;
1571                                         if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1572                                             break;
1573                                         if (num)
1574                                             av_log(matroska->ctx, AV_LOG_ERROR,
1575                                                    "Unsupported encoding type");
1576                                         break;
1577                                     }
1578
1579                                     case MATROSKA_ID_ENCODINGCOMPRESSION: {
1580                                         if ((res = ebml_read_master(matroska, &id)) < 0)
1581                                             break;
1582
1583                                         while (res == 0) {
1584                                             if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1585                                                 res = AVERROR(EIO);
1586                                                 break;
1587                                             } else if (matroska->level_up > 0) {
1588                                                 matroska->level_up--;
1589                                                 break;
1590                                             }
1591
1592                                             switch (id) {
1593                                                 case MATROSKA_ID_ENCODINGCOMPALGO: {
1594                                                     uint64_t num;
1595                                                     if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1596                                                         break;
1597                                                     if (num != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1598 #ifdef CONFIG_ZLIB
1599                                                         num != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1600 #endif
1601 #ifdef CONFIG_BZLIB
1602                                                         num != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1603 #endif
1604                                                         num != MATROSKA_TRACK_ENCODING_COMP_LZO)
1605                                                         av_log(matroska->ctx, AV_LOG_ERROR,
1606                                                                "Unsupported compression algo\n");
1607                                                     track->encoding_algo = num;
1608                                                     break;
1609                                                 }
1610
1611                                                 case MATROSKA_ID_ENCODINGCOMPSETTINGS: {
1612                                                     uint8_t *data;
1613                                                     int size;
1614                                                     if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1615                                                         break;
1616                                                     track->encoding_settings = data;
1617                                                     track->encoding_settings_len = size;
1618                                                     break;
1619                                                 }
1620
1621                                                 default:
1622                                                     av_log(matroska->ctx, AV_LOG_INFO,
1623                                                            "Unknown compression header entry "
1624                                                            "0x%x - ignoring\n", id);
1625                                                     /* pass-through */
1626
1627                                                 case EBML_ID_VOID:
1628                                                     res = ebml_read_skip(matroska);
1629                                                     break;
1630                                             }
1631
1632                                             if (matroska->level_up) {
1633                                                 matroska->level_up--;
1634                                                 break;
1635                                             }
1636                                         }
1637                                         break;
1638                                     }
1639
1640                                     default:
1641                                         av_log(matroska->ctx, AV_LOG_INFO,
1642                                                "Unknown content encoding header entry "
1643                                                "0x%x - ignoring\n", id);
1644                                         /* pass-through */
1645
1646                                     case EBML_ID_VOID:
1647                                         res = ebml_read_skip(matroska);
1648                                         break;
1649                                 }
1650
1651                                 if (matroska->level_up) {
1652                                     matroska->level_up--;
1653                                     break;
1654                                 }
1655                             }
1656
1657                             track->encoding_scope = encoding_scope;
1658                             break;
1659                         }
1660
1661                         default:
1662                             av_log(matroska->ctx, AV_LOG_INFO,
1663                                    "Unknown content encodings header entry "
1664                                    "0x%x - ignoring\n", id);
1665                             /* pass-through */
1666
1667                         case EBML_ID_VOID:
1668                             res = ebml_read_skip(matroska);
1669                             break;
1670                     }
1671
1672                     if (matroska->level_up) {
1673                         matroska->level_up--;
1674                         break;
1675                     }
1676                 }
1677                 break;
1678             }
1679
1680             case MATROSKA_ID_TRACKTIMECODESCALE: {
1681                 double num;
1682                 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1683                     break;
1684                 track->time_scale = num;
1685                 break;
1686             }
1687
1688             default:
1689                 av_log(matroska->ctx, AV_LOG_INFO,
1690                        "Unknown track header entry 0x%x - ignoring\n", id);
1691                 /* pass-through */
1692
1693             case EBML_ID_VOID:
1694             /* we ignore these because they're nothing useful. */
1695             case MATROSKA_ID_TRACKFLAGFORCED:
1696             case MATROSKA_ID_CODECNAME:
1697             case MATROSKA_ID_CODECDECODEALL:
1698             case MATROSKA_ID_CODECINFOURL:
1699             case MATROSKA_ID_CODECDOWNLOADURL:
1700             case MATROSKA_ID_TRACKMINCACHE:
1701             case MATROSKA_ID_TRACKMAXCACHE:
1702                 res = ebml_read_skip(matroska);
1703                 break;
1704         }
1705
1706         if (matroska->level_up) {
1707             matroska->level_up--;
1708             break;
1709         }
1710     }
1711
1712     if (track->codec_priv_size && track->encoding_scope & 2) {
1713         uint8_t *orig_priv = track->codec_priv;
1714         int offset = matroska_decode_buffer(&track->codec_priv,
1715                                             &track->codec_priv_size, track);
1716         if (offset > 0) {
1717             track->codec_priv = av_malloc(track->codec_priv_size + offset);
1718             memcpy(track->codec_priv, track->encoding_settings, offset);
1719             memcpy(track->codec_priv+offset, orig_priv, track->codec_priv_size);
1720             track->codec_priv_size += offset;
1721             av_free(orig_priv);
1722         } else if (!offset) {
1723             av_free(orig_priv);
1724         } else
1725             av_log(matroska->ctx, AV_LOG_ERROR,
1726                    "Failed to decode codec private data\n");
1727     }
1728
1729     if (track->type && matroska->num_tracks < ARRAY_SIZE(matroska->tracks)) {
1730         matroska->tracks[matroska->num_tracks++] = track;
1731     } else {
1732         av_free(track);
1733     }
1734     return res;
1735 }
1736
1737 static int
1738 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1739 {
1740     int res = 0;
1741     uint32_t id;
1742
1743     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1744
1745     while (res == 0) {
1746         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1747             res = AVERROR(EIO);
1748             break;
1749         } else if (matroska->level_up) {
1750             matroska->level_up--;
1751             break;
1752         }
1753
1754         switch (id) {
1755             /* one track within the "all-tracks" header */
1756             case MATROSKA_ID_TRACKENTRY:
1757                 res = matroska_add_stream(matroska);
1758                 break;
1759
1760             default:
1761                 av_log(matroska->ctx, AV_LOG_INFO,
1762                        "Unknown entry 0x%x in track header\n", id);
1763                 /* fall-through */
1764
1765             case EBML_ID_VOID:
1766                 res = ebml_read_skip(matroska);
1767                 break;
1768         }
1769
1770         if (matroska->level_up) {
1771             matroska->level_up--;
1772             break;
1773         }
1774     }
1775
1776     return res;
1777 }
1778
1779 static int
1780 matroska_parse_index (MatroskaDemuxContext *matroska)
1781 {
1782     return ebml_parse(matroska, matroska_index, matroska, MATROSKA_ID_CUES, 0);
1783 }
1784
1785 static int
1786 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1787 {
1788     return ebml_parse(matroska, matroska_tags, matroska, MATROSKA_ID_TAGS, 0);
1789 }
1790
1791 static int
1792 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1793 {
1794     int res = 0;
1795     uint32_t id;
1796
1797     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1798
1799     while (res == 0) {
1800         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1801             res = AVERROR(EIO);
1802             break;
1803         } else if (matroska->level_up) {
1804             matroska->level_up--;
1805             break;
1806         }
1807
1808         switch (id) {
1809             case MATROSKA_ID_SEEKENTRY: {
1810                 uint32_t seek_id = 0, peek_id_cache = 0;
1811                 uint64_t seek_pos = (uint64_t) -1, t;
1812                 int dummy_level = 0;
1813
1814                 if ((res = ebml_read_master(matroska, &id)) < 0)
1815                     break;
1816
1817                 while (res == 0) {
1818                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1819                         res = AVERROR(EIO);
1820                         break;
1821                     } else if (matroska->level_up) {
1822                         matroska->level_up--;
1823                         break;
1824                     }
1825
1826                     switch (id) {
1827                         case MATROSKA_ID_SEEKID:
1828                             res = ebml_read_uint(matroska, &id, &t);
1829                             seek_id = t;
1830                             break;
1831
1832                         case MATROSKA_ID_SEEKPOSITION:
1833                             res = ebml_read_uint(matroska, &id, &seek_pos);
1834                             break;
1835
1836                         default:
1837                             av_log(matroska->ctx, AV_LOG_INFO,
1838                                    "Unknown seekhead ID 0x%x\n", id);
1839                             /* fall-through */
1840
1841                         case EBML_ID_VOID:
1842                             res = ebml_read_skip(matroska);
1843                             break;
1844                     }
1845
1846                     if (matroska->level_up) {
1847                         matroska->level_up--;
1848                         break;
1849                     }
1850                 }
1851
1852                 if (!seek_id || seek_pos == (uint64_t) -1) {
1853                     av_log(matroska->ctx, AV_LOG_INFO,
1854                            "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1855                            seek_id, seek_pos);
1856                     break;
1857                 }
1858
1859                 switch (seek_id) {
1860                     case MATROSKA_ID_CUES:
1861                     case MATROSKA_ID_TAGS: {
1862                         uint32_t level_up = matroska->level_up;
1863                         offset_t before_pos;
1864                         uint64_t length;
1865                         MatroskaLevel level;
1866
1867                         /* remember the peeked ID and the current position */
1868                         peek_id_cache = matroska->peek_id;
1869                         before_pos = url_ftell(matroska->ctx->pb);
1870
1871                         /* seek */
1872                         if ((res = ebml_read_seek(matroska, seek_pos +
1873                                                matroska->segment_start)) < 0)
1874                             goto finish;
1875
1876                         /* we don't want to lose our seekhead level, so we add
1877                          * a dummy. This is a crude hack. */
1878                         if (matroska->num_levels == EBML_MAX_DEPTH) {
1879                             av_log(matroska->ctx, AV_LOG_INFO,
1880                                    "Max EBML element depth (%d) reached, "
1881                                    "cannot parse further.\n", EBML_MAX_DEPTH);
1882                             return AVERROR_UNKNOWN;
1883                         }
1884
1885                         level.start = 0;
1886                         level.length = (uint64_t)-1;
1887                         matroska->levels[matroska->num_levels] = level;
1888                         matroska->num_levels++;
1889                         dummy_level = 1;
1890
1891                         /* check ID */
1892                         if (!(id = ebml_peek_id (matroska,
1893                                                  &matroska->level_up)))
1894                             goto finish;
1895                         if (id != seek_id) {
1896                             av_log(matroska->ctx, AV_LOG_INFO,
1897                                    "We looked for ID=0x%x but got "
1898                                    "ID=0x%x (pos=%"PRIu64")",
1899                                    seek_id, id, seek_pos +
1900                                    matroska->segment_start);
1901                             goto finish;
1902                         }
1903
1904                         /* read master + parse */
1905                         switch (id) {
1906                             case MATROSKA_ID_CUES:
1907                                 if (!(res = matroska_parse_index(matroska)) ||
1908                                     url_feof(matroska->ctx->pb)) {
1909                                     matroska->index_parsed = 1;
1910                                     res = 0;
1911                                 }
1912                                 break;
1913                             case MATROSKA_ID_TAGS:
1914                                 if (!(res = matroska_parse_metadata(matroska)) ||
1915                                    url_feof(matroska->ctx->pb)) {
1916                                     matroska->metadata_parsed = 1;
1917                                     res = 0;
1918                                 }
1919                                 break;
1920                         }
1921
1922                     finish:
1923                         /* remove dummy level */
1924                         if (dummy_level)
1925                             while (matroska->num_levels) {
1926                                 matroska->num_levels--;
1927                                 length =
1928                                   matroska->levels[matroska->num_levels].length;
1929                                 if (length == (uint64_t)-1)
1930                                     break;
1931                             }
1932
1933                         /* seek back */
1934                         if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1935                             return res;
1936                         matroska->peek_id = peek_id_cache;
1937                         matroska->level_up = level_up;
1938                         break;
1939                     }
1940
1941                     default:
1942                         av_log(matroska->ctx, AV_LOG_INFO,
1943                                "Ignoring seekhead entry for ID=0x%x\n",
1944                                seek_id);
1945                         break;
1946                 }
1947
1948                 break;
1949             }
1950
1951             default:
1952                 av_log(matroska->ctx, AV_LOG_INFO,
1953                        "Unknown seekhead ID 0x%x\n", id);
1954                 /* fall-through */
1955
1956             case EBML_ID_VOID:
1957                 res = ebml_read_skip(matroska);
1958                 break;
1959         }
1960
1961         if (matroska->level_up) {
1962             matroska->level_up--;
1963             break;
1964         }
1965     }
1966
1967     return res;
1968 }
1969
1970 static int
1971 matroska_parse_attachments(AVFormatContext *s)
1972 {
1973     MatroskaDemuxContext *matroska = s->priv_data;
1974     EbmlList *attachements_list = &matroska->attachments;
1975     MatroskaAttachement *attachements;
1976     int i, j, res;
1977
1978     res = ebml_parse(matroska, matroska_attachments, matroska, MATROSKA_ID_ATTACHMENTS, 0);
1979
1980     attachements = attachements_list->elem;
1981     for (j=0; j<attachements_list->nb_elem; j++) {
1982         if (!(attachements[j].filename && attachements[j].mime &&
1983               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1984             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1985         } else {
1986             AVStream *st = av_new_stream(s, matroska->num_streams++);
1987             if (st == NULL)
1988                 break;
1989             st->filename          = av_strdup(attachements[j].filename);
1990             st->codec->codec_id = CODEC_ID_NONE;
1991             st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1992             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1993             if(st->codec->extradata == NULL)
1994                 break;
1995             st->codec->extradata_size = attachements[j].bin.size;
1996             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1997
1998             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1999                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
2000                              strlen(ff_mkv_mime_tags[i].str))) {
2001                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
2002                     break;
2003                 }
2004             }
2005         }
2006     }
2007
2008     return res;
2009 }
2010
2011 static int
2012 matroska_parse_chapters(AVFormatContext *s)
2013 {
2014     MatroskaDemuxContext *matroska = s->priv_data;
2015     EbmlList *chapters_list = &matroska->chapters;
2016     MatroskaChapter *chapters;
2017     int i, res;
2018
2019     res = ebml_parse(matroska, matroska_chapters, matroska, MATROSKA_ID_CHAPTERS, 0);
2020
2021     chapters = chapters_list->elem;
2022     for (i=0; i<chapters_list->nb_elem; i++)
2023         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
2024             ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
2025                            chapters[i].start, chapters[i].end,
2026                            chapters[i].title);
2027
2028     return res;
2029 }
2030
2031 static int
2032 matroska_aac_profile (char *codec_id)
2033 {
2034     static const char *aac_profiles[] = {
2035         "MAIN", "LC", "SSR"
2036     };
2037     int profile;
2038
2039     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2040         if (strstr(codec_id, aac_profiles[profile]))
2041             break;
2042     return profile + 1;
2043 }
2044
2045 static int
2046 matroska_aac_sri (int samplerate)
2047 {
2048     int sri;
2049
2050     for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2051         if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2052             break;
2053     return sri;
2054 }
2055
2056 static int
2057 matroska_read_header (AVFormatContext    *s,
2058                       AVFormatParameters *ap)
2059 {
2060     MatroskaDemuxContext *matroska = s->priv_data;
2061     EbmlList *index_list;
2062     MatroskaIndex *index;
2063     int i, j, last_level, res = 0;
2064     Ebml ebml = { 0 };
2065     uint32_t id;
2066
2067     matroska->ctx = s;
2068
2069     /* First read the EBML header. */
2070     if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
2071         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
2072         || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
2073         || ebml.doctype_version > 2) {
2074         av_log(matroska->ctx, AV_LOG_ERROR,
2075                "EBML header using unsupported features\n"
2076                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
2077                ebml.version, ebml.doctype, ebml.doctype_version);
2078         return AVERROR_NOFMT;
2079     }
2080     ebml_free(ebml_syntax, &ebml);
2081
2082     /* The next thing is a segment. */
2083     while (1) {
2084         if (!(id = ebml_peek_id(matroska, &last_level)))
2085             return AVERROR(EIO);
2086         if (id == MATROSKA_ID_SEGMENT)
2087             break;
2088
2089         /* oi! */
2090         av_log(matroska->ctx, AV_LOG_INFO,
2091                "Expected a Segment ID (0x%x), but received 0x%x!\n",
2092                MATROSKA_ID_SEGMENT, id);
2093         if ((res = ebml_read_skip(matroska)) < 0)
2094             return res;
2095     }
2096
2097     /* We now have a Matroska segment.
2098      * Seeks are from the beginning of the segment,
2099      * after the segment ID/length. */
2100     if ((res = ebml_read_master(matroska, &id)) < 0)
2101         return res;
2102     matroska->segment_start = url_ftell(s->pb);
2103
2104     matroska->time_scale = 1000000;
2105     /* we've found our segment, start reading the different contents in here */
2106     while (res == 0) {
2107         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2108             res = AVERROR(EIO);
2109             break;
2110         } else if (matroska->level_up) {
2111             matroska->level_up--;
2112             break;
2113         }
2114
2115         switch (id) {
2116             /* stream info */
2117             case MATROSKA_ID_INFO: {
2118                 res = matroska_parse_info(matroska);
2119                 break;
2120             }
2121
2122             /* track info headers */
2123             case MATROSKA_ID_TRACKS: {
2124                 if ((res = ebml_read_master(matroska, &id)) < 0)
2125                     break;
2126                 res = matroska_parse_tracks(matroska);
2127                 break;
2128             }
2129
2130             /* stream index */
2131             case MATROSKA_ID_CUES: {
2132                 if (!matroska->index_parsed) {
2133                     res = matroska_parse_index(matroska);
2134                 } else
2135                     res = ebml_read_skip(matroska);
2136                 break;
2137             }
2138
2139             /* metadata */
2140             case MATROSKA_ID_TAGS: {
2141                 if (!matroska->metadata_parsed) {
2142                     res = matroska_parse_metadata(matroska);
2143                 } else
2144                     res = ebml_read_skip(matroska);
2145                 break;
2146             }
2147
2148             /* file index (if seekable, seek to Cues/Tags to parse it) */
2149             case MATROSKA_ID_SEEKHEAD: {
2150                 if ((res = ebml_read_master(matroska, &id)) < 0)
2151                     break;
2152                 res = matroska_parse_seekhead(matroska);
2153                 break;
2154             }
2155
2156             case MATROSKA_ID_ATTACHMENTS: {
2157                 res = matroska_parse_attachments(s);
2158                 break;
2159             }
2160
2161             case MATROSKA_ID_CLUSTER: {
2162                 /* Do not read the master - this will be done in the next
2163                  * call to matroska_read_packet. */
2164                 res = 1;
2165                 break;
2166             }
2167
2168             case MATROSKA_ID_CHAPTERS: {
2169                 res = matroska_parse_chapters(s);
2170                 break;
2171             }
2172
2173             default:
2174                 av_log(matroska->ctx, AV_LOG_INFO,
2175                        "Unknown matroska file header ID 0x%x\n", id);
2176             /* fall-through */
2177
2178             case EBML_ID_VOID:
2179                 res = ebml_read_skip(matroska);
2180                 break;
2181         }
2182
2183         if (matroska->level_up) {
2184             matroska->level_up--;
2185             break;
2186         }
2187     }
2188
2189     /* Have we found a cluster? */
2190     if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2191         int i, j;
2192         MatroskaTrack *track;
2193         AVStream *st;
2194
2195         for (i = 0; i < matroska->num_tracks; i++) {
2196             enum CodecID codec_id = CODEC_ID_NONE;
2197             uint8_t *extradata = NULL;
2198             int extradata_size = 0;
2199             int extradata_offset = 0;
2200             track = matroska->tracks[i];
2201
2202             /* Apply some sanity checks. */
2203             if (track->codec_id == NULL)
2204                 continue;
2205
2206             for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2207                 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2208                             strlen(ff_mkv_codec_tags[j].str))){
2209                     codec_id= ff_mkv_codec_tags[j].id;
2210                     break;
2211                 }
2212             }
2213
2214             st = track->stream = av_new_stream(s, matroska->num_streams++);
2215             if (st == NULL)
2216                 return AVERROR(ENOMEM);
2217
2218             /* Set the FourCC from the CodecID. */
2219             /* This is the MS compatibility mode which stores a
2220              * BITMAPINFOHEADER in the CodecPrivate. */
2221             if (!strcmp(track->codec_id,
2222                         MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2223                 (track->codec_priv_size >= 40) &&
2224                 (track->codec_priv != NULL)) {
2225                 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2226
2227                 /* Offset of biCompression. Stored in LE. */
2228                 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2229                 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2230
2231             }
2232
2233             /* This is the MS compatibility mode which stores a
2234              * WAVEFORMATEX in the CodecPrivate. */
2235             else if (!strcmp(track->codec_id,
2236                              MATROSKA_CODEC_ID_AUDIO_ACM) &&
2237                 (track->codec_priv_size >= 18) &&
2238                 (track->codec_priv != NULL)) {
2239                 uint16_t tag;
2240
2241                 /* Offset of wFormatTag. Stored in LE. */
2242                 tag = AV_RL16(track->codec_priv);
2243                 codec_id = codec_get_id(codec_wav_tags, tag);
2244
2245             }
2246
2247             if (!strcmp(track->codec_id, "V_QUICKTIME") &&
2248                 (track->codec_priv_size >= 86) &&
2249                 (track->codec_priv != NULL)) {
2250                 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2251
2252                 vtrack->fourcc = AV_RL32(track->codec_priv);
2253                 codec_id = codec_get_id(codec_movvideo_tags, vtrack->fourcc);
2254             }
2255
2256             else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2257                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2258                 int profile = matroska_aac_profile(track->codec_id);
2259                 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2260                 extradata = av_malloc(5);
2261                 if (extradata == NULL)
2262                     return AVERROR(ENOMEM);
2263                 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2264                 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2265                 if (strstr(track->codec_id, "SBR")) {
2266                     sri = matroska_aac_sri(audiotrack->samplerate);
2267                     extradata[2] = 0x56;
2268                     extradata[3] = 0xE5;
2269                     extradata[4] = 0x80 | (sri<<3);
2270                     extradata_size = 5;
2271                 } else {
2272                     extradata_size = 2;
2273                 }
2274             }
2275
2276             else if (codec_id == CODEC_ID_TTA) {
2277                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2278                 ByteIOContext b;
2279                 extradata_size = 30;
2280                 extradata = av_mallocz(extradata_size);
2281                 if (extradata == NULL)
2282                     return AVERROR(ENOMEM);
2283                 init_put_byte(&b, extradata, extradata_size, 1,
2284                               NULL, NULL, NULL, NULL);
2285                 put_buffer(&b, "TTA1", 4);
2286                 put_le16(&b, 1);
2287                 put_le16(&b, audiotrack->channels);
2288                 put_le16(&b, audiotrack->bitdepth);
2289                 put_le32(&b, audiotrack->samplerate);
2290                 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2291             }
2292
2293             else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2294                      codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2295                 extradata_offset = 26;
2296                 track->codec_priv_size -= extradata_offset;
2297             }
2298
2299             else if (codec_id == CODEC_ID_RA_144) {
2300                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2301                 audiotrack->samplerate = 8000;
2302                 audiotrack->channels = 1;
2303             }
2304
2305             else if (codec_id == CODEC_ID_RA_288 ||
2306                      codec_id == CODEC_ID_COOK ||
2307                      codec_id == CODEC_ID_ATRAC3) {
2308                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2309                 ByteIOContext b;
2310
2311                 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2312                               NULL, NULL, NULL, NULL);
2313                 url_fskip(&b, 24);
2314                 audiotrack->coded_framesize = get_be32(&b);
2315                 url_fskip(&b, 12);
2316                 audiotrack->sub_packet_h    = get_be16(&b);
2317                 audiotrack->frame_size      = get_be16(&b);
2318                 audiotrack->sub_packet_size = get_be16(&b);
2319                 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2320                 if (codec_id == CODEC_ID_RA_288) {
2321                     audiotrack->block_align = audiotrack->coded_framesize;
2322                     track->codec_priv_size = 0;
2323                 } else {
2324                     audiotrack->block_align = audiotrack->sub_packet_size;
2325                     extradata_offset = 78;
2326                     track->codec_priv_size -= extradata_offset;
2327                 }
2328             }
2329
2330             if (codec_id == CODEC_ID_NONE) {
2331                 av_log(matroska->ctx, AV_LOG_INFO,
2332                        "Unknown/unsupported CodecID %s.\n",
2333                        track->codec_id);
2334             }
2335
2336             av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2337
2338             st->codec->codec_id = codec_id;
2339             st->start_time = 0;
2340             if (strcmp(track->language, "und"))
2341                 av_strlcpy(st->language, track->language, 4);
2342
2343             if (track->flag_default)
2344                 st->disposition |= AV_DISPOSITION_DEFAULT;
2345
2346             if (track->default_duration)
2347                 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2348                           track->default_duration, 1000000000, 30000);
2349
2350             if(extradata){
2351                 st->codec->extradata = extradata;
2352                 st->codec->extradata_size = extradata_size;
2353             } else if(track->codec_priv && track->codec_priv_size > 0){
2354                 st->codec->extradata = av_malloc(track->codec_priv_size);
2355                 if(st->codec->extradata == NULL)
2356                     return AVERROR(ENOMEM);
2357                 st->codec->extradata_size = track->codec_priv_size;
2358                 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2359                        track->codec_priv_size);
2360             }
2361
2362             if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2363                 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2364
2365                 st->codec->codec_type = CODEC_TYPE_VIDEO;
2366                 st->codec->codec_tag = videotrack->fourcc;
2367                 st->codec->width = videotrack->pixel_width;
2368                 st->codec->height = videotrack->pixel_height;
2369                 if (videotrack->display_width == 0)
2370                     videotrack->display_width= videotrack->pixel_width;
2371                 if (videotrack->display_height == 0)
2372                     videotrack->display_height= videotrack->pixel_height;
2373                 av_reduce(&st->codec->sample_aspect_ratio.num,
2374                           &st->codec->sample_aspect_ratio.den,
2375                           st->codec->height * videotrack->display_width,
2376                           st->codec-> width * videotrack->display_height,
2377                           255);
2378                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2379             } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2380                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2381
2382                 st->codec->codec_type = CODEC_TYPE_AUDIO;
2383                 st->codec->sample_rate = audiotrack->samplerate;
2384                 st->codec->channels = audiotrack->channels;
2385                 st->codec->block_align = audiotrack->block_align;
2386             } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2387                 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2388             }
2389
2390             /* What do we do with private data? E.g. for Vorbis. */
2391         }
2392         res = 0;
2393     }
2394
2395     index_list = &matroska->index;
2396     index = index_list->elem;
2397     for (i=0; i<index_list->nb_elem; i++) {
2398         EbmlList *pos_list = &index[i].pos;
2399         MatroskaIndexPos *pos = pos_list->elem;
2400         for (j=0; j<pos_list->nb_elem; j++) {
2401             MatroskaTrack *track = matroska_find_track_by_num(matroska,
2402                                                               pos[j].track);
2403             if (track && track->stream)
2404                 av_add_index_entry(track->stream,
2405                                    pos[j].pos + matroska->segment_start,
2406                                    index[i].time*matroska->time_scale/AV_TIME_BASE,
2407                                    0, 0, AVINDEX_KEYFRAME);
2408         }
2409     }
2410
2411     return res;
2412 }
2413
2414 static int
2415 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2416                      int64_t pos, uint64_t cluster_time, uint64_t duration,
2417                      int is_keyframe)
2418 {
2419     MatroskaTrack *track;
2420     int res = 0;
2421     AVStream *st;
2422     AVPacket *pkt;
2423     uint8_t *origdata = data;
2424     int16_t block_time;
2425     uint32_t *lace_size = NULL;
2426     int n, flags, laces = 0;
2427     uint64_t num;
2428
2429     /* first byte(s): tracknum */
2430     if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2431         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2432         av_free(origdata);
2433         return res;
2434     }
2435     data += n;
2436     size -= n;
2437
2438     /* fetch track from num */
2439     track = matroska_find_track_by_num(matroska, num);
2440     if (size <= 3 || !track || !track->stream) {
2441         av_log(matroska->ctx, AV_LOG_INFO,
2442                "Invalid stream %"PRIu64" or size %u\n", num, size);
2443         av_free(origdata);
2444         return res;
2445     }
2446     st = track->stream;
2447     if (st->discard >= AVDISCARD_ALL) {
2448         av_free(origdata);
2449         return res;
2450     }
2451     if (duration == AV_NOPTS_VALUE)
2452         duration = track->default_duration / matroska->time_scale;
2453
2454     /* block_time (relative to cluster time) */
2455     block_time = AV_RB16(data);
2456     data += 2;
2457     flags = *data++;
2458     size -= 3;
2459     if (is_keyframe == -1)
2460         is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2461
2462     if (matroska->skip_to_keyframe) {
2463         if (!is_keyframe || st != matroska->skip_to_stream) {
2464             av_free(origdata);
2465             return res;
2466         }
2467         matroska->skip_to_keyframe = 0;
2468     }
2469
2470     switch ((flags & 0x06) >> 1) {
2471         case 0x0: /* no lacing */
2472             laces = 1;
2473             lace_size = av_mallocz(sizeof(int));
2474             lace_size[0] = size;
2475             break;
2476
2477         case 0x1: /* xiph lacing */
2478         case 0x2: /* fixed-size lacing */
2479         case 0x3: /* EBML lacing */
2480             assert(size>0); // size <=3 is checked before size-=3 above
2481             laces = (*data) + 1;
2482             data += 1;
2483             size -= 1;
2484             lace_size = av_mallocz(laces * sizeof(int));
2485
2486             switch ((flags & 0x06) >> 1) {
2487                 case 0x1: /* xiph lacing */ {
2488                     uint8_t temp;
2489                     uint32_t total = 0;
2490                     for (n = 0; res == 0 && n < laces - 1; n++) {
2491                         while (1) {
2492                             if (size == 0) {
2493                                 res = -1;
2494                                 break;
2495                             }
2496                             temp = *data;
2497                             lace_size[n] += temp;
2498                             data += 1;
2499                             size -= 1;
2500                             if (temp != 0xff)
2501                                 break;
2502                         }
2503                         total += lace_size[n];
2504                     }
2505                     lace_size[n] = size - total;
2506                     break;
2507                 }
2508
2509                 case 0x2: /* fixed-size lacing */
2510                     for (n = 0; n < laces; n++)
2511                         lace_size[n] = size / laces;
2512                     break;
2513
2514                 case 0x3: /* EBML lacing */ {
2515                     uint32_t total;
2516                     n = matroska_ebmlnum_uint(data, size, &num);
2517                     if (n < 0) {
2518                         av_log(matroska->ctx, AV_LOG_INFO,
2519                                "EBML block data error\n");
2520                         break;
2521                     }
2522                     data += n;
2523                     size -= n;
2524                     total = lace_size[0] = num;
2525                     for (n = 1; res == 0 && n < laces - 1; n++) {
2526                         int64_t snum;
2527                         int r;
2528                         r = matroska_ebmlnum_sint (data, size, &snum);
2529                         if (r < 0) {
2530                             av_log(matroska->ctx, AV_LOG_INFO,
2531                                    "EBML block data error\n");
2532                             break;
2533                         }
2534                         data += r;
2535                         size -= r;
2536                         lace_size[n] = lace_size[n - 1] + snum;
2537                         total += lace_size[n];
2538                     }
2539                     lace_size[n] = size - total;
2540                     break;
2541                 }
2542             }
2543             break;
2544     }
2545
2546     if (res == 0) {
2547         uint64_t timecode = AV_NOPTS_VALUE;
2548
2549         if (cluster_time != (uint64_t)-1
2550             && (block_time >= 0 || cluster_time >= -block_time))
2551             timecode = cluster_time + block_time;
2552
2553         for (n = 0; n < laces; n++) {
2554             if (st->codec->codec_id == CODEC_ID_RA_288 ||
2555                 st->codec->codec_id == CODEC_ID_COOK ||
2556                 st->codec->codec_id == CODEC_ID_ATRAC3) {
2557                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2558                 int a = st->codec->block_align;
2559                 int sps = audiotrack->sub_packet_size;
2560                 int cfs = audiotrack->coded_framesize;
2561                 int h = audiotrack->sub_packet_h;
2562                 int y = audiotrack->sub_packet_cnt;
2563                 int w = audiotrack->frame_size;
2564                 int x;
2565
2566                 if (!audiotrack->pkt_cnt) {
2567                     if (st->codec->codec_id == CODEC_ID_RA_288)
2568                         for (x=0; x<h/2; x++)
2569                             memcpy(audiotrack->buf+x*2*w+y*cfs,
2570                                    data+x*cfs, cfs);
2571                     else
2572                         for (x=0; x<w/sps; x++)
2573                             memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2574
2575                     if (++audiotrack->sub_packet_cnt >= h) {
2576                         audiotrack->sub_packet_cnt = 0;
2577                         audiotrack->pkt_cnt = h*w / a;
2578                     }
2579                 }
2580                 while (audiotrack->pkt_cnt) {
2581                     pkt = av_mallocz(sizeof(AVPacket));
2582                     av_new_packet(pkt, a);
2583                     memcpy(pkt->data, audiotrack->buf
2584                            + a * (h*w / a - audiotrack->pkt_cnt--), a);
2585                     pkt->pos = pos;
2586                     pkt->stream_index = st->index;
2587                     matroska_queue_packet(matroska, pkt);
2588                 }
2589             } else {
2590                 int offset = 0, pkt_size = lace_size[n];
2591                 uint8_t *pkt_data = data;
2592
2593                 if (track->encoding_scope & 1) {
2594                     offset = matroska_decode_buffer(&pkt_data, &pkt_size,
2595                                                     track);
2596                     if (offset < 0)
2597                         continue;
2598                 }
2599
2600                 pkt = av_mallocz(sizeof(AVPacket));
2601                 /* XXX: prevent data copy... */
2602                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
2603                     av_free(pkt);
2604                     res = AVERROR(ENOMEM);
2605                     n = laces-1;
2606                     break;
2607                 }
2608                 if (offset)
2609                     memcpy (pkt->data, track->encoding_settings, offset);
2610                 memcpy (pkt->data+offset, pkt_data, pkt_size);
2611
2612                 if (pkt_data != data)
2613                     av_free(pkt_data);
2614
2615                 if (n == 0)
2616                     pkt->flags = is_keyframe;
2617                 pkt->stream_index = st->index;
2618
2619                 pkt->pts = timecode;
2620                 pkt->pos = pos;
2621                 pkt->duration = duration;
2622
2623                 matroska_queue_packet(matroska, pkt);
2624             }
2625
2626             if (timecode != AV_NOPTS_VALUE)
2627                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2628             data += lace_size[n];
2629         }
2630     }
2631
2632     av_free(lace_size);
2633     av_free(origdata);
2634     return res;
2635 }
2636
2637 static int
2638 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2639                            uint64_t              cluster_time)
2640 {
2641     int res = 0;
2642     uint32_t id;
2643     int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2644     uint64_t duration = AV_NOPTS_VALUE;
2645     uint8_t *data;
2646     int size = 0;
2647     int64_t pos = 0;
2648
2649     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2650
2651     while (res == 0) {
2652         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2653             res = AVERROR(EIO);
2654             break;
2655         } else if (matroska->level_up) {
2656             matroska->level_up--;
2657             break;
2658         }
2659
2660         switch (id) {
2661             /* one block inside the group. Note, block parsing is one
2662              * of the harder things, so this code is a bit complicated.
2663              * See http://www.matroska.org/ for documentation. */
2664             case MATROSKA_ID_BLOCK: {
2665                 pos = url_ftell(matroska->ctx->pb);
2666                 res = ebml_read_binary(matroska, &id, &data, &size);
2667                 break;
2668             }
2669
2670             case MATROSKA_ID_BLOCKDURATION: {
2671                 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2672                     break;
2673                 break;
2674             }
2675
2676             case MATROSKA_ID_BLOCKREFERENCE: {
2677                 int64_t num;
2678                 /* We've found a reference, so not even the first frame in
2679                  * the lace is a key frame. */
2680                 is_keyframe = 0;
2681                 if (last_num_packets != matroska->num_packets)
2682                     matroska->packets[last_num_packets]->flags = 0;
2683                 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2684                     break;
2685                 break;
2686             }
2687
2688             default:
2689                 av_log(matroska->ctx, AV_LOG_INFO,
2690                        "Unknown entry 0x%x in blockgroup data\n", id);
2691                 /* fall-through */
2692
2693             case EBML_ID_VOID:
2694                 res = ebml_read_skip(matroska);
2695                 break;
2696         }
2697
2698         if (matroska->level_up) {
2699             matroska->level_up--;
2700             break;
2701         }
2702     }
2703
2704     if (res)
2705         return res;
2706
2707     if (size > 0)
2708         res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2709                                    duration, is_keyframe);
2710
2711     return res;
2712 }
2713
2714 static int
2715 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2716 {
2717     int res = 0;
2718     uint32_t id;
2719     uint64_t cluster_time = 0;
2720     uint8_t *data;
2721     int64_t pos;
2722     int size;
2723
2724     av_log(matroska->ctx, AV_LOG_DEBUG,
2725            "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2726
2727     while (res == 0) {
2728         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2729             res = AVERROR(EIO);
2730             break;
2731         } else if (matroska->level_up) {
2732             matroska->level_up--;
2733             break;
2734         }
2735
2736         switch (id) {
2737             /* cluster timecode */
2738             case MATROSKA_ID_CLUSTERTIMECODE: {
2739                 uint64_t num;
2740                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2741                     break;
2742                 cluster_time = num;
2743                 break;
2744             }
2745
2746                 /* a group of blocks inside a cluster */
2747             case MATROSKA_ID_BLOCKGROUP:
2748                 if ((res = ebml_read_master(matroska, &id)) < 0)
2749                     break;
2750                 res = matroska_parse_blockgroup(matroska, cluster_time);
2751                 break;
2752
2753             case MATROSKA_ID_SIMPLEBLOCK:
2754                 pos = url_ftell(matroska->ctx->pb);
2755                 res = ebml_read_binary(matroska, &id, &data, &size);
2756                 if (res == 0)
2757                     res = matroska_parse_block(matroska, data, size, pos,
2758                                                cluster_time, AV_NOPTS_VALUE,
2759                                                -1);
2760                 break;
2761
2762             default:
2763                 av_log(matroska->ctx, AV_LOG_INFO,
2764                        "Unknown entry 0x%x in cluster data\n", id);
2765                 /* fall-through */
2766
2767             case EBML_ID_VOID:
2768                 res = ebml_read_skip(matroska);
2769                 break;
2770         }
2771
2772         if (matroska->level_up) {
2773             matroska->level_up--;
2774             break;
2775         }
2776     }
2777
2778     return res;
2779 }
2780
2781 static int
2782 matroska_read_packet (AVFormatContext *s,
2783                       AVPacket        *pkt)
2784 {
2785     MatroskaDemuxContext *matroska = s->priv_data;
2786     int res;
2787     uint32_t id;
2788
2789     /* Read stream until we have a packet queued. */
2790     while (matroska_deliver_packet(matroska, pkt)) {
2791
2792         /* Have we already reached the end? */
2793         if (matroska->done)
2794             return AVERROR(EIO);
2795
2796         res = 0;
2797         while (res == 0) {
2798             if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2799                 return AVERROR(EIO);
2800             } else if (matroska->level_up) {
2801                 matroska->level_up--;
2802                 break;
2803             }
2804
2805             switch (id) {
2806                 case MATROSKA_ID_CLUSTER:
2807                     if ((res = ebml_read_master(matroska, &id)) < 0)
2808                         break;
2809                     if ((res = matroska_parse_cluster(matroska)) == 0)
2810                         res = 1; /* Parsed one cluster, let's get out. */
2811                     break;
2812
2813                 default:
2814                 case EBML_ID_VOID:
2815                     res = ebml_read_skip(matroska);
2816                     break;
2817             }
2818
2819             if (matroska->level_up) {
2820                 matroska->level_up--;
2821                 break;
2822             }
2823         }
2824
2825         if (res == -1)
2826             matroska->done = 1;
2827     }
2828
2829     return 0;
2830 }
2831
2832 static int
2833 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2834                     int flags)
2835 {
2836     MatroskaDemuxContext *matroska = s->priv_data;
2837     AVStream *st = s->streams[stream_index];
2838     int index;
2839
2840     /* find index entry */
2841     index = av_index_search_timestamp(st, timestamp, flags);
2842     if (index < 0)
2843         return 0;
2844
2845     matroska_clear_queue(matroska);
2846
2847     /* do the seek */
2848     url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2849     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2850     matroska->skip_to_stream = st;
2851     matroska->peek_id = 0;
2852     av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2853     return 0;
2854 }
2855
2856 static int
2857 matroska_read_close (AVFormatContext *s)
2858 {
2859     MatroskaDemuxContext *matroska = s->priv_data;
2860     int n = 0;
2861
2862     matroska_clear_queue(matroska);
2863
2864     for (n = 0; n < matroska->num_tracks; n++) {
2865         MatroskaTrack *track = matroska->tracks[n];
2866         av_free(track->codec_id);
2867         av_free(track->codec_priv);
2868         av_free(track->name);
2869
2870         if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2871             MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2872             av_free(audiotrack->buf);
2873         }
2874
2875         av_free(track);
2876     }
2877     ebml_free(matroska_index, matroska);
2878
2879     return 0;
2880 }
2881
2882 AVInputFormat matroska_demuxer = {
2883     "matroska",
2884     NULL_IF_CONFIG_SMALL("Matroska file format"),
2885     sizeof(MatroskaDemuxContext),
2886     matroska_probe,
2887     matroska_read_header,
2888     matroska_read_packet,
2889     matroska_read_close,
2890     matroska_read_seek,
2891 };