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