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_REORDER = (1<<8),
182 MATROSKA_TRACK_SHIFT = (1<<16)
183 } MatroskaTrackFlags;
186 MATROSKA_VIDEOTRACK_INTERLACED = (MATROSKA_TRACK_SHIFT<<0)
187 } MatroskaVideoTrackFlags;
190 * Matroska Codec IDs. Strings.
193 typedef struct CodecTags{
198 #define MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC "V_MS/VFW/FOURCC"
199 #define MATROSKA_CODEC_ID_AUDIO_ACM "A_MS/ACM"
201 static CodecTags codec_tags[]={
202 // {"V_MS/VFW/FOURCC" , CODEC_ID_NONE},
203 {"V_UNCOMPRESSED" , CODEC_ID_RAWVIDEO},
204 {"V_MPEG4/ISO/SP" , CODEC_ID_MPEG4},
205 {"V_MPEG4/ISO/ASP" , CODEC_ID_MPEG4},
206 {"V_MPEG4/ISO/AP" , CODEC_ID_MPEG4},
207 {"V_MPEG4/ISO/AVC" , CODEC_ID_H264},
208 {"V_MPEG4/MS/V3" , CODEC_ID_MSMPEG4V3},
209 {"V_MPEG1" , CODEC_ID_MPEG1VIDEO},
210 {"V_MPEG2" , CODEC_ID_MPEG2VIDEO},
211 {"V_MJPEG" , CODEC_ID_MJPEG},
212 {"V_REAL/RV10" , CODEC_ID_RV10},
213 {"V_REAL/RV20" , CODEC_ID_RV20},
214 {"V_REAL/RV30" , CODEC_ID_RV30},
215 {"V_REAL/RV40" , CODEC_ID_RV40},
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 int64_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 /* position (time, ns) */
326 /* num_streams is the number of streams that av_new_stream() was called
327 * for ( = that are available to the calling program). */
328 int num_tracks, num_streams;
329 MatroskaTrack *tracks[MAX_STREAMS];
331 /* cache for ID peeking */
334 /* byte position of the segment inside the stream */
335 offset_t segment_start;
337 /* The packet queue. */
340 /* Second packet queue used to reorder pts of some video track. */
341 AVPacket **packets_reorder;
342 int num_packets_reorder;
343 uint64_t reorder_max_pts;
345 /* have we already parse metadata/cues/clusters? */
350 /* The index for seeking. */
352 MatroskaDemuxIndex *index;
353 } MatroskaDemuxContext;
356 * The first few functions handle EBML file parsing. The rest
357 * is the document interpretation. Matroska really just is a
362 * Return: the amount of levels in the hierarchy that the
363 * current element lies higher than the previous one.
364 * The opposite isn't done - that's auto-done using master
369 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
371 ByteIOContext *pb = &matroska->ctx->pb;
372 offset_t pos = url_ftell(pb);
375 while (matroska->num_levels > 0) {
376 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
378 if (pos >= level->start + level->length) {
379 matroska->num_levels--;
390 * Read: an "EBML number", which is defined as a variable-length
391 * array of bytes. The first byte indicates the length by giving a
392 * number of 0-bits followed by a one. The position of the first
393 * "one" bit inside the first byte indicates the length of this
395 * Returns: num. of bytes read. < 0 on error.
399 ebml_read_num (MatroskaDemuxContext *matroska,
403 ByteIOContext *pb = &matroska->ctx->pb;
404 int len_mask = 0x80, read = 1, n = 1;
407 /* the first byte tells us the length in bytes - get_byte() can normally
408 * return 0, but since that's not a valid first ebmlID byte, we can
409 * use it safely here to catch EOS. */
410 if (!(total = get_byte(pb))) {
411 /* we might encounter EOS here */
413 offset_t pos = url_ftell(pb);
414 av_log(matroska->ctx, AV_LOG_ERROR,
415 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
418 return AVERROR_IO; /* EOS or actual I/O error */
421 /* get the length of the EBML number */
422 while (read <= max_size && !(total & len_mask)) {
426 if (read > max_size) {
427 offset_t pos = url_ftell(pb) - 1;
428 av_log(matroska->ctx, AV_LOG_ERROR,
429 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
430 (uint8_t) total, pos, pos);
431 return AVERROR_INVALIDDATA;
434 /* read out length */
437 total = (total << 8) | get_byte(pb);
445 * Read: the element content data ID.
446 * Return: the number of bytes read or < 0 on error.
450 ebml_read_element_id (MatroskaDemuxContext *matroska,
457 /* if we re-call this, use our cached ID */
458 if (matroska->peek_id != 0) {
461 *id = matroska->peek_id;
465 /* read out the "EBML number", include tag in ID */
466 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
468 *id = matroska->peek_id = total | (1 << (read * 7));
472 *level_up = ebml_read_element_level_up(matroska);
478 * Read: element content length.
479 * Return: the number of bytes read or < 0 on error.
483 ebml_read_element_length (MatroskaDemuxContext *matroska,
486 /* clear cache since we're now beyond that data point */
487 matroska->peek_id = 0;
489 /* read out the "EBML number", include tag in ID */
490 return ebml_read_num(matroska, 8, length);
494 * Return: the ID of the next element, or 0 on error.
495 * Level_up contains the amount of levels that this
496 * next element lies higher than the previous one.
500 ebml_peek_id (MatroskaDemuxContext *matroska,
505 assert(level_up != NULL);
507 if (ebml_read_element_id(matroska, &id, level_up) < 0)
514 * Seek to a given offset.
515 * 0 is success, -1 is failure.
519 ebml_read_seek (MatroskaDemuxContext *matroska,
522 ByteIOContext *pb = &matroska->ctx->pb;
524 /* clear ID cache, if any */
525 matroska->peek_id = 0;
527 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
531 * Skip the next element.
532 * 0 is success, -1 is failure.
536 ebml_read_skip (MatroskaDemuxContext *matroska)
538 ByteIOContext *pb = &matroska->ctx->pb;
543 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
544 (res = ebml_read_element_length(matroska, &length)) < 0)
547 url_fskip(pb, length);
553 * Read the next element as an unsigned int.
554 * 0 is success, < 0 is failure.
558 ebml_read_uint (MatroskaDemuxContext *matroska,
562 ByteIOContext *pb = &matroska->ctx->pb;
563 int n = 0, size, res;
566 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
567 (res = ebml_read_element_length(matroska, &rlength)) < 0)
570 if (size < 1 || size > 8) {
571 offset_t pos = url_ftell(pb);
572 av_log(matroska->ctx, AV_LOG_ERROR,
573 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
575 return AVERROR_INVALIDDATA;
578 /* big-endian ordening; build up number */
581 *num = (*num << 8) | get_byte(pb);
587 * Read the next element as a signed int.
588 * 0 is success, < 0 is failure.
592 ebml_read_sint (MatroskaDemuxContext *matroska,
596 ByteIOContext *pb = &matroska->ctx->pb;
597 int size, n = 1, negative = 0, res;
600 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
601 (res = ebml_read_element_length(matroska, &rlength)) < 0)
604 if (size < 1 || size > 8) {
605 offset_t pos = url_ftell(pb);
606 av_log(matroska->ctx, AV_LOG_ERROR,
607 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
609 return AVERROR_INVALIDDATA;
611 if ((*num = get_byte(pb)) & 0x80) {
616 *num = (*num << 8) | get_byte(pb);
620 *num = *num - (1LL << ((8 * size) - 1));
626 * Read the next element as a float.
627 * 0 is success, < 0 is failure.
631 ebml_read_float (MatroskaDemuxContext *matroska,
635 ByteIOContext *pb = &matroska->ctx->pb;
639 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
640 (res = ebml_read_element_length(matroska, &rlength)) < 0)
645 *num= av_int2flt(get_be32(pb));
647 *num= av_int2dbl(get_be64(pb));
649 offset_t pos = url_ftell(pb);
650 av_log(matroska->ctx, AV_LOG_ERROR,
651 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
653 return AVERROR_INVALIDDATA;
660 * Read the next element as an ASCII string.
661 * 0 is success, < 0 is failure.
665 ebml_read_ascii (MatroskaDemuxContext *matroska,
669 ByteIOContext *pb = &matroska->ctx->pb;
673 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
674 (res = ebml_read_element_length(matroska, &rlength)) < 0)
678 /* ebml strings are usually not 0-terminated, so we allocate one
679 * byte more, read the string and NULL-terminate it ourselves. */
680 if (size < 0 || !(*str = av_malloc(size + 1))) {
681 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
682 return AVERROR_NOMEM;
684 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
685 offset_t pos = url_ftell(pb);
686 av_log(matroska->ctx, AV_LOG_ERROR,
687 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
696 * Read the next element as a UTF-8 string.
697 * 0 is success, < 0 is failure.
701 ebml_read_utf8 (MatroskaDemuxContext *matroska,
705 return ebml_read_ascii(matroska, id, str);
709 * Read the next element as a date (nanoseconds since 1/1/2000).
710 * 0 is success, < 0 is failure.
714 ebml_read_date (MatroskaDemuxContext *matroska,
718 return ebml_read_sint(matroska, id, date);
722 * Read the next element, but only the header. The contents
723 * are supposed to be sub-elements which can be read separately.
724 * 0 is success, < 0 is failure.
728 ebml_read_master (MatroskaDemuxContext *matroska,
731 ByteIOContext *pb = &matroska->ctx->pb;
733 MatroskaLevel *level;
736 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
737 (res = ebml_read_element_length(matroska, &length)) < 0)
740 /* protect... (Heaven forbids that the '>' is true) */
741 if (matroska->num_levels >= EBML_MAX_DEPTH) {
742 av_log(matroska->ctx, AV_LOG_ERROR,
743 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
744 return AVERROR_NOTSUPP;
748 level = &matroska->levels[matroska->num_levels++];
749 level->start = url_ftell(pb);
750 level->length = length;
756 * Read the next element as binary data.
757 * 0 is success, < 0 is failure.
761 ebml_read_binary (MatroskaDemuxContext *matroska,
766 ByteIOContext *pb = &matroska->ctx->pb;
770 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
771 (res = ebml_read_element_length(matroska, &rlength)) < 0)
775 if (!(*binary = av_malloc(*size))) {
776 av_log(matroska->ctx, AV_LOG_ERROR,
777 "Memory allocation error\n");
778 return AVERROR_NOMEM;
781 if (get_buffer(pb, *binary, *size) != *size) {
782 offset_t pos = url_ftell(pb);
783 av_log(matroska->ctx, AV_LOG_ERROR,
784 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
792 * Read signed/unsigned "EBML" numbers.
793 * Return: number of bytes processed, < 0 on error.
794 * XXX: use ebml_read_num().
798 matroska_ebmlnum_uint (uint8_t *data,
802 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
806 return AVERROR_INVALIDDATA;
809 while (read <= 8 && !(total & len_mask)) {
814 return AVERROR_INVALIDDATA;
816 if ((total &= (len_mask - 1)) == len_mask - 1)
819 return AVERROR_INVALIDDATA;
823 total = (total << 8) | data[n];
836 * Same as above, but signed.
840 matroska_ebmlnum_sint (uint8_t *data,
847 /* read as unsigned number first */
848 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
851 /* make signed (weird way) */
852 if (unum == (uint64_t)-1)
855 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
861 * Read an EBML header.
862 * 0 is success, < 0 is failure.
866 ebml_read_header (MatroskaDemuxContext *matroska,
871 int level_up, res = 0;
879 if (!(id = ebml_peek_id(matroska, &level_up)) ||
880 level_up != 0 || id != EBML_ID_HEADER) {
881 av_log(matroska->ctx, AV_LOG_ERROR,
882 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
883 return AVERROR_INVALIDDATA;
885 if ((res = ebml_read_master(matroska, &id)) < 0)
889 if (!(id = ebml_peek_id(matroska, &level_up)))
897 /* is our read version uptodate? */
898 case EBML_ID_EBMLREADVERSION: {
901 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
903 if (num > EBML_VERSION) {
904 av_log(matroska->ctx, AV_LOG_ERROR,
905 "EBML version %"PRIu64" (> %d) is not supported\n",
907 return AVERROR_INVALIDDATA;
912 /* we only handle 8 byte lengths at max */
913 case EBML_ID_EBMLMAXSIZELENGTH: {
916 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
918 if (num > sizeof(uint64_t)) {
919 av_log(matroska->ctx, AV_LOG_ERROR,
920 "Integers of size %"PRIu64" (> %zd) not supported\n",
921 num, sizeof(uint64_t));
922 return AVERROR_INVALIDDATA;
927 /* we handle 4 byte IDs at max */
928 case EBML_ID_EBMLMAXIDLENGTH: {
931 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
933 if (num > sizeof(uint32_t)) {
934 av_log(matroska->ctx, AV_LOG_ERROR,
935 "IDs of size %"PRIu64" (> %zu) not supported\n",
936 num, sizeof(uint32_t));
937 return AVERROR_INVALIDDATA;
942 case EBML_ID_DOCTYPE: {
945 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
956 case EBML_ID_DOCTYPEREADVERSION: {
959 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
967 av_log(matroska->ctx, AV_LOG_INFO,
968 "Unknown data type 0x%x in EBML header", id);
972 /* we ignore these two, as they don't tell us anything we
974 case EBML_ID_EBMLVERSION:
975 case EBML_ID_DOCTYPEVERSION:
976 res = ebml_read_skip (matroska);
985 * Put one packet in an application-supplied AVPacket struct.
986 * Returns 0 on success or -1 on failure.
990 matroska_deliver_packet (MatroskaDemuxContext *matroska,
993 if (matroska->num_packets > 0) {
994 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
995 av_free(matroska->packets[0]);
996 if (matroska->num_packets > 1) {
997 memmove(&matroska->packets[0], &matroska->packets[1],
998 (matroska->num_packets - 1) * sizeof(AVPacket *));
1000 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1001 sizeof(AVPacket *));
1003 av_freep(&matroska->packets);
1005 matroska->num_packets--;
1013 * Put a packet into our internal queue. Will be delivered to the
1014 * user/application during the next get_packet() call.
1018 matroska_queue_packet (MatroskaDemuxContext *matroska,
1022 av_realloc(matroska->packets, (matroska->num_packets + 1) *
1023 sizeof(AVPacket *));
1024 matroska->packets[matroska->num_packets] = pkt;
1025 matroska->num_packets++;
1029 * Put a packet into our internal reordering queue. Will be moved to the
1030 * main packet queue when enough packets are available to reorder pts.
1034 matroska_queue_packet_reordered (MatroskaDemuxContext *matroska,
1038 if (matroska->num_packets_reorder && !is_bframe
1039 && pkt->pts > matroska->reorder_max_pts) {
1042 for (j=matroska->num_packets_reorder-1; j && k; j--) {
1044 for (i=0; i<j; i++) {
1045 if (matroska->packets_reorder[i]->pts > matroska->packets_reorder[i+1]->pts) {
1046 FFSWAP(uint64_t, matroska->packets_reorder[i]->pts, matroska->packets_reorder[i+1]->pts);
1051 /* then really queue the packets */
1052 for (i=0; i<matroska->num_packets_reorder; i++)
1053 matroska_queue_packet (matroska, matroska->packets_reorder[i]);
1054 matroska->num_packets_reorder = 0;
1056 matroska->packets_reorder =
1057 av_realloc(matroska->packets_reorder,
1058 (matroska->num_packets_reorder + 1) * sizeof(AVPacket *));
1059 matroska->packets_reorder[matroska->num_packets_reorder++] = pkt;
1060 if (pkt->pts > matroska->reorder_max_pts)
1061 matroska->reorder_max_pts = pkt->pts;
1070 matroska_probe (AVProbeData *p)
1073 int len_mask = 0x80, size = 1, n = 1;
1074 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1076 if (p->buf_size < 5)
1080 if ((p->buf[0] << 24 | p->buf[1] << 16 |
1081 p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
1084 /* length of header */
1086 while (size <= 8 && !(total & len_mask)) {
1092 total &= (len_mask - 1);
1094 total = (total << 8) | p->buf[4 + n++];
1096 /* does the probe data contain the whole header? */
1097 if (p->buf_size < 4 + size + total)
1100 /* the header must contain the document type 'matroska'. For now,
1101 * we don't parse the whole header but simply check for the
1102 * availability of that array of characters inside the header.
1103 * Not fully fool-proof, but good enough. */
1104 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
1105 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1106 return AVPROBE_SCORE_MAX;
1112 * From here on, it's all XML-style DTD stuff... Needs no comments.
1116 matroska_parse_info (MatroskaDemuxContext *matroska)
1121 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
1124 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1127 } else if (matroska->level_up) {
1128 matroska->level_up--;
1133 /* cluster timecode */
1134 case MATROSKA_ID_TIMECODESCALE: {
1136 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1138 matroska->time_scale = num;
1142 case MATROSKA_ID_DURATION: {
1144 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1146 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
1150 case MATROSKA_ID_TITLE: {
1152 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1154 strncpy(matroska->ctx->title, text,
1155 sizeof(matroska->ctx->title)-1);
1160 case MATROSKA_ID_WRITINGAPP: {
1162 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1164 matroska->writing_app = text;
1168 case MATROSKA_ID_MUXINGAPP: {
1170 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1172 matroska->muxing_app = text;
1176 case MATROSKA_ID_DATEUTC: {
1178 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
1180 matroska->created = time;
1185 av_log(matroska->ctx, AV_LOG_INFO,
1186 "Unknown entry 0x%x in info header\n", id);
1190 res = ebml_read_skip(matroska);
1194 if (matroska->level_up) {
1195 matroska->level_up--;
1204 matroska_add_stream (MatroskaDemuxContext *matroska)
1208 MatroskaTrack *track;
1210 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1212 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1213 track = av_mallocz(MAX_TRACK_SIZE);
1214 matroska->num_tracks++;
1216 /* start with the master */
1217 if ((res = ebml_read_master(matroska, &id)) < 0)
1220 /* try reading the trackentry headers */
1222 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1225 } else if (matroska->level_up > 0) {
1226 matroska->level_up--;
1231 /* track number (unique stream ID) */
1232 case MATROSKA_ID_TRACKNUMBER: {
1234 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1240 /* track UID (unique identifier) */
1241 case MATROSKA_ID_TRACKUID: {
1243 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1249 /* track type (video, audio, combined, subtitle, etc.) */
1250 case MATROSKA_ID_TRACKTYPE: {
1252 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1254 if (track->type && track->type != num) {
1255 av_log(matroska->ctx, AV_LOG_INFO,
1256 "More than one tracktype in an entry - skip\n");
1261 switch (track->type) {
1262 case MATROSKA_TRACK_TYPE_VIDEO:
1263 case MATROSKA_TRACK_TYPE_AUDIO:
1264 case MATROSKA_TRACK_TYPE_SUBTITLE:
1266 case MATROSKA_TRACK_TYPE_COMPLEX:
1267 case MATROSKA_TRACK_TYPE_LOGO:
1268 case MATROSKA_TRACK_TYPE_CONTROL:
1270 av_log(matroska->ctx, AV_LOG_INFO,
1271 "Unknown or unsupported track type 0x%x\n",
1276 matroska->tracks[matroska->num_tracks - 1] = track;
1280 /* tracktype specific stuff for video */
1281 case MATROSKA_ID_TRACKVIDEO: {
1282 MatroskaVideoTrack *videotrack;
1284 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1285 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1286 av_log(matroska->ctx, AV_LOG_INFO,
1287 "video data in non-video track - ignoring\n");
1288 res = AVERROR_INVALIDDATA;
1290 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1292 videotrack = (MatroskaVideoTrack *)track;
1295 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1298 } else if (matroska->level_up > 0) {
1299 matroska->level_up--;
1304 /* fixme, this should be one-up, but I get it here */
1305 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1307 if ((res = ebml_read_uint (matroska, &id,
1310 track->default_duration = num;
1314 /* video framerate */
1315 case MATROSKA_ID_VIDEOFRAMERATE: {
1317 if ((res = ebml_read_float(matroska, &id,
1320 track->default_duration = 1000000000 * (1. / num);
1324 /* width of the size to display the video at */
1325 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1327 if ((res = ebml_read_uint(matroska, &id,
1330 videotrack->display_width = num;
1334 /* height of the size to display the video at */
1335 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1337 if ((res = ebml_read_uint(matroska, &id,
1340 videotrack->display_height = num;
1344 /* width of the video in the file */
1345 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1347 if ((res = ebml_read_uint(matroska, &id,
1350 videotrack->pixel_width = num;
1354 /* height of the video in the file */
1355 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1357 if ((res = ebml_read_uint(matroska, &id,
1360 videotrack->pixel_height = num;
1364 /* whether the video is interlaced */
1365 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1367 if ((res = ebml_read_uint(matroska, &id,
1372 MATROSKA_VIDEOTRACK_INTERLACED;
1375 ~MATROSKA_VIDEOTRACK_INTERLACED;
1379 /* stereo mode (whether the video has two streams,
1380 * where one is for the left eye and the other for
1381 * the right eye, which creates a 3D-like
1383 case MATROSKA_ID_VIDEOSTEREOMODE: {
1385 if ((res = ebml_read_uint(matroska, &id,
1388 if (num != MATROSKA_EYE_MODE_MONO &&
1389 num != MATROSKA_EYE_MODE_LEFT &&
1390 num != MATROSKA_EYE_MODE_RIGHT &&
1391 num != MATROSKA_EYE_MODE_BOTH) {
1392 av_log(matroska->ctx, AV_LOG_INFO,
1393 "Ignoring unknown eye mode 0x%x\n",
1397 videotrack->eye_mode = num;
1401 /* aspect ratio behaviour */
1402 case MATROSKA_ID_VIDEOASPECTRATIO: {
1404 if ((res = ebml_read_uint(matroska, &id,
1407 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1408 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1409 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1410 av_log(matroska->ctx, AV_LOG_INFO,
1411 "Ignoring unknown aspect ratio 0x%x\n",
1415 videotrack->ar_mode = num;
1419 /* colourspace (only matters for raw video)
1421 case MATROSKA_ID_VIDEOCOLOURSPACE: {
1423 if ((res = ebml_read_uint(matroska, &id,
1426 videotrack->fourcc = num;
1431 av_log(matroska->ctx, AV_LOG_INFO,
1432 "Unknown video track header entry "
1433 "0x%x - ignoring\n", id);
1437 res = ebml_read_skip(matroska);
1441 if (matroska->level_up) {
1442 matroska->level_up--;
1449 /* tracktype specific stuff for audio */
1450 case MATROSKA_ID_TRACKAUDIO: {
1451 MatroskaAudioTrack *audiotrack;
1453 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1454 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1455 av_log(matroska->ctx, AV_LOG_INFO,
1456 "audio data in non-audio track - ignoring\n");
1457 res = AVERROR_INVALIDDATA;
1459 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1461 audiotrack = (MatroskaAudioTrack *)track;
1462 audiotrack->channels = 1;
1463 audiotrack->samplerate = 8000;
1466 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1469 } else if (matroska->level_up > 0) {
1470 matroska->level_up--;
1476 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1478 if ((res = ebml_read_float(matroska, &id,
1481 audiotrack->internal_samplerate =
1482 audiotrack->samplerate = num;
1486 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1488 if ((res = ebml_read_float(matroska, &id,
1491 audiotrack->samplerate = num;
1496 case MATROSKA_ID_AUDIOBITDEPTH: {
1498 if ((res = ebml_read_uint(matroska, &id,
1501 audiotrack->bitdepth = num;
1506 case MATROSKA_ID_AUDIOCHANNELS: {
1508 if ((res = ebml_read_uint(matroska, &id,
1511 audiotrack->channels = num;
1516 av_log(matroska->ctx, AV_LOG_INFO,
1517 "Unknown audio track header entry "
1518 "0x%x - ignoring\n", id);
1522 res = ebml_read_skip(matroska);
1526 if (matroska->level_up) {
1527 matroska->level_up--;
1534 /* codec identifier */
1535 case MATROSKA_ID_CODECID: {
1537 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1539 track->codec_id = text;
1543 /* codec private data */
1544 case MATROSKA_ID_CODECPRIVATE: {
1547 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1549 track->codec_priv = data;
1550 track->codec_priv_size = size;
1554 /* name of the codec */
1555 case MATROSKA_ID_CODECNAME: {
1557 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1559 track->codec_name = text;
1563 /* name of this track */
1564 case MATROSKA_ID_TRACKNAME: {
1566 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1572 /* language (matters for audio/subtitles, mostly) */
1573 case MATROSKA_ID_TRACKLANGUAGE: {
1575 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1577 track->language = text;
1581 /* whether this is actually used */
1582 case MATROSKA_ID_TRACKFLAGENABLED: {
1584 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1587 track->flags |= MATROSKA_TRACK_ENABLED;
1589 track->flags &= ~MATROSKA_TRACK_ENABLED;
1593 /* whether it's the default for this track type */
1594 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1596 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1599 track->flags |= MATROSKA_TRACK_DEFAULT;
1601 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1605 /* lacing (like MPEG, where blocks don't end/start on frame
1607 case MATROSKA_ID_TRACKFLAGLACING: {
1609 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1612 track->flags |= MATROSKA_TRACK_LACING;
1614 track->flags &= ~MATROSKA_TRACK_LACING;
1618 /* default length (in time) of one data block in this track */
1619 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1621 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1623 track->default_duration = num;
1628 av_log(matroska->ctx, AV_LOG_INFO,
1629 "Unknown track header entry 0x%x - ignoring\n", id);
1633 /* we ignore these because they're nothing useful. */
1634 case MATROSKA_ID_CODECINFOURL:
1635 case MATROSKA_ID_CODECDOWNLOADURL:
1636 case MATROSKA_ID_TRACKMINCACHE:
1637 case MATROSKA_ID_TRACKMAXCACHE:
1638 res = ebml_read_skip(matroska);
1642 if (matroska->level_up) {
1643 matroska->level_up--;
1652 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1657 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1660 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1663 } else if (matroska->level_up) {
1664 matroska->level_up--;
1669 /* one track within the "all-tracks" header */
1670 case MATROSKA_ID_TRACKENTRY:
1671 res = matroska_add_stream(matroska);
1675 av_log(matroska->ctx, AV_LOG_INFO,
1676 "Unknown entry 0x%x in track header\n", id);
1680 res = ebml_read_skip(matroska);
1684 if (matroska->level_up) {
1685 matroska->level_up--;
1694 matroska_parse_index (MatroskaDemuxContext *matroska)
1698 MatroskaDemuxIndex idx;
1700 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1703 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1706 } else if (matroska->level_up) {
1707 matroska->level_up--;
1712 /* one single index entry ('point') */
1713 case MATROSKA_ID_POINTENTRY:
1714 if ((res = ebml_read_master(matroska, &id)) < 0)
1717 /* in the end, we hope to fill one entry with a
1718 * timestamp, a file position and a tracknum */
1719 idx.pos = (uint64_t) -1;
1720 idx.time = (uint64_t) -1;
1721 idx.track = (uint16_t) -1;
1724 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1727 } else if (matroska->level_up) {
1728 matroska->level_up--;
1733 /* one single index entry ('point') */
1734 case MATROSKA_ID_CUETIME: {
1736 if ((res = ebml_read_uint(matroska, &id,
1739 idx.time = time * matroska->time_scale;
1743 /* position in the file + track to which it
1745 case MATROSKA_ID_CUETRACKPOSITION:
1746 if ((res = ebml_read_master(matroska, &id)) < 0)
1750 if (!(id = ebml_peek_id (matroska,
1751 &matroska->level_up))) {
1754 } else if (matroska->level_up) {
1755 matroska->level_up--;
1761 case MATROSKA_ID_CUETRACK: {
1763 if ((res = ebml_read_uint(matroska,
1770 /* position in file */
1771 case MATROSKA_ID_CUECLUSTERPOSITION: {
1773 if ((res = ebml_read_uint(matroska,
1781 av_log(matroska->ctx, AV_LOG_INFO,
1782 "Unknown entry 0x%x in "
1783 "CuesTrackPositions\n", id);
1787 res = ebml_read_skip(matroska);
1791 if (matroska->level_up) {
1792 matroska->level_up--;
1800 av_log(matroska->ctx, AV_LOG_INFO,
1801 "Unknown entry 0x%x in cuespoint "
1806 res = ebml_read_skip(matroska);
1810 if (matroska->level_up) {
1811 matroska->level_up--;
1816 /* so let's see if we got what we wanted */
1817 if (idx.pos != (uint64_t) -1 &&
1818 idx.time != (uint64_t) -1 &&
1819 idx.track != (uint16_t) -1) {
1820 if (matroska->num_indexes % 32 == 0) {
1821 /* re-allocate bigger index */
1823 av_realloc(matroska->index,
1824 (matroska->num_indexes + 32) *
1825 sizeof(MatroskaDemuxIndex));
1827 matroska->index[matroska->num_indexes] = idx;
1828 matroska->num_indexes++;
1833 av_log(matroska->ctx, AV_LOG_INFO,
1834 "Unknown entry 0x%x in cues header\n", id);
1838 res = ebml_read_skip(matroska);
1842 if (matroska->level_up) {
1843 matroska->level_up--;
1852 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1858 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1861 } else if (matroska->level_up) {
1862 matroska->level_up--;
1867 /* Hm, this is unsupported... */
1869 av_log(matroska->ctx, AV_LOG_INFO,
1870 "Unknown entry 0x%x in metadata header\n", id);
1874 res = ebml_read_skip(matroska);
1878 if (matroska->level_up) {
1879 matroska->level_up--;
1888 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1893 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1896 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1899 } else if (matroska->level_up) {
1900 matroska->level_up--;
1905 case MATROSKA_ID_SEEKENTRY: {
1906 uint32_t seek_id = 0, peek_id_cache = 0;
1907 uint64_t seek_pos = (uint64_t) -1, t;
1909 if ((res = ebml_read_master(matroska, &id)) < 0)
1913 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1916 } else if (matroska->level_up) {
1917 matroska->level_up--;
1922 case MATROSKA_ID_SEEKID:
1923 res = ebml_read_uint(matroska, &id, &t);
1927 case MATROSKA_ID_SEEKPOSITION:
1928 res = ebml_read_uint(matroska, &id, &seek_pos);
1932 av_log(matroska->ctx, AV_LOG_INFO,
1933 "Unknown seekhead ID 0x%x\n", id);
1937 res = ebml_read_skip(matroska);
1941 if (matroska->level_up) {
1942 matroska->level_up--;
1947 if (!seek_id || seek_pos == (uint64_t) -1) {
1948 av_log(matroska->ctx, AV_LOG_INFO,
1949 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1955 case MATROSKA_ID_CUES:
1956 case MATROSKA_ID_TAGS: {
1957 uint32_t level_up = matroska->level_up;
1958 offset_t before_pos;
1960 MatroskaLevel level;
1962 /* remember the peeked ID and the current position */
1963 peek_id_cache = matroska->peek_id;
1964 before_pos = url_ftell(&matroska->ctx->pb);
1967 if ((res = ebml_read_seek(matroska, seek_pos +
1968 matroska->segment_start)) < 0)
1971 /* we don't want to lose our seekhead level, so we add
1972 * a dummy. This is a crude hack. */
1973 if (matroska->num_levels == EBML_MAX_DEPTH) {
1974 av_log(matroska->ctx, AV_LOG_INFO,
1975 "Max EBML element depth (%d) reached, "
1976 "cannot parse further.\n", EBML_MAX_DEPTH);
1977 return AVERROR_UNKNOWN;
1981 level.length = (uint64_t)-1;
1982 matroska->levels[matroska->num_levels] = level;
1983 matroska->num_levels++;
1986 if (!(id = ebml_peek_id (matroska,
1987 &matroska->level_up)))
1989 if (id != seek_id) {
1990 av_log(matroska->ctx, AV_LOG_INFO,
1991 "We looked for ID=0x%x but got "
1992 "ID=0x%x (pos=%"PRIu64")",
1993 seek_id, id, seek_pos +
1994 matroska->segment_start);
1998 /* read master + parse */
1999 if ((res = ebml_read_master(matroska, &id)) < 0)
2002 case MATROSKA_ID_CUES:
2003 if (!(res = matroska_parse_index(matroska)) ||
2004 url_feof(&matroska->ctx->pb)) {
2005 matroska->index_parsed = 1;
2009 case MATROSKA_ID_TAGS:
2010 if (!(res = matroska_parse_metadata(matroska)) ||
2011 url_feof(&matroska->ctx->pb)) {
2012 matroska->metadata_parsed = 1;
2019 /* remove dummy level */
2020 while (matroska->num_levels) {
2021 matroska->num_levels--;
2023 matroska->levels[matroska->num_levels].length;
2024 if (length == (uint64_t)-1)
2029 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
2031 matroska->peek_id = peek_id_cache;
2032 matroska->level_up = level_up;
2037 av_log(matroska->ctx, AV_LOG_INFO,
2038 "Ignoring seekhead entry for ID=0x%x\n",
2047 av_log(matroska->ctx, AV_LOG_INFO,
2048 "Unknown seekhead ID 0x%x\n", id);
2052 res = ebml_read_skip(matroska);
2056 if (matroska->level_up) {
2057 matroska->level_up--;
2065 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
2068 matroska_aac_profile (char *codec_id)
2070 static const char *aac_profiles[] = {
2075 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2076 if (strstr(codec_id, aac_profiles[profile]))
2082 matroska_aac_sri (int samplerate)
2084 static const int aac_sample_rates[] = {
2085 96000, 88200, 64000, 48000, 44100, 32000,
2086 24000, 22050, 16000, 12000, 11025, 8000,
2090 for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
2091 if (aac_sample_rates[sri] == samplerate)
2097 matroska_read_header (AVFormatContext *s,
2098 AVFormatParameters *ap)
2100 MatroskaDemuxContext *matroska = s->priv_data;
2102 int version, last_level, res = 0;
2107 /* First read the EBML header. */
2109 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2111 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2112 av_log(matroska->ctx, AV_LOG_ERROR,
2113 "Wrong EBML doctype ('%s' != 'matroska').\n",
2114 doctype ? doctype : "(none)");
2117 return AVERROR_NOFMT;
2121 av_log(matroska->ctx, AV_LOG_ERROR,
2122 "Matroska demuxer version 2 too old for file version %d\n",
2124 return AVERROR_NOFMT;
2127 /* The next thing is a segment. */
2129 if (!(id = ebml_peek_id(matroska, &last_level)))
2131 if (id == MATROSKA_ID_SEGMENT)
2135 av_log(matroska->ctx, AV_LOG_INFO,
2136 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2137 MATROSKA_ID_SEGMENT, id);
2138 if ((res = ebml_read_skip(matroska)) < 0)
2142 /* We now have a Matroska segment.
2143 * Seeks are from the beginning of the segment,
2144 * after the segment ID/length. */
2145 if ((res = ebml_read_master(matroska, &id)) < 0)
2147 matroska->segment_start = url_ftell(&s->pb);
2149 matroska->time_scale = 1000000;
2150 /* we've found our segment, start reading the different contents in here */
2152 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2155 } else if (matroska->level_up) {
2156 matroska->level_up--;
2162 case MATROSKA_ID_INFO: {
2163 if ((res = ebml_read_master(matroska, &id)) < 0)
2165 res = matroska_parse_info(matroska);
2169 /* track info headers */
2170 case MATROSKA_ID_TRACKS: {
2171 if ((res = ebml_read_master(matroska, &id)) < 0)
2173 res = matroska_parse_tracks(matroska);
2178 case MATROSKA_ID_CUES: {
2179 if (!matroska->index_parsed) {
2180 if ((res = ebml_read_master(matroska, &id)) < 0)
2182 res = matroska_parse_index(matroska);
2184 res = ebml_read_skip(matroska);
2189 case MATROSKA_ID_TAGS: {
2190 if (!matroska->metadata_parsed) {
2191 if ((res = ebml_read_master(matroska, &id)) < 0)
2193 res = matroska_parse_metadata(matroska);
2195 res = ebml_read_skip(matroska);
2199 /* file index (if seekable, seek to Cues/Tags to parse it) */
2200 case MATROSKA_ID_SEEKHEAD: {
2201 if ((res = ebml_read_master(matroska, &id)) < 0)
2203 res = matroska_parse_seekhead(matroska);
2207 case MATROSKA_ID_CLUSTER: {
2208 /* Do not read the master - this will be done in the next
2209 * call to matroska_read_packet. */
2215 av_log(matroska->ctx, AV_LOG_INFO,
2216 "Unknown matroska file header ID 0x%x\n", id);
2220 res = ebml_read_skip(matroska);
2224 if (matroska->level_up) {
2225 matroska->level_up--;
2230 /* Have we found a cluster? */
2231 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2233 MatroskaTrack *track;
2236 for (i = 0; i < matroska->num_tracks; i++) {
2237 enum CodecID codec_id = CODEC_ID_NONE;
2238 uint8_t *extradata = NULL;
2239 int extradata_size = 0;
2240 int extradata_offset = 0;
2241 track = matroska->tracks[i];
2243 /* libavformat does not really support subtitles.
2244 * Also apply some sanity checks. */
2245 if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2246 (track->codec_id == NULL))
2249 for(j=0; codec_tags[j].str; j++){
2250 if(!strncmp(codec_tags[j].str, track->codec_id,
2251 strlen(codec_tags[j].str))){
2252 codec_id= codec_tags[j].id;
2257 /* Set the FourCC from the CodecID. */
2258 /* This is the MS compatibility mode which stores a
2259 * BITMAPINFOHEADER in the CodecPrivate. */
2260 if (!strcmp(track->codec_id,
2261 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2262 (track->codec_priv_size >= 40) &&
2263 (track->codec_priv != NULL)) {
2266 /* Offset of biCompression. Stored in LE. */
2267 p = (unsigned char *)track->codec_priv + 16;
2268 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2269 (p[2] << 16) | (p[1] << 8) | p[0];
2270 codec_id = codec_get_id(codec_bmp_tags, ((MatroskaVideoTrack *)track)->fourcc);
2274 /* This is the MS compatibility mode which stores a
2275 * WAVEFORMATEX in the CodecPrivate. */
2276 else if (!strcmp(track->codec_id,
2277 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2278 (track->codec_priv_size >= 18) &&
2279 (track->codec_priv != NULL)) {
2283 /* Offset of wFormatTag. Stored in LE. */
2284 p = (unsigned char *)track->codec_priv;
2285 tag = (p[1] << 8) | p[0];
2286 codec_id = codec_get_id(codec_wav_tags, tag);
2290 else if (codec_id == CODEC_ID_MPEG1VIDEO ||
2291 codec_id == CODEC_ID_MPEG2VIDEO ||
2292 codec_id == CODEC_ID_MPEG4 ||
2293 codec_id == CODEC_ID_MSMPEG4V3 ||
2294 codec_id == CODEC_ID_H264) {
2295 track->flags |= MATROSKA_TRACK_REORDER;
2298 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2299 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2300 int profile = matroska_aac_profile(track->codec_id);
2301 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2302 extradata = av_malloc(5);
2303 if (extradata == NULL)
2304 return AVERROR_NOMEM;
2305 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2306 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2307 if (strstr(track->codec_id, "SBR")) {
2308 sri = matroska_aac_sri(audiotrack->samplerate);
2309 extradata[2] = 0x56;
2310 extradata[3] = 0xE5;
2311 extradata[4] = 0x80 | (sri<<3);
2318 else if (codec_id == CODEC_ID_TTA) {
2319 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2321 extradata_size = 30;
2322 extradata = av_mallocz(extradata_size);
2323 if (extradata == NULL)
2324 return AVERROR_NOMEM;
2325 init_put_byte(&b, extradata, extradata_size, 1,
2326 NULL, NULL, NULL, NULL);
2327 put_buffer(&b, (uint8_t *) "TTA1", 4);
2329 put_le16(&b, audiotrack->channels);
2330 put_le16(&b, audiotrack->bitdepth);
2331 put_le32(&b, audiotrack->samplerate);
2332 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2335 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2336 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2337 extradata_offset = 26;
2338 track->codec_priv_size -= extradata_offset;
2339 track->flags |= MATROSKA_TRACK_REAL_V;
2342 if (codec_id == CODEC_ID_NONE) {
2343 av_log(matroska->ctx, AV_LOG_INFO,
2344 "Unknown/unsupported CodecID %s.\n",
2348 track->stream_index = matroska->num_streams;
2350 matroska->num_streams++;
2351 st = av_new_stream(s, track->stream_index);
2353 return AVERROR_NOMEM;
2354 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2356 st->codec->codec_id = codec_id;
2358 if (track->default_duration)
2359 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2360 track->default_duration, 1000000000, 30000);
2363 st->codec->extradata = extradata;
2364 st->codec->extradata_size = extradata_size;
2365 } else if(track->codec_priv && track->codec_priv_size > 0){
2366 st->codec->extradata = av_malloc(track->codec_priv_size);
2367 if(st->codec->extradata == NULL)
2368 return AVERROR_NOMEM;
2369 st->codec->extradata_size = track->codec_priv_size;
2370 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2371 track->codec_priv_size);
2374 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2375 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2377 st->codec->codec_type = CODEC_TYPE_VIDEO;
2378 st->codec->codec_tag = videotrack->fourcc;
2379 st->codec->width = videotrack->pixel_width;
2380 st->codec->height = videotrack->pixel_height;
2381 if (videotrack->display_width == 0)
2382 videotrack->display_width= videotrack->pixel_width;
2383 if (videotrack->display_height == 0)
2384 videotrack->display_height= videotrack->pixel_height;
2385 av_reduce(&st->codec->sample_aspect_ratio.num,
2386 &st->codec->sample_aspect_ratio.den,
2387 st->codec->height * videotrack->display_width,
2388 st->codec-> width * videotrack->display_height,
2390 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2391 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2393 st->codec->codec_type = CODEC_TYPE_AUDIO;
2394 st->codec->sample_rate = audiotrack->samplerate;
2395 st->codec->channels = audiotrack->channels;
2396 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2397 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2400 /* What do we do with private data? E.g. for Vorbis. */
2409 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
2414 for (i = 0; i < matroska->num_tracks; i++)
2415 if (matroska->tracks[i]->num == num)
2422 rv_offset(uint8_t *data, int slice, int slices)
2424 return AV_RL32(data+8*slice+4) + 8*slices;
2428 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2429 int64_t pos, uint64_t cluster_time,
2430 int is_keyframe, int is_bframe,
2431 int *ptrack, AVPacket **ppkt)
2436 uint8_t *origdata = data;
2438 uint32_t *lace_size = NULL;
2439 int n, flags, laces = 0;
2442 /* first byte(s): tracknum */
2443 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2444 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2451 /* fetch track from num */
2452 track = matroska_find_track_by_num(matroska, num);
2453 if (ptrack) *ptrack = track;
2454 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2455 av_log(matroska->ctx, AV_LOG_INFO,
2456 "Invalid stream %d or size %u\n", track, size);
2460 if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){
2465 /* block_time (relative to cluster time) */
2466 block_time = (data[0] << 8) | data[1];
2472 if (is_keyframe == -1)
2473 is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2474 switch ((flags & 0x06) >> 1) {
2475 case 0x0: /* no lacing */
2477 lace_size = av_mallocz(sizeof(int));
2478 lace_size[0] = size;
2481 case 0x1: /* xiph lacing */
2482 case 0x2: /* fixed-size lacing */
2483 case 0x3: /* EBML lacing */
2488 laces = (*data) + 1;
2491 lace_size = av_mallocz(laces * sizeof(int));
2493 switch ((flags & 0x06) >> 1) {
2494 case 0x1: /* xiph lacing */ {
2497 for (n = 0; res == 0 && n < laces - 1; n++) {
2504 lace_size[n] += temp;
2510 total += lace_size[n];
2512 lace_size[n] = size - total;
2516 case 0x2: /* fixed-size lacing */
2517 for (n = 0; n < laces; n++)
2518 lace_size[n] = size / laces;
2521 case 0x3: /* EBML lacing */ {
2523 n = matroska_ebmlnum_uint(data, size, &num);
2525 av_log(matroska->ctx, AV_LOG_INFO,
2526 "EBML block data error\n");
2531 total = lace_size[0] = num;
2532 for (n = 1; res == 0 && n < laces - 1; n++) {
2535 r = matroska_ebmlnum_sint (data, size, &snum);
2537 av_log(matroska->ctx, AV_LOG_INFO,
2538 "EBML block data error\n");
2543 lace_size[n] = lace_size[n - 1] + snum;
2544 total += lace_size[n];
2546 lace_size[n] = size - total;
2554 int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2555 for (n = 0; n < laces; n++) {
2556 uint64_t timecode = AV_NOPTS_VALUE;
2557 int slice, slices = 1;
2560 slices = *data++ + 1;
2563 if (cluster_time != (uint64_t)-1 && n == 0) {
2564 if (cluster_time + block_time >= 0)
2565 timecode = cluster_time + block_time;
2567 /* FIXME: duration */
2569 for (slice=0; slice<slices; slice++) {
2570 int slice_size, slice_offset = 0;
2572 slice_offset = rv_offset(data, slice, slices);
2573 if (slice+1 == slices)
2574 slice_size = lace_size[n] - slice_offset;
2576 slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2577 pkt = av_mallocz(sizeof(AVPacket));
2578 if (ppkt) *ppkt = pkt;
2579 /* XXX: prevent data copy... */
2580 if (av_new_packet(pkt, slice_size) < 0) {
2581 res = AVERROR_NOMEM;
2585 memcpy (pkt->data, data+slice_offset, slice_size);
2588 pkt->flags = is_keyframe;
2589 pkt->stream_index = matroska->tracks[track]->stream_index;
2591 pkt->pts = timecode;
2594 if (matroska->tracks[track]->flags & MATROSKA_TRACK_REORDER)
2595 matroska_queue_packet_reordered(matroska, pkt, is_bframe);
2597 matroska_queue_packet(matroska, pkt);
2599 data += lace_size[n];
2609 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2610 uint64_t cluster_time)
2614 AVPacket *pkt = NULL;
2616 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2617 uint64_t duration = AV_NOPTS_VALUE;
2623 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2626 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2629 } else if (matroska->level_up) {
2630 matroska->level_up--;
2635 /* one block inside the group. Note, block parsing is one
2636 * of the harder things, so this code is a bit complicated.
2637 * See http://www.matroska.org/ for documentation. */
2638 case MATROSKA_ID_BLOCK: {
2639 pos = url_ftell(&matroska->ctx->pb);
2640 res = ebml_read_binary(matroska, &id, &data, &size);
2644 case MATROSKA_ID_BLOCKDURATION: {
2645 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2650 case MATROSKA_ID_BLOCKREFERENCE: {
2652 /* We've found a reference, so not even the first frame in
2653 * the lace is a key frame. */
2655 if (last_num_packets != matroska->num_packets)
2656 matroska->packets[last_num_packets]->flags = 0;
2657 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2665 av_log(matroska->ctx, AV_LOG_INFO,
2666 "Unknown entry 0x%x in blockgroup data\n", id);
2670 res = ebml_read_skip(matroska);
2674 if (matroska->level_up) {
2675 matroska->level_up--;
2684 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2685 is_keyframe, is_bframe, &track, &pkt);
2689 if (duration != AV_NOPTS_VALUE)
2690 pkt->duration = duration;
2691 else if (track >= 0 && track < matroska->num_tracks)
2692 pkt->duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2699 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2703 uint64_t cluster_time = 0;
2708 av_log(matroska->ctx, AV_LOG_DEBUG,
2709 "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2712 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2715 } else if (matroska->level_up) {
2716 matroska->level_up--;
2721 /* cluster timecode */
2722 case MATROSKA_ID_CLUSTERTIMECODE: {
2724 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2730 /* a group of blocks inside a cluster */
2731 case MATROSKA_ID_BLOCKGROUP:
2732 if ((res = ebml_read_master(matroska, &id)) < 0)
2734 res = matroska_parse_blockgroup(matroska, cluster_time);
2737 case MATROSKA_ID_SIMPLEBLOCK:
2738 pos = url_ftell(&matroska->ctx->pb);
2739 res = ebml_read_binary(matroska, &id, &data, &size);
2741 res = matroska_parse_block(matroska, data, size, pos,
2742 cluster_time, -1,0, NULL, NULL);
2746 av_log(matroska->ctx, AV_LOG_INFO,
2747 "Unknown entry 0x%x in cluster data\n", id);
2751 res = ebml_read_skip(matroska);
2755 if (matroska->level_up) {
2756 matroska->level_up--;
2765 matroska_read_packet (AVFormatContext *s,
2768 MatroskaDemuxContext *matroska = s->priv_data;
2772 /* Read stream until we have a packet queued. */
2773 while (matroska_deliver_packet(matroska, pkt)) {
2775 /* Have we already reached the end? */
2780 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2782 } else if (matroska->level_up) {
2783 matroska->level_up--;
2788 case MATROSKA_ID_CLUSTER:
2789 if ((res = ebml_read_master(matroska, &id)) < 0)
2791 if ((res = matroska_parse_cluster(matroska)) == 0)
2792 res = 1; /* Parsed one cluster, let's get out. */
2797 res = ebml_read_skip(matroska);
2801 if (matroska->level_up) {
2802 matroska->level_up--;
2815 matroska_read_close (AVFormatContext *s)
2817 MatroskaDemuxContext *matroska = s->priv_data;
2820 av_free(matroska->writing_app);
2821 av_free(matroska->muxing_app);
2822 av_free(matroska->index);
2824 if (matroska->packets != NULL) {
2825 for (n = 0; n < matroska->num_packets; n++) {
2826 av_free_packet(matroska->packets[n]);
2827 av_free(matroska->packets[n]);
2829 av_free(matroska->packets);
2831 if (matroska->packets_reorder) {
2832 for (n = 0; n < matroska->num_packets_reorder; n++) {
2833 av_free_packet(matroska->packets_reorder[n]);
2834 av_free(matroska->packets_reorder[n]);
2836 av_free(matroska->packets_reorder);
2839 for (n = 0; n < matroska->num_tracks; n++) {
2840 MatroskaTrack *track = matroska->tracks[n];
2841 av_free(track->codec_id);
2842 av_free(track->codec_name);
2843 av_free(track->codec_priv);
2844 av_free(track->name);
2845 av_free(track->language);
2853 AVInputFormat matroska_demuxer = {
2855 "Matroska file format",
2856 sizeof(MatroskaDemuxContext),
2858 matroska_read_header,
2859 matroska_read_packet,
2860 matroska_read_close,