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