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