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