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;
171 typedef struct MatroskaLevel {
176 typedef struct MatroskaDemuxContext {
177 AVFormatContext *ctx;
181 MatroskaLevel levels[EBML_MAX_DEPTH];
184 /* timescale in the file */
189 EbmlList attachments;
194 /* num_streams is the number of streams that av_new_stream() was called
195 * for ( = that are available to the calling program). */
198 /* cache for ID peeking */
201 /* byte position of the segment inside the stream */
202 offset_t segment_start;
204 /* The packet queue. */
208 /* have we already parse metadata/cues/clusters? */
214 /* What to skip before effectively reading a packet. */
215 int skip_to_keyframe;
216 AVStream *skip_to_stream;
217 } MatroskaDemuxContext;
219 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
221 static EbmlSyntax ebml_header[] = {
222 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
223 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
224 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
225 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
226 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
227 { EBML_ID_EBMLVERSION, EBML_NONE },
228 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
229 { EBML_ID_VOID, EBML_NONE },
233 static EbmlSyntax ebml_syntax[] = {
234 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
238 static EbmlSyntax matroska_info[] = {
239 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
240 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
241 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
242 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
243 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
244 { MATROSKA_ID_DATEUTC, EBML_NONE },
245 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
246 { EBML_ID_VOID, EBML_NONE },
250 static EbmlSyntax matroska_track_video[] = {
251 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
252 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
253 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
254 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
255 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
256 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
257 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
258 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
259 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
260 { EBML_ID_VOID, EBML_NONE },
264 static EbmlSyntax matroska_track_audio[] = {
265 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
266 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
267 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
268 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
269 { EBML_ID_VOID, EBML_NONE },
273 static EbmlSyntax matroska_track_encoding_compression[] = {
274 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
275 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
276 { EBML_ID_VOID, EBML_NONE },
280 static EbmlSyntax matroska_track_encoding[] = {
281 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
282 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
283 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
284 { EBML_ID_VOID, EBML_NONE },
288 static EbmlSyntax matroska_track_encodings[] = {
289 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
290 { EBML_ID_VOID, EBML_NONE },
294 static EbmlSyntax matroska_track[] = {
295 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
296 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
297 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
298 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
299 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
300 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
301 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
302 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
303 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
304 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
305 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
306 { MATROSKA_ID_TRACKUID, EBML_NONE },
307 { MATROSKA_ID_TRACKNAME, EBML_NONE },
308 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
309 { MATROSKA_ID_TRACKFLAGFORCED, EBML_NONE },
310 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
311 { MATROSKA_ID_CODECNAME, EBML_NONE },
312 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
313 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
314 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
315 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
316 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
317 { EBML_ID_VOID, EBML_NONE },
321 static EbmlSyntax matroska_tracks[] = {
322 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
323 { EBML_ID_VOID, EBML_NONE },
327 static EbmlSyntax matroska_attachment[] = {
328 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
329 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
330 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
331 { MATROSKA_ID_FILEUID, EBML_NONE },
332 { EBML_ID_VOID, EBML_NONE },
336 static EbmlSyntax matroska_attachments[] = {
337 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
338 { EBML_ID_VOID, EBML_NONE },
342 static EbmlSyntax matroska_chapter_display[] = {
343 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
344 { EBML_ID_VOID, EBML_NONE },
348 static EbmlSyntax matroska_chapter_entry[] = {
349 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
350 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
351 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
352 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
353 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
354 { EBML_ID_VOID, EBML_NONE },
358 static EbmlSyntax matroska_chapter[] = {
359 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
360 { MATROSKA_ID_EDITIONUID, EBML_NONE },
361 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
362 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
363 { EBML_ID_VOID, EBML_NONE },
367 static EbmlSyntax matroska_chapters[] = {
368 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
369 { EBML_ID_VOID, EBML_NONE },
373 static EbmlSyntax matroska_index_pos[] = {
374 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
375 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
376 { EBML_ID_VOID, EBML_NONE },
380 static EbmlSyntax matroska_index_entry[] = {
381 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
382 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
383 { EBML_ID_VOID, EBML_NONE },
387 static EbmlSyntax matroska_index[] = {
388 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
389 { EBML_ID_VOID, EBML_NONE },
393 static EbmlSyntax matroska_tags[] = {
394 { EBML_ID_VOID, EBML_NONE },
398 static EbmlSyntax matroska_seekhead_entry[] = {
399 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
400 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
401 { EBML_ID_VOID, EBML_NONE },
405 static EbmlSyntax matroska_seekhead[] = {
406 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
407 { EBML_ID_VOID, EBML_NONE },
411 static EbmlSyntax matroska_segment[] = {
412 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
413 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
414 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
415 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
416 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
417 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
418 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
419 { MATROSKA_ID_CLUSTER, EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
420 { EBML_ID_VOID, EBML_NONE },
424 static EbmlSyntax matroska_segments[] = {
425 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
430 * The first few functions handle EBML file parsing. The rest
431 * is the document interpretation. Matroska really just is a
436 * Return: the amount of levels in the hierarchy that the
437 * current element lies higher than the previous one.
438 * The opposite isn't done - that's auto-done using master
443 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
445 ByteIOContext *pb = matroska->ctx->pb;
446 offset_t pos = url_ftell(pb);
449 while (matroska->num_levels > 0) {
450 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
452 if (pos >= level->start + level->length) {
453 matroska->num_levels--;
464 * Read: an "EBML number", which is defined as a variable-length
465 * array of bytes. The first byte indicates the length by giving a
466 * number of 0-bits followed by a one. The position of the first
467 * "one" bit inside the first byte indicates the length of this
469 * Returns: num. of bytes read. < 0 on error.
473 ebml_read_num (MatroskaDemuxContext *matroska,
477 ByteIOContext *pb = matroska->ctx->pb;
478 int len_mask = 0x80, read = 1, n = 1;
481 /* the first byte tells us the length in bytes - get_byte() can normally
482 * return 0, but since that's not a valid first ebmlID byte, we can
483 * use it safely here to catch EOS. */
484 if (!(total = get_byte(pb))) {
485 /* we might encounter EOS here */
487 offset_t pos = url_ftell(pb);
488 av_log(matroska->ctx, AV_LOG_ERROR,
489 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
492 return AVERROR(EIO); /* EOS or actual I/O error */
495 /* get the length of the EBML number */
496 while (read <= max_size && !(total & len_mask)) {
500 if (read > max_size) {
501 offset_t pos = url_ftell(pb) - 1;
502 av_log(matroska->ctx, AV_LOG_ERROR,
503 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
504 (uint8_t) total, pos, pos);
505 return AVERROR_INVALIDDATA;
508 /* read out length */
511 total = (total << 8) | get_byte(pb);
519 * Read: the element content data ID.
520 * Return: the number of bytes read or < 0 on error.
524 ebml_read_element_id (MatroskaDemuxContext *matroska,
531 /* if we re-call this, use our cached ID */
532 if (matroska->peek_id != 0) {
535 *id = matroska->peek_id;
539 /* read out the "EBML number", include tag in ID */
540 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
542 *id = matroska->peek_id = total | (1 << (read * 7));
546 *level_up = ebml_read_element_level_up(matroska);
552 * Read: element content length.
553 * Return: the number of bytes read or < 0 on error.
557 ebml_read_element_length (MatroskaDemuxContext *matroska,
560 /* clear cache since we're now beyond that data point */
561 matroska->peek_id = 0;
563 /* read out the "EBML number", include tag in ID */
564 return ebml_read_num(matroska, 8, length);
568 * Return: the ID of the next element, or 0 on error.
569 * Level_up contains the amount of levels that this
570 * next element lies higher than the previous one.
574 ebml_peek_id (MatroskaDemuxContext *matroska,
579 if (ebml_read_element_id(matroska, &id, level_up) < 0)
586 * Seek to a given offset.
587 * 0 is success, -1 is failure.
591 ebml_read_seek (MatroskaDemuxContext *matroska,
594 ByteIOContext *pb = matroska->ctx->pb;
596 /* clear ID cache, if any */
597 matroska->peek_id = 0;
599 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
603 * Skip the next element.
604 * 0 is success, -1 is failure.
608 ebml_read_skip (MatroskaDemuxContext *matroska)
610 ByteIOContext *pb = matroska->ctx->pb;
615 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
616 (res = ebml_read_element_length(matroska, &length)) < 0)
619 url_fskip(pb, length);
625 * Read the next element as an unsigned int.
626 * 0 is success, < 0 is failure.
630 ebml_read_uint (MatroskaDemuxContext *matroska,
634 ByteIOContext *pb = matroska->ctx->pb;
635 int n = 0, size, res;
638 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
639 (res = ebml_read_element_length(matroska, &rlength)) < 0)
642 if (size < 1 || size > 8) {
643 offset_t pos = url_ftell(pb);
644 av_log(matroska->ctx, AV_LOG_ERROR,
645 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
647 return AVERROR_INVALIDDATA;
650 /* big-endian ordening; build up number */
653 *num = (*num << 8) | get_byte(pb);
659 * Read the next element as a signed int.
660 * 0 is success, < 0 is failure.
664 ebml_read_sint (MatroskaDemuxContext *matroska,
668 ByteIOContext *pb = matroska->ctx->pb;
669 int size, n = 1, negative = 0, res;
672 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
673 (res = ebml_read_element_length(matroska, &rlength)) < 0)
676 if (size < 1 || size > 8) {
677 offset_t pos = url_ftell(pb);
678 av_log(matroska->ctx, AV_LOG_ERROR,
679 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
681 return AVERROR_INVALIDDATA;
683 if ((*num = get_byte(pb)) & 0x80) {
688 *num = (*num << 8) | get_byte(pb);
692 *num = *num - (1LL << ((8 * size) - 1));
698 * Read the next element as a float.
699 * 0 is success, < 0 is failure.
703 ebml_read_float (MatroskaDemuxContext *matroska,
707 ByteIOContext *pb = matroska->ctx->pb;
711 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
712 (res = ebml_read_element_length(matroska, &rlength)) < 0)
717 *num= av_int2flt(get_be32(pb));
719 *num= av_int2dbl(get_be64(pb));
721 offset_t pos = url_ftell(pb);
722 av_log(matroska->ctx, AV_LOG_ERROR,
723 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
725 return AVERROR_INVALIDDATA;
732 * Read the next element as an ASCII string.
733 * 0 is success, < 0 is failure.
737 ebml_read_ascii (MatroskaDemuxContext *matroska,
741 ByteIOContext *pb = matroska->ctx->pb;
745 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
746 (res = ebml_read_element_length(matroska, &rlength)) < 0)
750 /* ebml strings are usually not 0-terminated, so we allocate one
751 * byte more, read the string and NULL-terminate it ourselves. */
752 if (size < 0 || !(*str = av_malloc(size + 1))) {
753 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
754 return AVERROR(ENOMEM);
756 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
757 offset_t pos = url_ftell(pb);
758 av_log(matroska->ctx, AV_LOG_ERROR,
759 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
769 * Read the next element as a UTF-8 string.
770 * 0 is success, < 0 is failure.
774 ebml_read_utf8 (MatroskaDemuxContext *matroska,
778 return ebml_read_ascii(matroska, id, str);
782 * Read the next element, but only the header. The contents
783 * are supposed to be sub-elements which can be read separately.
784 * 0 is success, < 0 is failure.
788 ebml_read_master (MatroskaDemuxContext *matroska,
791 ByteIOContext *pb = matroska->ctx->pb;
793 MatroskaLevel *level;
796 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
797 (res = ebml_read_element_length(matroska, &length)) < 0)
800 /* protect... (Heaven forbids that the '>' is true) */
801 if (matroska->num_levels >= EBML_MAX_DEPTH) {
802 av_log(matroska->ctx, AV_LOG_ERROR,
803 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
804 return AVERROR(ENOSYS);
808 level = &matroska->levels[matroska->num_levels++];
809 level->start = url_ftell(pb);
810 level->length = length;
816 * Read the next element as binary data.
817 * 0 is success, < 0 is failure.
821 ebml_read_binary (MatroskaDemuxContext *matroska,
826 ByteIOContext *pb = matroska->ctx->pb;
830 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
831 (res = ebml_read_element_length(matroska, &rlength)) < 0)
835 if (!(*binary = av_malloc(*size))) {
836 av_log(matroska->ctx, AV_LOG_ERROR,
837 "Memory allocation error\n");
838 return AVERROR(ENOMEM);
841 if (get_buffer(pb, *binary, *size) != *size) {
842 offset_t pos = url_ftell(pb);
843 av_log(matroska->ctx, AV_LOG_ERROR,
844 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
852 * Read signed/unsigned "EBML" numbers.
853 * Return: number of bytes processed, < 0 on error.
854 * XXX: use ebml_read_num().
858 matroska_ebmlnum_uint (uint8_t *data,
862 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
866 return AVERROR_INVALIDDATA;
869 while (read <= 8 && !(total & len_mask)) {
874 return AVERROR_INVALIDDATA;
876 if ((total &= (len_mask - 1)) == len_mask - 1)
879 return AVERROR_INVALIDDATA;
883 total = (total << 8) | data[n];
896 * Same as above, but signed.
900 matroska_ebmlnum_sint (uint8_t *data,
907 /* read as unsigned number first */
908 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
911 /* make signed (weird way) */
912 if (unum == (uint64_t)-1)
915 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
921 static MatroskaTrack *
922 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
925 MatroskaTrack *tracks = matroska->tracks.elem;
928 for (i=0; i < matroska->tracks.nb_elem; i++)
929 if (tracks[i].num == num)
932 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
938 * Put one packet in an application-supplied AVPacket struct.
939 * Returns 0 on success or -1 on failure.
943 matroska_deliver_packet (MatroskaDemuxContext *matroska,
946 if (matroska->num_packets > 0) {
947 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
948 av_free(matroska->packets[0]);
949 if (matroska->num_packets > 1) {
950 memmove(&matroska->packets[0], &matroska->packets[1],
951 (matroska->num_packets - 1) * sizeof(AVPacket *));
953 av_realloc(matroska->packets, (matroska->num_packets - 1) *
956 av_freep(&matroska->packets);
958 matroska->num_packets--;
966 * Put a packet into our internal queue. Will be delivered to the
967 * user/application during the next get_packet() call.
971 matroska_queue_packet (MatroskaDemuxContext *matroska,
975 av_realloc(matroska->packets, (matroska->num_packets + 1) *
977 matroska->packets[matroska->num_packets] = pkt;
978 matroska->num_packets++;
982 * Free all packets in our internal queue.
985 matroska_clear_queue (MatroskaDemuxContext *matroska)
987 if (matroska->packets) {
989 for (n = 0; n < matroska->num_packets; n++) {
990 av_free_packet(matroska->packets[n]);
991 av_free(matroska->packets[n]);
993 av_free(matroska->packets);
994 matroska->packets = NULL;
995 matroska->num_packets = 0;
1005 matroska_probe (AVProbeData *p)
1008 int len_mask = 0x80, size = 1, n = 1;
1009 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1012 if (AV_RB32(p->buf) != EBML_ID_HEADER)
1015 /* length of header */
1017 while (size <= 8 && !(total & len_mask)) {
1023 total &= (len_mask - 1);
1025 total = (total << 8) | p->buf[4 + n++];
1027 /* does the probe data contain the whole header? */
1028 if (p->buf_size < 4 + size + total)
1031 /* the header must contain the document type 'matroska'. For now,
1032 * we don't parse the whole header but simply check for the
1033 * availability of that array of characters inside the header.
1034 * Not fully fool-proof, but good enough. */
1035 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
1036 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1037 return AVPROBE_SCORE_MAX;
1043 * From here on, it's all XML-style DTD stuff... Needs no comments.
1046 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1047 void *data, uint32_t expected_id, int once);
1049 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1050 EbmlSyntax *syntax, void *data)
1052 uint32_t id = syntax->id;
1056 data = (char *)data + syntax->data_offset;
1057 if (syntax->list_elem_size) {
1058 EbmlList *list = data;
1059 list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1060 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1061 memset(data, 0, syntax->list_elem_size);
1066 switch (syntax->type) {
1067 case EBML_UINT: return ebml_read_uint (matroska, &id, data);
1068 case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1070 case EBML_UTF8: av_free(*(char **)data);
1071 return ebml_read_ascii(matroska, &id, data);
1072 case EBML_BIN: av_free(bin->data);
1073 bin->pos = url_ftell(matroska->ctx->pb);
1074 return ebml_read_binary(matroska, &id, &bin->data,
1076 case EBML_NEST: if ((res=ebml_read_master(matroska, &id)) < 0)
1078 if (id == MATROSKA_ID_SEGMENT)
1079 matroska->segment_start = url_ftell(matroska->ctx->pb);
1080 return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1081 case EBML_PASS: return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1082 case EBML_STOP: *(int *)data = 1; return 1;
1083 default: return ebml_read_skip(matroska);
1087 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1088 uint32_t id, void *data)
1091 for (i=0; syntax[i].id; i++)
1092 if (id == syntax[i].id)
1095 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1096 return ebml_parse_elem(matroska, &syntax[i], data);
1099 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1100 void *data, uint32_t expected_id, int once)
1105 for (i=0; syntax[i].id; i++)
1106 switch (syntax[i].type) {
1108 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1111 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1115 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1120 res = ebml_read_master(matroska, &id);
1121 if (id != expected_id)
1122 return AVERROR_INVALIDDATA;
1123 if (id == MATROSKA_ID_SEGMENT)
1124 matroska->segment_start = url_ftell(matroska->ctx->pb);
1128 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1131 } else if (matroska->level_up) {
1132 matroska->level_up--;
1136 res = ebml_parse_id(matroska, syntax, id, data);
1141 if (matroska->level_up) {
1142 matroska->level_up--;
1150 static void ebml_free(EbmlSyntax *syntax, void *data)
1153 for (i=0; syntax[i].id; i++) {
1154 void *data_off = (char *)data + syntax[i].data_offset;
1155 switch (syntax[i].type) {
1157 case EBML_UTF8: av_freep(data_off); break;
1158 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
1160 if (syntax[i].list_elem_size) {
1161 EbmlList *list = data_off;
1162 char *ptr = list->elem;
1163 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1164 ebml_free(syntax[i].def.n, ptr);
1165 av_free(list->elem);
1167 ebml_free(syntax[i].def.n, data_off);
1174 matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1176 MatroskaTrackEncoding *encodings = track->encodings.elem;
1177 uint8_t* data = *buf;
1178 int isize = *buf_size;
1179 uint8_t* pkt_data = NULL;
1180 int pkt_size = isize;
1184 switch (encodings[0].compression.algo) {
1185 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1186 return encodings[0].compression.settings.size;
1187 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1189 olen = pkt_size *= 3;
1190 pkt_data = av_realloc(pkt_data,
1191 pkt_size+LZO_OUTPUT_PADDING);
1192 result = lzo1x_decode(pkt_data, &olen, data, &isize);
1193 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1199 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1200 z_stream zstream = {0};
1201 if (inflateInit(&zstream) != Z_OK)
1203 zstream.next_in = data;
1204 zstream.avail_in = isize;
1207 pkt_data = av_realloc(pkt_data, pkt_size);
1208 zstream.avail_out = pkt_size - zstream.total_out;
1209 zstream.next_out = pkt_data + zstream.total_out;
1210 result = inflate(&zstream, Z_NO_FLUSH);
1211 } while (result==Z_OK && pkt_size<10000000);
1212 pkt_size = zstream.total_out;
1213 inflateEnd(&zstream);
1214 if (result != Z_STREAM_END)
1220 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1221 bz_stream bzstream = {0};
1222 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1224 bzstream.next_in = data;
1225 bzstream.avail_in = isize;
1228 pkt_data = av_realloc(pkt_data, pkt_size);
1229 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1230 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1231 result = BZ2_bzDecompress(&bzstream);
1232 } while (result==BZ_OK && pkt_size<10000000);
1233 pkt_size = bzstream.total_out_lo32;
1234 BZ2_bzDecompressEnd(&bzstream);
1235 if (result != BZ_STREAM_END)
1243 *buf_size = pkt_size;
1251 matroska_parse_index (MatroskaDemuxContext *matroska)
1253 return ebml_parse(matroska, matroska_index, matroska, MATROSKA_ID_CUES, 0);
1257 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1259 return ebml_parse(matroska, matroska_tags, matroska, MATROSKA_ID_TAGS, 0);
1263 matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1265 EbmlList *seekhead_list = &matroska->seekhead;
1266 MatroskaSeekhead *seekhead = seekhead_list->elem;
1267 uint32_t peek_id_cache = matroska->peek_id;
1268 uint32_t level_up = matroska->level_up;
1269 offset_t before_pos = url_ftell(matroska->ctx->pb);
1270 MatroskaLevel level;
1274 for (i=0; i<seekhead_list->nb_elem; i++) {
1275 if (seekhead[i].pos <= before_pos
1276 || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1277 || seekhead[i].id == MATROSKA_ID_CLUSTER)
1281 if (ebml_read_seek(matroska,
1282 seekhead[i].pos+matroska->segment_start) < 0)
1285 /* we don't want to lose our seekhead level, so we add
1286 * a dummy. This is a crude hack. */
1287 if (matroska->num_levels == EBML_MAX_DEPTH) {
1288 av_log(matroska->ctx, AV_LOG_INFO,
1289 "Max EBML element depth (%d) reached, "
1290 "cannot parse further.\n", EBML_MAX_DEPTH);
1295 level.length = (uint64_t)-1;
1296 matroska->levels[matroska->num_levels] = level;
1297 matroska->num_levels++;
1300 if (!(id = ebml_peek_id (matroska,
1301 &matroska->level_up)))
1303 if (id != seekhead[i].id) {
1304 av_log(matroska->ctx, AV_LOG_INFO,
1305 "We looked for ID=0x%x but got "
1306 "ID=0x%x (pos=%"PRIu64")",
1307 (int)seekhead[i].id, id, seekhead[i].pos +
1308 matroska->segment_start);
1312 /* read master + parse */
1314 case MATROSKA_ID_CUES:
1315 if (!(res = matroska_parse_index(matroska)) ||
1316 url_feof(matroska->ctx->pb)) {
1317 matroska->index_parsed = 1;
1321 case MATROSKA_ID_TAGS:
1322 if (!(res = matroska_parse_metadata(matroska)) ||
1323 url_feof(matroska->ctx->pb)) {
1324 matroska->metadata_parsed = 1;
1331 /* remove dummy level */
1332 while (matroska->num_levels) {
1333 uint64_t length = matroska->levels[--matroska->num_levels].length;
1334 if (length == (uint64_t)-1)
1340 ebml_read_seek(matroska, before_pos);
1341 matroska->peek_id = peek_id_cache;
1342 matroska->level_up = level_up;
1346 matroska_aac_profile (char *codec_id)
1348 static const char *aac_profiles[] = {
1353 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1354 if (strstr(codec_id, aac_profiles[profile]))
1360 matroska_aac_sri (int samplerate)
1364 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1365 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1371 matroska_read_header (AVFormatContext *s,
1372 AVFormatParameters *ap)
1374 MatroskaDemuxContext *matroska = s->priv_data;
1375 EbmlList *attachements_list = &matroska->attachments;
1376 MatroskaAttachement *attachements;
1377 EbmlList *chapters_list = &matroska->chapters;
1378 MatroskaChapter *chapters;
1379 MatroskaTrack *tracks;
1380 EbmlList *index_list;
1381 MatroskaIndex *index;
1388 /* First read the EBML header. */
1389 if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1390 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1391 || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1392 || ebml.doctype_version > 2) {
1393 av_log(matroska->ctx, AV_LOG_ERROR,
1394 "EBML header using unsupported features\n"
1395 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1396 ebml.version, ebml.doctype, ebml.doctype_version);
1397 return AVERROR_NOFMT;
1399 ebml_free(ebml_syntax, &ebml);
1401 /* The next thing is a segment. */
1402 if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1404 matroska_execute_seekhead(matroska);
1406 /* Have we found a cluster? */
1407 if (ebml_peek_id(matroska, NULL) != MATROSKA_ID_CLUSTER)
1410 if (matroska->duration)
1411 matroska->ctx->duration = matroska->duration * matroska->time_scale
1412 * 1000 / AV_TIME_BASE;
1413 if (matroska->title)
1414 strncpy(matroska->ctx->title, matroska->title,
1415 sizeof(matroska->ctx->title)-1);
1417 tracks = matroska->tracks.elem;
1418 for (i=0; i < matroska->tracks.nb_elem; i++) {
1419 MatroskaTrack *track = &tracks[i];
1420 enum CodecID codec_id = CODEC_ID_NONE;
1421 EbmlList *encodings_list = &tracks->encodings;
1422 MatroskaTrackEncoding *encodings = encodings_list->elem;
1423 uint8_t *extradata = NULL;
1424 int extradata_size = 0;
1425 int extradata_offset = 0;
1427 /* Apply some sanity checks. */
1428 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1429 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1430 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1431 av_log(matroska->ctx, AV_LOG_INFO,
1432 "Unknown or unsupported track type %"PRIu64"\n",
1436 if (track->codec_id == NULL)
1439 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1440 if (!track->default_duration)
1441 track->default_duration = 1000000000/track->video.frame_rate;
1442 if (!track->video.display_width)
1443 track->video.display_width = track->video.pixel_width;
1444 if (!track->video.display_height)
1445 track->video.display_height = track->video.pixel_height;
1446 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1447 if (!track->audio.out_samplerate)
1448 track->audio.out_samplerate = track->audio.samplerate;
1450 if (encodings_list->nb_elem > 1) {
1451 av_log(matroska->ctx, AV_LOG_ERROR,
1452 "Multiple combined encodings no supported");
1453 } else if (encodings_list->nb_elem == 1) {
1454 if (encodings[0].type ||
1455 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1457 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1460 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1462 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1463 encodings[0].scope = 0;
1464 av_log(matroska->ctx, AV_LOG_ERROR,
1465 "Unsupported encoding type");
1466 } else if (track->codec_priv.size && encodings[0].scope&2) {
1467 uint8_t *codec_priv = track->codec_priv.data;
1468 int offset = matroska_decode_buffer(&track->codec_priv.data,
1469 &track->codec_priv.size,
1472 track->codec_priv.data = NULL;
1473 track->codec_priv.size = 0;
1474 av_log(matroska->ctx, AV_LOG_ERROR,
1475 "Failed to decode codec private data\n");
1476 } else if (offset > 0) {
1477 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1478 memcpy(track->codec_priv.data,
1479 encodings[0].compression.settings.data, offset);
1480 memcpy(track->codec_priv.data+offset, codec_priv,
1481 track->codec_priv.size);
1482 track->codec_priv.size += offset;
1484 if (codec_priv != track->codec_priv.data)
1485 av_free(codec_priv);
1489 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1490 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1491 strlen(ff_mkv_codec_tags[j].str))){
1492 codec_id= ff_mkv_codec_tags[j].id;
1497 st = track->stream = av_new_stream(s, matroska->num_streams++);
1499 return AVERROR(ENOMEM);
1501 /* Set the FourCC from the CodecID. */
1502 /* This is the MS compatibility mode which stores a
1503 * BITMAPINFOHEADER in the CodecPrivate. */
1504 if (!strcmp(track->codec_id,
1505 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
1506 (track->codec_priv.size >= 40) &&
1507 (track->codec_priv.data != NULL)) {
1508 /* Offset of biCompression. Stored in LE. */
1509 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1510 codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1514 /* This is the MS compatibility mode which stores a
1515 * WAVEFORMATEX in the CodecPrivate. */
1516 else if (!strcmp(track->codec_id,
1517 MATROSKA_CODEC_ID_AUDIO_ACM) &&
1518 (track->codec_priv.size >= 18) &&
1519 (track->codec_priv.data != NULL)) {
1520 /* Offset of wFormatTag. Stored in LE. */
1521 uint16_t tag = AV_RL16(track->codec_priv.data);
1522 codec_id = codec_get_id(codec_wav_tags, tag);
1526 else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1527 (track->codec_priv.size >= 86) &&
1528 (track->codec_priv.data != NULL)) {
1529 track->video.fourcc = AV_RL32(track->codec_priv.data);
1530 codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1533 else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1534 int profile = matroska_aac_profile(track->codec_id);
1535 int sri = matroska_aac_sri(track->audio.samplerate);
1536 extradata = av_malloc(5);
1537 if (extradata == NULL)
1538 return AVERROR(ENOMEM);
1539 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1540 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1541 if (strstr(track->codec_id, "SBR")) {
1542 sri = matroska_aac_sri(track->audio.out_samplerate);
1543 extradata[2] = 0x56;
1544 extradata[3] = 0xE5;
1545 extradata[4] = 0x80 | (sri<<3);
1552 else if (codec_id == CODEC_ID_TTA) {
1554 extradata_size = 30;
1555 extradata = av_mallocz(extradata_size);
1556 if (extradata == NULL)
1557 return AVERROR(ENOMEM);
1558 init_put_byte(&b, extradata, extradata_size, 1,
1559 NULL, NULL, NULL, NULL);
1560 put_buffer(&b, "TTA1", 4);
1562 put_le16(&b, track->audio.channels);
1563 put_le16(&b, track->audio.bitdepth);
1564 put_le32(&b, track->audio.out_samplerate);
1565 put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1568 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1569 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1570 extradata_offset = 26;
1571 track->codec_priv.size -= extradata_offset;
1574 else if (codec_id == CODEC_ID_RA_144) {
1575 track->audio.out_samplerate = 8000;
1576 track->audio.channels = 1;
1579 else if (codec_id == CODEC_ID_RA_288 ||
1580 codec_id == CODEC_ID_COOK ||
1581 codec_id == CODEC_ID_ATRAC3) {
1584 init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1585 0, NULL, NULL, NULL, NULL);
1587 track->audio.coded_framesize = get_be32(&b);
1589 track->audio.sub_packet_h = get_be16(&b);
1590 track->audio.frame_size = get_be16(&b);
1591 track->audio.sub_packet_size = get_be16(&b);
1592 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1593 if (codec_id == CODEC_ID_RA_288) {
1594 st->codec->block_align = track->audio.coded_framesize;
1595 track->codec_priv.size = 0;
1597 st->codec->block_align = track->audio.sub_packet_size;
1598 extradata_offset = 78;
1599 track->codec_priv.size -= extradata_offset;
1603 if (codec_id == CODEC_ID_NONE) {
1604 av_log(matroska->ctx, AV_LOG_INFO,
1605 "Unknown/unsupported CodecID %s.\n",
1609 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1611 st->codec->codec_id = codec_id;
1613 if (strcmp(track->language, "und"))
1614 av_strlcpy(st->language, track->language, 4);
1616 if (track->flag_default)
1617 st->disposition |= AV_DISPOSITION_DEFAULT;
1619 if (track->default_duration)
1620 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1621 track->default_duration, 1000000000, 30000);
1624 st->codec->extradata = extradata;
1625 st->codec->extradata_size = extradata_size;
1626 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1627 st->codec->extradata = av_malloc(track->codec_priv.size);
1628 if(st->codec->extradata == NULL)
1629 return AVERROR(ENOMEM);
1630 st->codec->extradata_size = track->codec_priv.size;
1631 memcpy(st->codec->extradata,
1632 track->codec_priv.data + extradata_offset,
1633 track->codec_priv.size);
1636 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1637 st->codec->codec_type = CODEC_TYPE_VIDEO;
1638 st->codec->codec_tag = track->video.fourcc;
1639 st->codec->width = track->video.pixel_width;
1640 st->codec->height = track->video.pixel_height;
1641 av_reduce(&st->codec->sample_aspect_ratio.num,
1642 &st->codec->sample_aspect_ratio.den,
1643 st->codec->height * track->video.display_width,
1644 st->codec-> width * track->video.display_height,
1646 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1647 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1648 st->codec->codec_type = CODEC_TYPE_AUDIO;
1649 st->codec->sample_rate = track->audio.out_samplerate;
1650 st->codec->channels = track->audio.channels;
1651 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1652 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1655 /* What do we do with private data? E.g. for Vorbis. */
1658 attachements = attachements_list->elem;
1659 for (j=0; j<attachements_list->nb_elem; j++) {
1660 if (!(attachements[j].filename && attachements[j].mime &&
1661 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1662 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1664 AVStream *st = av_new_stream(s, matroska->num_streams++);
1667 st->filename = av_strdup(attachements[j].filename);
1668 st->codec->codec_id = CODEC_ID_NONE;
1669 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1670 st->codec->extradata = av_malloc(attachements[j].bin.size);
1671 if(st->codec->extradata == NULL)
1673 st->codec->extradata_size = attachements[j].bin.size;
1674 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1676 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1677 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1678 strlen(ff_mkv_mime_tags[i].str))) {
1679 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1686 chapters = chapters_list->elem;
1687 for (i=0; i<chapters_list->nb_elem; i++)
1688 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1689 ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1690 chapters[i].start, chapters[i].end,
1693 index_list = &matroska->index;
1694 index = index_list->elem;
1695 for (i=0; i<index_list->nb_elem; i++) {
1696 EbmlList *pos_list = &index[i].pos;
1697 MatroskaIndexPos *pos = pos_list->elem;
1698 for (j=0; j<pos_list->nb_elem; j++) {
1699 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1701 if (track && track->stream)
1702 av_add_index_entry(track->stream,
1703 pos[j].pos + matroska->segment_start,
1704 index[i].time*matroska->time_scale/AV_TIME_BASE,
1705 0, 0, AVINDEX_KEYFRAME);
1713 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1714 int64_t pos, uint64_t cluster_time, uint64_t duration,
1717 MatroskaTrack *track;
1721 uint8_t *origdata = data;
1723 uint32_t *lace_size = NULL;
1724 int n, flags, laces = 0;
1727 /* first byte(s): tracknum */
1728 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1729 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1736 /* fetch track from num */
1737 track = matroska_find_track_by_num(matroska, num);
1738 if (size <= 3 || !track || !track->stream) {
1739 av_log(matroska->ctx, AV_LOG_INFO,
1740 "Invalid stream %"PRIu64" or size %u\n", num, size);
1745 if (st->discard >= AVDISCARD_ALL) {
1749 if (duration == AV_NOPTS_VALUE)
1750 duration = track->default_duration / matroska->time_scale;
1752 /* block_time (relative to cluster time) */
1753 block_time = AV_RB16(data);
1757 if (is_keyframe == -1)
1758 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1760 if (matroska->skip_to_keyframe) {
1761 if (!is_keyframe || st != matroska->skip_to_stream) {
1765 matroska->skip_to_keyframe = 0;
1768 switch ((flags & 0x06) >> 1) {
1769 case 0x0: /* no lacing */
1771 lace_size = av_mallocz(sizeof(int));
1772 lace_size[0] = size;
1775 case 0x1: /* xiph lacing */
1776 case 0x2: /* fixed-size lacing */
1777 case 0x3: /* EBML lacing */
1778 assert(size>0); // size <=3 is checked before size-=3 above
1779 laces = (*data) + 1;
1782 lace_size = av_mallocz(laces * sizeof(int));
1784 switch ((flags & 0x06) >> 1) {
1785 case 0x1: /* xiph lacing */ {
1788 for (n = 0; res == 0 && n < laces - 1; n++) {
1795 lace_size[n] += temp;
1801 total += lace_size[n];
1803 lace_size[n] = size - total;
1807 case 0x2: /* fixed-size lacing */
1808 for (n = 0; n < laces; n++)
1809 lace_size[n] = size / laces;
1812 case 0x3: /* EBML lacing */ {
1814 n = matroska_ebmlnum_uint(data, size, &num);
1816 av_log(matroska->ctx, AV_LOG_INFO,
1817 "EBML block data error\n");
1822 total = lace_size[0] = num;
1823 for (n = 1; res == 0 && n < laces - 1; n++) {
1826 r = matroska_ebmlnum_sint (data, size, &snum);
1828 av_log(matroska->ctx, AV_LOG_INFO,
1829 "EBML block data error\n");
1834 lace_size[n] = lace_size[n - 1] + snum;
1835 total += lace_size[n];
1837 lace_size[n] = size - total;
1845 uint64_t timecode = AV_NOPTS_VALUE;
1847 if (cluster_time != (uint64_t)-1
1848 && (block_time >= 0 || cluster_time >= -block_time))
1849 timecode = cluster_time + block_time;
1851 for (n = 0; n < laces; n++) {
1852 if (st->codec->codec_id == CODEC_ID_RA_288 ||
1853 st->codec->codec_id == CODEC_ID_COOK ||
1854 st->codec->codec_id == CODEC_ID_ATRAC3) {
1855 int a = st->codec->block_align;
1856 int sps = track->audio.sub_packet_size;
1857 int cfs = track->audio.coded_framesize;
1858 int h = track->audio.sub_packet_h;
1859 int y = track->audio.sub_packet_cnt;
1860 int w = track->audio.frame_size;
1863 if (!track->audio.pkt_cnt) {
1864 if (st->codec->codec_id == CODEC_ID_RA_288)
1865 for (x=0; x<h/2; x++)
1866 memcpy(track->audio.buf+x*2*w+y*cfs,
1869 for (x=0; x<w/sps; x++)
1870 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1872 if (++track->audio.sub_packet_cnt >= h) {
1873 track->audio.sub_packet_cnt = 0;
1874 track->audio.pkt_cnt = h*w / a;
1877 while (track->audio.pkt_cnt) {
1878 pkt = av_mallocz(sizeof(AVPacket));
1879 av_new_packet(pkt, a);
1880 memcpy(pkt->data, track->audio.buf
1881 + a * (h*w / a - track->audio.pkt_cnt--), a);
1883 pkt->stream_index = st->index;
1884 matroska_queue_packet(matroska, pkt);
1887 MatroskaTrackEncoding *encodings = track->encodings.elem;
1888 int offset = 0, pkt_size = lace_size[n];
1889 uint8_t *pkt_data = data;
1891 if (encodings && encodings->scope & 1) {
1892 offset = matroska_decode_buffer(&pkt_data, &pkt_size,
1898 pkt = av_mallocz(sizeof(AVPacket));
1899 /* XXX: prevent data copy... */
1900 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1902 res = AVERROR(ENOMEM);
1907 memcpy (pkt->data, encodings->compression.settings.data, offset);
1908 memcpy (pkt->data+offset, pkt_data, pkt_size);
1910 if (pkt_data != data)
1914 pkt->flags = is_keyframe;
1915 pkt->stream_index = st->index;
1917 pkt->pts = timecode;
1919 pkt->duration = duration;
1921 matroska_queue_packet(matroska, pkt);
1924 if (timecode != AV_NOPTS_VALUE)
1925 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1926 data += lace_size[n];
1936 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
1937 uint64_t cluster_time)
1941 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
1942 uint64_t duration = AV_NOPTS_VALUE;
1947 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
1950 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1953 } else if (matroska->level_up) {
1954 matroska->level_up--;
1959 /* one block inside the group. Note, block parsing is one
1960 * of the harder things, so this code is a bit complicated.
1961 * See http://www.matroska.org/ for documentation. */
1962 case MATROSKA_ID_BLOCK: {
1963 pos = url_ftell(matroska->ctx->pb);
1964 res = ebml_read_binary(matroska, &id, &data, &size);
1968 case MATROSKA_ID_BLOCKDURATION: {
1969 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
1974 case MATROSKA_ID_BLOCKREFERENCE: {
1976 /* We've found a reference, so not even the first frame in
1977 * the lace is a key frame. */
1979 if (last_num_packets != matroska->num_packets)
1980 matroska->packets[last_num_packets]->flags = 0;
1981 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
1987 av_log(matroska->ctx, AV_LOG_INFO,
1988 "Unknown entry 0x%x in blockgroup data\n", id);
1992 res = ebml_read_skip(matroska);
1996 if (matroska->level_up) {
1997 matroska->level_up--;
2006 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2007 duration, is_keyframe);
2013 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2017 uint64_t cluster_time = 0;
2022 av_log(matroska->ctx, AV_LOG_DEBUG,
2023 "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2026 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2029 } else if (matroska->level_up) {
2030 matroska->level_up--;
2035 /* cluster timecode */
2036 case MATROSKA_ID_CLUSTERTIMECODE: {
2038 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2044 /* a group of blocks inside a cluster */
2045 case MATROSKA_ID_BLOCKGROUP:
2046 if ((res = ebml_read_master(matroska, &id)) < 0)
2048 res = matroska_parse_blockgroup(matroska, cluster_time);
2051 case MATROSKA_ID_SIMPLEBLOCK:
2052 pos = url_ftell(matroska->ctx->pb);
2053 res = ebml_read_binary(matroska, &id, &data, &size);
2055 res = matroska_parse_block(matroska, data, size, pos,
2056 cluster_time, AV_NOPTS_VALUE,
2061 av_log(matroska->ctx, AV_LOG_INFO,
2062 "Unknown entry 0x%x in cluster data\n", id);
2066 res = ebml_read_skip(matroska);
2070 if (matroska->level_up) {
2071 matroska->level_up--;
2080 matroska_read_packet (AVFormatContext *s,
2083 MatroskaDemuxContext *matroska = s->priv_data;
2087 /* Read stream until we have a packet queued. */
2088 while (matroska_deliver_packet(matroska, pkt)) {
2090 /* Have we already reached the end? */
2092 return AVERROR(EIO);
2096 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2097 return AVERROR(EIO);
2098 } else if (matroska->level_up) {
2099 matroska->level_up--;
2104 case MATROSKA_ID_CLUSTER:
2105 if ((res = ebml_read_master(matroska, &id)) < 0)
2107 if ((res = matroska_parse_cluster(matroska)) == 0)
2108 res = 1; /* Parsed one cluster, let's get out. */
2113 res = ebml_read_skip(matroska);
2117 if (matroska->level_up) {
2118 matroska->level_up--;
2131 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2134 MatroskaDemuxContext *matroska = s->priv_data;
2135 AVStream *st = s->streams[stream_index];
2138 /* find index entry */
2139 index = av_index_search_timestamp(st, timestamp, flags);
2143 matroska_clear_queue(matroska);
2146 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2147 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2148 matroska->skip_to_stream = st;
2149 matroska->peek_id = 0;
2150 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2155 matroska_read_close (AVFormatContext *s)
2157 MatroskaDemuxContext *matroska = s->priv_data;
2158 MatroskaTrack *tracks = matroska->tracks.elem;
2161 matroska_clear_queue(matroska);
2163 for (n=0; n < matroska->tracks.nb_elem; n++)
2164 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2165 av_free(tracks[n].audio.buf);
2166 ebml_free(matroska_segment, matroska);
2171 AVInputFormat matroska_demuxer = {
2173 NULL_IF_CONFIG_SMALL("Matroska file format"),
2174 sizeof(MatroskaDemuxContext),
2176 matroska_read_header,
2177 matroska_read_packet,
2178 matroska_read_close,