2 * Matroska file demuxer
3 * Copyright (c) 2003-2008 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 * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28 * Specs available on the Matroska project page: http://www.matroska.org/.
34 #include "avio_internal.h"
35 /* For ff_codec_get_id(). */
40 #include "libavcodec/mpeg4audio.h"
41 #include "libavutil/intfloat_readwrite.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/avstring.h"
44 #include "libavutil/lzo.h"
65 typedef const struct EbmlSyntax {
74 const struct EbmlSyntax *n;
94 uint64_t doctype_version;
100 } MatroskaTrackCompression;
105 MatroskaTrackCompression compression;
106 } MatroskaTrackEncoding;
110 uint64_t display_width;
111 uint64_t display_height;
112 uint64_t pixel_width;
113 uint64_t pixel_height;
115 } MatroskaTrackVideo;
119 double out_samplerate;
123 /* real audio header (extracted from extradata) */
130 uint64_t buf_timecode;
132 } MatroskaTrackAudio;
143 uint64_t default_duration;
144 uint64_t flag_default;
145 uint64_t flag_forced;
146 MatroskaTrackVideo video;
147 MatroskaTrackAudio audio;
151 int64_t end_timecode;
162 } MatroskaAttachement;
200 MatroskaTagTarget target;
215 AVFormatContext *ctx;
219 MatroskaLevel levels[EBML_MAX_DEPTH];
227 EbmlList attachments;
233 /* byte position of the segment inside the stream */
234 int64_t segment_start;
236 /* the packet queue */
243 /* What to skip before effectively reading a packet. */
244 int skip_to_keyframe;
245 uint64_t skip_to_timecode;
246 } MatroskaDemuxContext;
260 static EbmlSyntax ebml_header[] = {
261 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
262 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
263 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
264 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
265 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
266 { EBML_ID_EBMLVERSION, EBML_NONE },
267 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
271 static EbmlSyntax ebml_syntax[] = {
272 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
276 static EbmlSyntax matroska_info[] = {
277 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
278 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
279 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
280 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
281 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
282 { MATROSKA_ID_DATEUTC, EBML_NONE },
283 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
287 static EbmlSyntax matroska_track_video[] = {
288 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
289 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
290 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
291 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
292 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
293 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
294 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
295 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
296 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
297 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
298 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
299 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
300 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
301 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
305 static EbmlSyntax matroska_track_audio[] = {
306 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
307 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
308 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
309 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
313 static EbmlSyntax matroska_track_encoding_compression[] = {
314 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
315 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
319 static EbmlSyntax matroska_track_encoding[] = {
320 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
321 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
322 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
323 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
327 static EbmlSyntax matroska_track_encodings[] = {
328 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
332 static EbmlSyntax matroska_track[] = {
333 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
334 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
335 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
336 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
337 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
338 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
339 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
340 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
341 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
342 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
343 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
344 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
345 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
346 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
347 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
348 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
349 { MATROSKA_ID_CODECNAME, EBML_NONE },
350 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
351 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
352 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
353 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
354 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
355 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
359 static EbmlSyntax matroska_tracks[] = {
360 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
364 static EbmlSyntax matroska_attachment[] = {
365 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
366 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
367 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
368 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
369 { MATROSKA_ID_FILEDESC, EBML_NONE },
373 static EbmlSyntax matroska_attachments[] = {
374 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
378 static EbmlSyntax matroska_chapter_display[] = {
379 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
380 { MATROSKA_ID_CHAPLANG, EBML_NONE },
384 static EbmlSyntax matroska_chapter_entry[] = {
385 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
386 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
387 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
388 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
389 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
390 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
391 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
392 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
396 static EbmlSyntax matroska_chapter[] = {
397 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
398 { MATROSKA_ID_EDITIONUID, EBML_NONE },
399 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
400 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
401 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
405 static EbmlSyntax matroska_chapters[] = {
406 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
410 static EbmlSyntax matroska_index_pos[] = {
411 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
412 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
413 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
417 static EbmlSyntax matroska_index_entry[] = {
418 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
419 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
423 static EbmlSyntax matroska_index[] = {
424 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
428 static EbmlSyntax matroska_simpletag[] = {
429 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
430 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
431 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
432 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
433 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
434 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
438 static EbmlSyntax matroska_tagtargets[] = {
439 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
440 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
441 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
442 { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
443 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
447 static EbmlSyntax matroska_tag[] = {
448 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
449 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
453 static EbmlSyntax matroska_tags[] = {
454 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
458 static EbmlSyntax matroska_seekhead_entry[] = {
459 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
460 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
464 static EbmlSyntax matroska_seekhead[] = {
465 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
469 static EbmlSyntax matroska_segment[] = {
470 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
471 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
472 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
473 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
474 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
475 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
476 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
477 { MATROSKA_ID_CLUSTER, EBML_STOP },
481 static EbmlSyntax matroska_segments[] = {
482 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
486 static EbmlSyntax matroska_blockgroup[] = {
487 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
488 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
489 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
490 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
491 { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
495 static EbmlSyntax matroska_cluster[] = {
496 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
497 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
498 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
499 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
500 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
504 static EbmlSyntax matroska_clusters[] = {
505 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
506 { MATROSKA_ID_INFO, EBML_NONE },
507 { MATROSKA_ID_CUES, EBML_NONE },
508 { MATROSKA_ID_TAGS, EBML_NONE },
509 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
513 static const char *matroska_doctypes[] = { "matroska", "webm" };
516 * Return: Whether we reached the end of a level in the hierarchy or not.
518 static int ebml_level_end(MatroskaDemuxContext *matroska)
520 AVIOContext *pb = matroska->ctx->pb;
521 int64_t pos = avio_tell(pb);
523 if (matroska->num_levels > 0) {
524 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
525 if (pos - level->start >= level->length || matroska->current_id) {
526 matroska->num_levels--;
534 * Read: an "EBML number", which is defined as a variable-length
535 * array of bytes. The first byte indicates the length by giving a
536 * number of 0-bits followed by a one. The position of the first
537 * "one" bit inside the first byte indicates the length of this
539 * Returns: number of bytes read, < 0 on error
541 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
542 int max_size, uint64_t *number)
547 /* The first byte tells us the length in bytes - avio_r8() can normally
548 * return 0, but since that's not a valid first ebmlID byte, we can
549 * use it safely here to catch EOS. */
550 if (!(total = avio_r8(pb))) {
551 /* we might encounter EOS here */
553 int64_t pos = avio_tell(pb);
554 av_log(matroska->ctx, AV_LOG_ERROR,
555 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
558 return AVERROR(EIO); /* EOS or actual I/O error */
561 /* get the length of the EBML number */
562 read = 8 - ff_log2_tab[total];
563 if (read > max_size) {
564 int64_t pos = avio_tell(pb) - 1;
565 av_log(matroska->ctx, AV_LOG_ERROR,
566 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
567 (uint8_t) total, pos, pos);
568 return AVERROR_INVALIDDATA;
571 /* read out length */
572 total ^= 1 << ff_log2_tab[total];
574 total = (total << 8) | avio_r8(pb);
582 * Read a EBML length value.
583 * This needs special handling for the "unknown length" case which has multiple
586 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
589 int res = ebml_read_num(matroska, pb, 8, number);
590 if (res > 0 && *number + 1 == 1ULL << (7 * res))
591 *number = 0xffffffffffffffULL;
596 * Read the next element as an unsigned int.
597 * 0 is success, < 0 is failure.
599 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
604 return AVERROR_INVALIDDATA;
606 /* big-endian ordering; build up number */
609 *num = (*num << 8) | avio_r8(pb);
615 * Read the next element as a float.
616 * 0 is success, < 0 is failure.
618 static int ebml_read_float(AVIOContext *pb, int size, double *num)
622 } else if (size == 4) {
623 *num= av_int2flt(avio_rb32(pb));
625 *num= av_int2dbl(avio_rb64(pb));
627 return AVERROR_INVALIDDATA;
633 * Read the next element as an ASCII string.
634 * 0 is success, < 0 is failure.
636 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
639 /* EBML strings are usually not 0-terminated, so we allocate one
640 * byte more, read the string and NULL-terminate it ourselves. */
641 if (!(*str = av_malloc(size + 1)))
642 return AVERROR(ENOMEM);
643 if (avio_read(pb, (uint8_t *) *str, size) != size) {
653 * Read the next element as binary data.
654 * 0 is success, < 0 is failure.
656 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
659 if (!(bin->data = av_malloc(length)))
660 return AVERROR(ENOMEM);
663 bin->pos = avio_tell(pb);
664 if (avio_read(pb, bin->data, length) != length) {
665 av_freep(&bin->data);
673 * Read the next element, but only the header. The contents
674 * are supposed to be sub-elements which can be read separately.
675 * 0 is success, < 0 is failure.
677 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
679 AVIOContext *pb = matroska->ctx->pb;
680 MatroskaLevel *level;
682 if (matroska->num_levels >= EBML_MAX_DEPTH) {
683 av_log(matroska->ctx, AV_LOG_ERROR,
684 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
685 return AVERROR(ENOSYS);
688 level = &matroska->levels[matroska->num_levels++];
689 level->start = avio_tell(pb);
690 level->length = length;
696 * Read signed/unsigned "EBML" numbers.
697 * Return: number of bytes processed, < 0 on error
699 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
700 uint8_t *data, uint32_t size, uint64_t *num)
703 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
704 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
708 * Same as above, but signed.
710 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
711 uint8_t *data, uint32_t size, int64_t *num)
716 /* read as unsigned number first */
717 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
720 /* make signed (weird way) */
721 *num = unum - ((1LL << (7*res - 1)) - 1);
726 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
727 EbmlSyntax *syntax, void *data);
729 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
730 uint32_t id, void *data)
733 for (i=0; syntax[i].id; i++)
734 if (id == syntax[i].id)
736 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
737 matroska->num_levels > 0 &&
738 matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
739 return 0; // we reached the end of an unknown size cluster
740 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
741 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
742 return ebml_parse_elem(matroska, &syntax[i], data);
745 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
748 if (!matroska->current_id) {
750 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
753 matroska->current_id = id | 1 << 7*res;
755 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
758 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
763 for (i=0; syntax[i].id; i++)
764 switch (syntax[i].type) {
766 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
769 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
773 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
777 while (!res && !ebml_level_end(matroska))
778 res = ebml_parse(matroska, syntax, data);
783 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
784 EbmlSyntax *syntax, void *data)
786 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
789 // max. 16 MB for strings
790 [EBML_STR] = 0x1000000,
791 [EBML_UTF8] = 0x1000000,
792 // max. 256 MB for binary data
793 [EBML_BIN] = 0x10000000,
794 // no limits for anything else
796 AVIOContext *pb = matroska->ctx->pb;
797 uint32_t id = syntax->id;
801 data = (char *)data + syntax->data_offset;
802 if (syntax->list_elem_size) {
803 EbmlList *list = data;
804 list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
805 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
806 memset(data, 0, syntax->list_elem_size);
810 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
811 matroska->current_id = 0;
812 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
814 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
815 av_log(matroska->ctx, AV_LOG_ERROR,
816 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
817 length, max_lengths[syntax->type], syntax->type);
818 return AVERROR_INVALIDDATA;
822 switch (syntax->type) {
823 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
824 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
826 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
827 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
828 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
830 if (id == MATROSKA_ID_SEGMENT)
831 matroska->segment_start = avio_tell(matroska->ctx->pb);
832 return ebml_parse_nest(matroska, syntax->def.n, data);
833 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
834 case EBML_STOP: return 1;
835 default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
837 if (res == AVERROR_INVALIDDATA)
838 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
839 else if (res == AVERROR(EIO))
840 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
844 static void ebml_free(EbmlSyntax *syntax, void *data)
847 for (i=0; syntax[i].id; i++) {
848 void *data_off = (char *)data + syntax[i].data_offset;
849 switch (syntax[i].type) {
851 case EBML_UTF8: av_freep(data_off); break;
852 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
854 if (syntax[i].list_elem_size) {
855 EbmlList *list = data_off;
856 char *ptr = list->elem;
857 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
858 ebml_free(syntax[i].def.n, ptr);
861 ebml_free(syntax[i].def.n, data_off);
871 static int matroska_probe(AVProbeData *p)
874 int len_mask = 0x80, size = 1, n = 1, i;
877 if (AV_RB32(p->buf) != EBML_ID_HEADER)
880 /* length of header */
882 while (size <= 8 && !(total & len_mask)) {
888 total &= (len_mask - 1);
890 total = (total << 8) | p->buf[4 + n++];
892 /* Does the probe data contain the whole header? */
893 if (p->buf_size < 4 + size + total)
896 /* The header should contain a known document type. For now,
897 * we don't parse the whole header but simply check for the
898 * availability of that array of characters inside the header.
899 * Not fully fool-proof, but good enough. */
900 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
901 int probelen = strlen(matroska_doctypes[i]);
902 for (n = 4+size; n <= 4+size+total-probelen; n++)
903 if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
904 return AVPROBE_SCORE_MAX;
907 // probably valid EBML header but no recognized doctype
908 return AVPROBE_SCORE_MAX/2;
911 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
914 MatroskaTrack *tracks = matroska->tracks.elem;
917 for (i=0; i < matroska->tracks.nb_elem; i++)
918 if (tracks[i].num == num)
921 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
925 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
926 MatroskaTrack *track)
928 MatroskaTrackEncoding *encodings = track->encodings.elem;
929 uint8_t* data = *buf;
930 int isize = *buf_size;
931 uint8_t* pkt_data = NULL;
932 int pkt_size = isize;
936 if (pkt_size >= 10000000)
939 switch (encodings[0].compression.algo) {
940 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
941 return encodings[0].compression.settings.size;
942 case MATROSKA_TRACK_ENCODING_COMP_LZO:
944 olen = pkt_size *= 3;
945 pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
946 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
947 } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
953 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
954 z_stream zstream = {0};
955 if (inflateInit(&zstream) != Z_OK)
957 zstream.next_in = data;
958 zstream.avail_in = isize;
961 pkt_data = av_realloc(pkt_data, pkt_size);
962 zstream.avail_out = pkt_size - zstream.total_out;
963 zstream.next_out = pkt_data + zstream.total_out;
964 result = inflate(&zstream, Z_NO_FLUSH);
965 } while (result==Z_OK && pkt_size<10000000);
966 pkt_size = zstream.total_out;
967 inflateEnd(&zstream);
968 if (result != Z_STREAM_END)
974 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
975 bz_stream bzstream = {0};
976 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
978 bzstream.next_in = data;
979 bzstream.avail_in = isize;
982 pkt_data = av_realloc(pkt_data, pkt_size);
983 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
984 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
985 result = BZ2_bzDecompress(&bzstream);
986 } while (result==BZ_OK && pkt_size<10000000);
987 pkt_size = bzstream.total_out_lo32;
988 BZ2_bzDecompressEnd(&bzstream);
989 if (result != BZ_STREAM_END)
999 *buf_size = pkt_size;
1006 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1007 AVPacket *pkt, uint64_t display_duration)
1009 char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1010 for (; *ptr!=',' && ptr<end-1; ptr++);
1013 for (; *ptr!=',' && ptr<end-1; ptr++);
1015 int64_t end_pts = pkt->pts + display_duration;
1016 int sc = matroska->time_scale * pkt->pts / 10000000;
1017 int ec = matroska->time_scale * end_pts / 10000000;
1018 int sh, sm, ss, eh, em, es, len;
1019 sh = sc/360000; sc -= 360000*sh;
1020 sm = sc/ 6000; sc -= 6000*sm;
1021 ss = sc/ 100; sc -= 100*ss;
1022 eh = ec/360000; ec -= 360000*eh;
1023 em = ec/ 6000; ec -= 6000*em;
1024 es = ec/ 100; ec -= 100*es;
1026 len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1027 if (!(line = av_malloc(len)))
1029 snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1030 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1033 pkt->size = strlen(line);
1037 static void matroska_merge_packets(AVPacket *out, AVPacket *in)
1039 out->data = av_realloc(out->data, out->size+in->size);
1040 memcpy(out->data+out->size, in->data, in->size);
1041 out->size += in->size;
1042 av_destruct_packet(in);
1046 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1047 AVMetadata **metadata, char *prefix)
1049 MatroskaTag *tags = list->elem;
1053 for (i=0; i < list->nb_elem; i++) {
1054 const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1056 if (!tags[i].name) {
1057 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1060 if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1061 else av_strlcpy(key, tags[i].name, sizeof(key));
1062 if (tags[i].def || !lang) {
1063 av_metadata_set2(metadata, key, tags[i].string, 0);
1064 if (tags[i].sub.nb_elem)
1065 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1068 av_strlcat(key, "-", sizeof(key));
1069 av_strlcat(key, lang, sizeof(key));
1070 av_metadata_set2(metadata, key, tags[i].string, 0);
1071 if (tags[i].sub.nb_elem)
1072 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1075 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1078 static void matroska_convert_tags(AVFormatContext *s)
1080 MatroskaDemuxContext *matroska = s->priv_data;
1081 MatroskaTags *tags = matroska->tags.elem;
1084 for (i=0; i < matroska->tags.nb_elem; i++) {
1085 if (tags[i].target.attachuid) {
1086 MatroskaAttachement *attachment = matroska->attachments.elem;
1087 for (j=0; j<matroska->attachments.nb_elem; j++)
1088 if (attachment[j].uid == tags[i].target.attachuid
1089 && attachment[j].stream)
1090 matroska_convert_tag(s, &tags[i].tag,
1091 &attachment[j].stream->metadata, NULL);
1092 } else if (tags[i].target.chapteruid) {
1093 MatroskaChapter *chapter = matroska->chapters.elem;
1094 for (j=0; j<matroska->chapters.nb_elem; j++)
1095 if (chapter[j].uid == tags[i].target.chapteruid
1096 && chapter[j].chapter)
1097 matroska_convert_tag(s, &tags[i].tag,
1098 &chapter[j].chapter->metadata, NULL);
1099 } else if (tags[i].target.trackuid) {
1100 MatroskaTrack *track = matroska->tracks.elem;
1101 for (j=0; j<matroska->tracks.nb_elem; j++)
1102 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1103 matroska_convert_tag(s, &tags[i].tag,
1104 &track[j].stream->metadata, NULL);
1106 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1107 tags[i].target.type);
1112 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1114 EbmlList *seekhead_list = &matroska->seekhead;
1115 MatroskaSeekhead *seekhead = seekhead_list->elem;
1116 uint32_t level_up = matroska->level_up;
1117 int64_t before_pos = avio_tell(matroska->ctx->pb);
1118 uint32_t saved_id = matroska->current_id;
1119 MatroskaLevel level;
1122 // we should not do any seeking in the streaming case
1123 if (url_is_streamed(matroska->ctx->pb) ||
1124 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1127 for (i=0; i<seekhead_list->nb_elem; i++) {
1128 int64_t offset = seekhead[i].pos + matroska->segment_start;
1130 if (seekhead[i].pos <= before_pos
1131 || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1132 || seekhead[i].id == MATROSKA_ID_CLUSTER)
1136 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1139 /* We don't want to lose our seekhead level, so we add
1140 * a dummy. This is a crude hack. */
1141 if (matroska->num_levels == EBML_MAX_DEPTH) {
1142 av_log(matroska->ctx, AV_LOG_INFO,
1143 "Max EBML element depth (%d) reached, "
1144 "cannot parse further.\n", EBML_MAX_DEPTH);
1149 level.length = (uint64_t)-1;
1150 matroska->levels[matroska->num_levels] = level;
1151 matroska->num_levels++;
1152 matroska->current_id = 0;
1154 ebml_parse(matroska, matroska_segment, matroska);
1156 /* remove dummy level */
1157 while (matroska->num_levels) {
1158 uint64_t length = matroska->levels[--matroska->num_levels].length;
1159 if (length == (uint64_t)-1)
1165 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1166 matroska->level_up = level_up;
1167 matroska->current_id = saved_id;
1170 static int matroska_aac_profile(char *codec_id)
1172 static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1175 for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1176 if (strstr(codec_id, aac_profiles[profile]))
1181 static int matroska_aac_sri(int samplerate)
1185 for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1186 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1191 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1193 MatroskaDemuxContext *matroska = s->priv_data;
1194 EbmlList *attachements_list = &matroska->attachments;
1195 MatroskaAttachement *attachements;
1196 EbmlList *chapters_list = &matroska->chapters;
1197 MatroskaChapter *chapters;
1198 MatroskaTrack *tracks;
1199 EbmlList *index_list;
1200 MatroskaIndex *index;
1201 int index_scale = 1;
1202 uint64_t max_start = 0;
1209 /* First read the EBML header. */
1210 if (ebml_parse(matroska, ebml_syntax, &ebml)
1211 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1212 || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1213 av_log(matroska->ctx, AV_LOG_ERROR,
1214 "EBML header using unsupported features\n"
1215 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1216 ebml.version, ebml.doctype, ebml.doctype_version);
1217 ebml_free(ebml_syntax, &ebml);
1218 return AVERROR_PATCHWELCOME;
1220 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1221 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1223 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1224 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1226 ebml_free(ebml_syntax, &ebml);
1228 /* The next thing is a segment. */
1229 if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1231 matroska_execute_seekhead(matroska);
1233 if (!matroska->time_scale)
1234 matroska->time_scale = 1000000;
1235 if (matroska->duration)
1236 matroska->ctx->duration = matroska->duration * matroska->time_scale
1237 * 1000 / AV_TIME_BASE;
1238 av_metadata_set2(&s->metadata, "title", matroska->title, 0);
1240 tracks = matroska->tracks.elem;
1241 for (i=0; i < matroska->tracks.nb_elem; i++) {
1242 MatroskaTrack *track = &tracks[i];
1243 enum CodecID codec_id = CODEC_ID_NONE;
1244 EbmlList *encodings_list = &tracks->encodings;
1245 MatroskaTrackEncoding *encodings = encodings_list->elem;
1246 uint8_t *extradata = NULL;
1247 int extradata_size = 0;
1248 int extradata_offset = 0;
1251 /* Apply some sanity checks. */
1252 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1253 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1254 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1255 av_log(matroska->ctx, AV_LOG_INFO,
1256 "Unknown or unsupported track type %"PRIu64"\n",
1260 if (track->codec_id == NULL)
1263 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1264 if (!track->default_duration)
1265 track->default_duration = 1000000000/track->video.frame_rate;
1266 if (!track->video.display_width)
1267 track->video.display_width = track->video.pixel_width;
1268 if (!track->video.display_height)
1269 track->video.display_height = track->video.pixel_height;
1270 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1271 if (!track->audio.out_samplerate)
1272 track->audio.out_samplerate = track->audio.samplerate;
1274 if (encodings_list->nb_elem > 1) {
1275 av_log(matroska->ctx, AV_LOG_ERROR,
1276 "Multiple combined encodings no supported");
1277 } else if (encodings_list->nb_elem == 1) {
1278 if (encodings[0].type ||
1279 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1281 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1284 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1286 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1287 encodings[0].scope = 0;
1288 av_log(matroska->ctx, AV_LOG_ERROR,
1289 "Unsupported encoding type");
1290 } else if (track->codec_priv.size && encodings[0].scope&2) {
1291 uint8_t *codec_priv = track->codec_priv.data;
1292 int offset = matroska_decode_buffer(&track->codec_priv.data,
1293 &track->codec_priv.size,
1296 track->codec_priv.data = NULL;
1297 track->codec_priv.size = 0;
1298 av_log(matroska->ctx, AV_LOG_ERROR,
1299 "Failed to decode codec private data\n");
1300 } else if (offset > 0) {
1301 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1302 memcpy(track->codec_priv.data,
1303 encodings[0].compression.settings.data, offset);
1304 memcpy(track->codec_priv.data+offset, codec_priv,
1305 track->codec_priv.size);
1306 track->codec_priv.size += offset;
1308 if (codec_priv != track->codec_priv.data)
1309 av_free(codec_priv);
1313 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1314 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1315 strlen(ff_mkv_codec_tags[j].str))){
1316 codec_id= ff_mkv_codec_tags[j].id;
1321 st = track->stream = av_new_stream(s, 0);
1323 return AVERROR(ENOMEM);
1325 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1326 && track->codec_priv.size >= 40
1327 && track->codec_priv.data != NULL) {
1328 track->ms_compat = 1;
1329 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1330 codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1331 extradata_offset = 40;
1332 } else if (!strcmp(track->codec_id, "A_MS/ACM")
1333 && track->codec_priv.size >= 14
1334 && track->codec_priv.data != NULL) {
1335 ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1336 URL_RDONLY, NULL, NULL, NULL, NULL);
1337 ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1338 codec_id = st->codec->codec_id;
1339 extradata_offset = FFMIN(track->codec_priv.size, 18);
1340 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1341 && (track->codec_priv.size >= 86)
1342 && (track->codec_priv.data != NULL)) {
1343 track->video.fourcc = AV_RL32(track->codec_priv.data);
1344 codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
1345 } else if (codec_id == CODEC_ID_PCM_S16BE) {
1346 switch (track->audio.bitdepth) {
1347 case 8: codec_id = CODEC_ID_PCM_U8; break;
1348 case 24: codec_id = CODEC_ID_PCM_S24BE; break;
1349 case 32: codec_id = CODEC_ID_PCM_S32BE; break;
1351 } else if (codec_id == CODEC_ID_PCM_S16LE) {
1352 switch (track->audio.bitdepth) {
1353 case 8: codec_id = CODEC_ID_PCM_U8; break;
1354 case 24: codec_id = CODEC_ID_PCM_S24LE; break;
1355 case 32: codec_id = CODEC_ID_PCM_S32LE; break;
1357 } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1358 codec_id = CODEC_ID_PCM_F64LE;
1359 } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1360 int profile = matroska_aac_profile(track->codec_id);
1361 int sri = matroska_aac_sri(track->audio.samplerate);
1362 extradata = av_malloc(5);
1363 if (extradata == NULL)
1364 return AVERROR(ENOMEM);
1365 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1366 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1367 if (strstr(track->codec_id, "SBR")) {
1368 sri = matroska_aac_sri(track->audio.out_samplerate);
1369 extradata[2] = 0x56;
1370 extradata[3] = 0xE5;
1371 extradata[4] = 0x80 | (sri<<3);
1375 } else if (codec_id == CODEC_ID_TTA) {
1376 extradata_size = 30;
1377 extradata = av_mallocz(extradata_size);
1378 if (extradata == NULL)
1379 return AVERROR(ENOMEM);
1380 ffio_init_context(&b, extradata, extradata_size, 1,
1381 NULL, NULL, NULL, NULL);
1382 avio_write(&b, "TTA1", 4);
1384 avio_wl16(&b, track->audio.channels);
1385 avio_wl16(&b, track->audio.bitdepth);
1386 avio_wl32(&b, track->audio.out_samplerate);
1387 avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1388 } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1389 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1390 extradata_offset = 26;
1391 } else if (codec_id == CODEC_ID_RA_144) {
1392 track->audio.out_samplerate = 8000;
1393 track->audio.channels = 1;
1394 } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1395 codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1397 ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1398 0, NULL, NULL, NULL, NULL);
1400 flavor = avio_rb16(&b);
1401 track->audio.coded_framesize = avio_rb32(&b);
1403 track->audio.sub_packet_h = avio_rb16(&b);
1404 track->audio.frame_size = avio_rb16(&b);
1405 track->audio.sub_packet_size = avio_rb16(&b);
1406 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1407 if (codec_id == CODEC_ID_RA_288) {
1408 st->codec->block_align = track->audio.coded_framesize;
1409 track->codec_priv.size = 0;
1411 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1412 const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1413 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1414 st->codec->bit_rate = sipr_bit_rate[flavor];
1416 st->codec->block_align = track->audio.sub_packet_size;
1417 extradata_offset = 78;
1420 track->codec_priv.size -= extradata_offset;
1422 if (codec_id == CODEC_ID_NONE)
1423 av_log(matroska->ctx, AV_LOG_INFO,
1424 "Unknown/unsupported CodecID %s.\n", track->codec_id);
1426 if (track->time_scale < 0.01)
1427 track->time_scale = 1.0;
1428 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1430 st->codec->codec_id = codec_id;
1432 if (strcmp(track->language, "und"))
1433 av_metadata_set2(&st->metadata, "language", track->language, 0);
1434 av_metadata_set2(&st->metadata, "title", track->name, 0);
1436 if (track->flag_default)
1437 st->disposition |= AV_DISPOSITION_DEFAULT;
1438 if (track->flag_forced)
1439 st->disposition |= AV_DISPOSITION_FORCED;
1441 if (track->default_duration)
1442 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1443 track->default_duration, 1000000000, 30000);
1445 if (!st->codec->extradata) {
1447 st->codec->extradata = extradata;
1448 st->codec->extradata_size = extradata_size;
1449 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1450 st->codec->extradata = av_mallocz(track->codec_priv.size +
1451 FF_INPUT_BUFFER_PADDING_SIZE);
1452 if(st->codec->extradata == NULL)
1453 return AVERROR(ENOMEM);
1454 st->codec->extradata_size = track->codec_priv.size;
1455 memcpy(st->codec->extradata,
1456 track->codec_priv.data + extradata_offset,
1457 track->codec_priv.size);
1461 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1462 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1463 st->codec->codec_tag = track->video.fourcc;
1464 st->codec->width = track->video.pixel_width;
1465 st->codec->height = track->video.pixel_height;
1466 av_reduce(&st->sample_aspect_ratio.num,
1467 &st->sample_aspect_ratio.den,
1468 st->codec->height * track->video.display_width,
1469 st->codec-> width * track->video.display_height,
1471 if (st->codec->codec_id != CODEC_ID_H264)
1472 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1473 if (track->default_duration)
1474 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1475 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1476 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1477 st->codec->sample_rate = track->audio.out_samplerate;
1478 st->codec->channels = track->audio.channels;
1479 if (st->codec->codec_id != CODEC_ID_AAC)
1480 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1481 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1482 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1486 attachements = attachements_list->elem;
1487 for (j=0; j<attachements_list->nb_elem; j++) {
1488 if (!(attachements[j].filename && attachements[j].mime &&
1489 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1490 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1492 AVStream *st = av_new_stream(s, 0);
1495 av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
1496 st->codec->codec_id = CODEC_ID_NONE;
1497 st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1498 st->codec->extradata = av_malloc(attachements[j].bin.size);
1499 if(st->codec->extradata == NULL)
1501 st->codec->extradata_size = attachements[j].bin.size;
1502 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1504 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1505 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1506 strlen(ff_mkv_mime_tags[i].str))) {
1507 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1511 attachements[j].stream = st;
1515 chapters = chapters_list->elem;
1516 for (i=0; i<chapters_list->nb_elem; i++)
1517 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1518 && (max_start==0 || chapters[i].start > max_start)) {
1519 chapters[i].chapter =
1520 ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1521 chapters[i].start, chapters[i].end,
1523 av_metadata_set2(&chapters[i].chapter->metadata,
1524 "title", chapters[i].title, 0);
1525 max_start = chapters[i].start;
1528 index_list = &matroska->index;
1529 index = index_list->elem;
1530 if (index_list->nb_elem
1531 && index[0].time > 100000000000000/matroska->time_scale) {
1532 av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1533 index_scale = matroska->time_scale;
1535 for (i=0; i<index_list->nb_elem; i++) {
1536 EbmlList *pos_list = &index[i].pos;
1537 MatroskaIndexPos *pos = pos_list->elem;
1538 for (j=0; j<pos_list->nb_elem; j++) {
1539 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1541 if (track && track->stream)
1542 av_add_index_entry(track->stream,
1543 pos[j].pos + matroska->segment_start,
1544 index[i].time/index_scale, 0, 0,
1549 matroska_convert_tags(s);
1555 * Put one packet in an application-supplied AVPacket struct.
1556 * Returns 0 on success or -1 on failure.
1558 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1561 if (matroska->num_packets > 0) {
1562 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1563 av_free(matroska->packets[0]);
1564 if (matroska->num_packets > 1) {
1565 memmove(&matroska->packets[0], &matroska->packets[1],
1566 (matroska->num_packets - 1) * sizeof(AVPacket *));
1568 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1569 sizeof(AVPacket *));
1571 av_freep(&matroska->packets);
1573 matroska->num_packets--;
1581 * Free all packets in our internal queue.
1583 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1585 if (matroska->packets) {
1587 for (n = 0; n < matroska->num_packets; n++) {
1588 av_free_packet(matroska->packets[n]);
1589 av_free(matroska->packets[n]);
1591 av_freep(&matroska->packets);
1592 matroska->num_packets = 0;
1596 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1597 int size, int64_t pos, uint64_t cluster_time,
1598 uint64_t duration, int is_keyframe,
1599 int64_t cluster_pos)
1601 uint64_t timecode = AV_NOPTS_VALUE;
1602 MatroskaTrack *track;
1607 uint32_t *lace_size = NULL;
1608 int n, flags, laces = 0;
1611 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1612 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1618 track = matroska_find_track_by_num(matroska, num);
1619 if (size <= 3 || !track || !track->stream) {
1620 av_log(matroska->ctx, AV_LOG_INFO,
1621 "Invalid stream %"PRIu64" or size %u\n", num, size);
1625 if (st->discard >= AVDISCARD_ALL)
1628 duration = track->default_duration / matroska->time_scale;
1630 block_time = AV_RB16(data);
1634 if (is_keyframe == -1)
1635 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1637 if (cluster_time != (uint64_t)-1
1638 && (block_time >= 0 || cluster_time >= -block_time)) {
1639 timecode = cluster_time + block_time;
1640 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1641 && timecode < track->end_timecode)
1642 is_keyframe = 0; /* overlapping subtitles are not key frame */
1644 av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1645 track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1648 if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1649 if (!is_keyframe || timecode < matroska->skip_to_timecode)
1651 matroska->skip_to_keyframe = 0;
1654 switch ((flags & 0x06) >> 1) {
1655 case 0x0: /* no lacing */
1657 lace_size = av_mallocz(sizeof(int));
1658 lace_size[0] = size;
1661 case 0x1: /* Xiph lacing */
1662 case 0x2: /* fixed-size lacing */
1663 case 0x3: /* EBML lacing */
1664 assert(size>0); // size <=3 is checked before size-=3 above
1665 laces = (*data) + 1;
1668 lace_size = av_mallocz(laces * sizeof(int));
1670 switch ((flags & 0x06) >> 1) {
1671 case 0x1: /* Xiph lacing */ {
1674 for (n = 0; res == 0 && n < laces - 1; n++) {
1681 lace_size[n] += temp;
1687 total += lace_size[n];
1689 lace_size[n] = size - total;
1693 case 0x2: /* fixed-size lacing */
1694 for (n = 0; n < laces; n++)
1695 lace_size[n] = size / laces;
1698 case 0x3: /* EBML lacing */ {
1700 n = matroska_ebmlnum_uint(matroska, data, size, &num);
1702 av_log(matroska->ctx, AV_LOG_INFO,
1703 "EBML block data error\n");
1708 total = lace_size[0] = num;
1709 for (n = 1; res == 0 && n < laces - 1; n++) {
1712 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1714 av_log(matroska->ctx, AV_LOG_INFO,
1715 "EBML block data error\n");
1720 lace_size[n] = lace_size[n - 1] + snum;
1721 total += lace_size[n];
1723 lace_size[n] = size - total;
1731 for (n = 0; n < laces; n++) {
1732 if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1733 st->codec->codec_id == CODEC_ID_COOK ||
1734 st->codec->codec_id == CODEC_ID_SIPR ||
1735 st->codec->codec_id == CODEC_ID_ATRAC3) &&
1736 st->codec->block_align && track->audio.sub_packet_size) {
1737 int a = st->codec->block_align;
1738 int sps = track->audio.sub_packet_size;
1739 int cfs = track->audio.coded_framesize;
1740 int h = track->audio.sub_packet_h;
1741 int y = track->audio.sub_packet_cnt;
1742 int w = track->audio.frame_size;
1745 if (!track->audio.pkt_cnt) {
1746 if (track->audio.sub_packet_cnt == 0)
1747 track->audio.buf_timecode = timecode;
1748 if (st->codec->codec_id == CODEC_ID_RA_288)
1749 for (x=0; x<h/2; x++)
1750 memcpy(track->audio.buf+x*2*w+y*cfs,
1752 else if (st->codec->codec_id == CODEC_ID_SIPR)
1753 memcpy(track->audio.buf + y*w, data, w);
1755 for (x=0; x<w/sps; x++)
1756 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1758 if (++track->audio.sub_packet_cnt >= h) {
1759 if (st->codec->codec_id == CODEC_ID_SIPR)
1760 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1761 track->audio.sub_packet_cnt = 0;
1762 track->audio.pkt_cnt = h*w / a;
1765 while (track->audio.pkt_cnt) {
1766 pkt = av_mallocz(sizeof(AVPacket));
1767 av_new_packet(pkt, a);
1768 memcpy(pkt->data, track->audio.buf
1769 + a * (h*w / a - track->audio.pkt_cnt--), a);
1770 pkt->pts = track->audio.buf_timecode;
1771 track->audio.buf_timecode = AV_NOPTS_VALUE;
1773 pkt->stream_index = st->index;
1774 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1777 MatroskaTrackEncoding *encodings = track->encodings.elem;
1778 int offset = 0, pkt_size = lace_size[n];
1779 uint8_t *pkt_data = data;
1781 if (pkt_size > size) {
1782 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1786 if (encodings && encodings->scope & 1) {
1787 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1792 pkt = av_mallocz(sizeof(AVPacket));
1793 /* XXX: prevent data copy... */
1794 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1796 res = AVERROR(ENOMEM);
1800 memcpy (pkt->data, encodings->compression.settings.data, offset);
1801 memcpy (pkt->data+offset, pkt_data, pkt_size);
1803 if (pkt_data != data)
1807 pkt->flags = is_keyframe;
1808 pkt->stream_index = st->index;
1810 if (track->ms_compat)
1811 pkt->dts = timecode;
1813 pkt->pts = timecode;
1815 if (st->codec->codec_id == CODEC_ID_TEXT)
1816 pkt->convergence_duration = duration;
1817 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1818 pkt->duration = duration;
1820 if (st->codec->codec_id == CODEC_ID_SSA)
1821 matroska_fix_ass_packet(matroska, pkt, duration);
1823 if (matroska->prev_pkt &&
1824 timecode != AV_NOPTS_VALUE &&
1825 matroska->prev_pkt->pts == timecode &&
1826 matroska->prev_pkt->stream_index == st->index &&
1827 st->codec->codec_id == CODEC_ID_SSA)
1828 matroska_merge_packets(matroska->prev_pkt, pkt);
1830 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1831 matroska->prev_pkt = pkt;
1835 if (timecode != AV_NOPTS_VALUE)
1836 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1837 data += lace_size[n];
1838 size -= lace_size[n];
1846 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1848 MatroskaCluster cluster = { 0 };
1849 EbmlList *blocks_list;
1850 MatroskaBlock *blocks;
1852 int64_t pos = avio_tell(matroska->ctx->pb);
1853 matroska->prev_pkt = NULL;
1854 if (matroska->current_id)
1855 pos -= 4; /* sizeof the ID which was already read */
1856 res = ebml_parse(matroska, matroska_clusters, &cluster);
1857 blocks_list = &cluster.blocks;
1858 blocks = blocks_list->elem;
1859 for (i=0; i<blocks_list->nb_elem; i++)
1860 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1861 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1862 if (!blocks[i].non_simple)
1863 blocks[i].duration = AV_NOPTS_VALUE;
1864 res=matroska_parse_block(matroska,
1865 blocks[i].bin.data, blocks[i].bin.size,
1866 blocks[i].bin.pos, cluster.timecode,
1867 blocks[i].duration, is_keyframe,
1870 ebml_free(matroska_cluster, &cluster);
1871 if (res < 0) matroska->done = 1;
1875 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1877 MatroskaDemuxContext *matroska = s->priv_data;
1879 while (matroska_deliver_packet(matroska, pkt)) {
1882 matroska_parse_cluster(matroska);
1888 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1889 int64_t timestamp, int flags)
1891 MatroskaDemuxContext *matroska = s->priv_data;
1892 MatroskaTrack *tracks = matroska->tracks.elem;
1893 AVStream *st = s->streams[stream_index];
1894 int i, index, index_sub, index_min;
1896 if (!st->nb_index_entries)
1898 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1900 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1901 avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1902 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1903 matroska_clear_queue(matroska);
1904 if (matroska_parse_cluster(matroska) < 0)
1909 matroska_clear_queue(matroska);
1914 for (i=0; i < matroska->tracks.nb_elem; i++) {
1915 tracks[i].audio.pkt_cnt = 0;
1916 tracks[i].audio.sub_packet_cnt = 0;
1917 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
1918 tracks[i].end_timecode = 0;
1919 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1920 && !tracks[i].stream->discard != AVDISCARD_ALL) {
1921 index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1923 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1924 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1925 index_min = index_sub;
1929 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1930 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1931 matroska->skip_to_timecode = st->index_entries[index].timestamp;
1933 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1937 static int matroska_read_close(AVFormatContext *s)
1939 MatroskaDemuxContext *matroska = s->priv_data;
1940 MatroskaTrack *tracks = matroska->tracks.elem;
1943 matroska_clear_queue(matroska);
1945 for (n=0; n < matroska->tracks.nb_elem; n++)
1946 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1947 av_free(tracks[n].audio.buf);
1948 ebml_free(matroska_segment, matroska);
1953 AVInputFormat ff_matroska_demuxer = {
1955 NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
1956 sizeof(MatroskaDemuxContext),
1958 matroska_read_header,
1959 matroska_read_packet,
1960 matroska_read_close,