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