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