2 * Matroska file demuxer (no muxer yet)
3 * Copyright (c) 2003-2004 The ffmpeg Project
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * Matroska file demuxer
25 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * Specs available on the matroska project page:
28 * http://www.matroska.org/.
32 /* For codec_get_bmp_id and codec_get_wav_id. */
34 #include "intfloat_readwrite.h"
36 /* EBML version supported */
37 #define EBML_VERSION 1
39 /* top-level master-IDs */
40 #define EBML_ID_HEADER 0x1A45DFA3
42 /* IDs in the HEADER master */
43 #define EBML_ID_EBMLVERSION 0x4286
44 #define EBML_ID_EBMLREADVERSION 0x42F7
45 #define EBML_ID_EBMLMAXIDLENGTH 0x42F2
46 #define EBML_ID_EBMLMAXSIZELENGTH 0x42F3
47 #define EBML_ID_DOCTYPE 0x4282
48 #define EBML_ID_DOCTYPEVERSION 0x4287
49 #define EBML_ID_DOCTYPEREADVERSION 0x4285
51 /* general EBML types */
52 #define EBML_ID_VOID 0xEC
55 * Matroska element IDs. max. 32-bit.
58 /* toplevel segment */
59 #define MATROSKA_ID_SEGMENT 0x18538067
61 /* matroska top-level master IDs */
62 #define MATROSKA_ID_INFO 0x1549A966
63 #define MATROSKA_ID_TRACKS 0x1654AE6B
64 #define MATROSKA_ID_CUES 0x1C53BB6B
65 #define MATROSKA_ID_TAGS 0x1254C367
66 #define MATROSKA_ID_SEEKHEAD 0x114D9B74
67 #define MATROSKA_ID_CLUSTER 0x1F43B675
69 /* IDs in the info master */
70 #define MATROSKA_ID_TIMECODESCALE 0x2AD7B1
71 #define MATROSKA_ID_DURATION 0x4489
72 #define MATROSKA_ID_TITLE 0x7BA9
73 #define MATROSKA_ID_WRITINGAPP 0x5741
74 #define MATROSKA_ID_MUXINGAPP 0x4D80
75 #define MATROSKA_ID_DATEUTC 0x4461
77 /* ID in the tracks master */
78 #define MATROSKA_ID_TRACKENTRY 0xAE
80 /* IDs in the trackentry master */
81 #define MATROSKA_ID_TRACKNUMBER 0xD7
82 #define MATROSKA_ID_TRACKUID 0x73C5
83 #define MATROSKA_ID_TRACKTYPE 0x83
84 #define MATROSKA_ID_TRACKAUDIO 0xE1
85 #define MATROSKA_ID_TRACKVIDEO 0xE0
86 #define MATROSKA_ID_CODECID 0x86
87 #define MATROSKA_ID_CODECPRIVATE 0x63A2
88 #define MATROSKA_ID_CODECNAME 0x258688
89 #define MATROSKA_ID_CODECINFOURL 0x3B4040
90 #define MATROSKA_ID_CODECDOWNLOADURL 0x26B240
91 #define MATROSKA_ID_TRACKNAME 0x536E
92 #define MATROSKA_ID_TRACKLANGUAGE 0x22B59C
93 #define MATROSKA_ID_TRACKFLAGENABLED 0xB9
94 #define MATROSKA_ID_TRACKFLAGDEFAULT 0x88
95 #define MATROSKA_ID_TRACKFLAGLACING 0x9C
96 #define MATROSKA_ID_TRACKMINCACHE 0x6DE7
97 #define MATROSKA_ID_TRACKMAXCACHE 0x6DF8
98 #define MATROSKA_ID_TRACKDEFAULTDURATION 0x23E383
100 /* IDs in the trackvideo master */
101 #define MATROSKA_ID_VIDEOFRAMERATE 0x2383E3
102 #define MATROSKA_ID_VIDEODISPLAYWIDTH 0x54B0
103 #define MATROSKA_ID_VIDEODISPLAYHEIGHT 0x54BA
104 #define MATROSKA_ID_VIDEOPIXELWIDTH 0xB0
105 #define MATROSKA_ID_VIDEOPIXELHEIGHT 0xBA
106 #define MATROSKA_ID_VIDEOFLAGINTERLACED 0x9A
107 #define MATROSKA_ID_VIDEOSTEREOMODE 0x53B9
108 #define MATROSKA_ID_VIDEOASPECTRATIO 0x54B3
109 #define MATROSKA_ID_VIDEOCOLOURSPACE 0x2EB524
111 /* IDs in the trackaudio master */
112 #define MATROSKA_ID_AUDIOSAMPLINGFREQ 0xB5
113 #define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ 0x78B5
115 #define MATROSKA_ID_AUDIOBITDEPTH 0x6264
116 #define MATROSKA_ID_AUDIOCHANNELS 0x9F
118 /* ID in the cues master */
119 #define MATROSKA_ID_POINTENTRY 0xBB
121 /* IDs in the pointentry master */
122 #define MATROSKA_ID_CUETIME 0xB3
123 #define MATROSKA_ID_CUETRACKPOSITION 0xB7
125 /* IDs in the cuetrackposition master */
126 #define MATROSKA_ID_CUETRACK 0xF7
127 #define MATROSKA_ID_CUECLUSTERPOSITION 0xF1
129 /* IDs in the tags master */
132 /* IDs in the seekhead master */
133 #define MATROSKA_ID_SEEKENTRY 0x4DBB
135 /* IDs in the seekpoint master */
136 #define MATROSKA_ID_SEEKID 0x53AB
137 #define MATROSKA_ID_SEEKPOSITION 0x53AC
139 /* IDs in the cluster master */
140 #define MATROSKA_ID_CLUSTERTIMECODE 0xE7
141 #define MATROSKA_ID_BLOCKGROUP 0xA0
143 /* IDs in the blockgroup master */
144 #define MATROSKA_ID_BLOCK 0xA1
145 #define MATROSKA_ID_BLOCKDURATION 0x9B
146 #define MATROSKA_ID_BLOCKREFERENCE 0xFB
149 MATROSKA_TRACK_TYPE_VIDEO = 0x1,
150 MATROSKA_TRACK_TYPE_AUDIO = 0x2,
151 MATROSKA_TRACK_TYPE_COMPLEX = 0x3,
152 MATROSKA_TRACK_TYPE_LOGO = 0x10,
153 MATROSKA_TRACK_TYPE_SUBTITLE = 0x11,
154 MATROSKA_TRACK_TYPE_CONTROL = 0x20,
158 MATROSKA_EYE_MODE_MONO = 0x0,
159 MATROSKA_EYE_MODE_RIGHT = 0x1,
160 MATROSKA_EYE_MODE_LEFT = 0x2,
161 MATROSKA_EYE_MODE_BOTH = 0x3,
165 MATROSKA_ASPECT_RATIO_MODE_FREE = 0x0,
166 MATROSKA_ASPECT_RATIO_MODE_KEEP = 0x1,
167 MATROSKA_ASPECT_RATIO_MODE_FIXED = 0x2,
168 } MatroskaAspectRatioMode;
171 * These aren't in any way "matroska-form" things,
172 * it's just something I use in the muxer/demuxer.
176 MATROSKA_TRACK_ENABLED = (1<<0),
177 MATROSKA_TRACK_DEFAULT = (1<<1),
178 MATROSKA_TRACK_LACING = (1<<2),
179 MATROSKA_TRACK_REAL_V = (1<<4),
180 MATROSKA_TRACK_SHIFT = (1<<16)
181 } MatroskaTrackFlags;
184 MATROSKA_VIDEOTRACK_INTERLACED = (MATROSKA_TRACK_SHIFT<<0)
185 } MatroskaVideoTrackFlags;
188 * Matroska Codec IDs. Strings.
191 typedef struct CodecTags{
196 #define MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC "V_MS/VFW/FOURCC"
197 #define MATROSKA_CODEC_ID_AUDIO_ACM "A_MS/ACM"
199 static CodecTags codec_tags[]={
200 // {"V_MS/VFW/FOURCC" , CODEC_ID_NONE},
201 {"V_UNCOMPRESSED" , CODEC_ID_RAWVIDEO},
202 {"V_MPEG4/ISO/SP" , CODEC_ID_MPEG4},
203 {"V_MPEG4/ISO/ASP" , CODEC_ID_MPEG4},
204 {"V_MPEG4/ISO/AP" , CODEC_ID_MPEG4},
205 {"V_MPEG4/ISO/AVC" , CODEC_ID_H264},
206 {"V_MPEG4/MS/V3" , CODEC_ID_MSMPEG4V3},
207 {"V_MPEG1" , CODEC_ID_MPEG1VIDEO},
208 {"V_MPEG2" , CODEC_ID_MPEG2VIDEO},
209 {"V_MJPEG" , CODEC_ID_MJPEG},
210 {"V_REAL/RV10" , CODEC_ID_RV10},
211 {"V_REAL/RV20" , CODEC_ID_RV20},
212 {"V_REAL/RV30" , CODEC_ID_RV30},
213 {"V_REAL/RV40" , CODEC_ID_RV40},
214 /* TODO: Real/Quicktime */
216 // {"A_MS/ACM" , CODEC_ID_NONE},
217 {"A_MPEG/L1" , CODEC_ID_MP3},
218 {"A_MPEG/L2" , CODEC_ID_MP3},
219 {"A_MPEG/L3" , CODEC_ID_MP3},
220 {"A_PCM/INT/BIG" , CODEC_ID_PCM_U16BE},
221 {"A_PCM/INT/LIT" , CODEC_ID_PCM_U16LE},
222 // {"A_PCM/FLOAT/IEEE" , CODEC_ID_NONE},
223 {"A_AC3" , CODEC_ID_AC3},
224 {"A_DTS" , CODEC_ID_DTS},
225 {"A_VORBIS" , CODEC_ID_VORBIS},
226 {"A_AAC" , CODEC_ID_AAC},
227 {"A_WAVPACK4" , CODEC_ID_WAVPACK},
228 {NULL , CODEC_ID_NONE}
229 /* TODO: AC3-9/10 (?), Real, Musepack, Quicktime */
232 /* max. depth in the EBML tree structure */
233 #define EBML_MAX_DEPTH 16
235 typedef struct Track {
236 MatroskaTrackType type;
238 /* Unique track number and track ID. stream_index is the index that
239 * the calling app uses for this track. */
250 unsigned char *codec_priv;
253 int64_t default_duration;
254 MatroskaTrackFlags flags;
257 typedef struct MatroskaVideoTrack {
267 MatroskaAspectRatioMode ar_mode;
268 MatroskaEyeMode eye_mode;
271 } MatroskaVideoTrack;
273 typedef struct MatroskaAudioTrack {
281 } MatroskaAudioTrack;
283 typedef struct MatroskaSubtitleTrack {
287 } MatroskaSubtitleTrack;
289 typedef struct MatroskaLevel {
290 uint64_t start, length;
293 typedef struct MatroskaDemuxIndex {
294 uint64_t pos; /* of the corresponding *cluster*! */
295 uint16_t track; /* reference to 'num' */
296 uint64_t time; /* in nanoseconds */
297 } MatroskaDemuxIndex;
299 typedef struct MatroskaDemuxContext {
300 AVFormatContext *ctx;
304 MatroskaLevel levels[EBML_MAX_DEPTH];
312 /* timescale in the file */
315 /* position (time, ns) */
318 /* num_streams is the number of streams that av_new_stream() was called
319 * for ( = that are available to the calling program). */
320 int num_tracks, num_streams;
321 MatroskaTrack *tracks[MAX_STREAMS];
323 /* cache for ID peeking */
326 /* byte position of the segment inside the stream */
327 offset_t segment_start;
329 /* The packet queue. */
333 /* have we already parse metadata/cues/clusters? */
338 /* The index for seeking. */
340 MatroskaDemuxIndex *index;
341 } MatroskaDemuxContext;
344 * The first few functions handle EBML file parsing. The rest
345 * is the document interpretation. Matroska really just is a
350 * Return: the amount of levels in the hierarchy that the
351 * current element lies higher than the previous one.
352 * The opposite isn't done - that's auto-done using master
357 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
359 ByteIOContext *pb = &matroska->ctx->pb;
360 offset_t pos = url_ftell(pb);
363 while (matroska->num_levels > 0) {
364 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
366 if (pos >= level->start + level->length) {
367 matroska->num_levels--;
378 * Read: an "EBML number", which is defined as a variable-length
379 * array of bytes. The first byte indicates the length by giving a
380 * number of 0-bits followed by a one. The position of the first
381 * "one" bit inside the first byte indicates the length of this
383 * Returns: num. of bytes read. < 0 on error.
387 ebml_read_num (MatroskaDemuxContext *matroska,
391 ByteIOContext *pb = &matroska->ctx->pb;
392 int len_mask = 0x80, read = 1, n = 1;
395 /* the first byte tells us the length in bytes - get_byte() can normally
396 * return 0, but since that's not a valid first ebmlID byte, we can
397 * use it safely here to catch EOS. */
398 if (!(total = get_byte(pb))) {
399 /* we might encounter EOS here */
401 offset_t pos = url_ftell(pb);
402 av_log(matroska->ctx, AV_LOG_ERROR,
403 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
406 return AVERROR_IO; /* EOS or actual I/O error */
409 /* get the length of the EBML number */
410 while (read <= max_size && !(total & len_mask)) {
414 if (read > max_size) {
415 offset_t pos = url_ftell(pb) - 1;
416 av_log(matroska->ctx, AV_LOG_ERROR,
417 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
418 (uint8_t) total, pos, pos);
419 return AVERROR_INVALIDDATA;
422 /* read out length */
425 total = (total << 8) | get_byte(pb);
433 * Read: the element content data ID.
434 * Return: the number of bytes read or < 0 on error.
438 ebml_read_element_id (MatroskaDemuxContext *matroska,
445 /* if we re-call this, use our cached ID */
446 if (matroska->peek_id != 0) {
449 *id = matroska->peek_id;
453 /* read out the "EBML number", include tag in ID */
454 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
456 *id = matroska->peek_id = total | (1 << (read * 7));
460 *level_up = ebml_read_element_level_up(matroska);
466 * Read: element content length.
467 * Return: the number of bytes read or < 0 on error.
471 ebml_read_element_length (MatroskaDemuxContext *matroska,
474 /* clear cache since we're now beyond that data point */
475 matroska->peek_id = 0;
477 /* read out the "EBML number", include tag in ID */
478 return ebml_read_num(matroska, 8, length);
482 * Return: the ID of the next element, or 0 on error.
483 * Level_up contains the amount of levels that this
484 * next element lies higher than the previous one.
488 ebml_peek_id (MatroskaDemuxContext *matroska,
493 assert(level_up != NULL);
495 if (ebml_read_element_id(matroska, &id, level_up) < 0)
502 * Seek to a given offset.
503 * 0 is success, -1 is failure.
507 ebml_read_seek (MatroskaDemuxContext *matroska,
510 ByteIOContext *pb = &matroska->ctx->pb;
512 /* clear ID cache, if any */
513 matroska->peek_id = 0;
515 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
519 * Skip the next element.
520 * 0 is success, -1 is failure.
524 ebml_read_skip (MatroskaDemuxContext *matroska)
526 ByteIOContext *pb = &matroska->ctx->pb;
531 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
532 (res = ebml_read_element_length(matroska, &length)) < 0)
535 url_fskip(pb, length);
541 * Read the next element as an unsigned int.
542 * 0 is success, < 0 is failure.
546 ebml_read_uint (MatroskaDemuxContext *matroska,
550 ByteIOContext *pb = &matroska->ctx->pb;
551 int n = 0, size, res;
554 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
555 (res = ebml_read_element_length(matroska, &rlength)) < 0)
558 if (size < 1 || size > 8) {
559 offset_t pos = url_ftell(pb);
560 av_log(matroska->ctx, AV_LOG_ERROR,
561 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
563 return AVERROR_INVALIDDATA;
566 /* big-endian ordening; build up number */
569 *num = (*num << 8) | get_byte(pb);
575 * Read the next element as a signed int.
576 * 0 is success, < 0 is failure.
580 ebml_read_sint (MatroskaDemuxContext *matroska,
584 ByteIOContext *pb = &matroska->ctx->pb;
585 int size, n = 1, negative = 0, res;
588 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
589 (res = ebml_read_element_length(matroska, &rlength)) < 0)
592 if (size < 1 || size > 8) {
593 offset_t pos = url_ftell(pb);
594 av_log(matroska->ctx, AV_LOG_ERROR,
595 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
597 return AVERROR_INVALIDDATA;
599 if ((*num = get_byte(pb)) & 0x80) {
605 *num = (*num << 8) | get_byte(pb);
609 *num = *num - (1LL << ((8 * size) - 1));
615 * Read the next element as a float.
616 * 0 is success, < 0 is failure.
620 ebml_read_float (MatroskaDemuxContext *matroska,
624 ByteIOContext *pb = &matroska->ctx->pb;
628 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
629 (res = ebml_read_element_length(matroska, &rlength)) < 0)
634 *num= av_int2flt(get_be32(pb));
636 *num= av_int2dbl(get_be64(pb));
638 offset_t pos = url_ftell(pb);
639 av_log(matroska->ctx, AV_LOG_ERROR,
640 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
642 return AVERROR_INVALIDDATA;
649 * Read the next element as an ASCII string.
650 * 0 is success, < 0 is failure.
654 ebml_read_ascii (MatroskaDemuxContext *matroska,
658 ByteIOContext *pb = &matroska->ctx->pb;
662 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
663 (res = ebml_read_element_length(matroska, &rlength)) < 0)
667 /* ebml strings are usually not 0-terminated, so we allocate one
668 * byte more, read the string and NULL-terminate it ourselves. */
669 if (size < 0 || !(*str = av_malloc(size + 1))) {
670 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
671 return AVERROR_NOMEM;
673 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
674 offset_t pos = url_ftell(pb);
675 av_log(matroska->ctx, AV_LOG_ERROR,
676 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
685 * Read the next element as a UTF-8 string.
686 * 0 is success, < 0 is failure.
690 ebml_read_utf8 (MatroskaDemuxContext *matroska,
694 return ebml_read_ascii(matroska, id, str);
698 * Read the next element as a date (nanoseconds since 1/1/2000).
699 * 0 is success, < 0 is failure.
703 ebml_read_date (MatroskaDemuxContext *matroska,
707 return ebml_read_sint(matroska, id, date);
711 * Read the next element, but only the header. The contents
712 * are supposed to be sub-elements which can be read separately.
713 * 0 is success, < 0 is failure.
717 ebml_read_master (MatroskaDemuxContext *matroska,
720 ByteIOContext *pb = &matroska->ctx->pb;
722 MatroskaLevel *level;
725 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
726 (res = ebml_read_element_length(matroska, &length)) < 0)
729 /* protect... (Heaven forbids that the '>' is true) */
730 if (matroska->num_levels >= EBML_MAX_DEPTH) {
731 av_log(matroska->ctx, AV_LOG_ERROR,
732 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
733 return AVERROR_NOTSUPP;
737 level = &matroska->levels[matroska->num_levels++];
738 level->start = url_ftell(pb);
739 level->length = length;
745 * Read the next element as binary data.
746 * 0 is success, < 0 is failure.
750 ebml_read_binary (MatroskaDemuxContext *matroska,
755 ByteIOContext *pb = &matroska->ctx->pb;
759 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
760 (res = ebml_read_element_length(matroska, &rlength)) < 0)
764 if (!(*binary = av_malloc(*size))) {
765 av_log(matroska->ctx, AV_LOG_ERROR,
766 "Memory allocation error\n");
767 return AVERROR_NOMEM;
770 if (get_buffer(pb, *binary, *size) != *size) {
771 offset_t pos = url_ftell(pb);
772 av_log(matroska->ctx, AV_LOG_ERROR,
773 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
781 * Read signed/unsigned "EBML" numbers.
782 * Return: number of bytes processed, < 0 on error.
783 * XXX: use ebml_read_num().
787 matroska_ebmlnum_uint (uint8_t *data,
791 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
795 return AVERROR_INVALIDDATA;
798 while (read <= 8 && !(total & len_mask)) {
803 return AVERROR_INVALIDDATA;
805 if ((total &= (len_mask - 1)) == len_mask - 1)
808 return AVERROR_INVALIDDATA;
812 total = (total << 8) | data[n];
825 * Same as above, but signed.
829 matroska_ebmlnum_sint (uint8_t *data,
836 /* read as unsigned number first */
837 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
840 /* make signed (weird way) */
841 if (unum == (uint64_t)-1)
844 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
850 * Read an EBML header.
851 * 0 is success, < 0 is failure.
855 ebml_read_header (MatroskaDemuxContext *matroska,
860 int level_up, res = 0;
868 if (!(id = ebml_peek_id(matroska, &level_up)) ||
869 level_up != 0 || id != EBML_ID_HEADER) {
870 av_log(matroska->ctx, AV_LOG_ERROR,
871 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
872 return AVERROR_INVALIDDATA;
874 if ((res = ebml_read_master(matroska, &id)) < 0)
878 if (!(id = ebml_peek_id(matroska, &level_up)))
886 /* is our read version uptodate? */
887 case EBML_ID_EBMLREADVERSION: {
890 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
892 if (num > EBML_VERSION) {
893 av_log(matroska->ctx, AV_LOG_ERROR,
894 "EBML version %"PRIu64" (> %d) is not supported\n",
896 return AVERROR_INVALIDDATA;
901 /* we only handle 8 byte lengths at max */
902 case EBML_ID_EBMLMAXSIZELENGTH: {
905 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
907 if (num > sizeof(uint64_t)) {
908 av_log(matroska->ctx, AV_LOG_ERROR,
909 "Integers of size %"PRIu64" (> %zd) not supported\n",
910 num, sizeof(uint64_t));
911 return AVERROR_INVALIDDATA;
916 /* we handle 4 byte IDs at max */
917 case EBML_ID_EBMLMAXIDLENGTH: {
920 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
922 if (num > sizeof(uint32_t)) {
923 av_log(matroska->ctx, AV_LOG_ERROR,
924 "IDs of size %"PRIu64" (> %zu) not supported\n",
925 num, sizeof(uint32_t));
926 return AVERROR_INVALIDDATA;
931 case EBML_ID_DOCTYPE: {
934 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
945 case EBML_ID_DOCTYPEREADVERSION: {
948 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
956 av_log(matroska->ctx, AV_LOG_INFO,
957 "Unknown data type 0x%x in EBML header", id);
961 /* we ignore these two, as they don't tell us anything we
963 case EBML_ID_EBMLVERSION:
964 case EBML_ID_DOCTYPEVERSION:
965 res = ebml_read_skip (matroska);
974 * Put one packet in an application-supplied AVPacket struct.
975 * Returns 0 on success or -1 on failure.
979 matroska_deliver_packet (MatroskaDemuxContext *matroska,
982 if (matroska->num_packets > 0) {
983 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
984 av_free(matroska->packets[0]);
985 if (matroska->num_packets > 1) {
986 memmove(&matroska->packets[0], &matroska->packets[1],
987 (matroska->num_packets - 1) * sizeof(AVPacket *));
989 av_realloc(matroska->packets, (matroska->num_packets - 1) *
992 av_freep(&matroska->packets);
994 matroska->num_packets--;
1002 * Put a packet into our internal queue. Will be delivered to the
1003 * user/application during the next get_packet() call.
1007 matroska_queue_packet (MatroskaDemuxContext *matroska,
1011 av_realloc(matroska->packets, (matroska->num_packets + 1) *
1012 sizeof(AVPacket *));
1013 matroska->packets[matroska->num_packets] = pkt;
1014 matroska->num_packets++;
1022 matroska_probe (AVProbeData *p)
1025 int len_mask = 0x80, size = 1, n = 1;
1026 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1028 if (p->buf_size < 5)
1032 if ((p->buf[0] << 24 | p->buf[1] << 16 |
1033 p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
1036 /* length of header */
1038 while (size <= 8 && !(total & len_mask)) {
1044 total &= (len_mask - 1);
1046 total = (total << 8) | p->buf[4 + n++];
1048 /* does the probe data contain the whole header? */
1049 if (p->buf_size < 4 + size + total)
1052 /* the header must contain the document type 'matroska'. For now,
1053 * we don't parse the whole header but simply check for the
1054 * availability of that array of characters inside the header.
1055 * Not fully fool-proof, but good enough. */
1056 for (n = 4 + size; n < 4 + size + total - sizeof(probe_data); n++)
1057 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1058 return AVPROBE_SCORE_MAX;
1064 * From here on, it's all XML-style DTD stuff... Needs no comments.
1068 matroska_parse_info (MatroskaDemuxContext *matroska)
1073 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
1076 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1079 } else if (matroska->level_up) {
1080 matroska->level_up--;
1085 /* cluster timecode */
1086 case MATROSKA_ID_TIMECODESCALE: {
1088 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1090 matroska->time_scale = num;
1094 case MATROSKA_ID_DURATION: {
1096 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1098 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
1102 case MATROSKA_ID_TITLE: {
1104 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1106 strncpy(matroska->ctx->title, text,
1107 sizeof(matroska->ctx->title)-1);
1112 case MATROSKA_ID_WRITINGAPP: {
1114 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1116 matroska->writing_app = text;
1120 case MATROSKA_ID_MUXINGAPP: {
1122 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1124 matroska->muxing_app = text;
1128 case MATROSKA_ID_DATEUTC: {
1130 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
1132 matroska->created = time;
1137 av_log(matroska->ctx, AV_LOG_INFO,
1138 "Unknown entry 0x%x in info header\n", id);
1142 res = ebml_read_skip(matroska);
1146 if (matroska->level_up) {
1147 matroska->level_up--;
1156 matroska_add_stream (MatroskaDemuxContext *matroska)
1160 MatroskaTrack *track;
1162 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1164 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1165 track = av_mallocz(sizeof(MatroskaTrack));
1166 matroska->num_tracks++;
1168 /* start with the master */
1169 if ((res = ebml_read_master(matroska, &id)) < 0)
1172 /* try reading the trackentry headers */
1174 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1177 } else if (matroska->level_up > 0) {
1178 matroska->level_up--;
1183 /* track number (unique stream ID) */
1184 case MATROSKA_ID_TRACKNUMBER: {
1186 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1192 /* track UID (unique identifier) */
1193 case MATROSKA_ID_TRACKUID: {
1195 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1201 /* track type (video, audio, combined, subtitle, etc.) */
1202 case MATROSKA_ID_TRACKTYPE: {
1204 if (track->type != 0) {
1205 av_log(matroska->ctx, AV_LOG_INFO,
1206 "More than one tracktype in an entry - skip\n");
1209 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1213 /* ok, so we're actually going to reallocate this thing */
1214 switch (track->type) {
1215 case MATROSKA_TRACK_TYPE_VIDEO:
1216 track = (MatroskaTrack *)
1217 av_realloc(track, sizeof(MatroskaVideoTrack));
1219 case MATROSKA_TRACK_TYPE_AUDIO:
1220 track = (MatroskaTrack *)
1221 av_realloc(track, sizeof(MatroskaAudioTrack));
1222 ((MatroskaAudioTrack *)track)->channels = 1;
1223 ((MatroskaAudioTrack *)track)->samplerate = 8000;
1225 case MATROSKA_TRACK_TYPE_SUBTITLE:
1226 track = (MatroskaTrack *)
1227 av_realloc(track, sizeof(MatroskaSubtitleTrack));
1229 case MATROSKA_TRACK_TYPE_COMPLEX:
1230 case MATROSKA_TRACK_TYPE_LOGO:
1231 case MATROSKA_TRACK_TYPE_CONTROL:
1233 av_log(matroska->ctx, AV_LOG_INFO,
1234 "Unknown or unsupported track type 0x%x\n",
1239 matroska->tracks[matroska->num_tracks - 1] = track;
1243 /* tracktype specific stuff for video */
1244 case MATROSKA_ID_TRACKVIDEO: {
1245 MatroskaVideoTrack *videotrack;
1246 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1247 av_log(matroska->ctx, AV_LOG_INFO,
1248 "video data in non-video track - ignoring\n");
1249 res = AVERROR_INVALIDDATA;
1251 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1253 videotrack = (MatroskaVideoTrack *)track;
1256 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1259 } else if (matroska->level_up > 0) {
1260 matroska->level_up--;
1265 /* fixme, this should be one-up, but I get it here */
1266 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1268 if ((res = ebml_read_uint (matroska, &id,
1271 track->default_duration = num;
1275 /* video framerate */
1276 case MATROSKA_ID_VIDEOFRAMERATE: {
1278 if ((res = ebml_read_float(matroska, &id,
1281 track->default_duration = 1000000000 * (1. / num);
1285 /* width of the size to display the video at */
1286 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1288 if ((res = ebml_read_uint(matroska, &id,
1291 videotrack->display_width = num;
1295 /* height of the size to display the video at */
1296 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1298 if ((res = ebml_read_uint(matroska, &id,
1301 videotrack->display_height = num;
1305 /* width of the video in the file */
1306 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1308 if ((res = ebml_read_uint(matroska, &id,
1311 videotrack->pixel_width = num;
1315 /* height of the video in the file */
1316 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1318 if ((res = ebml_read_uint(matroska, &id,
1321 videotrack->pixel_height = num;
1325 /* whether the video is interlaced */
1326 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1328 if ((res = ebml_read_uint(matroska, &id,
1333 MATROSKA_VIDEOTRACK_INTERLACED;
1336 ~MATROSKA_VIDEOTRACK_INTERLACED;
1340 /* stereo mode (whether the video has two streams,
1341 * where one is for the left eye and the other for
1342 * the right eye, which creates a 3D-like
1344 case MATROSKA_ID_VIDEOSTEREOMODE: {
1346 if ((res = ebml_read_uint(matroska, &id,
1349 if (num != MATROSKA_EYE_MODE_MONO &&
1350 num != MATROSKA_EYE_MODE_LEFT &&
1351 num != MATROSKA_EYE_MODE_RIGHT &&
1352 num != MATROSKA_EYE_MODE_BOTH) {
1353 av_log(matroska->ctx, AV_LOG_INFO,
1354 "Ignoring unknown eye mode 0x%x\n",
1358 videotrack->eye_mode = num;
1362 /* aspect ratio behaviour */
1363 case MATROSKA_ID_VIDEOASPECTRATIO: {
1365 if ((res = ebml_read_uint(matroska, &id,
1368 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1369 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1370 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1371 av_log(matroska->ctx, AV_LOG_INFO,
1372 "Ignoring unknown aspect ratio 0x%x\n",
1376 videotrack->ar_mode = num;
1380 /* colourspace (only matters for raw video)
1382 case MATROSKA_ID_VIDEOCOLOURSPACE: {
1384 if ((res = ebml_read_uint(matroska, &id,
1387 videotrack->fourcc = num;
1392 av_log(matroska->ctx, AV_LOG_INFO,
1393 "Unknown video track header entry "
1394 "0x%x - ignoring\n", id);
1398 res = ebml_read_skip(matroska);
1402 if (matroska->level_up) {
1403 matroska->level_up--;
1410 /* tracktype specific stuff for audio */
1411 case MATROSKA_ID_TRACKAUDIO: {
1412 MatroskaAudioTrack *audiotrack;
1413 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1414 av_log(matroska->ctx, AV_LOG_INFO,
1415 "audio data in non-audio track - ignoring\n");
1416 res = AVERROR_INVALIDDATA;
1418 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1420 audiotrack = (MatroskaAudioTrack *)track;
1423 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1426 } else if (matroska->level_up > 0) {
1427 matroska->level_up--;
1433 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1435 if ((res = ebml_read_float(matroska, &id,
1438 audiotrack->internal_samplerate =
1439 audiotrack->samplerate = num;
1443 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1445 if ((res = ebml_read_float(matroska, &id,
1448 audiotrack->samplerate = num;
1453 case MATROSKA_ID_AUDIOBITDEPTH: {
1455 if ((res = ebml_read_uint(matroska, &id,
1458 audiotrack->bitdepth = num;
1463 case MATROSKA_ID_AUDIOCHANNELS: {
1465 if ((res = ebml_read_uint(matroska, &id,
1468 audiotrack->channels = num;
1473 av_log(matroska->ctx, AV_LOG_INFO,
1474 "Unknown audio track header entry "
1475 "0x%x - ignoring\n", id);
1479 res = ebml_read_skip(matroska);
1483 if (matroska->level_up) {
1484 matroska->level_up--;
1491 /* codec identifier */
1492 case MATROSKA_ID_CODECID: {
1494 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1496 track->codec_id = text;
1500 /* codec private data */
1501 case MATROSKA_ID_CODECPRIVATE: {
1504 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1506 track->codec_priv = data;
1507 track->codec_priv_size = size;
1511 /* name of the codec */
1512 case MATROSKA_ID_CODECNAME: {
1514 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1516 track->codec_name = text;
1520 /* name of this track */
1521 case MATROSKA_ID_TRACKNAME: {
1523 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1529 /* language (matters for audio/subtitles, mostly) */
1530 case MATROSKA_ID_TRACKLANGUAGE: {
1532 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1534 track->language = text;
1538 /* whether this is actually used */
1539 case MATROSKA_ID_TRACKFLAGENABLED: {
1541 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1544 track->flags |= MATROSKA_TRACK_ENABLED;
1546 track->flags &= ~MATROSKA_TRACK_ENABLED;
1550 /* whether it's the default for this track type */
1551 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1553 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1556 track->flags |= MATROSKA_TRACK_DEFAULT;
1558 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1562 /* lacing (like MPEG, where blocks don't end/start on frame
1564 case MATROSKA_ID_TRACKFLAGLACING: {
1566 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1569 track->flags |= MATROSKA_TRACK_LACING;
1571 track->flags &= ~MATROSKA_TRACK_LACING;
1575 /* default length (in time) of one data block in this track */
1576 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1578 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1580 track->default_duration = num;
1585 av_log(matroska->ctx, AV_LOG_INFO,
1586 "Unknown track header entry 0x%x - ignoring\n", id);
1590 /* we ignore these because they're nothing useful. */
1591 case MATROSKA_ID_CODECINFOURL:
1592 case MATROSKA_ID_CODECDOWNLOADURL:
1593 case MATROSKA_ID_TRACKMINCACHE:
1594 case MATROSKA_ID_TRACKMAXCACHE:
1595 res = ebml_read_skip(matroska);
1599 if (matroska->level_up) {
1600 matroska->level_up--;
1609 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1614 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1617 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1620 } else if (matroska->level_up) {
1621 matroska->level_up--;
1626 /* one track within the "all-tracks" header */
1627 case MATROSKA_ID_TRACKENTRY:
1628 res = matroska_add_stream(matroska);
1632 av_log(matroska->ctx, AV_LOG_INFO,
1633 "Unknown entry 0x%x in track header\n", id);
1637 res = ebml_read_skip(matroska);
1641 if (matroska->level_up) {
1642 matroska->level_up--;
1651 matroska_parse_index (MatroskaDemuxContext *matroska)
1655 MatroskaDemuxIndex idx;
1657 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1660 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1663 } else if (matroska->level_up) {
1664 matroska->level_up--;
1669 /* one single index entry ('point') */
1670 case MATROSKA_ID_POINTENTRY:
1671 if ((res = ebml_read_master(matroska, &id)) < 0)
1674 /* in the end, we hope to fill one entry with a
1675 * timestamp, a file position and a tracknum */
1676 idx.pos = (uint64_t) -1;
1677 idx.time = (uint64_t) -1;
1678 idx.track = (uint16_t) -1;
1681 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1684 } else if (matroska->level_up) {
1685 matroska->level_up--;
1690 /* one single index entry ('point') */
1691 case MATROSKA_ID_CUETIME: {
1693 if ((res = ebml_read_uint(matroska, &id,
1696 idx.time = time * matroska->time_scale;
1700 /* position in the file + track to which it
1702 case MATROSKA_ID_CUETRACKPOSITION:
1703 if ((res = ebml_read_master(matroska, &id)) < 0)
1707 if (!(id = ebml_peek_id (matroska,
1708 &matroska->level_up))) {
1711 } else if (matroska->level_up) {
1712 matroska->level_up--;
1718 case MATROSKA_ID_CUETRACK: {
1720 if ((res = ebml_read_uint(matroska,
1727 /* position in file */
1728 case MATROSKA_ID_CUECLUSTERPOSITION: {
1730 if ((res = ebml_read_uint(matroska,
1738 av_log(matroska->ctx, AV_LOG_INFO,
1739 "Unknown entry 0x%x in "
1740 "CuesTrackPositions\n", id);
1744 res = ebml_read_skip(matroska);
1748 if (matroska->level_up) {
1749 matroska->level_up--;
1757 av_log(matroska->ctx, AV_LOG_INFO,
1758 "Unknown entry 0x%x in cuespoint "
1763 res = ebml_read_skip(matroska);
1767 if (matroska->level_up) {
1768 matroska->level_up--;
1773 /* so let's see if we got what we wanted */
1774 if (idx.pos != (uint64_t) -1 &&
1775 idx.time != (uint64_t) -1 &&
1776 idx.track != (uint16_t) -1) {
1777 if (matroska->num_indexes % 32 == 0) {
1778 /* re-allocate bigger index */
1780 av_realloc(matroska->index,
1781 (matroska->num_indexes + 32) *
1782 sizeof(MatroskaDemuxIndex));
1784 matroska->index[matroska->num_indexes] = idx;
1785 matroska->num_indexes++;
1790 av_log(matroska->ctx, AV_LOG_INFO,
1791 "Unknown entry 0x%x in cues header\n", id);
1795 res = ebml_read_skip(matroska);
1799 if (matroska->level_up) {
1800 matroska->level_up--;
1809 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1815 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1818 } else if (matroska->level_up) {
1819 matroska->level_up--;
1824 /* Hm, this is unsupported... */
1826 av_log(matroska->ctx, AV_LOG_INFO,
1827 "Unknown entry 0x%x in metadata header\n", id);
1831 res = ebml_read_skip(matroska);
1835 if (matroska->level_up) {
1836 matroska->level_up--;
1845 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1850 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1853 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1856 } else if (matroska->level_up) {
1857 matroska->level_up--;
1862 case MATROSKA_ID_SEEKENTRY: {
1863 uint32_t seek_id = 0, peek_id_cache = 0;
1864 uint64_t seek_pos = (uint64_t) -1, t;
1866 if ((res = ebml_read_master(matroska, &id)) < 0)
1870 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1873 } else if (matroska->level_up) {
1874 matroska->level_up--;
1879 case MATROSKA_ID_SEEKID:
1880 res = ebml_read_uint(matroska, &id, &t);
1884 case MATROSKA_ID_SEEKPOSITION:
1885 res = ebml_read_uint(matroska, &id, &seek_pos);
1889 av_log(matroska->ctx, AV_LOG_INFO,
1890 "Unknown seekhead ID 0x%x\n", id);
1894 res = ebml_read_skip(matroska);
1898 if (matroska->level_up) {
1899 matroska->level_up--;
1904 if (!seek_id || seek_pos == (uint64_t) -1) {
1905 av_log(matroska->ctx, AV_LOG_INFO,
1906 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1912 case MATROSKA_ID_CUES:
1913 case MATROSKA_ID_TAGS: {
1914 uint32_t level_up = matroska->level_up;
1915 offset_t before_pos;
1917 MatroskaLevel level;
1919 /* remember the peeked ID and the current position */
1920 peek_id_cache = matroska->peek_id;
1921 before_pos = url_ftell(&matroska->ctx->pb);
1924 if ((res = ebml_read_seek(matroska, seek_pos +
1925 matroska->segment_start)) < 0)
1928 /* we don't want to lose our seekhead level, so we add
1929 * a dummy. This is a crude hack. */
1930 if (matroska->num_levels == EBML_MAX_DEPTH) {
1931 av_log(matroska->ctx, AV_LOG_INFO,
1932 "Max EBML element depth (%d) reached, "
1933 "cannot parse further.\n", EBML_MAX_DEPTH);
1934 return AVERROR_UNKNOWN;
1938 level.length = (uint64_t)-1;
1939 matroska->levels[matroska->num_levels] = level;
1940 matroska->num_levels++;
1943 if (!(id = ebml_peek_id (matroska,
1944 &matroska->level_up)))
1946 if (id != seek_id) {
1947 av_log(matroska->ctx, AV_LOG_INFO,
1948 "We looked for ID=0x%x but got "
1949 "ID=0x%x (pos=%"PRIu64")",
1950 seek_id, id, seek_pos +
1951 matroska->segment_start);
1955 /* read master + parse */
1956 if ((res = ebml_read_master(matroska, &id)) < 0)
1959 case MATROSKA_ID_CUES:
1960 if (!(res = matroska_parse_index(matroska)) ||
1961 url_feof(&matroska->ctx->pb)) {
1962 matroska->index_parsed = 1;
1966 case MATROSKA_ID_TAGS:
1967 if (!(res = matroska_parse_metadata(matroska)) ||
1968 url_feof(&matroska->ctx->pb)) {
1969 matroska->metadata_parsed = 1;
1976 /* remove dummy level */
1977 while (matroska->num_levels) {
1978 matroska->num_levels--;
1980 matroska->levels[matroska->num_levels].length;
1981 if (length == (uint64_t)-1)
1986 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1988 matroska->peek_id = peek_id_cache;
1989 matroska->level_up = level_up;
1994 av_log(matroska->ctx, AV_LOG_INFO,
1995 "Ignoring seekhead entry for ID=0x%x\n",
2004 av_log(matroska->ctx, AV_LOG_INFO,
2005 "Unknown seekhead ID 0x%x\n", id);
2009 res = ebml_read_skip(matroska);
2013 if (matroska->level_up) {
2014 matroska->level_up--;
2022 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
2025 matroska_aac_profile (char *codec_id)
2027 static const char *aac_profiles[] = {
2032 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2033 if (strstr(codec_id, aac_profiles[profile]))
2039 matroska_aac_sri (int samplerate)
2041 static const int aac_sample_rates[] = {
2042 96000, 88200, 64000, 48000, 44100, 32000,
2043 24000, 22050, 16000, 12000, 11025, 8000,
2047 for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
2048 if (aac_sample_rates[sri] == samplerate)
2054 matroska_read_header (AVFormatContext *s,
2055 AVFormatParameters *ap)
2057 MatroskaDemuxContext *matroska = s->priv_data;
2059 int version, last_level, res = 0;
2064 /* First read the EBML header. */
2066 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2068 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2069 av_log(matroska->ctx, AV_LOG_ERROR,
2070 "Wrong EBML doctype ('%s' != 'matroska').\n",
2071 doctype ? doctype : "(none)");
2074 return AVERROR_NOFMT;
2078 av_log(matroska->ctx, AV_LOG_ERROR,
2079 "Matroska demuxer version 1 too old for file version %d\n",
2081 return AVERROR_NOFMT;
2084 /* The next thing is a segment. */
2086 if (!(id = ebml_peek_id(matroska, &last_level)))
2088 if (id == MATROSKA_ID_SEGMENT)
2092 av_log(matroska->ctx, AV_LOG_INFO,
2093 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2094 MATROSKA_ID_SEGMENT, id);
2095 if ((res = ebml_read_skip(matroska)) < 0)
2099 /* We now have a Matroska segment.
2100 * Seeks are from the beginning of the segment,
2101 * after the segment ID/length. */
2102 if ((res = ebml_read_master(matroska, &id)) < 0)
2104 matroska->segment_start = url_ftell(&s->pb);
2106 matroska->time_scale = 1000000;
2107 /* we've found our segment, start reading the different contents in here */
2109 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2112 } else if (matroska->level_up) {
2113 matroska->level_up--;
2119 case MATROSKA_ID_INFO: {
2120 if ((res = ebml_read_master(matroska, &id)) < 0)
2122 res = matroska_parse_info(matroska);
2126 /* track info headers */
2127 case MATROSKA_ID_TRACKS: {
2128 if ((res = ebml_read_master(matroska, &id)) < 0)
2130 res = matroska_parse_tracks(matroska);
2135 case MATROSKA_ID_CUES: {
2136 if (!matroska->index_parsed) {
2137 if ((res = ebml_read_master(matroska, &id)) < 0)
2139 res = matroska_parse_index(matroska);
2141 res = ebml_read_skip(matroska);
2146 case MATROSKA_ID_TAGS: {
2147 if (!matroska->metadata_parsed) {
2148 if ((res = ebml_read_master(matroska, &id)) < 0)
2150 res = matroska_parse_metadata(matroska);
2152 res = ebml_read_skip(matroska);
2156 /* file index (if seekable, seek to Cues/Tags to parse it) */
2157 case MATROSKA_ID_SEEKHEAD: {
2158 if ((res = ebml_read_master(matroska, &id)) < 0)
2160 res = matroska_parse_seekhead(matroska);
2164 case MATROSKA_ID_CLUSTER: {
2165 /* Do not read the master - this will be done in the next
2166 * call to matroska_read_packet. */
2172 av_log(matroska->ctx, AV_LOG_INFO,
2173 "Unknown matroska file header ID 0x%x\n", id);
2177 res = ebml_read_skip(matroska);
2181 if (matroska->level_up) {
2182 matroska->level_up--;
2187 /* Have we found a cluster? */
2188 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2190 MatroskaTrack *track;
2193 for (i = 0; i < matroska->num_tracks; i++) {
2194 enum CodecID codec_id = CODEC_ID_NONE;
2195 uint8_t *extradata = NULL;
2196 int extradata_size = 0;
2197 int extradata_offset = 0;
2198 track = matroska->tracks[i];
2200 /* libavformat does not really support subtitles.
2201 * Also apply some sanity checks. */
2202 if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2203 (track->codec_id == NULL))
2206 for(j=0; codec_tags[j].str; j++){
2207 if(!strncmp(codec_tags[j].str, track->codec_id,
2208 strlen(codec_tags[j].str))){
2209 codec_id= codec_tags[j].id;
2214 /* Set the FourCC from the CodecID. */
2215 /* This is the MS compatibility mode which stores a
2216 * BITMAPINFOHEADER in the CodecPrivate. */
2217 if (!strcmp(track->codec_id,
2218 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2219 (track->codec_priv_size >= 40) &&
2220 (track->codec_priv != NULL)) {
2223 /* Offset of biCompression. Stored in LE. */
2224 p = (unsigned char *)track->codec_priv + 16;
2225 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2226 (p[2] << 16) | (p[1] << 8) | p[0];
2227 codec_id = codec_get_bmp_id(((MatroskaVideoTrack *)track)->fourcc);
2231 /* This is the MS compatibility mode which stores a
2232 * WAVEFORMATEX in the CodecPrivate. */
2233 else if (!strcmp(track->codec_id,
2234 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2235 (track->codec_priv_size >= 18) &&
2236 (track->codec_priv != NULL)) {
2240 /* Offset of wFormatTag. Stored in LE. */
2241 p = (unsigned char *)track->codec_priv;
2242 tag = (p[1] << 8) | p[0];
2243 codec_id = codec_get_wav_id(tag);
2247 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2248 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2249 int profile = matroska_aac_profile(track->codec_id);
2250 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2251 extradata = av_malloc(5);
2252 if (extradata == NULL)
2253 return AVERROR_NOMEM;
2254 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2255 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2256 if (strstr(track->codec_id, "SBR")) {
2257 sri = matroska_aac_sri(audiotrack->samplerate);
2258 extradata[2] = 0x56;
2259 extradata[3] = 0xE5;
2260 extradata[4] = 0x80 | (sri<<3);
2267 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2268 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2269 extradata_offset = 26;
2270 track->codec_priv_size -= extradata_offset;
2271 track->flags |= MATROSKA_TRACK_REAL_V;
2274 if (codec_id == CODEC_ID_NONE) {
2275 av_log(matroska->ctx, AV_LOG_INFO,
2276 "Unknown/unsupported CodecID %s.\n",
2280 track->stream_index = matroska->num_streams;
2282 matroska->num_streams++;
2283 st = av_new_stream(s, track->stream_index);
2285 return AVERROR_NOMEM;
2286 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2288 st->codec->codec_id = codec_id;
2290 if (track->default_duration)
2291 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2292 track->default_duration, 1000000000, 30000);
2295 st->codec->extradata = extradata;
2296 st->codec->extradata_size = extradata_size;
2297 } else if(track->codec_priv && track->codec_priv_size > 0){
2298 st->codec->extradata = av_malloc(track->codec_priv_size);
2299 if(st->codec->extradata == NULL)
2300 return AVERROR_NOMEM;
2301 st->codec->extradata_size = track->codec_priv_size;
2302 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2303 track->codec_priv_size);
2306 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2307 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2309 st->codec->codec_type = CODEC_TYPE_VIDEO;
2310 st->codec->codec_tag = videotrack->fourcc;
2311 st->codec->width = videotrack->pixel_width;
2312 st->codec->height = videotrack->pixel_height;
2313 if (videotrack->display_width == 0)
2314 videotrack->display_width= videotrack->pixel_width;
2315 if (videotrack->display_height == 0)
2316 videotrack->display_height= videotrack->pixel_height;
2317 av_reduce(&st->codec->sample_aspect_ratio.num,
2318 &st->codec->sample_aspect_ratio.den,
2319 st->codec->height * videotrack->display_width,
2320 st->codec-> width * videotrack->display_height,
2322 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2323 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2325 st->codec->codec_type = CODEC_TYPE_AUDIO;
2326 st->codec->sample_rate = audiotrack->samplerate;
2327 st->codec->channels = audiotrack->channels;
2328 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2329 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2332 /* What do we do with private data? E.g. for Vorbis. */
2341 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
2346 for (i = 0; i < matroska->num_tracks; i++)
2347 if (matroska->tracks[i]->num == num)
2354 rv_offset(uint8_t *data, int slice, int slices)
2356 return LE_32(data+8*slice+4) + 8*slices;
2360 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2361 uint64_t cluster_time)
2365 AVPacket *pkt = NULL;
2366 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2367 uint64_t duration = AV_NOPTS_VALUE;
2370 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2373 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2376 } else if (matroska->level_up) {
2377 matroska->level_up--;
2382 /* one block inside the group. Note, block parsing is one
2383 * of the harder things, so this code is a bit complicated.
2384 * See http://www.matroska.org/ for documentation. */
2385 case MATROSKA_ID_BLOCK: {
2386 uint8_t *data, *origdata;
2389 uint32_t *lace_size = NULL;
2390 int n, flags, laces = 0;
2392 int64_t pos= url_ftell(&matroska->ctx->pb);
2394 if ((res = ebml_read_binary(matroska, &id, &data, &size)) < 0)
2398 /* first byte(s): tracknum */
2399 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2400 av_log(matroska->ctx, AV_LOG_ERROR,
2401 "EBML block data error\n");
2408 /* fetch track from num */
2409 track = matroska_find_track_by_num(matroska, num);
2410 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2411 av_log(matroska->ctx, AV_LOG_INFO,
2412 "Invalid stream %d or size %u\n", track, size);
2416 if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){
2421 /* block_time (relative to cluster time) */
2422 block_time = (data[0] << 8) | data[1];
2428 switch ((flags & 0x06) >> 1) {
2429 case 0x0: /* no lacing */
2431 lace_size = av_mallocz(sizeof(int));
2432 lace_size[0] = size;
2435 case 0x1: /* xiph lacing */
2436 case 0x2: /* fixed-size lacing */
2437 case 0x3: /* EBML lacing */
2442 laces = (*data) + 1;
2445 lace_size = av_mallocz(laces * sizeof(int));
2447 switch ((flags & 0x06) >> 1) {
2448 case 0x1: /* xiph lacing */ {
2451 for (n = 0; res == 0 && n < laces - 1; n++) {
2458 lace_size[n] += temp;
2464 total += lace_size[n];
2466 lace_size[n] = size - total;
2470 case 0x2: /* fixed-size lacing */
2471 for (n = 0; n < laces; n++)
2472 lace_size[n] = size / laces;
2475 case 0x3: /* EBML lacing */ {
2477 n = matroska_ebmlnum_uint(data, size, &num);
2479 av_log(matroska->ctx, AV_LOG_INFO,
2480 "EBML block data error\n");
2485 total = lace_size[0] = num;
2486 for (n = 1; res == 0 && n < laces - 1; n++) {
2489 r = matroska_ebmlnum_sint (data, size,
2492 av_log(matroska->ctx, AV_LOG_INFO,
2493 "EBML block data error\n");
2498 lace_size[n] = lace_size[n - 1] + snum;
2499 total += lace_size[n];
2501 lace_size[n] = size - total;
2509 int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2510 for (n = 0; n < laces; n++) {
2511 uint64_t timecode = AV_NOPTS_VALUE;
2512 int slice, slices = 1;
2515 slices = *data++ + 1;
2518 if (cluster_time != (uint64_t)-1 && n == 0) {
2519 if (cluster_time + block_time >= 0)
2520 timecode = cluster_time + block_time;
2522 /* FIXME: duration */
2524 for (slice=0; slice<slices; slice++) {
2525 int slice_size, slice_offset = 0;
2527 slice_offset = rv_offset(data, slice, slices);
2528 if (slice+1 == slices)
2529 slice_size = lace_size[n] - slice_offset;
2531 slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2532 pkt = av_mallocz(sizeof(AVPacket));
2533 /* XXX: prevent data copy... */
2534 if (av_new_packet(pkt, slice_size) < 0) {
2535 res = AVERROR_NOMEM;
2539 memcpy (pkt->data, data+slice_offset, slice_size);
2542 pkt->flags = is_keyframe;
2544 matroska->tracks[track]->stream_index;
2546 pkt->pts = timecode;
2549 matroska_queue_packet(matroska, pkt);
2551 data += lace_size[n];
2560 case MATROSKA_ID_BLOCKDURATION: {
2561 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2566 case MATROSKA_ID_BLOCKREFERENCE:
2567 /* We've found a reference, so not even the first frame in
2568 * the lace is a key frame. */
2570 if (last_num_packets != matroska->num_packets)
2571 matroska->packets[last_num_packets]->flags = 0;
2572 res = ebml_read_skip(matroska);
2576 av_log(matroska->ctx, AV_LOG_INFO,
2577 "Unknown entry 0x%x in blockgroup data\n", id);
2581 res = ebml_read_skip(matroska);
2585 if (matroska->level_up) {
2586 matroska->level_up--;
2593 if (duration != AV_NOPTS_VALUE)
2594 pkt->duration = duration;
2595 else if (track >= 0 && track < matroska->num_tracks)
2596 pkt->duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2603 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2607 uint64_t cluster_time = 0;
2609 av_log(matroska->ctx, AV_LOG_DEBUG,
2610 "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2613 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2616 } else if (matroska->level_up) {
2617 matroska->level_up--;
2622 /* cluster timecode */
2623 case MATROSKA_ID_CLUSTERTIMECODE: {
2625 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2631 /* a group of blocks inside a cluster */
2632 case MATROSKA_ID_BLOCKGROUP:
2633 if ((res = ebml_read_master(matroska, &id)) < 0)
2635 res = matroska_parse_blockgroup(matroska, cluster_time);
2639 av_log(matroska->ctx, AV_LOG_INFO,
2640 "Unknown entry 0x%x in cluster data\n", id);
2644 res = ebml_read_skip(matroska);
2648 if (matroska->level_up) {
2649 matroska->level_up--;
2658 matroska_read_packet (AVFormatContext *s,
2661 MatroskaDemuxContext *matroska = s->priv_data;
2665 /* Do we still have a packet queued? */
2666 if (matroska_deliver_packet(matroska, pkt) == 0)
2669 /* Have we already reached the end? */
2674 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2677 } else if (matroska->level_up) {
2678 matroska->level_up--;
2683 case MATROSKA_ID_CLUSTER:
2684 if ((res = ebml_read_master(matroska, &id)) < 0)
2686 if ((res = matroska_parse_cluster(matroska)) == 0)
2687 res = 1; /* Parsed one cluster, let's get out. */
2692 res = ebml_read_skip(matroska);
2696 if (matroska->level_up) {
2697 matroska->level_up--;
2705 return matroska_deliver_packet(matroska, pkt);
2709 matroska_read_close (AVFormatContext *s)
2711 MatroskaDemuxContext *matroska = s->priv_data;
2714 av_free(matroska->writing_app);
2715 av_free(matroska->muxing_app);
2716 av_free(matroska->index);
2718 if (matroska->packets != NULL) {
2719 for (n = 0; n < matroska->num_packets; n++) {
2720 av_free_packet(matroska->packets[n]);
2721 av_free(matroska->packets[n]);
2723 av_free(matroska->packets);
2726 for (n = 0; n < matroska->num_tracks; n++) {
2727 MatroskaTrack *track = matroska->tracks[n];
2728 av_free(track->codec_id);
2729 av_free(track->codec_name);
2730 av_free(track->codec_priv);
2731 av_free(track->name);
2732 av_free(track->language);
2740 AVInputFormat matroska_demuxer = {
2742 "Matroska file format",
2743 sizeof(MatroskaDemuxContext),
2745 matroska_read_header,
2746 matroska_read_packet,
2747 matroska_read_close,