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