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