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