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