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 * @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/base64.h"
43 #include "libavutil/intfloat.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/lzo.h"
47 #include "libavutil/dict.h"
69 typedef const struct EbmlSyntax {
78 const struct EbmlSyntax *n;
98 uint64_t doctype_version;
104 } MatroskaTrackCompression;
109 } MatroskaTrackEncryption;
114 MatroskaTrackCompression compression;
115 MatroskaTrackEncryption encryption;
116 } MatroskaTrackEncoding;
120 uint64_t display_width;
121 uint64_t display_height;
122 uint64_t pixel_width;
123 uint64_t pixel_height;
125 uint64_t stereo_mode;
127 } MatroskaTrackVideo;
131 double out_samplerate;
135 /* real audio header (extracted from extradata) */
142 uint64_t buf_timecode;
144 } MatroskaTrackAudio;
149 } MatroskaTrackPlane;
152 EbmlList combine_planes;
153 } MatroskaTrackOperation;
164 uint64_t default_duration;
165 uint64_t flag_default;
166 uint64_t flag_forced;
167 uint64_t codec_delay;
168 uint64_t seek_preroll;
169 MatroskaTrackVideo video;
170 MatroskaTrackAudio audio;
171 MatroskaTrackOperation operation;
175 int64_t end_timecode;
177 uint64_t max_block_additional_id;
187 } MatroskaAttachement;
225 MatroskaTagTarget target;
245 AVFormatContext *ctx;
249 MatroskaLevel levels[EBML_MAX_DEPTH];
259 EbmlList attachments;
265 /* byte position of the segment inside the stream */
266 int64_t segment_start;
268 /* the packet queue */
275 /* What to skip before effectively reading a packet. */
276 int skip_to_keyframe;
277 uint64_t skip_to_timecode;
279 /* File has a CUES element, but we defer parsing until it is needed. */
280 int cues_parsing_deferred;
282 int current_cluster_num_blocks;
283 int64_t current_cluster_pos;
284 MatroskaCluster current_cluster;
286 /* File has SSA subtitles which prevent incremental cluster parsing. */
288 } MatroskaDemuxContext;
295 uint64_t additional_id;
297 int64_t discard_padding;
300 static EbmlSyntax ebml_header[] = {
301 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
302 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
303 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
304 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
305 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
306 { EBML_ID_EBMLVERSION, EBML_NONE },
307 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
311 static EbmlSyntax ebml_syntax[] = {
312 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
316 static EbmlSyntax matroska_info[] = {
317 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
318 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
319 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
320 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
321 { MATROSKA_ID_MUXINGAPP, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,muxingapp) },
322 { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext,date_utc) },
323 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
327 static EbmlSyntax matroska_track_video[] = {
328 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
329 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width), {.u=-1} },
330 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height), {.u=-1} },
331 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
332 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
333 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
334 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
335 { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,alpha_mode) },
336 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
337 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
338 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
339 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
340 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
341 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
342 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
346 static EbmlSyntax matroska_track_audio[] = {
347 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
348 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
349 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
350 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
354 static EbmlSyntax matroska_track_encoding_compression[] = {
355 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
356 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
360 static EbmlSyntax matroska_track_encoding_encryption[] = {
361 { MATROSKA_ID_ENCODINGENCALGO, EBML_UINT, 0, offsetof(MatroskaTrackEncryption,algo), {.u=0} },
362 { MATROSKA_ID_ENCODINGENCKEYID, EBML_BIN, 0, offsetof(MatroskaTrackEncryption,key_id) },
363 { MATROSKA_ID_ENCODINGENCAESSETTINGS, EBML_NONE },
364 { MATROSKA_ID_ENCODINGSIGALGO, EBML_NONE },
365 { MATROSKA_ID_ENCODINGSIGHASHALGO, EBML_NONE },
366 { MATROSKA_ID_ENCODINGSIGKEYID, EBML_NONE },
367 { MATROSKA_ID_ENCODINGSIGNATURE, EBML_NONE },
370 static EbmlSyntax matroska_track_encoding[] = {
371 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
372 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
373 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
374 { MATROSKA_ID_ENCODINGENCRYPTION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding,encryption), {.n=matroska_track_encoding_encryption} },
375 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
379 static EbmlSyntax matroska_track_encodings[] = {
380 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
384 static EbmlSyntax matroska_track_plane[] = {
385 { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
386 { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
390 static EbmlSyntax matroska_track_combine_planes[] = {
391 { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
395 static EbmlSyntax matroska_track_operation[] = {
396 { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
400 static EbmlSyntax matroska_track[] = {
401 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
402 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
403 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
404 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
405 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
406 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
407 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
408 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
409 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
410 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
411 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
412 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
413 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
414 { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
415 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
416 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, offsetof(MatroskaTrack,max_block_additional_id) },
417 { MATROSKA_ID_CODECDELAY, EBML_UINT, 0, offsetof(MatroskaTrack,codec_delay) },
418 { MATROSKA_ID_SEEKPREROLL, EBML_UINT, 0, offsetof(MatroskaTrack,seek_preroll) },
419 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
420 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
421 { MATROSKA_ID_CODECNAME, EBML_NONE },
422 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
423 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
424 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
425 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
426 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
430 static EbmlSyntax matroska_tracks[] = {
431 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
435 static EbmlSyntax matroska_attachment[] = {
436 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
437 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
438 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
439 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
440 { MATROSKA_ID_FILEDESC, EBML_NONE },
444 static EbmlSyntax matroska_attachments[] = {
445 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
449 static EbmlSyntax matroska_chapter_display[] = {
450 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
451 { MATROSKA_ID_CHAPLANG, EBML_NONE },
455 static EbmlSyntax matroska_chapter_entry[] = {
456 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
457 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
458 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
459 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
460 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
461 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
462 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
463 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
467 static EbmlSyntax matroska_chapter[] = {
468 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
469 { MATROSKA_ID_EDITIONUID, EBML_NONE },
470 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
471 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
472 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
476 static EbmlSyntax matroska_chapters[] = {
477 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
481 static EbmlSyntax matroska_index_pos[] = {
482 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
483 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
484 { MATROSKA_ID_CUERELATIVEPOSITION,EBML_NONE },
485 { MATROSKA_ID_CUEDURATION, EBML_NONE },
486 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
490 static EbmlSyntax matroska_index_entry[] = {
491 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
492 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
496 static EbmlSyntax matroska_index[] = {
497 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
501 static EbmlSyntax matroska_simpletag[] = {
502 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
503 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
504 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
505 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
506 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
507 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
511 static EbmlSyntax matroska_tagtargets[] = {
512 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
513 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
514 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
515 { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
516 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
520 static EbmlSyntax matroska_tag[] = {
521 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
522 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
526 static EbmlSyntax matroska_tags[] = {
527 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
531 static EbmlSyntax matroska_seekhead_entry[] = {
532 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
533 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
537 static EbmlSyntax matroska_seekhead[] = {
538 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
542 static EbmlSyntax matroska_segment[] = {
543 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
544 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
545 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
546 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
547 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
548 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
549 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
550 { MATROSKA_ID_CLUSTER, EBML_STOP },
554 static EbmlSyntax matroska_segments[] = {
555 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
559 static EbmlSyntax matroska_blockmore[] = {
560 { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
561 { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) },
565 static EbmlSyntax matroska_blockadditions[] = {
566 { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n=matroska_blockmore} },
570 static EbmlSyntax matroska_blockgroup[] = {
571 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
572 { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, {.n=matroska_blockadditions} },
573 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
574 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
575 { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, offsetof(MatroskaBlock,discard_padding) },
576 { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock,reference) },
577 { MATROSKA_ID_CODECSTATE, EBML_NONE },
578 { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
582 static EbmlSyntax matroska_cluster[] = {
583 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
584 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
585 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
586 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
587 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
591 static EbmlSyntax matroska_clusters[] = {
592 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
593 { MATROSKA_ID_INFO, EBML_NONE },
594 { MATROSKA_ID_CUES, EBML_NONE },
595 { MATROSKA_ID_TAGS, EBML_NONE },
596 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
600 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
601 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
602 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
603 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
604 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
605 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
606 { MATROSKA_ID_INFO, EBML_NONE },
607 { MATROSKA_ID_CUES, EBML_NONE },
608 { MATROSKA_ID_TAGS, EBML_NONE },
609 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
610 { MATROSKA_ID_CLUSTER, EBML_STOP },
614 static EbmlSyntax matroska_cluster_incremental[] = {
615 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
616 { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
617 { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
618 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
619 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
623 static EbmlSyntax matroska_clusters_incremental[] = {
624 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
625 { MATROSKA_ID_INFO, EBML_NONE },
626 { MATROSKA_ID_CUES, EBML_NONE },
627 { MATROSKA_ID_TAGS, EBML_NONE },
628 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
632 static const char *const matroska_doctypes[] = { "matroska", "webm" };
634 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
636 AVIOContext *pb = matroska->ctx->pb;
638 matroska->current_id = 0;
639 matroska->num_levels = 0;
641 /* seek to next position to resync from */
642 if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
647 // try to find a toplevel element
648 while (!url_feof(pb)) {
649 if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
650 id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
651 id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
652 id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
653 matroska->current_id = id;
656 id = (id << 8) | avio_r8(pb);
664 * Return: Whether we reached the end of a level in the hierarchy or not.
666 static int ebml_level_end(MatroskaDemuxContext *matroska)
668 AVIOContext *pb = matroska->ctx->pb;
669 int64_t pos = avio_tell(pb);
671 if (matroska->num_levels > 0) {
672 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
673 if (pos - level->start >= level->length || matroska->current_id) {
674 matroska->num_levels--;
682 * Read: an "EBML number", which is defined as a variable-length
683 * array of bytes. The first byte indicates the length by giving a
684 * number of 0-bits followed by a one. The position of the first
685 * "one" bit inside the first byte indicates the length of this
687 * Returns: number of bytes read, < 0 on error
689 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
690 int max_size, uint64_t *number)
695 /* The first byte tells us the length in bytes - avio_r8() can normally
696 * return 0, but since that's not a valid first ebmlID byte, we can
697 * use it safely here to catch EOS. */
698 if (!(total = avio_r8(pb))) {
699 /* we might encounter EOS here */
701 int64_t pos = avio_tell(pb);
702 av_log(matroska->ctx, AV_LOG_ERROR,
703 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
705 return pb->error ? pb->error : AVERROR(EIO);
710 /* get the length of the EBML number */
711 read = 8 - ff_log2_tab[total];
712 if (read > max_size) {
713 int64_t pos = avio_tell(pb) - 1;
714 av_log(matroska->ctx, AV_LOG_ERROR,
715 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
716 (uint8_t) total, pos, pos);
717 return AVERROR_INVALIDDATA;
720 /* read out length */
721 total ^= 1 << ff_log2_tab[total];
723 total = (total << 8) | avio_r8(pb);
731 * Read a EBML length value.
732 * This needs special handling for the "unknown length" case which has multiple
735 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
738 int res = ebml_read_num(matroska, pb, 8, number);
739 if (res > 0 && *number + 1 == 1ULL << (7 * res))
740 *number = 0xffffffffffffffULL;
745 * Read the next element as an unsigned int.
746 * 0 is success, < 0 is failure.
748 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
753 return AVERROR_INVALIDDATA;
755 /* big-endian ordering; build up number */
758 *num = (*num << 8) | avio_r8(pb);
764 * Read the next element as a signed int.
765 * 0 is success, < 0 is failure.
767 static int ebml_read_sint(AVIOContext *pb, int size, int64_t *num)
772 return AVERROR_INVALIDDATA;
777 *num = sign_extend(avio_r8(pb), 8);
779 /* big-endian ordering; build up number */
781 *num = (*num << 8) | avio_r8(pb);
788 * Read the next element as a float.
789 * 0 is success, < 0 is failure.
791 static int ebml_read_float(AVIOContext *pb, int size, double *num)
795 } else if (size == 4) {
796 *num = av_int2float(avio_rb32(pb));
797 } else if (size == 8){
798 *num = av_int2double(avio_rb64(pb));
800 return AVERROR_INVALIDDATA;
806 * Read the next element as an ASCII string.
807 * 0 is success, < 0 is failure.
809 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
813 /* EBML strings are usually not 0-terminated, so we allocate one
814 * byte more, read the string and NULL-terminate it ourselves. */
815 if (!(res = av_malloc(size + 1)))
816 return AVERROR(ENOMEM);
817 if (avio_read(pb, (uint8_t *) res, size) != size) {
829 * Read the next element as binary data.
830 * 0 is success, < 0 is failure.
832 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
834 av_fast_padded_malloc(&bin->data, &bin->size, length);
836 return AVERROR(ENOMEM);
839 bin->pos = avio_tell(pb);
840 if (avio_read(pb, bin->data, length) != length) {
841 av_freep(&bin->data);
850 * Read the next element, but only the header. The contents
851 * are supposed to be sub-elements which can be read separately.
852 * 0 is success, < 0 is failure.
854 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
856 AVIOContext *pb = matroska->ctx->pb;
857 MatroskaLevel *level;
859 if (matroska->num_levels >= EBML_MAX_DEPTH) {
860 av_log(matroska->ctx, AV_LOG_ERROR,
861 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
862 return AVERROR(ENOSYS);
865 level = &matroska->levels[matroska->num_levels++];
866 level->start = avio_tell(pb);
867 level->length = length;
873 * Read signed/unsigned "EBML" numbers.
874 * Return: number of bytes processed, < 0 on error
876 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
877 uint8_t *data, uint32_t size, uint64_t *num)
880 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
881 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
885 * Same as above, but signed.
887 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
888 uint8_t *data, uint32_t size, int64_t *num)
893 /* read as unsigned number first */
894 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
897 /* make signed (weird way) */
898 *num = unum - ((1LL << (7*res - 1)) - 1);
903 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
904 EbmlSyntax *syntax, void *data);
906 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
907 uint32_t id, void *data)
910 for (i=0; syntax[i].id; i++)
911 if (id == syntax[i].id)
913 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
914 matroska->num_levels > 0 &&
915 matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
916 return 0; // we reached the end of an unknown size cluster
917 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
918 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
919 if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
920 return AVERROR_INVALIDDATA;
922 return ebml_parse_elem(matroska, &syntax[i], data);
925 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
928 if (!matroska->current_id) {
930 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
933 matroska->current_id = id | 1 << 7*res;
935 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
938 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
943 for (i=0; syntax[i].id; i++)
944 switch (syntax[i].type) {
946 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
949 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
953 // the default may be NULL
954 if (syntax[i].def.s) {
955 uint8_t **dst = (uint8_t**)((uint8_t*)data + syntax[i].data_offset);
956 *dst = av_strdup(syntax[i].def.s);
958 return AVERROR(ENOMEM);
963 while (!res && !ebml_level_end(matroska))
964 res = ebml_parse(matroska, syntax, data);
969 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
970 EbmlSyntax *syntax, void *data)
972 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
975 // max. 16 MB for strings
976 [EBML_STR] = 0x1000000,
977 [EBML_UTF8] = 0x1000000,
978 // max. 256 MB for binary data
979 [EBML_BIN] = 0x10000000,
980 // no limits for anything else
982 AVIOContext *pb = matroska->ctx->pb;
983 uint32_t id = syntax->id;
988 data = (char *)data + syntax->data_offset;
989 if (syntax->list_elem_size) {
990 EbmlList *list = data;
991 newelem = av_realloc_array(list->elem, list->nb_elem+1, syntax->list_elem_size);
993 return AVERROR(ENOMEM);
994 list->elem = newelem;
995 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
996 memset(data, 0, syntax->list_elem_size);
1000 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
1001 matroska->current_id = 0;
1002 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
1004 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
1005 av_log(matroska->ctx, AV_LOG_ERROR,
1006 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
1007 length, max_lengths[syntax->type], syntax->type);
1008 return AVERROR_INVALIDDATA;
1012 switch (syntax->type) {
1013 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
1014 case EBML_SINT: res = ebml_read_sint (pb, length, data); break;
1015 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
1017 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
1018 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
1019 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
1021 if (id == MATROSKA_ID_SEGMENT)
1022 matroska->segment_start = avio_tell(matroska->ctx->pb);
1023 return ebml_parse_nest(matroska, syntax->def.n, data);
1024 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
1025 case EBML_STOP: return 1;
1027 if(ffio_limit(pb, length) != length)
1028 return AVERROR(EIO);
1029 return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
1031 if (res == AVERROR_INVALIDDATA)
1032 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
1033 else if (res == AVERROR(EIO))
1034 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
1038 static void ebml_free(EbmlSyntax *syntax, void *data)
1041 for (i=0; syntax[i].id; i++) {
1042 void *data_off = (char *)data + syntax[i].data_offset;
1043 switch (syntax[i].type) {
1045 case EBML_UTF8: av_freep(data_off); break;
1046 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
1048 if (syntax[i].list_elem_size) {
1049 EbmlList *list = data_off;
1050 char *ptr = list->elem;
1051 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1052 ebml_free(syntax[i].def.n, ptr);
1053 av_free(list->elem);
1055 ebml_free(syntax[i].def.n, data_off);
1065 static int matroska_probe(AVProbeData *p)
1068 int len_mask = 0x80, size = 1, n = 1, i;
1071 if (AV_RB32(p->buf) != EBML_ID_HEADER)
1074 /* length of header */
1076 while (size <= 8 && !(total & len_mask)) {
1082 total &= (len_mask - 1);
1084 total = (total << 8) | p->buf[4 + n++];
1086 /* Does the probe data contain the whole header? */
1087 if (p->buf_size < 4 + size + total)
1090 /* The header should contain a known document type. For now,
1091 * we don't parse the whole header but simply check for the
1092 * availability of that array of characters inside the header.
1093 * Not fully fool-proof, but good enough. */
1094 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1095 int probelen = strlen(matroska_doctypes[i]);
1096 if (total < probelen)
1098 for (n = 4+size; n <= 4+size+total-probelen; n++)
1099 if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
1100 return AVPROBE_SCORE_MAX;
1103 // probably valid EBML header but no recognized doctype
1104 return AVPROBE_SCORE_EXTENSION;
1107 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1110 MatroskaTrack *tracks = matroska->tracks.elem;
1113 for (i=0; i < matroska->tracks.nb_elem; i++)
1114 if (tracks[i].num == num)
1117 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1121 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1122 MatroskaTrack *track)
1124 MatroskaTrackEncoding *encodings = track->encodings.elem;
1125 uint8_t* data = *buf;
1126 int isize = *buf_size;
1127 uint8_t* pkt_data = NULL;
1128 uint8_t av_unused *newpktdata;
1129 int pkt_size = isize;
1133 if (pkt_size >= 10000000U)
1134 return AVERROR_INVALIDDATA;
1136 switch (encodings[0].compression.algo) {
1137 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
1138 int header_size = encodings[0].compression.settings.size;
1139 uint8_t *header = encodings[0].compression.settings.data;
1141 if (header_size && !header) {
1142 av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1149 pkt_size = isize + header_size;
1150 pkt_data = av_malloc(pkt_size);
1152 return AVERROR(ENOMEM);
1154 memcpy(pkt_data, header, header_size);
1155 memcpy(pkt_data + header_size, data, isize);
1159 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1161 olen = pkt_size *= 3;
1162 newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1164 result = AVERROR(ENOMEM);
1167 pkt_data = newpktdata;
1168 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1169 } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1171 result = AVERROR_INVALIDDATA;
1178 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1179 z_stream zstream = {0};
1180 if (inflateInit(&zstream) != Z_OK)
1182 zstream.next_in = data;
1183 zstream.avail_in = isize;
1186 newpktdata = av_realloc(pkt_data, pkt_size);
1188 inflateEnd(&zstream);
1191 pkt_data = newpktdata;
1192 zstream.avail_out = pkt_size - zstream.total_out;
1193 zstream.next_out = pkt_data + zstream.total_out;
1195 result = inflate(&zstream, Z_NO_FLUSH);
1197 result = Z_MEM_ERROR;
1198 } while (result==Z_OK && pkt_size<10000000);
1199 pkt_size = zstream.total_out;
1200 inflateEnd(&zstream);
1201 if (result != Z_STREAM_END) {
1202 if (result == Z_MEM_ERROR)
1203 result = AVERROR(ENOMEM);
1205 result = AVERROR_INVALIDDATA;
1212 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1213 bz_stream bzstream = {0};
1214 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1216 bzstream.next_in = data;
1217 bzstream.avail_in = isize;
1220 newpktdata = av_realloc(pkt_data, pkt_size);
1222 BZ2_bzDecompressEnd(&bzstream);
1225 pkt_data = newpktdata;
1226 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1227 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1229 result = BZ2_bzDecompress(&bzstream);
1231 result = BZ_MEM_ERROR;
1232 } while (result==BZ_OK && pkt_size<10000000);
1233 pkt_size = bzstream.total_out_lo32;
1234 BZ2_bzDecompressEnd(&bzstream);
1235 if (result != BZ_STREAM_END) {
1236 if (result == BZ_MEM_ERROR)
1237 result = AVERROR(ENOMEM);
1239 result = AVERROR_INVALIDDATA;
1246 return AVERROR_INVALIDDATA;
1250 *buf_size = pkt_size;
1258 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1259 AVPacket *pkt, uint64_t display_duration)
1262 char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1263 for (; *ptr!=',' && ptr<end-1; ptr++);
1267 for (; *ptr!=',' && ptr<end-1; ptr++);
1269 int64_t end_pts = pkt->pts + display_duration;
1270 int sc = matroska->time_scale * pkt->pts / 10000000;
1271 int ec = matroska->time_scale * end_pts / 10000000;
1272 int sh, sm, ss, eh, em, es, len;
1273 sh = sc/360000; sc -= 360000*sh;
1274 sm = sc/ 6000; sc -= 6000*sm;
1275 ss = sc/ 100; sc -= 100*ss;
1276 eh = ec/360000; ec -= 360000*eh;
1277 em = ec/ 6000; ec -= 6000*em;
1278 es = ec/ 100; ec -= 100*es;
1280 len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1281 if (!(line = av_buffer_alloc(len)))
1283 snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1284 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1285 av_buffer_unref(&pkt->buf);
1287 pkt->data = line->data;
1288 pkt->size = strlen(line->data);
1292 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1294 int ret = av_grow_packet(out, in->size);
1298 memcpy(out->data + out->size - in->size, in->data, in->size);
1306 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1307 AVDictionary **metadata, char *prefix)
1309 MatroskaTag *tags = list->elem;
1313 for (i=0; i < list->nb_elem; i++) {
1314 const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
1315 tags[i].lang : NULL;
1317 if (!tags[i].name) {
1318 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1321 if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1322 else av_strlcpy(key, tags[i].name, sizeof(key));
1323 if (tags[i].def || !lang) {
1324 av_dict_set(metadata, key, tags[i].string, 0);
1325 if (tags[i].sub.nb_elem)
1326 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1329 av_strlcat(key, "-", sizeof(key));
1330 av_strlcat(key, lang, sizeof(key));
1331 av_dict_set(metadata, key, tags[i].string, 0);
1332 if (tags[i].sub.nb_elem)
1333 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1336 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1339 static void matroska_convert_tags(AVFormatContext *s)
1341 MatroskaDemuxContext *matroska = s->priv_data;
1342 MatroskaTags *tags = matroska->tags.elem;
1345 for (i=0; i < matroska->tags.nb_elem; i++) {
1346 if (tags[i].target.attachuid) {
1347 MatroskaAttachement *attachment = matroska->attachments.elem;
1348 for (j=0; j<matroska->attachments.nb_elem; j++)
1349 if (attachment[j].uid == tags[i].target.attachuid
1350 && attachment[j].stream)
1351 matroska_convert_tag(s, &tags[i].tag,
1352 &attachment[j].stream->metadata, NULL);
1353 } else if (tags[i].target.chapteruid) {
1354 MatroskaChapter *chapter = matroska->chapters.elem;
1355 for (j=0; j<matroska->chapters.nb_elem; j++)
1356 if (chapter[j].uid == tags[i].target.chapteruid
1357 && chapter[j].chapter)
1358 matroska_convert_tag(s, &tags[i].tag,
1359 &chapter[j].chapter->metadata, NULL);
1360 } else if (tags[i].target.trackuid) {
1361 MatroskaTrack *track = matroska->tracks.elem;
1362 for (j=0; j<matroska->tracks.nb_elem; j++)
1363 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1364 matroska_convert_tag(s, &tags[i].tag,
1365 &track[j].stream->metadata, NULL);
1367 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1368 tags[i].target.type);
1373 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1375 EbmlList *seekhead_list = &matroska->seekhead;
1376 MatroskaSeekhead *seekhead = seekhead_list->elem;
1377 uint32_t level_up = matroska->level_up;
1378 int64_t before_pos = avio_tell(matroska->ctx->pb);
1379 uint32_t saved_id = matroska->current_id;
1380 MatroskaLevel level;
1384 if (idx >= seekhead_list->nb_elem
1385 || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1386 || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1390 offset = seekhead[idx].pos + matroska->segment_start;
1391 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1392 /* We don't want to lose our seekhead level, so we add
1393 * a dummy. This is a crude hack. */
1394 if (matroska->num_levels == EBML_MAX_DEPTH) {
1395 av_log(matroska->ctx, AV_LOG_INFO,
1396 "Max EBML element depth (%d) reached, "
1397 "cannot parse further.\n", EBML_MAX_DEPTH);
1398 ret = AVERROR_INVALIDDATA;
1401 level.length = (uint64_t)-1;
1402 matroska->levels[matroska->num_levels] = level;
1403 matroska->num_levels++;
1404 matroska->current_id = 0;
1406 ret = ebml_parse(matroska, matroska_segment, matroska);
1408 /* remove dummy level */
1409 while (matroska->num_levels) {
1410 uint64_t length = matroska->levels[--matroska->num_levels].length;
1411 if (length == (uint64_t)-1)
1417 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1418 matroska->level_up = level_up;
1419 matroska->current_id = saved_id;
1424 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1426 EbmlList *seekhead_list = &matroska->seekhead;
1427 int64_t before_pos = avio_tell(matroska->ctx->pb);
1430 // we should not do any seeking in the streaming case
1431 if (!matroska->ctx->pb->seekable ||
1432 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1435 for (i = 0; i < seekhead_list->nb_elem; i++) {
1436 MatroskaSeekhead *seekhead = seekhead_list->elem;
1437 if (seekhead[i].pos <= before_pos)
1440 // defer cues parsing until we actually need cue data.
1441 if (seekhead[i].id == MATROSKA_ID_CUES) {
1442 matroska->cues_parsing_deferred = 1;
1446 if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1447 // mark index as broken
1448 matroska->cues_parsing_deferred = -1;
1454 static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
1455 EbmlList *index_list;
1456 MatroskaIndex *index;
1457 int index_scale = 1;
1460 index_list = &matroska->index;
1461 index = index_list->elem;
1462 if (index_list->nb_elem
1463 && index[0].time > 1E14/matroska->time_scale) {
1464 av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1465 index_scale = matroska->time_scale;
1467 for (i = 0; i < index_list->nb_elem; i++) {
1468 EbmlList *pos_list = &index[i].pos;
1469 MatroskaIndexPos *pos = pos_list->elem;
1470 for (j = 0; j < pos_list->nb_elem; j++) {
1471 MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1472 if (track && track->stream)
1473 av_add_index_entry(track->stream,
1474 pos[j].pos + matroska->segment_start,
1475 index[i].time/index_scale, 0, 0,
1481 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1482 EbmlList *seekhead_list = &matroska->seekhead;
1483 MatroskaSeekhead *seekhead = seekhead_list->elem;
1486 for (i = 0; i < seekhead_list->nb_elem; i++)
1487 if (seekhead[i].id == MATROSKA_ID_CUES)
1489 av_assert1(i <= seekhead_list->nb_elem);
1491 if (matroska_parse_seekhead_entry(matroska, i) < 0)
1492 matroska->cues_parsing_deferred = -1;
1493 matroska_add_index_entries(matroska);
1496 static int matroska_aac_profile(char *codec_id)
1498 static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1501 for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1502 if (strstr(codec_id, aac_profiles[profile]))
1507 static int matroska_aac_sri(int samplerate)
1511 for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1512 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1517 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1520 /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1521 time_t creation_time = date_utc / 1000000000 + 978307200;
1522 struct tm *ptm = gmtime(&creation_time);
1524 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1525 av_dict_set(metadata, "creation_time", buffer, 0);
1528 static int matroska_read_header(AVFormatContext *s)
1530 MatroskaDemuxContext *matroska = s->priv_data;
1531 EbmlList *attachements_list = &matroska->attachments;
1532 MatroskaAttachement *attachements;
1533 EbmlList *chapters_list = &matroska->chapters;
1534 MatroskaChapter *chapters;
1535 MatroskaTrack *tracks;
1536 uint64_t max_start = 0;
1544 /* First read the EBML header. */
1545 if (ebml_parse(matroska, ebml_syntax, &ebml)
1546 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1547 || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
1548 av_log(matroska->ctx, AV_LOG_ERROR,
1549 "EBML header using unsupported features\n"
1550 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1551 ebml.version, ebml.doctype, ebml.doctype_version);
1552 ebml_free(ebml_syntax, &ebml);
1553 return AVERROR_PATCHWELCOME;
1554 } else if (ebml.doctype_version == 3) {
1555 av_log(matroska->ctx, AV_LOG_WARNING,
1556 "EBML header using unsupported features\n"
1557 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1558 ebml.version, ebml.doctype, ebml.doctype_version);
1560 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1561 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1563 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1564 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1565 if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1566 ebml_free(ebml_syntax, &ebml);
1567 return AVERROR_INVALIDDATA;
1570 ebml_free(ebml_syntax, &ebml);
1572 /* The next thing is a segment. */
1573 pos = avio_tell(matroska->ctx->pb);
1574 res = ebml_parse(matroska, matroska_segments, matroska);
1575 // try resyncing until we find a EBML_STOP type element.
1577 res = matroska_resync(matroska, pos);
1580 pos = avio_tell(matroska->ctx->pb);
1581 res = ebml_parse(matroska, matroska_segment, matroska);
1583 matroska_execute_seekhead(matroska);
1585 if (!matroska->time_scale)
1586 matroska->time_scale = 1000000;
1587 if (matroska->duration)
1588 matroska->ctx->duration = matroska->duration * matroska->time_scale
1589 * 1000 / AV_TIME_BASE;
1590 av_dict_set(&s->metadata, "title", matroska->title, 0);
1591 av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
1593 if (matroska->date_utc.size == 8)
1594 matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
1596 tracks = matroska->tracks.elem;
1597 for (i=0; i < matroska->tracks.nb_elem; i++) {
1598 MatroskaTrack *track = &tracks[i];
1599 enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1600 EbmlList *encodings_list = &track->encodings;
1601 MatroskaTrackEncoding *encodings = encodings_list->elem;
1602 uint8_t *extradata = NULL;
1603 int extradata_size = 0;
1604 int extradata_offset = 0;
1605 uint32_t fourcc = 0;
1607 char* key_id_base64 = NULL;
1609 /* Apply some sanity checks. */
1610 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1611 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1612 track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
1613 track->type != MATROSKA_TRACK_TYPE_METADATA) {
1614 av_log(matroska->ctx, AV_LOG_INFO,
1615 "Unknown or unsupported track type %"PRIu64"\n",
1619 if (track->codec_id == NULL)
1622 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1623 if (!track->default_duration && track->video.frame_rate > 0)
1624 track->default_duration = 1000000000/track->video.frame_rate;
1625 if (track->video.display_width == -1)
1626 track->video.display_width = track->video.pixel_width;
1627 if (track->video.display_height == -1)
1628 track->video.display_height = track->video.pixel_height;
1629 if (track->video.color_space.size == 4)
1630 fourcc = AV_RL32(track->video.color_space.data);
1631 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1632 if (!track->audio.out_samplerate)
1633 track->audio.out_samplerate = track->audio.samplerate;
1635 if (encodings_list->nb_elem > 1) {
1636 av_log(matroska->ctx, AV_LOG_ERROR,
1637 "Multiple combined encodings not supported");
1638 } else if (encodings_list->nb_elem == 1) {
1639 if (encodings[0].type) {
1640 if (encodings[0].encryption.key_id.size > 0) {
1641 /* Save the encryption key id to be stored later as a
1643 const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
1644 key_id_base64 = av_malloc(b64_size);
1645 if (key_id_base64 == NULL)
1646 return AVERROR(ENOMEM);
1648 av_base64_encode(key_id_base64, b64_size,
1649 encodings[0].encryption.key_id.data,
1650 encodings[0].encryption.key_id.size);
1652 encodings[0].scope = 0;
1653 av_log(matroska->ctx, AV_LOG_ERROR,
1654 "Unsupported encoding type");
1658 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1661 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1664 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1666 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
1667 encodings[0].scope = 0;
1668 av_log(matroska->ctx, AV_LOG_ERROR,
1669 "Unsupported encoding type");
1670 } else if (track->codec_priv.size && encodings[0].scope&2) {
1671 uint8_t *codec_priv = track->codec_priv.data;
1672 int ret = matroska_decode_buffer(&track->codec_priv.data,
1673 &track->codec_priv.size,
1676 track->codec_priv.data = NULL;
1677 track->codec_priv.size = 0;
1678 av_log(matroska->ctx, AV_LOG_ERROR,
1679 "Failed to decode codec private data\n");
1682 if (codec_priv != track->codec_priv.data)
1683 av_free(codec_priv);
1687 for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1688 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1689 strlen(ff_mkv_codec_tags[j].str))){
1690 codec_id= ff_mkv_codec_tags[j].id;
1695 st = track->stream = avformat_new_stream(s, NULL);
1697 av_free(key_id_base64);
1698 return AVERROR(ENOMEM);
1701 if (key_id_base64) {
1702 /* export encryption key id as base64 metadata tag */
1703 av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
1704 av_freep(&key_id_base64);
1707 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1708 && track->codec_priv.size >= 40
1709 && track->codec_priv.data != NULL) {
1710 track->ms_compat = 1;
1711 fourcc = AV_RL32(track->codec_priv.data + 16);
1712 codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1713 extradata_offset = 40;
1714 } else if (!strcmp(track->codec_id, "A_MS/ACM")
1715 && track->codec_priv.size >= 14
1716 && track->codec_priv.data != NULL) {
1718 ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1719 0, NULL, NULL, NULL, NULL);
1720 ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1723 codec_id = st->codec->codec_id;
1724 extradata_offset = FFMIN(track->codec_priv.size, 18);
1725 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1726 && (track->codec_priv.size >= 86)
1727 && (track->codec_priv.data != NULL)) {
1728 fourcc = AV_RL32(track->codec_priv.data);
1729 codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1730 } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1731 switch (track->audio.bitdepth) {
1732 case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1733 case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
1734 case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
1736 } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1737 switch (track->audio.bitdepth) {
1738 case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1739 case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
1740 case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
1742 } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1743 codec_id = AV_CODEC_ID_PCM_F64LE;
1744 } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1745 int profile = matroska_aac_profile(track->codec_id);
1746 int sri = matroska_aac_sri(track->audio.samplerate);
1747 extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1748 if (extradata == NULL)
1749 return AVERROR(ENOMEM);
1750 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1751 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1752 if (strstr(track->codec_id, "SBR")) {
1753 sri = matroska_aac_sri(track->audio.out_samplerate);
1754 extradata[2] = 0x56;
1755 extradata[3] = 0xE5;
1756 extradata[4] = 0x80 | (sri<<3);
1760 } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - FF_INPUT_BUFFER_PADDING_SIZE) {
1761 /* Only ALAC's magic cookie is stored in Matroska's track headers.
1762 Create the "atom size", "tag", and "tag version" fields the
1763 decoder expects manually. */
1764 extradata_size = 12 + track->codec_priv.size;
1765 extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1766 if (extradata == NULL)
1767 return AVERROR(ENOMEM);
1768 AV_WB32(extradata, extradata_size);
1769 memcpy(&extradata[4], "alac", 4);
1770 AV_WB32(&extradata[8], 0);
1771 memcpy(&extradata[12], track->codec_priv.data,
1772 track->codec_priv.size);
1773 } else if (codec_id == AV_CODEC_ID_TTA) {
1774 extradata_size = 30;
1775 extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1776 if (extradata == NULL)
1777 return AVERROR(ENOMEM);
1778 ffio_init_context(&b, extradata, extradata_size, 1,
1779 NULL, NULL, NULL, NULL);
1780 avio_write(&b, "TTA1", 4);
1782 avio_wl16(&b, track->audio.channels);
1783 avio_wl16(&b, track->audio.bitdepth);
1784 if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
1785 return AVERROR_INVALIDDATA;
1786 avio_wl32(&b, track->audio.out_samplerate);
1787 avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale), track->audio.out_samplerate, AV_TIME_BASE * 1000));
1788 } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1789 codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1790 extradata_offset = 26;
1791 } else if (codec_id == AV_CODEC_ID_RA_144) {
1792 track->audio.out_samplerate = 8000;
1793 track->audio.channels = 1;
1794 } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1795 codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
1796 && track->codec_priv.data) {
1799 ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1800 0, NULL, NULL, NULL, NULL);
1802 flavor = avio_rb16(&b);
1803 track->audio.coded_framesize = avio_rb32(&b);
1805 track->audio.sub_packet_h = avio_rb16(&b);
1806 track->audio.frame_size = avio_rb16(&b);
1807 track->audio.sub_packet_size = avio_rb16(&b);
1808 if (flavor < 0 || track->audio.coded_framesize <= 0 ||
1809 track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
1810 track->audio.sub_packet_size <= 0)
1811 return AVERROR_INVALIDDATA;
1812 track->audio.buf = av_malloc_array(track->audio.sub_packet_h, track->audio.frame_size);
1813 if (!track->audio.buf)
1814 return AVERROR(ENOMEM);
1815 if (codec_id == AV_CODEC_ID_RA_288) {
1816 st->codec->block_align = track->audio.coded_framesize;
1817 track->codec_priv.size = 0;
1819 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1820 static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1821 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1822 st->codec->bit_rate = sipr_bit_rate[flavor];
1824 st->codec->block_align = track->audio.sub_packet_size;
1825 extradata_offset = 78;
1828 track->codec_priv.size -= extradata_offset;
1830 if (codec_id == AV_CODEC_ID_NONE)
1831 av_log(matroska->ctx, AV_LOG_INFO,
1832 "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1834 if (track->time_scale < 0.01)
1835 track->time_scale = 1.0;
1836 avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1838 st->codec->codec_id = codec_id;
1840 if (strcmp(track->language, "und"))
1841 av_dict_set(&st->metadata, "language", track->language, 0);
1842 av_dict_set(&st->metadata, "title", track->name, 0);
1844 if (track->flag_default)
1845 st->disposition |= AV_DISPOSITION_DEFAULT;
1846 if (track->flag_forced)
1847 st->disposition |= AV_DISPOSITION_FORCED;
1849 if (!st->codec->extradata) {
1851 st->codec->extradata = extradata;
1852 st->codec->extradata_size = extradata_size;
1853 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1854 if (ff_alloc_extradata(st->codec, track->codec_priv.size))
1855 return AVERROR(ENOMEM);
1856 memcpy(st->codec->extradata,
1857 track->codec_priv.data + extradata_offset,
1858 track->codec_priv.size);
1862 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1863 MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1865 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1866 st->codec->codec_tag = fourcc;
1867 st->codec->width = track->video.pixel_width;
1868 st->codec->height = track->video.pixel_height;
1869 av_reduce(&st->sample_aspect_ratio.num,
1870 &st->sample_aspect_ratio.den,
1871 st->codec->height * track->video.display_width,
1872 st->codec-> width * track->video.display_height,
1874 if (st->codec->codec_id != AV_CODEC_ID_HEVC)
1875 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1877 if (track->default_duration) {
1878 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1879 1000000000, track->default_duration, 30000);
1880 #if FF_API_R_FRAME_RATE
1881 if (st->avg_frame_rate.num < st->avg_frame_rate.den * 1000L)
1882 st->r_frame_rate = st->avg_frame_rate;
1886 /* export stereo mode flag as metadata tag */
1887 if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1888 av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
1890 /* export alpha mode flag as metadata tag */
1891 if (track->video.alpha_mode)
1892 av_dict_set(&st->metadata, "alpha_mode", "1", 0);
1894 /* if we have virtual track, mark the real tracks */
1895 for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1897 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1899 snprintf(buf, sizeof(buf), "%s_%d",
1900 ff_matroska_video_stereo_plane[planes[j].type], i);
1901 for (k=0; k < matroska->tracks.nb_elem; k++)
1902 if (planes[j].uid == tracks[k].uid) {
1903 av_dict_set(&s->streams[k]->metadata,
1904 "stereo_mode", buf, 0);
1908 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1909 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1910 st->codec->sample_rate = track->audio.out_samplerate;
1911 st->codec->channels = track->audio.channels;
1912 if (!st->codec->bits_per_coded_sample)
1913 st->codec->bits_per_coded_sample = track->audio.bitdepth;
1914 if (st->codec->codec_id != AV_CODEC_ID_AAC)
1915 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1916 if (track->codec_delay > 0) {
1917 st->codec->delay = av_rescale_q(track->codec_delay,
1918 (AVRational){1, 1000000000},
1919 (AVRational){1, st->codec->sample_rate});
1921 if (track->seek_preroll > 0) {
1922 av_codec_set_seek_preroll(st->codec,
1923 av_rescale_q(track->seek_preroll,
1924 (AVRational){1, 1000000000},
1925 (AVRational){1, st->codec->sample_rate}));
1927 } else if (codec_id == AV_CODEC_ID_WEBVTT) {
1928 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1930 if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
1931 st->disposition |= AV_DISPOSITION_CAPTIONS;
1932 } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
1933 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1934 } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
1935 st->disposition |= AV_DISPOSITION_METADATA;
1937 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1938 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1940 if (st->codec->codec_id == AV_CODEC_ID_SSA ||
1941 st->codec->codec_id == AV_CODEC_ID_ASS)
1943 if (st->codec->codec_id == AV_CODEC_ID_ASS)
1945 matroska->contains_ssa = 1;
1949 attachements = attachements_list->elem;
1950 for (j=0; j<attachements_list->nb_elem; j++) {
1951 if (!(attachements[j].filename && attachements[j].mime &&
1952 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1953 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1955 AVStream *st = avformat_new_stream(s, NULL);
1958 av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1959 av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1960 st->codec->codec_id = AV_CODEC_ID_NONE;
1961 st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1962 if (ff_alloc_extradata(st->codec, attachements[j].bin.size))
1964 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1966 for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1967 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1968 strlen(ff_mkv_mime_tags[i].str))) {
1969 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1973 attachements[j].stream = st;
1977 chapters = chapters_list->elem;
1978 for (i=0; i<chapters_list->nb_elem; i++)
1979 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1980 && (max_start==0 || chapters[i].start > max_start)) {
1981 chapters[i].chapter =
1982 avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1983 chapters[i].start, chapters[i].end,
1985 av_dict_set(&chapters[i].chapter->metadata,
1986 "title", chapters[i].title, 0);
1987 max_start = chapters[i].start;
1990 matroska_add_index_entries(matroska);
1992 matroska_convert_tags(s);
1998 * Put one packet in an application-supplied AVPacket struct.
1999 * Returns 0 on success or -1 on failure.
2001 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
2004 if (matroska->num_packets > 0) {
2005 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
2006 av_free(matroska->packets[0]);
2007 if (matroska->num_packets > 1) {
2009 memmove(&matroska->packets[0], &matroska->packets[1],
2010 (matroska->num_packets - 1) * sizeof(AVPacket *));
2011 newpackets = av_realloc(matroska->packets,
2012 (matroska->num_packets - 1) * sizeof(AVPacket *));
2014 matroska->packets = newpackets;
2016 av_freep(&matroska->packets);
2017 matroska->prev_pkt = NULL;
2019 matroska->num_packets--;
2027 * Free all packets in our internal queue.
2029 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2031 matroska->prev_pkt = NULL;
2032 if (matroska->packets) {
2034 for (n = 0; n < matroska->num_packets; n++) {
2035 av_free_packet(matroska->packets[n]);
2036 av_free(matroska->packets[n]);
2038 av_freep(&matroska->packets);
2039 matroska->num_packets = 0;
2043 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2044 int* buf_size, int type,
2045 uint32_t **lace_buf, int *laces)
2047 int res = 0, n, size = *buf_size;
2048 uint8_t *data = *buf;
2049 uint32_t *lace_size;
2053 *lace_buf = av_mallocz(sizeof(int));
2055 return AVERROR(ENOMEM);
2057 *lace_buf[0] = size;
2061 av_assert0(size > 0);
2065 lace_size = av_mallocz(*laces * sizeof(int));
2067 return AVERROR(ENOMEM);
2070 case 0x1: /* Xiph lacing */ {
2073 for (n = 0; res == 0 && n < *laces - 1; n++) {
2075 if (size <= total) {
2076 res = AVERROR_INVALIDDATA;
2081 lace_size[n] += temp;
2088 if (size <= total) {
2089 res = AVERROR_INVALIDDATA;
2093 lace_size[n] = size - total;
2097 case 0x2: /* fixed-size lacing */
2098 if (size % (*laces)) {
2099 res = AVERROR_INVALIDDATA;
2102 for (n = 0; n < *laces; n++)
2103 lace_size[n] = size / *laces;
2106 case 0x3: /* EBML lacing */ {
2109 n = matroska_ebmlnum_uint(matroska, data, size, &num);
2110 if (n < 0 || num > INT_MAX) {
2111 av_log(matroska->ctx, AV_LOG_INFO,
2112 "EBML block data error\n");
2113 res = n<0 ? n : AVERROR_INVALIDDATA;
2118 total = lace_size[0] = num;
2119 for (n = 1; res == 0 && n < *laces - 1; n++) {
2122 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2123 if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
2124 av_log(matroska->ctx, AV_LOG_INFO,
2125 "EBML block data error\n");
2126 res = r<0 ? r : AVERROR_INVALIDDATA;
2131 lace_size[n] = lace_size[n - 1] + snum;
2132 total += lace_size[n];
2134 if (size <= total) {
2135 res = AVERROR_INVALIDDATA;
2138 lace_size[*laces - 1] = size - total;
2144 *lace_buf = lace_size;
2150 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2151 MatroskaTrack *track,
2153 uint8_t *data, int size,
2157 int a = st->codec->block_align;
2158 int sps = track->audio.sub_packet_size;
2159 int cfs = track->audio.coded_framesize;
2160 int h = track->audio.sub_packet_h;
2161 int y = track->audio.sub_packet_cnt;
2162 int w = track->audio.frame_size;
2165 if (!track->audio.pkt_cnt) {
2166 if (track->audio.sub_packet_cnt == 0)
2167 track->audio.buf_timecode = timecode;
2168 if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
2169 if (size < cfs * h / 2) {
2170 av_log(matroska->ctx, AV_LOG_ERROR,
2171 "Corrupt int4 RM-style audio packet size\n");
2172 return AVERROR_INVALIDDATA;
2174 for (x=0; x<h/2; x++)
2175 memcpy(track->audio.buf+x*2*w+y*cfs,
2177 } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
2179 av_log(matroska->ctx, AV_LOG_ERROR,
2180 "Corrupt sipr RM-style audio packet size\n");
2181 return AVERROR_INVALIDDATA;
2183 memcpy(track->audio.buf + y*w, data, w);
2185 if (size < sps * w / sps || h<=0 || w%sps) {
2186 av_log(matroska->ctx, AV_LOG_ERROR,
2187 "Corrupt generic RM-style audio packet size\n");
2188 return AVERROR_INVALIDDATA;
2190 for (x=0; x<w/sps; x++)
2191 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2194 if (++track->audio.sub_packet_cnt >= h) {
2195 if (st->codec->codec_id == AV_CODEC_ID_SIPR)
2196 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2197 track->audio.sub_packet_cnt = 0;
2198 track->audio.pkt_cnt = h*w / a;
2202 while (track->audio.pkt_cnt) {
2203 AVPacket *pkt = NULL;
2204 if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
2206 return AVERROR(ENOMEM);
2208 memcpy(pkt->data, track->audio.buf
2209 + a * (h*w / a - track->audio.pkt_cnt--), a);
2210 pkt->pts = track->audio.buf_timecode;
2211 track->audio.buf_timecode = AV_NOPTS_VALUE;
2213 pkt->stream_index = st->index;
2214 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2220 /* reconstruct full wavpack blocks from mangled matroska ones */
2221 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
2222 uint8_t **pdst, int *size)
2224 uint8_t *dst = NULL;
2229 int ret, offset = 0;
2231 if (srclen < 12 || track->stream->codec->extradata_size < 2)
2232 return AVERROR_INVALIDDATA;
2234 ver = AV_RL16(track->stream->codec->extradata);
2236 samples = AV_RL32(src);
2240 while (srclen >= 8) {
2245 uint32_t flags = AV_RL32(src);
2246 uint32_t crc = AV_RL32(src + 4);
2250 multiblock = (flags & 0x1800) != 0x1800;
2253 ret = AVERROR_INVALIDDATA;
2256 blocksize = AV_RL32(src);
2262 if (blocksize > srclen) {
2263 ret = AVERROR_INVALIDDATA;
2267 tmp = av_realloc(dst, dstlen + blocksize + 32);
2269 ret = AVERROR(ENOMEM);
2273 dstlen += blocksize + 32;
2275 AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
2276 AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
2277 AV_WL16(dst + offset + 8, ver); // version
2278 AV_WL16(dst + offset + 10, 0); // track/index_no
2279 AV_WL32(dst + offset + 12, 0); // total samples
2280 AV_WL32(dst + offset + 16, 0); // block index
2281 AV_WL32(dst + offset + 20, samples); // number of samples
2282 AV_WL32(dst + offset + 24, flags); // flags
2283 AV_WL32(dst + offset + 28, crc); // crc
2284 memcpy (dst + offset + 32, src, blocksize); // block data
2287 srclen -= blocksize;
2288 offset += blocksize + 32;
2301 static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
2302 MatroskaTrack *track,
2304 uint8_t *data, int data_len,
2310 uint8_t *id, *settings, *text, *buf;
2311 int id_len, settings_len, text_len;
2316 return AVERROR_INVALIDDATA;
2319 q = data + data_len;
2324 if (*p == '\r' || *p == '\n') {
2333 if (p >= q || *p != '\n')
2334 return AVERROR_INVALIDDATA;
2340 if (*p == '\r' || *p == '\n') {
2341 settings_len = p - settings;
2349 if (p >= q || *p != '\n')
2350 return AVERROR_INVALIDDATA;
2355 while (text_len > 0) {
2356 const int len = text_len - 1;
2357 const uint8_t c = p[len];
2358 if (c != '\r' && c != '\n')
2364 return AVERROR_INVALIDDATA;
2366 pkt = av_mallocz(sizeof(*pkt));
2367 err = av_new_packet(pkt, text_len);
2370 return AVERROR(err);
2373 memcpy(pkt->data, text, text_len);
2376 buf = av_packet_new_side_data(pkt,
2377 AV_PKT_DATA_WEBVTT_IDENTIFIER,
2381 return AVERROR(ENOMEM);
2383 memcpy(buf, id, id_len);
2386 if (settings_len > 0) {
2387 buf = av_packet_new_side_data(pkt,
2388 AV_PKT_DATA_WEBVTT_SETTINGS,
2392 return AVERROR(ENOMEM);
2394 memcpy(buf, settings, settings_len);
2397 // Do we need this for subtitles?
2398 // pkt->flags = AV_PKT_FLAG_KEY;
2400 pkt->stream_index = st->index;
2401 pkt->pts = timecode;
2403 // Do we need this for subtitles?
2404 // pkt->dts = timecode;
2406 pkt->duration = duration;
2409 dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2410 matroska->prev_pkt = pkt;
2415 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2416 MatroskaTrack *track,
2418 uint8_t *data, int pkt_size,
2419 uint64_t timecode, uint64_t lace_duration,
2420 int64_t pos, int is_keyframe,
2421 uint8_t *additional, uint64_t additional_id, int additional_size,
2422 int64_t discard_padding)
2424 MatroskaTrackEncoding *encodings = track->encodings.elem;
2425 uint8_t *pkt_data = data;
2426 int offset = 0, res;
2429 if (encodings && !encodings->type && encodings->scope & 1) {
2430 res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2435 if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
2437 res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2439 av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
2442 if (pkt_data != data)
2443 av_freep(&pkt_data);
2447 if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2450 pkt = av_mallocz(sizeof(AVPacket));
2451 /* XXX: prevent data copy... */
2452 if (av_new_packet(pkt, pkt_size + offset) < 0) {
2454 res = AVERROR(ENOMEM);
2458 if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2459 uint8_t *buf = pkt->data;
2460 bytestream_put_be32(&buf, pkt_size);
2461 bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2464 memcpy(pkt->data + offset, pkt_data, pkt_size);
2466 if (pkt_data != data)
2467 av_freep(&pkt_data);
2469 pkt->flags = is_keyframe;
2470 pkt->stream_index = st->index;
2472 if (additional_size > 0) {
2473 uint8_t *side_data = av_packet_new_side_data(pkt,
2474 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
2475 additional_size + 8);
2476 if(side_data == NULL) {
2477 av_free_packet(pkt);
2479 return AVERROR(ENOMEM);
2481 AV_WB64(side_data, additional_id);
2482 memcpy(side_data + 8, additional, additional_size);
2485 if (discard_padding) {
2486 uint8_t *side_data = av_packet_new_side_data(pkt,
2487 AV_PKT_DATA_SKIP_SAMPLES,
2489 if(side_data == NULL) {
2490 av_free_packet(pkt);
2492 return AVERROR(ENOMEM);
2494 AV_WL32(side_data, 0);
2495 AV_WL32(side_data + 4, av_rescale_q(discard_padding,
2496 (AVRational){1, 1000000000},
2497 (AVRational){1, st->codec->sample_rate}));
2500 if (track->ms_compat)
2501 pkt->dts = timecode;
2503 pkt->pts = timecode;
2505 if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
2507 * For backward compatibility.
2508 * Historically, we have put subtitle duration
2509 * in convergence_duration, on the off chance
2510 * that the time_scale is less than 1us, which
2511 * could result in a 32bit overflow on the
2512 * normal duration field.
2514 pkt->convergence_duration = lace_duration;
2517 if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
2518 lace_duration <= INT_MAX) {
2520 * For non subtitle tracks, just store the duration
2523 * If it's a subtitle track and duration value does
2524 * not overflow a uint32, then also store it normally.
2526 pkt->duration = lace_duration;
2530 if (st->codec->codec_id == AV_CODEC_ID_SSA)
2531 matroska_fix_ass_packet(matroska, pkt, lace_duration);
2533 if (matroska->prev_pkt &&
2534 timecode != AV_NOPTS_VALUE &&
2535 matroska->prev_pkt->pts == timecode &&
2536 matroska->prev_pkt->stream_index == st->index &&
2537 st->codec->codec_id == AV_CODEC_ID_SSA)
2538 matroska_merge_packets(matroska->prev_pkt, pkt);
2540 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2541 matroska->prev_pkt = pkt;
2544 dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2545 matroska->prev_pkt = pkt;
2550 if (pkt_data != data)
2551 av_freep(&pkt_data);
2555 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2556 int size, int64_t pos, uint64_t cluster_time,
2557 uint64_t block_duration, int is_keyframe,
2558 uint8_t *additional, uint64_t additional_id, int additional_size,
2559 int64_t cluster_pos, int64_t discard_padding)
2561 uint64_t timecode = AV_NOPTS_VALUE;
2562 MatroskaTrack *track;
2566 uint32_t *lace_size = NULL;
2567 int n, flags, laces = 0;
2569 int trust_default_duration = 1;
2571 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2572 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2578 track = matroska_find_track_by_num(matroska, num);
2579 if (!track || !track->stream) {
2580 av_log(matroska->ctx, AV_LOG_INFO,
2581 "Invalid stream %"PRIu64" or size %u\n", num, size);
2582 return AVERROR_INVALIDDATA;
2583 } else if (size <= 3)
2586 if (st->discard >= AVDISCARD_ALL)
2588 av_assert1(block_duration != AV_NOPTS_VALUE);
2590 block_time = sign_extend(AV_RB16(data), 16);
2594 if (is_keyframe == -1)
2595 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2597 if (cluster_time != (uint64_t)-1
2598 && (block_time >= 0 || cluster_time >= -block_time)) {
2599 timecode = cluster_time + block_time;
2600 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2601 && timecode < track->end_timecode)
2602 is_keyframe = 0; /* overlapping subtitles are not key frame */
2604 av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2607 if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2608 if (timecode < matroska->skip_to_timecode)
2611 matroska->skip_to_keyframe = 0;
2612 else if (!st->skip_to_keyframe) {
2613 av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
2614 matroska->skip_to_keyframe = 0;
2618 res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2619 &lace_size, &laces);
2624 if (track->audio.samplerate == 8000) {
2625 // If this is needed for more codecs, then add them here
2626 if (st->codec->codec_id == AV_CODEC_ID_AC3) {
2627 if(track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
2628 trust_default_duration = 0;
2632 if (!block_duration && trust_default_duration)
2633 block_duration = track->default_duration * laces / matroska->time_scale;
2635 if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
2636 track->end_timecode =
2637 FFMAX(track->end_timecode, timecode + block_duration);
2639 for (n = 0; n < laces; n++) {
2640 int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
2642 if (lace_size[n] > size) {
2643 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
2647 if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2648 st->codec->codec_id == AV_CODEC_ID_COOK ||
2649 st->codec->codec_id == AV_CODEC_ID_SIPR ||
2650 st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2651 st->codec->block_align && track->audio.sub_packet_size) {
2653 res = matroska_parse_rm_audio(matroska, track, st, data,
2659 } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
2660 res = matroska_parse_webvtt(matroska, track, st,
2662 timecode, lace_duration,
2668 res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2669 timecode, lace_duration,
2670 pos, !n? is_keyframe : 0,
2671 additional, additional_id, additional_size,
2677 if (timecode != AV_NOPTS_VALUE)
2678 timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
2679 data += lace_size[n];
2680 size -= lace_size[n];
2688 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2690 EbmlList *blocks_list;
2691 MatroskaBlock *blocks;
2693 res = ebml_parse(matroska,
2694 matroska_cluster_incremental_parsing,
2695 &matroska->current_cluster);
2698 if (matroska->current_cluster_pos)
2699 ebml_level_end(matroska);
2700 ebml_free(matroska_cluster, &matroska->current_cluster);
2701 memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2702 matroska->current_cluster_num_blocks = 0;
2703 matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2704 matroska->prev_pkt = NULL;
2705 /* sizeof the ID which was already read */
2706 if (matroska->current_id)
2707 matroska->current_cluster_pos -= 4;
2708 res = ebml_parse(matroska,
2709 matroska_clusters_incremental,
2710 &matroska->current_cluster);
2711 /* Try parsing the block again. */
2713 res = ebml_parse(matroska,
2714 matroska_cluster_incremental_parsing,
2715 &matroska->current_cluster);
2719 matroska->current_cluster_num_blocks <
2720 matroska->current_cluster.blocks.nb_elem) {
2721 blocks_list = &matroska->current_cluster.blocks;
2722 blocks = blocks_list->elem;
2724 matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2725 i = blocks_list->nb_elem - 1;
2726 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2727 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2728 uint8_t* additional = blocks[i].additional.size > 0 ?
2729 blocks[i].additional.data : NULL;
2730 if (!blocks[i].non_simple)
2731 blocks[i].duration = 0;
2732 res = matroska_parse_block(matroska,
2733 blocks[i].bin.data, blocks[i].bin.size,
2735 matroska->current_cluster.timecode,
2736 blocks[i].duration, is_keyframe,
2737 additional, blocks[i].additional_id,
2738 blocks[i].additional.size,
2739 matroska->current_cluster_pos,
2740 blocks[i].discard_padding);
2747 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2749 MatroskaCluster cluster = { 0 };
2750 EbmlList *blocks_list;
2751 MatroskaBlock *blocks;
2754 if (!matroska->contains_ssa)
2755 return matroska_parse_cluster_incremental(matroska);
2756 pos = avio_tell(matroska->ctx->pb);
2757 matroska->prev_pkt = NULL;
2758 if (matroska->current_id)
2759 pos -= 4; /* sizeof the ID which was already read */
2760 res = ebml_parse(matroska, matroska_clusters, &cluster);
2761 blocks_list = &cluster.blocks;
2762 blocks = blocks_list->elem;
2763 for (i=0; i<blocks_list->nb_elem; i++)
2764 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2765 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2766 res=matroska_parse_block(matroska,
2767 blocks[i].bin.data, blocks[i].bin.size,
2768 blocks[i].bin.pos, cluster.timecode,
2769 blocks[i].duration, is_keyframe, NULL, 0, 0,
2770 pos, blocks[i].discard_padding);
2772 ebml_free(matroska_cluster, &cluster);
2776 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2778 MatroskaDemuxContext *matroska = s->priv_data;
2780 while (matroska_deliver_packet(matroska, pkt)) {
2781 int64_t pos = avio_tell(matroska->ctx->pb);
2784 if (matroska_parse_cluster(matroska) < 0)
2785 matroska_resync(matroska, pos);
2791 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2792 int64_t timestamp, int flags)
2794 MatroskaDemuxContext *matroska = s->priv_data;
2795 MatroskaTrack *tracks = matroska->tracks.elem;
2796 AVStream *st = s->streams[stream_index];
2797 int i, index, index_sub, index_min;
2799 /* Parse the CUES now since we need the index data to seek. */
2800 if (matroska->cues_parsing_deferred > 0) {
2801 matroska->cues_parsing_deferred = 0;
2802 matroska_parse_cues(matroska);
2805 if (!st->nb_index_entries)
2807 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2809 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2810 avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2811 matroska->current_id = 0;
2812 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2813 matroska_clear_queue(matroska);
2814 if (matroska_parse_cluster(matroska) < 0)
2819 matroska_clear_queue(matroska);
2820 if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2824 for (i=0; i < matroska->tracks.nb_elem; i++) {
2825 tracks[i].audio.pkt_cnt = 0;
2826 tracks[i].audio.sub_packet_cnt = 0;
2827 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2828 tracks[i].end_timecode = 0;
2829 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2830 && tracks[i].stream->discard != AVDISCARD_ALL) {
2831 index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2832 while(index_sub >= 0
2834 && tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos
2835 && st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2840 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2841 matroska->current_id = 0;
2842 if (flags & AVSEEK_FLAG_ANY) {
2843 st->skip_to_keyframe = 0;
2844 matroska->skip_to_timecode = timestamp;
2846 st->skip_to_keyframe = 1;
2847 matroska->skip_to_timecode = st->index_entries[index].timestamp;
2849 matroska->skip_to_keyframe = 1;
2851 matroska->num_levels = 0;
2852 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2855 // slightly hackish but allows proper fallback to
2856 // the generic seeking code.
2857 matroska_clear_queue(matroska);
2858 matroska->current_id = 0;
2859 st->skip_to_keyframe =
2860 matroska->skip_to_keyframe = 0;
2862 matroska->num_levels = 0;
2866 static int matroska_read_close(AVFormatContext *s)
2868 MatroskaDemuxContext *matroska = s->priv_data;
2869 MatroskaTrack *tracks = matroska->tracks.elem;
2872 matroska_clear_queue(matroska);
2874 for (n=0; n < matroska->tracks.nb_elem; n++)
2875 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2876 av_free(tracks[n].audio.buf);
2877 ebml_free(matroska_cluster, &matroska->current_cluster);
2878 ebml_free(matroska_segment, matroska);
2883 AVInputFormat ff_matroska_demuxer = {
2884 .name = "matroska,webm",
2885 .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2886 .priv_data_size = sizeof(MatroskaDemuxContext),
2887 .read_probe = matroska_probe,
2888 .read_header = matroska_read_header,
2889 .read_packet = matroska_read_packet,
2890 .read_close = matroska_read_close,
2891 .read_seek = matroska_read_seek,