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