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