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(). */
36 #include "libavcodec/mpeg4audio.h"
37 #include "libavutil/intfloat_readwrite.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/lzo.h"
59 typedef const struct EbmlSyntax {
68 const struct EbmlSyntax *n;
88 uint64_t doctype_version;
94 } MatroskaTrackCompression;
99 MatroskaTrackCompression compression;
100 } MatroskaTrackEncoding;
104 uint64_t display_width;
105 uint64_t display_height;
106 uint64_t pixel_width;
107 uint64_t pixel_height;
109 } MatroskaTrackVideo;
113 double out_samplerate;
117 /* real audio header (extracted from extradata) */
125 } MatroskaTrackAudio;
134 uint64_t default_duration;
135 uint64_t flag_default;
136 MatroskaTrackVideo video;
137 MatroskaTrackAudio audio;
147 } MatroskaAttachement;
166 typedef struct MatroskaLevel {
171 typedef struct MatroskaDemuxContext {
172 AVFormatContext *ctx;
176 MatroskaLevel levels[EBML_MAX_DEPTH];
179 /* timescale in the file */
184 EbmlList attachments;
188 /* num_streams is the number of streams that av_new_stream() was called
189 * for ( = that are available to the calling program). */
192 /* cache for ID peeking */
195 /* byte position of the segment inside the stream */
196 offset_t segment_start;
198 /* The packet queue. */
202 /* have we already parse metadata/cues/clusters? */
207 /* What to skip before effectively reading a packet. */
208 int skip_to_keyframe;
209 AVStream *skip_to_stream;
210 } MatroskaDemuxContext;
212 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
214 static EbmlSyntax ebml_header[] = {
215 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
216 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
217 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
218 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
219 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
220 { EBML_ID_EBMLVERSION, EBML_NONE },
221 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
222 { EBML_ID_VOID, EBML_NONE },
226 static EbmlSyntax ebml_syntax[] = {
227 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
231 static EbmlSyntax matroska_info[] = {
232 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
233 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
234 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
235 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
236 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
237 { MATROSKA_ID_DATEUTC, EBML_NONE },
238 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
239 { EBML_ID_VOID, EBML_NONE },
243 static EbmlSyntax matroska_track_video[] = {
244 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
245 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
246 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
247 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
248 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
249 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
250 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
251 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
252 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
253 { EBML_ID_VOID, EBML_NONE },
257 static EbmlSyntax matroska_track_audio[] = {
258 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
259 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
260 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
261 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
262 { EBML_ID_VOID, EBML_NONE },
266 static EbmlSyntax matroska_track_encoding_compression[] = {
267 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
268 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
269 { EBML_ID_VOID, EBML_NONE },
273 static EbmlSyntax matroska_track_encoding[] = {
274 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
275 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
276 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
277 { EBML_ID_VOID, EBML_NONE },
281 static EbmlSyntax matroska_track_encodings[] = {
282 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
283 { EBML_ID_VOID, EBML_NONE },
287 static EbmlSyntax matroska_track[] = {
288 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
289 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
290 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
291 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
292 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
293 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
294 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
295 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
296 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
297 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
298 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
299 { MATROSKA_ID_TRACKUID, EBML_NONE },
300 { MATROSKA_ID_TRACKNAME, EBML_NONE },
301 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
302 { MATROSKA_ID_TRACKFLAGFORCED, EBML_NONE },
303 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
304 { MATROSKA_ID_CODECNAME, EBML_NONE },
305 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
306 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
307 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
308 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
309 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
310 { EBML_ID_VOID, EBML_NONE },
314 static EbmlSyntax matroska_tracks[] = {
315 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
316 { EBML_ID_VOID, EBML_NONE },
320 static EbmlSyntax matroska_attachment[] = {
321 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
322 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
323 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
324 { MATROSKA_ID_FILEUID, EBML_NONE },
325 { EBML_ID_VOID, EBML_NONE },
329 static EbmlSyntax matroska_attachments[] = {
330 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
331 { EBML_ID_VOID, EBML_NONE },
335 static EbmlSyntax matroska_chapter_display[] = {
336 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
337 { EBML_ID_VOID, EBML_NONE },
341 static EbmlSyntax matroska_chapter_entry[] = {
342 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
343 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
344 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
345 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
346 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
347 { EBML_ID_VOID, EBML_NONE },
351 static EbmlSyntax matroska_chapter[] = {
352 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
353 { MATROSKA_ID_EDITIONUID, EBML_NONE },
354 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
355 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
356 { EBML_ID_VOID, EBML_NONE },
360 static EbmlSyntax matroska_chapters[] = {
361 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
362 { EBML_ID_VOID, EBML_NONE },
366 static EbmlSyntax matroska_index_pos[] = {
367 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
368 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
369 { EBML_ID_VOID, EBML_NONE },
373 static EbmlSyntax matroska_index_entry[] = {
374 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
375 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
376 { EBML_ID_VOID, EBML_NONE },
380 static EbmlSyntax matroska_index[] = {
381 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
382 { EBML_ID_VOID, EBML_NONE },
386 static EbmlSyntax matroska_tags[] = {
387 { EBML_ID_VOID, EBML_NONE },
392 * The first few functions handle EBML file parsing. The rest
393 * is the document interpretation. Matroska really just is a
398 * Return: the amount of levels in the hierarchy that the
399 * current element lies higher than the previous one.
400 * The opposite isn't done - that's auto-done using master
405 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
407 ByteIOContext *pb = matroska->ctx->pb;
408 offset_t pos = url_ftell(pb);
411 while (matroska->num_levels > 0) {
412 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
414 if (pos >= level->start + level->length) {
415 matroska->num_levels--;
426 * Read: an "EBML number", which is defined as a variable-length
427 * array of bytes. The first byte indicates the length by giving a
428 * number of 0-bits followed by a one. The position of the first
429 * "one" bit inside the first byte indicates the length of this
431 * Returns: num. of bytes read. < 0 on error.
435 ebml_read_num (MatroskaDemuxContext *matroska,
439 ByteIOContext *pb = matroska->ctx->pb;
440 int len_mask = 0x80, read = 1, n = 1;
443 /* the first byte tells us the length in bytes - get_byte() can normally
444 * return 0, but since that's not a valid first ebmlID byte, we can
445 * use it safely here to catch EOS. */
446 if (!(total = get_byte(pb))) {
447 /* we might encounter EOS here */
449 offset_t pos = url_ftell(pb);
450 av_log(matroska->ctx, AV_LOG_ERROR,
451 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
454 return AVERROR(EIO); /* EOS or actual I/O error */
457 /* get the length of the EBML number */
458 while (read <= max_size && !(total & len_mask)) {
462 if (read > max_size) {
463 offset_t pos = url_ftell(pb) - 1;
464 av_log(matroska->ctx, AV_LOG_ERROR,
465 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
466 (uint8_t) total, pos, pos);
467 return AVERROR_INVALIDDATA;
470 /* read out length */
473 total = (total << 8) | get_byte(pb);
481 * Read: the element content data ID.
482 * Return: the number of bytes read or < 0 on error.
486 ebml_read_element_id (MatroskaDemuxContext *matroska,
493 /* if we re-call this, use our cached ID */
494 if (matroska->peek_id != 0) {
497 *id = matroska->peek_id;
501 /* read out the "EBML number", include tag in ID */
502 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
504 *id = matroska->peek_id = total | (1 << (read * 7));
508 *level_up = ebml_read_element_level_up(matroska);
514 * Read: element content length.
515 * Return: the number of bytes read or < 0 on error.
519 ebml_read_element_length (MatroskaDemuxContext *matroska,
522 /* clear cache since we're now beyond that data point */
523 matroska->peek_id = 0;
525 /* read out the "EBML number", include tag in ID */
526 return ebml_read_num(matroska, 8, length);
530 * Return: the ID of the next element, or 0 on error.
531 * Level_up contains the amount of levels that this
532 * next element lies higher than the previous one.
536 ebml_peek_id (MatroskaDemuxContext *matroska,
541 if (ebml_read_element_id(matroska, &id, level_up) < 0)
548 * Seek to a given offset.
549 * 0 is success, -1 is failure.
553 ebml_read_seek (MatroskaDemuxContext *matroska,
556 ByteIOContext *pb = matroska->ctx->pb;
558 /* clear ID cache, if any */
559 matroska->peek_id = 0;
561 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
565 * Skip the next element.
566 * 0 is success, -1 is failure.
570 ebml_read_skip (MatroskaDemuxContext *matroska)
572 ByteIOContext *pb = matroska->ctx->pb;
577 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
578 (res = ebml_read_element_length(matroska, &length)) < 0)
581 url_fskip(pb, length);
587 * Read the next element as an unsigned int.
588 * 0 is success, < 0 is failure.
592 ebml_read_uint (MatroskaDemuxContext *matroska,
596 ByteIOContext *pb = matroska->ctx->pb;
597 int n = 0, size, 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 uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
609 return AVERROR_INVALIDDATA;
612 /* big-endian ordening; build up number */
615 *num = (*num << 8) | get_byte(pb);
621 * Read the next element as a signed int.
622 * 0 is success, < 0 is failure.
626 ebml_read_sint (MatroskaDemuxContext *matroska,
630 ByteIOContext *pb = matroska->ctx->pb;
631 int size, n = 1, negative = 0, res;
634 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
635 (res = ebml_read_element_length(matroska, &rlength)) < 0)
638 if (size < 1 || size > 8) {
639 offset_t pos = url_ftell(pb);
640 av_log(matroska->ctx, AV_LOG_ERROR,
641 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
643 return AVERROR_INVALIDDATA;
645 if ((*num = get_byte(pb)) & 0x80) {
650 *num = (*num << 8) | get_byte(pb);
654 *num = *num - (1LL << ((8 * size) - 1));
660 * Read the next element as a float.
661 * 0 is success, < 0 is failure.
665 ebml_read_float (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)
679 *num= av_int2flt(get_be32(pb));
681 *num= av_int2dbl(get_be64(pb));
683 offset_t pos = url_ftell(pb);
684 av_log(matroska->ctx, AV_LOG_ERROR,
685 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
687 return AVERROR_INVALIDDATA;
694 * Read the next element as an ASCII string.
695 * 0 is success, < 0 is failure.
699 ebml_read_ascii (MatroskaDemuxContext *matroska,
703 ByteIOContext *pb = matroska->ctx->pb;
707 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
708 (res = ebml_read_element_length(matroska, &rlength)) < 0)
712 /* ebml strings are usually not 0-terminated, so we allocate one
713 * byte more, read the string and NULL-terminate it ourselves. */
714 if (size < 0 || !(*str = av_malloc(size + 1))) {
715 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
716 return AVERROR(ENOMEM);
718 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
719 offset_t pos = url_ftell(pb);
720 av_log(matroska->ctx, AV_LOG_ERROR,
721 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
731 * Read the next element as a UTF-8 string.
732 * 0 is success, < 0 is failure.
736 ebml_read_utf8 (MatroskaDemuxContext *matroska,
740 return ebml_read_ascii(matroska, id, str);
744 * Read the next element, but only the header. The contents
745 * are supposed to be sub-elements which can be read separately.
746 * 0 is success, < 0 is failure.
750 ebml_read_master (MatroskaDemuxContext *matroska,
753 ByteIOContext *pb = matroska->ctx->pb;
755 MatroskaLevel *level;
758 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
759 (res = ebml_read_element_length(matroska, &length)) < 0)
762 /* protect... (Heaven forbids that the '>' is true) */
763 if (matroska->num_levels >= EBML_MAX_DEPTH) {
764 av_log(matroska->ctx, AV_LOG_ERROR,
765 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
766 return AVERROR(ENOSYS);
770 level = &matroska->levels[matroska->num_levels++];
771 level->start = url_ftell(pb);
772 level->length = length;
778 * Read the next element as binary data.
779 * 0 is success, < 0 is failure.
783 ebml_read_binary (MatroskaDemuxContext *matroska,
788 ByteIOContext *pb = matroska->ctx->pb;
792 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
793 (res = ebml_read_element_length(matroska, &rlength)) < 0)
797 if (!(*binary = av_malloc(*size))) {
798 av_log(matroska->ctx, AV_LOG_ERROR,
799 "Memory allocation error\n");
800 return AVERROR(ENOMEM);
803 if (get_buffer(pb, *binary, *size) != *size) {
804 offset_t pos = url_ftell(pb);
805 av_log(matroska->ctx, AV_LOG_ERROR,
806 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
814 * Read signed/unsigned "EBML" numbers.
815 * Return: number of bytes processed, < 0 on error.
816 * XXX: use ebml_read_num().
820 matroska_ebmlnum_uint (uint8_t *data,
824 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
828 return AVERROR_INVALIDDATA;
831 while (read <= 8 && !(total & len_mask)) {
836 return AVERROR_INVALIDDATA;
838 if ((total &= (len_mask - 1)) == len_mask - 1)
841 return AVERROR_INVALIDDATA;
845 total = (total << 8) | data[n];
858 * Same as above, but signed.
862 matroska_ebmlnum_sint (uint8_t *data,
869 /* read as unsigned number first */
870 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
873 /* make signed (weird way) */
874 if (unum == (uint64_t)-1)
877 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
883 static MatroskaTrack *
884 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
887 MatroskaTrack *tracks = matroska->tracks.elem;
890 for (i=0; i < matroska->tracks.nb_elem; i++)
891 if (tracks[i].num == num)
894 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
900 * Put one packet in an application-supplied AVPacket struct.
901 * Returns 0 on success or -1 on failure.
905 matroska_deliver_packet (MatroskaDemuxContext *matroska,
908 if (matroska->num_packets > 0) {
909 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
910 av_free(matroska->packets[0]);
911 if (matroska->num_packets > 1) {
912 memmove(&matroska->packets[0], &matroska->packets[1],
913 (matroska->num_packets - 1) * sizeof(AVPacket *));
915 av_realloc(matroska->packets, (matroska->num_packets - 1) *
918 av_freep(&matroska->packets);
920 matroska->num_packets--;
928 * Put a packet into our internal queue. Will be delivered to the
929 * user/application during the next get_packet() call.
933 matroska_queue_packet (MatroskaDemuxContext *matroska,
937 av_realloc(matroska->packets, (matroska->num_packets + 1) *
939 matroska->packets[matroska->num_packets] = pkt;
940 matroska->num_packets++;
944 * Free all packets in our internal queue.
947 matroska_clear_queue (MatroskaDemuxContext *matroska)
949 if (matroska->packets) {
951 for (n = 0; n < matroska->num_packets; n++) {
952 av_free_packet(matroska->packets[n]);
953 av_free(matroska->packets[n]);
955 av_free(matroska->packets);
956 matroska->packets = NULL;
957 matroska->num_packets = 0;
967 matroska_probe (AVProbeData *p)
970 int len_mask = 0x80, size = 1, n = 1;
971 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
974 if (AV_RB32(p->buf) != EBML_ID_HEADER)
977 /* length of header */
979 while (size <= 8 && !(total & len_mask)) {
985 total &= (len_mask - 1);
987 total = (total << 8) | p->buf[4 + n++];
989 /* does the probe data contain the whole header? */
990 if (p->buf_size < 4 + size + total)
993 /* the header must contain the document type 'matroska'. For now,
994 * we don't parse the whole header but simply check for the
995 * availability of that array of characters inside the header.
996 * Not fully fool-proof, but good enough. */
997 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
998 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
999 return AVPROBE_SCORE_MAX;
1005 * From here on, it's all XML-style DTD stuff... Needs no comments.
1008 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1009 void *data, uint32_t expected_id, int once);
1011 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1012 EbmlSyntax *syntax, void *data)
1014 uint32_t id = syntax->id;
1018 data = (char *)data + syntax->data_offset;
1019 if (syntax->list_elem_size) {
1020 EbmlList *list = data;
1021 list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1022 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1023 memset(data, 0, syntax->list_elem_size);
1028 switch (syntax->type) {
1029 case EBML_UINT: return ebml_read_uint (matroska, &id, data);
1030 case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1032 case EBML_UTF8: av_free(*(char **)data);
1033 return ebml_read_ascii(matroska, &id, data);
1034 case EBML_BIN: av_free(bin->data);
1035 bin->pos = url_ftell(matroska->ctx->pb);
1036 return ebml_read_binary(matroska, &id, &bin->data,
1038 case EBML_NEST: if ((res=ebml_read_master(matroska, &id)) < 0)
1040 if (id == MATROSKA_ID_SEGMENT)
1041 matroska->segment_start = url_ftell(matroska->ctx->pb);
1042 return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1043 case EBML_PASS: return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1044 case EBML_STOP: *(int *)data = 1; return 1;
1045 default: return ebml_read_skip(matroska);
1049 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1050 uint32_t id, void *data)
1053 for (i=0; syntax[i].id; i++)
1054 if (id == syntax[i].id)
1057 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1058 return ebml_parse_elem(matroska, &syntax[i], data);
1061 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1062 void *data, uint32_t expected_id, int once)
1067 for (i=0; syntax[i].id; i++)
1068 switch (syntax[i].type) {
1070 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1073 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1077 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1082 res = ebml_read_master(matroska, &id);
1083 if (id != expected_id)
1084 return AVERROR_INVALIDDATA;
1085 if (id == MATROSKA_ID_SEGMENT)
1086 matroska->segment_start = url_ftell(matroska->ctx->pb);
1090 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1093 } else if (matroska->level_up) {
1094 matroska->level_up--;
1098 res = ebml_parse_id(matroska, syntax, id, data);
1103 if (matroska->level_up) {
1104 matroska->level_up--;
1112 static void ebml_free(EbmlSyntax *syntax, void *data)
1115 for (i=0; syntax[i].id; i++) {
1116 void *data_off = (char *)data + syntax[i].data_offset;
1117 switch (syntax[i].type) {
1119 case EBML_UTF8: av_freep(data_off); break;
1120 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
1122 if (syntax[i].list_elem_size) {
1123 EbmlList *list = data_off;
1124 char *ptr = list->elem;
1125 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1126 ebml_free(syntax[i].def.n, ptr);
1127 av_free(list->elem);
1129 ebml_free(syntax[i].def.n, data_off);
1136 matroska_parse_info (MatroskaDemuxContext *matroska)
1138 int res = ebml_parse(matroska, matroska_info, matroska, MATROSKA_ID_INFO, 0);
1140 if (matroska->duration)
1141 matroska->ctx->duration = matroska->duration * matroska->time_scale
1142 * 1000 / AV_TIME_BASE;
1143 if (matroska->title)
1144 strncpy(matroska->ctx->title, matroska->title,
1145 sizeof(matroska->ctx->title)-1);
1151 matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1153 MatroskaTrackEncoding *encodings = track->encodings.elem;
1154 uint8_t* data = *buf;
1155 int isize = *buf_size;
1156 uint8_t* pkt_data = NULL;
1157 int pkt_size = isize;
1161 switch (encodings[0].compression.algo) {
1162 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1163 return encodings[0].compression.settings.size;
1164 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1166 olen = pkt_size *= 3;
1167 pkt_data = av_realloc(pkt_data,
1168 pkt_size+LZO_OUTPUT_PADDING);
1169 result = lzo1x_decode(pkt_data, &olen, data, &isize);
1170 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1176 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1177 z_stream zstream = {0};
1178 if (inflateInit(&zstream) != Z_OK)
1180 zstream.next_in = data;
1181 zstream.avail_in = isize;
1184 pkt_data = av_realloc(pkt_data, pkt_size);
1185 zstream.avail_out = pkt_size - zstream.total_out;
1186 zstream.next_out = pkt_data + zstream.total_out;
1187 result = inflate(&zstream, Z_NO_FLUSH);
1188 } while (result==Z_OK && pkt_size<10000000);
1189 pkt_size = zstream.total_out;
1190 inflateEnd(&zstream);
1191 if (result != Z_STREAM_END)
1197 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1198 bz_stream bzstream = {0};
1199 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1201 bzstream.next_in = data;
1202 bzstream.avail_in = isize;
1205 pkt_data = av_realloc(pkt_data, pkt_size);
1206 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1207 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1208 result = BZ2_bzDecompress(&bzstream);
1209 } while (result==BZ_OK && pkt_size<10000000);
1210 pkt_size = bzstream.total_out_lo32;
1211 BZ2_bzDecompressEnd(&bzstream);
1212 if (result != BZ_STREAM_END)
1220 *buf_size = pkt_size;
1228 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1230 MatroskaTrack *tracks;
1233 res = ebml_parse(matroska, matroska_tracks, matroska, MATROSKA_ID_TRACKS, 0);
1235 tracks = matroska->tracks.elem;
1236 for (i=0; i<matroska->tracks.nb_elem; i++) {
1237 MatroskaTrack *track = &tracks[i];
1238 EbmlList *encodings_list = &tracks->encodings;
1239 MatroskaTrackEncoding *encodings = encodings_list->elem;
1241 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1242 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1243 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1244 av_log(matroska->ctx, AV_LOG_INFO,
1245 "Unknown or unsupported track type %"PRIu64"\n",
1250 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1251 if (!track->default_duration)
1252 track->default_duration = 1000000000/track->video.frame_rate;
1253 if (!track->video.display_width)
1254 track->video.display_width = track->video.pixel_width;
1255 if (!track->video.display_height)
1256 track->video.display_height = track->video.pixel_height;
1257 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1258 if (!track->audio.out_samplerate)
1259 track->audio.out_samplerate = track->audio.samplerate;
1261 if (encodings_list->nb_elem > 1) {
1262 av_log(matroska->ctx, AV_LOG_ERROR,
1263 "Multiple combined encodings no supported");
1264 } else if (encodings_list->nb_elem == 1) {
1265 if (encodings[0].type ||
1266 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1268 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1271 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1273 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1274 encodings[0].scope = 0;
1275 av_log(matroska->ctx, AV_LOG_ERROR,
1276 "Unsupported encoding type");
1277 } else if (track->codec_priv.size && encodings[0].scope&2) {
1278 uint8_t *codec_priv = track->codec_priv.data;
1279 int offset = matroska_decode_buffer(&track->codec_priv.data,
1280 &track->codec_priv.size,
1283 track->codec_priv.data = NULL;
1284 track->codec_priv.size = 0;
1285 av_log(matroska->ctx, AV_LOG_ERROR,
1286 "Failed to decode codec private data\n");
1287 } else if (offset > 0) {
1288 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1289 memcpy(track->codec_priv.data,
1290 encodings[0].compression.settings.data, offset);
1291 memcpy(track->codec_priv.data+offset, codec_priv,
1292 track->codec_priv.size);
1293 track->codec_priv.size += offset;
1295 if (codec_priv != track->codec_priv.data)
1296 av_free(codec_priv);
1305 matroska_parse_index (MatroskaDemuxContext *matroska)
1307 return ebml_parse(matroska, matroska_index, matroska, MATROSKA_ID_CUES, 0);
1311 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1313 return ebml_parse(matroska, matroska_tags, matroska, MATROSKA_ID_TAGS, 0);
1317 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1322 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1325 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1328 } else if (matroska->level_up) {
1329 matroska->level_up--;
1334 case MATROSKA_ID_SEEKENTRY: {
1335 uint32_t seek_id = 0, peek_id_cache = 0;
1336 uint64_t seek_pos = (uint64_t) -1, t;
1337 int dummy_level = 0;
1339 if ((res = ebml_read_master(matroska, &id)) < 0)
1343 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1346 } else if (matroska->level_up) {
1347 matroska->level_up--;
1352 case MATROSKA_ID_SEEKID:
1353 res = ebml_read_uint(matroska, &id, &t);
1357 case MATROSKA_ID_SEEKPOSITION:
1358 res = ebml_read_uint(matroska, &id, &seek_pos);
1362 av_log(matroska->ctx, AV_LOG_INFO,
1363 "Unknown seekhead ID 0x%x\n", id);
1367 res = ebml_read_skip(matroska);
1371 if (matroska->level_up) {
1372 matroska->level_up--;
1377 if (!seek_id || seek_pos == (uint64_t) -1) {
1378 av_log(matroska->ctx, AV_LOG_INFO,
1379 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1385 case MATROSKA_ID_CUES:
1386 case MATROSKA_ID_TAGS: {
1387 uint32_t level_up = matroska->level_up;
1388 offset_t before_pos;
1389 MatroskaLevel level;
1391 /* remember the peeked ID and the current position */
1392 peek_id_cache = matroska->peek_id;
1393 before_pos = url_ftell(matroska->ctx->pb);
1396 if ((res = ebml_read_seek(matroska, seek_pos +
1397 matroska->segment_start)) < 0)
1400 /* we don't want to lose our seekhead level, so we add
1401 * a dummy. This is a crude hack. */
1402 if (matroska->num_levels == EBML_MAX_DEPTH) {
1403 av_log(matroska->ctx, AV_LOG_INFO,
1404 "Max EBML element depth (%d) reached, "
1405 "cannot parse further.\n", EBML_MAX_DEPTH);
1406 return AVERROR_UNKNOWN;
1410 level.length = (uint64_t)-1;
1411 matroska->levels[matroska->num_levels] = level;
1412 matroska->num_levels++;
1416 if (!(id = ebml_peek_id (matroska,
1417 &matroska->level_up)))
1419 if (id != seek_id) {
1420 av_log(matroska->ctx, AV_LOG_INFO,
1421 "We looked for ID=0x%x but got "
1422 "ID=0x%x (pos=%"PRIu64")",
1423 seek_id, id, seek_pos +
1424 matroska->segment_start);
1428 /* read master + parse */
1430 case MATROSKA_ID_CUES:
1431 if (!(res = matroska_parse_index(matroska)) ||
1432 url_feof(matroska->ctx->pb)) {
1433 matroska->index_parsed = 1;
1437 case MATROSKA_ID_TAGS:
1438 if (!(res = matroska_parse_metadata(matroska)) ||
1439 url_feof(matroska->ctx->pb)) {
1440 matroska->metadata_parsed = 1;
1447 /* remove dummy level */
1449 while (matroska->num_levels) {
1450 uint64_t length = matroska->levels[--matroska->num_levels].length;
1451 if (length == (uint64_t)-1)
1456 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1458 matroska->peek_id = peek_id_cache;
1459 matroska->level_up = level_up;
1464 av_log(matroska->ctx, AV_LOG_INFO,
1465 "Ignoring seekhead entry for ID=0x%x\n",
1474 av_log(matroska->ctx, AV_LOG_INFO,
1475 "Unknown seekhead ID 0x%x\n", id);
1479 res = ebml_read_skip(matroska);
1483 if (matroska->level_up) {
1484 matroska->level_up--;
1493 matroska_parse_attachments(AVFormatContext *s)
1495 MatroskaDemuxContext *matroska = s->priv_data;
1496 EbmlList *attachements_list = &matroska->attachments;
1497 MatroskaAttachement *attachements;
1500 res = ebml_parse(matroska, matroska_attachments, matroska, MATROSKA_ID_ATTACHMENTS, 0);
1502 attachements = attachements_list->elem;
1503 for (j=0; j<attachements_list->nb_elem; j++) {
1504 if (!(attachements[j].filename && attachements[j].mime &&
1505 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1506 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1508 AVStream *st = av_new_stream(s, matroska->num_streams++);
1511 st->filename = av_strdup(attachements[j].filename);
1512 st->codec->codec_id = CODEC_ID_NONE;
1513 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1514 st->codec->extradata = av_malloc(attachements[j].bin.size);
1515 if(st->codec->extradata == NULL)
1517 st->codec->extradata_size = attachements[j].bin.size;
1518 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1520 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1521 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1522 strlen(ff_mkv_mime_tags[i].str))) {
1523 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1534 matroska_parse_chapters(AVFormatContext *s)
1536 MatroskaDemuxContext *matroska = s->priv_data;
1537 EbmlList *chapters_list = &matroska->chapters;
1538 MatroskaChapter *chapters;
1541 res = ebml_parse(matroska, matroska_chapters, matroska, MATROSKA_ID_CHAPTERS, 0);
1543 chapters = chapters_list->elem;
1544 for (i=0; i<chapters_list->nb_elem; i++)
1545 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1546 ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1547 chapters[i].start, chapters[i].end,
1554 matroska_aac_profile (char *codec_id)
1556 static const char *aac_profiles[] = {
1561 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1562 if (strstr(codec_id, aac_profiles[profile]))
1568 matroska_aac_sri (int samplerate)
1572 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1573 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1579 matroska_read_header (AVFormatContext *s,
1580 AVFormatParameters *ap)
1582 MatroskaDemuxContext *matroska = s->priv_data;
1583 EbmlList *index_list;
1584 MatroskaIndex *index;
1585 int i, j, last_level, res = 0;
1591 /* First read the EBML header. */
1592 if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1593 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1594 || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1595 || ebml.doctype_version > 2) {
1596 av_log(matroska->ctx, AV_LOG_ERROR,
1597 "EBML header using unsupported features\n"
1598 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1599 ebml.version, ebml.doctype, ebml.doctype_version);
1600 return AVERROR_NOFMT;
1602 ebml_free(ebml_syntax, &ebml);
1604 /* The next thing is a segment. */
1606 if (!(id = ebml_peek_id(matroska, &last_level)))
1607 return AVERROR(EIO);
1608 if (id == MATROSKA_ID_SEGMENT)
1612 av_log(matroska->ctx, AV_LOG_INFO,
1613 "Expected a Segment ID (0x%x), but received 0x%x!\n",
1614 MATROSKA_ID_SEGMENT, id);
1615 if ((res = ebml_read_skip(matroska)) < 0)
1619 /* We now have a Matroska segment.
1620 * Seeks are from the beginning of the segment,
1621 * after the segment ID/length. */
1622 if ((res = ebml_read_master(matroska, &id)) < 0)
1624 matroska->segment_start = url_ftell(s->pb);
1626 matroska->time_scale = 1000000;
1627 /* we've found our segment, start reading the different contents in here */
1629 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1632 } else if (matroska->level_up) {
1633 matroska->level_up--;
1639 case MATROSKA_ID_INFO: {
1640 res = matroska_parse_info(matroska);
1644 /* track info headers */
1645 case MATROSKA_ID_TRACKS: {
1646 res = matroska_parse_tracks(matroska);
1651 case MATROSKA_ID_CUES: {
1652 if (!matroska->index_parsed) {
1653 res = matroska_parse_index(matroska);
1655 res = ebml_read_skip(matroska);
1660 case MATROSKA_ID_TAGS: {
1661 if (!matroska->metadata_parsed) {
1662 res = matroska_parse_metadata(matroska);
1664 res = ebml_read_skip(matroska);
1668 /* file index (if seekable, seek to Cues/Tags to parse it) */
1669 case MATROSKA_ID_SEEKHEAD: {
1670 if ((res = ebml_read_master(matroska, &id)) < 0)
1672 res = matroska_parse_seekhead(matroska);
1676 case MATROSKA_ID_ATTACHMENTS: {
1677 res = matroska_parse_attachments(s);
1681 case MATROSKA_ID_CLUSTER: {
1682 /* Do not read the master - this will be done in the next
1683 * call to matroska_read_packet. */
1688 case MATROSKA_ID_CHAPTERS: {
1689 res = matroska_parse_chapters(s);
1694 av_log(matroska->ctx, AV_LOG_INFO,
1695 "Unknown matroska file header ID 0x%x\n", id);
1699 res = ebml_read_skip(matroska);
1703 if (matroska->level_up) {
1704 matroska->level_up--;
1709 /* Have we found a cluster? */
1710 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
1711 MatroskaTrack *tracks = matroska->tracks.elem;
1715 for (i=0; i < matroska->tracks.nb_elem; i++) {
1716 MatroskaTrack *track = &tracks[i];
1717 enum CodecID codec_id = CODEC_ID_NONE;
1718 uint8_t *extradata = NULL;
1719 int extradata_size = 0;
1720 int extradata_offset = 0;
1722 /* Apply some sanity checks. */
1723 if (track->codec_id == NULL)
1726 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1727 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1728 strlen(ff_mkv_codec_tags[j].str))){
1729 codec_id= ff_mkv_codec_tags[j].id;
1734 st = track->stream = av_new_stream(s, matroska->num_streams++);
1736 return AVERROR(ENOMEM);
1738 /* Set the FourCC from the CodecID. */
1739 /* This is the MS compatibility mode which stores a
1740 * BITMAPINFOHEADER in the CodecPrivate. */
1741 if (!strcmp(track->codec_id,
1742 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
1743 (track->codec_priv.size >= 40) &&
1744 (track->codec_priv.data != NULL)) {
1745 /* Offset of biCompression. Stored in LE. */
1746 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1747 codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1751 /* This is the MS compatibility mode which stores a
1752 * WAVEFORMATEX in the CodecPrivate. */
1753 else if (!strcmp(track->codec_id,
1754 MATROSKA_CODEC_ID_AUDIO_ACM) &&
1755 (track->codec_priv.size >= 18) &&
1756 (track->codec_priv.data != NULL)) {
1757 /* Offset of wFormatTag. Stored in LE. */
1758 uint16_t tag = AV_RL16(track->codec_priv.data);
1759 codec_id = codec_get_id(codec_wav_tags, tag);
1763 if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1764 (track->codec_priv.size >= 86) &&
1765 (track->codec_priv.data != NULL)) {
1766 track->video.fourcc = AV_RL32(track->codec_priv.data);
1767 codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1770 else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1771 int profile = matroska_aac_profile(track->codec_id);
1772 int sri = matroska_aac_sri(track->audio.samplerate);
1773 extradata = av_malloc(5);
1774 if (extradata == NULL)
1775 return AVERROR(ENOMEM);
1776 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1777 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1778 if (strstr(track->codec_id, "SBR")) {
1779 sri = matroska_aac_sri(track->audio.out_samplerate);
1780 extradata[2] = 0x56;
1781 extradata[3] = 0xE5;
1782 extradata[4] = 0x80 | (sri<<3);
1789 else if (codec_id == CODEC_ID_TTA) {
1791 extradata_size = 30;
1792 extradata = av_mallocz(extradata_size);
1793 if (extradata == NULL)
1794 return AVERROR(ENOMEM);
1795 init_put_byte(&b, extradata, extradata_size, 1,
1796 NULL, NULL, NULL, NULL);
1797 put_buffer(&b, "TTA1", 4);
1799 put_le16(&b, track->audio.channels);
1800 put_le16(&b, track->audio.bitdepth);
1801 put_le32(&b, track->audio.out_samplerate);
1802 put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1805 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1806 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1807 extradata_offset = 26;
1808 track->codec_priv.size -= extradata_offset;
1811 else if (codec_id == CODEC_ID_RA_144) {
1812 track->audio.out_samplerate = 8000;
1813 track->audio.channels = 1;
1816 else if (codec_id == CODEC_ID_RA_288 ||
1817 codec_id == CODEC_ID_COOK ||
1818 codec_id == CODEC_ID_ATRAC3) {
1821 init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1822 0, NULL, NULL, NULL, NULL);
1824 track->audio.coded_framesize = get_be32(&b);
1826 track->audio.sub_packet_h = get_be16(&b);
1827 track->audio.frame_size = get_be16(&b);
1828 track->audio.sub_packet_size = get_be16(&b);
1829 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1830 if (codec_id == CODEC_ID_RA_288) {
1831 st->codec->block_align = track->audio.coded_framesize;
1832 track->codec_priv.size = 0;
1834 st->codec->block_align = track->audio.sub_packet_size;
1835 extradata_offset = 78;
1836 track->codec_priv.size -= extradata_offset;
1840 if (codec_id == CODEC_ID_NONE) {
1841 av_log(matroska->ctx, AV_LOG_INFO,
1842 "Unknown/unsupported CodecID %s.\n",
1846 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1848 st->codec->codec_id = codec_id;
1850 if (strcmp(track->language, "und"))
1851 av_strlcpy(st->language, track->language, 4);
1853 if (track->flag_default)
1854 st->disposition |= AV_DISPOSITION_DEFAULT;
1856 if (track->default_duration)
1857 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1858 track->default_duration, 1000000000, 30000);
1861 st->codec->extradata = extradata;
1862 st->codec->extradata_size = extradata_size;
1863 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1864 st->codec->extradata = av_malloc(track->codec_priv.size);
1865 if(st->codec->extradata == NULL)
1866 return AVERROR(ENOMEM);
1867 st->codec->extradata_size = track->codec_priv.size;
1868 memcpy(st->codec->extradata,
1869 track->codec_priv.data + extradata_offset,
1870 track->codec_priv.size);
1873 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1874 st->codec->codec_type = CODEC_TYPE_VIDEO;
1875 st->codec->codec_tag = track->video.fourcc;
1876 st->codec->width = track->video.pixel_width;
1877 st->codec->height = track->video.pixel_height;
1878 av_reduce(&st->codec->sample_aspect_ratio.num,
1879 &st->codec->sample_aspect_ratio.den,
1880 st->codec->height * track->video.display_width,
1881 st->codec-> width * track->video.display_height,
1883 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1884 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1885 st->codec->codec_type = CODEC_TYPE_AUDIO;
1886 st->codec->sample_rate = track->audio.out_samplerate;
1887 st->codec->channels = track->audio.channels;
1888 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1889 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1892 /* What do we do with private data? E.g. for Vorbis. */
1897 index_list = &matroska->index;
1898 index = index_list->elem;
1899 for (i=0; i<index_list->nb_elem; i++) {
1900 EbmlList *pos_list = &index[i].pos;
1901 MatroskaIndexPos *pos = pos_list->elem;
1902 for (j=0; j<pos_list->nb_elem; j++) {
1903 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1905 if (track && track->stream)
1906 av_add_index_entry(track->stream,
1907 pos[j].pos + matroska->segment_start,
1908 index[i].time*matroska->time_scale/AV_TIME_BASE,
1909 0, 0, AVINDEX_KEYFRAME);
1917 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1918 int64_t pos, uint64_t cluster_time, uint64_t duration,
1921 MatroskaTrack *track;
1925 uint8_t *origdata = data;
1927 uint32_t *lace_size = NULL;
1928 int n, flags, laces = 0;
1931 /* first byte(s): tracknum */
1932 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1933 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1940 /* fetch track from num */
1941 track = matroska_find_track_by_num(matroska, num);
1942 if (size <= 3 || !track || !track->stream) {
1943 av_log(matroska->ctx, AV_LOG_INFO,
1944 "Invalid stream %"PRIu64" or size %u\n", num, size);
1949 if (st->discard >= AVDISCARD_ALL) {
1953 if (duration == AV_NOPTS_VALUE)
1954 duration = track->default_duration / matroska->time_scale;
1956 /* block_time (relative to cluster time) */
1957 block_time = AV_RB16(data);
1961 if (is_keyframe == -1)
1962 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1964 if (matroska->skip_to_keyframe) {
1965 if (!is_keyframe || st != matroska->skip_to_stream) {
1969 matroska->skip_to_keyframe = 0;
1972 switch ((flags & 0x06) >> 1) {
1973 case 0x0: /* no lacing */
1975 lace_size = av_mallocz(sizeof(int));
1976 lace_size[0] = size;
1979 case 0x1: /* xiph lacing */
1980 case 0x2: /* fixed-size lacing */
1981 case 0x3: /* EBML lacing */
1982 assert(size>0); // size <=3 is checked before size-=3 above
1983 laces = (*data) + 1;
1986 lace_size = av_mallocz(laces * sizeof(int));
1988 switch ((flags & 0x06) >> 1) {
1989 case 0x1: /* xiph lacing */ {
1992 for (n = 0; res == 0 && n < laces - 1; n++) {
1999 lace_size[n] += temp;
2005 total += lace_size[n];
2007 lace_size[n] = size - total;
2011 case 0x2: /* fixed-size lacing */
2012 for (n = 0; n < laces; n++)
2013 lace_size[n] = size / laces;
2016 case 0x3: /* EBML lacing */ {
2018 n = matroska_ebmlnum_uint(data, size, &num);
2020 av_log(matroska->ctx, AV_LOG_INFO,
2021 "EBML block data error\n");
2026 total = lace_size[0] = num;
2027 for (n = 1; res == 0 && n < laces - 1; n++) {
2030 r = matroska_ebmlnum_sint (data, size, &snum);
2032 av_log(matroska->ctx, AV_LOG_INFO,
2033 "EBML block data error\n");
2038 lace_size[n] = lace_size[n - 1] + snum;
2039 total += lace_size[n];
2041 lace_size[n] = size - total;
2049 uint64_t timecode = AV_NOPTS_VALUE;
2051 if (cluster_time != (uint64_t)-1
2052 && (block_time >= 0 || cluster_time >= -block_time))
2053 timecode = cluster_time + block_time;
2055 for (n = 0; n < laces; n++) {
2056 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2057 st->codec->codec_id == CODEC_ID_COOK ||
2058 st->codec->codec_id == CODEC_ID_ATRAC3) {
2059 int a = st->codec->block_align;
2060 int sps = track->audio.sub_packet_size;
2061 int cfs = track->audio.coded_framesize;
2062 int h = track->audio.sub_packet_h;
2063 int y = track->audio.sub_packet_cnt;
2064 int w = track->audio.frame_size;
2067 if (!track->audio.pkt_cnt) {
2068 if (st->codec->codec_id == CODEC_ID_RA_288)
2069 for (x=0; x<h/2; x++)
2070 memcpy(track->audio.buf+x*2*w+y*cfs,
2073 for (x=0; x<w/sps; x++)
2074 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2076 if (++track->audio.sub_packet_cnt >= h) {
2077 track->audio.sub_packet_cnt = 0;
2078 track->audio.pkt_cnt = h*w / a;
2081 while (track->audio.pkt_cnt) {
2082 pkt = av_mallocz(sizeof(AVPacket));
2083 av_new_packet(pkt, a);
2084 memcpy(pkt->data, track->audio.buf
2085 + a * (h*w / a - track->audio.pkt_cnt--), a);
2087 pkt->stream_index = st->index;
2088 matroska_queue_packet(matroska, pkt);
2091 MatroskaTrackEncoding *encodings = track->encodings.elem;
2092 int offset = 0, pkt_size = lace_size[n];
2093 uint8_t *pkt_data = data;
2095 if (encodings && encodings->scope & 1) {
2096 offset = matroska_decode_buffer(&pkt_data, &pkt_size,
2102 pkt = av_mallocz(sizeof(AVPacket));
2103 /* XXX: prevent data copy... */
2104 if (av_new_packet(pkt, pkt_size+offset) < 0) {
2106 res = AVERROR(ENOMEM);
2111 memcpy (pkt->data, encodings->compression.settings.data, offset);
2112 memcpy (pkt->data+offset, pkt_data, pkt_size);
2114 if (pkt_data != data)
2118 pkt->flags = is_keyframe;
2119 pkt->stream_index = st->index;
2121 pkt->pts = timecode;
2123 pkt->duration = duration;
2125 matroska_queue_packet(matroska, pkt);
2128 if (timecode != AV_NOPTS_VALUE)
2129 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2130 data += lace_size[n];
2140 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2141 uint64_t cluster_time)
2145 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2146 uint64_t duration = AV_NOPTS_VALUE;
2151 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2154 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2157 } else if (matroska->level_up) {
2158 matroska->level_up--;
2163 /* one block inside the group. Note, block parsing is one
2164 * of the harder things, so this code is a bit complicated.
2165 * See http://www.matroska.org/ for documentation. */
2166 case MATROSKA_ID_BLOCK: {
2167 pos = url_ftell(matroska->ctx->pb);
2168 res = ebml_read_binary(matroska, &id, &data, &size);
2172 case MATROSKA_ID_BLOCKDURATION: {
2173 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2178 case MATROSKA_ID_BLOCKREFERENCE: {
2180 /* We've found a reference, so not even the first frame in
2181 * the lace is a key frame. */
2183 if (last_num_packets != matroska->num_packets)
2184 matroska->packets[last_num_packets]->flags = 0;
2185 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2191 av_log(matroska->ctx, AV_LOG_INFO,
2192 "Unknown entry 0x%x in blockgroup data\n", id);
2196 res = ebml_read_skip(matroska);
2200 if (matroska->level_up) {
2201 matroska->level_up--;
2210 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2211 duration, is_keyframe);
2217 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2221 uint64_t cluster_time = 0;
2226 av_log(matroska->ctx, AV_LOG_DEBUG,
2227 "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2230 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2233 } else if (matroska->level_up) {
2234 matroska->level_up--;
2239 /* cluster timecode */
2240 case MATROSKA_ID_CLUSTERTIMECODE: {
2242 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2248 /* a group of blocks inside a cluster */
2249 case MATROSKA_ID_BLOCKGROUP:
2250 if ((res = ebml_read_master(matroska, &id)) < 0)
2252 res = matroska_parse_blockgroup(matroska, cluster_time);
2255 case MATROSKA_ID_SIMPLEBLOCK:
2256 pos = url_ftell(matroska->ctx->pb);
2257 res = ebml_read_binary(matroska, &id, &data, &size);
2259 res = matroska_parse_block(matroska, data, size, pos,
2260 cluster_time, AV_NOPTS_VALUE,
2265 av_log(matroska->ctx, AV_LOG_INFO,
2266 "Unknown entry 0x%x in cluster data\n", id);
2270 res = ebml_read_skip(matroska);
2274 if (matroska->level_up) {
2275 matroska->level_up--;
2284 matroska_read_packet (AVFormatContext *s,
2287 MatroskaDemuxContext *matroska = s->priv_data;
2291 /* Read stream until we have a packet queued. */
2292 while (matroska_deliver_packet(matroska, pkt)) {
2294 /* Have we already reached the end? */
2296 return AVERROR(EIO);
2300 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2301 return AVERROR(EIO);
2302 } else if (matroska->level_up) {
2303 matroska->level_up--;
2308 case MATROSKA_ID_CLUSTER:
2309 if ((res = ebml_read_master(matroska, &id)) < 0)
2311 if ((res = matroska_parse_cluster(matroska)) == 0)
2312 res = 1; /* Parsed one cluster, let's get out. */
2317 res = ebml_read_skip(matroska);
2321 if (matroska->level_up) {
2322 matroska->level_up--;
2335 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2338 MatroskaDemuxContext *matroska = s->priv_data;
2339 AVStream *st = s->streams[stream_index];
2342 /* find index entry */
2343 index = av_index_search_timestamp(st, timestamp, flags);
2347 matroska_clear_queue(matroska);
2350 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2351 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2352 matroska->skip_to_stream = st;
2353 matroska->peek_id = 0;
2354 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2359 matroska_read_close (AVFormatContext *s)
2361 MatroskaDemuxContext *matroska = s->priv_data;
2362 MatroskaTrack *tracks = matroska->tracks.elem;
2365 matroska_clear_queue(matroska);
2367 for (n=0; n < matroska->tracks.nb_elem; n++)
2368 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2369 av_free(tracks[n].audio.buf);
2370 ebml_free(matroska_tracks, matroska);
2371 ebml_free(matroska_index, matroska);
2376 AVInputFormat matroska_demuxer = {
2378 NULL_IF_CONFIG_SMALL("Matroska file format"),
2379 sizeof(MatroskaDemuxContext),
2381 matroska_read_header,
2382 matroska_read_packet,
2383 matroska_read_close,