add an intermediate variable (prepare for next patch)
[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 static int
979 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
980                             int                   num)
981 {
982     int i;
983
984     for (i = 0; i < matroska->num_tracks; i++)
985         if (matroska->tracks[i]->num == num)
986             return i;
987
988     return -1;
989 }
990
991
992 /*
993  * Put one packet in an application-supplied AVPacket struct.
994  * Returns 0 on success or -1 on failure.
995  */
996
997 static int
998 matroska_deliver_packet (MatroskaDemuxContext *matroska,
999                          AVPacket             *pkt)
1000 {
1001     if (matroska->num_packets > 0) {
1002         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1003         av_free(matroska->packets[0]);
1004         if (matroska->num_packets > 1) {
1005             memmove(&matroska->packets[0], &matroska->packets[1],
1006                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1007             matroska->packets =
1008                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1009                            sizeof(AVPacket *));
1010         } else {
1011             av_freep(&matroska->packets);
1012         }
1013         matroska->num_packets--;
1014         return 0;
1015     }
1016
1017     return -1;
1018 }
1019
1020 /*
1021  * Put a packet into our internal queue. Will be delivered to the
1022  * user/application during the next get_packet() call.
1023  */
1024
1025 static void
1026 matroska_queue_packet (MatroskaDemuxContext *matroska,
1027                        AVPacket             *pkt)
1028 {
1029     matroska->packets =
1030         av_realloc(matroska->packets, (matroska->num_packets + 1) *
1031                    sizeof(AVPacket *));
1032     matroska->packets[matroska->num_packets] = pkt;
1033     matroska->num_packets++;
1034 }
1035
1036
1037 /*
1038  * Autodetecting...
1039  */
1040
1041 static int
1042 matroska_probe (AVProbeData *p)
1043 {
1044     uint64_t total = 0;
1045     int len_mask = 0x80, size = 1, n = 1;
1046     uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1047
1048     /* ebml header? */
1049     if ((p->buf[0] << 24 | p->buf[1] << 16 |
1050          p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
1051         return 0;
1052
1053     /* length of header */
1054     total = p->buf[4];
1055     while (size <= 8 && !(total & len_mask)) {
1056         size++;
1057         len_mask >>= 1;
1058     }
1059     if (size > 8)
1060       return 0;
1061     total &= (len_mask - 1);
1062     while (n < size)
1063         total = (total << 8) | p->buf[4 + n++];
1064
1065     /* does the probe data contain the whole header? */
1066     if (p->buf_size < 4 + size + total)
1067       return 0;
1068
1069     /* the header must contain the document type 'matroska'. For now,
1070      * we don't parse the whole header but simply check for the
1071      * availability of that array of characters inside the header.
1072      * Not fully fool-proof, but good enough. */
1073     for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
1074         if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1075             return AVPROBE_SCORE_MAX;
1076
1077     return 0;
1078 }
1079
1080 /*
1081  * From here on, it's all XML-style DTD stuff... Needs no comments.
1082  */
1083
1084 static int
1085 matroska_parse_info (MatroskaDemuxContext *matroska)
1086 {
1087     int res = 0;
1088     uint32_t id;
1089
1090     av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
1091
1092     while (res == 0) {
1093         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1094             res = AVERROR_IO;
1095             break;
1096         } else if (matroska->level_up) {
1097             matroska->level_up--;
1098             break;
1099         }
1100
1101         switch (id) {
1102             /* cluster timecode */
1103             case MATROSKA_ID_TIMECODESCALE: {
1104                 uint64_t num;
1105                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1106                     break;
1107                 matroska->time_scale = num;
1108                 break;
1109             }
1110
1111             case MATROSKA_ID_DURATION: {
1112                 double num;
1113                 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1114                     break;
1115                 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
1116                 break;
1117             }
1118
1119             case MATROSKA_ID_TITLE: {
1120                 char *text;
1121                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1122                     break;
1123                 strncpy(matroska->ctx->title, text,
1124                         sizeof(matroska->ctx->title)-1);
1125                 av_free(text);
1126                 break;
1127             }
1128
1129             case MATROSKA_ID_WRITINGAPP: {
1130                 char *text;
1131                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1132                     break;
1133                 matroska->writing_app = text;
1134                 break;
1135             }
1136
1137             case MATROSKA_ID_MUXINGAPP: {
1138                 char *text;
1139                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1140                     break;
1141                 matroska->muxing_app = text;
1142                 break;
1143             }
1144
1145             case MATROSKA_ID_DATEUTC: {
1146                 int64_t time;
1147                 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
1148                     break;
1149                 matroska->created = time;
1150                 break;
1151             }
1152
1153             default:
1154                 av_log(matroska->ctx, AV_LOG_INFO,
1155                        "Unknown entry 0x%x in info header\n", id);
1156                 /* fall-through */
1157
1158             case EBML_ID_VOID:
1159                 res = ebml_read_skip(matroska);
1160                 break;
1161         }
1162
1163         if (matroska->level_up) {
1164             matroska->level_up--;
1165             break;
1166         }
1167     }
1168
1169     return res;
1170 }
1171
1172 static int
1173 matroska_add_stream (MatroskaDemuxContext *matroska)
1174 {
1175     int res = 0;
1176     uint32_t id;
1177     MatroskaTrack *track;
1178
1179     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1180
1181     /* Allocate a generic track. As soon as we know its type we'll realloc. */
1182     track = av_mallocz(MAX_TRACK_SIZE);
1183     matroska->num_tracks++;
1184
1185     /* start with the master */
1186     if ((res = ebml_read_master(matroska, &id)) < 0)
1187         return res;
1188
1189     /* try reading the trackentry headers */
1190     while (res == 0) {
1191         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1192             res = AVERROR_IO;
1193             break;
1194         } else if (matroska->level_up > 0) {
1195             matroska->level_up--;
1196             break;
1197         }
1198
1199         switch (id) {
1200             /* track number (unique stream ID) */
1201             case MATROSKA_ID_TRACKNUMBER: {
1202                 uint64_t num;
1203                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1204                     break;
1205                 track->num = num;
1206                 break;
1207             }
1208
1209             /* track UID (unique identifier) */
1210             case MATROSKA_ID_TRACKUID: {
1211                 uint64_t num;
1212                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1213                     break;
1214                 track->uid = num;
1215                 break;
1216             }
1217
1218             /* track type (video, audio, combined, subtitle, etc.) */
1219             case MATROSKA_ID_TRACKTYPE: {
1220                 uint64_t num;
1221                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1222                     break;
1223                 if (track->type && track->type != num) {
1224                     av_log(matroska->ctx, AV_LOG_INFO,
1225                            "More than one tracktype in an entry - skip\n");
1226                     break;
1227                 }
1228                 track->type = num;
1229
1230                 switch (track->type) {
1231                     case MATROSKA_TRACK_TYPE_VIDEO:
1232                     case MATROSKA_TRACK_TYPE_AUDIO:
1233                     case MATROSKA_TRACK_TYPE_SUBTITLE:
1234                         break;
1235                     case MATROSKA_TRACK_TYPE_COMPLEX:
1236                     case MATROSKA_TRACK_TYPE_LOGO:
1237                     case MATROSKA_TRACK_TYPE_CONTROL:
1238                     default:
1239                         av_log(matroska->ctx, AV_LOG_INFO,
1240                                "Unknown or unsupported track type 0x%x\n",
1241                                track->type);
1242                         track->type = 0;
1243                         break;
1244                 }
1245                 matroska->tracks[matroska->num_tracks - 1] = track;
1246                 break;
1247             }
1248
1249             /* tracktype specific stuff for video */
1250             case MATROSKA_ID_TRACKVIDEO: {
1251                 MatroskaVideoTrack *videotrack;
1252                 if (!track->type)
1253                     track->type = MATROSKA_TRACK_TYPE_VIDEO;
1254                 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1255                     av_log(matroska->ctx, AV_LOG_INFO,
1256                            "video data in non-video track - ignoring\n");
1257                     res = AVERROR_INVALIDDATA;
1258                     break;
1259                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1260                     break;
1261                 videotrack = (MatroskaVideoTrack *)track;
1262
1263                 while (res == 0) {
1264                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1265                         res = AVERROR_IO;
1266                         break;
1267                     } else if (matroska->level_up > 0) {
1268                         matroska->level_up--;
1269                         break;
1270                     }
1271
1272                     switch (id) {
1273                         /* fixme, this should be one-up, but I get it here */
1274                         case MATROSKA_ID_TRACKDEFAULTDURATION: {
1275                             uint64_t num;
1276                             if ((res = ebml_read_uint (matroska, &id,
1277                                                        &num)) < 0)
1278                                 break;
1279                             track->default_duration = num/matroska->time_scale;
1280                             break;
1281                         }
1282
1283                         /* video framerate */
1284                         case MATROSKA_ID_VIDEOFRAMERATE: {
1285                             double num;
1286                             if ((res = ebml_read_float(matroska, &id,
1287                                                        &num)) < 0)
1288                                 break;
1289                             track->default_duration = 1000000000/(matroska->time_scale*num);
1290                             break;
1291                         }
1292
1293                         /* width of the size to display the video at */
1294                         case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1295                             uint64_t num;
1296                             if ((res = ebml_read_uint(matroska, &id,
1297                                                       &num)) < 0)
1298                                 break;
1299                             videotrack->display_width = num;
1300                             break;
1301                         }
1302
1303                         /* height of the size to display the video at */
1304                         case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1305                             uint64_t num;
1306                             if ((res = ebml_read_uint(matroska, &id,
1307                                                       &num)) < 0)
1308                                 break;
1309                             videotrack->display_height = num;
1310                             break;
1311                         }
1312
1313                         /* width of the video in the file */
1314                         case MATROSKA_ID_VIDEOPIXELWIDTH: {
1315                             uint64_t num;
1316                             if ((res = ebml_read_uint(matroska, &id,
1317                                                       &num)) < 0)
1318                                 break;
1319                             videotrack->pixel_width = num;
1320                             break;
1321                         }
1322
1323                         /* height of the video in the file */
1324                         case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1325                             uint64_t num;
1326                             if ((res = ebml_read_uint(matroska, &id,
1327                                                       &num)) < 0)
1328                                 break;
1329                             videotrack->pixel_height = num;
1330                             break;
1331                         }
1332
1333                         /* whether the video is interlaced */
1334                         case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1335                             uint64_t num;
1336                             if ((res = ebml_read_uint(matroska, &id,
1337                                                       &num)) < 0)
1338                                 break;
1339                             if (num)
1340                                 track->flags |=
1341                                     MATROSKA_VIDEOTRACK_INTERLACED;
1342                             else
1343                                 track->flags &=
1344                                     ~MATROSKA_VIDEOTRACK_INTERLACED;
1345                             break;
1346                         }
1347
1348                         /* stereo mode (whether the video has two streams,
1349                          * where one is for the left eye and the other for
1350                          * the right eye, which creates a 3D-like
1351                          * effect) */
1352                         case MATROSKA_ID_VIDEOSTEREOMODE: {
1353                             uint64_t num;
1354                             if ((res = ebml_read_uint(matroska, &id,
1355                                                       &num)) < 0)
1356                                 break;
1357                             if (num != MATROSKA_EYE_MODE_MONO &&
1358                                 num != MATROSKA_EYE_MODE_LEFT &&
1359                                 num != MATROSKA_EYE_MODE_RIGHT &&
1360                                 num != MATROSKA_EYE_MODE_BOTH) {
1361                                 av_log(matroska->ctx, AV_LOG_INFO,
1362                                        "Ignoring unknown eye mode 0x%x\n",
1363                                        (uint32_t) num);
1364                                 break;
1365                             }
1366                             videotrack->eye_mode = num;
1367                             break;
1368                         }
1369
1370                         /* aspect ratio behaviour */
1371                         case MATROSKA_ID_VIDEOASPECTRATIO: {
1372                             uint64_t num;
1373                             if ((res = ebml_read_uint(matroska, &id,
1374                                                       &num)) < 0)
1375                                 break;
1376                             if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1377                                 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1378                                 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1379                                 av_log(matroska->ctx, AV_LOG_INFO,
1380                                        "Ignoring unknown aspect ratio 0x%x\n",
1381                                        (uint32_t) num);
1382                                 break;
1383                             }
1384                             videotrack->ar_mode = num;
1385                             break;
1386                         }
1387
1388                         /* colourspace (only matters for raw video)
1389                          * fourcc */
1390                         case MATROSKA_ID_VIDEOCOLOURSPACE: {
1391                             uint64_t num;
1392                             if ((res = ebml_read_uint(matroska, &id,
1393                                                       &num)) < 0)
1394                                 break;
1395                             videotrack->fourcc = num;
1396                             break;
1397                         }
1398
1399                         default:
1400                             av_log(matroska->ctx, AV_LOG_INFO,
1401                                    "Unknown video track header entry "
1402                                    "0x%x - ignoring\n", id);
1403                             /* pass-through */
1404
1405                         case EBML_ID_VOID:
1406                             res = ebml_read_skip(matroska);
1407                             break;
1408                     }
1409
1410                     if (matroska->level_up) {
1411                         matroska->level_up--;
1412                         break;
1413                     }
1414                 }
1415                 break;
1416             }
1417
1418             /* tracktype specific stuff for audio */
1419             case MATROSKA_ID_TRACKAUDIO: {
1420                 MatroskaAudioTrack *audiotrack;
1421                 if (!track->type)
1422                     track->type = MATROSKA_TRACK_TYPE_AUDIO;
1423                 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1424                     av_log(matroska->ctx, AV_LOG_INFO,
1425                            "audio data in non-audio track - ignoring\n");
1426                     res = AVERROR_INVALIDDATA;
1427                     break;
1428                 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1429                     break;
1430                 audiotrack = (MatroskaAudioTrack *)track;
1431                 audiotrack->channels = 1;
1432                 audiotrack->samplerate = 8000;
1433
1434                 while (res == 0) {
1435                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1436                         res = AVERROR_IO;
1437                         break;
1438                     } else if (matroska->level_up > 0) {
1439                         matroska->level_up--;
1440                         break;
1441                     }
1442
1443                     switch (id) {
1444                         /* samplerate */
1445                         case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1446                             double num;
1447                             if ((res = ebml_read_float(matroska, &id,
1448                                                        &num)) < 0)
1449                                 break;
1450                             audiotrack->internal_samplerate =
1451                             audiotrack->samplerate = num;
1452                             break;
1453                         }
1454
1455                         case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1456                             double num;
1457                             if ((res = ebml_read_float(matroska, &id,
1458                                                        &num)) < 0)
1459                                 break;
1460                             audiotrack->samplerate = num;
1461                             break;
1462                         }
1463
1464                             /* bitdepth */
1465                         case MATROSKA_ID_AUDIOBITDEPTH: {
1466                             uint64_t num;
1467                             if ((res = ebml_read_uint(matroska, &id,
1468                                                       &num)) < 0)
1469                                 break;
1470                             audiotrack->bitdepth = num;
1471                             break;
1472                         }
1473
1474                             /* channels */
1475                         case MATROSKA_ID_AUDIOCHANNELS: {
1476                             uint64_t num;
1477                             if ((res = ebml_read_uint(matroska, &id,
1478                                                       &num)) < 0)
1479                                 break;
1480                             audiotrack->channels = num;
1481                             break;
1482                         }
1483
1484                         default:
1485                             av_log(matroska->ctx, AV_LOG_INFO,
1486                                    "Unknown audio track header entry "
1487                                    "0x%x - ignoring\n", id);
1488                             /* pass-through */
1489
1490                         case EBML_ID_VOID:
1491                             res = ebml_read_skip(matroska);
1492                             break;
1493                     }
1494
1495                     if (matroska->level_up) {
1496                         matroska->level_up--;
1497                         break;
1498                     }
1499                 }
1500                 break;
1501             }
1502
1503                 /* codec identifier */
1504             case MATROSKA_ID_CODECID: {
1505                 char *text;
1506                 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1507                     break;
1508                 track->codec_id = text;
1509                 break;
1510             }
1511
1512                 /* codec private data */
1513             case MATROSKA_ID_CODECPRIVATE: {
1514                 uint8_t *data;
1515                 int size;
1516                 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1517                     break;
1518                 track->codec_priv = data;
1519                 track->codec_priv_size = size;
1520                 break;
1521             }
1522
1523                 /* name of the codec */
1524             case MATROSKA_ID_CODECNAME: {
1525                 char *text;
1526                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1527                     break;
1528                 track->codec_name = text;
1529                 break;
1530             }
1531
1532                 /* name of this track */
1533             case MATROSKA_ID_TRACKNAME: {
1534                 char *text;
1535                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1536                     break;
1537                 track->name = text;
1538                 break;
1539             }
1540
1541                 /* language (matters for audio/subtitles, mostly) */
1542             case MATROSKA_ID_TRACKLANGUAGE: {
1543                 char *text;
1544                 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1545                     break;
1546                 track->language = text;
1547                 break;
1548             }
1549
1550                 /* whether this is actually used */
1551             case MATROSKA_ID_TRACKFLAGENABLED: {
1552                 uint64_t num;
1553                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1554                     break;
1555                 if (num)
1556                     track->flags |= MATROSKA_TRACK_ENABLED;
1557                 else
1558                     track->flags &= ~MATROSKA_TRACK_ENABLED;
1559                 break;
1560             }
1561
1562                 /* whether it's the default for this track type */
1563             case MATROSKA_ID_TRACKFLAGDEFAULT: {
1564                 uint64_t num;
1565                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1566                     break;
1567                 if (num)
1568                     track->flags |= MATROSKA_TRACK_DEFAULT;
1569                 else
1570                     track->flags &= ~MATROSKA_TRACK_DEFAULT;
1571                 break;
1572             }
1573
1574                 /* lacing (like MPEG, where blocks don't end/start on frame
1575                  * boundaries) */
1576             case MATROSKA_ID_TRACKFLAGLACING: {
1577                 uint64_t num;
1578                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1579                     break;
1580                 if (num)
1581                     track->flags |= MATROSKA_TRACK_LACING;
1582                 else
1583                     track->flags &= ~MATROSKA_TRACK_LACING;
1584                 break;
1585             }
1586
1587                 /* default length (in time) of one data block in this track */
1588             case MATROSKA_ID_TRACKDEFAULTDURATION: {
1589                 uint64_t num;
1590                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1591                     break;
1592                 track->default_duration = num / matroska->time_scale;
1593                 break;
1594             }
1595
1596             default:
1597                 av_log(matroska->ctx, AV_LOG_INFO,
1598                        "Unknown track header entry 0x%x - ignoring\n", id);
1599                 /* pass-through */
1600
1601             case EBML_ID_VOID:
1602             /* we ignore these because they're nothing useful. */
1603             case MATROSKA_ID_CODECINFOURL:
1604             case MATROSKA_ID_CODECDOWNLOADURL:
1605             case MATROSKA_ID_TRACKMINCACHE:
1606             case MATROSKA_ID_TRACKMAXCACHE:
1607                 res = ebml_read_skip(matroska);
1608                 break;
1609         }
1610
1611         if (matroska->level_up) {
1612             matroska->level_up--;
1613             break;
1614         }
1615     }
1616
1617     return res;
1618 }
1619
1620 static int
1621 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1622 {
1623     int res = 0;
1624     uint32_t id;
1625
1626     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1627
1628     while (res == 0) {
1629         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1630             res = AVERROR_IO;
1631             break;
1632         } else if (matroska->level_up) {
1633             matroska->level_up--;
1634             break;
1635         }
1636
1637         switch (id) {
1638             /* one track within the "all-tracks" header */
1639             case MATROSKA_ID_TRACKENTRY:
1640                 res = matroska_add_stream(matroska);
1641                 break;
1642
1643             default:
1644                 av_log(matroska->ctx, AV_LOG_INFO,
1645                        "Unknown entry 0x%x in track header\n", id);
1646                 /* fall-through */
1647
1648             case EBML_ID_VOID:
1649                 res = ebml_read_skip(matroska);
1650                 break;
1651         }
1652
1653         if (matroska->level_up) {
1654             matroska->level_up--;
1655             break;
1656         }
1657     }
1658
1659     return res;
1660 }
1661
1662 static int
1663 matroska_parse_index (MatroskaDemuxContext *matroska)
1664 {
1665     int res = 0;
1666     uint32_t id;
1667     MatroskaDemuxIndex idx;
1668
1669     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1670
1671     while (res == 0) {
1672         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1673             res = AVERROR_IO;
1674             break;
1675         } else if (matroska->level_up) {
1676             matroska->level_up--;
1677             break;
1678         }
1679
1680         switch (id) {
1681             /* one single index entry ('point') */
1682             case MATROSKA_ID_POINTENTRY:
1683                 if ((res = ebml_read_master(matroska, &id)) < 0)
1684                     break;
1685
1686                 /* in the end, we hope to fill one entry with a
1687                  * timestamp, a file position and a tracknum */
1688                 idx.pos   = (uint64_t) -1;
1689                 idx.time  = (uint64_t) -1;
1690                 idx.track = (uint16_t) -1;
1691
1692                 while (res == 0) {
1693                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1694                         res = AVERROR_IO;
1695                         break;
1696                     } else if (matroska->level_up) {
1697                         matroska->level_up--;
1698                         break;
1699                     }
1700
1701                     switch (id) {
1702                         /* one single index entry ('point') */
1703                         case MATROSKA_ID_CUETIME: {
1704                             uint64_t time;
1705                             if ((res = ebml_read_uint(matroska, &id,
1706                                                       &time)) < 0)
1707                                 break;
1708                             idx.time = time * matroska->time_scale;
1709                             break;
1710                         }
1711
1712                         /* position in the file + track to which it
1713                          * belongs */
1714                         case MATROSKA_ID_CUETRACKPOSITION:
1715                             if ((res = ebml_read_master(matroska, &id)) < 0)
1716                                 break;
1717
1718                             while (res == 0) {
1719                                 if (!(id = ebml_peek_id (matroska,
1720                                                     &matroska->level_up))) {
1721                                     res = AVERROR_IO;
1722                                     break;
1723                                 } else if (matroska->level_up) {
1724                                     matroska->level_up--;
1725                                     break;
1726                                 }
1727
1728                                 switch (id) {
1729                                     /* track number */
1730                                     case MATROSKA_ID_CUETRACK: {
1731                                         uint64_t num;
1732                                         if ((res = ebml_read_uint(matroska,
1733                                                           &id, &num)) < 0)
1734                                             break;
1735                                         idx.track = num;
1736                                         break;
1737                                     }
1738
1739                                         /* position in file */
1740                                     case MATROSKA_ID_CUECLUSTERPOSITION: {
1741                                         uint64_t num;
1742                                         if ((res = ebml_read_uint(matroska,
1743                                                           &id, &num)) < 0)
1744                                             break;
1745                                         idx.pos = num+matroska->segment_start;
1746                                         break;
1747                                     }
1748
1749                                     default:
1750                                         av_log(matroska->ctx, AV_LOG_INFO,
1751                                                "Unknown entry 0x%x in "
1752                                                "CuesTrackPositions\n", id);
1753                                         /* fall-through */
1754
1755                                     case EBML_ID_VOID:
1756                                         res = ebml_read_skip(matroska);
1757                                         break;
1758                                 }
1759
1760                                 if (matroska->level_up) {
1761                                     matroska->level_up--;
1762                                     break;
1763                                 }
1764                             }
1765
1766                             break;
1767
1768                         default:
1769                             av_log(matroska->ctx, AV_LOG_INFO,
1770                                    "Unknown entry 0x%x in cuespoint "
1771                                    "index\n", id);
1772                             /* fall-through */
1773
1774                         case EBML_ID_VOID:
1775                             res = ebml_read_skip(matroska);
1776                             break;
1777                     }
1778
1779                     if (matroska->level_up) {
1780                         matroska->level_up--;
1781                         break;
1782                     }
1783                 }
1784
1785                 /* so let's see if we got what we wanted */
1786                 if (idx.pos   != (uint64_t) -1 &&
1787                     idx.time  != (uint64_t) -1 &&
1788                     idx.track != (uint16_t) -1) {
1789                     if (matroska->num_indexes % 32 == 0) {
1790                         /* re-allocate bigger index */
1791                         matroska->index =
1792                             av_realloc(matroska->index,
1793                                        (matroska->num_indexes + 32) *
1794                                        sizeof(MatroskaDemuxIndex));
1795                     }
1796                     matroska->index[matroska->num_indexes] = idx;
1797                     matroska->num_indexes++;
1798                 }
1799                 break;
1800
1801             default:
1802                 av_log(matroska->ctx, AV_LOG_INFO,
1803                        "Unknown entry 0x%x in cues header\n", id);
1804                 /* fall-through */
1805
1806             case EBML_ID_VOID:
1807                 res = ebml_read_skip(matroska);
1808                 break;
1809         }
1810
1811         if (matroska->level_up) {
1812             matroska->level_up--;
1813             break;
1814         }
1815     }
1816
1817     return res;
1818 }
1819
1820 static int
1821 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1822 {
1823     int res = 0;
1824     uint32_t id;
1825
1826     while (res == 0) {
1827         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1828             res = AVERROR_IO;
1829             break;
1830         } else if (matroska->level_up) {
1831             matroska->level_up--;
1832             break;
1833         }
1834
1835         switch (id) {
1836             /* Hm, this is unsupported... */
1837             default:
1838                 av_log(matroska->ctx, AV_LOG_INFO,
1839                        "Unknown entry 0x%x in metadata header\n", id);
1840                 /* fall-through */
1841
1842             case EBML_ID_VOID:
1843                 res = ebml_read_skip(matroska);
1844                 break;
1845         }
1846
1847         if (matroska->level_up) {
1848             matroska->level_up--;
1849             break;
1850         }
1851     }
1852
1853     return res;
1854 }
1855
1856 static int
1857 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1858 {
1859     int res = 0;
1860     uint32_t id;
1861
1862     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1863
1864     while (res == 0) {
1865         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1866             res = AVERROR_IO;
1867             break;
1868         } else if (matroska->level_up) {
1869             matroska->level_up--;
1870             break;
1871         }
1872
1873         switch (id) {
1874             case MATROSKA_ID_SEEKENTRY: {
1875                 uint32_t seek_id = 0, peek_id_cache = 0;
1876                 uint64_t seek_pos = (uint64_t) -1, t;
1877
1878                 if ((res = ebml_read_master(matroska, &id)) < 0)
1879                     break;
1880
1881                 while (res == 0) {
1882                     if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1883                         res = AVERROR_IO;
1884                         break;
1885                     } else if (matroska->level_up) {
1886                         matroska->level_up--;
1887                         break;
1888                     }
1889
1890                     switch (id) {
1891                         case MATROSKA_ID_SEEKID:
1892                             res = ebml_read_uint(matroska, &id, &t);
1893                             seek_id = t;
1894                             break;
1895
1896                         case MATROSKA_ID_SEEKPOSITION:
1897                             res = ebml_read_uint(matroska, &id, &seek_pos);
1898                             break;
1899
1900                         default:
1901                             av_log(matroska->ctx, AV_LOG_INFO,
1902                                    "Unknown seekhead ID 0x%x\n", id);
1903                             /* fall-through */
1904
1905                         case EBML_ID_VOID:
1906                             res = ebml_read_skip(matroska);
1907                             break;
1908                     }
1909
1910                     if (matroska->level_up) {
1911                         matroska->level_up--;
1912                         break;
1913                     }
1914                 }
1915
1916                 if (!seek_id || seek_pos == (uint64_t) -1) {
1917                     av_log(matroska->ctx, AV_LOG_INFO,
1918                            "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1919                            seek_id, seek_pos);
1920                     break;
1921                 }
1922
1923                 switch (seek_id) {
1924                     case MATROSKA_ID_CUES:
1925                     case MATROSKA_ID_TAGS: {
1926                         uint32_t level_up = matroska->level_up;
1927                         offset_t before_pos;
1928                         uint64_t length;
1929                         MatroskaLevel level;
1930
1931                         /* remember the peeked ID and the current position */
1932                         peek_id_cache = matroska->peek_id;
1933                         before_pos = url_ftell(&matroska->ctx->pb);
1934
1935                         /* seek */
1936                         if ((res = ebml_read_seek(matroska, seek_pos +
1937                                                matroska->segment_start)) < 0)
1938                             return res;
1939
1940                         /* we don't want to lose our seekhead level, so we add
1941                          * a dummy. This is a crude hack. */
1942                         if (matroska->num_levels == EBML_MAX_DEPTH) {
1943                             av_log(matroska->ctx, AV_LOG_INFO,
1944                                    "Max EBML element depth (%d) reached, "
1945                                    "cannot parse further.\n", EBML_MAX_DEPTH);
1946                             return AVERROR_UNKNOWN;
1947                         }
1948
1949                         level.start = 0;
1950                         level.length = (uint64_t)-1;
1951                         matroska->levels[matroska->num_levels] = level;
1952                         matroska->num_levels++;
1953
1954                         /* check ID */
1955                         if (!(id = ebml_peek_id (matroska,
1956                                                  &matroska->level_up)))
1957                             goto finish;
1958                         if (id != seek_id) {
1959                             av_log(matroska->ctx, AV_LOG_INFO,
1960                                    "We looked for ID=0x%x but got "
1961                                    "ID=0x%x (pos=%"PRIu64")",
1962                                    seek_id, id, seek_pos +
1963                                    matroska->segment_start);
1964                             goto finish;
1965                         }
1966
1967                         /* read master + parse */
1968                         if ((res = ebml_read_master(matroska, &id)) < 0)
1969                             goto finish;
1970                         switch (id) {
1971                             case MATROSKA_ID_CUES:
1972                                 if (!(res = matroska_parse_index(matroska)) ||
1973                                     url_feof(&matroska->ctx->pb)) {
1974                                     matroska->index_parsed = 1;
1975                                     res = 0;
1976                                 }
1977                                 break;
1978                             case MATROSKA_ID_TAGS:
1979                                 if (!(res = matroska_parse_metadata(matroska)) ||
1980                                    url_feof(&matroska->ctx->pb)) {
1981                                     matroska->metadata_parsed = 1;
1982                                     res = 0;
1983                                 }
1984                                 break;
1985                         }
1986
1987                     finish:
1988                         /* remove dummy level */
1989                         while (matroska->num_levels) {
1990                             matroska->num_levels--;
1991                             length =
1992                                 matroska->levels[matroska->num_levels].length;
1993                             if (length == (uint64_t)-1)
1994                                 break;
1995                         }
1996
1997                         /* seek back */
1998                         if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1999                             return res;
2000                         matroska->peek_id = peek_id_cache;
2001                         matroska->level_up = level_up;
2002                         break;
2003                     }
2004
2005                     default:
2006                         av_log(matroska->ctx, AV_LOG_INFO,
2007                                "Ignoring seekhead entry for ID=0x%x\n",
2008                                seek_id);
2009                         break;
2010                 }
2011
2012                 break;
2013             }
2014
2015             default:
2016                 av_log(matroska->ctx, AV_LOG_INFO,
2017                        "Unknown seekhead ID 0x%x\n", id);
2018                 /* fall-through */
2019
2020             case EBML_ID_VOID:
2021                 res = ebml_read_skip(matroska);
2022                 break;
2023         }
2024
2025         if (matroska->level_up) {
2026             matroska->level_up--;
2027             break;
2028         }
2029     }
2030
2031     return res;
2032 }
2033
2034 #define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
2035
2036 static int
2037 matroska_aac_profile (char *codec_id)
2038 {
2039     static const char *aac_profiles[] = {
2040         "MAIN", "LC", "SSR"
2041     };
2042     int profile;
2043
2044     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2045         if (strstr(codec_id, aac_profiles[profile]))
2046             break;
2047     return profile + 1;
2048 }
2049
2050 static int
2051 matroska_aac_sri (int samplerate)
2052 {
2053     static const int aac_sample_rates[] = {
2054         96000, 88200, 64000, 48000, 44100, 32000,
2055         24000, 22050, 16000, 12000, 11025,  8000,
2056     };
2057     int sri;
2058
2059     for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
2060         if (aac_sample_rates[sri] == samplerate)
2061             break;
2062     return sri;
2063 }
2064
2065 static int
2066 matroska_read_header (AVFormatContext    *s,
2067                       AVFormatParameters *ap)
2068 {
2069     MatroskaDemuxContext *matroska = s->priv_data;
2070     char *doctype;
2071     int version, last_level, res = 0;
2072     uint32_t id;
2073
2074     matroska->ctx = s;
2075
2076     /* First read the EBML header. */
2077     doctype = NULL;
2078     if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2079         return res;
2080     if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2081         av_log(matroska->ctx, AV_LOG_ERROR,
2082                "Wrong EBML doctype ('%s' != 'matroska').\n",
2083                doctype ? doctype : "(none)");
2084         if (doctype)
2085             av_free(doctype);
2086         return AVERROR_NOFMT;
2087     }
2088     av_free(doctype);
2089     if (version > 2) {
2090         av_log(matroska->ctx, AV_LOG_ERROR,
2091                "Matroska demuxer version 2 too old for file version %d\n",
2092                version);
2093         return AVERROR_NOFMT;
2094     }
2095
2096     /* The next thing is a segment. */
2097     while (1) {
2098         if (!(id = ebml_peek_id(matroska, &last_level)))
2099             return AVERROR_IO;
2100         if (id == MATROSKA_ID_SEGMENT)
2101             break;
2102
2103         /* oi! */
2104         av_log(matroska->ctx, AV_LOG_INFO,
2105                "Expected a Segment ID (0x%x), but received 0x%x!\n",
2106                MATROSKA_ID_SEGMENT, id);
2107         if ((res = ebml_read_skip(matroska)) < 0)
2108             return res;
2109     }
2110
2111     /* We now have a Matroska segment.
2112      * Seeks are from the beginning of the segment,
2113      * after the segment ID/length. */
2114     if ((res = ebml_read_master(matroska, &id)) < 0)
2115         return res;
2116     matroska->segment_start = url_ftell(&s->pb);
2117
2118     matroska->time_scale = 1000000;
2119     /* we've found our segment, start reading the different contents in here */
2120     while (res == 0) {
2121         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2122             res = AVERROR_IO;
2123             break;
2124         } else if (matroska->level_up) {
2125             matroska->level_up--;
2126             break;
2127         }
2128
2129         switch (id) {
2130             /* stream info */
2131             case MATROSKA_ID_INFO: {
2132                 if ((res = ebml_read_master(matroska, &id)) < 0)
2133                     break;
2134                 res = matroska_parse_info(matroska);
2135                 break;
2136             }
2137
2138             /* track info headers */
2139             case MATROSKA_ID_TRACKS: {
2140                 if ((res = ebml_read_master(matroska, &id)) < 0)
2141                     break;
2142                 res = matroska_parse_tracks(matroska);
2143                 break;
2144             }
2145
2146             /* stream index */
2147             case MATROSKA_ID_CUES: {
2148                 if (!matroska->index_parsed) {
2149                     if ((res = ebml_read_master(matroska, &id)) < 0)
2150                         break;
2151                     res = matroska_parse_index(matroska);
2152                 } else
2153                     res = ebml_read_skip(matroska);
2154                 break;
2155             }
2156
2157             /* metadata */
2158             case MATROSKA_ID_TAGS: {
2159                 if (!matroska->metadata_parsed) {
2160                     if ((res = ebml_read_master(matroska, &id)) < 0)
2161                         break;
2162                     res = matroska_parse_metadata(matroska);
2163                 } else
2164                     res = ebml_read_skip(matroska);
2165                 break;
2166             }
2167
2168             /* file index (if seekable, seek to Cues/Tags to parse it) */
2169             case MATROSKA_ID_SEEKHEAD: {
2170                 if ((res = ebml_read_master(matroska, &id)) < 0)
2171                     break;
2172                 res = matroska_parse_seekhead(matroska);
2173                 break;
2174             }
2175
2176             case MATROSKA_ID_CLUSTER: {
2177                 /* Do not read the master - this will be done in the next
2178                  * call to matroska_read_packet. */
2179                 res = 1;
2180                 break;
2181             }
2182
2183             default:
2184                 av_log(matroska->ctx, AV_LOG_INFO,
2185                        "Unknown matroska file header ID 0x%x\n", id);
2186             /* fall-through */
2187
2188             case EBML_ID_VOID:
2189                 res = ebml_read_skip(matroska);
2190                 break;
2191         }
2192
2193         if (matroska->level_up) {
2194             matroska->level_up--;
2195             break;
2196         }
2197     }
2198
2199     /* Have we found a cluster? */
2200     if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2201         int i, j;
2202         MatroskaTrack *track;
2203         AVStream *st;
2204
2205         for (i = 0; i < matroska->num_tracks; i++) {
2206             enum CodecID codec_id = CODEC_ID_NONE;
2207             uint8_t *extradata = NULL;
2208             int extradata_size = 0;
2209             int extradata_offset = 0;
2210             track = matroska->tracks[i];
2211
2212             /* libavformat does not really support subtitles.
2213              * Also apply some sanity checks. */
2214             if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2215                 (track->codec_id == NULL))
2216                 continue;
2217
2218             for(j=0; codec_tags[j].str; j++){
2219                 if(!strncmp(codec_tags[j].str, track->codec_id,
2220                             strlen(codec_tags[j].str))){
2221                     codec_id= codec_tags[j].id;
2222                     break;
2223                 }
2224             }
2225
2226             /* Set the FourCC from the CodecID. */
2227             /* This is the MS compatibility mode which stores a
2228              * BITMAPINFOHEADER in the CodecPrivate. */
2229             if (!strcmp(track->codec_id,
2230                         MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2231                 (track->codec_priv_size >= 40) &&
2232                 (track->codec_priv != NULL)) {
2233                 unsigned char *p;
2234
2235                 /* Offset of biCompression. Stored in LE. */
2236                 p = (unsigned char *)track->codec_priv + 16;
2237                 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2238                                  (p[2] << 16) | (p[1] << 8) | p[0];
2239                 codec_id = codec_get_id(codec_bmp_tags, ((MatroskaVideoTrack *)track)->fourcc);
2240
2241             }
2242
2243             /* This is the MS compatibility mode which stores a
2244              * WAVEFORMATEX in the CodecPrivate. */
2245             else if (!strcmp(track->codec_id,
2246                              MATROSKA_CODEC_ID_AUDIO_ACM) &&
2247                 (track->codec_priv_size >= 18) &&
2248                 (track->codec_priv != NULL)) {
2249                 unsigned char *p;
2250                 uint16_t tag;
2251
2252                 /* Offset of wFormatTag. Stored in LE. */
2253                 p = (unsigned char *)track->codec_priv;
2254                 tag = (p[1] << 8) | p[0];
2255                 codec_id = codec_get_id(codec_wav_tags, tag);
2256
2257             }
2258
2259             else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2260                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2261                 int profile = matroska_aac_profile(track->codec_id);
2262                 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2263                 extradata = av_malloc(5);
2264                 if (extradata == NULL)
2265                     return AVERROR_NOMEM;
2266                 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2267                 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2268                 if (strstr(track->codec_id, "SBR")) {
2269                     sri = matroska_aac_sri(audiotrack->samplerate);
2270                     extradata[2] = 0x56;
2271                     extradata[3] = 0xE5;
2272                     extradata[4] = 0x80 | (sri<<3);
2273                     extradata_size = 5;
2274                 } else {
2275                     extradata_size = 2;
2276                 }
2277                 track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
2278             }
2279
2280             else if (codec_id == CODEC_ID_TTA) {
2281                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2282                 ByteIOContext b;
2283                 extradata_size = 30;
2284                 extradata = av_mallocz(extradata_size);
2285                 if (extradata == NULL)
2286                     return AVERROR_NOMEM;
2287                 init_put_byte(&b, extradata, extradata_size, 1,
2288                               NULL, NULL, NULL, NULL);
2289                 put_buffer(&b, (uint8_t *) "TTA1", 4);
2290                 put_le16(&b, 1);
2291                 put_le16(&b, audiotrack->channels);
2292                 put_le16(&b, audiotrack->bitdepth);
2293                 put_le32(&b, audiotrack->samplerate);
2294                 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2295             }
2296
2297             else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2298                      codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2299                 extradata_offset = 26;
2300                 track->codec_priv_size -= extradata_offset;
2301                 track->flags |= MATROSKA_TRACK_REAL_V;
2302             }
2303
2304             if (codec_id == CODEC_ID_NONE) {
2305                 av_log(matroska->ctx, AV_LOG_INFO,
2306                        "Unknown/unsupported CodecID %s.\n",
2307                        track->codec_id);
2308             }
2309
2310             track->stream_index = matroska->num_streams;
2311
2312             matroska->num_streams++;
2313             st = av_new_stream(s, track->stream_index);
2314             if (st == NULL)
2315                 return AVERROR_NOMEM;
2316             av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2317
2318             st->codec->codec_id = codec_id;
2319             st->start_time = 0;
2320
2321             if (track->default_duration)
2322                 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2323                           track->default_duration, 1000, 30000);
2324
2325             if(extradata){
2326                 st->codec->extradata = extradata;
2327                 st->codec->extradata_size = extradata_size;
2328             } else if(track->codec_priv && track->codec_priv_size > 0){
2329                 st->codec->extradata = av_malloc(track->codec_priv_size);
2330                 if(st->codec->extradata == NULL)
2331                     return AVERROR_NOMEM;
2332                 st->codec->extradata_size = track->codec_priv_size;
2333                 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2334                        track->codec_priv_size);
2335             }
2336
2337             if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2338                 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2339
2340                 st->codec->codec_type = CODEC_TYPE_VIDEO;
2341                 st->codec->codec_tag = videotrack->fourcc;
2342                 st->codec->width = videotrack->pixel_width;
2343                 st->codec->height = videotrack->pixel_height;
2344                 if (videotrack->display_width == 0)
2345                     videotrack->display_width= videotrack->pixel_width;
2346                 if (videotrack->display_height == 0)
2347                     videotrack->display_height= videotrack->pixel_height;
2348                 av_reduce(&st->codec->sample_aspect_ratio.num,
2349                           &st->codec->sample_aspect_ratio.den,
2350                           st->codec->height * videotrack->display_width,
2351                           st->codec-> width * videotrack->display_height,
2352                           255);
2353                 st->need_parsing = 2;
2354             } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2355                 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2356
2357                 st->codec->codec_type = CODEC_TYPE_AUDIO;
2358                 st->codec->sample_rate = audiotrack->samplerate;
2359                 st->codec->channels = audiotrack->channels;
2360             } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2361                 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2362             }
2363
2364             /* What do we do with private data? E.g. for Vorbis. */
2365         }
2366         res = 0;
2367     }
2368
2369     if (matroska->index_parsed) {
2370         int i, track, stream;
2371         for (i=0; i<matroska->num_indexes; i++) {
2372             MatroskaDemuxIndex *idx = &matroska->index[i];
2373             track = matroska_find_track_by_num(matroska, idx->track);
2374             stream = matroska->tracks[track]->stream_index;
2375             av_add_index_entry(matroska->ctx->streams[stream],
2376                                idx->pos, idx->time/matroska->time_scale,
2377                                0, 0, AVINDEX_KEYFRAME);
2378         }
2379     }
2380
2381     return res;
2382 }
2383
2384 static inline int
2385 rv_offset(uint8_t *data, int slice, int slices)
2386 {
2387     return AV_RL32(data+8*slice+4) + 8*slices;
2388 }
2389
2390 static int
2391 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2392                      int64_t pos, uint64_t cluster_time, uint64_t duration,
2393                      int is_keyframe, int is_bframe)
2394 {
2395     int res = 0;
2396     int track;
2397     AVStream *st;
2398     AVPacket *pkt;
2399     uint8_t *origdata = data;
2400     int16_t block_time;
2401     uint32_t *lace_size = NULL;
2402     int n, flags, laces = 0;
2403     uint64_t num;
2404
2405     /* first byte(s): tracknum */
2406     if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2407         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2408         av_free(origdata);
2409         return res;
2410     }
2411     data += n;
2412     size -= n;
2413
2414     /* fetch track from num */
2415     track = matroska_find_track_by_num(matroska, num);
2416     if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2417         av_log(matroska->ctx, AV_LOG_INFO,
2418                "Invalid stream %d or size %u\n", track, size);
2419         av_free(origdata);
2420         return res;
2421     }
2422     st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2423     if (st->discard >= AVDISCARD_ALL) {
2424         av_free(origdata);
2425         return res;
2426     }
2427     if (duration == AV_NOPTS_VALUE)
2428         duration = matroska->tracks[track]->default_duration;
2429
2430     /* block_time (relative to cluster time) */
2431     block_time = (data[0] << 8) | data[1];
2432     data += 2;
2433     size -= 2;
2434     flags = *data;
2435     data += 1;
2436     size -= 1;
2437     if (is_keyframe == -1)
2438         is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2439     switch ((flags & 0x06) >> 1) {
2440         case 0x0: /* no lacing */
2441             laces = 1;
2442             lace_size = av_mallocz(sizeof(int));
2443             lace_size[0] = size;
2444             break;
2445
2446         case 0x1: /* xiph lacing */
2447         case 0x2: /* fixed-size lacing */
2448         case 0x3: /* EBML lacing */
2449             if (size == 0) {
2450                 res = -1;
2451                 break;
2452             }
2453             laces = (*data) + 1;
2454             data += 1;
2455             size -= 1;
2456             lace_size = av_mallocz(laces * sizeof(int));
2457
2458             switch ((flags & 0x06) >> 1) {
2459                 case 0x1: /* xiph lacing */ {
2460                     uint8_t temp;
2461                     uint32_t total = 0;
2462                     for (n = 0; res == 0 && n < laces - 1; n++) {
2463                         while (1) {
2464                             if (size == 0) {
2465                                 res = -1;
2466                                 break;
2467                             }
2468                             temp = *data;
2469                             lace_size[n] += temp;
2470                             data += 1;
2471                             size -= 1;
2472                             if (temp != 0xff)
2473                                 break;
2474                         }
2475                         total += lace_size[n];
2476                     }
2477                     lace_size[n] = size - total;
2478                     break;
2479                 }
2480
2481                 case 0x2: /* fixed-size lacing */
2482                     for (n = 0; n < laces; n++)
2483                         lace_size[n] = size / laces;
2484                     break;
2485
2486                 case 0x3: /* EBML lacing */ {
2487                     uint32_t total;
2488                     n = matroska_ebmlnum_uint(data, size, &num);
2489                     if (n < 0) {
2490                         av_log(matroska->ctx, AV_LOG_INFO,
2491                                "EBML block data error\n");
2492                         break;
2493                     }
2494                     data += n;
2495                     size -= n;
2496                     total = lace_size[0] = num;
2497                     for (n = 1; res == 0 && n < laces - 1; n++) {
2498                         int64_t snum;
2499                         int r;
2500                         r = matroska_ebmlnum_sint (data, size, &snum);
2501                         if (r < 0) {
2502                             av_log(matroska->ctx, AV_LOG_INFO,
2503                                    "EBML block data error\n");
2504                             break;
2505                         }
2506                         data += r;
2507                         size -= r;
2508                         lace_size[n] = lace_size[n - 1] + snum;
2509                         total += lace_size[n];
2510                     }
2511                     lace_size[n] = size - total;
2512                     break;
2513                 }
2514             }
2515             break;
2516     }
2517
2518     if (res == 0) {
2519         int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2520         uint64_t timecode = AV_NOPTS_VALUE;
2521
2522         if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
2523             timecode = cluster_time + block_time;
2524
2525         for (n = 0; n < laces; n++) {
2526             int slice, slices = 1;
2527
2528             if (real_v) {
2529                 slices = *data++ + 1;
2530                 lace_size[n]--;
2531             }
2532
2533             for (slice=0; slice<slices; slice++) {
2534                 int slice_size, slice_offset = 0;
2535                 if (real_v)
2536                     slice_offset = rv_offset(data, slice, slices);
2537                 if (slice+1 == slices)
2538                     slice_size = lace_size[n] - slice_offset;
2539                 else
2540                     slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2541                 pkt = av_mallocz(sizeof(AVPacket));
2542                 /* XXX: prevent data copy... */
2543                 if (av_new_packet(pkt, slice_size) < 0) {
2544                     res = AVERROR_NOMEM;
2545                     n = laces-1;
2546                     break;
2547                 }
2548                 memcpy (pkt->data, data+slice_offset, slice_size);
2549
2550                 if (n == 0)
2551                     pkt->flags = is_keyframe;
2552                 pkt->stream_index = matroska->tracks[track]->stream_index;
2553
2554                 pkt->pts = timecode;
2555                 pkt->pos = pos;
2556                 pkt->duration = duration;
2557
2558                     matroska_queue_packet(matroska, pkt);
2559
2560                 if (timecode != AV_NOPTS_VALUE)
2561                     timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2562             }
2563             data += lace_size[n];
2564         }
2565     }
2566
2567     av_free(lace_size);
2568     av_free(origdata);
2569     return res;
2570 }
2571
2572 static int
2573 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2574                            uint64_t              cluster_time)
2575 {
2576     int res = 0;
2577     uint32_t id;
2578     int is_bframe = 0;
2579     int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2580     uint64_t duration = AV_NOPTS_VALUE;
2581     uint8_t *data;
2582     int size = 0;
2583     int64_t pos = 0;
2584
2585     av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2586
2587     while (res == 0) {
2588         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2589             res = AVERROR_IO;
2590             break;
2591         } else if (matroska->level_up) {
2592             matroska->level_up--;
2593             break;
2594         }
2595
2596         switch (id) {
2597             /* one block inside the group. Note, block parsing is one
2598              * of the harder things, so this code is a bit complicated.
2599              * See http://www.matroska.org/ for documentation. */
2600             case MATROSKA_ID_BLOCK: {
2601                 pos = url_ftell(&matroska->ctx->pb);
2602                 res = ebml_read_binary(matroska, &id, &data, &size);
2603                 break;
2604             }
2605
2606             case MATROSKA_ID_BLOCKDURATION: {
2607                 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2608                     break;
2609                 duration /= matroska->time_scale;
2610                 break;
2611             }
2612
2613             case MATROSKA_ID_BLOCKREFERENCE: {
2614                 int64_t num;
2615                 /* We've found a reference, so not even the first frame in
2616                  * the lace is a key frame. */
2617                 is_keyframe = 0;
2618                 if (last_num_packets != matroska->num_packets)
2619                     matroska->packets[last_num_packets]->flags = 0;
2620                 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2621                     break;
2622                 if (num > 0)
2623                     is_bframe = 1;
2624                 break;
2625             }
2626
2627             default:
2628                 av_log(matroska->ctx, AV_LOG_INFO,
2629                        "Unknown entry 0x%x in blockgroup data\n", id);
2630                 /* fall-through */
2631
2632             case EBML_ID_VOID:
2633                 res = ebml_read_skip(matroska);
2634                 break;
2635         }
2636
2637         if (matroska->level_up) {
2638             matroska->level_up--;
2639             break;
2640         }
2641     }
2642
2643     if (res)
2644         return res;
2645
2646     if (size > 0)
2647         res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2648                                    duration, is_keyframe, is_bframe);
2649
2650     return res;
2651 }
2652
2653 static int
2654 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2655 {
2656     int res = 0;
2657     uint32_t id;
2658     uint64_t cluster_time = 0;
2659     uint8_t *data;
2660     int64_t pos;
2661     int size;
2662
2663     av_log(matroska->ctx, AV_LOG_DEBUG,
2664            "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2665
2666     while (res == 0) {
2667         if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2668             res = AVERROR_IO;
2669             break;
2670         } else if (matroska->level_up) {
2671             matroska->level_up--;
2672             break;
2673         }
2674
2675         switch (id) {
2676             /* cluster timecode */
2677             case MATROSKA_ID_CLUSTERTIMECODE: {
2678                 uint64_t num;
2679                 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2680                     break;
2681                 cluster_time = num;
2682                 break;
2683             }
2684
2685                 /* a group of blocks inside a cluster */
2686             case MATROSKA_ID_BLOCKGROUP:
2687                 if ((res = ebml_read_master(matroska, &id)) < 0)
2688                     break;
2689                 res = matroska_parse_blockgroup(matroska, cluster_time);
2690                 break;
2691
2692             case MATROSKA_ID_SIMPLEBLOCK:
2693                 pos = url_ftell(&matroska->ctx->pb);
2694                 res = ebml_read_binary(matroska, &id, &data, &size);
2695                 if (res == 0)
2696                     res = matroska_parse_block(matroska, data, size, pos,
2697                                                cluster_time, AV_NOPTS_VALUE,
2698                                                -1, 0);
2699                 break;
2700
2701             default:
2702                 av_log(matroska->ctx, AV_LOG_INFO,
2703                        "Unknown entry 0x%x in cluster data\n", id);
2704                 /* fall-through */
2705
2706             case EBML_ID_VOID:
2707                 res = ebml_read_skip(matroska);
2708                 break;
2709         }
2710
2711         if (matroska->level_up) {
2712             matroska->level_up--;
2713             break;
2714         }
2715     }
2716
2717     return res;
2718 }
2719
2720 static int
2721 matroska_read_packet (AVFormatContext *s,
2722                       AVPacket        *pkt)
2723 {
2724     MatroskaDemuxContext *matroska = s->priv_data;
2725     int res = 0;
2726     uint32_t id;
2727
2728     /* Read stream until we have a packet queued. */
2729     while (matroska_deliver_packet(matroska, pkt)) {
2730
2731         /* Have we already reached the end? */
2732         if (matroska->done)
2733             return AVERROR_IO;
2734
2735         while (res == 0) {
2736             if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2737                 return AVERROR_IO;
2738             } else if (matroska->level_up) {
2739                 matroska->level_up--;
2740                 break;
2741             }
2742
2743             switch (id) {
2744                 case MATROSKA_ID_CLUSTER:
2745                     if ((res = ebml_read_master(matroska, &id)) < 0)
2746                         break;
2747                     if ((res = matroska_parse_cluster(matroska)) == 0)
2748                         res = 1; /* Parsed one cluster, let's get out. */
2749                     break;
2750
2751                 default:
2752                 case EBML_ID_VOID:
2753                     res = ebml_read_skip(matroska);
2754                     break;
2755             }
2756
2757             if (matroska->level_up) {
2758                 matroska->level_up--;
2759                 break;
2760             }
2761         }
2762
2763         if (res == -1)
2764             matroska->done = 1;
2765     }
2766
2767     return 0;
2768 }
2769
2770 static int
2771 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2772                     int flags)
2773 {
2774     MatroskaDemuxContext *matroska = s->priv_data;
2775     AVStream *st = s->streams[stream_index];
2776     int index;
2777
2778     /* find index entry */
2779     index = av_index_search_timestamp(st, timestamp, flags);
2780     if (index < 0)
2781         return 0;
2782
2783     /* do the seek */
2784     url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
2785     matroska->num_packets = 0;
2786     matroska->peek_id = 0;
2787     return 0;
2788 }
2789
2790 static int
2791 matroska_read_close (AVFormatContext *s)
2792 {
2793     MatroskaDemuxContext *matroska = s->priv_data;
2794     int n = 0;
2795
2796     av_free(matroska->writing_app);
2797     av_free(matroska->muxing_app);
2798     av_free(matroska->index);
2799
2800     if (matroska->packets != NULL) {
2801         for (n = 0; n < matroska->num_packets; n++) {
2802             av_free_packet(matroska->packets[n]);
2803             av_free(matroska->packets[n]);
2804         }
2805         av_free(matroska->packets);
2806     }
2807
2808     for (n = 0; n < matroska->num_tracks; n++) {
2809         MatroskaTrack *track = matroska->tracks[n];
2810         av_free(track->codec_id);
2811         av_free(track->codec_name);
2812         av_free(track->codec_priv);
2813         av_free(track->name);
2814         av_free(track->language);
2815
2816         av_free(track);
2817     }
2818
2819     return 0;
2820 }
2821
2822 AVInputFormat matroska_demuxer = {
2823     "matroska",
2824     "Matroska file format",
2825     sizeof(MatroskaDemuxContext),
2826     matroska_probe,
2827     matroska_read_header,
2828     matroska_read_packet,
2829     matroska_read_close,
2830     matroska_read_seek,
2831 };