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