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_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
142 #define MATROSKA_ID_SIMPLEBLOCK 0xA3
144 /* IDs in the blockgroup master */
145 #define MATROSKA_ID_BLOCK 0xA1
146 #define MATROSKA_ID_BLOCKDURATION 0x9B
147 #define MATROSKA_ID_BLOCKREFERENCE 0xFB
150 MATROSKA_TRACK_TYPE_VIDEO = 0x1,
151 MATROSKA_TRACK_TYPE_AUDIO = 0x2,
152 MATROSKA_TRACK_TYPE_COMPLEX = 0x3,
153 MATROSKA_TRACK_TYPE_LOGO = 0x10,
154 MATROSKA_TRACK_TYPE_SUBTITLE = 0x11,
155 MATROSKA_TRACK_TYPE_CONTROL = 0x20,
159 MATROSKA_EYE_MODE_MONO = 0x0,
160 MATROSKA_EYE_MODE_RIGHT = 0x1,
161 MATROSKA_EYE_MODE_LEFT = 0x2,
162 MATROSKA_EYE_MODE_BOTH = 0x3,
166 MATROSKA_ASPECT_RATIO_MODE_FREE = 0x0,
167 MATROSKA_ASPECT_RATIO_MODE_KEEP = 0x1,
168 MATROSKA_ASPECT_RATIO_MODE_FIXED = 0x2,
169 } MatroskaAspectRatioMode;
172 * These aren't in any way "matroska-form" things,
173 * it's just something I use in the muxer/demuxer.
177 MATROSKA_TRACK_ENABLED = (1<<0),
178 MATROSKA_TRACK_DEFAULT = (1<<1),
179 MATROSKA_TRACK_LACING = (1<<2),
180 MATROSKA_TRACK_REAL_V = (1<<4),
181 MATROSKA_TRACK_SHIFT = (1<<16)
182 } MatroskaTrackFlags;
185 MATROSKA_VIDEOTRACK_INTERLACED = (MATROSKA_TRACK_SHIFT<<0)
186 } MatroskaVideoTrackFlags;
189 * Matroska Codec IDs. Strings.
192 typedef struct CodecTags{
197 #define MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC "V_MS/VFW/FOURCC"
198 #define MATROSKA_CODEC_ID_AUDIO_ACM "A_MS/ACM"
200 static CodecTags codec_tags[]={
201 // {"V_MS/VFW/FOURCC" , CODEC_ID_NONE},
202 {"V_UNCOMPRESSED" , CODEC_ID_RAWVIDEO},
203 {"V_MPEG4/ISO/SP" , CODEC_ID_MPEG4},
204 {"V_MPEG4/ISO/ASP" , CODEC_ID_MPEG4},
205 {"V_MPEG4/ISO/AP" , CODEC_ID_MPEG4},
206 {"V_MPEG4/ISO/AVC" , CODEC_ID_H264},
207 {"V_MPEG4/MS/V3" , CODEC_ID_MSMPEG4V3},
208 {"V_MPEG1" , CODEC_ID_MPEG1VIDEO},
209 {"V_MPEG2" , CODEC_ID_MPEG2VIDEO},
210 {"V_MJPEG" , CODEC_ID_MJPEG},
211 {"V_REAL/RV10" , CODEC_ID_RV10},
212 {"V_REAL/RV20" , CODEC_ID_RV20},
213 {"V_REAL/RV30" , CODEC_ID_RV30},
214 {"V_REAL/RV40" , CODEC_ID_RV40},
215 {"V_THEORA" , CODEC_ID_THEORA},
216 /* TODO: Real/Quicktime */
218 // {"A_MS/ACM" , CODEC_ID_NONE},
219 {"A_MPEG/L1" , CODEC_ID_MP3},
220 {"A_MPEG/L2" , CODEC_ID_MP3},
221 {"A_MPEG/L3" , CODEC_ID_MP3},
222 {"A_PCM/INT/BIG" , CODEC_ID_PCM_U16BE},
223 {"A_PCM/INT/LIT" , CODEC_ID_PCM_U16LE},
224 // {"A_PCM/FLOAT/IEEE" , CODEC_ID_NONE},
225 {"A_AC3" , CODEC_ID_AC3},
226 {"A_DTS" , CODEC_ID_DTS},
227 {"A_VORBIS" , CODEC_ID_VORBIS},
228 {"A_AAC" , CODEC_ID_AAC},
229 {"A_FLAC" , CODEC_ID_FLAC},
230 {"A_WAVPACK4" , CODEC_ID_WAVPACK},
231 {"A_TTA1" , CODEC_ID_TTA},
232 {NULL , CODEC_ID_NONE}
233 /* TODO: AC3-9/10 (?), Real, Musepack, Quicktime */
236 /* max. depth in the EBML tree structure */
237 #define EBML_MAX_DEPTH 16
239 typedef struct Track {
240 MatroskaTrackType type;
242 /* Unique track number and track ID. stream_index is the index that
243 * the calling app uses for this track. */
254 unsigned char *codec_priv;
257 uint64_t default_duration;
258 MatroskaTrackFlags flags;
261 typedef struct MatroskaVideoTrack {
271 MatroskaAspectRatioMode ar_mode;
272 MatroskaEyeMode eye_mode;
275 } MatroskaVideoTrack;
277 typedef struct MatroskaAudioTrack {
285 } MatroskaAudioTrack;
287 typedef struct MatroskaSubtitleTrack {
291 } MatroskaSubtitleTrack;
293 #define MAX_TRACK_SIZE (FFMAX(FFMAX(sizeof(MatroskaVideoTrack), \
294 sizeof(MatroskaAudioTrack)), \
295 sizeof(MatroskaSubtitleTrack)))
297 typedef struct MatroskaLevel {
298 uint64_t start, length;
301 typedef struct MatroskaDemuxIndex {
302 uint64_t pos; /* of the corresponding *cluster*! */
303 uint16_t track; /* reference to 'num' */
304 uint64_t time; /* in nanoseconds */
305 } MatroskaDemuxIndex;
307 typedef struct MatroskaDemuxContext {
308 AVFormatContext *ctx;
312 MatroskaLevel levels[EBML_MAX_DEPTH];
320 /* timescale in the file */
323 /* num_streams is the number of streams that av_new_stream() was called
324 * for ( = that are available to the calling program). */
325 int num_tracks, num_streams;
326 MatroskaTrack *tracks[MAX_STREAMS];
328 /* cache for ID peeking */
331 /* byte position of the segment inside the stream */
332 offset_t segment_start;
334 /* The packet queue. */
338 /* have we already parse metadata/cues/clusters? */
343 /* The index for seeking. */
345 MatroskaDemuxIndex *index;
347 /* What to skip before effectively reading a packet. */
348 int skip_to_keyframe;
349 AVStream *skip_to_stream;
350 } MatroskaDemuxContext;
353 * The first few functions handle EBML file parsing. The rest
354 * is the document interpretation. Matroska really just is a
359 * Return: the amount of levels in the hierarchy that the
360 * current element lies higher than the previous one.
361 * The opposite isn't done - that's auto-done using master
366 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
368 ByteIOContext *pb = &matroska->ctx->pb;
369 offset_t pos = url_ftell(pb);
372 while (matroska->num_levels > 0) {
373 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
375 if (pos >= level->start + level->length) {
376 matroska->num_levels--;
387 * Read: an "EBML number", which is defined as a variable-length
388 * array of bytes. The first byte indicates the length by giving a
389 * number of 0-bits followed by a one. The position of the first
390 * "one" bit inside the first byte indicates the length of this
392 * Returns: num. of bytes read. < 0 on error.
396 ebml_read_num (MatroskaDemuxContext *matroska,
400 ByteIOContext *pb = &matroska->ctx->pb;
401 int len_mask = 0x80, read = 1, n = 1;
404 /* the first byte tells us the length in bytes - get_byte() can normally
405 * return 0, but since that's not a valid first ebmlID byte, we can
406 * use it safely here to catch EOS. */
407 if (!(total = get_byte(pb))) {
408 /* we might encounter EOS here */
410 offset_t pos = url_ftell(pb);
411 av_log(matroska->ctx, AV_LOG_ERROR,
412 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
415 return AVERROR_IO; /* EOS or actual I/O error */
418 /* get the length of the EBML number */
419 while (read <= max_size && !(total & len_mask)) {
423 if (read > max_size) {
424 offset_t pos = url_ftell(pb) - 1;
425 av_log(matroska->ctx, AV_LOG_ERROR,
426 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
427 (uint8_t) total, pos, pos);
428 return AVERROR_INVALIDDATA;
431 /* read out length */
434 total = (total << 8) | get_byte(pb);
442 * Read: the element content data ID.
443 * Return: the number of bytes read or < 0 on error.
447 ebml_read_element_id (MatroskaDemuxContext *matroska,
454 /* if we re-call this, use our cached ID */
455 if (matroska->peek_id != 0) {
458 *id = matroska->peek_id;
462 /* read out the "EBML number", include tag in ID */
463 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
465 *id = matroska->peek_id = total | (1 << (read * 7));
469 *level_up = ebml_read_element_level_up(matroska);
475 * Read: element content length.
476 * Return: the number of bytes read or < 0 on error.
480 ebml_read_element_length (MatroskaDemuxContext *matroska,
483 /* clear cache since we're now beyond that data point */
484 matroska->peek_id = 0;
486 /* read out the "EBML number", include tag in ID */
487 return ebml_read_num(matroska, 8, length);
491 * Return: the ID of the next element, or 0 on error.
492 * Level_up contains the amount of levels that this
493 * next element lies higher than the previous one.
497 ebml_peek_id (MatroskaDemuxContext *matroska,
502 assert(level_up != NULL);
504 if (ebml_read_element_id(matroska, &id, level_up) < 0)
511 * Seek to a given offset.
512 * 0 is success, -1 is failure.
516 ebml_read_seek (MatroskaDemuxContext *matroska,
519 ByteIOContext *pb = &matroska->ctx->pb;
521 /* clear ID cache, if any */
522 matroska->peek_id = 0;
524 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
528 * Skip the next element.
529 * 0 is success, -1 is failure.
533 ebml_read_skip (MatroskaDemuxContext *matroska)
535 ByteIOContext *pb = &matroska->ctx->pb;
540 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
541 (res = ebml_read_element_length(matroska, &length)) < 0)
544 url_fskip(pb, length);
550 * Read the next element as an unsigned int.
551 * 0 is success, < 0 is failure.
555 ebml_read_uint (MatroskaDemuxContext *matroska,
559 ByteIOContext *pb = &matroska->ctx->pb;
560 int n = 0, size, res;
563 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
564 (res = ebml_read_element_length(matroska, &rlength)) < 0)
567 if (size < 1 || size > 8) {
568 offset_t pos = url_ftell(pb);
569 av_log(matroska->ctx, AV_LOG_ERROR,
570 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
572 return AVERROR_INVALIDDATA;
575 /* big-endian ordening; build up number */
578 *num = (*num << 8) | get_byte(pb);
584 * Read the next element as a signed int.
585 * 0 is success, < 0 is failure.
589 ebml_read_sint (MatroskaDemuxContext *matroska,
593 ByteIOContext *pb = &matroska->ctx->pb;
594 int size, n = 1, negative = 0, res;
597 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
598 (res = ebml_read_element_length(matroska, &rlength)) < 0)
601 if (size < 1 || size > 8) {
602 offset_t pos = url_ftell(pb);
603 av_log(matroska->ctx, AV_LOG_ERROR,
604 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
606 return AVERROR_INVALIDDATA;
608 if ((*num = get_byte(pb)) & 0x80) {
613 *num = (*num << 8) | get_byte(pb);
617 *num = *num - (1LL << ((8 * size) - 1));
623 * Read the next element as a float.
624 * 0 is success, < 0 is failure.
628 ebml_read_float (MatroskaDemuxContext *matroska,
632 ByteIOContext *pb = &matroska->ctx->pb;
636 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
637 (res = ebml_read_element_length(matroska, &rlength)) < 0)
642 *num= av_int2flt(get_be32(pb));
644 *num= av_int2dbl(get_be64(pb));
646 offset_t pos = url_ftell(pb);
647 av_log(matroska->ctx, AV_LOG_ERROR,
648 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
650 return AVERROR_INVALIDDATA;
657 * Read the next element as an ASCII string.
658 * 0 is success, < 0 is failure.
662 ebml_read_ascii (MatroskaDemuxContext *matroska,
666 ByteIOContext *pb = &matroska->ctx->pb;
670 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
671 (res = ebml_read_element_length(matroska, &rlength)) < 0)
675 /* ebml strings are usually not 0-terminated, so we allocate one
676 * byte more, read the string and NULL-terminate it ourselves. */
677 if (size < 0 || !(*str = av_malloc(size + 1))) {
678 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
679 return AVERROR_NOMEM;
681 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
682 offset_t pos = url_ftell(pb);
683 av_log(matroska->ctx, AV_LOG_ERROR,
684 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
693 * Read the next element as a UTF-8 string.
694 * 0 is success, < 0 is failure.
698 ebml_read_utf8 (MatroskaDemuxContext *matroska,
702 return ebml_read_ascii(matroska, id, str);
706 * Read the next element as a date (nanoseconds since 1/1/2000).
707 * 0 is success, < 0 is failure.
711 ebml_read_date (MatroskaDemuxContext *matroska,
715 return ebml_read_sint(matroska, id, date);
719 * Read the next element, but only the header. The contents
720 * are supposed to be sub-elements which can be read separately.
721 * 0 is success, < 0 is failure.
725 ebml_read_master (MatroskaDemuxContext *matroska,
728 ByteIOContext *pb = &matroska->ctx->pb;
730 MatroskaLevel *level;
733 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
734 (res = ebml_read_element_length(matroska, &length)) < 0)
737 /* protect... (Heaven forbids that the '>' is true) */
738 if (matroska->num_levels >= EBML_MAX_DEPTH) {
739 av_log(matroska->ctx, AV_LOG_ERROR,
740 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
741 return AVERROR_NOTSUPP;
745 level = &matroska->levels[matroska->num_levels++];
746 level->start = url_ftell(pb);
747 level->length = length;
753 * Read the next element as binary data.
754 * 0 is success, < 0 is failure.
758 ebml_read_binary (MatroskaDemuxContext *matroska,
763 ByteIOContext *pb = &matroska->ctx->pb;
767 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
768 (res = ebml_read_element_length(matroska, &rlength)) < 0)
772 if (!(*binary = av_malloc(*size))) {
773 av_log(matroska->ctx, AV_LOG_ERROR,
774 "Memory allocation error\n");
775 return AVERROR_NOMEM;
778 if (get_buffer(pb, *binary, *size) != *size) {
779 offset_t pos = url_ftell(pb);
780 av_log(matroska->ctx, AV_LOG_ERROR,
781 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
789 * Read signed/unsigned "EBML" numbers.
790 * Return: number of bytes processed, < 0 on error.
791 * XXX: use ebml_read_num().
795 matroska_ebmlnum_uint (uint8_t *data,
799 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
803 return AVERROR_INVALIDDATA;
806 while (read <= 8 && !(total & len_mask)) {
811 return AVERROR_INVALIDDATA;
813 if ((total &= (len_mask - 1)) == len_mask - 1)
816 return AVERROR_INVALIDDATA;
820 total = (total << 8) | data[n];
833 * Same as above, but signed.
837 matroska_ebmlnum_sint (uint8_t *data,
844 /* read as unsigned number first */
845 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
848 /* make signed (weird way) */
849 if (unum == (uint64_t)-1)
852 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
858 * Read an EBML header.
859 * 0 is success, < 0 is failure.
863 ebml_read_header (MatroskaDemuxContext *matroska,
868 int level_up, res = 0;
876 if (!(id = ebml_peek_id(matroska, &level_up)) ||
877 level_up != 0 || id != EBML_ID_HEADER) {
878 av_log(matroska->ctx, AV_LOG_ERROR,
879 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
880 return AVERROR_INVALIDDATA;
882 if ((res = ebml_read_master(matroska, &id)) < 0)
886 if (!(id = ebml_peek_id(matroska, &level_up)))
894 /* is our read version uptodate? */
895 case EBML_ID_EBMLREADVERSION: {
898 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
900 if (num > EBML_VERSION) {
901 av_log(matroska->ctx, AV_LOG_ERROR,
902 "EBML version %"PRIu64" (> %d) is not supported\n",
904 return AVERROR_INVALIDDATA;
909 /* we only handle 8 byte lengths at max */
910 case EBML_ID_EBMLMAXSIZELENGTH: {
913 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
915 if (num > sizeof(uint64_t)) {
916 av_log(matroska->ctx, AV_LOG_ERROR,
917 "Integers of size %"PRIu64" (> %zd) not supported\n",
918 num, sizeof(uint64_t));
919 return AVERROR_INVALIDDATA;
924 /* we handle 4 byte IDs at max */
925 case EBML_ID_EBMLMAXIDLENGTH: {
928 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
930 if (num > sizeof(uint32_t)) {
931 av_log(matroska->ctx, AV_LOG_ERROR,
932 "IDs of size %"PRIu64" (> %zu) not supported\n",
933 num, sizeof(uint32_t));
934 return AVERROR_INVALIDDATA;
939 case EBML_ID_DOCTYPE: {
942 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
953 case EBML_ID_DOCTYPEREADVERSION: {
956 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
964 av_log(matroska->ctx, AV_LOG_INFO,
965 "Unknown data type 0x%x in EBML header", id);
969 /* we ignore these two, as they don't tell us anything we
971 case EBML_ID_EBMLVERSION:
972 case EBML_ID_DOCTYPEVERSION:
973 res = ebml_read_skip (matroska);
983 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
988 for (i = 0; i < matroska->num_tracks; i++)
989 if (matroska->tracks[i]->num == num)
997 * Put one packet in an application-supplied AVPacket struct.
998 * Returns 0 on success or -1 on failure.
1002 matroska_deliver_packet (MatroskaDemuxContext *matroska,
1005 if (matroska->num_packets > 0) {
1006 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1007 av_free(matroska->packets[0]);
1008 if (matroska->num_packets > 1) {
1009 memmove(&matroska->packets[0], &matroska->packets[1],
1010 (matroska->num_packets - 1) * sizeof(AVPacket *));
1012 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1013 sizeof(AVPacket *));
1015 av_freep(&matroska->packets);
1017 matroska->num_packets--;
1025 * Put a packet into our internal queue. Will be delivered to the
1026 * user/application during the next get_packet() call.
1030 matroska_queue_packet (MatroskaDemuxContext *matroska,
1034 av_realloc(matroska->packets, (matroska->num_packets + 1) *
1035 sizeof(AVPacket *));
1036 matroska->packets[matroska->num_packets] = pkt;
1037 matroska->num_packets++;
1046 matroska_probe (AVProbeData *p)
1049 int len_mask = 0x80, size = 1, n = 1;
1050 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1053 if ((p->buf[0] << 24 | p->buf[1] << 16 |
1054 p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
1057 /* length of header */
1059 while (size <= 8 && !(total & len_mask)) {
1065 total &= (len_mask - 1);
1067 total = (total << 8) | p->buf[4 + n++];
1069 /* does the probe data contain the whole header? */
1070 if (p->buf_size < 4 + size + total)
1073 /* the header must contain the document type 'matroska'. For now,
1074 * we don't parse the whole header but simply check for the
1075 * availability of that array of characters inside the header.
1076 * Not fully fool-proof, but good enough. */
1077 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
1078 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1079 return AVPROBE_SCORE_MAX;
1085 * From here on, it's all XML-style DTD stuff... Needs no comments.
1089 matroska_parse_info (MatroskaDemuxContext *matroska)
1094 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
1097 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1100 } else if (matroska->level_up) {
1101 matroska->level_up--;
1106 /* cluster timecode */
1107 case MATROSKA_ID_TIMECODESCALE: {
1109 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1111 matroska->time_scale = num;
1115 case MATROSKA_ID_DURATION: {
1117 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1119 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
1123 case MATROSKA_ID_TITLE: {
1125 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1127 strncpy(matroska->ctx->title, text,
1128 sizeof(matroska->ctx->title)-1);
1133 case MATROSKA_ID_WRITINGAPP: {
1135 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1137 matroska->writing_app = text;
1141 case MATROSKA_ID_MUXINGAPP: {
1143 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1145 matroska->muxing_app = text;
1149 case MATROSKA_ID_DATEUTC: {
1151 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
1153 matroska->created = time;
1158 av_log(matroska->ctx, AV_LOG_INFO,
1159 "Unknown entry 0x%x in info header\n", id);
1163 res = ebml_read_skip(matroska);
1167 if (matroska->level_up) {
1168 matroska->level_up--;
1177 matroska_add_stream (MatroskaDemuxContext *matroska)
1181 MatroskaTrack *track;
1183 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1185 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1186 track = av_mallocz(MAX_TRACK_SIZE);
1187 matroska->num_tracks++;
1189 /* start with the master */
1190 if ((res = ebml_read_master(matroska, &id)) < 0)
1193 /* try reading the trackentry headers */
1195 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1198 } else if (matroska->level_up > 0) {
1199 matroska->level_up--;
1204 /* track number (unique stream ID) */
1205 case MATROSKA_ID_TRACKNUMBER: {
1207 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1213 /* track UID (unique identifier) */
1214 case MATROSKA_ID_TRACKUID: {
1216 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1222 /* track type (video, audio, combined, subtitle, etc.) */
1223 case MATROSKA_ID_TRACKTYPE: {
1225 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1227 if (track->type && track->type != num) {
1228 av_log(matroska->ctx, AV_LOG_INFO,
1229 "More than one tracktype in an entry - skip\n");
1234 switch (track->type) {
1235 case MATROSKA_TRACK_TYPE_VIDEO:
1236 case MATROSKA_TRACK_TYPE_AUDIO:
1237 case MATROSKA_TRACK_TYPE_SUBTITLE:
1239 case MATROSKA_TRACK_TYPE_COMPLEX:
1240 case MATROSKA_TRACK_TYPE_LOGO:
1241 case MATROSKA_TRACK_TYPE_CONTROL:
1243 av_log(matroska->ctx, AV_LOG_INFO,
1244 "Unknown or unsupported track type 0x%x\n",
1249 matroska->tracks[matroska->num_tracks - 1] = track;
1253 /* tracktype specific stuff for video */
1254 case MATROSKA_ID_TRACKVIDEO: {
1255 MatroskaVideoTrack *videotrack;
1257 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1258 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1259 av_log(matroska->ctx, AV_LOG_INFO,
1260 "video data in non-video track - ignoring\n");
1261 res = AVERROR_INVALIDDATA;
1263 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1265 videotrack = (MatroskaVideoTrack *)track;
1268 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1271 } else if (matroska->level_up > 0) {
1272 matroska->level_up--;
1277 /* fixme, this should be one-up, but I get it here */
1278 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1280 if ((res = ebml_read_uint (matroska, &id,
1283 track->default_duration = num/matroska->time_scale;
1287 /* video framerate */
1288 case MATROSKA_ID_VIDEOFRAMERATE: {
1290 if ((res = ebml_read_float(matroska, &id,
1293 track->default_duration = 1000000000/(matroska->time_scale*num);
1297 /* width of the size to display the video at */
1298 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1300 if ((res = ebml_read_uint(matroska, &id,
1303 videotrack->display_width = num;
1307 /* height of the size to display the video at */
1308 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1310 if ((res = ebml_read_uint(matroska, &id,
1313 videotrack->display_height = num;
1317 /* width of the video in the file */
1318 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1320 if ((res = ebml_read_uint(matroska, &id,
1323 videotrack->pixel_width = num;
1327 /* height of the video in the file */
1328 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1330 if ((res = ebml_read_uint(matroska, &id,
1333 videotrack->pixel_height = num;
1337 /* whether the video is interlaced */
1338 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1340 if ((res = ebml_read_uint(matroska, &id,
1345 MATROSKA_VIDEOTRACK_INTERLACED;
1348 ~MATROSKA_VIDEOTRACK_INTERLACED;
1352 /* stereo mode (whether the video has two streams,
1353 * where one is for the left eye and the other for
1354 * the right eye, which creates a 3D-like
1356 case MATROSKA_ID_VIDEOSTEREOMODE: {
1358 if ((res = ebml_read_uint(matroska, &id,
1361 if (num != MATROSKA_EYE_MODE_MONO &&
1362 num != MATROSKA_EYE_MODE_LEFT &&
1363 num != MATROSKA_EYE_MODE_RIGHT &&
1364 num != MATROSKA_EYE_MODE_BOTH) {
1365 av_log(matroska->ctx, AV_LOG_INFO,
1366 "Ignoring unknown eye mode 0x%x\n",
1370 videotrack->eye_mode = num;
1374 /* aspect ratio behaviour */
1375 case MATROSKA_ID_VIDEOASPECTRATIO: {
1377 if ((res = ebml_read_uint(matroska, &id,
1380 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1381 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1382 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1383 av_log(matroska->ctx, AV_LOG_INFO,
1384 "Ignoring unknown aspect ratio 0x%x\n",
1388 videotrack->ar_mode = num;
1392 /* colourspace (only matters for raw video)
1394 case MATROSKA_ID_VIDEOCOLOURSPACE: {
1396 if ((res = ebml_read_uint(matroska, &id,
1399 videotrack->fourcc = num;
1404 av_log(matroska->ctx, AV_LOG_INFO,
1405 "Unknown video track header entry "
1406 "0x%x - ignoring\n", id);
1410 res = ebml_read_skip(matroska);
1414 if (matroska->level_up) {
1415 matroska->level_up--;
1422 /* tracktype specific stuff for audio */
1423 case MATROSKA_ID_TRACKAUDIO: {
1424 MatroskaAudioTrack *audiotrack;
1426 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1427 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1428 av_log(matroska->ctx, AV_LOG_INFO,
1429 "audio data in non-audio track - ignoring\n");
1430 res = AVERROR_INVALIDDATA;
1432 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1434 audiotrack = (MatroskaAudioTrack *)track;
1435 audiotrack->channels = 1;
1436 audiotrack->samplerate = 8000;
1439 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1442 } else if (matroska->level_up > 0) {
1443 matroska->level_up--;
1449 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1451 if ((res = ebml_read_float(matroska, &id,
1454 audiotrack->internal_samplerate =
1455 audiotrack->samplerate = num;
1459 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1461 if ((res = ebml_read_float(matroska, &id,
1464 audiotrack->samplerate = num;
1469 case MATROSKA_ID_AUDIOBITDEPTH: {
1471 if ((res = ebml_read_uint(matroska, &id,
1474 audiotrack->bitdepth = num;
1479 case MATROSKA_ID_AUDIOCHANNELS: {
1481 if ((res = ebml_read_uint(matroska, &id,
1484 audiotrack->channels = num;
1489 av_log(matroska->ctx, AV_LOG_INFO,
1490 "Unknown audio track header entry "
1491 "0x%x - ignoring\n", id);
1495 res = ebml_read_skip(matroska);
1499 if (matroska->level_up) {
1500 matroska->level_up--;
1507 /* codec identifier */
1508 case MATROSKA_ID_CODECID: {
1510 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1512 track->codec_id = text;
1516 /* codec private data */
1517 case MATROSKA_ID_CODECPRIVATE: {
1520 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1522 track->codec_priv = data;
1523 track->codec_priv_size = size;
1527 /* name of the codec */
1528 case MATROSKA_ID_CODECNAME: {
1530 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1532 track->codec_name = text;
1536 /* name of this track */
1537 case MATROSKA_ID_TRACKNAME: {
1539 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1545 /* language (matters for audio/subtitles, mostly) */
1546 case MATROSKA_ID_TRACKLANGUAGE: {
1548 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1550 track->language = text;
1554 /* whether this is actually used */
1555 case MATROSKA_ID_TRACKFLAGENABLED: {
1557 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1560 track->flags |= MATROSKA_TRACK_ENABLED;
1562 track->flags &= ~MATROSKA_TRACK_ENABLED;
1566 /* whether it's the default for this track type */
1567 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1569 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1572 track->flags |= MATROSKA_TRACK_DEFAULT;
1574 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1578 /* lacing (like MPEG, where blocks don't end/start on frame
1580 case MATROSKA_ID_TRACKFLAGLACING: {
1582 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1585 track->flags |= MATROSKA_TRACK_LACING;
1587 track->flags &= ~MATROSKA_TRACK_LACING;
1591 /* default length (in time) of one data block in this track */
1592 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1594 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1596 track->default_duration = num / matroska->time_scale;
1601 av_log(matroska->ctx, AV_LOG_INFO,
1602 "Unknown track header entry 0x%x - ignoring\n", id);
1606 /* we ignore these because they're nothing useful. */
1607 case MATROSKA_ID_CODECINFOURL:
1608 case MATROSKA_ID_CODECDOWNLOADURL:
1609 case MATROSKA_ID_TRACKMINCACHE:
1610 case MATROSKA_ID_TRACKMAXCACHE:
1611 res = ebml_read_skip(matroska);
1615 if (matroska->level_up) {
1616 matroska->level_up--;
1625 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1630 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1633 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1636 } else if (matroska->level_up) {
1637 matroska->level_up--;
1642 /* one track within the "all-tracks" header */
1643 case MATROSKA_ID_TRACKENTRY:
1644 res = matroska_add_stream(matroska);
1648 av_log(matroska->ctx, AV_LOG_INFO,
1649 "Unknown entry 0x%x in track header\n", id);
1653 res = ebml_read_skip(matroska);
1657 if (matroska->level_up) {
1658 matroska->level_up--;
1667 matroska_parse_index (MatroskaDemuxContext *matroska)
1671 MatroskaDemuxIndex idx;
1673 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1676 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1679 } else if (matroska->level_up) {
1680 matroska->level_up--;
1685 /* one single index entry ('point') */
1686 case MATROSKA_ID_POINTENTRY:
1687 if ((res = ebml_read_master(matroska, &id)) < 0)
1690 /* in the end, we hope to fill one entry with a
1691 * timestamp, a file position and a tracknum */
1692 idx.pos = (uint64_t) -1;
1693 idx.time = (uint64_t) -1;
1694 idx.track = (uint16_t) -1;
1697 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1700 } else if (matroska->level_up) {
1701 matroska->level_up--;
1706 /* one single index entry ('point') */
1707 case MATROSKA_ID_CUETIME: {
1709 if ((res = ebml_read_uint(matroska, &id,
1712 idx.time = time * matroska->time_scale;
1716 /* position in the file + track to which it
1718 case MATROSKA_ID_CUETRACKPOSITION:
1719 if ((res = ebml_read_master(matroska, &id)) < 0)
1723 if (!(id = ebml_peek_id (matroska,
1724 &matroska->level_up))) {
1727 } else if (matroska->level_up) {
1728 matroska->level_up--;
1734 case MATROSKA_ID_CUETRACK: {
1736 if ((res = ebml_read_uint(matroska,
1743 /* position in file */
1744 case MATROSKA_ID_CUECLUSTERPOSITION: {
1746 if ((res = ebml_read_uint(matroska,
1749 idx.pos = num+matroska->segment_start;
1754 av_log(matroska->ctx, AV_LOG_INFO,
1755 "Unknown entry 0x%x in "
1756 "CuesTrackPositions\n", id);
1760 res = ebml_read_skip(matroska);
1764 if (matroska->level_up) {
1765 matroska->level_up--;
1773 av_log(matroska->ctx, AV_LOG_INFO,
1774 "Unknown entry 0x%x in cuespoint "
1779 res = ebml_read_skip(matroska);
1783 if (matroska->level_up) {
1784 matroska->level_up--;
1789 /* so let's see if we got what we wanted */
1790 if (idx.pos != (uint64_t) -1 &&
1791 idx.time != (uint64_t) -1 &&
1792 idx.track != (uint16_t) -1) {
1793 if (matroska->num_indexes % 32 == 0) {
1794 /* re-allocate bigger index */
1796 av_realloc(matroska->index,
1797 (matroska->num_indexes + 32) *
1798 sizeof(MatroskaDemuxIndex));
1800 matroska->index[matroska->num_indexes] = idx;
1801 matroska->num_indexes++;
1806 av_log(matroska->ctx, AV_LOG_INFO,
1807 "Unknown entry 0x%x in cues header\n", id);
1811 res = ebml_read_skip(matroska);
1815 if (matroska->level_up) {
1816 matroska->level_up--;
1825 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1831 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1834 } else if (matroska->level_up) {
1835 matroska->level_up--;
1840 /* Hm, this is unsupported... */
1842 av_log(matroska->ctx, AV_LOG_INFO,
1843 "Unknown entry 0x%x in metadata header\n", id);
1847 res = ebml_read_skip(matroska);
1851 if (matroska->level_up) {
1852 matroska->level_up--;
1861 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1866 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1869 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1872 } else if (matroska->level_up) {
1873 matroska->level_up--;
1878 case MATROSKA_ID_SEEKENTRY: {
1879 uint32_t seek_id = 0, peek_id_cache = 0;
1880 uint64_t seek_pos = (uint64_t) -1, t;
1882 if ((res = ebml_read_master(matroska, &id)) < 0)
1886 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1889 } else if (matroska->level_up) {
1890 matroska->level_up--;
1895 case MATROSKA_ID_SEEKID:
1896 res = ebml_read_uint(matroska, &id, &t);
1900 case MATROSKA_ID_SEEKPOSITION:
1901 res = ebml_read_uint(matroska, &id, &seek_pos);
1905 av_log(matroska->ctx, AV_LOG_INFO,
1906 "Unknown seekhead ID 0x%x\n", id);
1910 res = ebml_read_skip(matroska);
1914 if (matroska->level_up) {
1915 matroska->level_up--;
1920 if (!seek_id || seek_pos == (uint64_t) -1) {
1921 av_log(matroska->ctx, AV_LOG_INFO,
1922 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1928 case MATROSKA_ID_CUES:
1929 case MATROSKA_ID_TAGS: {
1930 uint32_t level_up = matroska->level_up;
1931 offset_t before_pos;
1933 MatroskaLevel level;
1935 /* remember the peeked ID and the current position */
1936 peek_id_cache = matroska->peek_id;
1937 before_pos = url_ftell(&matroska->ctx->pb);
1940 if ((res = ebml_read_seek(matroska, seek_pos +
1941 matroska->segment_start)) < 0)
1944 /* we don't want to lose our seekhead level, so we add
1945 * a dummy. This is a crude hack. */
1946 if (matroska->num_levels == EBML_MAX_DEPTH) {
1947 av_log(matroska->ctx, AV_LOG_INFO,
1948 "Max EBML element depth (%d) reached, "
1949 "cannot parse further.\n", EBML_MAX_DEPTH);
1950 return AVERROR_UNKNOWN;
1954 level.length = (uint64_t)-1;
1955 matroska->levels[matroska->num_levels] = level;
1956 matroska->num_levels++;
1959 if (!(id = ebml_peek_id (matroska,
1960 &matroska->level_up)))
1962 if (id != seek_id) {
1963 av_log(matroska->ctx, AV_LOG_INFO,
1964 "We looked for ID=0x%x but got "
1965 "ID=0x%x (pos=%"PRIu64")",
1966 seek_id, id, seek_pos +
1967 matroska->segment_start);
1971 /* read master + parse */
1972 if ((res = ebml_read_master(matroska, &id)) < 0)
1975 case MATROSKA_ID_CUES:
1976 if (!(res = matroska_parse_index(matroska)) ||
1977 url_feof(&matroska->ctx->pb)) {
1978 matroska->index_parsed = 1;
1982 case MATROSKA_ID_TAGS:
1983 if (!(res = matroska_parse_metadata(matroska)) ||
1984 url_feof(&matroska->ctx->pb)) {
1985 matroska->metadata_parsed = 1;
1992 /* remove dummy level */
1993 while (matroska->num_levels) {
1994 matroska->num_levels--;
1996 matroska->levels[matroska->num_levels].length;
1997 if (length == (uint64_t)-1)
2002 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
2004 matroska->peek_id = peek_id_cache;
2005 matroska->level_up = level_up;
2010 av_log(matroska->ctx, AV_LOG_INFO,
2011 "Ignoring seekhead entry for ID=0x%x\n",
2020 av_log(matroska->ctx, AV_LOG_INFO,
2021 "Unknown seekhead ID 0x%x\n", id);
2025 res = ebml_read_skip(matroska);
2029 if (matroska->level_up) {
2030 matroska->level_up--;
2038 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
2041 matroska_aac_profile (char *codec_id)
2043 static const char *aac_profiles[] = {
2048 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2049 if (strstr(codec_id, aac_profiles[profile]))
2055 matroska_aac_sri (int samplerate)
2057 static const int aac_sample_rates[] = {
2058 96000, 88200, 64000, 48000, 44100, 32000,
2059 24000, 22050, 16000, 12000, 11025, 8000,
2063 for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
2064 if (aac_sample_rates[sri] == samplerate)
2070 matroska_read_header (AVFormatContext *s,
2071 AVFormatParameters *ap)
2073 MatroskaDemuxContext *matroska = s->priv_data;
2075 int version, last_level, res = 0;
2080 /* First read the EBML header. */
2082 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2084 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2085 av_log(matroska->ctx, AV_LOG_ERROR,
2086 "Wrong EBML doctype ('%s' != 'matroska').\n",
2087 doctype ? doctype : "(none)");
2090 return AVERROR_NOFMT;
2094 av_log(matroska->ctx, AV_LOG_ERROR,
2095 "Matroska demuxer version 2 too old for file version %d\n",
2097 return AVERROR_NOFMT;
2100 /* The next thing is a segment. */
2102 if (!(id = ebml_peek_id(matroska, &last_level)))
2104 if (id == MATROSKA_ID_SEGMENT)
2108 av_log(matroska->ctx, AV_LOG_INFO,
2109 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2110 MATROSKA_ID_SEGMENT, id);
2111 if ((res = ebml_read_skip(matroska)) < 0)
2115 /* We now have a Matroska segment.
2116 * Seeks are from the beginning of the segment,
2117 * after the segment ID/length. */
2118 if ((res = ebml_read_master(matroska, &id)) < 0)
2120 matroska->segment_start = url_ftell(&s->pb);
2122 matroska->time_scale = 1000000;
2123 /* we've found our segment, start reading the different contents in here */
2125 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2128 } else if (matroska->level_up) {
2129 matroska->level_up--;
2135 case MATROSKA_ID_INFO: {
2136 if ((res = ebml_read_master(matroska, &id)) < 0)
2138 res = matroska_parse_info(matroska);
2142 /* track info headers */
2143 case MATROSKA_ID_TRACKS: {
2144 if ((res = ebml_read_master(matroska, &id)) < 0)
2146 res = matroska_parse_tracks(matroska);
2151 case MATROSKA_ID_CUES: {
2152 if (!matroska->index_parsed) {
2153 if ((res = ebml_read_master(matroska, &id)) < 0)
2155 res = matroska_parse_index(matroska);
2157 res = ebml_read_skip(matroska);
2162 case MATROSKA_ID_TAGS: {
2163 if (!matroska->metadata_parsed) {
2164 if ((res = ebml_read_master(matroska, &id)) < 0)
2166 res = matroska_parse_metadata(matroska);
2168 res = ebml_read_skip(matroska);
2172 /* file index (if seekable, seek to Cues/Tags to parse it) */
2173 case MATROSKA_ID_SEEKHEAD: {
2174 if ((res = ebml_read_master(matroska, &id)) < 0)
2176 res = matroska_parse_seekhead(matroska);
2180 case MATROSKA_ID_CLUSTER: {
2181 /* Do not read the master - this will be done in the next
2182 * call to matroska_read_packet. */
2188 av_log(matroska->ctx, AV_LOG_INFO,
2189 "Unknown matroska file header ID 0x%x\n", id);
2193 res = ebml_read_skip(matroska);
2197 if (matroska->level_up) {
2198 matroska->level_up--;
2203 /* Have we found a cluster? */
2204 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2206 MatroskaTrack *track;
2209 for (i = 0; i < matroska->num_tracks; i++) {
2210 enum CodecID codec_id = CODEC_ID_NONE;
2211 uint8_t *extradata = NULL;
2212 int extradata_size = 0;
2213 int extradata_offset = 0;
2214 track = matroska->tracks[i];
2216 /* libavformat does not really support subtitles.
2217 * Also apply some sanity checks. */
2218 if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2219 (track->codec_id == NULL))
2222 for(j=0; codec_tags[j].str; j++){
2223 if(!strncmp(codec_tags[j].str, track->codec_id,
2224 strlen(codec_tags[j].str))){
2225 codec_id= codec_tags[j].id;
2230 /* Set the FourCC from the CodecID. */
2231 /* This is the MS compatibility mode which stores a
2232 * BITMAPINFOHEADER in the CodecPrivate. */
2233 if (!strcmp(track->codec_id,
2234 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2235 (track->codec_priv_size >= 40) &&
2236 (track->codec_priv != NULL)) {
2239 /* Offset of biCompression. Stored in LE. */
2240 p = (unsigned char *)track->codec_priv + 16;
2241 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2242 (p[2] << 16) | (p[1] << 8) | p[0];
2243 codec_id = codec_get_id(codec_bmp_tags, ((MatroskaVideoTrack *)track)->fourcc);
2247 /* This is the MS compatibility mode which stores a
2248 * WAVEFORMATEX in the CodecPrivate. */
2249 else if (!strcmp(track->codec_id,
2250 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2251 (track->codec_priv_size >= 18) &&
2252 (track->codec_priv != NULL)) {
2256 /* Offset of wFormatTag. Stored in LE. */
2257 p = (unsigned char *)track->codec_priv;
2258 tag = (p[1] << 8) | p[0];
2259 codec_id = codec_get_id(codec_wav_tags, tag);
2263 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2264 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2265 int profile = matroska_aac_profile(track->codec_id);
2266 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2267 extradata = av_malloc(5);
2268 if (extradata == NULL)
2269 return AVERROR_NOMEM;
2270 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2271 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2272 if (strstr(track->codec_id, "SBR")) {
2273 sri = matroska_aac_sri(audiotrack->samplerate);
2274 extradata[2] = 0x56;
2275 extradata[3] = 0xE5;
2276 extradata[4] = 0x80 | (sri<<3);
2281 track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
2284 else if (codec_id == CODEC_ID_TTA) {
2285 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2287 extradata_size = 30;
2288 extradata = av_mallocz(extradata_size);
2289 if (extradata == NULL)
2290 return AVERROR_NOMEM;
2291 init_put_byte(&b, extradata, extradata_size, 1,
2292 NULL, NULL, NULL, NULL);
2293 put_buffer(&b, (uint8_t *) "TTA1", 4);
2295 put_le16(&b, audiotrack->channels);
2296 put_le16(&b, audiotrack->bitdepth);
2297 put_le32(&b, audiotrack->samplerate);
2298 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2301 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2302 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2303 extradata_offset = 26;
2304 track->codec_priv_size -= extradata_offset;
2305 track->flags |= MATROSKA_TRACK_REAL_V;
2308 if (codec_id == CODEC_ID_NONE) {
2309 av_log(matroska->ctx, AV_LOG_INFO,
2310 "Unknown/unsupported CodecID %s.\n",
2314 track->stream_index = matroska->num_streams;
2316 matroska->num_streams++;
2317 st = av_new_stream(s, track->stream_index);
2319 return AVERROR_NOMEM;
2320 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2322 st->codec->codec_id = codec_id;
2325 if (track->default_duration)
2326 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2327 track->default_duration, 1000, 30000);
2330 st->codec->extradata = extradata;
2331 st->codec->extradata_size = extradata_size;
2332 } else if(track->codec_priv && track->codec_priv_size > 0){
2333 st->codec->extradata = av_malloc(track->codec_priv_size);
2334 if(st->codec->extradata == NULL)
2335 return AVERROR_NOMEM;
2336 st->codec->extradata_size = track->codec_priv_size;
2337 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2338 track->codec_priv_size);
2341 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2342 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2344 st->codec->codec_type = CODEC_TYPE_VIDEO;
2345 st->codec->codec_tag = videotrack->fourcc;
2346 st->codec->width = videotrack->pixel_width;
2347 st->codec->height = videotrack->pixel_height;
2348 if (videotrack->display_width == 0)
2349 videotrack->display_width= videotrack->pixel_width;
2350 if (videotrack->display_height == 0)
2351 videotrack->display_height= videotrack->pixel_height;
2352 av_reduce(&st->codec->sample_aspect_ratio.num,
2353 &st->codec->sample_aspect_ratio.den,
2354 st->codec->height * videotrack->display_width,
2355 st->codec-> width * videotrack->display_height,
2357 st->need_parsing = 2;
2358 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2359 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2361 st->codec->codec_type = CODEC_TYPE_AUDIO;
2362 st->codec->sample_rate = audiotrack->samplerate;
2363 st->codec->channels = audiotrack->channels;
2364 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2365 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2368 /* What do we do with private data? E.g. for Vorbis. */
2373 if (matroska->index_parsed) {
2374 int i, track, stream;
2375 for (i=0; i<matroska->num_indexes; i++) {
2376 MatroskaDemuxIndex *idx = &matroska->index[i];
2377 track = matroska_find_track_by_num(matroska, idx->track);
2378 stream = matroska->tracks[track]->stream_index;
2379 av_add_index_entry(matroska->ctx->streams[stream],
2380 idx->pos, idx->time/matroska->time_scale,
2381 0, 0, AVINDEX_KEYFRAME);
2389 rv_offset(uint8_t *data, int slice, int slices)
2391 return AV_RL32(data+8*slice+4) + 8*slices;
2395 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2396 int64_t pos, uint64_t cluster_time, uint64_t duration,
2397 int is_keyframe, int is_bframe)
2403 uint8_t *origdata = data;
2405 uint32_t *lace_size = NULL;
2406 int n, flags, laces = 0;
2409 /* first byte(s): tracknum */
2410 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2411 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2418 /* fetch track from num */
2419 track = matroska_find_track_by_num(matroska, num);
2420 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2421 av_log(matroska->ctx, AV_LOG_INFO,
2422 "Invalid stream %d or size %u\n", track, size);
2426 st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2427 if (st->discard >= AVDISCARD_ALL) {
2431 if (duration == AV_NOPTS_VALUE)
2432 duration = matroska->tracks[track]->default_duration;
2434 /* block_time (relative to cluster time) */
2435 block_time = (data[0] << 8) | data[1];
2441 if (is_keyframe == -1)
2442 is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2444 if (matroska->skip_to_keyframe) {
2445 if (!is_keyframe || st != matroska->skip_to_stream)
2447 matroska->skip_to_keyframe = 0;
2450 switch ((flags & 0x06) >> 1) {
2451 case 0x0: /* no lacing */
2453 lace_size = av_mallocz(sizeof(int));
2454 lace_size[0] = size;
2457 case 0x1: /* xiph lacing */
2458 case 0x2: /* fixed-size lacing */
2459 case 0x3: /* EBML lacing */
2464 laces = (*data) + 1;
2467 lace_size = av_mallocz(laces * sizeof(int));
2469 switch ((flags & 0x06) >> 1) {
2470 case 0x1: /* xiph lacing */ {
2473 for (n = 0; res == 0 && n < laces - 1; n++) {
2480 lace_size[n] += temp;
2486 total += lace_size[n];
2488 lace_size[n] = size - total;
2492 case 0x2: /* fixed-size lacing */
2493 for (n = 0; n < laces; n++)
2494 lace_size[n] = size / laces;
2497 case 0x3: /* EBML lacing */ {
2499 n = matroska_ebmlnum_uint(data, size, &num);
2501 av_log(matroska->ctx, AV_LOG_INFO,
2502 "EBML block data error\n");
2507 total = lace_size[0] = num;
2508 for (n = 1; res == 0 && n < laces - 1; n++) {
2511 r = matroska_ebmlnum_sint (data, size, &snum);
2513 av_log(matroska->ctx, AV_LOG_INFO,
2514 "EBML block data error\n");
2519 lace_size[n] = lace_size[n - 1] + snum;
2520 total += lace_size[n];
2522 lace_size[n] = size - total;
2530 int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2531 uint64_t timecode = AV_NOPTS_VALUE;
2533 if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
2534 timecode = cluster_time + block_time;
2536 for (n = 0; n < laces; n++) {
2537 int slice, slices = 1;
2540 slices = *data++ + 1;
2544 for (slice=0; slice<slices; slice++) {
2545 int slice_size, slice_offset = 0;
2547 slice_offset = rv_offset(data, slice, slices);
2548 if (slice+1 == slices)
2549 slice_size = lace_size[n] - slice_offset;
2551 slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2552 pkt = av_mallocz(sizeof(AVPacket));
2553 /* XXX: prevent data copy... */
2554 if (av_new_packet(pkt, slice_size) < 0) {
2555 res = AVERROR_NOMEM;
2559 memcpy (pkt->data, data+slice_offset, slice_size);
2562 pkt->flags = is_keyframe;
2563 pkt->stream_index = matroska->tracks[track]->stream_index;
2565 pkt->pts = timecode;
2567 pkt->duration = duration;
2569 matroska_queue_packet(matroska, pkt);
2571 if (timecode != AV_NOPTS_VALUE)
2572 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2574 data += lace_size[n];
2584 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2585 uint64_t cluster_time)
2590 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2591 uint64_t duration = AV_NOPTS_VALUE;
2596 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2599 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2602 } else if (matroska->level_up) {
2603 matroska->level_up--;
2608 /* one block inside the group. Note, block parsing is one
2609 * of the harder things, so this code is a bit complicated.
2610 * See http://www.matroska.org/ for documentation. */
2611 case MATROSKA_ID_BLOCK: {
2612 pos = url_ftell(&matroska->ctx->pb);
2613 res = ebml_read_binary(matroska, &id, &data, &size);
2617 case MATROSKA_ID_BLOCKDURATION: {
2618 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2620 duration /= matroska->time_scale;
2624 case MATROSKA_ID_BLOCKREFERENCE: {
2626 /* We've found a reference, so not even the first frame in
2627 * the lace is a key frame. */
2629 if (last_num_packets != matroska->num_packets)
2630 matroska->packets[last_num_packets]->flags = 0;
2631 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2639 av_log(matroska->ctx, AV_LOG_INFO,
2640 "Unknown entry 0x%x in blockgroup data\n", id);
2644 res = ebml_read_skip(matroska);
2648 if (matroska->level_up) {
2649 matroska->level_up--;
2658 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2659 duration, is_keyframe, is_bframe);
2665 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2669 uint64_t cluster_time = 0;
2674 av_log(matroska->ctx, AV_LOG_DEBUG,
2675 "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2678 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2681 } else if (matroska->level_up) {
2682 matroska->level_up--;
2687 /* cluster timecode */
2688 case MATROSKA_ID_CLUSTERTIMECODE: {
2690 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2696 /* a group of blocks inside a cluster */
2697 case MATROSKA_ID_BLOCKGROUP:
2698 if ((res = ebml_read_master(matroska, &id)) < 0)
2700 res = matroska_parse_blockgroup(matroska, cluster_time);
2703 case MATROSKA_ID_SIMPLEBLOCK:
2704 pos = url_ftell(&matroska->ctx->pb);
2705 res = ebml_read_binary(matroska, &id, &data, &size);
2707 res = matroska_parse_block(matroska, data, size, pos,
2708 cluster_time, AV_NOPTS_VALUE,
2713 av_log(matroska->ctx, AV_LOG_INFO,
2714 "Unknown entry 0x%x in cluster data\n", id);
2718 res = ebml_read_skip(matroska);
2722 if (matroska->level_up) {
2723 matroska->level_up--;
2732 matroska_read_packet (AVFormatContext *s,
2735 MatroskaDemuxContext *matroska = s->priv_data;
2739 /* Read stream until we have a packet queued. */
2740 while (matroska_deliver_packet(matroska, pkt)) {
2742 /* Have we already reached the end? */
2747 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2749 } else if (matroska->level_up) {
2750 matroska->level_up--;
2755 case MATROSKA_ID_CLUSTER:
2756 if ((res = ebml_read_master(matroska, &id)) < 0)
2758 if ((res = matroska_parse_cluster(matroska)) == 0)
2759 res = 1; /* Parsed one cluster, let's get out. */
2764 res = ebml_read_skip(matroska);
2768 if (matroska->level_up) {
2769 matroska->level_up--;
2782 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2785 MatroskaDemuxContext *matroska = s->priv_data;
2786 AVStream *st = s->streams[stream_index];
2789 /* find index entry */
2790 index = av_index_search_timestamp(st, timestamp, flags);
2795 url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
2796 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2797 matroska->skip_to_stream = st;
2798 matroska->num_packets = 0;
2799 matroska->peek_id = 0;
2804 matroska_read_close (AVFormatContext *s)
2806 MatroskaDemuxContext *matroska = s->priv_data;
2809 av_free(matroska->writing_app);
2810 av_free(matroska->muxing_app);
2811 av_free(matroska->index);
2813 if (matroska->packets != NULL) {
2814 for (n = 0; n < matroska->num_packets; n++) {
2815 av_free_packet(matroska->packets[n]);
2816 av_free(matroska->packets[n]);
2818 av_free(matroska->packets);
2821 for (n = 0; n < matroska->num_tracks; n++) {
2822 MatroskaTrack *track = matroska->tracks[n];
2823 av_free(track->codec_id);
2824 av_free(track->codec_name);
2825 av_free(track->codec_priv);
2826 av_free(track->name);
2827 av_free(track->language);
2835 AVInputFormat matroska_demuxer = {
2837 "Matroska file format",
2838 sizeof(MatroskaDemuxContext),
2840 matroska_read_header,
2841 matroska_read_packet,
2842 matroska_read_close,