2 * Matroska file demuxer (no muxer yet)
3 * Copyright (c) 2003-2004 The ffmpeg Project
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 * Matroska file demuxer
23 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
24 * with a little help from Moritz Bunkus <moritz@bunkus.org>
25 * Specs available on the matroska project page:
26 * http://www.matroska.org/.
30 /* For codec_get_bmp_id and codec_get_wav_id. */
32 #include "intfloat_readwrite.h"
34 /* EBML version supported */
35 #define EBML_VERSION 1
37 /* top-level master-IDs */
38 #define EBML_ID_HEADER 0x1A45DFA3
40 /* IDs in the HEADER master */
41 #define EBML_ID_EBMLVERSION 0x4286
42 #define EBML_ID_EBMLREADVERSION 0x42F7
43 #define EBML_ID_EBMLMAXIDLENGTH 0x42F2
44 #define EBML_ID_EBMLMAXSIZELENGTH 0x42F3
45 #define EBML_ID_DOCTYPE 0x4282
46 #define EBML_ID_DOCTYPEVERSION 0x4287
47 #define EBML_ID_DOCTYPEREADVERSION 0x4285
49 /* general EBML types */
50 #define EBML_ID_VOID 0xEC
53 * Matroska element IDs. max. 32-bit.
56 /* toplevel segment */
57 #define MATROSKA_ID_SEGMENT 0x18538067
59 /* matroska top-level master IDs */
60 #define MATROSKA_ID_INFO 0x1549A966
61 #define MATROSKA_ID_TRACKS 0x1654AE6B
62 #define MATROSKA_ID_CUES 0x1C53BB6B
63 #define MATROSKA_ID_TAGS 0x1254C367
64 #define MATROSKA_ID_SEEKHEAD 0x114D9B74
65 #define MATROSKA_ID_CLUSTER 0x1F43B675
67 /* IDs in the info master */
68 #define MATROSKA_ID_TIMECODESCALE 0x2AD7B1
69 #define MATROSKA_ID_DURATION 0x4489
70 #define MATROSKA_ID_WRITINGAPP 0x5741
71 #define MATROSKA_ID_MUXINGAPP 0x4D80
72 #define MATROSKA_ID_DATEUTC 0x4461
74 /* ID in the tracks master */
75 #define MATROSKA_ID_TRACKENTRY 0xAE
77 /* IDs in the trackentry master */
78 #define MATROSKA_ID_TRACKNUMBER 0xD7
79 #define MATROSKA_ID_TRACKUID 0x73C5
80 #define MATROSKA_ID_TRACKTYPE 0x83
81 #define MATROSKA_ID_TRACKAUDIO 0xE1
82 #define MATROSKA_ID_TRACKVIDEO 0xE0
83 #define MATROSKA_ID_CODECID 0x86
84 #define MATROSKA_ID_CODECPRIVATE 0x63A2
85 #define MATROSKA_ID_CODECNAME 0x258688
86 #define MATROSKA_ID_CODECINFOURL 0x3B4040
87 #define MATROSKA_ID_CODECDOWNLOADURL 0x26B240
88 #define MATROSKA_ID_TRACKNAME 0x536E
89 #define MATROSKA_ID_TRACKLANGUAGE 0x22B59C
90 #define MATROSKA_ID_TRACKFLAGENABLED 0xB9
91 #define MATROSKA_ID_TRACKFLAGDEFAULT 0x88
92 #define MATROSKA_ID_TRACKFLAGLACING 0x9C
93 #define MATROSKA_ID_TRACKMINCACHE 0x6DE7
94 #define MATROSKA_ID_TRACKMAXCACHE 0x6DF8
95 #define MATROSKA_ID_TRACKDEFAULTDURATION 0x23E383
97 /* IDs in the trackvideo master */
98 #define MATROSKA_ID_VIDEOFRAMERATE 0x2383E3
99 #define MATROSKA_ID_VIDEODISPLAYWIDTH 0x54B0
100 #define MATROSKA_ID_VIDEODISPLAYHEIGHT 0x54BA
101 #define MATROSKA_ID_VIDEOPIXELWIDTH 0xB0
102 #define MATROSKA_ID_VIDEOPIXELHEIGHT 0xBA
103 #define MATROSKA_ID_VIDEOFLAGINTERLACED 0x9A
104 #define MATROSKA_ID_VIDEOSTEREOMODE 0x53B9
105 #define MATROSKA_ID_VIDEOASPECTRATIO 0x54B3
106 #define MATROSKA_ID_VIDEOCOLOURSPACE 0x2EB524
108 /* IDs in the trackaudio master */
109 #define MATROSKA_ID_AUDIOSAMPLINGFREQ 0xB5
110 #define MATROSKA_ID_AUDIOBITDEPTH 0x6264
111 #define MATROSKA_ID_AUDIOCHANNELS 0x9F
113 /* ID in the cues master */
114 #define MATROSKA_ID_POINTENTRY 0xBB
116 /* IDs in the pointentry master */
117 #define MATROSKA_ID_CUETIME 0xB3
118 #define MATROSKA_ID_CUETRACKPOSITION 0xB7
120 /* IDs in the cuetrackposition master */
121 #define MATROSKA_ID_CUETRACK 0xF7
122 #define MATROSKA_ID_CUECLUSTERPOSITION 0xF1
124 /* IDs in the tags master */
127 /* IDs in the seekhead master */
128 #define MATROSKA_ID_SEEKENTRY 0x4DBB
130 /* IDs in the seekpoint master */
131 #define MATROSKA_ID_SEEKID 0x53AB
132 #define MATROSKA_ID_SEEKPOSITION 0x53AC
134 /* IDs in the cluster master */
135 #define MATROSKA_ID_CLUSTERTIMECODE 0xE7
136 #define MATROSKA_ID_BLOCKGROUP 0xA0
138 /* IDs in the blockgroup master */
139 #define MATROSKA_ID_BLOCK 0xA1
140 #define MATROSKA_ID_BLOCKDURATION 0x9B
141 #define MATROSKA_ID_BLOCKREFERENCE 0xFB
144 MATROSKA_TRACK_TYPE_VIDEO = 0x1,
145 MATROSKA_TRACK_TYPE_AUDIO = 0x2,
146 MATROSKA_TRACK_TYPE_COMPLEX = 0x3,
147 MATROSKA_TRACK_TYPE_LOGO = 0x10,
148 MATROSKA_TRACK_TYPE_SUBTITLE = 0x11,
149 MATROSKA_TRACK_TYPE_CONTROL = 0x20,
153 MATROSKA_EYE_MODE_MONO = 0x0,
154 MATROSKA_EYE_MODE_RIGHT = 0x1,
155 MATROSKA_EYE_MODE_LEFT = 0x2,
156 MATROSKA_EYE_MODE_BOTH = 0x3,
160 MATROSKA_ASPECT_RATIO_MODE_FREE = 0x0,
161 MATROSKA_ASPECT_RATIO_MODE_KEEP = 0x1,
162 MATROSKA_ASPECT_RATIO_MODE_FIXED = 0x2,
163 } MatroskaAspectRatioMode;
166 * These aren't in any way "matroska-form" things,
167 * it's just something I use in the muxer/demuxer.
171 MATROSKA_TRACK_ENABLED = (1<<0),
172 MATROSKA_TRACK_DEFAULT = (1<<1),
173 MATROSKA_TRACK_LACING = (1<<2),
174 MATROSKA_TRACK_SHIFT = (1<<16)
175 } MatroskaTrackFlags;
178 MATROSKA_VIDEOTRACK_INTERLACED = (MATROSKA_TRACK_SHIFT<<0)
179 } MatroskaVideoTrackFlags;
182 * Matroska Codec IDs. Strings.
185 typedef struct CodecTags{
190 #define MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC "V_MS/VFW/FOURCC"
191 #define MATROSKA_CODEC_ID_AUDIO_ACM "A_MS/ACM"
193 CodecTags codec_tags[]={
194 // {"V_MS/VFW/FOURCC" , CODEC_ID_NONE},
195 {"V_UNCOMPRESSED" , CODEC_ID_RAWVIDEO},
196 {"V_MPEG4/ISO/SP" , CODEC_ID_MPEG4},
197 {"V_MPEG4/ISO/ASP" , CODEC_ID_MPEG4},
198 {"V_MPEG4/ISO/AP" , CODEC_ID_MPEG4},
199 {"V_MPEG4/ISO/AVC" , CODEC_ID_H264},
200 {"V_MPEG4/MS/V3" , CODEC_ID_MSMPEG4V3},
201 {"V_MPEG1" , CODEC_ID_MPEG1VIDEO},
202 {"V_MPEG2" , CODEC_ID_MPEG2VIDEO},
203 {"V_MJPEG" , CODEC_ID_MJPEG},
204 {"V_REAL/RV10" , CODEC_ID_RV10},
205 {"V_REAL/RV20" , CODEC_ID_RV20},
206 {"V_REAL/RV30" , CODEC_ID_RV30},
207 {"V_REAL/RV40" , CODEC_ID_RV40},
208 /* TODO: Real/Quicktime */
210 // {"A_MS/ACM" , CODEC_ID_NONE},
211 {"A_MPEG/L1" , CODEC_ID_MP3},
212 {"A_MPEG/L2" , CODEC_ID_MP3},
213 {"A_MPEG/L3" , CODEC_ID_MP3},
214 {"A_PCM/INT/BIG" , CODEC_ID_PCM_U16BE},
215 {"A_PCM/INT/LIT" , CODEC_ID_PCM_U16LE},
216 // {"A_PCM/FLOAT/IEEE" , CODEC_ID_NONE},
217 {"A_AC3" , CODEC_ID_AC3},
218 {"A_DTS" , CODEC_ID_DTS},
219 {"A_VORBIS" , CODEC_ID_VORBIS},
220 {"A_AAC/MPEG2/" , CODEC_ID_AAC},
221 {"A_AAC/MPEG4/" , CODEC_ID_AAC},
222 {NULL , CODEC_ID_NONE}
223 /* TODO: AC3-9/10 (?), Real, Musepack, Quicktime */
226 /* max. depth in the EBML tree structure */
227 #define EBML_MAX_DEPTH 16
229 typedef struct Track {
230 MatroskaTrackType type;
232 /* Unique track number and track ID. stream_index is the index that
233 * the calling app uses for this track. */
244 unsigned char *codec_priv;
247 int64_t default_duration;
248 MatroskaTrackFlags flags;
251 typedef struct MatroskaVideoTrack {
261 MatroskaAspectRatioMode ar_mode;
262 MatroskaEyeMode eye_mode;
265 } MatroskaVideoTrack;
267 typedef struct MatroskaAudioTrack {
274 } MatroskaAudioTrack;
276 typedef struct MatroskaSubtitleTrack {
280 } MatroskaSubtitleTrack;
282 typedef struct MatroskaLevel {
283 uint64_t start, length;
286 typedef struct MatroskaDemuxIndex {
287 uint64_t pos; /* of the corresponding *cluster*! */
288 uint16_t track; /* reference to 'num' */
289 uint64_t time; /* in nanoseconds */
290 } MatroskaDemuxIndex;
292 typedef struct MatroskaDemuxContext {
293 AVFormatContext *ctx;
297 MatroskaLevel levels[EBML_MAX_DEPTH];
305 /* timescale in the file */
308 /* length, position (time, ns) */
312 /* num_streams is the number of streams that av_new_stream() was called
313 * for ( = that are available to the calling program). */
314 int num_tracks, num_streams;
315 MatroskaTrack *tracks[MAX_STREAMS];
317 /* cache for ID peeking */
320 /* byte position of the segment inside the stream */
321 offset_t segment_start;
323 /* The packet queue. */
327 /* have we already parse metadata/cues/clusters? */
332 /* The index for seeking. */
334 MatroskaDemuxIndex *index;
335 } MatroskaDemuxContext;
338 * The first few functions handle EBML file parsing. The rest
339 * is the document interpretation. Matroska really just is a
344 * Return: the amount of levels in the hierarchy that the
345 * current element lies higher than the previous one.
346 * The opposite isn't done - that's auto-done using master
351 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
353 ByteIOContext *pb = &matroska->ctx->pb;
354 offset_t pos = url_ftell(pb);
357 while (matroska->num_levels > 0) {
358 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
360 if (pos >= level->start + level->length) {
361 matroska->num_levels--;
372 * Read: an "EBML number", which is defined as a variable-length
373 * array of bytes. The first byte indicates the length by giving a
374 * number of 0-bits followed by a one. The position of the first
375 * "one" bit inside the first byte indicates the length of this
377 * Returns: num. of bytes read. < 0 on error.
381 ebml_read_num (MatroskaDemuxContext *matroska,
385 ByteIOContext *pb = &matroska->ctx->pb;
386 int len_mask = 0x80, read = 1, n = 1;
389 /* the first byte tells us the length in bytes - get_byte() can normally
390 * return 0, but since that's not a valid first ebmlID byte, we can
391 * use it safely here to catch EOS. */
392 if (!(total = get_byte(pb))) {
393 /* we might encounter EOS here */
395 offset_t pos = url_ftell(pb);
396 av_log(matroska->ctx, AV_LOG_ERROR,
397 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
400 return AVERROR_IO; /* EOS or actual I/O error */
403 /* get the length of the EBML number */
404 while (read <= max_size && !(total & len_mask)) {
408 if (read > max_size) {
409 offset_t pos = url_ftell(pb) - 1;
410 av_log(matroska->ctx, AV_LOG_ERROR,
411 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
412 (uint8_t) total, pos, pos);
413 return AVERROR_INVALIDDATA;
416 /* read out length */
419 total = (total << 8) | get_byte(pb);
427 * Read: the element content data ID.
428 * Return: the number of bytes read or < 0 on error.
432 ebml_read_element_id (MatroskaDemuxContext *matroska,
439 /* if we re-call this, use our cached ID */
440 if (matroska->peek_id != 0) {
443 *id = matroska->peek_id;
447 /* read out the "EBML number", include tag in ID */
448 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
450 *id = matroska->peek_id = total | (1 << (read * 7));
454 *level_up = ebml_read_element_level_up(matroska);
460 * Read: element content length.
461 * Return: the number of bytes read or < 0 on error.
465 ebml_read_element_length (MatroskaDemuxContext *matroska,
468 /* clear cache since we're now beyond that data point */
469 matroska->peek_id = 0;
471 /* read out the "EBML number", include tag in ID */
472 return ebml_read_num(matroska, 8, length);
476 * Return: the ID of the next element, or 0 on error.
477 * Level_up contains the amount of levels that this
478 * next element lies higher than the previous one.
482 ebml_peek_id (MatroskaDemuxContext *matroska,
487 assert(level_up != NULL);
489 if (ebml_read_element_id(matroska, &id, level_up) < 0)
496 * Seek to a given offset.
497 * 0 is success, -1 is failure.
501 ebml_read_seek (MatroskaDemuxContext *matroska,
504 ByteIOContext *pb = &matroska->ctx->pb;
506 /* clear ID cache, if any */
507 matroska->peek_id = 0;
509 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
513 * Skip the next element.
514 * 0 is success, -1 is failure.
518 ebml_read_skip (MatroskaDemuxContext *matroska)
520 ByteIOContext *pb = &matroska->ctx->pb;
525 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
526 (res = ebml_read_element_length(matroska, &length)) < 0)
529 url_fskip(pb, length);
535 * Read the next element as an unsigned int.
536 * 0 is success, < 0 is failure.
540 ebml_read_uint (MatroskaDemuxContext *matroska,
544 ByteIOContext *pb = &matroska->ctx->pb;
545 int n = 0, size, res;
548 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
549 (res = ebml_read_element_length(matroska, &rlength)) < 0)
552 if (size < 1 || size > 8) {
553 offset_t pos = url_ftell(pb);
554 av_log(matroska->ctx, AV_LOG_ERROR,
555 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
557 return AVERROR_INVALIDDATA;
560 /* big-endian ordening; build up number */
563 *num = (*num << 8) | get_byte(pb);
569 * Read the next element as a signed int.
570 * 0 is success, < 0 is failure.
574 ebml_read_sint (MatroskaDemuxContext *matroska,
578 ByteIOContext *pb = &matroska->ctx->pb;
579 int size, n = 1, negative = 0, res;
582 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
583 (res = ebml_read_element_length(matroska, &rlength)) < 0)
586 if (size < 1 || size > 8) {
587 offset_t pos = url_ftell(pb);
588 av_log(matroska->ctx, AV_LOG_ERROR,
589 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
591 return AVERROR_INVALIDDATA;
593 if ((*num = get_byte(pb)) & 0x80) {
599 *num = (*num << 8) | get_byte(pb);
603 *num = *num - (1LL << ((8 * size) - 1));
609 * Read the next element as a float.
610 * 0 is success, < 0 is failure.
614 ebml_read_float (MatroskaDemuxContext *matroska,
618 ByteIOContext *pb = &matroska->ctx->pb;
622 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
623 (res = ebml_read_element_length(matroska, &rlength)) < 0)
628 *num= av_int2flt(get_be32(pb));
630 *num= av_int2dbl(get_be64(pb));
632 av_log(matroska->ctx, AV_LOG_ERROR,
633 "FIXME! 10-byte floats unimplemented\n");
634 return AVERROR_UNKNOWN;
636 offset_t pos = url_ftell(pb);
637 av_log(matroska->ctx, AV_LOG_ERROR,
638 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
640 return AVERROR_INVALIDDATA;
647 * Read the next element as an ASCII string.
648 * 0 is success, < 0 is failure.
652 ebml_read_ascii (MatroskaDemuxContext *matroska,
656 ByteIOContext *pb = &matroska->ctx->pb;
660 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
661 (res = ebml_read_element_length(matroska, &rlength)) < 0)
665 /* ebml strings are usually not 0-terminated, so we allocate one
666 * byte more, read the string and NULL-terminate it ourselves. */
667 if (size < 0 || !(*str = av_malloc(size + 1))) {
668 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
669 return AVERROR_NOMEM;
671 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
672 offset_t pos = url_ftell(pb);
673 av_log(matroska->ctx, AV_LOG_ERROR,
674 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
683 * Read the next element as a UTF-8 string.
684 * 0 is success, < 0 is failure.
688 ebml_read_utf8 (MatroskaDemuxContext *matroska,
692 return ebml_read_ascii(matroska, id, str);
696 * Read the next element as a date (nanoseconds since 1/1/2000).
697 * 0 is success, < 0 is failure.
701 ebml_read_date (MatroskaDemuxContext *matroska,
705 return ebml_read_sint(matroska, id, date);
709 * Read the next element, but only the header. The contents
710 * are supposed to be sub-elements which can be read separately.
711 * 0 is success, < 0 is failure.
715 ebml_read_master (MatroskaDemuxContext *matroska,
718 ByteIOContext *pb = &matroska->ctx->pb;
720 MatroskaLevel *level;
723 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
724 (res = ebml_read_element_length(matroska, &length)) < 0)
727 /* protect... (Heaven forbids that the '>' is true) */
728 if (matroska->num_levels >= EBML_MAX_DEPTH) {
729 av_log(matroska->ctx, AV_LOG_ERROR,
730 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
731 return AVERROR_NOTSUPP;
735 level = &matroska->levels[matroska->num_levels++];
736 level->start = url_ftell(pb);
737 level->length = length;
743 * Read the next element as binary data.
744 * 0 is success, < 0 is failure.
748 ebml_read_binary (MatroskaDemuxContext *matroska,
753 ByteIOContext *pb = &matroska->ctx->pb;
757 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
758 (res = ebml_read_element_length(matroska, &rlength)) < 0)
762 if (!(*binary = av_malloc(*size))) {
763 av_log(matroska->ctx, AV_LOG_ERROR,
764 "Memory allocation error\n");
765 return AVERROR_NOMEM;
768 if (get_buffer(pb, *binary, *size) != *size) {
769 offset_t pos = url_ftell(pb);
770 av_log(matroska->ctx, AV_LOG_ERROR,
771 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
779 * Read signed/unsigned "EBML" numbers.
780 * Return: number of bytes processed, < 0 on error.
781 * XXX: use ebml_read_num().
785 matroska_ebmlnum_uint (uint8_t *data,
789 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
793 return AVERROR_INVALIDDATA;
796 while (read <= 8 && !(total & len_mask)) {
801 return AVERROR_INVALIDDATA;
803 if ((total &= (len_mask - 1)) == len_mask - 1)
806 return AVERROR_INVALIDDATA;
810 total = (total << 8) | data[n];
823 * Same as above, but signed.
827 matroska_ebmlnum_sint (uint8_t *data,
834 /* read as unsigned number first */
835 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
838 /* make signed (weird way) */
839 if (unum == (uint64_t)-1)
842 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
848 * Read an EBML header.
849 * 0 is success, < 0 is failure.
853 ebml_read_header (MatroskaDemuxContext *matroska,
858 int level_up, res = 0;
866 if (!(id = ebml_peek_id(matroska, &level_up)) ||
867 level_up != 0 || id != EBML_ID_HEADER) {
868 av_log(matroska->ctx, AV_LOG_ERROR,
869 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
870 return AVERROR_INVALIDDATA;
872 if ((res = ebml_read_master(matroska, &id)) < 0)
876 if (!(id = ebml_peek_id(matroska, &level_up)))
884 /* is our read version uptodate? */
885 case EBML_ID_EBMLREADVERSION: {
888 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
890 if (num > EBML_VERSION) {
891 av_log(matroska->ctx, AV_LOG_ERROR,
892 "EBML version %"PRIu64" (> %d) is not supported\n",
894 return AVERROR_INVALIDDATA;
899 /* we only handle 8 byte lengths at max */
900 case EBML_ID_EBMLMAXSIZELENGTH: {
903 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
905 if (num > sizeof(uint64_t)) {
906 av_log(matroska->ctx, AV_LOG_ERROR,
907 "Integers of size %"PRIu64" (> %zd) not supported\n",
908 num, sizeof(uint64_t));
909 return AVERROR_INVALIDDATA;
914 /* we handle 4 byte IDs at max */
915 case EBML_ID_EBMLMAXIDLENGTH: {
918 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
920 if (num > sizeof(uint32_t)) {
921 av_log(matroska->ctx, AV_LOG_ERROR,
922 "IDs of size %"PRIu64" (> %zu) not supported\n",
923 num, sizeof(uint32_t));
924 return AVERROR_INVALIDDATA;
929 case EBML_ID_DOCTYPE: {
932 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
943 case EBML_ID_DOCTYPEREADVERSION: {
946 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
954 av_log(matroska->ctx, AV_LOG_INFO,
955 "Unknown data type 0x%x in EBML header", id);
959 /* we ignore these two, as they don't tell us anything we
961 case EBML_ID_EBMLVERSION:
962 case EBML_ID_DOCTYPEVERSION:
963 res = ebml_read_skip (matroska);
972 * Put one packet in an application-supplied AVPacket struct.
973 * Returns 0 on success or -1 on failure.
977 matroska_deliver_packet (MatroskaDemuxContext *matroska,
980 if (matroska->num_packets > 0) {
981 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
982 av_free(matroska->packets[0]);
983 if (matroska->num_packets > 1) {
984 memmove(&matroska->packets[0], &matroska->packets[1],
985 (matroska->num_packets - 1) * sizeof(AVPacket *));
987 av_realloc(matroska->packets, (matroska->num_packets - 1) *
990 av_free(matroska->packets);
991 matroska->packets = NULL;
993 matroska->num_packets--;
1001 * Put a packet into our internal queue. Will be delivered to the
1002 * user/application during the next get_packet() call.
1006 matroska_queue_packet (MatroskaDemuxContext *matroska,
1010 av_realloc(matroska->packets, (matroska->num_packets + 1) *
1011 sizeof(AVPacket *));
1012 matroska->packets[matroska->num_packets] = pkt;
1013 matroska->num_packets++;
1021 matroska_probe (AVProbeData *p)
1024 int len_mask = 0x80, size = 1, n = 1;
1025 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1027 if (p->buf_size < 5)
1031 if ((p->buf[0] << 24 | p->buf[1] << 16 |
1032 p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
1035 /* length of header */
1037 while (size <= 8 && !(total & len_mask)) {
1043 total &= (len_mask - 1);
1045 total = (total << 8) | p->buf[4 + n++];
1047 /* does the probe data contain the whole header? */
1048 if (p->buf_size < 4 + size + total)
1051 /* the header must contain the document type 'matroska'. For now,
1052 * we don't parse the whole header but simply check for the
1053 * availability of that array of characters inside the header.
1054 * Not fully fool-proof, but good enough. */
1055 for (n = 4 + size; n < 4 + size + total - sizeof(probe_data); n++)
1056 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1057 return AVPROBE_SCORE_MAX;
1063 * From here on, it's all XML-style DTD stuff... Needs no comments.
1067 matroska_parse_info (MatroskaDemuxContext *matroska)
1072 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
1075 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1078 } else if (matroska->level_up) {
1079 matroska->level_up--;
1084 /* cluster timecode */
1085 case MATROSKA_ID_TIMECODESCALE: {
1087 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1089 matroska->time_scale = num;
1093 case MATROSKA_ID_DURATION: {
1095 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1097 matroska->duration = num * matroska->time_scale;
1101 case MATROSKA_ID_WRITINGAPP: {
1103 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1105 matroska->writing_app = text;
1109 case MATROSKA_ID_MUXINGAPP: {
1111 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1113 matroska->muxing_app = text;
1117 case MATROSKA_ID_DATEUTC: {
1119 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
1121 matroska->created = time;
1126 av_log(matroska->ctx, AV_LOG_INFO,
1127 "Unknown entry 0x%x in info header\n", id);
1131 res = ebml_read_skip(matroska);
1135 if (matroska->level_up) {
1136 matroska->level_up--;
1145 matroska_add_stream (MatroskaDemuxContext *matroska)
1149 MatroskaTrack *track;
1151 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1153 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1154 track = av_mallocz(sizeof(MatroskaTrack));
1155 matroska->num_tracks++;
1157 /* start with the master */
1158 if ((res = ebml_read_master(matroska, &id)) < 0)
1161 /* try reading the trackentry headers */
1163 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1166 } else if (matroska->level_up > 0) {
1167 matroska->level_up--;
1172 /* track number (unique stream ID) */
1173 case MATROSKA_ID_TRACKNUMBER: {
1175 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1181 /* track UID (unique identifier) */
1182 case MATROSKA_ID_TRACKUID: {
1184 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1190 /* track type (video, audio, combined, subtitle, etc.) */
1191 case MATROSKA_ID_TRACKTYPE: {
1193 if (track->type != 0) {
1194 av_log(matroska->ctx, AV_LOG_INFO,
1195 "More than one tracktype in an entry - skip\n");
1198 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1202 /* ok, so we're actually going to reallocate this thing */
1203 switch (track->type) {
1204 case MATROSKA_TRACK_TYPE_VIDEO:
1205 track = (MatroskaTrack *)
1206 av_realloc(track, sizeof(MatroskaVideoTrack));
1208 case MATROSKA_TRACK_TYPE_AUDIO:
1209 track = (MatroskaTrack *)
1210 av_realloc(track, sizeof(MatroskaAudioTrack));
1211 ((MatroskaAudioTrack *)track)->channels = 1;
1212 ((MatroskaAudioTrack *)track)->samplerate = 8000;
1214 case MATROSKA_TRACK_TYPE_SUBTITLE:
1215 track = (MatroskaTrack *)
1216 av_realloc(track, sizeof(MatroskaSubtitleTrack));
1218 case MATROSKA_TRACK_TYPE_COMPLEX:
1219 case MATROSKA_TRACK_TYPE_LOGO:
1220 case MATROSKA_TRACK_TYPE_CONTROL:
1222 av_log(matroska->ctx, AV_LOG_INFO,
1223 "Unknown or unsupported track type 0x%x\n",
1228 matroska->tracks[matroska->num_tracks - 1] = track;
1232 /* tracktype specific stuff for video */
1233 case MATROSKA_ID_TRACKVIDEO: {
1234 MatroskaVideoTrack *videotrack;
1235 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1236 av_log(matroska->ctx, AV_LOG_INFO,
1237 "video data in non-video track - ignoring\n");
1238 res = AVERROR_INVALIDDATA;
1240 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1242 videotrack = (MatroskaVideoTrack *)track;
1245 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1248 } else if (matroska->level_up > 0) {
1249 matroska->level_up--;
1254 /* fixme, this should be one-up, but I get it here */
1255 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1257 if ((res = ebml_read_uint (matroska, &id,
1260 track->default_duration = num;
1264 /* video framerate */
1265 case MATROSKA_ID_VIDEOFRAMERATE: {
1267 if ((res = ebml_read_float(matroska, &id,
1270 track->default_duration = 1000000000 * (1. / num);
1274 /* width of the size to display the video at */
1275 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1277 if ((res = ebml_read_uint(matroska, &id,
1280 videotrack->display_width = num;
1284 /* height of the size to display the video at */
1285 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1287 if ((res = ebml_read_uint(matroska, &id,
1290 videotrack->display_height = num;
1294 /* width of the video in the file */
1295 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1297 if ((res = ebml_read_uint(matroska, &id,
1300 videotrack->pixel_width = num;
1304 /* height of the video in the file */
1305 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1307 if ((res = ebml_read_uint(matroska, &id,
1310 videotrack->pixel_height = num;
1314 /* whether the video is interlaced */
1315 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1317 if ((res = ebml_read_uint(matroska, &id,
1322 MATROSKA_VIDEOTRACK_INTERLACED;
1325 ~MATROSKA_VIDEOTRACK_INTERLACED;
1329 /* stereo mode (whether the video has two streams,
1330 * where one is for the left eye and the other for
1331 * the right eye, which creates a 3D-like
1333 case MATROSKA_ID_VIDEOSTEREOMODE: {
1335 if ((res = ebml_read_uint(matroska, &id,
1338 if (num != MATROSKA_EYE_MODE_MONO &&
1339 num != MATROSKA_EYE_MODE_LEFT &&
1340 num != MATROSKA_EYE_MODE_RIGHT &&
1341 num != MATROSKA_EYE_MODE_BOTH) {
1342 av_log(matroska->ctx, AV_LOG_INFO,
1343 "Ignoring unknown eye mode 0x%x\n",
1347 videotrack->eye_mode = num;
1351 /* aspect ratio behaviour */
1352 case MATROSKA_ID_VIDEOASPECTRATIO: {
1354 if ((res = ebml_read_uint(matroska, &id,
1357 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1358 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1359 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1360 av_log(matroska->ctx, AV_LOG_INFO,
1361 "Ignoring unknown aspect ratio 0x%x\n",
1365 videotrack->ar_mode = num;
1369 /* colourspace (only matters for raw video)
1371 case MATROSKA_ID_VIDEOCOLOURSPACE: {
1373 if ((res = ebml_read_uint(matroska, &id,
1376 videotrack->fourcc = num;
1381 av_log(matroska->ctx, AV_LOG_INFO,
1382 "Unknown video track header entry "
1383 "0x%x - ignoring\n", id);
1387 res = ebml_read_skip(matroska);
1391 if (matroska->level_up) {
1392 matroska->level_up--;
1399 /* tracktype specific stuff for audio */
1400 case MATROSKA_ID_TRACKAUDIO: {
1401 MatroskaAudioTrack *audiotrack;
1402 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1403 av_log(matroska->ctx, AV_LOG_INFO,
1404 "audio data in non-audio track - ignoring\n");
1405 res = AVERROR_INVALIDDATA;
1407 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1409 audiotrack = (MatroskaAudioTrack *)track;
1412 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1415 } else if (matroska->level_up > 0) {
1416 matroska->level_up--;
1422 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1424 if ((res = ebml_read_float(matroska, &id,
1427 audiotrack->samplerate = num;
1432 case MATROSKA_ID_AUDIOBITDEPTH: {
1434 if ((res = ebml_read_uint(matroska, &id,
1437 audiotrack->bitdepth = num;
1442 case MATROSKA_ID_AUDIOCHANNELS: {
1444 if ((res = ebml_read_uint(matroska, &id,
1447 audiotrack->channels = num;
1452 av_log(matroska->ctx, AV_LOG_INFO,
1453 "Unknown audio track header entry "
1454 "0x%x - ignoring\n", id);
1458 res = ebml_read_skip(matroska);
1462 if (matroska->level_up) {
1463 matroska->level_up--;
1470 /* codec identifier */
1471 case MATROSKA_ID_CODECID: {
1473 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1475 track->codec_id = text;
1479 /* codec private data */
1480 case MATROSKA_ID_CODECPRIVATE: {
1483 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1485 track->codec_priv = data;
1486 track->codec_priv_size = size;
1490 /* name of the codec */
1491 case MATROSKA_ID_CODECNAME: {
1493 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1495 track->codec_name = text;
1499 /* name of this track */
1500 case MATROSKA_ID_TRACKNAME: {
1502 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1508 /* language (matters for audio/subtitles, mostly) */
1509 case MATROSKA_ID_TRACKLANGUAGE: {
1511 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1513 track->language = text;
1517 /* whether this is actually used */
1518 case MATROSKA_ID_TRACKFLAGENABLED: {
1520 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1523 track->flags |= MATROSKA_TRACK_ENABLED;
1525 track->flags &= ~MATROSKA_TRACK_ENABLED;
1529 /* whether it's the default for this track type */
1530 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1532 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1535 track->flags |= MATROSKA_TRACK_DEFAULT;
1537 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1541 /* lacing (like MPEG, where blocks don't end/start on frame
1543 case MATROSKA_ID_TRACKFLAGLACING: {
1545 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1548 track->flags |= MATROSKA_TRACK_LACING;
1550 track->flags &= ~MATROSKA_TRACK_LACING;
1554 /* default length (in time) of one data block in this track */
1555 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1557 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1559 track->default_duration = num;
1564 av_log(matroska->ctx, AV_LOG_INFO,
1565 "Unknown track header entry 0x%x - ignoring\n", id);
1569 /* we ignore these because they're nothing useful. */
1570 case MATROSKA_ID_CODECINFOURL:
1571 case MATROSKA_ID_CODECDOWNLOADURL:
1572 case MATROSKA_ID_TRACKMINCACHE:
1573 case MATROSKA_ID_TRACKMAXCACHE:
1574 res = ebml_read_skip(matroska);
1578 if (matroska->level_up) {
1579 matroska->level_up--;
1588 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1593 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1596 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1599 } else if (matroska->level_up) {
1600 matroska->level_up--;
1605 /* one track within the "all-tracks" header */
1606 case MATROSKA_ID_TRACKENTRY:
1607 res = matroska_add_stream(matroska);
1611 av_log(matroska->ctx, AV_LOG_INFO,
1612 "Unknown entry 0x%x in track header\n", id);
1616 res = ebml_read_skip(matroska);
1620 if (matroska->level_up) {
1621 matroska->level_up--;
1630 matroska_parse_index (MatroskaDemuxContext *matroska)
1634 MatroskaDemuxIndex idx;
1636 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1639 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1642 } else if (matroska->level_up) {
1643 matroska->level_up--;
1648 /* one single index entry ('point') */
1649 case MATROSKA_ID_POINTENTRY:
1650 if ((res = ebml_read_master(matroska, &id)) < 0)
1653 /* in the end, we hope to fill one entry with a
1654 * timestamp, a file position and a tracknum */
1655 idx.pos = (uint64_t) -1;
1656 idx.time = (uint64_t) -1;
1657 idx.track = (uint16_t) -1;
1660 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1663 } else if (matroska->level_up) {
1664 matroska->level_up--;
1669 /* one single index entry ('point') */
1670 case MATROSKA_ID_CUETIME: {
1672 if ((res = ebml_read_uint(matroska, &id,
1675 idx.time = time * matroska->time_scale;
1679 /* position in the file + track to which it
1681 case MATROSKA_ID_CUETRACKPOSITION:
1682 if ((res = ebml_read_master(matroska, &id)) < 0)
1686 if (!(id = ebml_peek_id (matroska,
1687 &matroska->level_up))) {
1690 } else if (matroska->level_up) {
1691 matroska->level_up--;
1697 case MATROSKA_ID_CUETRACK: {
1699 if ((res = ebml_read_uint(matroska,
1706 /* position in file */
1707 case MATROSKA_ID_CUECLUSTERPOSITION: {
1709 if ((res = ebml_read_uint(matroska,
1717 av_log(matroska->ctx, AV_LOG_INFO,
1718 "Unknown entry 0x%x in "
1719 "CuesTrackPositions\n", id);
1723 res = ebml_read_skip(matroska);
1727 if (matroska->level_up) {
1728 matroska->level_up--;
1736 av_log(matroska->ctx, AV_LOG_INFO,
1737 "Unknown entry 0x%x in cuespoint "
1742 res = ebml_read_skip(matroska);
1746 if (matroska->level_up) {
1747 matroska->level_up--;
1752 /* so let's see if we got what we wanted */
1753 if (idx.pos != (uint64_t) -1 &&
1754 idx.time != (uint64_t) -1 &&
1755 idx.track != (uint16_t) -1) {
1756 if (matroska->num_indexes % 32 == 0) {
1757 /* re-allocate bigger index */
1759 av_realloc(matroska->index,
1760 (matroska->num_indexes + 32) *
1761 sizeof(MatroskaDemuxIndex));
1763 matroska->index[matroska->num_indexes] = idx;
1764 matroska->num_indexes++;
1769 av_log(matroska->ctx, AV_LOG_INFO,
1770 "Unknown entry 0x%x in cues header\n", id);
1774 res = ebml_read_skip(matroska);
1778 if (matroska->level_up) {
1779 matroska->level_up--;
1788 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1794 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1797 } else if (matroska->level_up) {
1798 matroska->level_up--;
1803 /* Hm, this is unsupported... */
1805 av_log(matroska->ctx, AV_LOG_INFO,
1806 "Unknown entry 0x%x in metadata header\n", id);
1810 res = ebml_read_skip(matroska);
1814 if (matroska->level_up) {
1815 matroska->level_up--;
1824 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1829 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1832 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1835 } else if (matroska->level_up) {
1836 matroska->level_up--;
1841 case MATROSKA_ID_SEEKENTRY: {
1842 uint32_t seek_id = 0, peek_id_cache = 0;
1843 uint64_t seek_pos = (uint64_t) -1, t;
1845 if ((res = ebml_read_master(matroska, &id)) < 0)
1849 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1852 } else if (matroska->level_up) {
1853 matroska->level_up--;
1858 case MATROSKA_ID_SEEKID:
1859 res = ebml_read_uint(matroska, &id, &t);
1863 case MATROSKA_ID_SEEKPOSITION:
1864 res = ebml_read_uint(matroska, &id, &seek_pos);
1868 av_log(matroska->ctx, AV_LOG_INFO,
1869 "Unknown seekhead ID 0x%x\n", id);
1873 res = ebml_read_skip(matroska);
1877 if (matroska->level_up) {
1878 matroska->level_up--;
1883 if (!seek_id || seek_pos == (uint64_t) -1) {
1884 av_log(matroska->ctx, AV_LOG_INFO,
1885 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1891 case MATROSKA_ID_CUES:
1892 case MATROSKA_ID_TAGS: {
1893 uint32_t level_up = matroska->level_up;
1894 offset_t before_pos;
1896 MatroskaLevel level;
1898 /* remember the peeked ID and the current position */
1899 peek_id_cache = matroska->peek_id;
1900 before_pos = url_ftell(&matroska->ctx->pb);
1903 if ((res = ebml_read_seek(matroska, seek_pos +
1904 matroska->segment_start)) < 0)
1907 /* we don't want to lose our seekhead level, so we add
1908 * a dummy. This is a crude hack. */
1909 if (matroska->num_levels == EBML_MAX_DEPTH) {
1910 av_log(matroska->ctx, AV_LOG_INFO,
1911 "Max EBML element depth (%d) reached, "
1912 "cannot parse further.\n", EBML_MAX_DEPTH);
1913 return AVERROR_UNKNOWN;
1917 level.length = (uint64_t)-1;
1918 matroska->levels[matroska->num_levels] = level;
1919 matroska->num_levels++;
1922 if (!(id = ebml_peek_id (matroska,
1923 &matroska->level_up)))
1925 if (id != seek_id) {
1926 av_log(matroska->ctx, AV_LOG_INFO,
1927 "We looked for ID=0x%x but got "
1928 "ID=0x%x (pos=%"PRIu64")",
1929 seek_id, id, seek_pos +
1930 matroska->segment_start);
1934 /* read master + parse */
1935 if ((res = ebml_read_master(matroska, &id)) < 0)
1938 case MATROSKA_ID_CUES:
1939 if (!(res = matroska_parse_index(matroska)) ||
1940 url_feof(&matroska->ctx->pb)) {
1941 matroska->index_parsed = 1;
1945 case MATROSKA_ID_TAGS:
1946 if (!(res = matroska_parse_metadata(matroska)) ||
1947 url_feof(&matroska->ctx->pb)) {
1948 matroska->metadata_parsed = 1;
1957 /* remove dummy level */
1958 while (matroska->num_levels) {
1959 matroska->num_levels--;
1961 matroska->levels[matroska->num_levels].length;
1962 if (length == (uint64_t)-1)
1967 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1969 matroska->peek_id = peek_id_cache;
1970 matroska->level_up = level_up;
1975 av_log(matroska->ctx, AV_LOG_INFO,
1976 "Ignoring seekhead entry for ID=0x%x\n",
1985 av_log(matroska->ctx, AV_LOG_INFO,
1986 "Unknown seekhead ID 0x%x\n", id);
1990 res = ebml_read_skip(matroska);
1994 if (matroska->level_up) {
1995 matroska->level_up--;
2004 matroska_read_header (AVFormatContext *s,
2005 AVFormatParameters *ap)
2007 MatroskaDemuxContext *matroska = s->priv_data;
2009 int version, last_level, res = 0;
2014 /* First read the EBML header. */
2016 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2018 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2019 av_log(matroska->ctx, AV_LOG_ERROR,
2020 "Wrong EBML doctype ('%s' != 'matroska').\n",
2021 doctype ? doctype : "(none)");
2024 return AVERROR_NOFMT;
2028 av_log(matroska->ctx, AV_LOG_ERROR,
2029 "Matroska demuxer version 1 too old for file version %d\n",
2031 return AVERROR_NOFMT;
2034 /* The next thing is a segment. */
2036 if (!(id = ebml_peek_id(matroska, &last_level)))
2038 if (id == MATROSKA_ID_SEGMENT)
2042 av_log(matroska->ctx, AV_LOG_INFO,
2043 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2044 MATROSKA_ID_SEGMENT, id);
2045 if ((res = ebml_read_skip(matroska)) < 0)
2049 /* We now have a Matroska segment.
2050 * Seeks are from the beginning of the segment,
2051 * after the segment ID/length. */
2052 if ((res = ebml_read_master(matroska, &id)) < 0)
2054 matroska->segment_start = url_ftell(&s->pb);
2056 matroska->time_scale = 1000000;
2057 /* we've found our segment, start reading the different contents in here */
2059 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2062 } else if (matroska->level_up) {
2063 matroska->level_up--;
2069 case MATROSKA_ID_INFO: {
2070 if ((res = ebml_read_master(matroska, &id)) < 0)
2072 res = matroska_parse_info(matroska);
2076 /* track info headers */
2077 case MATROSKA_ID_TRACKS: {
2078 if ((res = ebml_read_master(matroska, &id)) < 0)
2080 res = matroska_parse_tracks(matroska);
2085 case MATROSKA_ID_CUES: {
2086 if (!matroska->index_parsed) {
2087 if ((res = ebml_read_master(matroska, &id)) < 0)
2089 res = matroska_parse_index(matroska);
2091 res = ebml_read_skip(matroska);
2096 case MATROSKA_ID_TAGS: {
2097 if (!matroska->metadata_parsed) {
2098 if ((res = ebml_read_master(matroska, &id)) < 0)
2100 res = matroska_parse_metadata(matroska);
2102 res = ebml_read_skip(matroska);
2106 /* file index (if seekable, seek to Cues/Tags to parse it) */
2107 case MATROSKA_ID_SEEKHEAD: {
2108 if ((res = ebml_read_master(matroska, &id)) < 0)
2110 res = matroska_parse_seekhead(matroska);
2114 case MATROSKA_ID_CLUSTER: {
2115 /* Do not read the master - this will be done in the next
2116 * call to matroska_read_packet. */
2122 av_log(matroska->ctx, AV_LOG_INFO,
2123 "Unknown matroska file header ID 0x%x\n", id);
2127 res = ebml_read_skip(matroska);
2131 if (matroska->level_up) {
2132 matroska->level_up--;
2140 /* Have we found a cluster? */
2143 enum CodecID codec_id= CODEC_ID_NONE;
2144 MatroskaTrack *track;
2147 for (i = 0; i < matroska->num_tracks; i++) {
2148 void *extradata = NULL;
2149 int extradata_size = 0;
2150 track = matroska->tracks[i];
2152 /* libavformat does not really support subtitles.
2153 * Also apply some sanity checks. */
2154 if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2155 (track->codec_id == NULL))
2158 for(j=0; codec_tags[j].str; j++){
2159 if(!strcmp(codec_tags[j].str, track->codec_id)){
2160 codec_id= codec_tags[j].id;
2165 /* Set the FourCC from the CodecID. */
2166 /* This is the MS compatibility mode which stores a
2167 * BITMAPINFOHEADER in the CodecPrivate. */
2168 if (!strcmp(track->codec_id,
2169 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2170 (track->codec_priv_size >= 40) &&
2171 (track->codec_priv != NULL)) {
2174 /* Offset of biCompression. Stored in LE. */
2175 p = (unsigned char *)track->codec_priv + 16;
2176 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2177 (p[2] << 16) | (p[1] << 8) | p[0];
2178 codec_id = codec_get_bmp_id(((MatroskaVideoTrack *)track)->fourcc);
2182 /* This is the MS compatibility mode which stores a
2183 * WAVEFORMATEX in the CodecPrivate. */
2184 else if (!strcmp(track->codec_id,
2185 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2186 (track->codec_priv_size >= 18) &&
2187 (track->codec_priv != NULL)) {
2191 /* Offset of wFormatTag. Stored in LE. */
2192 p = (unsigned char *)track->codec_priv;
2193 tag = (p[1] << 8) | p[0];
2194 codec_id = codec_get_wav_id(tag);
2198 if (codec_id == CODEC_ID_NONE) {
2199 av_log(matroska->ctx, AV_LOG_INFO,
2200 "Unknown/unsupported CodecID %s.\n",
2204 track->stream_index = matroska->num_streams;
2206 matroska->num_streams++;
2207 st = av_new_stream(s, track->stream_index);
2209 return AVERROR_NOMEM;
2210 av_set_pts_info(st, 24, 1, 1000); /* 24 bit pts in ms */
2212 st->codec->codec_id = codec_id;
2215 st->codec->extradata = extradata;
2216 st->codec->extradata_size = extradata_size;
2217 } else if(track->codec_priv && track->codec_priv_size > 0){
2218 st->codec->extradata = av_malloc(track->codec_priv_size);
2219 if(st->codec->extradata == NULL)
2220 return AVERROR_NOMEM;
2221 st->codec->extradata_size = track->codec_priv_size;
2222 memcpy(st->codec->extradata, track->codec_priv,
2223 track->codec_priv_size);
2226 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2227 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2229 st->codec->codec_type = CODEC_TYPE_VIDEO;
2230 st->codec->codec_tag = videotrack->fourcc;
2231 st->codec->width = videotrack->pixel_width;
2232 st->codec->height = videotrack->pixel_height;
2233 if (videotrack->display_width == 0)
2234 videotrack->display_width= videotrack->pixel_width;
2235 if (videotrack->display_height == 0)
2236 videotrack->display_height= videotrack->pixel_height;
2237 av_reduce(&st->codec->sample_aspect_ratio.num,
2238 &st->codec->sample_aspect_ratio.den,
2239 st->codec->height * videotrack->display_width,
2240 st->codec-> width * videotrack->display_height,
2242 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2243 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2245 st->codec->codec_type = CODEC_TYPE_AUDIO;
2246 st->codec->sample_rate = audiotrack->samplerate;
2247 st->codec->channels = audiotrack->channels;
2250 /* What do we do with private data? E.g. for Vorbis. */
2258 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
2263 for (i = 0; i < matroska->num_tracks; i++)
2264 if (matroska->tracks[i]->num == num)
2271 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2272 uint64_t cluster_time)
2277 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2279 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2282 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2285 } else if (matroska->level_up) {
2286 matroska->level_up--;
2291 /* one block inside the group. Note, block parsing is one
2292 * of the harder things, so this code is a bit complicated.
2293 * See http://www.matroska.org/ for documentation. */
2294 case MATROSKA_ID_BLOCK: {
2295 uint8_t *data, *origdata;
2298 uint32_t *lace_size = NULL;
2299 int n, track, flags, laces = 0;
2301 int64_t pos= url_ftell(&matroska->ctx->pb);
2303 if ((res = ebml_read_binary(matroska, &id, &data, &size)) < 0)
2307 /* first byte(s): blocknum */
2308 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2309 av_log(matroska->ctx, AV_LOG_ERROR,
2310 "EBML block data error\n");
2317 /* fetch track from num */
2318 track = matroska_find_track_by_num(matroska, num);
2319 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2320 av_log(matroska->ctx, AV_LOG_INFO,
2321 "Invalid stream %d or size %u\n", track, size);
2325 if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){
2330 /* time (relative to cluster time) */
2331 time = ((data[0] << 8) | data[1]) * matroska->time_scale;
2337 switch ((flags & 0x06) >> 1) {
2338 case 0x0: /* no lacing */
2340 lace_size = av_mallocz(sizeof(int));
2341 lace_size[0] = size;
2344 case 0x1: /* xiph lacing */
2345 case 0x2: /* fixed-size lacing */
2346 case 0x3: /* EBML lacing */
2351 laces = (*data) + 1;
2354 lace_size = av_mallocz(laces * sizeof(int));
2356 switch ((flags & 0x06) >> 1) {
2357 case 0x1: /* xiph lacing */ {
2360 for (n = 0; res == 0 && n < laces - 1; n++) {
2367 lace_size[n] += temp;
2373 total += lace_size[n];
2375 lace_size[n] = size - total;
2379 case 0x2: /* fixed-size lacing */
2380 for (n = 0; n < laces; n++)
2381 lace_size[n] = size / laces;
2384 case 0x3: /* EBML lacing */ {
2386 n = matroska_ebmlnum_uint(data, size, &num);
2388 av_log(matroska->ctx, AV_LOG_INFO,
2389 "EBML block data error\n");
2394 total = lace_size[0] = num;
2395 for (n = 1; res == 0 && n < laces - 1; n++) {
2398 r = matroska_ebmlnum_sint (data, size,
2401 av_log(matroska->ctx, AV_LOG_INFO,
2402 "EBML block data error\n");
2407 lace_size[n] = lace_size[n - 1] + snum;
2408 total += lace_size[n];
2410 lace_size[n] = size - total;
2418 for (n = 0; n < laces; n++) {
2419 uint64_t timecode = 0;
2421 pkt = av_mallocz(sizeof(AVPacket));
2422 /* XXX: prevent data copy... */
2423 if (av_new_packet(pkt,lace_size[n]) < 0) {
2424 res = AVERROR_NOMEM;
2427 if (cluster_time != (uint64_t)-1) {
2428 if (time < 0 && (-time) > cluster_time)
2429 timecode = cluster_time;
2431 timecode = cluster_time + time;
2433 /* FIXME: duration */
2435 memcpy(pkt->data, data, lace_size[n]);
2436 data += lace_size[n];
2438 pkt->flags = is_keyframe;
2440 matroska->tracks[track]->stream_index;
2442 pkt->pts = timecode / 1000000; /* ns to ms */
2445 matroska_queue_packet(matroska, pkt);
2454 case MATROSKA_ID_BLOCKDURATION: {
2456 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2458 av_log(matroska->ctx, AV_LOG_INFO,
2459 "FIXME: implement support for BlockDuration\n");
2463 case MATROSKA_ID_BLOCKREFERENCE:
2464 /* We've found a reference, so not even the first frame in
2465 * the lace is a key frame. */
2467 if (last_num_packets != matroska->num_packets)
2468 matroska->packets[last_num_packets]->flags = 0;
2469 res = ebml_read_skip(matroska);
2473 av_log(matroska->ctx, AV_LOG_INFO,
2474 "Unknown entry 0x%x in blockgroup data\n", id);
2478 res = ebml_read_skip(matroska);
2482 if (matroska->level_up) {
2483 matroska->level_up--;
2492 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2496 uint64_t cluster_time = 0;
2498 av_log(matroska->ctx, AV_LOG_DEBUG,
2499 "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2502 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2505 } else if (matroska->level_up) {
2506 matroska->level_up--;
2511 /* cluster timecode */
2512 case MATROSKA_ID_CLUSTERTIMECODE: {
2514 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2516 cluster_time = num * matroska->time_scale;
2520 /* a group of blocks inside a cluster */
2521 case MATROSKA_ID_BLOCKGROUP:
2522 if ((res = ebml_read_master(matroska, &id)) < 0)
2524 res = matroska_parse_blockgroup(matroska, cluster_time);
2528 av_log(matroska->ctx, AV_LOG_INFO,
2529 "Unknown entry 0x%x in cluster data\n", id);
2533 res = ebml_read_skip(matroska);
2537 if (matroska->level_up) {
2538 matroska->level_up--;
2547 matroska_read_packet (AVFormatContext *s,
2550 MatroskaDemuxContext *matroska = s->priv_data;
2554 /* Do we still have a packet queued? */
2555 if (matroska_deliver_packet(matroska, pkt) == 0)
2558 /* Have we already reached the end? */
2563 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2566 } else if (matroska->level_up) {
2567 matroska->level_up--;
2572 case MATROSKA_ID_CLUSTER:
2573 if ((res = ebml_read_master(matroska, &id)) < 0)
2575 if ((res = matroska_parse_cluster(matroska)) == 0)
2576 res = 1; /* Parsed one cluster, let's get out. */
2581 res = ebml_read_skip(matroska);
2585 if (matroska->level_up) {
2586 matroska->level_up--;
2594 return matroska_deliver_packet(matroska, pkt);
2598 matroska_read_close (AVFormatContext *s)
2600 MatroskaDemuxContext *matroska = s->priv_data;
2603 if (matroska->writing_app)
2604 av_free(matroska->writing_app);
2605 if (matroska->muxing_app)
2606 av_free(matroska->muxing_app);
2607 if (matroska->index)
2608 av_free(matroska->index);
2610 if (matroska->packets != NULL) {
2611 for (n = 0; n < matroska->num_packets; n++) {
2612 av_free_packet(matroska->packets[n]);
2613 av_free(matroska->packets[n]);
2615 av_free(matroska->packets);
2618 for (n = 0; n < matroska->num_tracks; n++) {
2619 MatroskaTrack *track = matroska->tracks[n];
2620 if (track->codec_id)
2621 av_free(track->codec_id);
2622 if (track->codec_name)
2623 av_free(track->codec_name);
2624 if (track->codec_priv)
2625 av_free(track->codec_priv);
2627 av_free(track->name);
2628 if (track->language)
2629 av_free(track->language);
2634 for (n = 0; n < s->nb_streams; n++) {
2635 av_free(s->streams[n]->codec->extradata);
2638 memset(matroska, 0, sizeof(MatroskaDemuxContext));
2643 static AVInputFormat matroska_iformat = {
2645 "Matroska file format",
2646 sizeof(MatroskaDemuxContext),
2648 matroska_read_header,
2649 matroska_read_packet,
2650 matroska_read_close,
2656 av_register_input_format(&matroska_iformat);