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