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/
36 #include "libavutil/avstring.h"
37 #include "libavutil/base64.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/intfloat.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/lzo.h"
42 #include "libavutil/mastering_display_metadata.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/opt.h"
45 #include "libavutil/time_internal.h"
47 #include "libavcodec/bytestream.h"
48 #include "libavcodec/flac.h"
49 #include "libavcodec/mpeg4audio.h"
52 #include "avio_internal.h"
57 /* For ff_codec_get_id(). */
68 #include "qtpalette.h"
85 typedef const struct EbmlSyntax {
94 const struct EbmlSyntax *n;
98 typedef struct EbmlList {
103 typedef struct EbmlBin {
109 typedef struct Ebml {
114 uint64_t doctype_version;
117 typedef struct MatroskaTrackCompression {
120 } MatroskaTrackCompression;
122 typedef struct MatroskaTrackEncryption {
125 } MatroskaTrackEncryption;
127 typedef struct MatroskaTrackEncoding {
130 MatroskaTrackCompression compression;
131 MatroskaTrackEncryption encryption;
132 } MatroskaTrackEncoding;
134 typedef struct MatroskaMasteringMeta {
143 double max_luminance;
144 double min_luminance;
145 } MatroskaMasteringMeta;
147 typedef struct MatroskaTrackVideoColor {
148 uint64_t matrix_coefficients;
149 uint64_t bits_per_channel;
150 uint64_t chroma_sub_horz;
151 uint64_t chroma_sub_vert;
152 uint64_t cb_sub_horz;
153 uint64_t cb_sub_vert;
154 uint64_t chroma_siting_horz;
155 uint64_t chroma_siting_vert;
157 uint64_t transfer_characteristics;
161 MatroskaMasteringMeta mastering_meta;
162 } MatroskaTrackVideoColor;
164 typedef struct MatroskaTrackVideo {
166 uint64_t display_width;
167 uint64_t display_height;
168 uint64_t pixel_width;
169 uint64_t pixel_height;
171 uint64_t stereo_mode;
173 MatroskaTrackVideoColor color;
174 } MatroskaTrackVideo;
176 typedef struct MatroskaTrackAudio {
178 double out_samplerate;
182 /* real audio header (extracted from extradata) */
189 uint64_t buf_timecode;
191 } MatroskaTrackAudio;
193 typedef struct MatroskaTrackPlane {
196 } MatroskaTrackPlane;
198 typedef struct MatroskaTrackOperation {
199 EbmlList combine_planes;
200 } MatroskaTrackOperation;
202 typedef struct MatroskaTrack {
211 uint64_t default_duration;
212 uint64_t flag_default;
213 uint64_t flag_forced;
214 uint64_t seek_preroll;
215 MatroskaTrackVideo video;
216 MatroskaTrackAudio audio;
217 MatroskaTrackOperation operation;
219 uint64_t codec_delay;
222 int64_t end_timecode;
224 uint64_t max_block_additional_id;
226 uint32_t palette[AVPALETTE_COUNT];
230 typedef struct MatroskaAttachment {
237 } MatroskaAttachment;
239 typedef struct MatroskaChapter {
248 typedef struct MatroskaIndexPos {
253 typedef struct MatroskaIndex {
258 typedef struct MatroskaTag {
266 typedef struct MatroskaTagTarget {
274 typedef struct MatroskaTags {
275 MatroskaTagTarget target;
279 typedef struct MatroskaSeekhead {
284 typedef struct MatroskaLevel {
289 typedef struct MatroskaCluster {
294 typedef struct MatroskaLevel1Element {
298 } MatroskaLevel1Element;
300 typedef struct MatroskaDemuxContext {
301 const AVClass *class;
302 AVFormatContext *ctx;
306 MatroskaLevel levels[EBML_MAX_DEPTH];
316 EbmlList attachments;
322 /* byte position of the segment inside the stream */
323 int64_t segment_start;
325 /* the packet queue */
332 /* What to skip before effectively reading a packet. */
333 int skip_to_keyframe;
334 uint64_t skip_to_timecode;
336 /* File has a CUES element, but we defer parsing until it is needed. */
337 int cues_parsing_deferred;
339 /* Level1 elements and whether they were read yet */
340 MatroskaLevel1Element level1_elems[64];
341 int num_level1_elems;
343 int current_cluster_num_blocks;
344 int64_t current_cluster_pos;
345 MatroskaCluster current_cluster;
347 /* File has SSA subtitles which prevent incremental cluster parsing. */
350 /* WebM DASH Manifest live flag/ */
352 } MatroskaDemuxContext;
354 typedef struct MatroskaBlock {
359 uint64_t additional_id;
361 int64_t discard_padding;
364 static const EbmlSyntax ebml_header[] = {
365 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml, version), { .u = EBML_VERSION } },
366 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml, max_size), { .u = 8 } },
367 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml, id_length), { .u = 4 } },
368 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml, doctype), { .s = "(none)" } },
369 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
370 { EBML_ID_EBMLVERSION, EBML_NONE },
371 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
375 static const EbmlSyntax ebml_syntax[] = {
376 { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
380 static const EbmlSyntax matroska_info[] = {
381 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
382 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext, duration) },
383 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext, title) },
384 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
385 { MATROSKA_ID_MUXINGAPP, EBML_UTF8, 0, offsetof(MatroskaDemuxContext, muxingapp) },
386 { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext, date_utc) },
387 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
391 static const EbmlSyntax matroska_mastering_meta[] = {
392 { MATROSKA_ID_VIDEOCOLOR_RX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, r_x), { .f=-1 } },
393 { MATROSKA_ID_VIDEOCOLOR_RY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, r_y), { .f=-1 } },
394 { MATROSKA_ID_VIDEOCOLOR_GX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, g_x), { .f=-1 } },
395 { MATROSKA_ID_VIDEOCOLOR_GY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, g_y), { .f=-1 } },
396 { MATROSKA_ID_VIDEOCOLOR_BX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, b_x), { .f=-1 } },
397 { MATROSKA_ID_VIDEOCOLOR_BY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, b_y), { .f=-1 } },
398 { MATROSKA_ID_VIDEOCOLOR_WHITEX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, white_x), { .f=-1 } },
399 { MATROSKA_ID_VIDEOCOLOR_WHITEY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, white_y), { .f=-1 } },
400 { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, min_luminance), { .f=-1 } },
401 { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, max_luminance), { .f=-1 } },
405 static const EbmlSyntax matroska_track_video_color[] = {
406 { MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, matrix_coefficients), { .u=2 } },
407 { MATROSKA_ID_VIDEOCOLORBITSPERCHANNEL, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, bits_per_channel), { .u=8 } },
408 { MATROSKA_ID_VIDEOCOLORCHROMASUBHORZ, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_horz), { .u=0 } },
409 { MATROSKA_ID_VIDEOCOLORCHROMASUBVERT, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_vert), { .u=0 } },
410 { MATROSKA_ID_VIDEOCOLORCBSUBHORZ, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, cb_sub_horz), { .u=0 } },
411 { MATROSKA_ID_VIDEOCOLORCBSUBVERT, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, cb_sub_vert), { .u=0 } },
412 { MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_siting_horz), { .u=0 } },
413 { MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_siting_vert), { .u=0 } },
414 { MATROSKA_ID_VIDEOCOLORRANGE, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, range), { .u=0 } },
415 { MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, transfer_characteristics), { .u=2 } },
416 { MATROSKA_ID_VIDEOCOLORPRIMARIES, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, primaries), { .u=2 } },
417 { MATROSKA_ID_VIDEOCOLORMAXCLL, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, max_cll), { .u=0 } },
418 { MATROSKA_ID_VIDEOCOLORMAXFALL, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, max_fall), { .u=0 } },
419 { MATROSKA_ID_VIDEOCOLORMASTERINGMETA, EBML_NEST, 0, offsetof(MatroskaTrackVideoColor, mastering_meta), { .n = matroska_mastering_meta } },
423 static const EbmlSyntax matroska_track_video[] = {
424 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT, 0, offsetof(MatroskaTrackVideo, frame_rate) },
425 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_width), { .u=-1 } },
426 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_height), { .u=-1 } },
427 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_width) },
428 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_height) },
429 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo, color_space) },
430 { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, alpha_mode) },
431 { MATROSKA_ID_VIDEOCOLOR, EBML_NEST, 0, offsetof(MatroskaTrackVideo, color), { .n = matroska_track_video_color } },
432 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
433 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
434 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
435 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
436 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
437 { MATROSKA_ID_VIDEOFLAGINTERLACED, EBML_NONE },
438 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, stereo_mode), { .u = MATROSKA_VIDEO_STEREOMODE_TYPE_NB } },
439 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
443 static const EbmlSyntax matroska_track_audio[] = {
444 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
445 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
446 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio, bitdepth) },
447 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio, channels), { .u = 1 } },
451 static const EbmlSyntax matroska_track_encoding_compression[] = {
452 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
453 { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN, 0, offsetof(MatroskaTrackCompression, settings) },
457 static const EbmlSyntax matroska_track_encoding_encryption[] = {
458 { MATROSKA_ID_ENCODINGENCALGO, EBML_UINT, 0, offsetof(MatroskaTrackEncryption,algo), {.u = 0} },
459 { MATROSKA_ID_ENCODINGENCKEYID, EBML_BIN, 0, offsetof(MatroskaTrackEncryption,key_id) },
460 { MATROSKA_ID_ENCODINGENCAESSETTINGS, EBML_NONE },
461 { MATROSKA_ID_ENCODINGSIGALGO, EBML_NONE },
462 { MATROSKA_ID_ENCODINGSIGHASHALGO, EBML_NONE },
463 { MATROSKA_ID_ENCODINGSIGKEYID, EBML_NONE },
464 { MATROSKA_ID_ENCODINGSIGNATURE, EBML_NONE },
467 static const EbmlSyntax matroska_track_encoding[] = {
468 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, scope), { .u = 1 } },
469 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, type), { .u = 0 } },
470 { MATROSKA_ID_ENCODINGCOMPRESSION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, compression), { .n = matroska_track_encoding_compression } },
471 { MATROSKA_ID_ENCODINGENCRYPTION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, encryption), { .n = matroska_track_encoding_encryption } },
472 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
476 static const EbmlSyntax matroska_track_encodings[] = {
477 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
481 static const EbmlSyntax matroska_track_plane[] = {
482 { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
483 { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
487 static const EbmlSyntax matroska_track_combine_planes[] = {
488 { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n = matroska_track_plane} },
492 static const EbmlSyntax matroska_track_operation[] = {
493 { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n = matroska_track_combine_planes} },
497 static const EbmlSyntax matroska_track[] = {
498 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack, num) },
499 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack, name) },
500 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack, uid) },
501 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack, type) },
502 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack, codec_id) },
503 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack, codec_priv) },
504 { MATROSKA_ID_CODECDELAY, EBML_UINT, 0, offsetof(MatroskaTrack, codec_delay) },
505 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack, language), { .s = "eng" } },
506 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack, default_duration) },
507 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT, 0, offsetof(MatroskaTrack, time_scale), { .f = 1.0 } },
508 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack, flag_default), { .u = 1 } },
509 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack, flag_forced), { .u = 0 } },
510 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack, video), { .n = matroska_track_video } },
511 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack, audio), { .n = matroska_track_audio } },
512 { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack, operation), { .n = matroska_track_operation } },
513 { MATROSKA_ID_TRACKCONTENTENCODINGS, EBML_NEST, 0, 0, { .n = matroska_track_encodings } },
514 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, offsetof(MatroskaTrack, max_block_additional_id) },
515 { MATROSKA_ID_SEEKPREROLL, EBML_UINT, 0, offsetof(MatroskaTrack, seek_preroll) },
516 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
517 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
518 { MATROSKA_ID_CODECNAME, EBML_NONE },
519 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
520 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
521 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
522 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
523 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
527 static const EbmlSyntax matroska_tracks[] = {
528 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
532 static const EbmlSyntax matroska_attachment[] = {
533 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachment, uid) },
534 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachment, filename) },
535 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachment, mime) },
536 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachment, bin) },
537 { MATROSKA_ID_FILEDESC, EBML_NONE },
541 static const EbmlSyntax matroska_attachments[] = {
542 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
546 static const EbmlSyntax matroska_chapter_display[] = {
547 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
548 { MATROSKA_ID_CHAPLANG, EBML_NONE },
549 { MATROSKA_ID_CHAPCOUNTRY, EBML_NONE },
553 static const EbmlSyntax matroska_chapter_entry[] = {
554 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
555 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter, end), { .u = AV_NOPTS_VALUE } },
556 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter, uid) },
557 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, { .n = matroska_chapter_display } },
558 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
559 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
560 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
561 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
565 static const EbmlSyntax matroska_chapter[] = {
566 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
567 { MATROSKA_ID_EDITIONUID, EBML_NONE },
568 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
569 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
570 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
574 static const EbmlSyntax matroska_chapters[] = {
575 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
579 static const EbmlSyntax matroska_index_pos[] = {
580 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
581 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
582 { MATROSKA_ID_CUERELATIVEPOSITION,EBML_NONE },
583 { MATROSKA_ID_CUEDURATION, EBML_NONE },
584 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
588 static const EbmlSyntax matroska_index_entry[] = {
589 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex, time) },
590 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex, pos), { .n = matroska_index_pos } },
594 static const EbmlSyntax matroska_index[] = {
595 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
599 static const EbmlSyntax matroska_simpletag[] = {
600 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag, name) },
601 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag, string) },
602 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag, lang), { .s = "und" } },
603 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag, def) },
604 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag, def) },
605 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag, sub), { .n = matroska_simpletag } },
609 static const EbmlSyntax matroska_tagtargets[] = {
610 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget, type) },
611 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
612 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, trackuid) },
613 { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, chapteruid) },
614 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, attachuid) },
618 static const EbmlSyntax matroska_tag[] = {
619 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags, tag), { .n = matroska_simpletag } },
620 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
624 static const EbmlSyntax matroska_tags[] = {
625 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
629 static const EbmlSyntax matroska_seekhead_entry[] = {
630 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
631 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
635 static const EbmlSyntax matroska_seekhead[] = {
636 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
640 static const EbmlSyntax matroska_segment[] = {
641 { MATROSKA_ID_INFO, EBML_LEVEL1, 0, 0, { .n = matroska_info } },
642 { MATROSKA_ID_TRACKS, EBML_LEVEL1, 0, 0, { .n = matroska_tracks } },
643 { MATROSKA_ID_ATTACHMENTS, EBML_LEVEL1, 0, 0, { .n = matroska_attachments } },
644 { MATROSKA_ID_CHAPTERS, EBML_LEVEL1, 0, 0, { .n = matroska_chapters } },
645 { MATROSKA_ID_CUES, EBML_LEVEL1, 0, 0, { .n = matroska_index } },
646 { MATROSKA_ID_TAGS, EBML_LEVEL1, 0, 0, { .n = matroska_tags } },
647 { MATROSKA_ID_SEEKHEAD, EBML_LEVEL1, 0, 0, { .n = matroska_seekhead } },
648 { MATROSKA_ID_CLUSTER, EBML_STOP },
652 static const EbmlSyntax matroska_segments[] = {
653 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
657 static const EbmlSyntax matroska_blockmore[] = {
658 { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
659 { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) },
663 static const EbmlSyntax matroska_blockadditions[] = {
664 { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n = matroska_blockmore} },
668 static const EbmlSyntax matroska_blockgroup[] = {
669 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
670 { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, { .n = matroska_blockadditions} },
671 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
672 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock, duration) },
673 { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, offsetof(MatroskaBlock, discard_padding) },
674 { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock, reference) },
675 { MATROSKA_ID_CODECSTATE, EBML_NONE },
676 { 1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
680 static const EbmlSyntax matroska_cluster[] = {
681 { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
682 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
683 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
684 { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
685 { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
689 static const EbmlSyntax matroska_clusters[] = {
690 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster } },
691 { MATROSKA_ID_INFO, EBML_NONE },
692 { MATROSKA_ID_CUES, EBML_NONE },
693 { MATROSKA_ID_TAGS, EBML_NONE },
694 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
698 static const EbmlSyntax matroska_cluster_incremental_parsing[] = {
699 { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
700 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
701 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
702 { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
703 { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
704 { MATROSKA_ID_INFO, EBML_NONE },
705 { MATROSKA_ID_CUES, EBML_NONE },
706 { MATROSKA_ID_TAGS, EBML_NONE },
707 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
708 { MATROSKA_ID_CLUSTER, EBML_STOP },
712 static const EbmlSyntax matroska_cluster_incremental[] = {
713 { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
714 { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
715 { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
716 { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
717 { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
721 static const EbmlSyntax matroska_clusters_incremental[] = {
722 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster_incremental } },
723 { MATROSKA_ID_INFO, EBML_NONE },
724 { MATROSKA_ID_CUES, EBML_NONE },
725 { MATROSKA_ID_TAGS, EBML_NONE },
726 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
730 static const char *const matroska_doctypes[] = { "matroska", "webm" };
732 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
734 AVIOContext *pb = matroska->ctx->pb;
736 matroska->current_id = 0;
737 matroska->num_levels = 0;
739 /* seek to next position to resync from */
740 if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
745 // try to find a toplevel element
746 while (!avio_feof(pb)) {
747 if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
748 id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
749 id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
750 id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
751 matroska->current_id = id;
754 id = (id << 8) | avio_r8(pb);
763 * Return: Whether we reached the end of a level in the hierarchy or not.
765 static int ebml_level_end(MatroskaDemuxContext *matroska)
767 AVIOContext *pb = matroska->ctx->pb;
768 int64_t pos = avio_tell(pb);
770 if (matroska->num_levels > 0) {
771 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
772 if (pos - level->start >= level->length || matroska->current_id) {
773 matroska->num_levels--;
777 return (matroska->is_live && matroska->ctx->pb->eof_reached) ? 1 : 0;
781 * Read: an "EBML number", which is defined as a variable-length
782 * array of bytes. The first byte indicates the length by giving a
783 * number of 0-bits followed by a one. The position of the first
784 * "one" bit inside the first byte indicates the length of this
786 * Returns: number of bytes read, < 0 on error
788 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
789 int max_size, uint64_t *number)
794 /* The first byte tells us the length in bytes - avio_r8() can normally
795 * return 0, but since that's not a valid first ebmlID byte, we can
796 * use it safely here to catch EOS. */
797 if (!(total = avio_r8(pb))) {
798 /* we might encounter EOS here */
799 if (!avio_feof(pb)) {
800 int64_t pos = avio_tell(pb);
801 av_log(matroska->ctx, AV_LOG_ERROR,
802 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
804 return pb->error ? pb->error : AVERROR(EIO);
809 /* get the length of the EBML number */
810 read = 8 - ff_log2_tab[total];
811 if (read > max_size) {
812 int64_t pos = avio_tell(pb) - 1;
813 av_log(matroska->ctx, AV_LOG_ERROR,
814 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
815 (uint8_t) total, pos, pos);
816 return AVERROR_INVALIDDATA;
819 /* read out length */
820 total ^= 1 << ff_log2_tab[total];
822 total = (total << 8) | avio_r8(pb);
830 * Read a EBML length value.
831 * This needs special handling for the "unknown length" case which has multiple
834 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
837 int res = ebml_read_num(matroska, pb, 8, number);
838 if (res > 0 && *number + 1 == 1ULL << (7 * res))
839 *number = 0xffffffffffffffULL;
844 * Read the next element as an unsigned int.
845 * 0 is success, < 0 is failure.
847 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
852 return AVERROR_INVALIDDATA;
854 /* big-endian ordering; build up number */
857 *num = (*num << 8) | avio_r8(pb);
863 * Read the next element as a signed int.
864 * 0 is success, < 0 is failure.
866 static int ebml_read_sint(AVIOContext *pb, int size, int64_t *num)
871 return AVERROR_INVALIDDATA;
876 *num = sign_extend(avio_r8(pb), 8);
878 /* big-endian ordering; build up number */
880 *num = ((uint64_t)*num << 8) | avio_r8(pb);
887 * Read the next element as a float.
888 * 0 is success, < 0 is failure.
890 static int ebml_read_float(AVIOContext *pb, int size, double *num)
895 *num = av_int2float(avio_rb32(pb));
897 *num = av_int2double(avio_rb64(pb));
899 return AVERROR_INVALIDDATA;
905 * Read the next element as an ASCII string.
906 * 0 is success, < 0 is failure.
908 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
912 /* EBML strings are usually not 0-terminated, so we allocate one
913 * byte more, read the string and NULL-terminate it ourselves. */
914 if (!(res = av_malloc(size + 1)))
915 return AVERROR(ENOMEM);
916 if (avio_read(pb, (uint8_t *) res, size) != size) {
928 * Read the next element as binary data.
929 * 0 is success, < 0 is failure.
931 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
933 av_fast_padded_malloc(&bin->data, &bin->size, length);
935 return AVERROR(ENOMEM);
938 bin->pos = avio_tell(pb);
939 if (avio_read(pb, bin->data, length) != length) {
940 av_freep(&bin->data);
949 * Read the next element, but only the header. The contents
950 * are supposed to be sub-elements which can be read separately.
951 * 0 is success, < 0 is failure.
953 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
955 AVIOContext *pb = matroska->ctx->pb;
956 MatroskaLevel *level;
958 if (matroska->num_levels >= EBML_MAX_DEPTH) {
959 av_log(matroska->ctx, AV_LOG_ERROR,
960 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
961 return AVERROR(ENOSYS);
964 level = &matroska->levels[matroska->num_levels++];
965 level->start = avio_tell(pb);
966 level->length = length;
972 * Read signed/unsigned "EBML" numbers.
973 * Return: number of bytes processed, < 0 on error
975 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
976 uint8_t *data, uint32_t size, uint64_t *num)
979 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
980 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
984 * Same as above, but signed.
986 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
987 uint8_t *data, uint32_t size, int64_t *num)
992 /* read as unsigned number first */
993 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
996 /* make signed (weird way) */
997 *num = unum - ((1LL << (7 * res - 1)) - 1);
1002 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1003 EbmlSyntax *syntax, void *data);
1005 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1006 uint32_t id, void *data)
1009 for (i = 0; syntax[i].id; i++)
1010 if (id == syntax[i].id)
1012 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
1013 matroska->num_levels > 0 &&
1014 matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
1015 return 0; // we reached the end of an unknown size cluster
1016 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
1017 av_log(matroska->ctx, AV_LOG_DEBUG, "Unknown entry 0x%"PRIX32"\n", id);
1019 return ebml_parse_elem(matroska, &syntax[i], data);
1022 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1025 if (!matroska->current_id) {
1027 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
1029 // in live mode, finish parsing if EOF is reached.
1030 return (matroska->is_live && matroska->ctx->pb->eof_reached &&
1031 res == AVERROR_EOF) ? 1 : res;
1033 matroska->current_id = id | 1 << 7 * res;
1035 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
1038 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1043 for (i = 0; syntax[i].id; i++)
1044 switch (syntax[i].type) {
1046 *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
1049 *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
1053 // the default may be NULL
1054 if (syntax[i].def.s) {
1055 uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
1056 *dst = av_strdup(syntax[i].def.s);
1058 return AVERROR(ENOMEM);
1063 while (!res && !ebml_level_end(matroska))
1064 res = ebml_parse(matroska, syntax, data);
1069 static int is_ebml_id_valid(uint32_t id)
1071 // Due to endian nonsense in Matroska, the highest byte with any bits set
1072 // will contain the leading length bit. This bit in turn identifies the
1073 // total byte length of the element by its position within the byte.
1074 unsigned int bits = av_log2(id);
1075 return id && (bits + 7) / 8 == (8 - bits % 8);
1079 * Allocate and return the entry for the level1 element with the given ID. If
1080 * an entry already exists, return the existing entry.
1082 static MatroskaLevel1Element *matroska_find_level1_elem(MatroskaDemuxContext *matroska,
1086 MatroskaLevel1Element *elem;
1088 if (!is_ebml_id_valid(id))
1091 // Some files link to all clusters; useless.
1092 if (id == MATROSKA_ID_CLUSTER)
1095 // There can be multiple seekheads.
1096 if (id != MATROSKA_ID_SEEKHEAD) {
1097 for (i = 0; i < matroska->num_level1_elems; i++) {
1098 if (matroska->level1_elems[i].id == id)
1099 return &matroska->level1_elems[i];
1103 // Only a completely broken file would have more elements.
1104 // It also provides a low-effort way to escape from circular seekheads
1105 // (every iteration will add a level1 entry).
1106 if (matroska->num_level1_elems >= FF_ARRAY_ELEMS(matroska->level1_elems)) {
1107 av_log(matroska->ctx, AV_LOG_ERROR, "Too many level1 elements or circular seekheads.\n");
1111 elem = &matroska->level1_elems[matroska->num_level1_elems++];
1112 *elem = (MatroskaLevel1Element){.id = id};
1117 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1118 EbmlSyntax *syntax, void *data)
1120 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
1123 // max. 16 MB for strings
1124 [EBML_STR] = 0x1000000,
1125 [EBML_UTF8] = 0x1000000,
1126 // max. 256 MB for binary data
1127 [EBML_BIN] = 0x10000000,
1128 // no limits for anything else
1130 AVIOContext *pb = matroska->ctx->pb;
1131 uint32_t id = syntax->id;
1135 MatroskaLevel1Element *level1_elem;
1137 data = (char *) data + syntax->data_offset;
1138 if (syntax->list_elem_size) {
1139 EbmlList *list = data;
1140 newelem = av_realloc_array(list->elem, list->nb_elem + 1, syntax->list_elem_size);
1142 return AVERROR(ENOMEM);
1143 list->elem = newelem;
1144 data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
1145 memset(data, 0, syntax->list_elem_size);
1149 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
1150 matroska->current_id = 0;
1151 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
1153 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
1154 av_log(matroska->ctx, AV_LOG_ERROR,
1155 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
1156 length, max_lengths[syntax->type], syntax->type);
1157 return AVERROR_INVALIDDATA;
1161 switch (syntax->type) {
1163 res = ebml_read_uint(pb, length, data);
1166 res = ebml_read_sint(pb, length, data);
1169 res = ebml_read_float(pb, length, data);
1173 res = ebml_read_ascii(pb, length, data);
1176 res = ebml_read_binary(pb, length, data);
1180 if ((res = ebml_read_master(matroska, length)) < 0)
1182 if (id == MATROSKA_ID_SEGMENT)
1183 matroska->segment_start = avio_tell(matroska->ctx->pb);
1184 if (id == MATROSKA_ID_CUES)
1185 matroska->cues_parsing_deferred = 0;
1186 if (syntax->type == EBML_LEVEL1 &&
1187 (level1_elem = matroska_find_level1_elem(matroska, syntax->id))) {
1188 if (level1_elem->parsed)
1189 av_log(matroska->ctx, AV_LOG_ERROR, "Duplicate element\n");
1190 level1_elem->parsed = 1;
1192 return ebml_parse_nest(matroska, syntax->def.n, data);
1194 return ebml_parse_id(matroska, syntax->def.n, id, data);
1198 if (ffio_limit(pb, length) != length)
1199 return AVERROR(EIO);
1200 return avio_skip(pb, length) < 0 ? AVERROR(EIO) : 0;
1202 if (res == AVERROR_INVALIDDATA)
1203 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
1204 else if (res == AVERROR(EIO))
1205 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
1209 static void ebml_free(EbmlSyntax *syntax, void *data)
1212 for (i = 0; syntax[i].id; i++) {
1213 void *data_off = (char *) data + syntax[i].data_offset;
1214 switch (syntax[i].type) {
1220 av_freep(&((EbmlBin *) data_off)->data);
1224 if (syntax[i].list_elem_size) {
1225 EbmlList *list = data_off;
1226 char *ptr = list->elem;
1227 for (j = 0; j < list->nb_elem;
1228 j++, ptr += syntax[i].list_elem_size)
1229 ebml_free(syntax[i].def.n, ptr);
1230 av_freep(&list->elem);
1232 ebml_free(syntax[i].def.n, data_off);
1242 static int matroska_probe(AVProbeData *p)
1245 int len_mask = 0x80, size = 1, n = 1, i;
1248 if (AV_RB32(p->buf) != EBML_ID_HEADER)
1251 /* length of header */
1253 while (size <= 8 && !(total & len_mask)) {
1259 total &= (len_mask - 1);
1261 total = (total << 8) | p->buf[4 + n++];
1263 /* Does the probe data contain the whole header? */
1264 if (p->buf_size < 4 + size + total)
1267 /* The header should contain a known document type. For now,
1268 * we don't parse the whole header but simply check for the
1269 * availability of that array of characters inside the header.
1270 * Not fully fool-proof, but good enough. */
1271 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1272 size_t probelen = strlen(matroska_doctypes[i]);
1273 if (total < probelen)
1275 for (n = 4 + size; n <= 4 + size + total - probelen; n++)
1276 if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
1277 return AVPROBE_SCORE_MAX;
1280 // probably valid EBML header but no recognized doctype
1281 return AVPROBE_SCORE_EXTENSION;
1284 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1287 MatroskaTrack *tracks = matroska->tracks.elem;
1290 for (i = 0; i < matroska->tracks.nb_elem; i++)
1291 if (tracks[i].num == num)
1294 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1298 static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
1299 MatroskaTrack *track)
1301 MatroskaTrackEncoding *encodings = track->encodings.elem;
1302 uint8_t *data = *buf;
1303 int isize = *buf_size;
1304 uint8_t *pkt_data = NULL;
1305 uint8_t av_unused *newpktdata;
1306 int pkt_size = isize;
1310 if (pkt_size >= 10000000U)
1311 return AVERROR_INVALIDDATA;
1313 switch (encodings[0].compression.algo) {
1314 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1316 int header_size = encodings[0].compression.settings.size;
1317 uint8_t *header = encodings[0].compression.settings.data;
1319 if (header_size && !header) {
1320 av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1327 pkt_size = isize + header_size;
1328 pkt_data = av_malloc(pkt_size);
1330 return AVERROR(ENOMEM);
1332 memcpy(pkt_data, header, header_size);
1333 memcpy(pkt_data + header_size, data, isize);
1337 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1339 olen = pkt_size *= 3;
1340 newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1342 result = AVERROR(ENOMEM);
1345 pkt_data = newpktdata;
1346 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1347 } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
1349 result = AVERROR_INVALIDDATA;
1356 case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
1358 z_stream zstream = { 0 };
1359 if (inflateInit(&zstream) != Z_OK)
1361 zstream.next_in = data;
1362 zstream.avail_in = isize;
1365 newpktdata = av_realloc(pkt_data, pkt_size);
1367 inflateEnd(&zstream);
1368 result = AVERROR(ENOMEM);
1371 pkt_data = newpktdata;
1372 zstream.avail_out = pkt_size - zstream.total_out;
1373 zstream.next_out = pkt_data + zstream.total_out;
1374 result = inflate(&zstream, Z_NO_FLUSH);
1375 } while (result == Z_OK && pkt_size < 10000000);
1376 pkt_size = zstream.total_out;
1377 inflateEnd(&zstream);
1378 if (result != Z_STREAM_END) {
1379 if (result == Z_MEM_ERROR)
1380 result = AVERROR(ENOMEM);
1382 result = AVERROR_INVALIDDATA;
1389 case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
1391 bz_stream bzstream = { 0 };
1392 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1394 bzstream.next_in = data;
1395 bzstream.avail_in = isize;
1398 newpktdata = av_realloc(pkt_data, pkt_size);
1400 BZ2_bzDecompressEnd(&bzstream);
1401 result = AVERROR(ENOMEM);
1404 pkt_data = newpktdata;
1405 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1406 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1407 result = BZ2_bzDecompress(&bzstream);
1408 } while (result == BZ_OK && pkt_size < 10000000);
1409 pkt_size = bzstream.total_out_lo32;
1410 BZ2_bzDecompressEnd(&bzstream);
1411 if (result != BZ_STREAM_END) {
1412 if (result == BZ_MEM_ERROR)
1413 result = AVERROR(ENOMEM);
1415 result = AVERROR_INVALIDDATA;
1422 return AVERROR_INVALIDDATA;
1426 *buf_size = pkt_size;
1434 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1435 AVDictionary **metadata, char *prefix)
1437 MatroskaTag *tags = list->elem;
1441 for (i = 0; i < list->nb_elem; i++) {
1442 const char *lang = tags[i].lang &&
1443 strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1445 if (!tags[i].name) {
1446 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1450 snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1452 av_strlcpy(key, tags[i].name, sizeof(key));
1453 if (tags[i].def || !lang) {
1454 av_dict_set(metadata, key, tags[i].string, 0);
1455 if (tags[i].sub.nb_elem)
1456 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1459 av_strlcat(key, "-", sizeof(key));
1460 av_strlcat(key, lang, sizeof(key));
1461 av_dict_set(metadata, key, tags[i].string, 0);
1462 if (tags[i].sub.nb_elem)
1463 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1466 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1469 static void matroska_convert_tags(AVFormatContext *s)
1471 MatroskaDemuxContext *matroska = s->priv_data;
1472 MatroskaTags *tags = matroska->tags.elem;
1475 for (i = 0; i < matroska->tags.nb_elem; i++) {
1476 if (tags[i].target.attachuid) {
1477 MatroskaAttachment *attachment = matroska->attachments.elem;
1479 for (j = 0; j < matroska->attachments.nb_elem; j++) {
1480 if (attachment[j].uid == tags[i].target.attachuid &&
1481 attachment[j].stream) {
1482 matroska_convert_tag(s, &tags[i].tag,
1483 &attachment[j].stream->metadata, NULL);
1488 av_log(NULL, AV_LOG_WARNING,
1489 "The tags at index %d refer to a "
1490 "non-existent attachment %"PRId64".\n",
1491 i, tags[i].target.attachuid);
1493 } else if (tags[i].target.chapteruid) {
1494 MatroskaChapter *chapter = matroska->chapters.elem;
1496 for (j = 0; j < matroska->chapters.nb_elem; j++) {
1497 if (chapter[j].uid == tags[i].target.chapteruid &&
1498 chapter[j].chapter) {
1499 matroska_convert_tag(s, &tags[i].tag,
1500 &chapter[j].chapter->metadata, NULL);
1505 av_log(NULL, AV_LOG_WARNING,
1506 "The tags at index %d refer to a non-existent chapter "
1508 i, tags[i].target.chapteruid);
1510 } else if (tags[i].target.trackuid) {
1511 MatroskaTrack *track = matroska->tracks.elem;
1513 for (j = 0; j < matroska->tracks.nb_elem; j++) {
1514 if (track[j].uid == tags[i].target.trackuid &&
1516 matroska_convert_tag(s, &tags[i].tag,
1517 &track[j].stream->metadata, NULL);
1522 av_log(NULL, AV_LOG_WARNING,
1523 "The tags at index %d refer to a non-existent track "
1525 i, tags[i].target.trackuid);
1528 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1529 tags[i].target.type);
1534 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
1537 uint32_t level_up = matroska->level_up;
1538 uint32_t saved_id = matroska->current_id;
1539 int64_t before_pos = avio_tell(matroska->ctx->pb);
1540 MatroskaLevel level;
1545 offset = pos + matroska->segment_start;
1546 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1547 /* We don't want to lose our seekhead level, so we add
1548 * a dummy. This is a crude hack. */
1549 if (matroska->num_levels == EBML_MAX_DEPTH) {
1550 av_log(matroska->ctx, AV_LOG_INFO,
1551 "Max EBML element depth (%d) reached, "
1552 "cannot parse further.\n", EBML_MAX_DEPTH);
1553 ret = AVERROR_INVALIDDATA;
1556 level.length = (uint64_t) -1;
1557 matroska->levels[matroska->num_levels] = level;
1558 matroska->num_levels++;
1559 matroska->current_id = 0;
1561 ret = ebml_parse(matroska, matroska_segment, matroska);
1563 /* remove dummy level */
1564 while (matroska->num_levels) {
1565 uint64_t length = matroska->levels[--matroska->num_levels].length;
1566 if (length == (uint64_t) -1)
1572 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1573 matroska->level_up = level_up;
1574 matroska->current_id = saved_id;
1579 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1581 EbmlList *seekhead_list = &matroska->seekhead;
1584 // we should not do any seeking in the streaming case
1585 if (!matroska->ctx->pb->seekable)
1588 for (i = 0; i < seekhead_list->nb_elem; i++) {
1589 MatroskaSeekhead *seekheads = seekhead_list->elem;
1590 uint32_t id = seekheads[i].id;
1591 uint64_t pos = seekheads[i].pos;
1593 MatroskaLevel1Element *elem = matroska_find_level1_elem(matroska, id);
1594 if (!elem || elem->parsed)
1599 // defer cues parsing until we actually need cue data.
1600 if (id == MATROSKA_ID_CUES)
1603 if (matroska_parse_seekhead_entry(matroska, pos) < 0) {
1604 // mark index as broken
1605 matroska->cues_parsing_deferred = -1;
1613 static void matroska_add_index_entries(MatroskaDemuxContext *matroska)
1615 EbmlList *index_list;
1616 MatroskaIndex *index;
1617 uint64_t index_scale = 1;
1620 if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
1623 index_list = &matroska->index;
1624 index = index_list->elem;
1625 if (index_list->nb_elem < 2)
1627 if (index[1].time > 1E14 / matroska->time_scale) {
1628 av_log(matroska->ctx, AV_LOG_WARNING, "Dropping apparently-broken index.\n");
1631 for (i = 0; i < index_list->nb_elem; i++) {
1632 EbmlList *pos_list = &index[i].pos;
1633 MatroskaIndexPos *pos = pos_list->elem;
1634 for (j = 0; j < pos_list->nb_elem; j++) {
1635 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1637 if (track && track->stream)
1638 av_add_index_entry(track->stream,
1639 pos[j].pos + matroska->segment_start,
1640 index[i].time / index_scale, 0, 0,
1646 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1649 if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
1652 for (i = 0; i < matroska->num_level1_elems; i++) {
1653 MatroskaLevel1Element *elem = &matroska->level1_elems[i];
1654 if (elem->id == MATROSKA_ID_CUES && !elem->parsed) {
1655 if (matroska_parse_seekhead_entry(matroska, elem->pos) < 0)
1656 matroska->cues_parsing_deferred = -1;
1662 matroska_add_index_entries(matroska);
1665 static int matroska_aac_profile(char *codec_id)
1667 static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
1670 for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
1671 if (strstr(codec_id, aac_profiles[profile]))
1676 static int matroska_aac_sri(int samplerate)
1680 for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1681 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1686 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1689 /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1690 time_t creation_time = date_utc / 1000000000 + 978307200;
1691 struct tm tmpbuf, *ptm = gmtime_r(&creation_time, &tmpbuf);
1693 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1694 av_dict_set(metadata, "creation_time", buffer, 0);
1697 static int matroska_parse_flac(AVFormatContext *s,
1698 MatroskaTrack *track,
1701 AVStream *st = track->stream;
1702 uint8_t *p = track->codec_priv.data;
1703 int size = track->codec_priv.size;
1705 if (size < 8 + FLAC_STREAMINFO_SIZE || p[4] & 0x7f) {
1706 av_log(s, AV_LOG_WARNING, "Invalid FLAC private data\n");
1707 track->codec_priv.size = 0;
1711 track->codec_priv.size = 8 + FLAC_STREAMINFO_SIZE;
1713 p += track->codec_priv.size;
1714 size -= track->codec_priv.size;
1716 /* parse the remaining metadata blocks if present */
1718 int block_last, block_type, block_size;
1720 flac_parse_block_header(p, &block_last, &block_type, &block_size);
1724 if (block_size > size)
1727 /* check for the channel mask */
1728 if (block_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
1729 AVDictionary *dict = NULL;
1730 AVDictionaryEntry *chmask;
1732 ff_vorbis_comment(s, &dict, p, block_size, 0);
1733 chmask = av_dict_get(dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
1735 uint64_t mask = strtol(chmask->value, NULL, 0);
1736 if (!mask || mask & ~0x3ffffULL) {
1737 av_log(s, AV_LOG_WARNING,
1738 "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
1740 st->codecpar->channel_layout = mask;
1742 av_dict_free(&dict);
1752 static void mkv_stereo_mode_display_mul(int stereo_mode, int *h_width, int *h_height)
1754 switch (stereo_mode) {
1755 case MATROSKA_VIDEO_STEREOMODE_TYPE_MONO:
1756 case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_RL:
1757 case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR:
1758 case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_RL:
1759 case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR:
1761 case MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT:
1762 case MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT:
1763 case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_RL:
1764 case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR:
1767 case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTTOM_TOP:
1768 case MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM:
1769 case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_RL:
1770 case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR:
1776 static int mkv_parse_video_color(AVStream *st, const MatroskaTrack *track) {
1777 const MatroskaMasteringMeta* mastering_meta =
1778 &track->video.color.mastering_meta;
1779 // Mastering primaries are CIE 1931 coords, and must be > 0.
1780 const int has_mastering_primaries =
1781 mastering_meta->r_x > 0 && mastering_meta->r_y > 0 &&
1782 mastering_meta->g_x > 0 && mastering_meta->g_y > 0 &&
1783 mastering_meta->b_x > 0 && mastering_meta->b_y > 0 &&
1784 mastering_meta->white_x > 0 && mastering_meta->white_y > 0;
1785 const int has_mastering_luminance = mastering_meta->max_luminance > 0;
1787 if (track->video.color.matrix_coefficients != AVCOL_SPC_RESERVED)
1788 st->codecpar->color_space = track->video.color.matrix_coefficients;
1789 if (track->video.color.primaries != AVCOL_PRI_RESERVED)
1790 st->codecpar->color_primaries = track->video.color.primaries;
1791 if (track->video.color.transfer_characteristics != AVCOL_TRC_RESERVED)
1792 st->codecpar->color_trc = track->video.color.transfer_characteristics;
1793 if (track->video.color.range != AVCOL_RANGE_UNSPECIFIED &&
1794 track->video.color.range <= AVCOL_RANGE_JPEG)
1795 st->codecpar->color_range = track->video.color.range;
1797 if (has_mastering_primaries || has_mastering_luminance) {
1798 // Use similar rationals as other standards.
1799 const int chroma_den = 50000;
1800 const int luma_den = 10000;
1801 AVMasteringDisplayMetadata *metadata =
1802 (AVMasteringDisplayMetadata*) av_stream_new_side_data(
1803 st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
1804 sizeof(AVMasteringDisplayMetadata));
1806 return AVERROR(ENOMEM);
1808 memset(metadata, 0, sizeof(AVMasteringDisplayMetadata));
1809 if (has_mastering_primaries) {
1810 metadata->display_primaries[0][0] = av_make_q(
1811 round(mastering_meta->r_x * chroma_den), chroma_den);
1812 metadata->display_primaries[0][1] = av_make_q(
1813 round(mastering_meta->r_y * chroma_den), chroma_den);
1814 metadata->display_primaries[1][0] = av_make_q(
1815 round(mastering_meta->g_x * chroma_den), chroma_den);
1816 metadata->display_primaries[1][1] = av_make_q(
1817 round(mastering_meta->g_y * chroma_den), chroma_den);
1818 metadata->display_primaries[2][0] = av_make_q(
1819 round(mastering_meta->b_x * chroma_den), chroma_den);
1820 metadata->display_primaries[2][1] = av_make_q(
1821 round(mastering_meta->b_y * chroma_den), chroma_den);
1822 metadata->white_point[0] = av_make_q(
1823 round(mastering_meta->white_x * chroma_den), chroma_den);
1824 metadata->white_point[1] = av_make_q(
1825 round(mastering_meta->white_y * chroma_den), chroma_den);
1826 metadata->has_primaries = 1;
1828 if (has_mastering_luminance) {
1829 metadata->max_luminance = av_make_q(
1830 round(mastering_meta->max_luminance * luma_den), luma_den);
1831 metadata->min_luminance = av_make_q(
1832 round(mastering_meta->min_luminance * luma_den), luma_den);
1833 metadata->has_luminance = 1;
1839 static int get_qt_codec(MatroskaTrack *track, uint32_t *fourcc, enum AVCodecID *codec_id)
1841 const AVCodecTag *codec_tags;
1843 codec_tags = track->type == MATROSKA_TRACK_TYPE_VIDEO ?
1844 ff_codec_movvideo_tags : ff_codec_movaudio_tags;
1846 /* Normalize noncompliant private data that starts with the fourcc
1847 * by expanding/shifting the data by 4 bytes and storing the data
1848 * size at the start. */
1849 if (ff_codec_get_id(codec_tags, AV_RL32(track->codec_priv.data))) {
1850 uint8_t *p = av_realloc(track->codec_priv.data,
1851 track->codec_priv.size + 4);
1853 return AVERROR(ENOMEM);
1854 memmove(p + 4, p, track->codec_priv.size);
1855 track->codec_priv.data = p;
1856 track->codec_priv.size += 4;
1857 AV_WB32(track->codec_priv.data, track->codec_priv.size);
1860 *fourcc = AV_RL32(track->codec_priv.data + 4);
1861 *codec_id = ff_codec_get_id(codec_tags, *fourcc);
1866 static int matroska_parse_tracks(AVFormatContext *s)
1868 MatroskaDemuxContext *matroska = s->priv_data;
1869 MatroskaTrack *tracks = matroska->tracks.elem;
1874 for (i = 0; i < matroska->tracks.nb_elem; i++) {
1875 MatroskaTrack *track = &tracks[i];
1876 enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1877 EbmlList *encodings_list = &track->encodings;
1878 MatroskaTrackEncoding *encodings = encodings_list->elem;
1879 uint8_t *extradata = NULL;
1880 int extradata_size = 0;
1881 int extradata_offset = 0;
1882 uint32_t fourcc = 0;
1884 char* key_id_base64 = NULL;
1887 /* Apply some sanity checks. */
1888 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1889 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1890 track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
1891 track->type != MATROSKA_TRACK_TYPE_METADATA) {
1892 av_log(matroska->ctx, AV_LOG_INFO,
1893 "Unknown or unsupported track type %"PRIu64"\n",
1897 if (!track->codec_id)
1900 if (track->audio.samplerate < 0 || track->audio.samplerate > INT_MAX ||
1901 isnan(track->audio.samplerate)) {
1902 av_log(matroska->ctx, AV_LOG_WARNING,
1903 "Invalid sample rate %f, defaulting to 8000 instead.\n",
1904 track->audio.samplerate);
1905 track->audio.samplerate = 8000;
1908 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1909 if (!track->default_duration && track->video.frame_rate > 0)
1910 track->default_duration = 1000000000 / track->video.frame_rate;
1911 if (track->video.display_width == -1)
1912 track->video.display_width = track->video.pixel_width;
1913 if (track->video.display_height == -1)
1914 track->video.display_height = track->video.pixel_height;
1915 if (track->video.color_space.size == 4)
1916 fourcc = AV_RL32(track->video.color_space.data);
1917 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1918 if (!track->audio.out_samplerate)
1919 track->audio.out_samplerate = track->audio.samplerate;
1921 if (encodings_list->nb_elem > 1) {
1922 av_log(matroska->ctx, AV_LOG_ERROR,
1923 "Multiple combined encodings not supported");
1924 } else if (encodings_list->nb_elem == 1) {
1925 if (encodings[0].type) {
1926 if (encodings[0].encryption.key_id.size > 0) {
1927 /* Save the encryption key id to be stored later as a
1929 const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
1930 key_id_base64 = av_malloc(b64_size);
1931 if (key_id_base64 == NULL)
1932 return AVERROR(ENOMEM);
1934 av_base64_encode(key_id_base64, b64_size,
1935 encodings[0].encryption.key_id.data,
1936 encodings[0].encryption.key_id.size);
1938 encodings[0].scope = 0;
1939 av_log(matroska->ctx, AV_LOG_ERROR,
1940 "Unsupported encoding type");
1944 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1947 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1950 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1952 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
1953 encodings[0].scope = 0;
1954 av_log(matroska->ctx, AV_LOG_ERROR,
1955 "Unsupported encoding type");
1956 } else if (track->codec_priv.size && encodings[0].scope & 2) {
1957 uint8_t *codec_priv = track->codec_priv.data;
1958 int ret = matroska_decode_buffer(&track->codec_priv.data,
1959 &track->codec_priv.size,
1962 track->codec_priv.data = NULL;
1963 track->codec_priv.size = 0;
1964 av_log(matroska->ctx, AV_LOG_ERROR,
1965 "Failed to decode codec private data\n");
1968 if (codec_priv != track->codec_priv.data)
1969 av_free(codec_priv);
1973 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1974 if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1975 strlen(ff_mkv_codec_tags[j].str))) {
1976 codec_id = ff_mkv_codec_tags[j].id;
1981 st = track->stream = avformat_new_stream(s, NULL);
1983 av_free(key_id_base64);
1984 return AVERROR(ENOMEM);
1987 if (key_id_base64) {
1988 /* export encryption key id as base64 metadata tag */
1989 av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
1990 av_freep(&key_id_base64);
1993 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
1994 track->codec_priv.size >= 40 &&
1995 track->codec_priv.data) {
1996 track->ms_compat = 1;
1997 bit_depth = AV_RL16(track->codec_priv.data + 14);
1998 fourcc = AV_RL32(track->codec_priv.data + 16);
1999 codec_id = ff_codec_get_id(ff_codec_bmp_tags,
2002 codec_id = ff_codec_get_id(ff_codec_movvideo_tags,
2004 extradata_offset = 40;
2005 } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
2006 track->codec_priv.size >= 14 &&
2007 track->codec_priv.data) {
2009 ffio_init_context(&b, track->codec_priv.data,
2010 track->codec_priv.size,
2011 0, NULL, NULL, NULL, NULL);
2012 ret = ff_get_wav_header(s, &b, st->codecpar, track->codec_priv.size, 0);
2015 codec_id = st->codecpar->codec_id;
2016 fourcc = st->codecpar->codec_tag;
2017 extradata_offset = FFMIN(track->codec_priv.size, 18);
2018 } else if (!strcmp(track->codec_id, "A_QUICKTIME")
2019 /* Normally 36, but allow noncompliant private data */
2020 && (track->codec_priv.size >= 32)
2021 && (track->codec_priv.data)) {
2022 uint16_t sample_size;
2023 int ret = get_qt_codec(track, &fourcc, &codec_id);
2026 sample_size = AV_RB16(track->codec_priv.data + 26);
2028 if (sample_size == 8) {
2029 fourcc = MKTAG('r','a','w',' ');
2030 codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
2031 } else if (sample_size == 16) {
2032 fourcc = MKTAG('t','w','o','s');
2033 codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
2036 if ((fourcc == MKTAG('t','w','o','s') ||
2037 fourcc == MKTAG('s','o','w','t')) &&
2039 codec_id = AV_CODEC_ID_PCM_S8;
2040 } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
2041 (track->codec_priv.size >= 21) &&
2042 (track->codec_priv.data)) {
2043 int ret = get_qt_codec(track, &fourcc, &codec_id);
2046 if (codec_id == AV_CODEC_ID_NONE && AV_RL32(track->codec_priv.data+4) == AV_RL32("SMI ")) {
2047 fourcc = MKTAG('S','V','Q','3');
2048 codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
2050 if (codec_id == AV_CODEC_ID_NONE) {
2052 av_get_codec_tag_string(buf, sizeof(buf), fourcc);
2053 av_log(matroska->ctx, AV_LOG_ERROR,
2054 "mov FourCC not found %s.\n", buf);
2056 if (track->codec_priv.size >= 86) {
2057 bit_depth = AV_RB16(track->codec_priv.data + 82);
2058 ffio_init_context(&b, track->codec_priv.data,
2059 track->codec_priv.size,
2060 0, NULL, NULL, NULL, NULL);
2061 if (ff_get_qtpalette(codec_id, &b, track->palette)) {
2063 track->has_palette = 1;
2066 } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
2067 switch (track->audio.bitdepth) {
2069 codec_id = AV_CODEC_ID_PCM_U8;
2072 codec_id = AV_CODEC_ID_PCM_S24BE;
2075 codec_id = AV_CODEC_ID_PCM_S32BE;
2078 } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
2079 switch (track->audio.bitdepth) {
2081 codec_id = AV_CODEC_ID_PCM_U8;
2084 codec_id = AV_CODEC_ID_PCM_S24LE;
2087 codec_id = AV_CODEC_ID_PCM_S32LE;
2090 } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
2091 track->audio.bitdepth == 64) {
2092 codec_id = AV_CODEC_ID_PCM_F64LE;
2093 } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
2094 int profile = matroska_aac_profile(track->codec_id);
2095 int sri = matroska_aac_sri(track->audio.samplerate);
2096 extradata = av_mallocz(5 + AV_INPUT_BUFFER_PADDING_SIZE);
2098 return AVERROR(ENOMEM);
2099 extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
2100 extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
2101 if (strstr(track->codec_id, "SBR")) {
2102 sri = matroska_aac_sri(track->audio.out_samplerate);
2103 extradata[2] = 0x56;
2104 extradata[3] = 0xE5;
2105 extradata[4] = 0x80 | (sri << 3);
2109 } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - AV_INPUT_BUFFER_PADDING_SIZE) {
2110 /* Only ALAC's magic cookie is stored in Matroska's track headers.
2111 * Create the "atom size", "tag", and "tag version" fields the
2112 * decoder expects manually. */
2113 extradata_size = 12 + track->codec_priv.size;
2114 extradata = av_mallocz(extradata_size +
2115 AV_INPUT_BUFFER_PADDING_SIZE);
2117 return AVERROR(ENOMEM);
2118 AV_WB32(extradata, extradata_size);
2119 memcpy(&extradata[4], "alac", 4);
2120 AV_WB32(&extradata[8], 0);
2121 memcpy(&extradata[12], track->codec_priv.data,
2122 track->codec_priv.size);
2123 } else if (codec_id == AV_CODEC_ID_TTA) {
2124 extradata_size = 30;
2125 extradata = av_mallocz(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2127 return AVERROR(ENOMEM);
2128 ffio_init_context(&b, extradata, extradata_size, 1,
2129 NULL, NULL, NULL, NULL);
2130 avio_write(&b, "TTA1", 4);
2132 if (track->audio.channels > UINT16_MAX ||
2133 track->audio.bitdepth > UINT16_MAX) {
2134 av_log(matroska->ctx, AV_LOG_WARNING,
2135 "Too large audio channel number %"PRIu64
2136 " or bitdepth %"PRIu64". Skipping track.\n",
2137 track->audio.channels, track->audio.bitdepth);
2138 av_freep(&extradata);
2139 if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
2140 return AVERROR_INVALIDDATA;
2144 avio_wl16(&b, track->audio.channels);
2145 avio_wl16(&b, track->audio.bitdepth);
2146 if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
2147 return AVERROR_INVALIDDATA;
2148 avio_wl32(&b, track->audio.out_samplerate);
2149 avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale),
2150 track->audio.out_samplerate,
2151 AV_TIME_BASE * 1000));
2152 } else if (codec_id == AV_CODEC_ID_RV10 ||
2153 codec_id == AV_CODEC_ID_RV20 ||
2154 codec_id == AV_CODEC_ID_RV30 ||
2155 codec_id == AV_CODEC_ID_RV40) {
2156 extradata_offset = 26;
2157 } else if (codec_id == AV_CODEC_ID_RA_144) {
2158 track->audio.out_samplerate = 8000;
2159 track->audio.channels = 1;
2160 } else if ((codec_id == AV_CODEC_ID_RA_288 ||
2161 codec_id == AV_CODEC_ID_COOK ||
2162 codec_id == AV_CODEC_ID_ATRAC3 ||
2163 codec_id == AV_CODEC_ID_SIPR)
2164 && track->codec_priv.data) {
2167 ffio_init_context(&b, track->codec_priv.data,
2168 track->codec_priv.size,
2169 0, NULL, NULL, NULL, NULL);
2171 flavor = avio_rb16(&b);
2172 track->audio.coded_framesize = avio_rb32(&b);
2174 track->audio.sub_packet_h = avio_rb16(&b);
2175 track->audio.frame_size = avio_rb16(&b);
2176 track->audio.sub_packet_size = avio_rb16(&b);
2178 track->audio.coded_framesize <= 0 ||
2179 track->audio.sub_packet_h <= 0 ||
2180 track->audio.frame_size <= 0 ||
2181 track->audio.sub_packet_size <= 0)
2182 return AVERROR_INVALIDDATA;
2183 track->audio.buf = av_malloc_array(track->audio.sub_packet_h,
2184 track->audio.frame_size);
2185 if (!track->audio.buf)
2186 return AVERROR(ENOMEM);
2187 if (codec_id == AV_CODEC_ID_RA_288) {
2188 st->codecpar->block_align = track->audio.coded_framesize;
2189 track->codec_priv.size = 0;
2191 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
2192 static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
2193 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
2194 st->codecpar->bit_rate = sipr_bit_rate[flavor];
2196 st->codecpar->block_align = track->audio.sub_packet_size;
2197 extradata_offset = 78;
2199 } else if (codec_id == AV_CODEC_ID_FLAC && track->codec_priv.size) {
2200 ret = matroska_parse_flac(s, track, &extradata_offset);
2203 } else if (codec_id == AV_CODEC_ID_PRORES && track->codec_priv.size == 4) {
2204 fourcc = AV_RL32(track->codec_priv.data);
2206 track->codec_priv.size -= extradata_offset;
2208 if (codec_id == AV_CODEC_ID_NONE)
2209 av_log(matroska->ctx, AV_LOG_INFO,
2210 "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
2212 if (track->time_scale < 0.01)
2213 track->time_scale = 1.0;
2214 avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
2215 1000 * 1000 * 1000); /* 64 bit pts in ns */
2217 /* convert the delay from ns to the track timebase */
2218 track->codec_delay = av_rescale_q(track->codec_delay,
2219 (AVRational){ 1, 1000000000 },
2222 st->codecpar->codec_id = codec_id;
2224 if (strcmp(track->language, "und"))
2225 av_dict_set(&st->metadata, "language", track->language, 0);
2226 av_dict_set(&st->metadata, "title", track->name, 0);
2228 if (track->flag_default)
2229 st->disposition |= AV_DISPOSITION_DEFAULT;
2230 if (track->flag_forced)
2231 st->disposition |= AV_DISPOSITION_FORCED;
2233 if (!st->codecpar->extradata) {
2235 st->codecpar->extradata = extradata;
2236 st->codecpar->extradata_size = extradata_size;
2237 } else if (track->codec_priv.data && track->codec_priv.size > 0) {
2238 if (ff_alloc_extradata(st->codecpar, track->codec_priv.size))
2239 return AVERROR(ENOMEM);
2240 memcpy(st->codecpar->extradata,
2241 track->codec_priv.data + extradata_offset,
2242 track->codec_priv.size);
2246 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2247 MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
2248 int display_width_mul = 1;
2249 int display_height_mul = 1;
2251 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2252 st->codecpar->codec_tag = fourcc;
2254 st->codecpar->bits_per_coded_sample = bit_depth;
2255 st->codecpar->width = track->video.pixel_width;
2256 st->codecpar->height = track->video.pixel_height;
2258 if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
2259 mkv_stereo_mode_display_mul(track->video.stereo_mode, &display_width_mul, &display_height_mul);
2261 av_reduce(&st->sample_aspect_ratio.num,
2262 &st->sample_aspect_ratio.den,
2263 st->codecpar->height * track->video.display_width * display_width_mul,
2264 st->codecpar->width * track->video.display_height * display_height_mul,
2266 if (st->codecpar->codec_id != AV_CODEC_ID_HEVC)
2267 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2269 if (track->default_duration) {
2270 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2271 1000000000, track->default_duration, 30000);
2272 #if FF_API_R_FRAME_RATE
2273 if ( st->avg_frame_rate.num < st->avg_frame_rate.den * 1000LL
2274 && st->avg_frame_rate.num > st->avg_frame_rate.den * 5LL)
2275 st->r_frame_rate = st->avg_frame_rate;
2279 /* export stereo mode flag as metadata tag */
2280 if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
2281 av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
2283 /* export alpha mode flag as metadata tag */
2284 if (track->video.alpha_mode)
2285 av_dict_set(&st->metadata, "alpha_mode", "1", 0);
2287 /* if we have virtual track, mark the real tracks */
2288 for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
2290 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
2292 snprintf(buf, sizeof(buf), "%s_%d",
2293 ff_matroska_video_stereo_plane[planes[j].type], i);
2294 for (k=0; k < matroska->tracks.nb_elem; k++)
2295 if (planes[j].uid == tracks[k].uid && tracks[k].stream) {
2296 av_dict_set(&tracks[k].stream->metadata,
2297 "stereo_mode", buf, 0);
2301 // add stream level stereo3d side data if it is a supported format
2302 if (track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
2303 track->video.stereo_mode != 10 && track->video.stereo_mode != 12) {
2304 int ret = ff_mkv_stereo3d_conv(st, track->video.stereo_mode);
2309 if (s->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2310 int ret = mkv_parse_video_color(st, track);
2314 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2315 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2316 st->codecpar->codec_tag = fourcc;
2317 st->codecpar->sample_rate = track->audio.out_samplerate;
2318 st->codecpar->channels = track->audio.channels;
2319 if (!st->codecpar->bits_per_coded_sample)
2320 st->codecpar->bits_per_coded_sample = track->audio.bitdepth;
2321 if (st->codecpar->codec_id == AV_CODEC_ID_MP3)
2322 st->need_parsing = AVSTREAM_PARSE_FULL;
2323 else if (st->codecpar->codec_id != AV_CODEC_ID_AAC)
2324 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2325 if (track->codec_delay > 0) {
2326 st->codecpar->initial_padding = av_rescale_q(track->codec_delay,
2328 (AVRational){1, st->codecpar->sample_rate});
2330 if (track->seek_preroll > 0) {
2331 st->codecpar->seek_preroll = av_rescale_q(track->seek_preroll,
2332 (AVRational){1, 1000000000},
2333 (AVRational){1, st->codecpar->sample_rate});
2335 } else if (codec_id == AV_CODEC_ID_WEBVTT) {
2336 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2338 if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
2339 st->disposition |= AV_DISPOSITION_CAPTIONS;
2340 } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
2341 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2342 } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
2343 st->disposition |= AV_DISPOSITION_METADATA;
2345 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2346 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2347 if (st->codecpar->codec_id == AV_CODEC_ID_ASS)
2348 matroska->contains_ssa = 1;
2355 static int matroska_read_header(AVFormatContext *s)
2357 MatroskaDemuxContext *matroska = s->priv_data;
2358 EbmlList *attachments_list = &matroska->attachments;
2359 EbmlList *chapters_list = &matroska->chapters;
2360 MatroskaAttachment *attachments;
2361 MatroskaChapter *chapters;
2362 uint64_t max_start = 0;
2368 matroska->cues_parsing_deferred = 1;
2370 /* First read the EBML header. */
2371 if (ebml_parse(matroska, ebml_syntax, &ebml) || !ebml.doctype) {
2372 av_log(matroska->ctx, AV_LOG_ERROR, "EBML header parsing failed\n");
2373 ebml_free(ebml_syntax, &ebml);
2374 return AVERROR_INVALIDDATA;
2376 if (ebml.version > EBML_VERSION ||
2377 ebml.max_size > sizeof(uint64_t) ||
2378 ebml.id_length > sizeof(uint32_t) ||
2379 ebml.doctype_version > 3) {
2380 av_log(matroska->ctx, AV_LOG_ERROR,
2381 "EBML header using unsupported features\n"
2382 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
2383 ebml.version, ebml.doctype, ebml.doctype_version);
2384 ebml_free(ebml_syntax, &ebml);
2385 return AVERROR_PATCHWELCOME;
2386 } else if (ebml.doctype_version == 3) {
2387 av_log(matroska->ctx, AV_LOG_WARNING,
2388 "EBML header using unsupported features\n"
2389 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
2390 ebml.version, ebml.doctype, ebml.doctype_version);
2392 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
2393 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
2395 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
2396 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
2397 if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
2398 ebml_free(ebml_syntax, &ebml);
2399 return AVERROR_INVALIDDATA;
2402 ebml_free(ebml_syntax, &ebml);
2404 /* The next thing is a segment. */
2405 pos = avio_tell(matroska->ctx->pb);
2406 res = ebml_parse(matroska, matroska_segments, matroska);
2407 // try resyncing until we find a EBML_STOP type element.
2409 res = matroska_resync(matroska, pos);
2412 pos = avio_tell(matroska->ctx->pb);
2413 res = ebml_parse(matroska, matroska_segment, matroska);
2415 matroska_execute_seekhead(matroska);
2417 if (!matroska->time_scale)
2418 matroska->time_scale = 1000000;
2419 if (matroska->duration)
2420 matroska->ctx->duration = matroska->duration * matroska->time_scale *
2421 1000 / AV_TIME_BASE;
2422 av_dict_set(&s->metadata, "title", matroska->title, 0);
2423 av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
2425 if (matroska->date_utc.size == 8)
2426 matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
2428 res = matroska_parse_tracks(s);
2432 attachments = attachments_list->elem;
2433 for (j = 0; j < attachments_list->nb_elem; j++) {
2434 if (!(attachments[j].filename && attachments[j].mime &&
2435 attachments[j].bin.data && attachments[j].bin.size > 0)) {
2436 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2438 AVStream *st = avformat_new_stream(s, NULL);
2441 av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
2442 av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
2443 st->codecpar->codec_id = AV_CODEC_ID_NONE;
2445 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2446 if (!strncmp(ff_mkv_image_mime_tags[i].str, attachments[j].mime,
2447 strlen(ff_mkv_image_mime_tags[i].str))) {
2448 st->codecpar->codec_id = ff_mkv_image_mime_tags[i].id;
2453 attachments[j].stream = st;
2455 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
2456 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
2457 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2459 av_init_packet(&st->attached_pic);
2460 if ((res = av_new_packet(&st->attached_pic, attachments[j].bin.size)) < 0)
2462 memcpy(st->attached_pic.data, attachments[j].bin.data, attachments[j].bin.size);
2463 st->attached_pic.stream_index = st->index;
2464 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
2466 st->codecpar->codec_type = AVMEDIA_TYPE_ATTACHMENT;
2467 if (ff_alloc_extradata(st->codecpar, attachments[j].bin.size))
2469 memcpy(st->codecpar->extradata, attachments[j].bin.data,
2470 attachments[j].bin.size);
2472 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2473 if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
2474 strlen(ff_mkv_mime_tags[i].str))) {
2475 st->codecpar->codec_id = ff_mkv_mime_tags[i].id;
2483 chapters = chapters_list->elem;
2484 for (i = 0; i < chapters_list->nb_elem; i++)
2485 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
2486 (max_start == 0 || chapters[i].start > max_start)) {
2487 chapters[i].chapter =
2488 avpriv_new_chapter(s, chapters[i].uid,
2489 (AVRational) { 1, 1000000000 },
2490 chapters[i].start, chapters[i].end,
2492 if (chapters[i].chapter) {
2493 av_dict_set(&chapters[i].chapter->metadata,
2494 "title", chapters[i].title, 0);
2496 max_start = chapters[i].start;
2499 matroska_add_index_entries(matroska);
2501 matroska_convert_tags(s);
2507 * Put one packet in an application-supplied AVPacket struct.
2508 * Returns 0 on success or -1 on failure.
2510 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
2513 if (matroska->num_packets > 0) {
2514 MatroskaTrack *tracks = matroska->tracks.elem;
2515 MatroskaTrack *track;
2516 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
2517 av_freep(&matroska->packets[0]);
2518 track = &tracks[pkt->stream_index];
2519 if (track->has_palette) {
2520 uint8_t *pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2522 av_log(matroska->ctx, AV_LOG_ERROR, "Cannot append palette to packet\n");
2524 memcpy(pal, track->palette, AVPALETTE_SIZE);
2526 track->has_palette = 0;
2528 if (matroska->num_packets > 1) {
2530 memmove(&matroska->packets[0], &matroska->packets[1],
2531 (matroska->num_packets - 1) * sizeof(AVPacket *));
2532 newpackets = av_realloc(matroska->packets,
2533 (matroska->num_packets - 1) *
2534 sizeof(AVPacket *));
2536 matroska->packets = newpackets;
2538 av_freep(&matroska->packets);
2539 matroska->prev_pkt = NULL;
2541 matroska->num_packets--;
2549 * Free all packets in our internal queue.
2551 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2553 matroska->prev_pkt = NULL;
2554 if (matroska->packets) {
2556 for (n = 0; n < matroska->num_packets; n++) {
2557 av_packet_unref(matroska->packets[n]);
2558 av_freep(&matroska->packets[n]);
2560 av_freep(&matroska->packets);
2561 matroska->num_packets = 0;
2565 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2566 int *buf_size, int type,
2567 uint32_t **lace_buf, int *laces)
2569 int res = 0, n, size = *buf_size;
2570 uint8_t *data = *buf;
2571 uint32_t *lace_size;
2575 *lace_buf = av_mallocz(sizeof(int));
2577 return AVERROR(ENOMEM);
2579 *lace_buf[0] = size;
2583 av_assert0(size > 0);
2587 lace_size = av_mallocz(*laces * sizeof(int));
2589 return AVERROR(ENOMEM);
2592 case 0x1: /* Xiph lacing */
2596 for (n = 0; res == 0 && n < *laces - 1; n++) {
2598 if (size <= total) {
2599 res = AVERROR_INVALIDDATA;
2604 lace_size[n] += temp;
2611 if (size <= total) {
2612 res = AVERROR_INVALIDDATA;
2616 lace_size[n] = size - total;
2620 case 0x2: /* fixed-size lacing */
2621 if (size % (*laces)) {
2622 res = AVERROR_INVALIDDATA;
2625 for (n = 0; n < *laces; n++)
2626 lace_size[n] = size / *laces;
2629 case 0x3: /* EBML lacing */
2633 n = matroska_ebmlnum_uint(matroska, data, size, &num);
2634 if (n < 0 || num > INT_MAX) {
2635 av_log(matroska->ctx, AV_LOG_INFO,
2636 "EBML block data error\n");
2637 res = n<0 ? n : AVERROR_INVALIDDATA;
2642 total = lace_size[0] = num;
2643 for (n = 1; res == 0 && n < *laces - 1; n++) {
2646 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2647 if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
2648 av_log(matroska->ctx, AV_LOG_INFO,
2649 "EBML block data error\n");
2650 res = r<0 ? r : AVERROR_INVALIDDATA;
2655 lace_size[n] = lace_size[n - 1] + snum;
2656 total += lace_size[n];
2658 if (size <= total) {
2659 res = AVERROR_INVALIDDATA;
2662 lace_size[*laces - 1] = size - total;
2668 *lace_buf = lace_size;
2674 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2675 MatroskaTrack *track, AVStream *st,
2676 uint8_t *data, int size, uint64_t timecode,
2679 int a = st->codecpar->block_align;
2680 int sps = track->audio.sub_packet_size;
2681 int cfs = track->audio.coded_framesize;
2682 int h = track->audio.sub_packet_h;
2683 int y = track->audio.sub_packet_cnt;
2684 int w = track->audio.frame_size;
2687 if (!track->audio.pkt_cnt) {
2688 if (track->audio.sub_packet_cnt == 0)
2689 track->audio.buf_timecode = timecode;
2690 if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
2691 if (size < cfs * h / 2) {
2692 av_log(matroska->ctx, AV_LOG_ERROR,
2693 "Corrupt int4 RM-style audio packet size\n");
2694 return AVERROR_INVALIDDATA;
2696 for (x = 0; x < h / 2; x++)
2697 memcpy(track->audio.buf + x * 2 * w + y * cfs,
2698 data + x * cfs, cfs);
2699 } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
2701 av_log(matroska->ctx, AV_LOG_ERROR,
2702 "Corrupt sipr RM-style audio packet size\n");
2703 return AVERROR_INVALIDDATA;
2705 memcpy(track->audio.buf + y * w, data, w);
2707 if (size < sps * w / sps || h<=0 || w%sps) {
2708 av_log(matroska->ctx, AV_LOG_ERROR,
2709 "Corrupt generic RM-style audio packet size\n");
2710 return AVERROR_INVALIDDATA;
2712 for (x = 0; x < w / sps; x++)
2713 memcpy(track->audio.buf +
2714 sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
2715 data + x * sps, sps);
2718 if (++track->audio.sub_packet_cnt >= h) {
2719 if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
2720 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2721 track->audio.sub_packet_cnt = 0;
2722 track->audio.pkt_cnt = h * w / a;
2726 while (track->audio.pkt_cnt) {
2728 AVPacket *pkt = av_mallocz(sizeof(AVPacket));
2730 return AVERROR(ENOMEM);
2732 ret = av_new_packet(pkt, a);
2738 track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
2740 pkt->pts = track->audio.buf_timecode;
2741 track->audio.buf_timecode = AV_NOPTS_VALUE;
2743 pkt->stream_index = st->index;
2744 dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2750 /* reconstruct full wavpack blocks from mangled matroska ones */
2751 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
2752 uint8_t **pdst, int *size)
2754 uint8_t *dst = NULL;
2759 int ret, offset = 0;
2761 if (srclen < 12 || track->stream->codecpar->extradata_size < 2)
2762 return AVERROR_INVALIDDATA;
2764 ver = AV_RL16(track->stream->codecpar->extradata);
2766 samples = AV_RL32(src);
2770 while (srclen >= 8) {
2775 uint32_t flags = AV_RL32(src);
2776 uint32_t crc = AV_RL32(src + 4);
2780 multiblock = (flags & 0x1800) != 0x1800;
2783 ret = AVERROR_INVALIDDATA;
2786 blocksize = AV_RL32(src);
2792 if (blocksize > srclen) {
2793 ret = AVERROR_INVALIDDATA;
2797 tmp = av_realloc(dst, dstlen + blocksize + 32);
2799 ret = AVERROR(ENOMEM);
2803 dstlen += blocksize + 32;
2805 AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
2806 AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
2807 AV_WL16(dst + offset + 8, ver); // version
2808 AV_WL16(dst + offset + 10, 0); // track/index_no
2809 AV_WL32(dst + offset + 12, 0); // total samples
2810 AV_WL32(dst + offset + 16, 0); // block index
2811 AV_WL32(dst + offset + 20, samples); // number of samples
2812 AV_WL32(dst + offset + 24, flags); // flags
2813 AV_WL32(dst + offset + 28, crc); // crc
2814 memcpy(dst + offset + 32, src, blocksize); // block data
2817 srclen -= blocksize;
2818 offset += blocksize + 32;
2831 static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
2832 MatroskaTrack *track,
2834 uint8_t *data, int data_len,
2840 uint8_t *id, *settings, *text, *buf;
2841 int id_len, settings_len, text_len;
2846 return AVERROR_INVALIDDATA;
2849 q = data + data_len;
2854 if (*p == '\r' || *p == '\n') {
2863 if (p >= q || *p != '\n')
2864 return AVERROR_INVALIDDATA;
2870 if (*p == '\r' || *p == '\n') {
2871 settings_len = p - settings;
2879 if (p >= q || *p != '\n')
2880 return AVERROR_INVALIDDATA;
2885 while (text_len > 0) {
2886 const int len = text_len - 1;
2887 const uint8_t c = p[len];
2888 if (c != '\r' && c != '\n')
2894 return AVERROR_INVALIDDATA;
2896 pkt = av_mallocz(sizeof(*pkt));
2898 return AVERROR(ENOMEM);
2899 err = av_new_packet(pkt, text_len);
2902 return AVERROR(err);
2905 memcpy(pkt->data, text, text_len);
2908 buf = av_packet_new_side_data(pkt,
2909 AV_PKT_DATA_WEBVTT_IDENTIFIER,
2913 return AVERROR(ENOMEM);
2915 memcpy(buf, id, id_len);
2918 if (settings_len > 0) {
2919 buf = av_packet_new_side_data(pkt,
2920 AV_PKT_DATA_WEBVTT_SETTINGS,
2924 return AVERROR(ENOMEM);
2926 memcpy(buf, settings, settings_len);
2929 // Do we need this for subtitles?
2930 // pkt->flags = AV_PKT_FLAG_KEY;
2932 pkt->stream_index = st->index;
2933 pkt->pts = timecode;
2935 // Do we need this for subtitles?
2936 // pkt->dts = timecode;
2938 pkt->duration = duration;
2941 dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2942 matroska->prev_pkt = pkt;
2947 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2948 MatroskaTrack *track, AVStream *st,
2949 uint8_t *data, int pkt_size,
2950 uint64_t timecode, uint64_t lace_duration,
2951 int64_t pos, int is_keyframe,
2952 uint8_t *additional, uint64_t additional_id, int additional_size,
2953 int64_t discard_padding)
2955 MatroskaTrackEncoding *encodings = track->encodings.elem;
2956 uint8_t *pkt_data = data;
2957 int offset = 0, res;
2960 if (encodings && !encodings->type && encodings->scope & 1) {
2961 res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2966 if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
2968 res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2970 av_log(matroska->ctx, AV_LOG_ERROR,
2971 "Error parsing a wavpack block.\n");
2974 if (pkt_data != data)
2975 av_freep(&pkt_data);
2979 if (st->codecpar->codec_id == AV_CODEC_ID_PRORES &&
2980 AV_RB32(&data[4]) != MKBETAG('i', 'c', 'p', 'f'))
2983 pkt = av_mallocz(sizeof(AVPacket));
2985 if (pkt_data != data)
2986 av_freep(&pkt_data);
2987 return AVERROR(ENOMEM);
2989 /* XXX: prevent data copy... */
2990 if (av_new_packet(pkt, pkt_size + offset) < 0) {
2992 res = AVERROR(ENOMEM);
2996 if (st->codecpar->codec_id == AV_CODEC_ID_PRORES && offset == 8) {
2997 uint8_t *buf = pkt->data;
2998 bytestream_put_be32(&buf, pkt_size);
2999 bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
3002 memcpy(pkt->data + offset, pkt_data, pkt_size);
3004 if (pkt_data != data)
3005 av_freep(&pkt_data);
3007 pkt->flags = is_keyframe;
3008 pkt->stream_index = st->index;
3010 if (additional_size > 0) {
3011 uint8_t *side_data = av_packet_new_side_data(pkt,
3012 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
3013 additional_size + 8);
3015 av_packet_unref(pkt);
3017 return AVERROR(ENOMEM);
3019 AV_WB64(side_data, additional_id);
3020 memcpy(side_data + 8, additional, additional_size);
3023 if (discard_padding) {
3024 uint8_t *side_data = av_packet_new_side_data(pkt,
3025 AV_PKT_DATA_SKIP_SAMPLES,
3028 av_packet_unref(pkt);
3030 return AVERROR(ENOMEM);
3032 AV_WL32(side_data, 0);
3033 AV_WL32(side_data + 4, av_rescale_q(discard_padding,
3034 (AVRational){1, 1000000000},
3035 (AVRational){1, st->codecpar->sample_rate}));
3038 if (track->ms_compat)
3039 pkt->dts = timecode;
3041 pkt->pts = timecode;
3043 pkt->duration = lace_duration;
3045 #if FF_API_CONVERGENCE_DURATION
3046 FF_DISABLE_DEPRECATION_WARNINGS
3047 if (st->codecpar->codec_id == AV_CODEC_ID_SUBRIP) {
3048 pkt->convergence_duration = lace_duration;
3050 FF_ENABLE_DEPRECATION_WARNINGS
3053 dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
3054 matroska->prev_pkt = pkt;
3059 if (pkt_data != data)
3060 av_freep(&pkt_data);
3064 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
3065 int size, int64_t pos, uint64_t cluster_time,
3066 uint64_t block_duration, int is_keyframe,
3067 uint8_t *additional, uint64_t additional_id, int additional_size,
3068 int64_t cluster_pos, int64_t discard_padding)
3070 uint64_t timecode = AV_NOPTS_VALUE;
3071 MatroskaTrack *track;
3075 uint32_t *lace_size = NULL;
3076 int n, flags, laces = 0;
3078 int trust_default_duration = 1;
3080 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
3081 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
3087 track = matroska_find_track_by_num(matroska, num);
3088 if (!track || !track->stream) {
3089 av_log(matroska->ctx, AV_LOG_INFO,
3090 "Invalid stream %"PRIu64" or size %u\n", num, size);
3091 return AVERROR_INVALIDDATA;
3092 } else if (size <= 3)
3095 if (st->discard >= AVDISCARD_ALL)
3097 av_assert1(block_duration != AV_NOPTS_VALUE);
3099 block_time = sign_extend(AV_RB16(data), 16);
3103 if (is_keyframe == -1)
3104 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
3106 if (cluster_time != (uint64_t) -1 &&
3107 (block_time >= 0 || cluster_time >= -block_time)) {
3108 timecode = cluster_time + block_time - track->codec_delay;
3109 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
3110 timecode < track->end_timecode)
3111 is_keyframe = 0; /* overlapping subtitles are not key frame */
3113 av_add_index_entry(st, cluster_pos, timecode, 0, 0,
3117 if (matroska->skip_to_keyframe &&
3118 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
3119 if (timecode < matroska->skip_to_timecode)
3122 matroska->skip_to_keyframe = 0;
3123 else if (!st->skip_to_keyframe) {
3124 av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
3125 matroska->skip_to_keyframe = 0;
3129 res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
3130 &lace_size, &laces);
3135 if (track->audio.samplerate == 8000) {
3136 // If this is needed for more codecs, then add them here
3137 if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
3138 if (track->audio.samplerate != st->codecpar->sample_rate || !st->codecpar->frame_size)
3139 trust_default_duration = 0;
3143 if (!block_duration && trust_default_duration)
3144 block_duration = track->default_duration * laces / matroska->time_scale;
3146 if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
3147 track->end_timecode =
3148 FFMAX(track->end_timecode, timecode + block_duration);
3150 for (n = 0; n < laces; n++) {
3151 int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
3153 if (lace_size[n] > size) {
3154 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
3158 if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
3159 st->codecpar->codec_id == AV_CODEC_ID_COOK ||
3160 st->codecpar->codec_id == AV_CODEC_ID_SIPR ||
3161 st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) &&
3162 st->codecpar->block_align && track->audio.sub_packet_size) {
3163 res = matroska_parse_rm_audio(matroska, track, st, data,
3169 } else if (st->codecpar->codec_id == AV_CODEC_ID_WEBVTT) {
3170 res = matroska_parse_webvtt(matroska, track, st,
3172 timecode, lace_duration,
3177 res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
3178 timecode, lace_duration, pos,
3179 !n ? is_keyframe : 0,
3180 additional, additional_id, additional_size,
3186 if (timecode != AV_NOPTS_VALUE)
3187 timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
3188 data += lace_size[n];
3189 size -= lace_size[n];
3197 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
3199 EbmlList *blocks_list;
3200 MatroskaBlock *blocks;
3202 res = ebml_parse(matroska,
3203 matroska_cluster_incremental_parsing,
3204 &matroska->current_cluster);
3207 if (matroska->current_cluster_pos)
3208 ebml_level_end(matroska);
3209 ebml_free(matroska_cluster, &matroska->current_cluster);
3210 memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
3211 matroska->current_cluster_num_blocks = 0;
3212 matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
3213 matroska->prev_pkt = NULL;
3214 /* sizeof the ID which was already read */
3215 if (matroska->current_id)
3216 matroska->current_cluster_pos -= 4;
3217 res = ebml_parse(matroska,
3218 matroska_clusters_incremental,
3219 &matroska->current_cluster);
3220 /* Try parsing the block again. */
3222 res = ebml_parse(matroska,
3223 matroska_cluster_incremental_parsing,
3224 &matroska->current_cluster);
3228 matroska->current_cluster_num_blocks <
3229 matroska->current_cluster.blocks.nb_elem) {
3230 blocks_list = &matroska->current_cluster.blocks;
3231 blocks = blocks_list->elem;
3233 matroska->current_cluster_num_blocks = blocks_list->nb_elem;
3234 i = blocks_list->nb_elem - 1;
3235 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
3236 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
3237 uint8_t* additional = blocks[i].additional.size > 0 ?
3238 blocks[i].additional.data : NULL;
3239 if (!blocks[i].non_simple)
3240 blocks[i].duration = 0;
3241 res = matroska_parse_block(matroska, blocks[i].bin.data,
3242 blocks[i].bin.size, blocks[i].bin.pos,
3243 matroska->current_cluster.timecode,
3244 blocks[i].duration, is_keyframe,
3245 additional, blocks[i].additional_id,
3246 blocks[i].additional.size,
3247 matroska->current_cluster_pos,
3248 blocks[i].discard_padding);
3255 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
3257 MatroskaCluster cluster = { 0 };
3258 EbmlList *blocks_list;
3259 MatroskaBlock *blocks;
3263 if (!matroska->contains_ssa)
3264 return matroska_parse_cluster_incremental(matroska);
3265 pos = avio_tell(matroska->ctx->pb);
3266 matroska->prev_pkt = NULL;
3267 if (matroska->current_id)
3268 pos -= 4; /* sizeof the ID which was already read */
3269 res = ebml_parse(matroska, matroska_clusters, &cluster);
3270 blocks_list = &cluster.blocks;
3271 blocks = blocks_list->elem;
3272 for (i = 0; i < blocks_list->nb_elem; i++)
3273 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
3274 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
3275 res = matroska_parse_block(matroska, blocks[i].bin.data,
3276 blocks[i].bin.size, blocks[i].bin.pos,
3277 cluster.timecode, blocks[i].duration,
3278 is_keyframe, NULL, 0, 0, pos,
3279 blocks[i].discard_padding);
3281 ebml_free(matroska_cluster, &cluster);
3285 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
3287 MatroskaDemuxContext *matroska = s->priv_data;
3289 while (matroska_deliver_packet(matroska, pkt)) {
3290 int64_t pos = avio_tell(matroska->ctx->pb);
3293 if (matroska_parse_cluster(matroska) < 0)
3294 matroska_resync(matroska, pos);
3300 static int matroska_read_seek(AVFormatContext *s, int stream_index,
3301 int64_t timestamp, int flags)
3303 MatroskaDemuxContext *matroska = s->priv_data;
3304 MatroskaTrack *tracks = NULL;
3305 AVStream *st = s->streams[stream_index];
3306 int i, index, index_sub, index_min;
3308 /* Parse the CUES now since we need the index data to seek. */
3309 if (matroska->cues_parsing_deferred > 0) {
3310 matroska->cues_parsing_deferred = 0;
3311 matroska_parse_cues(matroska);
3314 if (!st->nb_index_entries)
3316 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
3318 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
3319 avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
3321 matroska->current_id = 0;
3322 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
3323 matroska_clear_queue(matroska);
3324 if (matroska_parse_cluster(matroska) < 0)
3329 matroska_clear_queue(matroska);
3330 if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
3334 tracks = matroska->tracks.elem;
3335 for (i = 0; i < matroska->tracks.nb_elem; i++) {
3336 tracks[i].audio.pkt_cnt = 0;
3337 tracks[i].audio.sub_packet_cnt = 0;
3338 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
3339 tracks[i].end_timecode = 0;
3340 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
3342 tracks[i].stream->discard != AVDISCARD_ALL) {
3343 index_sub = av_index_search_timestamp(
3344 tracks[i].stream, st->index_entries[index].timestamp,
3345 AVSEEK_FLAG_BACKWARD);
3346 while (index_sub >= 0 &&
3348 tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
3349 st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
3354 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
3355 matroska->current_id = 0;
3356 if (flags & AVSEEK_FLAG_ANY) {
3357 st->skip_to_keyframe = 0;
3358 matroska->skip_to_timecode = timestamp;
3360 st->skip_to_keyframe = 1;
3361 matroska->skip_to_timecode = st->index_entries[index].timestamp;
3363 matroska->skip_to_keyframe = 1;
3365 matroska->num_levels = 0;
3366 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
3369 // slightly hackish but allows proper fallback to
3370 // the generic seeking code.
3371 matroska_clear_queue(matroska);
3372 matroska->current_id = 0;
3373 st->skip_to_keyframe =
3374 matroska->skip_to_keyframe = 0;
3376 matroska->num_levels = 0;
3380 static int matroska_read_close(AVFormatContext *s)
3382 MatroskaDemuxContext *matroska = s->priv_data;
3383 MatroskaTrack *tracks = matroska->tracks.elem;
3386 matroska_clear_queue(matroska);
3388 for (n = 0; n < matroska->tracks.nb_elem; n++)
3389 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
3390 av_freep(&tracks[n].audio.buf);
3391 ebml_free(matroska_cluster, &matroska->current_cluster);
3392 ebml_free(matroska_segment, matroska);
3398 int64_t start_time_ns;
3399 int64_t end_time_ns;
3400 int64_t start_offset;
3404 /* This function searches all the Cues and returns the CueDesc corresponding the
3405 * the timestamp ts. Returned CueDesc will be such that start_time_ns <= ts <
3406 * end_time_ns. All 4 fields will be set to -1 if ts >= file's duration.
3408 static CueDesc get_cue_desc(AVFormatContext *s, int64_t ts, int64_t cues_start) {
3409 MatroskaDemuxContext *matroska = s->priv_data;
3412 int nb_index_entries = s->streams[0]->nb_index_entries;
3413 AVIndexEntry *index_entries = s->streams[0]->index_entries;
3414 if (ts >= matroska->duration * matroska->time_scale) return (CueDesc) {-1, -1, -1, -1};
3415 for (i = 1; i < nb_index_entries; i++) {
3416 if (index_entries[i - 1].timestamp * matroska->time_scale <= ts &&
3417 index_entries[i].timestamp * matroska->time_scale > ts) {
3422 cue_desc.start_time_ns = index_entries[i].timestamp * matroska->time_scale;
3423 cue_desc.start_offset = index_entries[i].pos - matroska->segment_start;
3424 if (i != nb_index_entries - 1) {
3425 cue_desc.end_time_ns = index_entries[i + 1].timestamp * matroska->time_scale;
3426 cue_desc.end_offset = index_entries[i + 1].pos - matroska->segment_start;
3428 cue_desc.end_time_ns = matroska->duration * matroska->time_scale;
3429 // FIXME: this needs special handling for files where Cues appear
3430 // before Clusters. the current logic assumes Cues appear after
3432 cue_desc.end_offset = cues_start - matroska->segment_start;
3437 static int webm_clusters_start_with_keyframe(AVFormatContext *s)
3439 MatroskaDemuxContext *matroska = s->priv_data;
3440 int64_t cluster_pos, before_pos;
3442 if (s->streams[0]->nb_index_entries <= 0) return 0;
3443 // seek to the first cluster using cues.
3444 index = av_index_search_timestamp(s->streams[0], 0, 0);
3445 if (index < 0) return 0;
3446 cluster_pos = s->streams[0]->index_entries[index].pos;
3447 before_pos = avio_tell(s->pb);
3449 int64_t cluster_id = 0, cluster_length = 0;
3451 avio_seek(s->pb, cluster_pos, SEEK_SET);
3452 // read cluster id and length
3453 ebml_read_num(matroska, matroska->ctx->pb, 4, &cluster_id);
3454 ebml_read_length(matroska, matroska->ctx->pb, &cluster_length);
3455 if (cluster_id != 0xF43B675) { // done with all clusters
3458 avio_seek(s->pb, cluster_pos, SEEK_SET);
3459 matroska->current_id = 0;
3460 matroska_clear_queue(matroska);
3461 if (matroska_parse_cluster(matroska) < 0 ||
3462 matroska->num_packets <= 0) {
3465 pkt = matroska->packets[0];
3466 cluster_pos += cluster_length + 12; // 12 is the offset of the cluster id and length.
3467 if (!(pkt->flags & AV_PKT_FLAG_KEY)) {
3472 avio_seek(s->pb, before_pos, SEEK_SET);
3476 static int buffer_size_after_time_downloaded(int64_t time_ns, double search_sec, int64_t bps,
3477 double min_buffer, double* buffer,
3478 double* sec_to_download, AVFormatContext *s,
3481 double nano_seconds_per_second = 1000000000.0;
3482 double time_sec = time_ns / nano_seconds_per_second;
3484 int64_t time_to_search_ns = (int64_t)(search_sec * nano_seconds_per_second);
3485 int64_t end_time_ns = time_ns + time_to_search_ns;
3486 double sec_downloaded = 0.0;
3487 CueDesc desc_curr = get_cue_desc(s, time_ns, cues_start);
3488 if (desc_curr.start_time_ns == -1)
3490 *sec_to_download = 0.0;
3492 // Check for non cue start time.
3493 if (time_ns > desc_curr.start_time_ns) {
3494 int64_t cue_nano = desc_curr.end_time_ns - time_ns;
3495 double percent = (double)(cue_nano) / (desc_curr.end_time_ns - desc_curr.start_time_ns);
3496 double cueBytes = (desc_curr.end_offset - desc_curr.start_offset) * percent;
3497 double timeToDownload = (cueBytes * 8.0) / bps;
3499 sec_downloaded += (cue_nano / nano_seconds_per_second) - timeToDownload;
3500 *sec_to_download += timeToDownload;
3502 // Check if the search ends within the first cue.
3503 if (desc_curr.end_time_ns >= end_time_ns) {
3504 double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
3505 double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
3506 sec_downloaded = percent_to_sub * sec_downloaded;
3507 *sec_to_download = percent_to_sub * *sec_to_download;
3510 if ((sec_downloaded + *buffer) <= min_buffer) {
3514 // Get the next Cue.
3515 desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
3518 while (desc_curr.start_time_ns != -1) {
3519 int64_t desc_bytes = desc_curr.end_offset - desc_curr.start_offset;
3520 int64_t desc_ns = desc_curr.end_time_ns - desc_curr.start_time_ns;
3521 double desc_sec = desc_ns / nano_seconds_per_second;
3522 double bits = (desc_bytes * 8.0);
3523 double time_to_download = bits / bps;
3525 sec_downloaded += desc_sec - time_to_download;
3526 *sec_to_download += time_to_download;
3528 if (desc_curr.end_time_ns >= end_time_ns) {
3529 double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
3530 double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
3531 sec_downloaded = percent_to_sub * sec_downloaded;
3532 *sec_to_download = percent_to_sub * *sec_to_download;
3534 if ((sec_downloaded + *buffer) <= min_buffer)
3539 if ((sec_downloaded + *buffer) <= min_buffer) {
3544 desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
3546 *buffer = *buffer + sec_downloaded;
3550 /* This function computes the bandwidth of the WebM file with the help of
3551 * buffer_size_after_time_downloaded() function. Both of these functions are
3552 * adapted from WebM Tools project and are adapted to work with FFmpeg's
3553 * Matroska parsing mechanism.
3555 * Returns the bandwidth of the file on success; -1 on error.
3557 static int64_t webm_dash_manifest_compute_bandwidth(AVFormatContext *s, int64_t cues_start)
3559 MatroskaDemuxContext *matroska = s->priv_data;
3560 AVStream *st = s->streams[0];
3561 double bandwidth = 0.0;
3564 for (i = 0; i < st->nb_index_entries; i++) {
3565 int64_t prebuffer_ns = 1000000000;
3566 int64_t time_ns = st->index_entries[i].timestamp * matroska->time_scale;
3567 double nano_seconds_per_second = 1000000000.0;
3568 int64_t prebuffered_ns = time_ns + prebuffer_ns;
3569 double prebuffer_bytes = 0.0;
3570 int64_t temp_prebuffer_ns = prebuffer_ns;
3571 int64_t pre_bytes, pre_ns;
3572 double pre_sec, prebuffer, bits_per_second;
3573 CueDesc desc_beg = get_cue_desc(s, time_ns, cues_start);
3575 // Start with the first Cue.
3576 CueDesc desc_end = desc_beg;
3578 // Figure out how much data we have downloaded for the prebuffer. This will
3579 // be used later to adjust the bits per sample to try.
3580 while (desc_end.start_time_ns != -1 && desc_end.end_time_ns < prebuffered_ns) {
3581 // Prebuffered the entire Cue.
3582 prebuffer_bytes += desc_end.end_offset - desc_end.start_offset;
3583 temp_prebuffer_ns -= desc_end.end_time_ns - desc_end.start_time_ns;
3584 desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
3586 if (desc_end.start_time_ns == -1) {
3587 // The prebuffer is larger than the duration.
3588 if (matroska->duration * matroska->time_scale >= prebuffered_ns)
3590 bits_per_second = 0.0;
3592 // The prebuffer ends in the last Cue. Estimate how much data was
3594 pre_bytes = desc_end.end_offset - desc_end.start_offset;
3595 pre_ns = desc_end.end_time_ns - desc_end.start_time_ns;
3596 pre_sec = pre_ns / nano_seconds_per_second;
3598 pre_bytes * ((temp_prebuffer_ns / nano_seconds_per_second) / pre_sec);
3600 prebuffer = prebuffer_ns / nano_seconds_per_second;
3602 // Set this to 0.0 in case our prebuffer buffers the entire video.
3603 bits_per_second = 0.0;
3605 int64_t desc_bytes = desc_end.end_offset - desc_beg.start_offset;
3606 int64_t desc_ns = desc_end.end_time_ns - desc_beg.start_time_ns;
3607 double desc_sec = desc_ns / nano_seconds_per_second;
3608 double calc_bits_per_second = (desc_bytes * 8) / desc_sec;
3610 // Drop the bps by the percentage of bytes buffered.
3611 double percent = (desc_bytes - prebuffer_bytes) / desc_bytes;
3612 double mod_bits_per_second = calc_bits_per_second * percent;
3614 if (prebuffer < desc_sec) {
3616 (double)(matroska->duration * matroska->time_scale) / nano_seconds_per_second;
3618 // Add 1 so the bits per second should be a little bit greater than file
3620 int64_t bps = (int64_t)(mod_bits_per_second) + 1;
3621 const double min_buffer = 0.0;
3622 double buffer = prebuffer;
3623 double sec_to_download = 0.0;
3625 int rv = buffer_size_after_time_downloaded(prebuffered_ns, search_sec, bps,
3626 min_buffer, &buffer, &sec_to_download,
3630 } else if (rv == 0) {
3631 bits_per_second = (double)(bps);
3636 desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
3637 } while (desc_end.start_time_ns != -1);
3639 if (bandwidth < bits_per_second) bandwidth = bits_per_second;
3641 return (int64_t)bandwidth;
3644 static int webm_dash_manifest_cues(AVFormatContext *s)
3646 MatroskaDemuxContext *matroska = s->priv_data;
3647 EbmlList *seekhead_list = &matroska->seekhead;
3648 MatroskaSeekhead *seekhead = seekhead_list->elem;
3650 int64_t cues_start = -1, cues_end = -1, before_pos, bandwidth;
3653 // determine cues start and end positions
3654 for (i = 0; i < seekhead_list->nb_elem; i++)
3655 if (seekhead[i].id == MATROSKA_ID_CUES)
3658 if (i >= seekhead_list->nb_elem) return -1;
3660 before_pos = avio_tell(matroska->ctx->pb);
3661 cues_start = seekhead[i].pos + matroska->segment_start;
3662 if (avio_seek(matroska->ctx->pb, cues_start, SEEK_SET) == cues_start) {
3663 // cues_end is computed as cues_start + cues_length + length of the
3664 // Cues element ID + EBML length of the Cues element. cues_end is
3665 // inclusive and the above sum is reduced by 1.
3666 uint64_t cues_length = 0, cues_id = 0, bytes_read = 0;
3667 bytes_read += ebml_read_num(matroska, matroska->ctx->pb, 4, &cues_id);
3668 bytes_read += ebml_read_length(matroska, matroska->ctx->pb, &cues_length);
3669 cues_end = cues_start + cues_length + bytes_read - 1;
3671 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
3672 if (cues_start == -1 || cues_end == -1) return -1;
3675 matroska_parse_cues(matroska);
3678 av_dict_set_int(&s->streams[0]->metadata, CUES_START, cues_start, 0);
3681 av_dict_set_int(&s->streams[0]->metadata, CUES_END, cues_end, 0);
3684 bandwidth = webm_dash_manifest_compute_bandwidth(s, cues_start);
3685 if (bandwidth < 0) return -1;
3686 av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH, bandwidth, 0);
3688 // check if all clusters start with key frames
3689 av_dict_set_int(&s->streams[0]->metadata, CLUSTER_KEYFRAME, webm_clusters_start_with_keyframe(s), 0);
3691 // store cue point timestamps as a comma separated list for checking subsegment alignment in
3692 // the muxer. assumes that each timestamp cannot be more than 20 characters long.
3693 buf = av_malloc_array(s->streams[0]->nb_index_entries, 20 * sizeof(char));
3694 if (!buf) return -1;
3696 for (i = 0; i < s->streams[0]->nb_index_entries; i++) {
3697 snprintf(buf, (i + 1) * 20 * sizeof(char),
3698 "%s%" PRId64, buf, s->streams[0]->index_entries[i].timestamp);
3699 if (i != s->streams[0]->nb_index_entries - 1)
3700 strncat(buf, ",", sizeof(char));
3702 av_dict_set(&s->streams[0]->metadata, CUE_TIMESTAMPS, buf, 0);
3708 static int webm_dash_manifest_read_header(AVFormatContext *s)
3711 int ret = matroska_read_header(s);
3712 MatroskaTrack *tracks;
3713 MatroskaDemuxContext *matroska = s->priv_data;
3715 av_log(s, AV_LOG_ERROR, "Failed to read file headers\n");
3719 if (!matroska->is_live) {
3720 buf = av_asprintf("%g", matroska->duration);
3721 if (!buf) return AVERROR(ENOMEM);
3722 av_dict_set(&s->streams[0]->metadata, DURATION, buf, 0);
3725 // initialization range
3726 // 5 is the offset of Cluster ID.
3727 av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, avio_tell(s->pb) - 5, 0);
3730 // basename of the file
3731 buf = strrchr(s->filename, '/');
3732 av_dict_set(&s->streams[0]->metadata, FILENAME, buf ? ++buf : s->filename, 0);
3735 tracks = matroska->tracks.elem;
3736 av_dict_set_int(&s->streams[0]->metadata, TRACK_NUMBER, tracks[0].num, 0);
3738 // parse the cues and populate Cue related fields
3739 return matroska->is_live ? 0 : webm_dash_manifest_cues(s);
3742 static int webm_dash_manifest_read_packet(AVFormatContext *s, AVPacket *pkt)
3747 #define OFFSET(x) offsetof(MatroskaDemuxContext, x)
3748 static const AVOption options[] = {
3749 { "live", "flag indicating that the input is a live file that only has the headers.", OFFSET(is_live), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
3753 static const AVClass webm_dash_class = {
3754 .class_name = "WebM DASH Manifest demuxer",
3755 .item_name = av_default_item_name,
3757 .version = LIBAVUTIL_VERSION_INT,
3760 AVInputFormat ff_matroska_demuxer = {
3761 .name = "matroska,webm",
3762 .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
3763 .extensions = "mkv,mk3d,mka,mks",
3764 .priv_data_size = sizeof(MatroskaDemuxContext),
3765 .read_probe = matroska_probe,
3766 .read_header = matroska_read_header,
3767 .read_packet = matroska_read_packet,
3768 .read_close = matroska_read_close,
3769 .read_seek = matroska_read_seek,
3770 .mime_type = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
3773 AVInputFormat ff_webm_dash_manifest_demuxer = {
3774 .name = "webm_dash_manifest",
3775 .long_name = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
3776 .priv_data_size = sizeof(MatroskaDemuxContext),
3777 .read_header = webm_dash_manifest_read_header,
3778 .read_packet = webm_dash_manifest_read_packet,
3779 .read_close = matroska_read_close,
3780 .priv_class = &webm_dash_class,