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 /* TODO: Real/Quicktime */
217 // {"A_MS/ACM" , CODEC_ID_NONE},
218 {"A_MPEG/L1" , CODEC_ID_MP3},
219 {"A_MPEG/L2" , CODEC_ID_MP3},
220 {"A_MPEG/L3" , CODEC_ID_MP3},
221 {"A_PCM/INT/BIG" , CODEC_ID_PCM_U16BE},
222 {"A_PCM/INT/LIT" , CODEC_ID_PCM_U16LE},
223 // {"A_PCM/FLOAT/IEEE" , CODEC_ID_NONE},
224 {"A_AC3" , CODEC_ID_AC3},
225 {"A_DTS" , CODEC_ID_DTS},
226 {"A_VORBIS" , CODEC_ID_VORBIS},
227 {"A_AAC" , CODEC_ID_AAC},
228 {"A_FLAC" , CODEC_ID_FLAC},
229 {"A_WAVPACK4" , CODEC_ID_WAVPACK},
230 {"A_TTA1" , CODEC_ID_TTA},
231 {NULL , CODEC_ID_NONE}
232 /* TODO: AC3-9/10 (?), Real, Musepack, Quicktime */
235 /* max. depth in the EBML tree structure */
236 #define EBML_MAX_DEPTH 16
238 typedef struct Track {
239 MatroskaTrackType type;
241 /* Unique track number and track ID. stream_index is the index that
242 * the calling app uses for this track. */
253 unsigned char *codec_priv;
256 int64_t default_duration;
257 MatroskaTrackFlags flags;
260 typedef struct MatroskaVideoTrack {
270 MatroskaAspectRatioMode ar_mode;
271 MatroskaEyeMode eye_mode;
274 } MatroskaVideoTrack;
276 typedef struct MatroskaAudioTrack {
284 } MatroskaAudioTrack;
286 typedef struct MatroskaSubtitleTrack {
290 } MatroskaSubtitleTrack;
292 #define MAX_TRACK_SIZE (FFMAX(FFMAX(sizeof(MatroskaVideoTrack), \
293 sizeof(MatroskaAudioTrack)), \
294 sizeof(MatroskaSubtitleTrack)))
296 typedef struct MatroskaLevel {
297 uint64_t start, length;
300 typedef struct MatroskaDemuxIndex {
301 uint64_t pos; /* of the corresponding *cluster*! */
302 uint16_t track; /* reference to 'num' */
303 uint64_t time; /* in nanoseconds */
304 } MatroskaDemuxIndex;
306 typedef struct MatroskaDemuxContext {
307 AVFormatContext *ctx;
311 MatroskaLevel levels[EBML_MAX_DEPTH];
319 /* timescale in the file */
322 /* position (time, ns) */
325 /* num_streams is the number of streams that av_new_stream() was called
326 * for ( = that are available to the calling program). */
327 int num_tracks, num_streams;
328 MatroskaTrack *tracks[MAX_STREAMS];
330 /* cache for ID peeking */
333 /* byte position of the segment inside the stream */
334 offset_t segment_start;
336 /* The packet queue. */
340 /* have we already parse metadata/cues/clusters? */
345 /* The index for seeking. */
347 MatroskaDemuxIndex *index;
348 } MatroskaDemuxContext;
351 * The first few functions handle EBML file parsing. The rest
352 * is the document interpretation. Matroska really just is a
357 * Return: the amount of levels in the hierarchy that the
358 * current element lies higher than the previous one.
359 * The opposite isn't done - that's auto-done using master
364 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
366 ByteIOContext *pb = &matroska->ctx->pb;
367 offset_t pos = url_ftell(pb);
370 while (matroska->num_levels > 0) {
371 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
373 if (pos >= level->start + level->length) {
374 matroska->num_levels--;
385 * Read: an "EBML number", which is defined as a variable-length
386 * array of bytes. The first byte indicates the length by giving a
387 * number of 0-bits followed by a one. The position of the first
388 * "one" bit inside the first byte indicates the length of this
390 * Returns: num. of bytes read. < 0 on error.
394 ebml_read_num (MatroskaDemuxContext *matroska,
398 ByteIOContext *pb = &matroska->ctx->pb;
399 int len_mask = 0x80, read = 1, n = 1;
402 /* the first byte tells us the length in bytes - get_byte() can normally
403 * return 0, but since that's not a valid first ebmlID byte, we can
404 * use it safely here to catch EOS. */
405 if (!(total = get_byte(pb))) {
406 /* we might encounter EOS here */
408 offset_t pos = url_ftell(pb);
409 av_log(matroska->ctx, AV_LOG_ERROR,
410 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
413 return AVERROR_IO; /* EOS or actual I/O error */
416 /* get the length of the EBML number */
417 while (read <= max_size && !(total & len_mask)) {
421 if (read > max_size) {
422 offset_t pos = url_ftell(pb) - 1;
423 av_log(matroska->ctx, AV_LOG_ERROR,
424 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
425 (uint8_t) total, pos, pos);
426 return AVERROR_INVALIDDATA;
429 /* read out length */
432 total = (total << 8) | get_byte(pb);
440 * Read: the element content data ID.
441 * Return: the number of bytes read or < 0 on error.
445 ebml_read_element_id (MatroskaDemuxContext *matroska,
452 /* if we re-call this, use our cached ID */
453 if (matroska->peek_id != 0) {
456 *id = matroska->peek_id;
460 /* read out the "EBML number", include tag in ID */
461 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
463 *id = matroska->peek_id = total | (1 << (read * 7));
467 *level_up = ebml_read_element_level_up(matroska);
473 * Read: element content length.
474 * Return: the number of bytes read or < 0 on error.
478 ebml_read_element_length (MatroskaDemuxContext *matroska,
481 /* clear cache since we're now beyond that data point */
482 matroska->peek_id = 0;
484 /* read out the "EBML number", include tag in ID */
485 return ebml_read_num(matroska, 8, length);
489 * Return: the ID of the next element, or 0 on error.
490 * Level_up contains the amount of levels that this
491 * next element lies higher than the previous one.
495 ebml_peek_id (MatroskaDemuxContext *matroska,
500 assert(level_up != NULL);
502 if (ebml_read_element_id(matroska, &id, level_up) < 0)
509 * Seek to a given offset.
510 * 0 is success, -1 is failure.
514 ebml_read_seek (MatroskaDemuxContext *matroska,
517 ByteIOContext *pb = &matroska->ctx->pb;
519 /* clear ID cache, if any */
520 matroska->peek_id = 0;
522 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
526 * Skip the next element.
527 * 0 is success, -1 is failure.
531 ebml_read_skip (MatroskaDemuxContext *matroska)
533 ByteIOContext *pb = &matroska->ctx->pb;
538 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
539 (res = ebml_read_element_length(matroska, &length)) < 0)
542 url_fskip(pb, length);
548 * Read the next element as an unsigned int.
549 * 0 is success, < 0 is failure.
553 ebml_read_uint (MatroskaDemuxContext *matroska,
557 ByteIOContext *pb = &matroska->ctx->pb;
558 int n = 0, size, res;
561 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
562 (res = ebml_read_element_length(matroska, &rlength)) < 0)
565 if (size < 1 || size > 8) {
566 offset_t pos = url_ftell(pb);
567 av_log(matroska->ctx, AV_LOG_ERROR,
568 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
570 return AVERROR_INVALIDDATA;
573 /* big-endian ordening; build up number */
576 *num = (*num << 8) | get_byte(pb);
582 * Read the next element as a signed int.
583 * 0 is success, < 0 is failure.
587 ebml_read_sint (MatroskaDemuxContext *matroska,
591 ByteIOContext *pb = &matroska->ctx->pb;
592 int size, n = 1, negative = 0, res;
595 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
596 (res = ebml_read_element_length(matroska, &rlength)) < 0)
599 if (size < 1 || size > 8) {
600 offset_t pos = url_ftell(pb);
601 av_log(matroska->ctx, AV_LOG_ERROR,
602 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
604 return AVERROR_INVALIDDATA;
606 if ((*num = get_byte(pb)) & 0x80) {
611 *num = (*num << 8) | get_byte(pb);
615 *num = *num - (1LL << ((8 * size) - 1));
621 * Read the next element as a float.
622 * 0 is success, < 0 is failure.
626 ebml_read_float (MatroskaDemuxContext *matroska,
630 ByteIOContext *pb = &matroska->ctx->pb;
634 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
635 (res = ebml_read_element_length(matroska, &rlength)) < 0)
640 *num= av_int2flt(get_be32(pb));
642 *num= av_int2dbl(get_be64(pb));
644 offset_t pos = url_ftell(pb);
645 av_log(matroska->ctx, AV_LOG_ERROR,
646 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
648 return AVERROR_INVALIDDATA;
655 * Read the next element as an ASCII string.
656 * 0 is success, < 0 is failure.
660 ebml_read_ascii (MatroskaDemuxContext *matroska,
664 ByteIOContext *pb = &matroska->ctx->pb;
668 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
669 (res = ebml_read_element_length(matroska, &rlength)) < 0)
673 /* ebml strings are usually not 0-terminated, so we allocate one
674 * byte more, read the string and NULL-terminate it ourselves. */
675 if (size < 0 || !(*str = av_malloc(size + 1))) {
676 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
677 return AVERROR_NOMEM;
679 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
680 offset_t pos = url_ftell(pb);
681 av_log(matroska->ctx, AV_LOG_ERROR,
682 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
691 * Read the next element as a UTF-8 string.
692 * 0 is success, < 0 is failure.
696 ebml_read_utf8 (MatroskaDemuxContext *matroska,
700 return ebml_read_ascii(matroska, id, str);
704 * Read the next element as a date (nanoseconds since 1/1/2000).
705 * 0 is success, < 0 is failure.
709 ebml_read_date (MatroskaDemuxContext *matroska,
713 return ebml_read_sint(matroska, id, date);
717 * Read the next element, but only the header. The contents
718 * are supposed to be sub-elements which can be read separately.
719 * 0 is success, < 0 is failure.
723 ebml_read_master (MatroskaDemuxContext *matroska,
726 ByteIOContext *pb = &matroska->ctx->pb;
728 MatroskaLevel *level;
731 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
732 (res = ebml_read_element_length(matroska, &length)) < 0)
735 /* protect... (Heaven forbids that the '>' is true) */
736 if (matroska->num_levels >= EBML_MAX_DEPTH) {
737 av_log(matroska->ctx, AV_LOG_ERROR,
738 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
739 return AVERROR_NOTSUPP;
743 level = &matroska->levels[matroska->num_levels++];
744 level->start = url_ftell(pb);
745 level->length = length;
751 * Read the next element as binary data.
752 * 0 is success, < 0 is failure.
756 ebml_read_binary (MatroskaDemuxContext *matroska,
761 ByteIOContext *pb = &matroska->ctx->pb;
765 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
766 (res = ebml_read_element_length(matroska, &rlength)) < 0)
770 if (!(*binary = av_malloc(*size))) {
771 av_log(matroska->ctx, AV_LOG_ERROR,
772 "Memory allocation error\n");
773 return AVERROR_NOMEM;
776 if (get_buffer(pb, *binary, *size) != *size) {
777 offset_t pos = url_ftell(pb);
778 av_log(matroska->ctx, AV_LOG_ERROR,
779 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
787 * Read signed/unsigned "EBML" numbers.
788 * Return: number of bytes processed, < 0 on error.
789 * XXX: use ebml_read_num().
793 matroska_ebmlnum_uint (uint8_t *data,
797 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
801 return AVERROR_INVALIDDATA;
804 while (read <= 8 && !(total & len_mask)) {
809 return AVERROR_INVALIDDATA;
811 if ((total &= (len_mask - 1)) == len_mask - 1)
814 return AVERROR_INVALIDDATA;
818 total = (total << 8) | data[n];
831 * Same as above, but signed.
835 matroska_ebmlnum_sint (uint8_t *data,
842 /* read as unsigned number first */
843 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
846 /* make signed (weird way) */
847 if (unum == (uint64_t)-1)
850 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
856 * Read an EBML header.
857 * 0 is success, < 0 is failure.
861 ebml_read_header (MatroskaDemuxContext *matroska,
866 int level_up, res = 0;
874 if (!(id = ebml_peek_id(matroska, &level_up)) ||
875 level_up != 0 || id != EBML_ID_HEADER) {
876 av_log(matroska->ctx, AV_LOG_ERROR,
877 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
878 return AVERROR_INVALIDDATA;
880 if ((res = ebml_read_master(matroska, &id)) < 0)
884 if (!(id = ebml_peek_id(matroska, &level_up)))
892 /* is our read version uptodate? */
893 case EBML_ID_EBMLREADVERSION: {
896 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
898 if (num > EBML_VERSION) {
899 av_log(matroska->ctx, AV_LOG_ERROR,
900 "EBML version %"PRIu64" (> %d) is not supported\n",
902 return AVERROR_INVALIDDATA;
907 /* we only handle 8 byte lengths at max */
908 case EBML_ID_EBMLMAXSIZELENGTH: {
911 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
913 if (num > sizeof(uint64_t)) {
914 av_log(matroska->ctx, AV_LOG_ERROR,
915 "Integers of size %"PRIu64" (> %zd) not supported\n",
916 num, sizeof(uint64_t));
917 return AVERROR_INVALIDDATA;
922 /* we handle 4 byte IDs at max */
923 case EBML_ID_EBMLMAXIDLENGTH: {
926 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
928 if (num > sizeof(uint32_t)) {
929 av_log(matroska->ctx, AV_LOG_ERROR,
930 "IDs of size %"PRIu64" (> %zu) not supported\n",
931 num, sizeof(uint32_t));
932 return AVERROR_INVALIDDATA;
937 case EBML_ID_DOCTYPE: {
940 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
951 case EBML_ID_DOCTYPEREADVERSION: {
954 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
962 av_log(matroska->ctx, AV_LOG_INFO,
963 "Unknown data type 0x%x in EBML header", id);
967 /* we ignore these two, as they don't tell us anything we
969 case EBML_ID_EBMLVERSION:
970 case EBML_ID_DOCTYPEVERSION:
971 res = ebml_read_skip (matroska);
980 * Put one packet in an application-supplied AVPacket struct.
981 * Returns 0 on success or -1 on failure.
985 matroska_deliver_packet (MatroskaDemuxContext *matroska,
988 if (matroska->num_packets > 0) {
989 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
990 av_free(matroska->packets[0]);
991 if (matroska->num_packets > 1) {
992 memmove(&matroska->packets[0], &matroska->packets[1],
993 (matroska->num_packets - 1) * sizeof(AVPacket *));
995 av_realloc(matroska->packets, (matroska->num_packets - 1) *
998 av_freep(&matroska->packets);
1000 matroska->num_packets--;
1008 * Put a packet into our internal queue. Will be delivered to the
1009 * user/application during the next get_packet() call.
1013 matroska_queue_packet (MatroskaDemuxContext *matroska,
1017 av_realloc(matroska->packets, (matroska->num_packets + 1) *
1018 sizeof(AVPacket *));
1019 matroska->packets[matroska->num_packets] = pkt;
1020 matroska->num_packets++;
1028 matroska_probe (AVProbeData *p)
1031 int len_mask = 0x80, size = 1, n = 1;
1032 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1034 if (p->buf_size < 5)
1038 if ((p->buf[0] << 24 | p->buf[1] << 16 |
1039 p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
1042 /* length of header */
1044 while (size <= 8 && !(total & len_mask)) {
1050 total &= (len_mask - 1);
1052 total = (total << 8) | p->buf[4 + n++];
1054 /* does the probe data contain the whole header? */
1055 if (p->buf_size < 4 + size + total)
1058 /* the header must contain the document type 'matroska'. For now,
1059 * we don't parse the whole header but simply check for the
1060 * availability of that array of characters inside the header.
1061 * Not fully fool-proof, but good enough. */
1062 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
1063 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1064 return AVPROBE_SCORE_MAX;
1070 * From here on, it's all XML-style DTD stuff... Needs no comments.
1074 matroska_parse_info (MatroskaDemuxContext *matroska)
1079 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
1082 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1085 } else if (matroska->level_up) {
1086 matroska->level_up--;
1091 /* cluster timecode */
1092 case MATROSKA_ID_TIMECODESCALE: {
1094 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1096 matroska->time_scale = num;
1100 case MATROSKA_ID_DURATION: {
1102 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1104 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
1108 case MATROSKA_ID_TITLE: {
1110 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1112 strncpy(matroska->ctx->title, text,
1113 sizeof(matroska->ctx->title)-1);
1118 case MATROSKA_ID_WRITINGAPP: {
1120 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1122 matroska->writing_app = text;
1126 case MATROSKA_ID_MUXINGAPP: {
1128 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1130 matroska->muxing_app = text;
1134 case MATROSKA_ID_DATEUTC: {
1136 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
1138 matroska->created = time;
1143 av_log(matroska->ctx, AV_LOG_INFO,
1144 "Unknown entry 0x%x in info header\n", id);
1148 res = ebml_read_skip(matroska);
1152 if (matroska->level_up) {
1153 matroska->level_up--;
1162 matroska_add_stream (MatroskaDemuxContext *matroska)
1166 MatroskaTrack *track;
1168 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1170 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1171 track = av_mallocz(MAX_TRACK_SIZE);
1172 matroska->num_tracks++;
1174 /* start with the master */
1175 if ((res = ebml_read_master(matroska, &id)) < 0)
1178 /* try reading the trackentry headers */
1180 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1183 } else if (matroska->level_up > 0) {
1184 matroska->level_up--;
1189 /* track number (unique stream ID) */
1190 case MATROSKA_ID_TRACKNUMBER: {
1192 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1198 /* track UID (unique identifier) */
1199 case MATROSKA_ID_TRACKUID: {
1201 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1207 /* track type (video, audio, combined, subtitle, etc.) */
1208 case MATROSKA_ID_TRACKTYPE: {
1210 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1212 if (track->type && track->type != num) {
1213 av_log(matroska->ctx, AV_LOG_INFO,
1214 "More than one tracktype in an entry - skip\n");
1219 switch (track->type) {
1220 case MATROSKA_TRACK_TYPE_VIDEO:
1221 case MATROSKA_TRACK_TYPE_AUDIO:
1222 case MATROSKA_TRACK_TYPE_SUBTITLE:
1224 case MATROSKA_TRACK_TYPE_COMPLEX:
1225 case MATROSKA_TRACK_TYPE_LOGO:
1226 case MATROSKA_TRACK_TYPE_CONTROL:
1228 av_log(matroska->ctx, AV_LOG_INFO,
1229 "Unknown or unsupported track type 0x%x\n",
1234 matroska->tracks[matroska->num_tracks - 1] = track;
1238 /* tracktype specific stuff for video */
1239 case MATROSKA_ID_TRACKVIDEO: {
1240 MatroskaVideoTrack *videotrack;
1242 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1243 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1244 av_log(matroska->ctx, AV_LOG_INFO,
1245 "video data in non-video track - ignoring\n");
1246 res = AVERROR_INVALIDDATA;
1248 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1250 videotrack = (MatroskaVideoTrack *)track;
1253 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1256 } else if (matroska->level_up > 0) {
1257 matroska->level_up--;
1262 /* fixme, this should be one-up, but I get it here */
1263 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1265 if ((res = ebml_read_uint (matroska, &id,
1268 track->default_duration = num;
1272 /* video framerate */
1273 case MATROSKA_ID_VIDEOFRAMERATE: {
1275 if ((res = ebml_read_float(matroska, &id,
1278 track->default_duration = 1000000000 * (1. / num);
1282 /* width of the size to display the video at */
1283 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1285 if ((res = ebml_read_uint(matroska, &id,
1288 videotrack->display_width = num;
1292 /* height of the size to display the video at */
1293 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1295 if ((res = ebml_read_uint(matroska, &id,
1298 videotrack->display_height = num;
1302 /* width of the video in the file */
1303 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1305 if ((res = ebml_read_uint(matroska, &id,
1308 videotrack->pixel_width = num;
1312 /* height of the video in the file */
1313 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1315 if ((res = ebml_read_uint(matroska, &id,
1318 videotrack->pixel_height = num;
1322 /* whether the video is interlaced */
1323 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1325 if ((res = ebml_read_uint(matroska, &id,
1330 MATROSKA_VIDEOTRACK_INTERLACED;
1333 ~MATROSKA_VIDEOTRACK_INTERLACED;
1337 /* stereo mode (whether the video has two streams,
1338 * where one is for the left eye and the other for
1339 * the right eye, which creates a 3D-like
1341 case MATROSKA_ID_VIDEOSTEREOMODE: {
1343 if ((res = ebml_read_uint(matroska, &id,
1346 if (num != MATROSKA_EYE_MODE_MONO &&
1347 num != MATROSKA_EYE_MODE_LEFT &&
1348 num != MATROSKA_EYE_MODE_RIGHT &&
1349 num != MATROSKA_EYE_MODE_BOTH) {
1350 av_log(matroska->ctx, AV_LOG_INFO,
1351 "Ignoring unknown eye mode 0x%x\n",
1355 videotrack->eye_mode = num;
1359 /* aspect ratio behaviour */
1360 case MATROSKA_ID_VIDEOASPECTRATIO: {
1362 if ((res = ebml_read_uint(matroska, &id,
1365 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1366 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1367 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1368 av_log(matroska->ctx, AV_LOG_INFO,
1369 "Ignoring unknown aspect ratio 0x%x\n",
1373 videotrack->ar_mode = num;
1377 /* colourspace (only matters for raw video)
1379 case MATROSKA_ID_VIDEOCOLOURSPACE: {
1381 if ((res = ebml_read_uint(matroska, &id,
1384 videotrack->fourcc = num;
1389 av_log(matroska->ctx, AV_LOG_INFO,
1390 "Unknown video track header entry "
1391 "0x%x - ignoring\n", id);
1395 res = ebml_read_skip(matroska);
1399 if (matroska->level_up) {
1400 matroska->level_up--;
1407 /* tracktype specific stuff for audio */
1408 case MATROSKA_ID_TRACKAUDIO: {
1409 MatroskaAudioTrack *audiotrack;
1411 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1412 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1413 av_log(matroska->ctx, AV_LOG_INFO,
1414 "audio data in non-audio track - ignoring\n");
1415 res = AVERROR_INVALIDDATA;
1417 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1419 audiotrack = (MatroskaAudioTrack *)track;
1420 audiotrack->channels = 1;
1421 audiotrack->samplerate = 8000;
1424 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1427 } else if (matroska->level_up > 0) {
1428 matroska->level_up--;
1434 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1436 if ((res = ebml_read_float(matroska, &id,
1439 audiotrack->internal_samplerate =
1440 audiotrack->samplerate = num;
1444 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1446 if ((res = ebml_read_float(matroska, &id,
1449 audiotrack->samplerate = num;
1454 case MATROSKA_ID_AUDIOBITDEPTH: {
1456 if ((res = ebml_read_uint(matroska, &id,
1459 audiotrack->bitdepth = num;
1464 case MATROSKA_ID_AUDIOCHANNELS: {
1466 if ((res = ebml_read_uint(matroska, &id,
1469 audiotrack->channels = num;
1474 av_log(matroska->ctx, AV_LOG_INFO,
1475 "Unknown audio track header entry "
1476 "0x%x - ignoring\n", id);
1480 res = ebml_read_skip(matroska);
1484 if (matroska->level_up) {
1485 matroska->level_up--;
1492 /* codec identifier */
1493 case MATROSKA_ID_CODECID: {
1495 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1497 track->codec_id = text;
1501 /* codec private data */
1502 case MATROSKA_ID_CODECPRIVATE: {
1505 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1507 track->codec_priv = data;
1508 track->codec_priv_size = size;
1512 /* name of the codec */
1513 case MATROSKA_ID_CODECNAME: {
1515 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1517 track->codec_name = text;
1521 /* name of this track */
1522 case MATROSKA_ID_TRACKNAME: {
1524 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1530 /* language (matters for audio/subtitles, mostly) */
1531 case MATROSKA_ID_TRACKLANGUAGE: {
1533 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1535 track->language = text;
1539 /* whether this is actually used */
1540 case MATROSKA_ID_TRACKFLAGENABLED: {
1542 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1545 track->flags |= MATROSKA_TRACK_ENABLED;
1547 track->flags &= ~MATROSKA_TRACK_ENABLED;
1551 /* whether it's the default for this track type */
1552 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1554 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1557 track->flags |= MATROSKA_TRACK_DEFAULT;
1559 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1563 /* lacing (like MPEG, where blocks don't end/start on frame
1565 case MATROSKA_ID_TRACKFLAGLACING: {
1567 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1570 track->flags |= MATROSKA_TRACK_LACING;
1572 track->flags &= ~MATROSKA_TRACK_LACING;
1576 /* default length (in time) of one data block in this track */
1577 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1579 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1581 track->default_duration = num;
1586 av_log(matroska->ctx, AV_LOG_INFO,
1587 "Unknown track header entry 0x%x - ignoring\n", id);
1591 /* we ignore these because they're nothing useful. */
1592 case MATROSKA_ID_CODECINFOURL:
1593 case MATROSKA_ID_CODECDOWNLOADURL:
1594 case MATROSKA_ID_TRACKMINCACHE:
1595 case MATROSKA_ID_TRACKMAXCACHE:
1596 res = ebml_read_skip(matroska);
1600 if (matroska->level_up) {
1601 matroska->level_up--;
1610 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1615 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1618 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1621 } else if (matroska->level_up) {
1622 matroska->level_up--;
1627 /* one track within the "all-tracks" header */
1628 case MATROSKA_ID_TRACKENTRY:
1629 res = matroska_add_stream(matroska);
1633 av_log(matroska->ctx, AV_LOG_INFO,
1634 "Unknown entry 0x%x in track header\n", id);
1638 res = ebml_read_skip(matroska);
1642 if (matroska->level_up) {
1643 matroska->level_up--;
1652 matroska_parse_index (MatroskaDemuxContext *matroska)
1656 MatroskaDemuxIndex idx;
1658 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1661 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1664 } else if (matroska->level_up) {
1665 matroska->level_up--;
1670 /* one single index entry ('point') */
1671 case MATROSKA_ID_POINTENTRY:
1672 if ((res = ebml_read_master(matroska, &id)) < 0)
1675 /* in the end, we hope to fill one entry with a
1676 * timestamp, a file position and a tracknum */
1677 idx.pos = (uint64_t) -1;
1678 idx.time = (uint64_t) -1;
1679 idx.track = (uint16_t) -1;
1682 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1685 } else if (matroska->level_up) {
1686 matroska->level_up--;
1691 /* one single index entry ('point') */
1692 case MATROSKA_ID_CUETIME: {
1694 if ((res = ebml_read_uint(matroska, &id,
1697 idx.time = time * matroska->time_scale;
1701 /* position in the file + track to which it
1703 case MATROSKA_ID_CUETRACKPOSITION:
1704 if ((res = ebml_read_master(matroska, &id)) < 0)
1708 if (!(id = ebml_peek_id (matroska,
1709 &matroska->level_up))) {
1712 } else if (matroska->level_up) {
1713 matroska->level_up--;
1719 case MATROSKA_ID_CUETRACK: {
1721 if ((res = ebml_read_uint(matroska,
1728 /* position in file */
1729 case MATROSKA_ID_CUECLUSTERPOSITION: {
1731 if ((res = ebml_read_uint(matroska,
1739 av_log(matroska->ctx, AV_LOG_INFO,
1740 "Unknown entry 0x%x in "
1741 "CuesTrackPositions\n", id);
1745 res = ebml_read_skip(matroska);
1749 if (matroska->level_up) {
1750 matroska->level_up--;
1758 av_log(matroska->ctx, AV_LOG_INFO,
1759 "Unknown entry 0x%x in cuespoint "
1764 res = ebml_read_skip(matroska);
1768 if (matroska->level_up) {
1769 matroska->level_up--;
1774 /* so let's see if we got what we wanted */
1775 if (idx.pos != (uint64_t) -1 &&
1776 idx.time != (uint64_t) -1 &&
1777 idx.track != (uint16_t) -1) {
1778 if (matroska->num_indexes % 32 == 0) {
1779 /* re-allocate bigger index */
1781 av_realloc(matroska->index,
1782 (matroska->num_indexes + 32) *
1783 sizeof(MatroskaDemuxIndex));
1785 matroska->index[matroska->num_indexes] = idx;
1786 matroska->num_indexes++;
1791 av_log(matroska->ctx, AV_LOG_INFO,
1792 "Unknown entry 0x%x in cues header\n", id);
1796 res = ebml_read_skip(matroska);
1800 if (matroska->level_up) {
1801 matroska->level_up--;
1810 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1816 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1819 } else if (matroska->level_up) {
1820 matroska->level_up--;
1825 /* Hm, this is unsupported... */
1827 av_log(matroska->ctx, AV_LOG_INFO,
1828 "Unknown entry 0x%x in metadata header\n", id);
1832 res = ebml_read_skip(matroska);
1836 if (matroska->level_up) {
1837 matroska->level_up--;
1846 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1851 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1854 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1857 } else if (matroska->level_up) {
1858 matroska->level_up--;
1863 case MATROSKA_ID_SEEKENTRY: {
1864 uint32_t seek_id = 0, peek_id_cache = 0;
1865 uint64_t seek_pos = (uint64_t) -1, t;
1867 if ((res = ebml_read_master(matroska, &id)) < 0)
1871 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1874 } else if (matroska->level_up) {
1875 matroska->level_up--;
1880 case MATROSKA_ID_SEEKID:
1881 res = ebml_read_uint(matroska, &id, &t);
1885 case MATROSKA_ID_SEEKPOSITION:
1886 res = ebml_read_uint(matroska, &id, &seek_pos);
1890 av_log(matroska->ctx, AV_LOG_INFO,
1891 "Unknown seekhead ID 0x%x\n", id);
1895 res = ebml_read_skip(matroska);
1899 if (matroska->level_up) {
1900 matroska->level_up--;
1905 if (!seek_id || seek_pos == (uint64_t) -1) {
1906 av_log(matroska->ctx, AV_LOG_INFO,
1907 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1913 case MATROSKA_ID_CUES:
1914 case MATROSKA_ID_TAGS: {
1915 uint32_t level_up = matroska->level_up;
1916 offset_t before_pos;
1918 MatroskaLevel level;
1920 /* remember the peeked ID and the current position */
1921 peek_id_cache = matroska->peek_id;
1922 before_pos = url_ftell(&matroska->ctx->pb);
1925 if ((res = ebml_read_seek(matroska, seek_pos +
1926 matroska->segment_start)) < 0)
1929 /* we don't want to lose our seekhead level, so we add
1930 * a dummy. This is a crude hack. */
1931 if (matroska->num_levels == EBML_MAX_DEPTH) {
1932 av_log(matroska->ctx, AV_LOG_INFO,
1933 "Max EBML element depth (%d) reached, "
1934 "cannot parse further.\n", EBML_MAX_DEPTH);
1935 return AVERROR_UNKNOWN;
1939 level.length = (uint64_t)-1;
1940 matroska->levels[matroska->num_levels] = level;
1941 matroska->num_levels++;
1944 if (!(id = ebml_peek_id (matroska,
1945 &matroska->level_up)))
1947 if (id != seek_id) {
1948 av_log(matroska->ctx, AV_LOG_INFO,
1949 "We looked for ID=0x%x but got "
1950 "ID=0x%x (pos=%"PRIu64")",
1951 seek_id, id, seek_pos +
1952 matroska->segment_start);
1956 /* read master + parse */
1957 if ((res = ebml_read_master(matroska, &id)) < 0)
1960 case MATROSKA_ID_CUES:
1961 if (!(res = matroska_parse_index(matroska)) ||
1962 url_feof(&matroska->ctx->pb)) {
1963 matroska->index_parsed = 1;
1967 case MATROSKA_ID_TAGS:
1968 if (!(res = matroska_parse_metadata(matroska)) ||
1969 url_feof(&matroska->ctx->pb)) {
1970 matroska->metadata_parsed = 1;
1977 /* remove dummy level */
1978 while (matroska->num_levels) {
1979 matroska->num_levels--;
1981 matroska->levels[matroska->num_levels].length;
1982 if (length == (uint64_t)-1)
1987 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1989 matroska->peek_id = peek_id_cache;
1990 matroska->level_up = level_up;
1995 av_log(matroska->ctx, AV_LOG_INFO,
1996 "Ignoring seekhead entry for ID=0x%x\n",
2005 av_log(matroska->ctx, AV_LOG_INFO,
2006 "Unknown seekhead ID 0x%x\n", id);
2010 res = ebml_read_skip(matroska);
2014 if (matroska->level_up) {
2015 matroska->level_up--;
2023 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
2026 matroska_aac_profile (char *codec_id)
2028 static const char *aac_profiles[] = {
2033 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2034 if (strstr(codec_id, aac_profiles[profile]))
2040 matroska_aac_sri (int samplerate)
2042 static const int aac_sample_rates[] = {
2043 96000, 88200, 64000, 48000, 44100, 32000,
2044 24000, 22050, 16000, 12000, 11025, 8000,
2048 for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
2049 if (aac_sample_rates[sri] == samplerate)
2055 matroska_read_header (AVFormatContext *s,
2056 AVFormatParameters *ap)
2058 MatroskaDemuxContext *matroska = s->priv_data;
2060 int version, last_level, res = 0;
2065 /* First read the EBML header. */
2067 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2069 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2070 av_log(matroska->ctx, AV_LOG_ERROR,
2071 "Wrong EBML doctype ('%s' != 'matroska').\n",
2072 doctype ? doctype : "(none)");
2075 return AVERROR_NOFMT;
2079 av_log(matroska->ctx, AV_LOG_ERROR,
2080 "Matroska demuxer version 2 too old for file version %d\n",
2082 return AVERROR_NOFMT;
2085 /* The next thing is a segment. */
2087 if (!(id = ebml_peek_id(matroska, &last_level)))
2089 if (id == MATROSKA_ID_SEGMENT)
2093 av_log(matroska->ctx, AV_LOG_INFO,
2094 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2095 MATROSKA_ID_SEGMENT, id);
2096 if ((res = ebml_read_skip(matroska)) < 0)
2100 /* We now have a Matroska segment.
2101 * Seeks are from the beginning of the segment,
2102 * after the segment ID/length. */
2103 if ((res = ebml_read_master(matroska, &id)) < 0)
2105 matroska->segment_start = url_ftell(&s->pb);
2107 matroska->time_scale = 1000000;
2108 /* we've found our segment, start reading the different contents in here */
2110 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2113 } else if (matroska->level_up) {
2114 matroska->level_up--;
2120 case MATROSKA_ID_INFO: {
2121 if ((res = ebml_read_master(matroska, &id)) < 0)
2123 res = matroska_parse_info(matroska);
2127 /* track info headers */
2128 case MATROSKA_ID_TRACKS: {
2129 if ((res = ebml_read_master(matroska, &id)) < 0)
2131 res = matroska_parse_tracks(matroska);
2136 case MATROSKA_ID_CUES: {
2137 if (!matroska->index_parsed) {
2138 if ((res = ebml_read_master(matroska, &id)) < 0)
2140 res = matroska_parse_index(matroska);
2142 res = ebml_read_skip(matroska);
2147 case MATROSKA_ID_TAGS: {
2148 if (!matroska->metadata_parsed) {
2149 if ((res = ebml_read_master(matroska, &id)) < 0)
2151 res = matroska_parse_metadata(matroska);
2153 res = ebml_read_skip(matroska);
2157 /* file index (if seekable, seek to Cues/Tags to parse it) */
2158 case MATROSKA_ID_SEEKHEAD: {
2159 if ((res = ebml_read_master(matroska, &id)) < 0)
2161 res = matroska_parse_seekhead(matroska);
2165 case MATROSKA_ID_CLUSTER: {
2166 /* Do not read the master - this will be done in the next
2167 * call to matroska_read_packet. */
2173 av_log(matroska->ctx, AV_LOG_INFO,
2174 "Unknown matroska file header ID 0x%x\n", id);
2178 res = ebml_read_skip(matroska);
2182 if (matroska->level_up) {
2183 matroska->level_up--;
2188 /* Have we found a cluster? */
2189 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2191 MatroskaTrack *track;
2194 for (i = 0; i < matroska->num_tracks; i++) {
2195 enum CodecID codec_id = CODEC_ID_NONE;
2196 uint8_t *extradata = NULL;
2197 int extradata_size = 0;
2198 int extradata_offset = 0;
2199 track = matroska->tracks[i];
2201 /* libavformat does not really support subtitles.
2202 * Also apply some sanity checks. */
2203 if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2204 (track->codec_id == NULL))
2207 for(j=0; codec_tags[j].str; j++){
2208 if(!strncmp(codec_tags[j].str, track->codec_id,
2209 strlen(codec_tags[j].str))){
2210 codec_id= codec_tags[j].id;
2215 /* Set the FourCC from the CodecID. */
2216 /* This is the MS compatibility mode which stores a
2217 * BITMAPINFOHEADER in the CodecPrivate. */
2218 if (!strcmp(track->codec_id,
2219 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2220 (track->codec_priv_size >= 40) &&
2221 (track->codec_priv != NULL)) {
2224 /* Offset of biCompression. Stored in LE. */
2225 p = (unsigned char *)track->codec_priv + 16;
2226 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2227 (p[2] << 16) | (p[1] << 8) | p[0];
2228 codec_id = codec_get_id(codec_bmp_tags, ((MatroskaVideoTrack *)track)->fourcc);
2232 /* This is the MS compatibility mode which stores a
2233 * WAVEFORMATEX in the CodecPrivate. */
2234 else if (!strcmp(track->codec_id,
2235 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2236 (track->codec_priv_size >= 18) &&
2237 (track->codec_priv != NULL)) {
2241 /* Offset of wFormatTag. Stored in LE. */
2242 p = (unsigned char *)track->codec_priv;
2243 tag = (p[1] << 8) | p[0];
2244 codec_id = codec_get_id(codec_wav_tags, tag);
2248 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2249 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2250 int profile = matroska_aac_profile(track->codec_id);
2251 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2252 extradata = av_malloc(5);
2253 if (extradata == NULL)
2254 return AVERROR_NOMEM;
2255 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2256 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2257 if (strstr(track->codec_id, "SBR")) {
2258 sri = matroska_aac_sri(audiotrack->samplerate);
2259 extradata[2] = 0x56;
2260 extradata[3] = 0xE5;
2261 extradata[4] = 0x80 | (sri<<3);
2268 else if (codec_id == CODEC_ID_TTA) {
2269 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2271 extradata_size = 30;
2272 extradata = av_mallocz(extradata_size);
2273 if (extradata == NULL)
2274 return AVERROR_NOMEM;
2275 init_put_byte(&b, extradata, extradata_size, 1,
2276 NULL, NULL, NULL, NULL);
2277 put_buffer(&b, (uint8_t *) "TTA1", 4);
2279 put_le16(&b, audiotrack->channels);
2280 put_le16(&b, audiotrack->bitdepth);
2281 put_le32(&b, audiotrack->samplerate);
2282 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2285 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2286 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2287 extradata_offset = 26;
2288 track->codec_priv_size -= extradata_offset;
2289 track->flags |= MATROSKA_TRACK_REAL_V;
2292 if (codec_id == CODEC_ID_NONE) {
2293 av_log(matroska->ctx, AV_LOG_INFO,
2294 "Unknown/unsupported CodecID %s.\n",
2298 track->stream_index = matroska->num_streams;
2300 matroska->num_streams++;
2301 st = av_new_stream(s, track->stream_index);
2303 return AVERROR_NOMEM;
2304 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2306 st->codec->codec_id = codec_id;
2308 if (track->default_duration)
2309 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2310 track->default_duration, 1000000000, 30000);
2313 st->codec->extradata = extradata;
2314 st->codec->extradata_size = extradata_size;
2315 } else if(track->codec_priv && track->codec_priv_size > 0){
2316 st->codec->extradata = av_malloc(track->codec_priv_size);
2317 if(st->codec->extradata == NULL)
2318 return AVERROR_NOMEM;
2319 st->codec->extradata_size = track->codec_priv_size;
2320 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2321 track->codec_priv_size);
2324 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2325 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2327 st->codec->codec_type = CODEC_TYPE_VIDEO;
2328 st->codec->codec_tag = videotrack->fourcc;
2329 st->codec->width = videotrack->pixel_width;
2330 st->codec->height = videotrack->pixel_height;
2331 if (videotrack->display_width == 0)
2332 videotrack->display_width= videotrack->pixel_width;
2333 if (videotrack->display_height == 0)
2334 videotrack->display_height= videotrack->pixel_height;
2335 av_reduce(&st->codec->sample_aspect_ratio.num,
2336 &st->codec->sample_aspect_ratio.den,
2337 st->codec->height * videotrack->display_width,
2338 st->codec-> width * videotrack->display_height,
2340 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2341 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2343 st->codec->codec_type = CODEC_TYPE_AUDIO;
2344 st->codec->sample_rate = audiotrack->samplerate;
2345 st->codec->channels = audiotrack->channels;
2346 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2347 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2350 /* What do we do with private data? E.g. for Vorbis. */
2359 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
2364 for (i = 0; i < matroska->num_tracks; i++)
2365 if (matroska->tracks[i]->num == num)
2372 rv_offset(uint8_t *data, int slice, int slices)
2374 return AV_RL32(data+8*slice+4) + 8*slices;
2378 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2379 int64_t pos, uint64_t cluster_time,
2380 int is_keyframe, int is_bframe,
2381 int *ptrack, AVPacket **ppkt)
2386 uint8_t *origdata = data;
2388 uint32_t *lace_size = NULL;
2389 int n, flags, laces = 0;
2392 /* first byte(s): tracknum */
2393 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2394 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2401 /* fetch track from num */
2402 track = matroska_find_track_by_num(matroska, num);
2403 if (ptrack) *ptrack = track;
2404 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2405 av_log(matroska->ctx, AV_LOG_INFO,
2406 "Invalid stream %d or size %u\n", track, size);
2410 if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){
2415 /* block_time (relative to cluster time) */
2416 block_time = (data[0] << 8) | data[1];
2422 if (is_keyframe == -1)
2423 is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2424 switch ((flags & 0x06) >> 1) {
2425 case 0x0: /* no lacing */
2427 lace_size = av_mallocz(sizeof(int));
2428 lace_size[0] = size;
2431 case 0x1: /* xiph lacing */
2432 case 0x2: /* fixed-size lacing */
2433 case 0x3: /* EBML lacing */
2438 laces = (*data) + 1;
2441 lace_size = av_mallocz(laces * sizeof(int));
2443 switch ((flags & 0x06) >> 1) {
2444 case 0x1: /* xiph lacing */ {
2447 for (n = 0; res == 0 && n < laces - 1; n++) {
2454 lace_size[n] += temp;
2460 total += lace_size[n];
2462 lace_size[n] = size - total;
2466 case 0x2: /* fixed-size lacing */
2467 for (n = 0; n < laces; n++)
2468 lace_size[n] = size / laces;
2471 case 0x3: /* EBML lacing */ {
2473 n = matroska_ebmlnum_uint(data, size, &num);
2475 av_log(matroska->ctx, AV_LOG_INFO,
2476 "EBML block data error\n");
2481 total = lace_size[0] = num;
2482 for (n = 1; res == 0 && n < laces - 1; n++) {
2485 r = matroska_ebmlnum_sint (data, size, &snum);
2487 av_log(matroska->ctx, AV_LOG_INFO,
2488 "EBML block data error\n");
2493 lace_size[n] = lace_size[n - 1] + snum;
2494 total += lace_size[n];
2496 lace_size[n] = size - total;
2504 int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2505 for (n = 0; n < laces; n++) {
2506 uint64_t timecode = AV_NOPTS_VALUE;
2507 int slice, slices = 1;
2510 slices = *data++ + 1;
2513 if (cluster_time != (uint64_t)-1 && n == 0) {
2514 if (cluster_time + block_time >= 0)
2515 timecode = (cluster_time + block_time) * matroska->time_scale;
2517 /* FIXME: duration */
2519 for (slice=0; slice<slices; slice++) {
2520 int slice_size, slice_offset = 0;
2522 slice_offset = rv_offset(data, slice, slices);
2523 if (slice+1 == slices)
2524 slice_size = lace_size[n] - slice_offset;
2526 slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2527 pkt = av_mallocz(sizeof(AVPacket));
2528 if (ppkt) *ppkt = pkt;
2529 /* XXX: prevent data copy... */
2530 if (av_new_packet(pkt, slice_size) < 0) {
2531 res = AVERROR_NOMEM;
2535 memcpy (pkt->data, data+slice_offset, slice_size);
2538 pkt->flags = is_keyframe;
2539 pkt->stream_index = matroska->tracks[track]->stream_index;
2541 pkt->pts = timecode;
2544 matroska_queue_packet(matroska, pkt);
2546 data += lace_size[n];
2556 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2557 uint64_t cluster_time)
2561 AVPacket *pkt = NULL;
2563 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2564 uint64_t duration = AV_NOPTS_VALUE;
2570 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2573 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2576 } else if (matroska->level_up) {
2577 matroska->level_up--;
2582 /* one block inside the group. Note, block parsing is one
2583 * of the harder things, so this code is a bit complicated.
2584 * See http://www.matroska.org/ for documentation. */
2585 case MATROSKA_ID_BLOCK: {
2586 pos = url_ftell(&matroska->ctx->pb);
2587 res = ebml_read_binary(matroska, &id, &data, &size);
2591 case MATROSKA_ID_BLOCKDURATION: {
2592 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2597 case MATROSKA_ID_BLOCKREFERENCE: {
2599 /* We've found a reference, so not even the first frame in
2600 * the lace is a key frame. */
2602 if (last_num_packets != matroska->num_packets)
2603 matroska->packets[last_num_packets]->flags = 0;
2604 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2612 av_log(matroska->ctx, AV_LOG_INFO,
2613 "Unknown entry 0x%x in blockgroup data\n", id);
2617 res = ebml_read_skip(matroska);
2621 if (matroska->level_up) {
2622 matroska->level_up--;
2631 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2632 is_keyframe, is_bframe, &track, &pkt);
2636 if (duration != AV_NOPTS_VALUE)
2637 pkt->duration = duration;
2638 else if (track >= 0 && track < matroska->num_tracks)
2639 pkt->duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2646 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2650 uint64_t cluster_time = 0;
2655 av_log(matroska->ctx, AV_LOG_DEBUG,
2656 "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2659 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2662 } else if (matroska->level_up) {
2663 matroska->level_up--;
2668 /* cluster timecode */
2669 case MATROSKA_ID_CLUSTERTIMECODE: {
2671 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2677 /* a group of blocks inside a cluster */
2678 case MATROSKA_ID_BLOCKGROUP:
2679 if ((res = ebml_read_master(matroska, &id)) < 0)
2681 res = matroska_parse_blockgroup(matroska, cluster_time);
2684 case MATROSKA_ID_SIMPLEBLOCK:
2685 pos = url_ftell(&matroska->ctx->pb);
2686 res = ebml_read_binary(matroska, &id, &data, &size);
2688 res = matroska_parse_block(matroska, data, size, pos,
2689 cluster_time, -1,0, NULL, NULL);
2693 av_log(matroska->ctx, AV_LOG_INFO,
2694 "Unknown entry 0x%x in cluster data\n", id);
2698 res = ebml_read_skip(matroska);
2702 if (matroska->level_up) {
2703 matroska->level_up--;
2712 matroska_read_packet (AVFormatContext *s,
2715 MatroskaDemuxContext *matroska = s->priv_data;
2719 /* Read stream until we have a packet queued. */
2720 while (matroska_deliver_packet(matroska, pkt)) {
2722 /* Have we already reached the end? */
2727 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2729 } else if (matroska->level_up) {
2730 matroska->level_up--;
2735 case MATROSKA_ID_CLUSTER:
2736 if ((res = ebml_read_master(matroska, &id)) < 0)
2738 if ((res = matroska_parse_cluster(matroska)) == 0)
2739 res = 1; /* Parsed one cluster, let's get out. */
2744 res = ebml_read_skip(matroska);
2748 if (matroska->level_up) {
2749 matroska->level_up--;
2762 matroska_read_close (AVFormatContext *s)
2764 MatroskaDemuxContext *matroska = s->priv_data;
2767 av_free(matroska->writing_app);
2768 av_free(matroska->muxing_app);
2769 av_free(matroska->index);
2771 if (matroska->packets != NULL) {
2772 for (n = 0; n < matroska->num_packets; n++) {
2773 av_free_packet(matroska->packets[n]);
2774 av_free(matroska->packets[n]);
2776 av_free(matroska->packets);
2779 for (n = 0; n < matroska->num_tracks; n++) {
2780 MatroskaTrack *track = matroska->tracks[n];
2781 av_free(track->codec_id);
2782 av_free(track->codec_name);
2783 av_free(track->codec_priv);
2784 av_free(track->name);
2785 av_free(track->language);
2793 AVInputFormat matroska_demuxer = {
2795 "Matroska file format",
2796 sizeof(MatroskaDemuxContext),
2798 matroska_read_header,
2799 matroska_read_packet,
2800 matroska_read_close,