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