]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
Add id to AVChapter, untested (where do i find matroska files with chapters?).
[ffmpeg] / libavformat / matroskadec.c
1 /*
2  * Matroska file demuxer (no muxer yet)
3  * Copyright (c) 2003-2004 The ffmpeg Project
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file matroskadec.c
24  * Matroska file demuxer
25  * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * Specs available on the matroska project page:
28  * http://www.matroska.org/.
29  */
30
31 #include "avformat.h"
32 /* For codec_get_id(). */
33 #include "riff.h"
34 #include "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             int64_t uid= -1;
2164             char* title = NULL;
2165             /* if there is more than one chapter edition
2166                we take only the first one */
2167             if(s->chapters) {
2168                     ebml_read_skip(matroska);
2169                     break;
2170             }
2171
2172             if ((res = ebml_read_master(matroska, &id)) < 0)
2173                 break;
2174
2175             while (res == 0) {
2176                 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2177                     res = AVERROR(EIO);
2178                     break;
2179                 } else if (matroska->level_up) {
2180                     matroska->level_up--;
2181                     break;
2182                 }
2183
2184                 switch (id) {
2185                 case MATROSKA_ID_CHAPTERATOM:
2186                     if ((res = ebml_read_master(matroska, &id)) < 0)
2187                         break;
2188
2189                     while (res == 0) {
2190                         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2191                             res = AVERROR(EIO);
2192                             break;
2193                         } else if (matroska->level_up) {
2194                             matroska->level_up--;
2195                             break;
2196                         }
2197
2198                         switch (id) {
2199                         case MATROSKA_ID_CHAPTERTIMEEND:
2200                             res = ebml_read_uint(matroska, &id, &end);
2201                             break;
2202
2203                         case MATROSKA_ID_CHAPTERTIMESTART:
2204                             res = ebml_read_uint(matroska, &id, &start);
2205                             break;
2206
2207                         case MATROSKA_ID_CHAPTERDISPLAY:
2208                             if ((res = ebml_read_master(matroska, &id)) < 0)
2209                                 break;
2210
2211                             while (res == 0) {
2212                                 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2213                                     res = AVERROR(EIO);
2214                                     break;
2215                                 } else if (matroska->level_up) {
2216                                     matroska->level_up--;
2217                                     break;
2218                                 }
2219
2220                                 switch (id) {
2221                                 case MATROSKA_ID_CHAPSTRING:
2222                                     res = ebml_read_utf8(matroska, &id, &title);
2223                                     break;
2224
2225                                 default:
2226                                     av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter display ID 0x%x\n", id);
2227                                 case EBML_ID_VOID:
2228                                     res = ebml_read_skip(matroska);
2229                                     break;
2230                                 }
2231
2232                                 if (matroska->level_up) {
2233                                     matroska->level_up--;
2234                                     break;
2235                                 }
2236                             }
2237                             break;
2238
2239                         case MATROSKA_ID_CHAPTERUID:
2240                             res = ebml_read_uint(matroska, &id, &uid);
2241                             break;
2242                         default:
2243                             av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter atom ID 0x%x\n", id);
2244                         case MATROSKA_ID_CHAPTERFLAGHIDDEN:
2245                         case EBML_ID_VOID:
2246                             res = ebml_read_skip(matroska);
2247                             break;
2248                         }
2249
2250                         if (matroska->level_up) {
2251                             matroska->level_up--;
2252                             break;
2253                         }
2254                     }
2255
2256                     if (start != AV_NOPTS_VALUE && uid != -1) {
2257                         start = start * AV_TIME_BASE / 1000000000;
2258                         if (end != AV_NOPTS_VALUE)
2259                             end = end * AV_TIME_BASE / 1000000000;
2260                         res = ff_new_chapter(s, uid, start, end, title);
2261                     }
2262                     av_free(title);
2263                     break;
2264
2265                 default:
2266                     av_log(s, AV_LOG_INFO, "Ignoring unknown Edition entry ID 0x%x\n", id);
2267                 case MATROSKA_ID_EDITIONUID:
2268                 case MATROSKA_ID_EDITIONFLAGHIDDEN:
2269                 case EBML_ID_VOID:
2270                     res = ebml_read_skip(matroska);
2271                     break;
2272                 }
2273
2274
2275                 if (matroska->level_up) {
2276                     matroska->level_up--;
2277                     break;
2278                 }
2279             }
2280         break;
2281         }
2282
2283         default:
2284             av_log(s, AV_LOG_INFO, "Expected an Edition entry (0x%x), but found 0x%x\n", MATROSKA_ID_EDITIONENTRY, id);
2285         case EBML_ID_VOID:
2286             res = ebml_read_skip(matroska);
2287             break;
2288         }
2289
2290         if (matroska->level_up) {
2291             matroska->level_up--;
2292             break;
2293         }
2294     }
2295
2296     return res;
2297 }
2298
2299 #define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
2300
2301 static int
2302 matroska_aac_profile (char *codec_id)
2303 {
2304     static const char *aac_profiles[] = {
2305         "MAIN", "LC", "SSR"
2306     };
2307     int profile;
2308
2309     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2310         if (strstr(codec_id, aac_profiles[profile]))
2311             break;
2312     return profile + 1;
2313 }
2314
2315 static int
2316 matroska_aac_sri (int samplerate)
2317 {
2318     int sri;
2319
2320     for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2321         if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2322             break;
2323     return sri;
2324 }
2325
2326 static int
2327 matroska_read_header (AVFormatContext    *s,
2328                       AVFormatParameters *ap)
2329 {
2330     MatroskaDemuxContext *matroska = s->priv_data;
2331     char *doctype;
2332     int version, last_level, res = 0;
2333     uint32_t id;
2334
2335     matroska->ctx = s;
2336
2337     /* First read the EBML header. */
2338     doctype = NULL;
2339     if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2340         return res;
2341     if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2342         av_log(matroska->ctx, AV_LOG_ERROR,
2343                "Wrong EBML doctype ('%s' != 'matroska').\n",
2344                doctype ? doctype : "(none)");
2345         if (doctype)
2346             av_free(doctype);
2347         return AVERROR_NOFMT;
2348     }
2349     av_free(doctype);
2350     if (version > 2) {
2351         av_log(matroska->ctx, AV_LOG_ERROR,
2352                "Matroska demuxer version 2 too old for file version %d\n",
2353                version);
2354         return AVERROR_NOFMT;
2355     }
2356
2357     /* The next thing is a segment. */
2358     while (1) {
2359         if (!(id = ebml_peek_id(matroska, &last_level)))
2360             return AVERROR(EIO);
2361         if (id == MATROSKA_ID_SEGMENT)
2362             break;
2363
2364         /* oi! */
2365         av_log(matroska->ctx, AV_LOG_INFO,
2366                "Expected a Segment ID (0x%x), but received 0x%x!\n",
2367                MATROSKA_ID_SEGMENT, id);
2368         if ((res = ebml_read_skip(matroska)) < 0)
2369             return res;
2370     }
2371
2372     /* We now have a Matroska segment.
2373      * Seeks are from the beginning of the segment,
2374      * after the segment ID/length. */
2375     if ((res = ebml_read_master(matroska, &id)) < 0)
2376         return res;
2377     matroska->segment_start = url_ftell(s->pb);
2378
2379     matroska->time_scale = 1000000;
2380     /* we've found our segment, start reading the different contents in here */
2381     while (res == 0) {
2382         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2383             res = AVERROR(EIO);
2384             break;
2385         } else if (matroska->level_up) {
2386             matroska->level_up--;
2387             break;
2388         }
2389
2390         switch (id) {
2391             /* stream info */
2392             case MATROSKA_ID_INFO: {
2393                 if ((res = ebml_read_master(matroska, &id)) < 0)
2394                     break;
2395                 res = matroska_parse_info(matroska);
2396                 break;
2397             }
2398
2399             /* track info headers */
2400             case MATROSKA_ID_TRACKS: {
2401                 if ((res = ebml_read_master(matroska, &id)) < 0)
2402                     break;
2403                 res = matroska_parse_tracks(matroska);
2404                 break;
2405             }
2406
2407             /* stream index */
2408             case MATROSKA_ID_CUES: {
2409                 if (!matroska->index_parsed) {
2410                     if ((res = ebml_read_master(matroska, &id)) < 0)
2411                         break;
2412                     res = matroska_parse_index(matroska);
2413                 } else
2414                     res = ebml_read_skip(matroska);
2415                 break;
2416             }
2417
2418             /* metadata */
2419             case MATROSKA_ID_TAGS: {
2420                 if (!matroska->metadata_parsed) {
2421                     if ((res = ebml_read_master(matroska, &id)) < 0)
2422                         break;
2423                     res = matroska_parse_metadata(matroska);
2424                 } else
2425                     res = ebml_read_skip(matroska);
2426                 break;
2427             }
2428
2429             /* file index (if seekable, seek to Cues/Tags to parse it) */
2430             case MATROSKA_ID_SEEKHEAD: {
2431                 if ((res = ebml_read_master(matroska, &id)) < 0)
2432                     break;
2433                 res = matroska_parse_seekhead(matroska);
2434                 break;
2435             }
2436
2437             case MATROSKA_ID_ATTACHMENTS: {
2438                 if ((res = ebml_read_master(matroska, &id)) < 0)
2439                     break;
2440                 res = matroska_parse_attachments(s);
2441                 break;
2442             }
2443
2444             case MATROSKA_ID_CLUSTER: {
2445                 /* Do not read the master - this will be done in the next
2446                  * call to matroska_read_packet. */
2447                 res = 1;
2448                 break;
2449             }
2450
2451             case MATROSKA_ID_CHAPTERS: {
2452                 if ((res = ebml_read_master(matroska, &id)) < 0)
2453                     return res;
2454                 res = matroska_parse_chapters(s);
2455                 break;
2456             }
2457
2458             default:
2459                 av_log(matroska->ctx, AV_LOG_INFO,
2460                        "Unknown matroska file header ID 0x%x\n", id);
2461             /* fall-through */
2462
2463             case EBML_ID_VOID:
2464                 res = ebml_read_skip(matroska);
2465                 break;
2466         }
2467
2468         if (matroska->level_up) {
2469             matroska->level_up--;
2470             break;
2471         }
2472     }
2473
2474     /* Have we found a cluster? */
2475     if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2476         int i, j;
2477         MatroskaTrack *track;
2478         AVStream *st;
2479
2480         for (i = 0; i < matroska->num_tracks; i++) {
2481             enum CodecID codec_id = CODEC_ID_NONE;
2482             uint8_t *extradata = NULL;
2483             int extradata_size = 0;
2484             int extradata_offset = 0;
2485             track = matroska->tracks[i];
2486             track->stream_index = -1;
2487
2488             /* Apply some sanity checks. */
2489             if (track->codec_id == NULL)
2490                 continue;
2491
2492             for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2493                 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2494                             strlen(ff_mkv_codec_tags[j].str))){
2495                     codec_id= ff_mkv_codec_tags[j].id;
2496                     break;
2497                 }
2498             }
2499
2500             /* Set the FourCC from the CodecID. */
2501             /* This is the MS compatibility mode which stores a
2502              * BITMAPINFOHEADER in the CodecPrivate. */
2503             if (!strcmp(track->codec_id,
2504                         MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2505                 (track->codec_priv_size >= 40) &&
2506                 (track->codec_priv != NULL)) {
2507                 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2508
2509                 /* Offset of biCompression. Stored in LE. */
2510                 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2511                 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2512
2513             }
2514
2515             /* This is the MS compatibility mode which stores a
2516              * WAVEFORMATEX in the CodecPrivate. */
2517             else if (!strcmp(track->codec_id,
2518                              MATROSKA_CODEC_ID_AUDIO_ACM) &&
2519                 (track->codec_priv_size >= 18) &&
2520                 (track->codec_priv != NULL)) {
2521                 uint16_t tag;
2522
2523                 /* Offset of wFormatTag. Stored in LE. */
2524                 tag = AV_RL16(track->codec_priv);
2525                 codec_id = codec_get_id(codec_wav_tags, tag);
2526
2527             }
2528
2529             else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2530                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2531                 int profile = matroska_aac_profile(track->codec_id);
2532                 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2533                 extradata = av_malloc(5);
2534                 if (extradata == NULL)
2535                     return AVERROR(ENOMEM);
2536                 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2537                 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2538                 if (strstr(track->codec_id, "SBR")) {
2539                     sri = matroska_aac_sri(audiotrack->samplerate);
2540                     extradata[2] = 0x56;
2541                     extradata[3] = 0xE5;
2542                     extradata[4] = 0x80 | (sri<<3);
2543                     extradata_size = 5;
2544                 } else {
2545                     extradata_size = 2;
2546                 }
2547             }
2548
2549             else if (codec_id == CODEC_ID_TTA) {
2550                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2551                 ByteIOContext b;
2552                 extradata_size = 30;
2553                 extradata = av_mallocz(extradata_size);
2554                 if (extradata == NULL)
2555                     return AVERROR(ENOMEM);
2556                 init_put_byte(&b, extradata, extradata_size, 1,
2557                               NULL, NULL, NULL, NULL);
2558                 put_buffer(&b, "TTA1", 4);
2559                 put_le16(&b, 1);
2560                 put_le16(&b, audiotrack->channels);
2561                 put_le16(&b, audiotrack->bitdepth);
2562                 put_le32(&b, audiotrack->samplerate);
2563                 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2564             }
2565
2566             else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2567                      codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2568                 extradata_offset = 26;
2569                 track->codec_priv_size -= extradata_offset;
2570             }
2571
2572             else if (codec_id == CODEC_ID_RA_144) {
2573                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2574                 audiotrack->samplerate = 8000;
2575                 audiotrack->channels = 1;
2576             }
2577
2578             else if (codec_id == CODEC_ID_RA_288 ||
2579                      codec_id == CODEC_ID_COOK ||
2580                      codec_id == CODEC_ID_ATRAC3) {
2581                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2582                 ByteIOContext b;
2583
2584                 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2585                               NULL, NULL, NULL, NULL);
2586                 url_fskip(&b, 24);
2587                 audiotrack->coded_framesize = get_be32(&b);
2588                 url_fskip(&b, 12);
2589                 audiotrack->sub_packet_h    = get_be16(&b);
2590                 audiotrack->frame_size      = get_be16(&b);
2591                 audiotrack->sub_packet_size = get_be16(&b);
2592                 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2593                 if (codec_id == CODEC_ID_RA_288) {
2594                     audiotrack->block_align = audiotrack->coded_framesize;
2595                     track->codec_priv_size = 0;
2596                 } else {
2597                     audiotrack->block_align = audiotrack->sub_packet_size;
2598                     extradata_offset = 78;
2599                     track->codec_priv_size -= extradata_offset;
2600                 }
2601             }
2602
2603             if (codec_id == CODEC_ID_NONE) {
2604                 av_log(matroska->ctx, AV_LOG_INFO,
2605                        "Unknown/unsupported CodecID %s.\n",
2606                        track->codec_id);
2607             }
2608
2609             track->stream_index = matroska->num_streams;
2610
2611             matroska->num_streams++;
2612             st = av_new_stream(s, track->stream_index);
2613             if (st == NULL)
2614                 return AVERROR(ENOMEM);
2615             av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2616
2617             st->codec->codec_id = codec_id;
2618             st->start_time = 0;
2619             if (strcmp(track->language, "und"))
2620                 strcpy(st->language, track->language);
2621
2622             if (track->flags & MATROSKA_TRACK_DEFAULT)
2623                 st->disposition |= AV_DISPOSITION_DEFAULT;
2624
2625             if (track->default_duration)
2626                 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2627                           track->default_duration, 1000000000, 30000);
2628
2629             if(extradata){
2630                 st->codec->extradata = extradata;
2631                 st->codec->extradata_size = extradata_size;
2632             } else if(track->codec_priv && track->codec_priv_size > 0){
2633                 st->codec->extradata = av_malloc(track->codec_priv_size);
2634                 if(st->codec->extradata == NULL)
2635                     return AVERROR(ENOMEM);
2636                 st->codec->extradata_size = track->codec_priv_size;
2637                 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2638                        track->codec_priv_size);
2639             }
2640
2641             if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2642                 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2643
2644                 st->codec->codec_type = CODEC_TYPE_VIDEO;
2645                 st->codec->codec_tag = videotrack->fourcc;
2646                 st->codec->width = videotrack->pixel_width;
2647                 st->codec->height = videotrack->pixel_height;
2648                 if (videotrack->display_width == 0)
2649                     videotrack->display_width= videotrack->pixel_width;
2650                 if (videotrack->display_height == 0)
2651                     videotrack->display_height= videotrack->pixel_height;
2652                 av_reduce(&st->codec->sample_aspect_ratio.num,
2653                           &st->codec->sample_aspect_ratio.den,
2654                           st->codec->height * videotrack->display_width,
2655                           st->codec-> width * videotrack->display_height,
2656                           255);
2657                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2658             } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2659                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2660
2661                 st->codec->codec_type = CODEC_TYPE_AUDIO;
2662                 st->codec->sample_rate = audiotrack->samplerate;
2663                 st->codec->channels = audiotrack->channels;
2664                 st->codec->block_align = audiotrack->block_align;
2665             } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2666                 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2667             }
2668
2669             /* What do we do with private data? E.g. for Vorbis. */
2670         }
2671         res = 0;
2672     }
2673
2674     if (matroska->index_parsed) {
2675         int i, track, stream;
2676         for (i=0; i<matroska->num_indexes; i++) {
2677             MatroskaDemuxIndex *idx = &matroska->index[i];
2678             track = matroska_find_track_by_num(matroska, idx->track);
2679             if (track < 0)  continue;
2680             stream = matroska->tracks[track]->stream_index;
2681             if (stream >= 0 && stream < matroska->ctx->nb_streams)
2682                 av_add_index_entry(matroska->ctx->streams[stream],
2683                                    idx->pos, idx->time/matroska->time_scale,
2684                                    0, 0, AVINDEX_KEYFRAME);
2685         }
2686     }
2687
2688     return res;
2689 }
2690
2691 static int
2692 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2693                      int64_t pos, uint64_t cluster_time, uint64_t duration,
2694                      int is_keyframe, int is_bframe)
2695 {
2696     int res = 0;
2697     int track;
2698     AVStream *st;
2699     AVPacket *pkt;
2700     uint8_t *origdata = data;
2701     int16_t block_time;
2702     uint32_t *lace_size = NULL;
2703     int n, flags, laces = 0;
2704     uint64_t num;
2705     int stream_index;
2706
2707     /* first byte(s): tracknum */
2708     if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2709         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2710         av_free(origdata);
2711         return res;
2712     }
2713     data += n;
2714     size -= n;
2715
2716     /* fetch track from num */
2717     track = matroska_find_track_by_num(matroska, num);
2718     if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2719         av_log(matroska->ctx, AV_LOG_INFO,
2720                "Invalid stream %d or size %u\n", track, size);
2721         av_free(origdata);
2722         return res;
2723     }
2724     stream_index = matroska->tracks[track]->stream_index;
2725     if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2726         av_free(origdata);
2727         return res;
2728     }
2729     st = matroska->ctx->streams[stream_index];
2730     if (st->discard >= AVDISCARD_ALL) {
2731         av_free(origdata);
2732         return res;
2733     }
2734     if (duration == AV_NOPTS_VALUE)
2735         duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2736
2737     /* block_time (relative to cluster time) */
2738     block_time = AV_RB16(data);
2739     data += 2;
2740     flags = *data++;
2741     size -= 3;
2742     if (is_keyframe == -1)
2743         is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2744
2745     if (matroska->skip_to_keyframe) {
2746         if (!is_keyframe || st != matroska->skip_to_stream) {
2747             av_free(origdata);
2748             return res;
2749         }
2750         matroska->skip_to_keyframe = 0;
2751     }
2752
2753     switch ((flags & 0x06) >> 1) {
2754         case 0x0: /* no lacing */
2755             laces = 1;
2756             lace_size = av_mallocz(sizeof(int));
2757             lace_size[0] = size;
2758             break;
2759
2760         case 0x1: /* xiph lacing */
2761         case 0x2: /* fixed-size lacing */
2762         case 0x3: /* EBML lacing */
2763             if (size == 0) {
2764                 res = -1;
2765                 break;
2766             }
2767             laces = (*data) + 1;
2768             data += 1;
2769             size -= 1;
2770             lace_size = av_mallocz(laces * sizeof(int));
2771
2772             switch ((flags & 0x06) >> 1) {
2773                 case 0x1: /* xiph lacing */ {
2774                     uint8_t temp;
2775                     uint32_t total = 0;
2776                     for (n = 0; res == 0 && n < laces - 1; n++) {
2777                         while (1) {
2778                             if (size == 0) {
2779                                 res = -1;
2780                                 break;
2781                             }
2782                             temp = *data;
2783                             lace_size[n] += temp;
2784                             data += 1;
2785                             size -= 1;
2786                             if (temp != 0xff)
2787                                 break;
2788                         }
2789                         total += lace_size[n];
2790                     }
2791                     lace_size[n] = size - total;
2792                     break;
2793                 }
2794
2795                 case 0x2: /* fixed-size lacing */
2796                     for (n = 0; n < laces; n++)
2797                         lace_size[n] = size / laces;
2798                     break;
2799
2800                 case 0x3: /* EBML lacing */ {
2801                     uint32_t total;
2802                     n = matroska_ebmlnum_uint(data, size, &num);
2803                     if (n < 0) {
2804                         av_log(matroska->ctx, AV_LOG_INFO,
2805                                "EBML block data error\n");
2806                         break;
2807                     }
2808                     data += n;
2809                     size -= n;
2810                     total = lace_size[0] = num;
2811                     for (n = 1; res == 0 && n < laces - 1; n++) {
2812                         int64_t snum;
2813                         int r;
2814                         r = matroska_ebmlnum_sint (data, size, &snum);
2815                         if (r < 0) {
2816                             av_log(matroska->ctx, AV_LOG_INFO,
2817                                    "EBML block data error\n");
2818                             break;
2819                         }
2820                         data += r;
2821                         size -= r;
2822                         lace_size[n] = lace_size[n - 1] + snum;
2823                         total += lace_size[n];
2824                     }
2825                     lace_size[n] = size - total;
2826                     break;
2827                 }
2828             }
2829             break;
2830     }
2831
2832     if (res == 0) {
2833         uint64_t timecode = AV_NOPTS_VALUE;
2834
2835         if (cluster_time != (uint64_t)-1
2836             && (block_time >= 0 || cluster_time >= -block_time))
2837             timecode = cluster_time + block_time;
2838
2839         for (n = 0; n < laces; n++) {
2840             if (st->codec->codec_id == CODEC_ID_RA_288 ||
2841                 st->codec->codec_id == CODEC_ID_COOK ||
2842                 st->codec->codec_id == CODEC_ID_ATRAC3) {
2843                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2844                 int a = st->codec->block_align;
2845                 int sps = audiotrack->sub_packet_size;
2846                 int cfs = audiotrack->coded_framesize;
2847                 int h = audiotrack->sub_packet_h;
2848                 int y = audiotrack->sub_packet_cnt;
2849                 int w = audiotrack->frame_size;
2850                 int x;
2851
2852                 if (!audiotrack->pkt_cnt) {
2853                     if (st->codec->codec_id == CODEC_ID_RA_288)
2854                         for (x=0; x<h/2; x++)
2855                             memcpy(audiotrack->buf+x*2*w+y*cfs,
2856                                    data+x*cfs, cfs);
2857                     else
2858                         for (x=0; x<w/sps; x++)
2859                             memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2860
2861                     if (++audiotrack->sub_packet_cnt >= h) {
2862                         audiotrack->sub_packet_cnt = 0;
2863                         audiotrack->pkt_cnt = h*w / a;
2864                     }
2865                 }
2866                 while (audiotrack->pkt_cnt) {
2867                     pkt = av_mallocz(sizeof(AVPacket));
2868                     av_new_packet(pkt, a);
2869                     memcpy(pkt->data, audiotrack->buf
2870                            + a * (h*w / a - audiotrack->pkt_cnt--), a);
2871                     pkt->pos = pos;
2872                     pkt->stream_index = stream_index;
2873                     matroska_queue_packet(matroska, pkt);
2874                 }
2875             } else {
2876                 int result, offset = 0, ilen, olen, pkt_size = lace_size[n];
2877                 uint8_t *pkt_data = data;
2878
2879                 if (matroska->tracks[track]->encoding_scope & 1) {
2880                     switch (matroska->tracks[track]->encoding_algo) {
2881                     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
2882                         offset = matroska->tracks[track]->encoding_settings_len;
2883                         break;
2884                     case MATROSKA_TRACK_ENCODING_COMP_LZO:
2885                         pkt_data = NULL;
2886                         do {
2887                             ilen = lace_size[n];
2888                             olen = pkt_size *= 3;
2889                             pkt_data = av_realloc(pkt_data,
2890                                                   pkt_size+LZO_OUTPUT_PADDING);
2891                             result = lzo1x_decode(pkt_data, &olen, data, &ilen);
2892                         } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
2893                         if (result) {
2894                             av_free(pkt_data);
2895                             continue;
2896                         }
2897                         pkt_size -= olen;
2898                         break;
2899 #ifdef CONFIG_ZLIB
2900                     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
2901                         z_stream zstream = {0};
2902                         pkt_data = NULL;
2903                         if (inflateInit(&zstream) != Z_OK)
2904                             continue;
2905                         zstream.next_in = data;
2906                         zstream.avail_in = lace_size[n];
2907                         do {
2908                             pkt_size *= 3;
2909                             pkt_data = av_realloc(pkt_data, pkt_size);
2910                             zstream.avail_out = pkt_size - zstream.total_out;
2911                             zstream.next_out = pkt_data + zstream.total_out;
2912                             result = inflate(&zstream, Z_NO_FLUSH);
2913                         } while (result==Z_OK && pkt_size<10000000);
2914                         pkt_size = zstream.total_out;
2915                         inflateEnd(&zstream);
2916                         if (result != Z_STREAM_END) {
2917                             av_free(pkt_data);
2918                             continue;
2919                         }
2920                         break;
2921                     }
2922 #endif
2923 #ifdef CONFIG_BZLIB
2924                     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
2925                         bz_stream bzstream = {0};
2926                         pkt_data = NULL;
2927                         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
2928                             continue;
2929                         bzstream.next_in = data;
2930                         bzstream.avail_in = lace_size[n];
2931                         do {
2932                             pkt_size *= 3;
2933                             pkt_data = av_realloc(pkt_data, pkt_size);
2934                             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
2935                             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
2936                             result = BZ2_bzDecompress(&bzstream);
2937                         } while (result==BZ_OK && pkt_size<10000000);
2938                         pkt_size = bzstream.total_out_lo32;
2939                         BZ2_bzDecompressEnd(&bzstream);
2940                         if (result != BZ_STREAM_END) {
2941                             av_free(pkt_data);
2942                             continue;
2943                         }
2944                         break;
2945                     }
2946 #endif
2947                     }
2948                 }
2949
2950                 pkt = av_mallocz(sizeof(AVPacket));
2951                 /* XXX: prevent data copy... */
2952                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
2953                     res = AVERROR(ENOMEM);
2954                     n = laces-1;
2955                     break;
2956                 }
2957                 if (offset)
2958                     memcpy (pkt->data, matroska->tracks[track]->encoding_settings, offset);
2959                 memcpy (pkt->data+offset, pkt_data, pkt_size);
2960
2961                 if (n == 0)
2962                     pkt->flags = is_keyframe;
2963                 pkt->stream_index = stream_index;
2964
2965                 pkt->pts = timecode;
2966                 pkt->pos = pos;
2967                 pkt->duration = duration;
2968
2969                 matroska_queue_packet(matroska, pkt);
2970             }
2971
2972             if (timecode != AV_NOPTS_VALUE)
2973                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2974             data += lace_size[n];
2975         }
2976     }
2977
2978     av_free(lace_size);
2979     av_free(origdata);
2980     return res;
2981 }
2982
2983 static int
2984 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2985                            uint64_t              cluster_time)
2986 {
2987     int res = 0;
2988     uint32_t id;
2989     int is_bframe = 0;
2990     int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2991     uint64_t duration = AV_NOPTS_VALUE;
2992     uint8_t *data;
2993     int size = 0;
2994     int64_t pos = 0;
2995
2996     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2997
2998     while (res == 0) {
2999         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3000             res = AVERROR(EIO);
3001             break;
3002         } else if (matroska->level_up) {
3003             matroska->level_up--;
3004             break;
3005         }
3006
3007         switch (id) {
3008             /* one block inside the group. Note, block parsing is one
3009              * of the harder things, so this code is a bit complicated.
3010              * See http://www.matroska.org/ for documentation. */
3011             case MATROSKA_ID_BLOCK: {
3012                 pos = url_ftell(matroska->ctx->pb);
3013                 res = ebml_read_binary(matroska, &id, &data, &size);
3014                 break;
3015             }
3016
3017             case MATROSKA_ID_BLOCKDURATION: {
3018                 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
3019                     break;
3020                 break;
3021             }
3022
3023             case MATROSKA_ID_BLOCKREFERENCE: {
3024                 int64_t num;
3025                 /* We've found a reference, so not even the first frame in
3026                  * the lace is a key frame. */
3027                 is_keyframe = 0;
3028                 if (last_num_packets != matroska->num_packets)
3029                     matroska->packets[last_num_packets]->flags = 0;
3030                 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
3031                     break;
3032                 if (num > 0)
3033                     is_bframe = 1;
3034                 break;
3035             }
3036
3037             default:
3038                 av_log(matroska->ctx, AV_LOG_INFO,
3039                        "Unknown entry 0x%x in blockgroup data\n", id);
3040                 /* fall-through */
3041
3042             case EBML_ID_VOID:
3043                 res = ebml_read_skip(matroska);
3044                 break;
3045         }
3046
3047         if (matroska->level_up) {
3048             matroska->level_up--;
3049             break;
3050         }
3051     }
3052
3053     if (res)
3054         return res;
3055
3056     if (size > 0)
3057         res = matroska_parse_block(matroska, data, size, pos, cluster_time,
3058                                    duration, is_keyframe, is_bframe);
3059
3060     return res;
3061 }
3062
3063 static int
3064 matroska_parse_cluster (MatroskaDemuxContext *matroska)
3065 {
3066     int res = 0;
3067     uint32_t id;
3068     uint64_t cluster_time = 0;
3069     uint8_t *data;
3070     int64_t pos;
3071     int size;
3072
3073     av_log(matroska->ctx, AV_LOG_DEBUG,
3074            "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
3075
3076     while (res == 0) {
3077         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3078             res = AVERROR(EIO);
3079             break;
3080         } else if (matroska->level_up) {
3081             matroska->level_up--;
3082             break;
3083         }
3084
3085         switch (id) {
3086             /* cluster timecode */
3087             case MATROSKA_ID_CLUSTERTIMECODE: {
3088                 uint64_t num;
3089                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
3090                     break;
3091                 cluster_time = num;
3092                 break;
3093             }
3094
3095                 /* a group of blocks inside a cluster */
3096             case MATROSKA_ID_BLOCKGROUP:
3097                 if ((res = ebml_read_master(matroska, &id)) < 0)
3098                     break;
3099                 res = matroska_parse_blockgroup(matroska, cluster_time);
3100                 break;
3101
3102             case MATROSKA_ID_SIMPLEBLOCK:
3103                 pos = url_ftell(matroska->ctx->pb);
3104                 res = ebml_read_binary(matroska, &id, &data, &size);
3105                 if (res == 0)
3106                     res = matroska_parse_block(matroska, data, size, pos,
3107                                                cluster_time, AV_NOPTS_VALUE,
3108                                                -1, 0);
3109                 break;
3110
3111             default:
3112                 av_log(matroska->ctx, AV_LOG_INFO,
3113                        "Unknown entry 0x%x in cluster data\n", id);
3114                 /* fall-through */
3115
3116             case EBML_ID_VOID:
3117                 res = ebml_read_skip(matroska);
3118                 break;
3119         }
3120
3121         if (matroska->level_up) {
3122             matroska->level_up--;
3123             break;
3124         }
3125     }
3126
3127     return res;
3128 }
3129
3130 static int
3131 matroska_read_packet (AVFormatContext *s,
3132                       AVPacket        *pkt)
3133 {
3134     MatroskaDemuxContext *matroska = s->priv_data;
3135     int res;
3136     uint32_t id;
3137
3138     /* Read stream until we have a packet queued. */
3139     while (matroska_deliver_packet(matroska, pkt)) {
3140
3141         /* Have we already reached the end? */
3142         if (matroska->done)
3143             return AVERROR(EIO);
3144
3145         res = 0;
3146         while (res == 0) {
3147             if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3148                 return AVERROR(EIO);
3149             } else if (matroska->level_up) {
3150                 matroska->level_up--;
3151                 break;
3152             }
3153
3154             switch (id) {
3155                 case MATROSKA_ID_CLUSTER:
3156                     if ((res = ebml_read_master(matroska, &id)) < 0)
3157                         break;
3158                     if ((res = matroska_parse_cluster(matroska)) == 0)
3159                         res = 1; /* Parsed one cluster, let's get out. */
3160                     break;
3161
3162                 default:
3163                 case EBML_ID_VOID:
3164                     res = ebml_read_skip(matroska);
3165                     break;
3166             }
3167
3168             if (matroska->level_up) {
3169                 matroska->level_up--;
3170                 break;
3171             }
3172         }
3173
3174         if (res == -1)
3175             matroska->done = 1;
3176     }
3177
3178     return 0;
3179 }
3180
3181 static int
3182 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
3183                     int flags)
3184 {
3185     MatroskaDemuxContext *matroska = s->priv_data;
3186     AVStream *st = s->streams[stream_index];
3187     int index;
3188
3189     /* find index entry */
3190     index = av_index_search_timestamp(st, timestamp, flags);
3191     if (index < 0)
3192         return 0;
3193
3194     matroska_clear_queue(matroska);
3195
3196     /* do the seek */
3197     url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
3198     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
3199     matroska->skip_to_stream = st;
3200     matroska->peek_id = 0;
3201     return 0;
3202 }
3203
3204 static int
3205 matroska_read_close (AVFormatContext *s)
3206 {
3207     MatroskaDemuxContext *matroska = s->priv_data;
3208     int n = 0;
3209
3210     av_free(matroska->writing_app);
3211     av_free(matroska->muxing_app);
3212     av_free(matroska->index);
3213
3214     matroska_clear_queue(matroska);
3215
3216     for (n = 0; n < matroska->num_tracks; n++) {
3217         MatroskaTrack *track = matroska->tracks[n];
3218         av_free(track->codec_id);
3219         av_free(track->codec_name);
3220         av_free(track->codec_priv);
3221         av_free(track->name);
3222
3223         if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
3224             MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
3225             av_free(audiotrack->buf);
3226         }
3227
3228         av_free(track);
3229     }
3230
3231     return 0;
3232 }
3233
3234 AVInputFormat matroska_demuxer = {
3235     "matroska",
3236     "Matroska file format",
3237     sizeof(MatroskaDemuxContext),
3238     matroska_probe,
3239     matroska_read_header,
3240     matroska_read_packet,
3241     matroska_read_close,
3242     matroska_read_seek,
3243 };