2 * Matroska file demuxer
3 * Copyright (c) 2003-2008 The Libav Project
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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 * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28 * @see 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/bytestream.h"
41 #include "libavcodec/mpeg4audio.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/lzo.h"
46 #include "libavutil/dict.h"
67 typedef const struct EbmlSyntax {
76 const struct EbmlSyntax *n;
96 uint64_t doctype_version;
102 } MatroskaTrackCompression;
107 MatroskaTrackCompression compression;
108 } MatroskaTrackEncoding;
112 uint64_t display_width;
113 uint64_t display_height;
114 uint64_t pixel_width;
115 uint64_t pixel_height;
117 } MatroskaTrackVideo;
121 double out_samplerate;
125 /* real audio header (extracted from extradata) */
132 uint64_t buf_timecode;
134 } MatroskaTrackAudio;
145 uint64_t default_duration;
146 uint64_t flag_default;
147 uint64_t flag_forced;
148 MatroskaTrackVideo video;
149 MatroskaTrackAudio audio;
153 int64_t end_timecode;
164 } MatroskaAttachement;
202 MatroskaTagTarget target;
222 AVFormatContext *ctx;
226 MatroskaLevel levels[EBML_MAX_DEPTH];
234 EbmlList attachments;
240 /* byte position of the segment inside the stream */
241 int64_t segment_start;
243 /* the packet queue */
250 /* What to skip before effectively reading a packet. */
251 int skip_to_keyframe;
252 uint64_t skip_to_timecode;
254 /* File has a CUES element, but we defer parsing until it is needed. */
255 int cues_parsing_deferred;
257 int current_cluster_num_blocks;
258 int64_t current_cluster_pos;
259 MatroskaCluster current_cluster;
261 /* File has SSA subtitles which prevent incremental cluster parsing. */
263 } MatroskaDemuxContext;
272 static EbmlSyntax ebml_header[] = {
273 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
274 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
275 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
276 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
277 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
278 { EBML_ID_EBMLVERSION, EBML_NONE },
279 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
283 static EbmlSyntax ebml_syntax[] = {
284 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
288 static EbmlSyntax matroska_info[] = {
289 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
290 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
291 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
292 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
293 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
294 { MATROSKA_ID_DATEUTC, EBML_NONE },
295 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
299 static EbmlSyntax matroska_track_video[] = {
300 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
301 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
302 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
303 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
304 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
305 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
306 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
307 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
308 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
309 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
310 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
311 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
312 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
313 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
317 static EbmlSyntax matroska_track_audio[] = {
318 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
319 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
320 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
321 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
325 static EbmlSyntax matroska_track_encoding_compression[] = {
326 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
327 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
331 static EbmlSyntax matroska_track_encoding[] = {
332 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
333 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
334 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
335 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
339 static EbmlSyntax matroska_track_encodings[] = {
340 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
344 static EbmlSyntax matroska_track[] = {
345 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
346 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
347 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
348 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
349 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
350 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
351 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
352 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
353 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
354 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
355 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
356 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
357 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
358 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
359 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
360 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
361 { MATROSKA_ID_CODECNAME, EBML_NONE },
362 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
363 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
364 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
365 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
366 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
367 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
371 static EbmlSyntax matroska_tracks[] = {
372 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
376 static EbmlSyntax matroska_attachment[] = {
377 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
378 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
379 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
380 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
381 { MATROSKA_ID_FILEDESC, EBML_NONE },
385 static EbmlSyntax matroska_attachments[] = {
386 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
390 static EbmlSyntax matroska_chapter_display[] = {
391 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
392 { MATROSKA_ID_CHAPLANG, EBML_NONE },
396 static EbmlSyntax matroska_chapter_entry[] = {
397 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
398 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
399 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
400 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
401 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
402 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
403 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
404 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
408 static EbmlSyntax matroska_chapter[] = {
409 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
410 { MATROSKA_ID_EDITIONUID, EBML_NONE },
411 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
412 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
413 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
417 static EbmlSyntax matroska_chapters[] = {
418 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
422 static EbmlSyntax matroska_index_pos[] = {
423 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
424 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
425 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
429 static EbmlSyntax matroska_index_entry[] = {
430 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
431 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
435 static EbmlSyntax matroska_index[] = {
436 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
440 static EbmlSyntax matroska_simpletag[] = {
441 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
442 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
443 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
444 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
445 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
446 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
450 static EbmlSyntax matroska_tagtargets[] = {
451 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
452 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
453 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
454 { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
455 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
459 static EbmlSyntax matroska_tag[] = {
460 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
461 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
465 static EbmlSyntax matroska_tags[] = {
466 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
470 static EbmlSyntax matroska_seekhead_entry[] = {
471 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
472 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
476 static EbmlSyntax matroska_seekhead[] = {
477 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
481 static EbmlSyntax matroska_segment[] = {
482 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
483 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
484 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
485 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
486 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
487 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
488 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
489 { MATROSKA_ID_CLUSTER, EBML_STOP },
493 static EbmlSyntax matroska_segments[] = {
494 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
498 static EbmlSyntax matroska_blockgroup[] = {
499 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
500 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
501 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
502 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
503 { MATROSKA_ID_CODECSTATE, EBML_NONE },
504 { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
508 static EbmlSyntax matroska_cluster[] = {
509 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
510 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
511 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
512 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
513 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
517 static EbmlSyntax matroska_clusters[] = {
518 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
519 { MATROSKA_ID_INFO, EBML_NONE },
520 { MATROSKA_ID_CUES, EBML_NONE },
521 { MATROSKA_ID_TAGS, EBML_NONE },
522 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
526 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
527 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
528 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
529 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
530 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
531 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
532 { MATROSKA_ID_INFO, EBML_NONE },
533 { MATROSKA_ID_CUES, EBML_NONE },
534 { MATROSKA_ID_TAGS, EBML_NONE },
535 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
536 { MATROSKA_ID_CLUSTER, EBML_STOP },
540 static EbmlSyntax matroska_cluster_incremental[] = {
541 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
542 { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
543 { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
544 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
545 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
549 static EbmlSyntax matroska_clusters_incremental[] = {
550 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
551 { MATROSKA_ID_INFO, EBML_NONE },
552 { MATROSKA_ID_CUES, EBML_NONE },
553 { MATROSKA_ID_TAGS, EBML_NONE },
554 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
558 static const char *const matroska_doctypes[] = { "matroska", "webm" };
560 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
562 AVIOContext *pb = matroska->ctx->pb;
564 matroska->current_id = 0;
565 matroska->num_levels = 0;
567 /* seek to next position to resync from */
568 if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
573 // try to find a toplevel element
574 while (!pb->eof_reached) {
575 if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
576 id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
577 id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
578 id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
579 matroska->current_id = id;
582 id = (id << 8) | avio_r8(pb);
590 * Return: Whether we reached the end of a level in the hierarchy or not.
592 static int ebml_level_end(MatroskaDemuxContext *matroska)
594 AVIOContext *pb = matroska->ctx->pb;
595 int64_t pos = avio_tell(pb);
597 if (matroska->num_levels > 0) {
598 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
599 if (pos - level->start >= level->length || matroska->current_id) {
600 matroska->num_levels--;
608 * Read: an "EBML number", which is defined as a variable-length
609 * array of bytes. The first byte indicates the length by giving a
610 * number of 0-bits followed by a one. The position of the first
611 * "one" bit inside the first byte indicates the length of this
613 * Returns: number of bytes read, < 0 on error
615 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
616 int max_size, uint64_t *number)
621 /* The first byte tells us the length in bytes - avio_r8() can normally
622 * return 0, but since that's not a valid first ebmlID byte, we can
623 * use it safely here to catch EOS. */
624 if (!(total = avio_r8(pb))) {
625 /* we might encounter EOS here */
626 if (!pb->eof_reached) {
627 int64_t pos = avio_tell(pb);
628 av_log(matroska->ctx, AV_LOG_ERROR,
629 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
631 return pb->error ? pb->error : AVERROR(EIO);
636 /* get the length of the EBML number */
637 read = 8 - ff_log2_tab[total];
638 if (read > max_size) {
639 int64_t pos = avio_tell(pb) - 1;
640 av_log(matroska->ctx, AV_LOG_ERROR,
641 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
642 (uint8_t) total, pos, pos);
643 return AVERROR_INVALIDDATA;
646 /* read out length */
647 total ^= 1 << ff_log2_tab[total];
649 total = (total << 8) | avio_r8(pb);
657 * Read a EBML length value.
658 * This needs special handling for the "unknown length" case which has multiple
661 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
664 int res = ebml_read_num(matroska, pb, 8, number);
665 if (res > 0 && *number + 1 == 1ULL << (7 * res))
666 *number = 0xffffffffffffffULL;
671 * Read the next element as an unsigned int.
672 * 0 is success, < 0 is failure.
674 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
679 return AVERROR_INVALIDDATA;
681 /* big-endian ordering; build up number */
684 *num = (*num << 8) | avio_r8(pb);
690 * Read the next element as a float.
691 * 0 is success, < 0 is failure.
693 static int ebml_read_float(AVIOContext *pb, int size, double *num)
697 } else if (size == 4) {
698 *num = av_int2float(avio_rb32(pb));
699 } else if (size == 8){
700 *num = av_int2double(avio_rb64(pb));
702 return AVERROR_INVALIDDATA;
708 * Read the next element as an ASCII string.
709 * 0 is success, < 0 is failure.
711 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
715 /* EBML strings are usually not 0-terminated, so we allocate one
716 * byte more, read the string and NULL-terminate it ourselves. */
717 if (!(res = av_malloc(size + 1)))
718 return AVERROR(ENOMEM);
719 if (avio_read(pb, (uint8_t *) res, size) != size) {
731 * Read the next element as binary data.
732 * 0 is success, < 0 is failure.
734 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
737 if (!(bin->data = av_malloc(length)))
738 return AVERROR(ENOMEM);
741 bin->pos = avio_tell(pb);
742 if (avio_read(pb, bin->data, length) != length) {
743 av_freep(&bin->data);
751 * Read the next element, but only the header. The contents
752 * are supposed to be sub-elements which can be read separately.
753 * 0 is success, < 0 is failure.
755 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
757 AVIOContext *pb = matroska->ctx->pb;
758 MatroskaLevel *level;
760 if (matroska->num_levels >= EBML_MAX_DEPTH) {
761 av_log(matroska->ctx, AV_LOG_ERROR,
762 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
763 return AVERROR(ENOSYS);
766 level = &matroska->levels[matroska->num_levels++];
767 level->start = avio_tell(pb);
768 level->length = length;
774 * Read signed/unsigned "EBML" numbers.
775 * Return: number of bytes processed, < 0 on error
777 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
778 uint8_t *data, uint32_t size, uint64_t *num)
781 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
782 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
786 * Same as above, but signed.
788 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
789 uint8_t *data, uint32_t size, int64_t *num)
794 /* read as unsigned number first */
795 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
798 /* make signed (weird way) */
799 *num = unum - ((1LL << (7*res - 1)) - 1);
804 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
805 EbmlSyntax *syntax, void *data);
807 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
808 uint32_t id, void *data)
811 for (i=0; syntax[i].id; i++)
812 if (id == syntax[i].id)
814 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
815 matroska->num_levels > 0 &&
816 matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
817 return 0; // we reached the end of an unknown size cluster
818 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
819 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
820 if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
821 return AVERROR_INVALIDDATA;
823 return ebml_parse_elem(matroska, &syntax[i], data);
826 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
829 if (!matroska->current_id) {
831 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
834 matroska->current_id = id | 1 << 7*res;
836 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
839 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
844 for (i=0; syntax[i].id; i++)
845 switch (syntax[i].type) {
847 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
850 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
854 // the default may be NULL
855 if (syntax[i].def.s) {
856 uint8_t **dst = (uint8_t**)((uint8_t*)data + syntax[i].data_offset);
857 *dst = av_strdup(syntax[i].def.s);
859 return AVERROR(ENOMEM);
864 while (!res && !ebml_level_end(matroska))
865 res = ebml_parse(matroska, syntax, data);
870 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
871 EbmlSyntax *syntax, void *data)
873 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
876 // max. 16 MB for strings
877 [EBML_STR] = 0x1000000,
878 [EBML_UTF8] = 0x1000000,
879 // max. 256 MB for binary data
880 [EBML_BIN] = 0x10000000,
881 // no limits for anything else
883 AVIOContext *pb = matroska->ctx->pb;
884 uint32_t id = syntax->id;
888 data = (char *)data + syntax->data_offset;
889 if (syntax->list_elem_size) {
890 EbmlList *list = data;
891 if ((res = av_reallocp_array(&list->elem,
893 syntax->list_elem_size)) < 0) {
897 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
898 memset(data, 0, syntax->list_elem_size);
902 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
903 matroska->current_id = 0;
904 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
906 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
907 av_log(matroska->ctx, AV_LOG_ERROR,
908 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
909 length, max_lengths[syntax->type], syntax->type);
910 return AVERROR_INVALIDDATA;
914 switch (syntax->type) {
915 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
916 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
918 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
919 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
920 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
922 if (id == MATROSKA_ID_SEGMENT)
923 matroska->segment_start = avio_tell(matroska->ctx->pb);
924 return ebml_parse_nest(matroska, syntax->def.n, data);
925 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
926 case EBML_STOP: return 1;
927 default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
929 if (res == AVERROR_INVALIDDATA)
930 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
931 else if (res == AVERROR(EIO))
932 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
936 static void ebml_free(EbmlSyntax *syntax, void *data)
939 for (i=0; syntax[i].id; i++) {
940 void *data_off = (char *)data + syntax[i].data_offset;
941 switch (syntax[i].type) {
943 case EBML_UTF8: av_freep(data_off); break;
944 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
946 if (syntax[i].list_elem_size) {
947 EbmlList *list = data_off;
948 char *ptr = list->elem;
949 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
950 ebml_free(syntax[i].def.n, ptr);
953 ebml_free(syntax[i].def.n, data_off);
963 static int matroska_probe(AVProbeData *p)
966 int len_mask = 0x80, size = 1, n = 1, i;
969 if (AV_RB32(p->buf) != EBML_ID_HEADER)
972 /* length of header */
974 while (size <= 8 && !(total & len_mask)) {
980 total &= (len_mask - 1);
982 total = (total << 8) | p->buf[4 + n++];
984 /* Does the probe data contain the whole header? */
985 if (p->buf_size < 4 + size + total)
988 /* The header should contain a known document type. For now,
989 * we don't parse the whole header but simply check for the
990 * availability of that array of characters inside the header.
991 * Not fully fool-proof, but good enough. */
992 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
993 int probelen = strlen(matroska_doctypes[i]);
994 if (total < probelen)
996 for (n = 4+size; n <= 4+size+total-probelen; n++)
997 if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
998 return AVPROBE_SCORE_MAX;
1001 // probably valid EBML header but no recognized doctype
1002 return AVPROBE_SCORE_EXTENSION;
1005 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1008 MatroskaTrack *tracks = matroska->tracks.elem;
1011 for (i=0; i < matroska->tracks.nb_elem; i++)
1012 if (tracks[i].num == num)
1015 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1019 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1020 MatroskaTrack *track)
1022 MatroskaTrackEncoding *encodings = track->encodings.elem;
1023 uint8_t* data = *buf;
1024 int isize = *buf_size;
1025 uint8_t* pkt_data = NULL;
1026 uint8_t av_unused *newpktdata;
1027 int pkt_size = isize;
1031 if (pkt_size >= 10000000)
1032 return AVERROR_INVALIDDATA;
1034 switch (encodings[0].compression.algo) {
1035 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
1036 int header_size = encodings[0].compression.settings.size;
1037 uint8_t *header = encodings[0].compression.settings.data;
1042 pkt_size = isize + header_size;
1043 pkt_data = av_malloc(pkt_size);
1045 return AVERROR(ENOMEM);
1047 memcpy(pkt_data, header, header_size);
1048 memcpy(pkt_data + header_size, data, isize);
1052 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1054 olen = pkt_size *= 3;
1055 newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1057 result = AVERROR(ENOMEM);
1060 pkt_data = newpktdata;
1061 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1062 } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1064 result = AVERROR_INVALIDDATA;
1071 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1072 z_stream zstream = {0};
1073 if (inflateInit(&zstream) != Z_OK)
1075 zstream.next_in = data;
1076 zstream.avail_in = isize;
1079 newpktdata = av_realloc(pkt_data, pkt_size);
1081 inflateEnd(&zstream);
1084 pkt_data = newpktdata;
1085 zstream.avail_out = pkt_size - zstream.total_out;
1086 zstream.next_out = pkt_data + zstream.total_out;
1087 result = inflate(&zstream, Z_NO_FLUSH);
1088 } while (result==Z_OK && pkt_size<10000000);
1089 pkt_size = zstream.total_out;
1090 inflateEnd(&zstream);
1091 if (result != Z_STREAM_END) {
1092 if (result == Z_MEM_ERROR)
1093 result = AVERROR(ENOMEM);
1095 result = AVERROR_INVALIDDATA;
1102 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1103 bz_stream bzstream = {0};
1104 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1106 bzstream.next_in = data;
1107 bzstream.avail_in = isize;
1110 newpktdata = av_realloc(pkt_data, pkt_size);
1112 BZ2_bzDecompressEnd(&bzstream);
1115 pkt_data = newpktdata;
1116 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1117 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1118 result = BZ2_bzDecompress(&bzstream);
1119 } while (result==BZ_OK && pkt_size<10000000);
1120 pkt_size = bzstream.total_out_lo32;
1121 BZ2_bzDecompressEnd(&bzstream);
1122 if (result != BZ_STREAM_END) {
1123 if (result == BZ_MEM_ERROR)
1124 result = AVERROR(ENOMEM);
1126 result = AVERROR_INVALIDDATA;
1133 return AVERROR_INVALIDDATA;
1137 *buf_size = pkt_size;
1144 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1145 AVPacket *pkt, uint64_t display_duration)
1148 char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1149 for (; *ptr!=',' && ptr<end-1; ptr++);
1152 for (; *ptr!=',' && ptr<end-1; ptr++);
1154 int64_t end_pts = pkt->pts + display_duration;
1155 int sc = matroska->time_scale * pkt->pts / 10000000;
1156 int ec = matroska->time_scale * end_pts / 10000000;
1157 int sh, sm, ss, eh, em, es, len;
1158 sh = sc/360000; sc -= 360000*sh;
1159 sm = sc/ 6000; sc -= 6000*sm;
1160 ss = sc/ 100; sc -= 100*ss;
1161 eh = ec/360000; ec -= 360000*eh;
1162 em = ec/ 6000; ec -= 6000*em;
1163 es = ec/ 100; ec -= 100*es;
1165 len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1166 if (!(line = av_buffer_alloc(len)))
1168 snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1169 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1170 av_buffer_unref(&pkt->buf);
1172 pkt->data = line->data;
1173 pkt->size = strlen(line->data);
1177 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1179 int old_size = out->size;
1180 int ret = av_grow_packet(out, in->size);
1184 memcpy(out->data + old_size, in->data, in->size);
1191 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1192 AVDictionary **metadata, char *prefix)
1194 MatroskaTag *tags = list->elem;
1198 for (i=0; i < list->nb_elem; i++) {
1199 const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
1200 tags[i].lang : NULL;
1202 if (!tags[i].name) {
1203 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1206 if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1207 else av_strlcpy(key, tags[i].name, sizeof(key));
1208 if (tags[i].def || !lang) {
1209 av_dict_set(metadata, key, tags[i].string, 0);
1210 if (tags[i].sub.nb_elem)
1211 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1214 av_strlcat(key, "-", sizeof(key));
1215 av_strlcat(key, lang, sizeof(key));
1216 av_dict_set(metadata, key, tags[i].string, 0);
1217 if (tags[i].sub.nb_elem)
1218 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1221 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1224 static void matroska_convert_tags(AVFormatContext *s)
1226 MatroskaDemuxContext *matroska = s->priv_data;
1227 MatroskaTags *tags = matroska->tags.elem;
1230 for (i=0; i < matroska->tags.nb_elem; i++) {
1231 if (tags[i].target.attachuid) {
1232 MatroskaAttachement *attachment = matroska->attachments.elem;
1233 for (j=0; j<matroska->attachments.nb_elem; j++)
1234 if (attachment[j].uid == tags[i].target.attachuid
1235 && attachment[j].stream)
1236 matroska_convert_tag(s, &tags[i].tag,
1237 &attachment[j].stream->metadata, NULL);
1238 } else if (tags[i].target.chapteruid) {
1239 MatroskaChapter *chapter = matroska->chapters.elem;
1240 for (j=0; j<matroska->chapters.nb_elem; j++)
1241 if (chapter[j].uid == tags[i].target.chapteruid
1242 && chapter[j].chapter)
1243 matroska_convert_tag(s, &tags[i].tag,
1244 &chapter[j].chapter->metadata, NULL);
1245 } else if (tags[i].target.trackuid) {
1246 MatroskaTrack *track = matroska->tracks.elem;
1247 for (j=0; j<matroska->tracks.nb_elem; j++)
1248 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1249 matroska_convert_tag(s, &tags[i].tag,
1250 &track[j].stream->metadata, NULL);
1252 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1253 tags[i].target.type);
1258 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1260 EbmlList *seekhead_list = &matroska->seekhead;
1261 MatroskaSeekhead *seekhead = seekhead_list->elem;
1262 uint32_t level_up = matroska->level_up;
1263 int64_t before_pos = avio_tell(matroska->ctx->pb);
1264 uint32_t saved_id = matroska->current_id;
1265 MatroskaLevel level;
1269 if (idx >= seekhead_list->nb_elem
1270 || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1271 || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1275 offset = seekhead[idx].pos + matroska->segment_start;
1276 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1277 /* We don't want to lose our seekhead level, so we add
1278 * a dummy. This is a crude hack. */
1279 if (matroska->num_levels == EBML_MAX_DEPTH) {
1280 av_log(matroska->ctx, AV_LOG_INFO,
1281 "Max EBML element depth (%d) reached, "
1282 "cannot parse further.\n", EBML_MAX_DEPTH);
1283 ret = AVERROR_INVALIDDATA;
1286 level.length = (uint64_t)-1;
1287 matroska->levels[matroska->num_levels] = level;
1288 matroska->num_levels++;
1289 matroska->current_id = 0;
1291 ret = ebml_parse(matroska, matroska_segment, matroska);
1293 /* remove dummy level */
1294 while (matroska->num_levels) {
1295 uint64_t length = matroska->levels[--matroska->num_levels].length;
1296 if (length == (uint64_t)-1)
1302 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1303 matroska->level_up = level_up;
1304 matroska->current_id = saved_id;
1309 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1311 EbmlList *seekhead_list = &matroska->seekhead;
1312 int64_t before_pos = avio_tell(matroska->ctx->pb);
1315 // we should not do any seeking in the streaming case
1316 if (!matroska->ctx->pb->seekable ||
1317 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1320 for (i = 0; i < seekhead_list->nb_elem; i++) {
1321 MatroskaSeekhead *seekhead = seekhead_list->elem;
1322 if (seekhead[i].pos <= before_pos)
1325 // defer cues parsing until we actually need cue data.
1326 if (seekhead[i].id == MATROSKA_ID_CUES) {
1327 matroska->cues_parsing_deferred = 1;
1331 if (matroska_parse_seekhead_entry(matroska, i) < 0)
1336 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1337 EbmlList *seekhead_list = &matroska->seekhead;
1338 MatroskaSeekhead *seekhead = seekhead_list->elem;
1339 EbmlList *index_list;
1340 MatroskaIndex *index;
1341 int index_scale = 1;
1344 for (i = 0; i < seekhead_list->nb_elem; i++)
1345 if (seekhead[i].id == MATROSKA_ID_CUES)
1347 assert(i <= seekhead_list->nb_elem);
1349 matroska_parse_seekhead_entry(matroska, i);
1351 index_list = &matroska->index;
1352 index = index_list->elem;
1353 if (index_list->nb_elem
1354 && index[0].time > 1E14/matroska->time_scale) {
1355 av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1356 index_scale = matroska->time_scale;
1358 for (i = 0; i < index_list->nb_elem; i++) {
1359 EbmlList *pos_list = &index[i].pos;
1360 MatroskaIndexPos *pos = pos_list->elem;
1361 for (j = 0; j < pos_list->nb_elem; j++) {
1362 MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1363 if (track && track->stream)
1364 av_add_index_entry(track->stream,
1365 pos[j].pos + matroska->segment_start,
1366 index[i].time/index_scale, 0, 0,
1372 static int matroska_aac_profile(char *codec_id)
1374 static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1377 for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1378 if (strstr(codec_id, aac_profiles[profile]))
1383 static int matroska_aac_sri(int samplerate)
1387 for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1388 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1393 static int matroska_read_header(AVFormatContext *s)
1395 MatroskaDemuxContext *matroska = s->priv_data;
1396 EbmlList *attachements_list = &matroska->attachments;
1397 MatroskaAttachement *attachements;
1398 EbmlList *chapters_list = &matroska->chapters;
1399 MatroskaChapter *chapters;
1400 MatroskaTrack *tracks;
1401 uint64_t max_start = 0;
1409 /* First read the EBML header. */
1410 if (ebml_parse(matroska, ebml_syntax, &ebml)
1411 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1412 || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1413 av_log(matroska->ctx, AV_LOG_ERROR,
1414 "EBML header using unsupported features\n"
1415 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1416 ebml.version, ebml.doctype, ebml.doctype_version);
1417 ebml_free(ebml_syntax, &ebml);
1418 return AVERROR_PATCHWELCOME;
1420 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1421 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1423 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1424 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1425 if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1426 ebml_free(ebml_syntax, &ebml);
1427 return AVERROR_INVALIDDATA;
1430 ebml_free(ebml_syntax, &ebml);
1432 /* The next thing is a segment. */
1433 pos = avio_tell(matroska->ctx->pb);
1434 res = ebml_parse(matroska, matroska_segments, matroska);
1435 // try resyncing until we find a EBML_STOP type element.
1437 res = matroska_resync(matroska, pos);
1440 pos = avio_tell(matroska->ctx->pb);
1441 res = ebml_parse(matroska, matroska_segment, matroska);
1443 matroska_execute_seekhead(matroska);
1445 if (!matroska->time_scale)
1446 matroska->time_scale = 1000000;
1447 if (matroska->duration)
1448 matroska->ctx->duration = matroska->duration * matroska->time_scale
1449 * 1000 / AV_TIME_BASE;
1450 av_dict_set(&s->metadata, "title", matroska->title, 0);
1452 tracks = matroska->tracks.elem;
1453 for (i=0; i < matroska->tracks.nb_elem; i++) {
1454 MatroskaTrack *track = &tracks[i];
1455 enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1456 EbmlList *encodings_list = &tracks->encodings;
1457 MatroskaTrackEncoding *encodings = encodings_list->elem;
1458 uint8_t *extradata = NULL;
1459 int extradata_size = 0;
1460 int extradata_offset = 0;
1463 /* Apply some sanity checks. */
1464 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1465 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1466 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1467 av_log(matroska->ctx, AV_LOG_INFO,
1468 "Unknown or unsupported track type %"PRIu64"\n",
1472 if (track->codec_id == NULL)
1475 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1476 if (!track->default_duration && track->video.frame_rate > 0)
1477 track->default_duration = 1000000000/track->video.frame_rate;
1478 if (!track->video.display_width)
1479 track->video.display_width = track->video.pixel_width;
1480 if (!track->video.display_height)
1481 track->video.display_height = track->video.pixel_height;
1482 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1483 if (!track->audio.out_samplerate)
1484 track->audio.out_samplerate = track->audio.samplerate;
1486 if (encodings_list->nb_elem > 1) {
1487 av_log(matroska->ctx, AV_LOG_ERROR,
1488 "Multiple combined encodings not supported");
1489 } else if (encodings_list->nb_elem == 1) {
1490 if (encodings[0].type ||
1493 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1496 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1499 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1501 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
1502 encodings[0].scope = 0;
1503 av_log(matroska->ctx, AV_LOG_ERROR,
1504 "Unsupported encoding type");
1505 } else if (track->codec_priv.size && encodings[0].scope&2) {
1506 uint8_t *codec_priv = track->codec_priv.data;
1507 int ret = matroska_decode_buffer(&track->codec_priv.data,
1508 &track->codec_priv.size,
1511 track->codec_priv.data = NULL;
1512 track->codec_priv.size = 0;
1513 av_log(matroska->ctx, AV_LOG_ERROR,
1514 "Failed to decode codec private data\n");
1517 if (codec_priv != track->codec_priv.data)
1518 av_free(codec_priv);
1522 for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1523 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1524 strlen(ff_mkv_codec_tags[j].str))){
1525 codec_id= ff_mkv_codec_tags[j].id;
1530 st = track->stream = avformat_new_stream(s, NULL);
1532 return AVERROR(ENOMEM);
1534 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1535 && track->codec_priv.size >= 40
1536 && track->codec_priv.data != NULL) {
1537 track->ms_compat = 1;
1538 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1539 codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1540 extradata_offset = 40;
1541 } else if (!strcmp(track->codec_id, "A_MS/ACM")
1542 && track->codec_priv.size >= 14
1543 && track->codec_priv.data != NULL) {
1545 ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1546 0, NULL, NULL, NULL, NULL);
1547 ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1550 codec_id = st->codec->codec_id;
1551 extradata_offset = FFMIN(track->codec_priv.size, 18);
1552 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1553 && (track->codec_priv.size >= 86)
1554 && (track->codec_priv.data != NULL)) {
1555 track->video.fourcc = AV_RL32(track->codec_priv.data);
1556 codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
1557 } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1558 switch (track->audio.bitdepth) {
1559 case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1560 case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
1561 case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
1563 } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1564 switch (track->audio.bitdepth) {
1565 case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1566 case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
1567 case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
1569 } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1570 codec_id = AV_CODEC_ID_PCM_F64LE;
1571 } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1572 int profile = matroska_aac_profile(track->codec_id);
1573 int sri = matroska_aac_sri(track->audio.samplerate);
1574 extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1575 if (extradata == NULL)
1576 return AVERROR(ENOMEM);
1577 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1578 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1579 if (strstr(track->codec_id, "SBR")) {
1580 sri = matroska_aac_sri(track->audio.out_samplerate);
1581 extradata[2] = 0x56;
1582 extradata[3] = 0xE5;
1583 extradata[4] = 0x80 | (sri<<3);
1587 } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
1588 /* Only ALAC's magic cookie is stored in Matroska's track headers.
1589 Create the "atom size", "tag", and "tag version" fields the
1590 decoder expects manually. */
1591 extradata_size = 12 + track->codec_priv.size;
1592 extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1593 if (extradata == NULL)
1594 return AVERROR(ENOMEM);
1595 AV_WB32(extradata, extradata_size);
1596 memcpy(&extradata[4], "alac", 4);
1597 AV_WB32(&extradata[8], 0);
1598 memcpy(&extradata[12], track->codec_priv.data,
1599 track->codec_priv.size);
1600 } else if (codec_id == AV_CODEC_ID_TTA) {
1601 extradata_size = 30;
1602 extradata = av_mallocz(extradata_size);
1603 if (extradata == NULL)
1604 return AVERROR(ENOMEM);
1605 ffio_init_context(&b, extradata, extradata_size, 1,
1606 NULL, NULL, NULL, NULL);
1607 avio_write(&b, "TTA1", 4);
1609 avio_wl16(&b, track->audio.channels);
1610 avio_wl16(&b, track->audio.bitdepth);
1611 avio_wl32(&b, track->audio.out_samplerate);
1612 avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1613 } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1614 codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1615 extradata_offset = 26;
1616 } else if (codec_id == AV_CODEC_ID_RA_144) {
1617 track->audio.out_samplerate = 8000;
1618 track->audio.channels = 1;
1619 } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1620 codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
1622 ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1623 0, NULL, NULL, NULL, NULL);
1625 flavor = avio_rb16(&b);
1626 track->audio.coded_framesize = avio_rb32(&b);
1628 track->audio.sub_packet_h = avio_rb16(&b);
1629 track->audio.frame_size = avio_rb16(&b);
1630 track->audio.sub_packet_size = avio_rb16(&b);
1631 if (flavor <= 0 || track->audio.coded_framesize <= 0 ||
1632 track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
1633 track->audio.sub_packet_size <= 0)
1634 return AVERROR_INVALIDDATA;
1635 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1636 if (codec_id == AV_CODEC_ID_RA_288) {
1637 st->codec->block_align = track->audio.coded_framesize;
1638 track->codec_priv.size = 0;
1640 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1641 const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1642 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1643 st->codec->bit_rate = sipr_bit_rate[flavor];
1645 st->codec->block_align = track->audio.sub_packet_size;
1646 extradata_offset = 78;
1649 track->codec_priv.size -= extradata_offset;
1651 if (codec_id == AV_CODEC_ID_NONE)
1652 av_log(matroska->ctx, AV_LOG_INFO,
1653 "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1655 if (track->time_scale < 0.01)
1656 track->time_scale = 1.0;
1657 avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1659 st->codec->codec_id = codec_id;
1661 if (strcmp(track->language, "und"))
1662 av_dict_set(&st->metadata, "language", track->language, 0);
1663 av_dict_set(&st->metadata, "title", track->name, 0);
1665 if (track->flag_default)
1666 st->disposition |= AV_DISPOSITION_DEFAULT;
1667 if (track->flag_forced)
1668 st->disposition |= AV_DISPOSITION_FORCED;
1670 if (!st->codec->extradata) {
1672 st->codec->extradata = extradata;
1673 st->codec->extradata_size = extradata_size;
1674 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1675 st->codec->extradata = av_mallocz(track->codec_priv.size +
1676 FF_INPUT_BUFFER_PADDING_SIZE);
1677 if(st->codec->extradata == NULL)
1678 return AVERROR(ENOMEM);
1679 st->codec->extradata_size = track->codec_priv.size;
1680 memcpy(st->codec->extradata,
1681 track->codec_priv.data + extradata_offset,
1682 track->codec_priv.size);
1686 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1687 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1688 st->codec->codec_tag = track->video.fourcc;
1689 st->codec->width = track->video.pixel_width;
1690 st->codec->height = track->video.pixel_height;
1691 av_reduce(&st->sample_aspect_ratio.num,
1692 &st->sample_aspect_ratio.den,
1693 st->codec->height * track->video.display_width,
1694 st->codec-> width * track->video.display_height,
1696 if (st->codec->codec_id != AV_CODEC_ID_H264 &&
1697 st->codec->codec_id != AV_CODEC_ID_HEVC)
1698 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1699 if (track->default_duration) {
1700 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1701 1000000000, track->default_duration, 30000);
1703 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1704 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1705 st->codec->sample_rate = track->audio.out_samplerate;
1706 st->codec->channels = track->audio.channels;
1707 if (st->codec->codec_id != AV_CODEC_ID_AAC)
1708 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1709 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1710 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1711 if (st->codec->codec_id == AV_CODEC_ID_SSA)
1712 matroska->contains_ssa = 1;
1716 attachements = attachements_list->elem;
1717 for (j=0; j<attachements_list->nb_elem; j++) {
1718 if (!(attachements[j].filename && attachements[j].mime &&
1719 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1720 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1722 AVStream *st = avformat_new_stream(s, NULL);
1725 av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1726 av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1727 st->codec->codec_id = AV_CODEC_ID_NONE;
1728 st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1729 st->codec->extradata = av_malloc(attachements[j].bin.size);
1730 if(st->codec->extradata == NULL)
1732 st->codec->extradata_size = attachements[j].bin.size;
1733 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1735 for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1736 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1737 strlen(ff_mkv_mime_tags[i].str))) {
1738 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1742 attachements[j].stream = st;
1746 chapters = chapters_list->elem;
1747 for (i=0; i<chapters_list->nb_elem; i++)
1748 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1749 && (max_start==0 || chapters[i].start > max_start)) {
1750 chapters[i].chapter =
1751 avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1752 chapters[i].start, chapters[i].end,
1754 av_dict_set(&chapters[i].chapter->metadata,
1755 "title", chapters[i].title, 0);
1756 max_start = chapters[i].start;
1759 matroska_convert_tags(s);
1765 * Put one packet in an application-supplied AVPacket struct.
1766 * Returns 0 on success or -1 on failure.
1768 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1771 if (matroska->num_packets > 0) {
1772 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1773 av_free(matroska->packets[0]);
1774 if (matroska->num_packets > 1) {
1776 memmove(&matroska->packets[0], &matroska->packets[1],
1777 (matroska->num_packets - 1) * sizeof(AVPacket *));
1778 newpackets = av_realloc(matroska->packets,
1779 (matroska->num_packets - 1) * sizeof(AVPacket *));
1781 matroska->packets = newpackets;
1783 av_freep(&matroska->packets);
1784 matroska->prev_pkt = NULL;
1786 matroska->num_packets--;
1794 * Free all packets in our internal queue.
1796 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1798 matroska->prev_pkt = NULL;
1799 if (matroska->packets) {
1801 for (n = 0; n < matroska->num_packets; n++) {
1802 av_free_packet(matroska->packets[n]);
1803 av_free(matroska->packets[n]);
1805 av_freep(&matroska->packets);
1806 matroska->num_packets = 0;
1810 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
1811 int* buf_size, int type,
1812 uint32_t **lace_buf, int *laces)
1814 int res = 0, n, size = *buf_size;
1815 uint8_t *data = *buf;
1816 uint32_t *lace_size;
1820 *lace_buf = av_mallocz(sizeof(int));
1822 return AVERROR(ENOMEM);
1824 *lace_buf[0] = size;
1832 lace_size = av_mallocz(*laces * sizeof(int));
1834 return AVERROR(ENOMEM);
1837 case 0x1: /* Xiph lacing */ {
1840 for (n = 0; res == 0 && n < *laces - 1; n++) {
1847 lace_size[n] += temp;
1853 total += lace_size[n];
1855 if (size <= total) {
1856 res = AVERROR_INVALIDDATA;
1860 lace_size[n] = size - total;
1864 case 0x2: /* fixed-size lacing */
1865 if (size % (*laces)) {
1866 res = AVERROR_INVALIDDATA;
1869 for (n = 0; n < *laces; n++)
1870 lace_size[n] = size / *laces;
1873 case 0x3: /* EBML lacing */ {
1876 n = matroska_ebmlnum_uint(matroska, data, size, &num);
1878 av_log(matroska->ctx, AV_LOG_INFO,
1879 "EBML block data error\n");
1885 total = lace_size[0] = num;
1886 for (n = 1; res == 0 && n < *laces - 1; n++) {
1889 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1891 av_log(matroska->ctx, AV_LOG_INFO,
1892 "EBML block data error\n");
1898 lace_size[n] = lace_size[n - 1] + snum;
1899 total += lace_size[n];
1901 if (size <= total) {
1902 res = AVERROR_INVALIDDATA;
1905 lace_size[*laces - 1] = size - total;
1911 *lace_buf = lace_size;
1917 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
1918 MatroskaTrack *track,
1920 uint8_t *data, int size,
1921 uint64_t timecode, uint64_t duration,
1924 int a = st->codec->block_align;
1925 int sps = track->audio.sub_packet_size;
1926 int cfs = track->audio.coded_framesize;
1927 int h = track->audio.sub_packet_h;
1928 int y = track->audio.sub_packet_cnt;
1929 int w = track->audio.frame_size;
1932 if (!track->audio.pkt_cnt) {
1933 if (track->audio.sub_packet_cnt == 0)
1934 track->audio.buf_timecode = timecode;
1935 if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
1936 if (size < cfs * h / 2) {
1937 av_log(matroska->ctx, AV_LOG_ERROR,
1938 "Corrupt int4 RM-style audio packet size\n");
1939 return AVERROR_INVALIDDATA;
1941 for (x=0; x<h/2; x++)
1942 memcpy(track->audio.buf+x*2*w+y*cfs,
1944 } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
1946 av_log(matroska->ctx, AV_LOG_ERROR,
1947 "Corrupt sipr RM-style audio packet size\n");
1948 return AVERROR_INVALIDDATA;
1950 memcpy(track->audio.buf + y*w, data, w);
1952 if (size < sps * w / sps) {
1953 av_log(matroska->ctx, AV_LOG_ERROR,
1954 "Corrupt generic RM-style audio packet size\n");
1955 return AVERROR_INVALIDDATA;
1957 for (x=0; x<w/sps; x++)
1958 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1961 if (++track->audio.sub_packet_cnt >= h) {
1962 if (st->codec->codec_id == AV_CODEC_ID_SIPR)
1963 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1964 track->audio.sub_packet_cnt = 0;
1965 track->audio.pkt_cnt = h*w / a;
1969 while (track->audio.pkt_cnt) {
1970 AVPacket *pkt = av_mallocz(sizeof(AVPacket));
1971 av_new_packet(pkt, a);
1972 memcpy(pkt->data, track->audio.buf
1973 + a * (h*w / a - track->audio.pkt_cnt--), a);
1974 pkt->pts = track->audio.buf_timecode;
1975 track->audio.buf_timecode = AV_NOPTS_VALUE;
1977 pkt->stream_index = st->index;
1978 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1984 /* reconstruct full wavpack blocks from mangled matroska ones */
1985 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
1986 uint8_t **pdst, int *size)
1988 uint8_t *dst = NULL;
1993 int ret, offset = 0;
1995 if (srclen < 12 || track->stream->codec->extradata_size < 2)
1996 return AVERROR_INVALIDDATA;
1998 ver = AV_RL16(track->stream->codec->extradata);
2000 samples = AV_RL32(src);
2004 while (srclen >= 8) {
2009 uint32_t flags = AV_RL32(src);
2010 uint32_t crc = AV_RL32(src + 4);
2014 multiblock = (flags & 0x1800) != 0x1800;
2017 ret = AVERROR_INVALIDDATA;
2020 blocksize = AV_RL32(src);
2026 if (blocksize > srclen) {
2027 ret = AVERROR_INVALIDDATA;
2031 tmp = av_realloc(dst, dstlen + blocksize + 32);
2033 ret = AVERROR(ENOMEM);
2037 dstlen += blocksize + 32;
2039 AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
2040 AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
2041 AV_WL16(dst + offset + 8, ver); // version
2042 AV_WL16(dst + offset + 10, 0); // track/index_no
2043 AV_WL32(dst + offset + 12, 0); // total samples
2044 AV_WL32(dst + offset + 16, 0); // block index
2045 AV_WL32(dst + offset + 20, samples); // number of samples
2046 AV_WL32(dst + offset + 24, flags); // flags
2047 AV_WL32(dst + offset + 28, crc); // crc
2048 memcpy (dst + offset + 32, src, blocksize); // block data
2051 srclen -= blocksize;
2052 offset += blocksize + 32;
2065 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2066 MatroskaTrack *track,
2068 uint8_t *data, int pkt_size,
2069 uint64_t timecode, uint64_t duration,
2070 int64_t pos, int is_keyframe)
2072 MatroskaTrackEncoding *encodings = track->encodings.elem;
2073 uint8_t *pkt_data = data;
2074 int offset = 0, res;
2077 if (encodings && encodings->scope & 1) {
2078 res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2083 if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
2085 res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2087 av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
2090 if (pkt_data != data)
2091 av_freep(&pkt_data);
2095 if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2098 pkt = av_mallocz(sizeof(AVPacket));
2099 /* XXX: prevent data copy... */
2100 if (av_new_packet(pkt, pkt_size + offset) < 0) {
2102 return AVERROR(ENOMEM);
2105 if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2106 uint8_t *buf = pkt->data;
2107 bytestream_put_be32(&buf, pkt_size);
2108 bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2111 memcpy(pkt->data + offset, pkt_data, pkt_size);
2113 if (pkt_data != data)
2116 pkt->flags = is_keyframe;
2117 pkt->stream_index = st->index;
2119 if (track->ms_compat)
2120 pkt->dts = timecode;
2122 pkt->pts = timecode;
2124 if (st->codec->codec_id == AV_CODEC_ID_TEXT)
2125 pkt->convergence_duration = duration;
2126 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
2127 pkt->duration = duration;
2129 if (st->codec->codec_id == AV_CODEC_ID_SSA)
2130 matroska_fix_ass_packet(matroska, pkt, duration);
2132 if (matroska->prev_pkt &&
2133 timecode != AV_NOPTS_VALUE &&
2134 matroska->prev_pkt->pts == timecode &&
2135 matroska->prev_pkt->stream_index == st->index &&
2136 st->codec->codec_id == AV_CODEC_ID_SSA)
2137 matroska_merge_packets(matroska->prev_pkt, pkt);
2139 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2140 matroska->prev_pkt = pkt;
2145 if (pkt_data != data)
2146 av_freep(&pkt_data);
2150 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2151 int size, int64_t pos, uint64_t cluster_time,
2152 uint64_t block_duration, int is_keyframe,
2153 int64_t cluster_pos)
2155 uint64_t timecode = AV_NOPTS_VALUE;
2156 MatroskaTrack *track;
2160 uint32_t *lace_size = NULL;
2161 int n, flags, laces = 0;
2162 uint64_t num, duration;
2164 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2165 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2171 track = matroska_find_track_by_num(matroska, num);
2172 if (!track || !track->stream) {
2173 av_log(matroska->ctx, AV_LOG_INFO,
2174 "Invalid stream %"PRIu64" or size %u\n", num, size);
2175 return AVERROR_INVALIDDATA;
2176 } else if (size <= 3)
2179 if (st->discard >= AVDISCARD_ALL)
2182 block_time = AV_RB16(data);
2186 if (is_keyframe == -1)
2187 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2189 if (cluster_time != (uint64_t)-1
2190 && (block_time >= 0 || cluster_time >= -block_time)) {
2191 timecode = cluster_time + block_time;
2192 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2193 && timecode < track->end_timecode)
2194 is_keyframe = 0; /* overlapping subtitles are not key frame */
2196 av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2199 if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2200 if (!is_keyframe || timecode < matroska->skip_to_timecode)
2202 matroska->skip_to_keyframe = 0;
2205 res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2206 &lace_size, &laces);
2211 if (block_duration != AV_NOPTS_VALUE) {
2212 duration = block_duration / laces;
2213 if (block_duration != duration * laces) {
2214 av_log(matroska->ctx, AV_LOG_WARNING,
2215 "Incorrect block_duration, possibly corrupted container");
2218 duration = track->default_duration / matroska->time_scale;
2219 block_duration = duration * laces;
2222 if (timecode != AV_NOPTS_VALUE)
2223 track->end_timecode =
2224 FFMAX(track->end_timecode, timecode + block_duration);
2226 for (n = 0; n < laces; n++) {
2227 if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2228 st->codec->codec_id == AV_CODEC_ID_COOK ||
2229 st->codec->codec_id == AV_CODEC_ID_SIPR ||
2230 st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2231 st->codec->block_align && track->audio.sub_packet_size) {
2233 res = matroska_parse_rm_audio(matroska, track, st, data,
2235 timecode, duration, pos);
2240 res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2242 pos, !n? is_keyframe : 0);
2247 if (timecode != AV_NOPTS_VALUE)
2248 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2249 data += lace_size[n];
2257 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2259 EbmlList *blocks_list;
2260 MatroskaBlock *blocks;
2262 res = ebml_parse(matroska,
2263 matroska_cluster_incremental_parsing,
2264 &matroska->current_cluster);
2267 if (matroska->current_cluster_pos)
2268 ebml_level_end(matroska);
2269 ebml_free(matroska_cluster, &matroska->current_cluster);
2270 memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2271 matroska->current_cluster_num_blocks = 0;
2272 matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2273 matroska->prev_pkt = NULL;
2274 /* sizeof the ID which was already read */
2275 if (matroska->current_id)
2276 matroska->current_cluster_pos -= 4;
2277 res = ebml_parse(matroska,
2278 matroska_clusters_incremental,
2279 &matroska->current_cluster);
2280 /* Try parsing the block again. */
2282 res = ebml_parse(matroska,
2283 matroska_cluster_incremental_parsing,
2284 &matroska->current_cluster);
2288 matroska->current_cluster_num_blocks <
2289 matroska->current_cluster.blocks.nb_elem) {
2290 blocks_list = &matroska->current_cluster.blocks;
2291 blocks = blocks_list->elem;
2293 matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2294 i = blocks_list->nb_elem - 1;
2295 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2296 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2297 if (!blocks[i].non_simple)
2298 blocks[i].duration = AV_NOPTS_VALUE;
2299 res = matroska_parse_block(matroska,
2300 blocks[i].bin.data, blocks[i].bin.size,
2302 matroska->current_cluster.timecode,
2303 blocks[i].duration, is_keyframe,
2304 matroska->current_cluster_pos);
2308 if (res < 0) matroska->done = 1;
2312 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2314 MatroskaCluster cluster = { 0 };
2315 EbmlList *blocks_list;
2316 MatroskaBlock *blocks;
2319 if (!matroska->contains_ssa)
2320 return matroska_parse_cluster_incremental(matroska);
2321 pos = avio_tell(matroska->ctx->pb);
2322 matroska->prev_pkt = NULL;
2323 if (matroska->current_id)
2324 pos -= 4; /* sizeof the ID which was already read */
2325 res = ebml_parse(matroska, matroska_clusters, &cluster);
2326 blocks_list = &cluster.blocks;
2327 blocks = blocks_list->elem;
2328 for (i=0; i<blocks_list->nb_elem && !res; i++)
2329 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2330 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2331 if (!blocks[i].non_simple)
2332 blocks[i].duration = AV_NOPTS_VALUE;
2333 res=matroska_parse_block(matroska,
2334 blocks[i].bin.data, blocks[i].bin.size,
2335 blocks[i].bin.pos, cluster.timecode,
2336 blocks[i].duration, is_keyframe,
2339 ebml_free(matroska_cluster, &cluster);
2343 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2345 MatroskaDemuxContext *matroska = s->priv_data;
2348 while (!ret && matroska_deliver_packet(matroska, pkt)) {
2349 int64_t pos = avio_tell(matroska->ctx->pb);
2352 if (matroska_parse_cluster(matroska) < 0)
2353 ret = matroska_resync(matroska, pos);
2356 if (ret == AVERROR_INVALIDDATA && pkt->data) {
2357 pkt->flags |= AV_PKT_FLAG_CORRUPT;
2364 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2365 int64_t timestamp, int flags)
2367 MatroskaDemuxContext *matroska = s->priv_data;
2368 MatroskaTrack *tracks = matroska->tracks.elem;
2369 AVStream *st = s->streams[stream_index];
2370 int i, index, index_sub, index_min;
2372 /* Parse the CUES now since we need the index data to seek. */
2373 if (matroska->cues_parsing_deferred) {
2374 matroska_parse_cues(matroska);
2375 matroska->cues_parsing_deferred = 0;
2378 if (!st->nb_index_entries)
2380 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2382 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2383 avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2384 matroska->current_id = 0;
2385 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2386 matroska_clear_queue(matroska);
2387 if (matroska_parse_cluster(matroska) < 0)
2392 matroska_clear_queue(matroska);
2397 for (i=0; i < matroska->tracks.nb_elem; i++) {
2398 tracks[i].audio.pkt_cnt = 0;
2399 tracks[i].audio.sub_packet_cnt = 0;
2400 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2401 tracks[i].end_timecode = 0;
2402 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2403 && !tracks[i].stream->discard != AVDISCARD_ALL) {
2404 index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2406 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2407 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2408 index_min = index_sub;
2412 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2413 matroska->current_id = 0;
2414 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2415 matroska->skip_to_timecode = st->index_entries[index].timestamp;
2417 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2421 static int matroska_read_close(AVFormatContext *s)
2423 MatroskaDemuxContext *matroska = s->priv_data;
2424 MatroskaTrack *tracks = matroska->tracks.elem;
2427 matroska_clear_queue(matroska);
2429 for (n=0; n < matroska->tracks.nb_elem; n++)
2430 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2431 av_free(tracks[n].audio.buf);
2432 ebml_free(matroska_cluster, &matroska->current_cluster);
2433 ebml_free(matroska_segment, matroska);
2438 AVInputFormat ff_matroska_demuxer = {
2439 .name = "matroska,webm",
2440 .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2441 .priv_data_size = sizeof(MatroskaDemuxContext),
2442 .read_probe = matroska_probe,
2443 .read_header = matroska_read_header,
2444 .read_packet = matroska_read_packet,
2445 .read_close = matroska_read_close,
2446 .read_seek = matroska_read_seek,