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