add support for AAC 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_SHIFT   = (1<<16)
180 } MatroskaTrackFlags;
181
182 typedef enum {
183   MATROSKA_VIDEOTRACK_INTERLACED = (MATROSKA_TRACK_SHIFT<<0)
184 } MatroskaVideoTrackFlags;
185
186 /*
187  * Matroska Codec IDs. Strings.
188  */
189
190 typedef struct CodecTags{
191     const char *str;
192     enum CodecID id;
193 }CodecTags;
194
195 #define MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC   "V_MS/VFW/FOURCC"
196 #define MATROSKA_CODEC_ID_AUDIO_ACM          "A_MS/ACM"
197
198 static CodecTags codec_tags[]={
199 //    {"V_MS/VFW/FOURCC"  , CODEC_ID_NONE},
200     {"V_UNCOMPRESSED"   , CODEC_ID_RAWVIDEO},
201     {"V_MPEG4/ISO/SP"   , CODEC_ID_MPEG4},
202     {"V_MPEG4/ISO/ASP"  , CODEC_ID_MPEG4},
203     {"V_MPEG4/ISO/AP"   , CODEC_ID_MPEG4},
204     {"V_MPEG4/ISO/AVC"  , CODEC_ID_H264},
205     {"V_MPEG4/MS/V3"    , CODEC_ID_MSMPEG4V3},
206     {"V_MPEG1"          , CODEC_ID_MPEG1VIDEO},
207     {"V_MPEG2"          , CODEC_ID_MPEG2VIDEO},
208     {"V_MJPEG"          , CODEC_ID_MJPEG},
209     {"V_REAL/RV10"      , CODEC_ID_RV10},
210     {"V_REAL/RV20"      , CODEC_ID_RV20},
211     {"V_REAL/RV30"      , CODEC_ID_RV30},
212     {"V_REAL/RV40"      , CODEC_ID_RV40},
213 /* TODO: Real/Quicktime */
214
215 //    {"A_MS/ACM"         , CODEC_ID_NONE},
216     {"A_MPEG/L1"        , CODEC_ID_MP3},
217     {"A_MPEG/L2"        , CODEC_ID_MP3},
218     {"A_MPEG/L3"        , CODEC_ID_MP3},
219     {"A_PCM/INT/BIG"    , CODEC_ID_PCM_U16BE},
220     {"A_PCM/INT/LIT"    , CODEC_ID_PCM_U16LE},
221 //    {"A_PCM/FLOAT/IEEE" , CODEC_ID_NONE},
222     {"A_AC3"            , CODEC_ID_AC3},
223     {"A_DTS"            , CODEC_ID_DTS},
224     {"A_VORBIS"         , CODEC_ID_VORBIS},
225     {"A_AAC/MPEG2/"     , CODEC_ID_AAC},
226     {"A_AAC/MPEG4/"     , CODEC_ID_MPEG4AAC},
227     {"A_WAVPACK4"       , CODEC_ID_WAVPACK},
228     {NULL               , CODEC_ID_NONE}
229 /* TODO: AC3-9/10 (?), Real, Musepack, Quicktime */
230 };
231
232 /* max. depth in the EBML tree structure */
233 #define EBML_MAX_DEPTH 16
234
235 typedef struct Track {
236     MatroskaTrackType type;
237
238     /* Unique track number and track ID. stream_index is the index that
239      * the calling app uses for this track. */
240     uint32_t num,
241         uid,
242         stream_index;
243
244     char *name,
245         *language;
246
247     char *codec_id,
248         *codec_name;
249
250     unsigned char *codec_priv;
251     int codec_priv_size;
252
253     int64_t default_duration;
254     MatroskaTrackFlags flags;
255 } MatroskaTrack;
256
257 typedef struct MatroskaVideoTrack {
258     MatroskaTrack track;
259
260     int pixel_width,
261         pixel_height,
262         display_width,
263         display_height;
264
265     uint32_t fourcc;
266
267     MatroskaAspectRatioMode ar_mode;
268     MatroskaEyeMode eye_mode;
269
270     //..
271 } MatroskaVideoTrack;
272
273 typedef struct MatroskaAudioTrack {
274     MatroskaTrack track;
275
276     int channels,
277         bitdepth,
278         internal_samplerate,
279         samplerate;
280     //..
281 } MatroskaAudioTrack;
282
283 typedef struct MatroskaSubtitleTrack {
284     MatroskaTrack track;
285
286     //..
287 } MatroskaSubtitleTrack;
288
289 typedef struct MatroskaLevel {
290     uint64_t start, length;
291 } MatroskaLevel;
292
293 typedef struct MatroskaDemuxIndex {
294   uint64_t        pos;   /* of the corresponding *cluster*! */
295   uint16_t        track; /* reference to 'num' */
296   uint64_t        time;  /* in nanoseconds */
297 } MatroskaDemuxIndex;
298
299 typedef struct MatroskaDemuxContext {
300     AVFormatContext *ctx;
301
302     /* ebml stuff */
303     int num_levels;
304     MatroskaLevel levels[EBML_MAX_DEPTH];
305     int level_up;
306
307     /* matroska stuff */
308     char *writing_app,
309         *muxing_app;
310     int64_t created;
311
312     /* timescale in the file */
313     int64_t time_scale;
314
315     /* position (time, ns) */
316     int64_t pos;
317
318     /* num_streams is the number of streams that av_new_stream() was called
319      * for ( = that are available to the calling program). */
320     int num_tracks, num_streams;
321     MatroskaTrack *tracks[MAX_STREAMS];
322
323     /* cache for ID peeking */
324     uint32_t peek_id;
325
326     /* byte position of the segment inside the stream */
327     offset_t segment_start;
328
329     /* The packet queue. */
330     AVPacket **packets;
331     int num_packets;
332
333     /* have we already parse metadata/cues/clusters? */
334     int metadata_parsed,
335         index_parsed,
336         done;
337
338     /* The index for seeking. */
339     int num_indexes;
340     MatroskaDemuxIndex *index;
341 } MatroskaDemuxContext;
342
343 /*
344  * The first few functions handle EBML file parsing. The rest
345  * is the document interpretation. Matroska really just is a
346  * EBML file.
347  */
348
349 /*
350  * Return: the amount of levels in the hierarchy that the
351  * current element lies higher than the previous one.
352  * The opposite isn't done - that's auto-done using master
353  * element reading.
354  */
355
356 static int
357 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
358 {
359     ByteIOContext *pb = &matroska->ctx->pb;
360     offset_t pos = url_ftell(pb);
361     int num = 0;
362
363     while (matroska->num_levels > 0) {
364         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
365
366         if (pos >= level->start + level->length) {
367             matroska->num_levels--;
368             num++;
369         } else {
370             break;
371         }
372     }
373
374     return num;
375 }
376
377 /*
378  * Read: an "EBML number", which is defined as a variable-length
379  * array of bytes. The first byte indicates the length by giving a
380  * number of 0-bits followed by a one. The position of the first
381  * "one" bit inside the first byte indicates the length of this
382  * number.
383  * Returns: num. of bytes read. < 0 on error.
384  */
385
386 static int
387 ebml_read_num (MatroskaDemuxContext *matroska,
388                int                   max_size,
389                uint64_t             *number)
390 {
391     ByteIOContext *pb = &matroska->ctx->pb;
392     int len_mask = 0x80, read = 1, n = 1;
393     int64_t total = 0;
394
395     /* the first byte tells us the length in bytes - get_byte() can normally
396      * return 0, but since that's not a valid first ebmlID byte, we can
397      * use it safely here to catch EOS. */
398     if (!(total = get_byte(pb))) {
399         /* we might encounter EOS here */
400         if (!url_feof(pb)) {
401             offset_t pos = url_ftell(pb);
402             av_log(matroska->ctx, AV_LOG_ERROR,
403                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
404                    pos, pos);
405         }
406         return AVERROR_IO; /* EOS or actual I/O error */
407     }
408
409     /* get the length of the EBML number */
410     while (read <= max_size && !(total & len_mask)) {
411         read++;
412         len_mask >>= 1;
413     }
414     if (read > max_size) {
415         offset_t pos = url_ftell(pb) - 1;
416         av_log(matroska->ctx, AV_LOG_ERROR,
417                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
418                (uint8_t) total, pos, pos);
419         return AVERROR_INVALIDDATA;
420     }
421
422     /* read out length */
423     total &= ~len_mask;
424     while (n++ < read)
425         total = (total << 8) | get_byte(pb);
426
427     *number = total;
428
429     return read;
430 }
431
432 /*
433  * Read: the element content data ID.
434  * Return: the number of bytes read or < 0 on error.
435  */
436
437 static int
438 ebml_read_element_id (MatroskaDemuxContext *matroska,
439                       uint32_t             *id,
440                       int                  *level_up)
441 {
442     int read;
443     uint64_t total;
444
445     /* if we re-call this, use our cached ID */
446     if (matroska->peek_id != 0) {
447         if (level_up)
448             *level_up = 0;
449         *id = matroska->peek_id;
450         return 0;
451     }
452
453     /* read out the "EBML number", include tag in ID */
454     if ((read = ebml_read_num(matroska, 4, &total)) < 0)
455         return read;
456     *id = matroska->peek_id  = total | (1 << (read * 7));
457
458     /* level tracking */
459     if (level_up)
460         *level_up = ebml_read_element_level_up(matroska);
461
462     return read;
463 }
464
465 /*
466  * Read: element content length.
467  * Return: the number of bytes read or < 0 on error.
468  */
469
470 static int
471 ebml_read_element_length (MatroskaDemuxContext *matroska,
472                           uint64_t             *length)
473 {
474     /* clear cache since we're now beyond that data point */
475     matroska->peek_id = 0;
476
477     /* read out the "EBML number", include tag in ID */
478     return ebml_read_num(matroska, 8, length);
479 }
480
481 /*
482  * Return: the ID of the next element, or 0 on error.
483  * Level_up contains the amount of levels that this
484  * next element lies higher than the previous one.
485  */
486
487 static uint32_t
488 ebml_peek_id (MatroskaDemuxContext *matroska,
489               int                  *level_up)
490 {
491     uint32_t id;
492
493     assert(level_up != NULL);
494
495     if (ebml_read_element_id(matroska, &id, level_up) < 0)
496         return 0;
497
498     return id;
499 }
500
501 /*
502  * Seek to a given offset.
503  * 0 is success, -1 is failure.
504  */
505
506 static int
507 ebml_read_seek (MatroskaDemuxContext *matroska,
508                 offset_t              offset)
509 {
510     ByteIOContext *pb = &matroska->ctx->pb;
511
512     /* clear ID cache, if any */
513     matroska->peek_id = 0;
514
515     return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
516 }
517
518 /*
519  * Skip the next element.
520  * 0 is success, -1 is failure.
521  */
522
523 static int
524 ebml_read_skip (MatroskaDemuxContext *matroska)
525 {
526     ByteIOContext *pb = &matroska->ctx->pb;
527     uint32_t id;
528     uint64_t length;
529     int res;
530
531     if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
532         (res = ebml_read_element_length(matroska, &length)) < 0)
533         return res;
534
535     url_fskip(pb, length);
536
537     return 0;
538 }
539
540 /*
541  * Read the next element as an unsigned int.
542  * 0 is success, < 0 is failure.
543  */
544
545 static int
546 ebml_read_uint (MatroskaDemuxContext *matroska,
547                 uint32_t             *id,
548                 uint64_t             *num)
549 {
550     ByteIOContext *pb = &matroska->ctx->pb;
551     int n = 0, size, res;
552     uint64_t rlength;
553
554     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
555         (res = ebml_read_element_length(matroska, &rlength)) < 0)
556         return res;
557     size = rlength;
558     if (size < 1 || size > 8) {
559         offset_t pos = url_ftell(pb);
560         av_log(matroska->ctx, AV_LOG_ERROR,
561                "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
562                 size, pos, pos);
563         return AVERROR_INVALIDDATA;
564     }
565
566     /* big-endian ordening; build up number */
567     *num = 0;
568     while (n++ < size)
569         *num = (*num << 8) | get_byte(pb);
570
571     return 0;
572 }
573
574 /*
575  * Read the next element as a signed int.
576  * 0 is success, < 0 is failure.
577  */
578
579 static int
580 ebml_read_sint (MatroskaDemuxContext *matroska,
581                 uint32_t             *id,
582                 int64_t              *num)
583 {
584     ByteIOContext *pb = &matroska->ctx->pb;
585     int size, n = 1, negative = 0, res;
586     uint64_t rlength;
587
588     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
589         (res = ebml_read_element_length(matroska, &rlength)) < 0)
590         return res;
591     size = rlength;
592     if (size < 1 || size > 8) {
593         offset_t pos = url_ftell(pb);
594         av_log(matroska->ctx, AV_LOG_ERROR,
595                "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
596                 size, pos, pos);
597         return AVERROR_INVALIDDATA;
598     }
599     if ((*num = get_byte(pb)) & 0x80) {
600         negative = 1;
601         *num &= ~0x80;
602     }
603     *num = 0;
604     while (n++ < size)
605         *num = (*num << 8) | get_byte(pb);
606
607     /* make signed */
608     if (negative)
609         *num = *num - (1LL << ((8 * size) - 1));
610
611     return 0;
612 }
613
614 /*
615  * Read the next element as a float.
616  * 0 is success, < 0 is failure.
617  */
618
619 static int
620 ebml_read_float (MatroskaDemuxContext *matroska,
621                  uint32_t             *id,
622                  double               *num)
623 {
624     ByteIOContext *pb = &matroska->ctx->pb;
625     int size, res;
626     uint64_t rlength;
627
628     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
629         (res = ebml_read_element_length(matroska, &rlength)) < 0)
630         return res;
631     size = rlength;
632
633     if (size == 4) {
634         *num= av_int2flt(get_be32(pb));
635     } else if(size==8){
636         *num= av_int2dbl(get_be64(pb));
637     } else{
638         offset_t pos = url_ftell(pb);
639         av_log(matroska->ctx, AV_LOG_ERROR,
640                "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
641                size, pos, pos);
642         return AVERROR_INVALIDDATA;
643     }
644
645     return 0;
646 }
647
648 /*
649  * Read the next element as an ASCII string.
650  * 0 is success, < 0 is failure.
651  */
652
653 static int
654 ebml_read_ascii (MatroskaDemuxContext *matroska,
655                  uint32_t             *id,
656                  char                **str)
657 {
658     ByteIOContext *pb = &matroska->ctx->pb;
659     int size, res;
660     uint64_t rlength;
661
662     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
663         (res = ebml_read_element_length(matroska, &rlength)) < 0)
664         return res;
665     size = rlength;
666
667     /* ebml strings are usually not 0-terminated, so we allocate one
668      * byte more, read the string and NULL-terminate it ourselves. */
669     if (size < 0 || !(*str = av_malloc(size + 1))) {
670         av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
671         return AVERROR_NOMEM;
672     }
673     if (get_buffer(pb, (uint8_t *) *str, size) != size) {
674         offset_t pos = url_ftell(pb);
675         av_log(matroska->ctx, AV_LOG_ERROR,
676                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
677         return AVERROR_IO;
678     }
679     (*str)[size] = '\0';
680
681     return 0;
682 }
683
684 /*
685  * Read the next element as a UTF-8 string.
686  * 0 is success, < 0 is failure.
687  */
688
689 static int
690 ebml_read_utf8 (MatroskaDemuxContext *matroska,
691                 uint32_t             *id,
692                 char                **str)
693 {
694   return ebml_read_ascii(matroska, id, str);
695 }
696
697 /*
698  * Read the next element as a date (nanoseconds since 1/1/2000).
699  * 0 is success, < 0 is failure.
700  */
701
702 static int
703 ebml_read_date (MatroskaDemuxContext *matroska,
704                 uint32_t             *id,
705                 int64_t              *date)
706 {
707   return ebml_read_sint(matroska, id, date);
708 }
709
710 /*
711  * Read the next element, but only the header. The contents
712  * are supposed to be sub-elements which can be read separately.
713  * 0 is success, < 0 is failure.
714  */
715
716 static int
717 ebml_read_master (MatroskaDemuxContext *matroska,
718                   uint32_t             *id)
719 {
720     ByteIOContext *pb = &matroska->ctx->pb;
721     uint64_t length;
722     MatroskaLevel *level;
723     int res;
724
725     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
726         (res = ebml_read_element_length(matroska, &length)) < 0)
727         return res;
728
729     /* protect... (Heaven forbids that the '>' is true) */
730     if (matroska->num_levels >= EBML_MAX_DEPTH) {
731         av_log(matroska->ctx, AV_LOG_ERROR,
732                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
733         return AVERROR_NOTSUPP;
734     }
735
736     /* remember level */
737     level = &matroska->levels[matroska->num_levels++];
738     level->start = url_ftell(pb);
739     level->length = length;
740
741     return 0;
742 }
743
744 /*
745  * Read the next element as binary data.
746  * 0 is success, < 0 is failure.
747  */
748
749 static int
750 ebml_read_binary (MatroskaDemuxContext *matroska,
751                   uint32_t             *id,
752                   uint8_t             **binary,
753                   int                  *size)
754 {
755     ByteIOContext *pb = &matroska->ctx->pb;
756     uint64_t rlength;
757     int res;
758
759     if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
760         (res = ebml_read_element_length(matroska, &rlength)) < 0)
761         return res;
762     *size = rlength;
763
764     if (!(*binary = av_malloc(*size))) {
765         av_log(matroska->ctx, AV_LOG_ERROR,
766                "Memory allocation error\n");
767         return AVERROR_NOMEM;
768     }
769
770     if (get_buffer(pb, *binary, *size) != *size) {
771         offset_t pos = url_ftell(pb);
772         av_log(matroska->ctx, AV_LOG_ERROR,
773                "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
774         return AVERROR_IO;
775     }
776
777     return 0;
778 }
779
780 /*
781  * Read signed/unsigned "EBML" numbers.
782  * Return: number of bytes processed, < 0 on error.
783  * XXX: use ebml_read_num().
784  */
785
786 static int
787 matroska_ebmlnum_uint (uint8_t  *data,
788                        uint32_t  size,
789                        uint64_t *num)
790 {
791     int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
792     uint64_t total;
793
794     if (size <= 0)
795         return AVERROR_INVALIDDATA;
796
797     total = data[0];
798     while (read <= 8 && !(total & len_mask)) {
799         read++;
800         len_mask >>= 1;
801     }
802     if (read > 8)
803         return AVERROR_INVALIDDATA;
804
805     if ((total &= (len_mask - 1)) == len_mask - 1)
806         num_ffs++;
807     if (size < read)
808         return AVERROR_INVALIDDATA;
809     while (n < read) {
810         if (data[n] == 0xff)
811             num_ffs++;
812         total = (total << 8) | data[n];
813         n++;
814     }
815
816     if (read == num_ffs)
817         *num = (uint64_t)-1;
818     else
819         *num = total;
820
821     return read;
822 }
823
824 /*
825  * Same as above, but signed.
826  */
827
828 static int
829 matroska_ebmlnum_sint (uint8_t  *data,
830                        uint32_t  size,
831                        int64_t  *num)
832 {
833     uint64_t unum;
834     int res;
835
836     /* read as unsigned number first */
837     if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
838         return res;
839
840     /* make signed (weird way) */
841     if (unum == (uint64_t)-1)
842         *num = INT64_MAX;
843     else
844         *num = unum - ((1LL << ((7 * res) - 1)) - 1);
845
846     return res;
847 }
848
849 /*
850  * Read an EBML header.
851  * 0 is success, < 0 is failure.
852  */
853
854 static int
855 ebml_read_header (MatroskaDemuxContext *matroska,
856                   char                **doctype,
857                   int                  *version)
858 {
859     uint32_t id;
860     int level_up, res = 0;
861
862     /* default init */
863     if (doctype)
864         *doctype = NULL;
865     if (version)
866         *version = 1;
867
868     if (!(id = ebml_peek_id(matroska, &level_up)) ||
869         level_up != 0 || id != EBML_ID_HEADER) {
870         av_log(matroska->ctx, AV_LOG_ERROR,
871                "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
872         return AVERROR_INVALIDDATA;
873     }
874     if ((res = ebml_read_master(matroska, &id)) < 0)
875         return res;
876
877     while (res == 0) {
878         if (!(id = ebml_peek_id(matroska, &level_up)))
879             return AVERROR_IO;
880
881         /* end-of-header */
882         if (level_up)
883             break;
884
885         switch (id) {
886             /* is our read version uptodate? */
887             case EBML_ID_EBMLREADVERSION: {
888                 uint64_t num;
889
890                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
891                     return res;
892                 if (num > EBML_VERSION) {
893                     av_log(matroska->ctx, AV_LOG_ERROR,
894                            "EBML version %"PRIu64" (> %d) is not supported\n",
895                            num, EBML_VERSION);
896                     return AVERROR_INVALIDDATA;
897                 }
898                 break;
899             }
900
901             /* we only handle 8 byte lengths at max */
902             case EBML_ID_EBMLMAXSIZELENGTH: {
903                 uint64_t num;
904
905                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
906                     return res;
907                 if (num > sizeof(uint64_t)) {
908                     av_log(matroska->ctx, AV_LOG_ERROR,
909                            "Integers of size %"PRIu64" (> %zd) not supported\n",
910                            num, sizeof(uint64_t));
911                     return AVERROR_INVALIDDATA;
912                 }
913                 break;
914             }
915
916             /* we handle 4 byte IDs at max */
917             case EBML_ID_EBMLMAXIDLENGTH: {
918                 uint64_t num;
919
920                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
921                     return res;
922                 if (num > sizeof(uint32_t)) {
923                     av_log(matroska->ctx, AV_LOG_ERROR,
924                            "IDs of size %"PRIu64" (> %zu) not supported\n",
925                             num, sizeof(uint32_t));
926                     return AVERROR_INVALIDDATA;
927                 }
928                 break;
929             }
930
931             case EBML_ID_DOCTYPE: {
932                 char *text;
933
934                 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
935                     return res;
936                 if (doctype) {
937                     if (*doctype)
938                         av_free(*doctype);
939                     *doctype = text;
940                 } else
941                     av_free(text);
942                 break;
943             }
944
945             case EBML_ID_DOCTYPEREADVERSION: {
946                 uint64_t num;
947
948                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
949                     return res;
950                 if (version)
951                     *version = num;
952                 break;
953             }
954
955             default:
956                 av_log(matroska->ctx, AV_LOG_INFO,
957                        "Unknown data type 0x%x in EBML header", id);
958                 /* pass-through */
959
960             case EBML_ID_VOID:
961             /* we ignore these two, as they don't tell us anything we
962              * care about */
963             case EBML_ID_EBMLVERSION:
964             case EBML_ID_DOCTYPEVERSION:
965                 res = ebml_read_skip (matroska);
966                 break;
967         }
968     }
969
970     return 0;
971 }
972
973 /*
974  * Put one packet in an application-supplied AVPacket struct.
975  * Returns 0 on success or -1 on failure.
976  */
977
978 static int
979 matroska_deliver_packet (MatroskaDemuxContext *matroska,
980                          AVPacket             *pkt)
981 {
982     if (matroska->num_packets > 0) {
983         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
984         av_free(matroska->packets[0]);
985         if (matroska->num_packets > 1) {
986             memmove(&matroska->packets[0], &matroska->packets[1],
987                     (matroska->num_packets - 1) * sizeof(AVPacket *));
988             matroska->packets =
989                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
990                            sizeof(AVPacket *));
991         } else {
992             av_free(matroska->packets);
993             matroska->packets = NULL;
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                             break;
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                             break;
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                         if (res < 0)
1976                             break;
1977
1978                     finish:
1979                         /* remove dummy level */
1980                         while (matroska->num_levels) {
1981                             matroska->num_levels--;
1982                             length =
1983                                 matroska->levels[matroska->num_levels].length;
1984                             if (length == (uint64_t)-1)
1985                                 break;
1986                         }
1987
1988                         /* seek back */
1989                         if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1990                             return res;
1991                         matroska->peek_id = peek_id_cache;
1992                         matroska->level_up = level_up;
1993                         break;
1994                     }
1995
1996                     default:
1997                         av_log(matroska->ctx, AV_LOG_INFO,
1998                                "Ignoring seekhead entry for ID=0x%x\n",
1999                                seek_id);
2000                         break;
2001                 }
2002
2003                 break;
2004             }
2005
2006             default:
2007                 av_log(matroska->ctx, AV_LOG_INFO,
2008                        "Unknown seekhead ID 0x%x\n", id);
2009                 /* fall-through */
2010
2011             case EBML_ID_VOID:
2012                 res = ebml_read_skip(matroska);
2013                 break;
2014         }
2015
2016         if (matroska->level_up) {
2017             matroska->level_up--;
2018             break;
2019         }
2020     }
2021
2022     return res;
2023 }
2024
2025 #define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
2026
2027 static int
2028 matroska_aac_profile (char *codec_id)
2029 {
2030     static const char *aac_profiles[] = {
2031         "MAIN", "LC", "SSR"
2032     };
2033     int profile;
2034
2035     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2036         if (strstr(codec_id, aac_profiles[profile]))
2037             break;
2038     return profile + 1;
2039 }
2040
2041 static int
2042 matroska_aac_sri (int samplerate)
2043 {
2044     static const int aac_sample_rates[] = {
2045         96000, 88200, 64000, 48000, 44100, 32000,
2046         24000, 22050, 16000, 12000, 11025,  8000,
2047     };
2048     int sri;
2049
2050     for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
2051         if (aac_sample_rates[sri] == samplerate)
2052             break;
2053     return sri;
2054 }
2055
2056 static int
2057 matroska_read_header (AVFormatContext    *s,
2058                       AVFormatParameters *ap)
2059 {
2060     MatroskaDemuxContext *matroska = s->priv_data;
2061     char *doctype;
2062     int version, last_level, res = 0;
2063     uint32_t id;
2064
2065     matroska->ctx = s;
2066
2067     /* First read the EBML header. */
2068     doctype = NULL;
2069     if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2070         return res;
2071     if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2072         av_log(matroska->ctx, AV_LOG_ERROR,
2073                "Wrong EBML doctype ('%s' != 'matroska').\n",
2074                doctype ? doctype : "(none)");
2075         if (doctype)
2076             av_free(doctype);
2077         return AVERROR_NOFMT;
2078     }
2079     av_free(doctype);
2080     if (version != 1) {
2081         av_log(matroska->ctx, AV_LOG_ERROR,
2082                "Matroska demuxer version 1 too old for file version %d\n",
2083                version);
2084         return AVERROR_NOFMT;
2085     }
2086
2087     /* The next thing is a segment. */
2088     while (1) {
2089         if (!(id = ebml_peek_id(matroska, &last_level)))
2090             return AVERROR_IO;
2091         if (id == MATROSKA_ID_SEGMENT)
2092             break;
2093
2094         /* oi! */
2095         av_log(matroska->ctx, AV_LOG_INFO,
2096                "Expected a Segment ID (0x%x), but received 0x%x!\n",
2097                MATROSKA_ID_SEGMENT, id);
2098         if ((res = ebml_read_skip(matroska)) < 0)
2099             return res;
2100     }
2101
2102     /* We now have a Matroska segment.
2103      * Seeks are from the beginning of the segment,
2104      * after the segment ID/length. */
2105     if ((res = ebml_read_master(matroska, &id)) < 0)
2106         return res;
2107     matroska->segment_start = url_ftell(&s->pb);
2108
2109     matroska->time_scale = 1000000;
2110     /* we've found our segment, start reading the different contents in here */
2111     while (res == 0) {
2112         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2113             res = AVERROR_IO;
2114             break;
2115         } else if (matroska->level_up) {
2116             matroska->level_up--;
2117             break;
2118         }
2119
2120         switch (id) {
2121             /* stream info */
2122             case MATROSKA_ID_INFO: {
2123                 if ((res = ebml_read_master(matroska, &id)) < 0)
2124                     break;
2125                 res = matroska_parse_info(matroska);
2126                 break;
2127             }
2128
2129             /* track info headers */
2130             case MATROSKA_ID_TRACKS: {
2131                 if ((res = ebml_read_master(matroska, &id)) < 0)
2132                     break;
2133                 res = matroska_parse_tracks(matroska);
2134                 break;
2135             }
2136
2137             /* stream index */
2138             case MATROSKA_ID_CUES: {
2139                 if (!matroska->index_parsed) {
2140                     if ((res = ebml_read_master(matroska, &id)) < 0)
2141                         break;
2142                     res = matroska_parse_index(matroska);
2143                 } else
2144                     res = ebml_read_skip(matroska);
2145                 break;
2146             }
2147
2148             /* metadata */
2149             case MATROSKA_ID_TAGS: {
2150                 if (!matroska->metadata_parsed) {
2151                     if ((res = ebml_read_master(matroska, &id)) < 0)
2152                         break;
2153                     res = matroska_parse_metadata(matroska);
2154                 } else
2155                     res = ebml_read_skip(matroska);
2156                 break;
2157             }
2158
2159             /* file index (if seekable, seek to Cues/Tags to parse it) */
2160             case MATROSKA_ID_SEEKHEAD: {
2161                 if ((res = ebml_read_master(matroska, &id)) < 0)
2162                     break;
2163                 res = matroska_parse_seekhead(matroska);
2164                 break;
2165             }
2166
2167             case MATROSKA_ID_CLUSTER: {
2168                 /* Do not read the master - this will be done in the next
2169                  * call to matroska_read_packet. */
2170                 res = 1;
2171                 break;
2172             }
2173
2174             default:
2175                 av_log(matroska->ctx, AV_LOG_INFO,
2176                        "Unknown matroska file header ID 0x%x\n", id);
2177             /* fall-through */
2178
2179             case EBML_ID_VOID:
2180                 res = ebml_read_skip(matroska);
2181                 break;
2182         }
2183
2184         if (matroska->level_up) {
2185             matroska->level_up--;
2186             break;
2187         }
2188     }
2189
2190     /* Have we found a cluster? */
2191     if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2192         int i, j;
2193         MatroskaTrack *track;
2194         AVStream *st;
2195
2196         for (i = 0; i < matroska->num_tracks; i++) {
2197             enum CodecID codec_id = CODEC_ID_NONE;
2198             uint8_t *extradata = NULL;
2199             int extradata_size = 0;
2200             track = matroska->tracks[i];
2201
2202             /* libavformat does not really support subtitles.
2203              * Also apply some sanity checks. */
2204             if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2205                 (track->codec_id == NULL))
2206                 continue;
2207
2208             for(j=0; codec_tags[j].str; j++){
2209                 if(!strncmp(codec_tags[j].str, track->codec_id,
2210                             strlen(codec_tags[j].str))){
2211                     codec_id= codec_tags[j].id;
2212                     break;
2213                 }
2214             }
2215
2216             /* Set the FourCC from the CodecID. */
2217             /* This is the MS compatibility mode which stores a
2218              * BITMAPINFOHEADER in the CodecPrivate. */
2219             if (!strcmp(track->codec_id,
2220                         MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2221                 (track->codec_priv_size >= 40) &&
2222                 (track->codec_priv != NULL)) {
2223                 unsigned char *p;
2224
2225                 /* Offset of biCompression. Stored in LE. */
2226                 p = (unsigned char *)track->codec_priv + 16;
2227                 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2228                                  (p[2] << 16) | (p[1] << 8) | p[0];
2229                 codec_id = codec_get_bmp_id(((MatroskaVideoTrack *)track)->fourcc);
2230
2231             }
2232
2233             /* This is the MS compatibility mode which stores a
2234              * WAVEFORMATEX in the CodecPrivate. */
2235             else if (!strcmp(track->codec_id,
2236                              MATROSKA_CODEC_ID_AUDIO_ACM) &&
2237                 (track->codec_priv_size >= 18) &&
2238                 (track->codec_priv != NULL)) {
2239                 unsigned char *p;
2240                 uint16_t tag;
2241
2242                 /* Offset of wFormatTag. Stored in LE. */
2243                 p = (unsigned char *)track->codec_priv;
2244                 tag = (p[1] << 8) | p[0];
2245                 codec_id = codec_get_wav_id(tag);
2246
2247             }
2248
2249             if (codec_id==CODEC_ID_AAC || codec_id==CODEC_ID_MPEG4AAC) {
2250                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2251                 int profile = matroska_aac_profile(track->codec_id);
2252                 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2253                 extradata = av_malloc(5);
2254                 if (extradata == NULL)
2255                     return AVERROR_NOMEM;
2256                 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2257                 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2258                 if (strstr(track->codec_id, "SBR")) {
2259                     sri = matroska_aac_sri(audiotrack->samplerate);
2260                     extradata[2] = 0x56;
2261                     extradata[3] = 0xE5;
2262                     extradata[4] = 0x80 | (sri<<3);
2263                     extradata_size = 5;
2264                 } else {
2265                     extradata_size = 2;
2266                 }
2267             }
2268
2269             if (codec_id == CODEC_ID_NONE) {
2270                 av_log(matroska->ctx, AV_LOG_INFO,
2271                        "Unknown/unsupported CodecID %s.\n",
2272                        track->codec_id);
2273             }
2274
2275             track->stream_index = matroska->num_streams;
2276
2277             matroska->num_streams++;
2278             st = av_new_stream(s, track->stream_index);
2279             if (st == NULL)
2280                 return AVERROR_NOMEM;
2281             av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2282
2283             st->codec->codec_id = codec_id;
2284
2285             if (track->default_duration)
2286                 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2287                           track->default_duration, 1000000000, 30000);
2288
2289             if(extradata){
2290                 st->codec->extradata = extradata;
2291                 st->codec->extradata_size = extradata_size;
2292             } else if(track->codec_priv && track->codec_priv_size > 0){
2293                 st->codec->extradata = av_malloc(track->codec_priv_size);
2294                 if(st->codec->extradata == NULL)
2295                     return AVERROR_NOMEM;
2296                 st->codec->extradata_size = track->codec_priv_size;
2297                 memcpy(st->codec->extradata, track->codec_priv,
2298                        track->codec_priv_size);
2299             }
2300
2301             if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2302                 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2303
2304                 st->codec->codec_type = CODEC_TYPE_VIDEO;
2305                 st->codec->codec_tag = videotrack->fourcc;
2306                 st->codec->width = videotrack->pixel_width;
2307                 st->codec->height = videotrack->pixel_height;
2308                 if (videotrack->display_width == 0)
2309                     videotrack->display_width= videotrack->pixel_width;
2310                 if (videotrack->display_height == 0)
2311                     videotrack->display_height= videotrack->pixel_height;
2312                 av_reduce(&st->codec->sample_aspect_ratio.num,
2313                           &st->codec->sample_aspect_ratio.den,
2314                           st->codec->height * videotrack->display_width,
2315                           st->codec-> width * videotrack->display_height,
2316                           255);
2317             } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2318                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2319
2320                 st->codec->codec_type = CODEC_TYPE_AUDIO;
2321                 st->codec->sample_rate = audiotrack->samplerate;
2322                 st->codec->channels = audiotrack->channels;
2323             } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2324                 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2325             }
2326
2327             /* What do we do with private data? E.g. for Vorbis. */
2328         }
2329         res = 0;
2330     }
2331
2332     return res;
2333 }
2334
2335 static int
2336 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
2337                             int                   num)
2338 {
2339     int i;
2340
2341     for (i = 0; i < matroska->num_tracks; i++)
2342         if (matroska->tracks[i]->num == num)
2343             return i;
2344
2345     return -1;
2346 }
2347
2348 static int
2349 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2350                            uint64_t              cluster_time)
2351 {
2352     int res = 0;
2353     uint32_t id;
2354     AVPacket *pkt = NULL;
2355     int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2356     uint64_t duration = AV_NOPTS_VALUE;
2357     int track = -1;
2358
2359     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2360
2361     while (res == 0) {
2362         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2363             res = AVERROR_IO;
2364             break;
2365         } else if (matroska->level_up) {
2366             matroska->level_up--;
2367             break;
2368         }
2369
2370         switch (id) {
2371             /* one block inside the group. Note, block parsing is one
2372              * of the harder things, so this code is a bit complicated.
2373              * See http://www.matroska.org/ for documentation. */
2374             case MATROSKA_ID_BLOCK: {
2375                 uint8_t *data, *origdata;
2376                 int size;
2377                 int16_t block_time;
2378                 uint32_t *lace_size = NULL;
2379                 int n, flags, laces = 0;
2380                 uint64_t num;
2381                 int64_t pos= url_ftell(&matroska->ctx->pb);
2382
2383                 if ((res = ebml_read_binary(matroska, &id, &data, &size)) < 0)
2384                     break;
2385                 origdata = data;
2386
2387                 /* first byte(s): blocknum */
2388                 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2389                     av_log(matroska->ctx, AV_LOG_ERROR,
2390                            "EBML block data error\n");
2391                     av_free(origdata);
2392                     break;
2393                 }
2394                 data += n;
2395                 size -= n;
2396
2397                 /* fetch track from num */
2398                 track = matroska_find_track_by_num(matroska, num);
2399                 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2400                     av_log(matroska->ctx, AV_LOG_INFO,
2401                            "Invalid stream %d or size %u\n", track, size);
2402                     av_free(origdata);
2403                     break;
2404                 }
2405                 if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){
2406                     av_free(origdata);
2407                     break;
2408                 }
2409
2410                 /* block_time (relative to cluster time) */
2411                 block_time = (data[0] << 8) | data[1];
2412                 data += 2;
2413                 size -= 2;
2414                 flags = *data;
2415                 data += 1;
2416                 size -= 1;
2417                 switch ((flags & 0x06) >> 1) {
2418                     case 0x0: /* no lacing */
2419                         laces = 1;
2420                         lace_size = av_mallocz(sizeof(int));
2421                         lace_size[0] = size;
2422                         break;
2423
2424                     case 0x1: /* xiph lacing */
2425                     case 0x2: /* fixed-size lacing */
2426                     case 0x3: /* EBML lacing */
2427                         if (size == 0) {
2428                             res = -1;
2429                             break;
2430                         }
2431                         laces = (*data) + 1;
2432                         data += 1;
2433                         size -= 1;
2434                         lace_size = av_mallocz(laces * sizeof(int));
2435
2436                         switch ((flags & 0x06) >> 1) {
2437                             case 0x1: /* xiph lacing */ {
2438                                 uint8_t temp;
2439                                 uint32_t total = 0;
2440                                 for (n = 0; res == 0 && n < laces - 1; n++) {
2441                                     while (1) {
2442                                         if (size == 0) {
2443                                             res = -1;
2444                                             break;
2445                                         }
2446                                         temp = *data;
2447                                         lace_size[n] += temp;
2448                                         data += 1;
2449                                         size -= 1;
2450                                         if (temp != 0xff)
2451                                             break;
2452                                     }
2453                                     total += lace_size[n];
2454                                 }
2455                                 lace_size[n] = size - total;
2456                                 break;
2457                             }
2458
2459                             case 0x2: /* fixed-size lacing */
2460                                 for (n = 0; n < laces; n++)
2461                                     lace_size[n] = size / laces;
2462                                 break;
2463
2464                             case 0x3: /* EBML lacing */ {
2465                                 uint32_t total;
2466                                 n = matroska_ebmlnum_uint(data, size, &num);
2467                                 if (n < 0) {
2468                                     av_log(matroska->ctx, AV_LOG_INFO,
2469                                            "EBML block data error\n");
2470                                     break;
2471                                 }
2472                                 data += n;
2473                                 size -= n;
2474                                 total = lace_size[0] = num;
2475                                 for (n = 1; res == 0 && n < laces - 1; n++) {
2476                                     int64_t snum;
2477                                     int r;
2478                                     r = matroska_ebmlnum_sint (data, size,
2479                                                                &snum);
2480                                     if (r < 0) {
2481                                         av_log(matroska->ctx, AV_LOG_INFO,
2482                                                "EBML block data error\n");
2483                                         break;
2484                                     }
2485                                     data += r;
2486                                     size -= r;
2487                                     lace_size[n] = lace_size[n - 1] + snum;
2488                                     total += lace_size[n];
2489                                 }
2490                                 lace_size[n] = size - total;
2491                                 break;
2492                             }
2493                         }
2494                         break;
2495                 }
2496
2497                 if (res == 0) {
2498                     for (n = 0; n < laces; n++) {
2499                         uint64_t timecode = AV_NOPTS_VALUE;
2500
2501                         pkt = av_mallocz(sizeof(AVPacket));
2502                         /* XXX: prevent data copy... */
2503                         if (av_new_packet(pkt,lace_size[n]) < 0) {
2504                             res = AVERROR_NOMEM;
2505                             break;
2506                         }
2507                         if (cluster_time != (uint64_t)-1 && n == 0) {
2508                             if (cluster_time + block_time >= 0)
2509                                 timecode = cluster_time + block_time;
2510                         }
2511                         /* FIXME: duration */
2512
2513                         memcpy(pkt->data, data, lace_size[n]);
2514                         data += lace_size[n];
2515                         if (n == 0)
2516                             pkt->flags = is_keyframe;
2517                         pkt->stream_index =
2518                             matroska->tracks[track]->stream_index;
2519
2520                         pkt->pts = timecode;
2521                         pkt->pos= pos;
2522
2523                         matroska_queue_packet(matroska, pkt);
2524                     }
2525                 }
2526
2527                 av_free(lace_size);
2528                 av_free(origdata);
2529                 break;
2530             }
2531
2532             case MATROSKA_ID_BLOCKDURATION: {
2533                 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2534                     break;
2535                 break;
2536             }
2537
2538             case MATROSKA_ID_BLOCKREFERENCE:
2539                 /* We've found a reference, so not even the first frame in
2540                  * the lace is a key frame. */
2541                 is_keyframe = 0;
2542                 if (last_num_packets != matroska->num_packets)
2543                     matroska->packets[last_num_packets]->flags = 0;
2544                 res = ebml_read_skip(matroska);
2545                 break;
2546
2547             default:
2548                 av_log(matroska->ctx, AV_LOG_INFO,
2549                        "Unknown entry 0x%x in blockgroup data\n", id);
2550                 /* fall-through */
2551
2552             case EBML_ID_VOID:
2553                 res = ebml_read_skip(matroska);
2554                 break;
2555         }
2556
2557         if (matroska->level_up) {
2558             matroska->level_up--;
2559             break;
2560         }
2561     }
2562
2563     if (pkt)
2564     {
2565         if (duration != AV_NOPTS_VALUE)
2566             pkt->duration = duration;
2567         else if (track >= 0 && track < matroska->num_tracks)
2568             pkt->duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2569     }
2570
2571     return res;
2572 }
2573
2574 static int
2575 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2576 {
2577     int res = 0;
2578     uint32_t id;
2579     uint64_t cluster_time = 0;
2580
2581     av_log(matroska->ctx, AV_LOG_DEBUG,
2582            "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2583
2584     while (res == 0) {
2585         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2586             res = AVERROR_IO;
2587             break;
2588         } else if (matroska->level_up) {
2589             matroska->level_up--;
2590             break;
2591         }
2592
2593         switch (id) {
2594             /* cluster timecode */
2595             case MATROSKA_ID_CLUSTERTIMECODE: {
2596                 uint64_t num;
2597                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2598                     break;
2599                 cluster_time = num;
2600                 break;
2601             }
2602
2603                 /* a group of blocks inside a cluster */
2604             case MATROSKA_ID_BLOCKGROUP:
2605                 if ((res = ebml_read_master(matroska, &id)) < 0)
2606                     break;
2607                 res = matroska_parse_blockgroup(matroska, cluster_time);
2608                 break;
2609
2610             default:
2611                 av_log(matroska->ctx, AV_LOG_INFO,
2612                        "Unknown entry 0x%x in cluster data\n", id);
2613                 /* fall-through */
2614
2615             case EBML_ID_VOID:
2616                 res = ebml_read_skip(matroska);
2617                 break;
2618         }
2619
2620         if (matroska->level_up) {
2621             matroska->level_up--;
2622             break;
2623         }
2624     }
2625
2626     return res;
2627 }
2628
2629 static int
2630 matroska_read_packet (AVFormatContext *s,
2631                       AVPacket        *pkt)
2632 {
2633     MatroskaDemuxContext *matroska = s->priv_data;
2634     int res = 0;
2635     uint32_t id;
2636
2637     /* Do we still have a packet queued? */
2638     if (matroska_deliver_packet(matroska, pkt) == 0)
2639         return 0;
2640
2641     /* Have we already reached the end? */
2642     if (matroska->done)
2643         return AVERROR_IO;
2644
2645     while (res == 0) {
2646         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2647             res = AVERROR_IO;
2648             break;
2649         } else if (matroska->level_up) {
2650             matroska->level_up--;
2651             break;
2652         }
2653
2654         switch (id) {
2655             case MATROSKA_ID_CLUSTER:
2656                 if ((res = ebml_read_master(matroska, &id)) < 0)
2657                     break;
2658                 if ((res = matroska_parse_cluster(matroska)) == 0)
2659                     res = 1; /* Parsed one cluster, let's get out. */
2660                 break;
2661
2662             default:
2663             case EBML_ID_VOID:
2664                 res = ebml_read_skip(matroska);
2665                 break;
2666         }
2667
2668         if (matroska->level_up) {
2669             matroska->level_up--;
2670             break;
2671         }
2672     }
2673
2674     if (res == -1)
2675         matroska->done = 1;
2676
2677     return matroska_deliver_packet(matroska, pkt);
2678 }
2679
2680 static int
2681 matroska_read_close (AVFormatContext *s)
2682 {
2683     MatroskaDemuxContext *matroska = s->priv_data;
2684     int n = 0;
2685
2686     av_free(matroska->writing_app);
2687     av_free(matroska->muxing_app);
2688     av_free(matroska->index);
2689
2690     if (matroska->packets != NULL) {
2691         for (n = 0; n < matroska->num_packets; n++) {
2692             av_free_packet(matroska->packets[n]);
2693             av_free(matroska->packets[n]);
2694         }
2695         av_free(matroska->packets);
2696     }
2697
2698     for (n = 0; n < matroska->num_tracks; n++) {
2699         MatroskaTrack *track = matroska->tracks[n];
2700         av_free(track->codec_id);
2701         av_free(track->codec_name);
2702         av_free(track->codec_priv);
2703         av_free(track->name);
2704         av_free(track->language);
2705
2706         av_free(track);
2707     }
2708
2709     return 0;
2710 }
2711
2712 AVInputFormat matroska_demuxer = {
2713     "matroska",
2714     "Matroska file format",
2715     sizeof(MatroskaDemuxContext),
2716     matroska_probe,
2717     matroska_read_header,
2718     matroska_read_packet,
2719     matroska_read_close,
2720 };