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