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"
46 #include "libavutil/spherical.h"
48 #include "libavcodec/bytestream.h"
49 #include "libavcodec/flac.h"
50 #include "libavcodec/mpeg4audio.h"
53 #include "avio_internal.h"
58 /* For ff_codec_get_id(). */
69 #include "qtpalette.h"
71 #define EBML_UNKNOWN_LENGTH UINT64_MAX /* EBML unknown length, in uint64_t */
88 typedef const struct EbmlSyntax {
98 const struct EbmlSyntax *n;
102 typedef struct EbmlList {
107 typedef struct EbmlBin {
114 typedef struct Ebml {
119 uint64_t doctype_version;
122 typedef struct MatroskaTrackCompression {
125 } MatroskaTrackCompression;
127 typedef struct MatroskaTrackEncryption {
130 } MatroskaTrackEncryption;
132 typedef struct MatroskaTrackEncoding {
135 MatroskaTrackCompression compression;
136 MatroskaTrackEncryption encryption;
137 } MatroskaTrackEncoding;
139 typedef struct MatroskaMasteringMeta {
148 double max_luminance;
149 double min_luminance;
150 } MatroskaMasteringMeta;
152 typedef struct MatroskaTrackVideoColor {
153 uint64_t matrix_coefficients;
154 uint64_t bits_per_channel;
155 uint64_t chroma_sub_horz;
156 uint64_t chroma_sub_vert;
157 uint64_t cb_sub_horz;
158 uint64_t cb_sub_vert;
159 uint64_t chroma_siting_horz;
160 uint64_t chroma_siting_vert;
162 uint64_t transfer_characteristics;
166 MatroskaMasteringMeta mastering_meta;
167 } MatroskaTrackVideoColor;
169 typedef struct MatroskaTrackVideoProjection {
175 } MatroskaTrackVideoProjection;
177 typedef struct MatroskaTrackVideo {
179 uint64_t display_width;
180 uint64_t display_height;
181 uint64_t pixel_width;
182 uint64_t pixel_height;
184 uint64_t display_unit;
186 uint64_t field_order;
187 uint64_t stereo_mode;
190 MatroskaTrackVideoProjection projection;
191 } MatroskaTrackVideo;
193 typedef struct MatroskaTrackAudio {
195 double out_samplerate;
199 /* real audio header (extracted from extradata) */
206 uint64_t buf_timecode;
208 } MatroskaTrackAudio;
210 typedef struct MatroskaTrackPlane {
213 } MatroskaTrackPlane;
215 typedef struct MatroskaTrackOperation {
216 EbmlList combine_planes;
217 } MatroskaTrackOperation;
219 typedef struct MatroskaTrack {
228 uint64_t default_duration;
229 uint64_t flag_default;
230 uint64_t flag_forced;
231 uint64_t seek_preroll;
232 MatroskaTrackVideo video;
233 MatroskaTrackAudio audio;
234 MatroskaTrackOperation operation;
236 uint64_t codec_delay;
237 uint64_t codec_delay_in_track_tb;
240 int64_t end_timecode;
242 uint64_t max_block_additional_id;
244 uint32_t palette[AVPALETTE_COUNT];
248 typedef struct MatroskaAttachment {
255 } MatroskaAttachment;
257 typedef struct MatroskaChapter {
266 typedef struct MatroskaIndexPos {
271 typedef struct MatroskaIndex {
276 typedef struct MatroskaTag {
284 typedef struct MatroskaTagTarget {
292 typedef struct MatroskaTags {
293 MatroskaTagTarget target;
297 typedef struct MatroskaSeekhead {
302 typedef struct MatroskaLevel {
307 typedef struct MatroskaCluster {
312 typedef struct MatroskaLevel1Element {
316 } MatroskaLevel1Element;
318 typedef struct MatroskaDemuxContext {
319 const AVClass *class;
320 AVFormatContext *ctx;
324 MatroskaLevel levels[EBML_MAX_DEPTH];
334 EbmlList attachments;
340 /* byte position of the segment inside the stream */
341 int64_t segment_start;
343 /* the packet queue */
345 AVPacketList *queue_end;
349 /* What to skip before effectively reading a packet. */
350 int skip_to_keyframe;
351 uint64_t skip_to_timecode;
353 /* File has a CUES element, but we defer parsing until it is needed. */
354 int cues_parsing_deferred;
356 /* Level1 elements and whether they were read yet */
357 MatroskaLevel1Element level1_elems[64];
358 int num_level1_elems;
360 int current_cluster_num_blocks;
361 int64_t current_cluster_pos;
362 MatroskaCluster current_cluster;
364 /* File has SSA subtitles which prevent incremental cluster parsing. */
367 /* WebM DASH Manifest live flag */
370 /* Bandwidth value for WebM DASH Manifest */
372 } MatroskaDemuxContext;
374 typedef struct MatroskaBlock {
379 uint64_t additional_id;
381 int64_t discard_padding;
384 static const EbmlSyntax ebml_header[] = {
385 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml, version), { .u = EBML_VERSION } },
386 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml, max_size), { .u = 8 } },
387 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml, id_length), { .u = 4 } },
388 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml, doctype), { .s = "(none)" } },
389 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
390 { EBML_ID_EBMLVERSION, EBML_NONE },
391 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
395 static const EbmlSyntax ebml_syntax[] = {
396 { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
400 static const EbmlSyntax matroska_info[] = {
401 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
402 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext, duration) },
403 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext, title) },
404 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
405 { MATROSKA_ID_MUXINGAPP, EBML_UTF8, 0, offsetof(MatroskaDemuxContext, muxingapp) },
406 { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext, date_utc) },
407 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
411 static const EbmlSyntax matroska_mastering_meta[] = {
412 { MATROSKA_ID_VIDEOCOLOR_RX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, r_x), { .f=-1 } },
413 { MATROSKA_ID_VIDEOCOLOR_RY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, r_y), { .f=-1 } },
414 { MATROSKA_ID_VIDEOCOLOR_GX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, g_x), { .f=-1 } },
415 { MATROSKA_ID_VIDEOCOLOR_GY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, g_y), { .f=-1 } },
416 { MATROSKA_ID_VIDEOCOLOR_BX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, b_x), { .f=-1 } },
417 { MATROSKA_ID_VIDEOCOLOR_BY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, b_y), { .f=-1 } },
418 { MATROSKA_ID_VIDEOCOLOR_WHITEX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, white_x), { .f=-1 } },
419 { MATROSKA_ID_VIDEOCOLOR_WHITEY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, white_y), { .f=-1 } },
420 { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, min_luminance), { .f=-1 } },
421 { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, max_luminance), { .f=-1 } },
425 static const EbmlSyntax matroska_track_video_color[] = {
426 { MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, matrix_coefficients), { .u = AVCOL_SPC_UNSPECIFIED } },
427 { MATROSKA_ID_VIDEOCOLORBITSPERCHANNEL, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, bits_per_channel), { .u=0 } },
428 { MATROSKA_ID_VIDEOCOLORCHROMASUBHORZ, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_horz), { .u=0 } },
429 { MATROSKA_ID_VIDEOCOLORCHROMASUBVERT, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_vert), { .u=0 } },
430 { MATROSKA_ID_VIDEOCOLORCBSUBHORZ, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, cb_sub_horz), { .u=0 } },
431 { MATROSKA_ID_VIDEOCOLORCBSUBVERT, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, cb_sub_vert), { .u=0 } },
432 { MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_siting_horz), { .u = MATROSKA_COLOUR_CHROMASITINGHORZ_UNDETERMINED } },
433 { MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_siting_vert), { .u = MATROSKA_COLOUR_CHROMASITINGVERT_UNDETERMINED } },
434 { MATROSKA_ID_VIDEOCOLORRANGE, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, range), { .u = AVCOL_RANGE_UNSPECIFIED } },
435 { MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, transfer_characteristics), { .u = AVCOL_TRC_UNSPECIFIED } },
436 { MATROSKA_ID_VIDEOCOLORPRIMARIES, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, primaries), { .u = AVCOL_PRI_UNSPECIFIED } },
437 { MATROSKA_ID_VIDEOCOLORMAXCLL, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, max_cll), { .u=0 } },
438 { MATROSKA_ID_VIDEOCOLORMAXFALL, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, max_fall), { .u=0 } },
439 { MATROSKA_ID_VIDEOCOLORMASTERINGMETA, EBML_NEST, 0, offsetof(MatroskaTrackVideoColor, mastering_meta), { .n = matroska_mastering_meta } },
443 static const EbmlSyntax matroska_track_video_projection[] = {
444 { MATROSKA_ID_VIDEOPROJECTIONTYPE, EBML_UINT, 0, offsetof(MatroskaTrackVideoProjection, type), { .u = MATROSKA_VIDEO_PROJECTION_TYPE_RECTANGULAR } },
445 { MATROSKA_ID_VIDEOPROJECTIONPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrackVideoProjection, private) },
446 { MATROSKA_ID_VIDEOPROJECTIONPOSEYAW, EBML_FLOAT, 0, offsetof(MatroskaTrackVideoProjection, yaw), { .f=0.0 } },
447 { MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH, EBML_FLOAT, 0, offsetof(MatroskaTrackVideoProjection, pitch), { .f=0.0 } },
448 { MATROSKA_ID_VIDEOPROJECTIONPOSEROLL, EBML_FLOAT, 0, offsetof(MatroskaTrackVideoProjection, roll), { .f=0.0 } },
452 static const EbmlSyntax matroska_track_video[] = {
453 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT, 0, offsetof(MatroskaTrackVideo, frame_rate) },
454 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_width), { .u=-1 } },
455 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_height), { .u=-1 } },
456 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_width) },
457 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, pixel_height) },
458 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo, color_space) },
459 { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, alpha_mode) },
460 { MATROSKA_ID_VIDEOCOLOR, EBML_NEST, sizeof(MatroskaTrackVideoColor), offsetof(MatroskaTrackVideo, color), { .n = matroska_track_video_color } },
461 { MATROSKA_ID_VIDEOPROJECTION, EBML_NEST, 0, offsetof(MatroskaTrackVideo, projection), { .n = matroska_track_video_projection } },
462 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
463 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
464 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
465 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
466 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_UINT, 0, offsetof(MatroskaTrackVideo, display_unit), { .u= MATROSKA_VIDEO_DISPLAYUNIT_PIXELS } },
467 { MATROSKA_ID_VIDEOFLAGINTERLACED, EBML_UINT, 0, offsetof(MatroskaTrackVideo, interlaced), { .u = MATROSKA_VIDEO_INTERLACE_FLAG_UNDETERMINED } },
468 { MATROSKA_ID_VIDEOFIELDORDER, EBML_UINT, 0, offsetof(MatroskaTrackVideo, field_order), { .u = MATROSKA_VIDEO_FIELDORDER_UNDETERMINED } },
469 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, stereo_mode), { .u = MATROSKA_VIDEO_STEREOMODE_TYPE_NB } },
470 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
474 static const EbmlSyntax matroska_track_audio[] = {
475 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
476 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
477 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio, bitdepth) },
478 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio, channels), { .u = 1 } },
482 static const EbmlSyntax matroska_track_encoding_compression[] = {
483 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
484 { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN, 0, offsetof(MatroskaTrackCompression, settings) },
488 static const EbmlSyntax matroska_track_encoding_encryption[] = {
489 { MATROSKA_ID_ENCODINGENCALGO, EBML_UINT, 0, offsetof(MatroskaTrackEncryption,algo), {.u = 0} },
490 { MATROSKA_ID_ENCODINGENCKEYID, EBML_BIN, 0, offsetof(MatroskaTrackEncryption,key_id) },
491 { MATROSKA_ID_ENCODINGENCAESSETTINGS, EBML_NONE },
492 { MATROSKA_ID_ENCODINGSIGALGO, EBML_NONE },
493 { MATROSKA_ID_ENCODINGSIGHASHALGO, EBML_NONE },
494 { MATROSKA_ID_ENCODINGSIGKEYID, EBML_NONE },
495 { MATROSKA_ID_ENCODINGSIGNATURE, EBML_NONE },
498 static const EbmlSyntax matroska_track_encoding[] = {
499 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, scope), { .u = 1 } },
500 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding, type), { .u = 0 } },
501 { MATROSKA_ID_ENCODINGCOMPRESSION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, compression), { .n = matroska_track_encoding_compression } },
502 { MATROSKA_ID_ENCODINGENCRYPTION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, encryption), { .n = matroska_track_encoding_encryption } },
503 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
507 static const EbmlSyntax matroska_track_encodings[] = {
508 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
512 static const EbmlSyntax matroska_track_plane[] = {
513 { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
514 { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
518 static const EbmlSyntax matroska_track_combine_planes[] = {
519 { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n = matroska_track_plane} },
523 static const EbmlSyntax matroska_track_operation[] = {
524 { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n = matroska_track_combine_planes} },
528 static const EbmlSyntax matroska_track[] = {
529 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack, num) },
530 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack, name) },
531 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack, uid) },
532 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack, type) },
533 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack, codec_id) },
534 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack, codec_priv) },
535 { MATROSKA_ID_CODECDELAY, EBML_UINT, 0, offsetof(MatroskaTrack, codec_delay) },
536 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack, language), { .s = "eng" } },
537 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack, default_duration) },
538 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT, 0, offsetof(MatroskaTrack, time_scale), { .f = 1.0 } },
539 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack, flag_default), { .u = 1 } },
540 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack, flag_forced), { .u = 0 } },
541 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack, video), { .n = matroska_track_video } },
542 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack, audio), { .n = matroska_track_audio } },
543 { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack, operation), { .n = matroska_track_operation } },
544 { MATROSKA_ID_TRACKCONTENTENCODINGS, EBML_NEST, 0, 0, { .n = matroska_track_encodings } },
545 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, offsetof(MatroskaTrack, max_block_additional_id) },
546 { MATROSKA_ID_SEEKPREROLL, EBML_UINT, 0, offsetof(MatroskaTrack, seek_preroll) },
547 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
548 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
549 { MATROSKA_ID_CODECNAME, EBML_NONE },
550 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
551 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
552 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
553 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
554 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
558 static const EbmlSyntax matroska_tracks[] = {
559 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
563 static const EbmlSyntax matroska_attachment[] = {
564 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachment, uid) },
565 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachment, filename) },
566 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachment, mime) },
567 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachment, bin) },
568 { MATROSKA_ID_FILEDESC, EBML_NONE },
572 static const EbmlSyntax matroska_attachments[] = {
573 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
577 static const EbmlSyntax matroska_chapter_display[] = {
578 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
579 { MATROSKA_ID_CHAPLANG, EBML_NONE },
580 { MATROSKA_ID_CHAPCOUNTRY, EBML_NONE },
584 static const EbmlSyntax matroska_chapter_entry[] = {
585 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
586 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter, end), { .u = AV_NOPTS_VALUE } },
587 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter, uid) },
588 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, { .n = matroska_chapter_display } },
589 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
590 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
591 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
592 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
596 static const EbmlSyntax matroska_chapter[] = {
597 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
598 { MATROSKA_ID_EDITIONUID, EBML_NONE },
599 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
600 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
601 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
605 static const EbmlSyntax matroska_chapters[] = {
606 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
610 static const EbmlSyntax matroska_index_pos[] = {
611 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
612 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
613 { MATROSKA_ID_CUERELATIVEPOSITION,EBML_NONE },
614 { MATROSKA_ID_CUEDURATION, EBML_NONE },
615 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
619 static const EbmlSyntax matroska_index_entry[] = {
620 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex, time) },
621 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex, pos), { .n = matroska_index_pos } },
625 static const EbmlSyntax matroska_index[] = {
626 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
630 static const EbmlSyntax matroska_simpletag[] = {
631 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag, name) },
632 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag, string) },
633 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag, lang), { .s = "und" } },
634 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag, def) },
635 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag, def) },
636 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag, sub), { .n = matroska_simpletag } },
640 static const EbmlSyntax matroska_tagtargets[] = {
641 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget, type) },
642 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
643 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, trackuid) },
644 { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, chapteruid) },
645 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, attachuid) },
649 static const EbmlSyntax matroska_tag[] = {
650 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags, tag), { .n = matroska_simpletag } },
651 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
655 static const EbmlSyntax matroska_tags[] = {
656 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
660 static const EbmlSyntax matroska_seekhead_entry[] = {
661 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
662 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
666 static const EbmlSyntax matroska_seekhead[] = {
667 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
671 static const EbmlSyntax matroska_segment[] = {
672 { MATROSKA_ID_INFO, EBML_LEVEL1, 0, 0, { .n = matroska_info } },
673 { MATROSKA_ID_TRACKS, EBML_LEVEL1, 0, 0, { .n = matroska_tracks } },
674 { MATROSKA_ID_ATTACHMENTS, EBML_LEVEL1, 0, 0, { .n = matroska_attachments } },
675 { MATROSKA_ID_CHAPTERS, EBML_LEVEL1, 0, 0, { .n = matroska_chapters } },
676 { MATROSKA_ID_CUES, EBML_LEVEL1, 0, 0, { .n = matroska_index } },
677 { MATROSKA_ID_TAGS, EBML_LEVEL1, 0, 0, { .n = matroska_tags } },
678 { MATROSKA_ID_SEEKHEAD, EBML_LEVEL1, 0, 0, { .n = matroska_seekhead } },
679 { MATROSKA_ID_CLUSTER, EBML_STOP },
683 static const EbmlSyntax matroska_segments[] = {
684 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
688 static const EbmlSyntax matroska_blockmore[] = {
689 { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
690 { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) },
694 static const EbmlSyntax matroska_blockadditions[] = {
695 { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n = matroska_blockmore} },
699 static const EbmlSyntax matroska_blockgroup[] = {
700 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
701 { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, { .n = matroska_blockadditions} },
702 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) },
703 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock, duration) },
704 { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, offsetof(MatroskaBlock, discard_padding) },
705 { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock, reference), { .i = INT64_MIN } },
706 { MATROSKA_ID_CODECSTATE, EBML_NONE },
707 { 1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
711 static const EbmlSyntax matroska_cluster[] = {
712 { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
713 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
714 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
715 { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
716 { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
720 static const EbmlSyntax matroska_clusters[] = {
721 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster } },
722 { MATROSKA_ID_INFO, EBML_NONE },
723 { MATROSKA_ID_CUES, EBML_NONE },
724 { MATROSKA_ID_TAGS, EBML_NONE },
725 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
729 static const EbmlSyntax matroska_cluster_incremental_parsing[] = {
730 { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
731 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
732 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
733 { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
734 { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
735 { MATROSKA_ID_INFO, EBML_NONE },
736 { MATROSKA_ID_CUES, EBML_NONE },
737 { MATROSKA_ID_TAGS, EBML_NONE },
738 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
739 { MATROSKA_ID_CLUSTER, EBML_STOP },
743 static const EbmlSyntax matroska_cluster_incremental[] = {
744 { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
745 { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
746 { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
747 { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
748 { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
752 static const EbmlSyntax matroska_clusters_incremental[] = {
753 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, { .n = matroska_cluster_incremental } },
754 { MATROSKA_ID_INFO, EBML_NONE },
755 { MATROSKA_ID_CUES, EBML_NONE },
756 { MATROSKA_ID_TAGS, EBML_NONE },
757 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
761 static const char *const matroska_doctypes[] = { "matroska", "webm" };
763 static int matroska_read_close(AVFormatContext *s);
765 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
767 AVIOContext *pb = matroska->ctx->pb;
770 matroska->current_id = 0;
771 matroska->num_levels = 0;
773 /* seek to next position to resync from */
774 if ((ret = avio_seek(pb, last_pos + 1, SEEK_SET)) < 0) {
781 // try to find a toplevel element
782 while (!avio_feof(pb)) {
783 if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
784 id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
785 id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
786 id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
787 matroska->current_id = id;
790 id = (id << 8) | avio_r8(pb);
798 * Return: Whether we reached the end of a level in the hierarchy or not.
800 static int ebml_level_end(MatroskaDemuxContext *matroska)
802 AVIOContext *pb = matroska->ctx->pb;
803 int64_t pos = avio_tell(pb);
805 if (matroska->num_levels > 0) {
806 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
807 if (pos - level->start >= level->length || matroska->current_id) {
808 matroska->num_levels--;
812 return (matroska->is_live && matroska->ctx->pb->eof_reached) ? 1 : 0;
816 * Read: an "EBML number", which is defined as a variable-length
817 * array of bytes. The first byte indicates the length by giving a
818 * number of 0-bits followed by a one. The position of the first
819 * "one" bit inside the first byte indicates the length of this
821 * Returns: number of bytes read, < 0 on error
823 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
824 int max_size, uint64_t *number)
829 /* The first byte tells us the length in bytes - avio_r8() can normally
830 * return 0, but since that's not a valid first ebmlID byte, we can
831 * use it safely here to catch EOS. */
832 if (!(total = avio_r8(pb))) {
833 /* we might encounter EOS here */
834 if (!avio_feof(pb)) {
835 int64_t pos = avio_tell(pb);
836 av_log(matroska->ctx, AV_LOG_ERROR,
837 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
839 return pb->error ? pb->error : AVERROR(EIO);
844 /* get the length of the EBML number */
845 read = 8 - ff_log2_tab[total];
846 if (read > max_size) {
847 int64_t pos = avio_tell(pb) - 1;
848 av_log(matroska->ctx, AV_LOG_ERROR,
849 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
850 (uint8_t) total, pos, pos);
851 return AVERROR_INVALIDDATA;
854 /* read out length */
855 total ^= 1 << ff_log2_tab[total];
857 total = (total << 8) | avio_r8(pb);
865 * Read a EBML length value.
866 * This needs special handling for the "unknown length" case which has multiple
869 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
872 int res = ebml_read_num(matroska, pb, 8, number);
873 if (res > 0 && *number + 1 == 1ULL << (7 * res))
874 *number = EBML_UNKNOWN_LENGTH;
879 * Read the next element as an unsigned int.
880 * 0 is success, < 0 is failure.
882 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
887 return AVERROR_INVALIDDATA;
889 /* big-endian ordering; build up number */
892 *num = (*num << 8) | avio_r8(pb);
898 * Read the next element as a signed int.
899 * 0 is success, < 0 is failure.
901 static int ebml_read_sint(AVIOContext *pb, int size, int64_t *num)
906 return AVERROR_INVALIDDATA;
911 *num = sign_extend(avio_r8(pb), 8);
913 /* big-endian ordering; build up number */
915 *num = ((uint64_t)*num << 8) | avio_r8(pb);
922 * Read the next element as a float.
923 * 0 is success, < 0 is failure.
925 static int ebml_read_float(AVIOContext *pb, int size, double *num)
930 *num = av_int2float(avio_rb32(pb));
932 *num = av_int2double(avio_rb64(pb));
934 return AVERROR_INVALIDDATA;
940 * Read the next element as an ASCII string.
941 * 0 is success, < 0 is failure.
943 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
947 /* EBML strings are usually not 0-terminated, so we allocate one
948 * byte more, read the string and NULL-terminate it ourselves. */
949 if (!(res = av_malloc(size + 1)))
950 return AVERROR(ENOMEM);
951 if (avio_read(pb, (uint8_t *) res, size) != size) {
963 * Read the next element as binary data.
964 * 0 is success, < 0 is failure.
966 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
970 ret = av_buffer_realloc(&bin->buf, length + AV_INPUT_BUFFER_PADDING_SIZE);
973 memset(bin->buf->data + length, 0, AV_INPUT_BUFFER_PADDING_SIZE);
975 bin->data = bin->buf->data;
977 bin->pos = avio_tell(pb);
978 if (avio_read(pb, bin->data, length) != length) {
979 av_buffer_unref(&bin->buf);
989 * Read the next element, but only the header. The contents
990 * are supposed to be sub-elements which can be read separately.
991 * 0 is success, < 0 is failure.
993 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
995 AVIOContext *pb = matroska->ctx->pb;
996 MatroskaLevel *level;
998 if (matroska->num_levels >= EBML_MAX_DEPTH) {
999 av_log(matroska->ctx, AV_LOG_ERROR,
1000 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
1001 return AVERROR(ENOSYS);
1004 level = &matroska->levels[matroska->num_levels++];
1005 level->start = avio_tell(pb);
1006 level->length = length;
1012 * Read signed/unsigned "EBML" numbers.
1013 * Return: number of bytes processed, < 0 on error
1015 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
1016 uint8_t *data, uint32_t size, uint64_t *num)
1019 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
1020 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
1024 * Same as above, but signed.
1026 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
1027 uint8_t *data, uint32_t size, int64_t *num)
1032 /* read as unsigned number first */
1033 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
1036 /* make signed (weird way) */
1037 *num = unum - ((1LL << (7 * res - 1)) - 1);
1042 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1043 EbmlSyntax *syntax, void *data);
1045 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1046 uint32_t id, void *data)
1049 for (i = 0; syntax[i].id; i++)
1050 if (id == syntax[i].id)
1052 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
1053 matroska->num_levels > 0 &&
1054 matroska->levels[matroska->num_levels - 1].length == EBML_UNKNOWN_LENGTH)
1055 return 0; // we reached the end of an unknown size cluster
1056 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
1057 av_log(matroska->ctx, AV_LOG_DEBUG, "Unknown entry 0x%"PRIX32"\n", id);
1059 return ebml_parse_elem(matroska, &syntax[i], data);
1062 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1065 if (!matroska->current_id) {
1067 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
1069 // in live mode, finish parsing if EOF is reached.
1070 return (matroska->is_live && matroska->ctx->pb->eof_reached &&
1071 res == AVERROR_EOF) ? 1 : res;
1073 matroska->current_id = id | 1 << 7 * res;
1075 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
1078 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1083 for (i = 0; syntax[i].id; i++)
1084 switch (syntax[i].type) {
1086 *(int64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.i;
1089 *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
1092 *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
1096 // the default may be NULL
1097 if (syntax[i].def.s) {
1098 uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
1099 *dst = av_strdup(syntax[i].def.s);
1101 return AVERROR(ENOMEM);
1106 while (!res && !ebml_level_end(matroska))
1107 res = ebml_parse(matroska, syntax, data);
1112 static int is_ebml_id_valid(uint32_t id)
1114 // Due to endian nonsense in Matroska, the highest byte with any bits set
1115 // will contain the leading length bit. This bit in turn identifies the
1116 // total byte length of the element by its position within the byte.
1117 unsigned int bits = av_log2(id);
1118 return id && (bits + 7) / 8 == (8 - bits % 8);
1122 * Allocate and return the entry for the level1 element with the given ID. If
1123 * an entry already exists, return the existing entry.
1125 static MatroskaLevel1Element *matroska_find_level1_elem(MatroskaDemuxContext *matroska,
1129 MatroskaLevel1Element *elem;
1131 if (!is_ebml_id_valid(id))
1134 // Some files link to all clusters; useless.
1135 if (id == MATROSKA_ID_CLUSTER)
1138 // There can be multiple seekheads.
1139 if (id != MATROSKA_ID_SEEKHEAD) {
1140 for (i = 0; i < matroska->num_level1_elems; i++) {
1141 if (matroska->level1_elems[i].id == id)
1142 return &matroska->level1_elems[i];
1146 // Only a completely broken file would have more elements.
1147 // It also provides a low-effort way to escape from circular seekheads
1148 // (every iteration will add a level1 entry).
1149 if (matroska->num_level1_elems >= FF_ARRAY_ELEMS(matroska->level1_elems)) {
1150 av_log(matroska->ctx, AV_LOG_ERROR, "Too many level1 elements or circular seekheads.\n");
1154 elem = &matroska->level1_elems[matroska->num_level1_elems++];
1155 *elem = (MatroskaLevel1Element){.id = id};
1160 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1161 EbmlSyntax *syntax, void *data)
1163 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
1166 // max. 16 MB for strings
1167 [EBML_STR] = 0x1000000,
1168 [EBML_UTF8] = 0x1000000,
1169 // max. 256 MB for binary data
1170 [EBML_BIN] = 0x10000000,
1171 // no limits for anything else
1173 AVIOContext *pb = matroska->ctx->pb;
1174 uint32_t id = syntax->id;
1178 MatroskaLevel1Element *level1_elem;
1180 data = (char *) data + syntax->data_offset;
1181 if (syntax->list_elem_size) {
1182 EbmlList *list = data;
1183 newelem = av_realloc_array(list->elem, list->nb_elem + 1, syntax->list_elem_size);
1185 return AVERROR(ENOMEM);
1186 list->elem = newelem;
1187 data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
1188 memset(data, 0, syntax->list_elem_size);
1192 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
1193 matroska->current_id = 0;
1194 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
1196 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
1197 av_log(matroska->ctx, AV_LOG_ERROR,
1198 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
1199 length, max_lengths[syntax->type], syntax->type);
1200 return AVERROR_INVALIDDATA;
1202 if (matroska->num_levels > 0) {
1203 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
1204 AVIOContext *pb = matroska->ctx->pb;
1205 int64_t pos = avio_tell(pb);
1206 if (level->length != EBML_UNKNOWN_LENGTH &&
1207 (pos + length) > (level->start + level->length)) {
1208 av_log(matroska->ctx, AV_LOG_ERROR,
1209 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" in parent\n",
1210 length, level->start + level->length);
1211 return AVERROR_INVALIDDATA;
1216 switch (syntax->type) {
1218 res = ebml_read_uint(pb, length, data);
1221 res = ebml_read_sint(pb, length, data);
1224 res = ebml_read_float(pb, length, data);
1228 res = ebml_read_ascii(pb, length, data);
1231 res = ebml_read_binary(pb, length, data);
1235 if ((res = ebml_read_master(matroska, length)) < 0)
1237 if (id == MATROSKA_ID_SEGMENT)
1238 matroska->segment_start = avio_tell(matroska->ctx->pb);
1239 if (id == MATROSKA_ID_CUES)
1240 matroska->cues_parsing_deferred = 0;
1241 if (syntax->type == EBML_LEVEL1 &&
1242 (level1_elem = matroska_find_level1_elem(matroska, syntax->id))) {
1243 if (level1_elem->parsed)
1244 av_log(matroska->ctx, AV_LOG_ERROR, "Duplicate element\n");
1245 level1_elem->parsed = 1;
1247 return ebml_parse_nest(matroska, syntax->def.n, data);
1249 return ebml_parse_id(matroska, syntax->def.n, id, data);
1253 if (ffio_limit(pb, length) != length)
1254 return AVERROR(EIO);
1255 return avio_skip(pb, length) < 0 ? AVERROR(EIO) : 0;
1257 if (res == AVERROR_INVALIDDATA)
1258 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
1259 else if (res == AVERROR(EIO))
1260 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
1264 static void ebml_free(EbmlSyntax *syntax, void *data)
1267 for (i = 0; syntax[i].id; i++) {
1268 void *data_off = (char *) data + syntax[i].data_offset;
1269 switch (syntax[i].type) {
1275 av_buffer_unref(&((EbmlBin *) data_off)->buf);
1279 if (syntax[i].list_elem_size) {
1280 EbmlList *list = data_off;
1281 char *ptr = list->elem;
1282 for (j = 0; j < list->nb_elem;
1283 j++, ptr += syntax[i].list_elem_size)
1284 ebml_free(syntax[i].def.n, ptr);
1285 av_freep(&list->elem);
1288 ebml_free(syntax[i].def.n, data_off);
1298 static int matroska_probe(AVProbeData *p)
1301 int len_mask = 0x80, size = 1, n = 1, i;
1304 if (AV_RB32(p->buf) != EBML_ID_HEADER)
1307 /* length of header */
1309 while (size <= 8 && !(total & len_mask)) {
1315 total &= (len_mask - 1);
1317 total = (total << 8) | p->buf[4 + n++];
1319 /* Does the probe data contain the whole header? */
1320 if (p->buf_size < 4 + size + total)
1323 /* The header should contain a known document type. For now,
1324 * we don't parse the whole header but simply check for the
1325 * availability of that array of characters inside the header.
1326 * Not fully fool-proof, but good enough. */
1327 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1328 size_t probelen = strlen(matroska_doctypes[i]);
1329 if (total < probelen)
1331 for (n = 4 + size; n <= 4 + size + total - probelen; n++)
1332 if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
1333 return AVPROBE_SCORE_MAX;
1336 // probably valid EBML header but no recognized doctype
1337 return AVPROBE_SCORE_EXTENSION;
1340 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1343 MatroskaTrack *tracks = matroska->tracks.elem;
1346 for (i = 0; i < matroska->tracks.nb_elem; i++)
1347 if (tracks[i].num == num)
1350 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1354 static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
1355 MatroskaTrack *track)
1357 MatroskaTrackEncoding *encodings = track->encodings.elem;
1358 uint8_t *data = *buf;
1359 int isize = *buf_size;
1360 uint8_t *pkt_data = NULL;
1361 uint8_t av_unused *newpktdata;
1362 int pkt_size = isize;
1366 if (pkt_size >= 10000000U)
1367 return AVERROR_INVALIDDATA;
1369 switch (encodings[0].compression.algo) {
1370 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1372 int header_size = encodings[0].compression.settings.size;
1373 uint8_t *header = encodings[0].compression.settings.data;
1375 if (header_size && !header) {
1376 av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1383 pkt_size = isize + header_size;
1384 pkt_data = av_malloc(pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
1386 return AVERROR(ENOMEM);
1388 memcpy(pkt_data, header, header_size);
1389 memcpy(pkt_data + header_size, data, isize);
1393 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1395 olen = pkt_size *= 3;
1396 newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING
1397 + AV_INPUT_BUFFER_PADDING_SIZE);
1399 result = AVERROR(ENOMEM);
1402 pkt_data = newpktdata;
1403 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1404 } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
1406 result = AVERROR_INVALIDDATA;
1413 case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
1415 z_stream zstream = { 0 };
1416 if (inflateInit(&zstream) != Z_OK)
1418 zstream.next_in = data;
1419 zstream.avail_in = isize;
1422 newpktdata = av_realloc(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
1424 inflateEnd(&zstream);
1425 result = AVERROR(ENOMEM);
1428 pkt_data = newpktdata;
1429 zstream.avail_out = pkt_size - zstream.total_out;
1430 zstream.next_out = pkt_data + zstream.total_out;
1431 result = inflate(&zstream, Z_NO_FLUSH);
1432 } while (result == Z_OK && pkt_size < 10000000);
1433 pkt_size = zstream.total_out;
1434 inflateEnd(&zstream);
1435 if (result != Z_STREAM_END) {
1436 if (result == Z_MEM_ERROR)
1437 result = AVERROR(ENOMEM);
1439 result = AVERROR_INVALIDDATA;
1446 case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
1448 bz_stream bzstream = { 0 };
1449 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1451 bzstream.next_in = data;
1452 bzstream.avail_in = isize;
1455 newpktdata = av_realloc(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
1457 BZ2_bzDecompressEnd(&bzstream);
1458 result = AVERROR(ENOMEM);
1461 pkt_data = newpktdata;
1462 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1463 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1464 result = BZ2_bzDecompress(&bzstream);
1465 } while (result == BZ_OK && pkt_size < 10000000);
1466 pkt_size = bzstream.total_out_lo32;
1467 BZ2_bzDecompressEnd(&bzstream);
1468 if (result != BZ_STREAM_END) {
1469 if (result == BZ_MEM_ERROR)
1470 result = AVERROR(ENOMEM);
1472 result = AVERROR_INVALIDDATA;
1479 return AVERROR_INVALIDDATA;
1482 memset(pkt_data + pkt_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1485 *buf_size = pkt_size;
1493 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1494 AVDictionary **metadata, char *prefix)
1496 MatroskaTag *tags = list->elem;
1500 for (i = 0; i < list->nb_elem; i++) {
1501 const char *lang = tags[i].lang &&
1502 strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1504 if (!tags[i].name) {
1505 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1509 snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1511 av_strlcpy(key, tags[i].name, sizeof(key));
1512 if (tags[i].def || !lang) {
1513 av_dict_set(metadata, key, tags[i].string, 0);
1514 if (tags[i].sub.nb_elem)
1515 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1518 av_strlcat(key, "-", sizeof(key));
1519 av_strlcat(key, lang, sizeof(key));
1520 av_dict_set(metadata, key, tags[i].string, 0);
1521 if (tags[i].sub.nb_elem)
1522 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1525 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1528 static void matroska_convert_tags(AVFormatContext *s)
1530 MatroskaDemuxContext *matroska = s->priv_data;
1531 MatroskaTags *tags = matroska->tags.elem;
1534 for (i = 0; i < matroska->tags.nb_elem; i++) {
1535 if (tags[i].target.attachuid) {
1536 MatroskaAttachment *attachment = matroska->attachments.elem;
1538 for (j = 0; j < matroska->attachments.nb_elem; j++) {
1539 if (attachment[j].uid == tags[i].target.attachuid &&
1540 attachment[j].stream) {
1541 matroska_convert_tag(s, &tags[i].tag,
1542 &attachment[j].stream->metadata, NULL);
1547 av_log(NULL, AV_LOG_WARNING,
1548 "The tags at index %d refer to a "
1549 "non-existent attachment %"PRId64".\n",
1550 i, tags[i].target.attachuid);
1552 } else if (tags[i].target.chapteruid) {
1553 MatroskaChapter *chapter = matroska->chapters.elem;
1555 for (j = 0; j < matroska->chapters.nb_elem; j++) {
1556 if (chapter[j].uid == tags[i].target.chapteruid &&
1557 chapter[j].chapter) {
1558 matroska_convert_tag(s, &tags[i].tag,
1559 &chapter[j].chapter->metadata, NULL);
1564 av_log(NULL, AV_LOG_WARNING,
1565 "The tags at index %d refer to a non-existent chapter "
1567 i, tags[i].target.chapteruid);
1569 } else if (tags[i].target.trackuid) {
1570 MatroskaTrack *track = matroska->tracks.elem;
1572 for (j = 0; j < matroska->tracks.nb_elem; j++) {
1573 if (track[j].uid == tags[i].target.trackuid &&
1575 matroska_convert_tag(s, &tags[i].tag,
1576 &track[j].stream->metadata, NULL);
1581 av_log(NULL, AV_LOG_WARNING,
1582 "The tags at index %d refer to a non-existent track "
1584 i, tags[i].target.trackuid);
1587 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1588 tags[i].target.type);
1593 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
1596 uint32_t level_up = matroska->level_up;
1597 uint32_t saved_id = matroska->current_id;
1598 int64_t before_pos = avio_tell(matroska->ctx->pb);
1599 MatroskaLevel level;
1604 offset = pos + matroska->segment_start;
1605 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1606 /* We don't want to lose our seekhead level, so we add
1607 * a dummy. This is a crude hack. */
1608 if (matroska->num_levels == EBML_MAX_DEPTH) {
1609 av_log(matroska->ctx, AV_LOG_INFO,
1610 "Max EBML element depth (%d) reached, "
1611 "cannot parse further.\n", EBML_MAX_DEPTH);
1612 ret = AVERROR_INVALIDDATA;
1615 level.length = EBML_UNKNOWN_LENGTH;
1616 matroska->levels[matroska->num_levels] = level;
1617 matroska->num_levels++;
1618 matroska->current_id = 0;
1620 ret = ebml_parse(matroska, matroska_segment, matroska);
1622 /* remove dummy level */
1623 while (matroska->num_levels) {
1624 uint64_t length = matroska->levels[--matroska->num_levels].length;
1625 if (length == EBML_UNKNOWN_LENGTH)
1631 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1632 matroska->level_up = level_up;
1633 matroska->current_id = saved_id;
1638 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1640 EbmlList *seekhead_list = &matroska->seekhead;
1643 // we should not do any seeking in the streaming case
1644 if (!(matroska->ctx->pb->seekable & AVIO_SEEKABLE_NORMAL))
1647 for (i = 0; i < seekhead_list->nb_elem; i++) {
1648 MatroskaSeekhead *seekheads = seekhead_list->elem;
1649 uint32_t id = seekheads[i].id;
1650 uint64_t pos = seekheads[i].pos;
1652 MatroskaLevel1Element *elem = matroska_find_level1_elem(matroska, id);
1653 if (!elem || elem->parsed)
1658 // defer cues parsing until we actually need cue data.
1659 if (id == MATROSKA_ID_CUES)
1662 if (matroska_parse_seekhead_entry(matroska, pos) < 0) {
1663 // mark index as broken
1664 matroska->cues_parsing_deferred = -1;
1672 static void matroska_add_index_entries(MatroskaDemuxContext *matroska)
1674 EbmlList *index_list;
1675 MatroskaIndex *index;
1676 uint64_t index_scale = 1;
1679 if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
1682 index_list = &matroska->index;
1683 index = index_list->elem;
1684 if (index_list->nb_elem < 2)
1686 if (index[1].time > 1E14 / matroska->time_scale) {
1687 av_log(matroska->ctx, AV_LOG_WARNING, "Dropping apparently-broken index.\n");
1690 for (i = 0; i < index_list->nb_elem; i++) {
1691 EbmlList *pos_list = &index[i].pos;
1692 MatroskaIndexPos *pos = pos_list->elem;
1693 for (j = 0; j < pos_list->nb_elem; j++) {
1694 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1696 if (track && track->stream)
1697 av_add_index_entry(track->stream,
1698 pos[j].pos + matroska->segment_start,
1699 index[i].time / index_scale, 0, 0,
1705 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1708 if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
1711 for (i = 0; i < matroska->num_level1_elems; i++) {
1712 MatroskaLevel1Element *elem = &matroska->level1_elems[i];
1713 if (elem->id == MATROSKA_ID_CUES && !elem->parsed) {
1714 if (matroska_parse_seekhead_entry(matroska, elem->pos) < 0)
1715 matroska->cues_parsing_deferred = -1;
1721 matroska_add_index_entries(matroska);
1724 static int matroska_aac_profile(char *codec_id)
1726 static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
1729 for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
1730 if (strstr(codec_id, aac_profiles[profile]))
1735 static int matroska_aac_sri(int samplerate)
1739 for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1740 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1745 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1747 /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1748 avpriv_dict_set_timestamp(metadata, "creation_time", date_utc / 1000 + 978307200000000LL);
1751 static int matroska_parse_flac(AVFormatContext *s,
1752 MatroskaTrack *track,
1755 AVStream *st = track->stream;
1756 uint8_t *p = track->codec_priv.data;
1757 int size = track->codec_priv.size;
1759 if (size < 8 + FLAC_STREAMINFO_SIZE || p[4] & 0x7f) {
1760 av_log(s, AV_LOG_WARNING, "Invalid FLAC private data\n");
1761 track->codec_priv.size = 0;
1765 track->codec_priv.size = 8 + FLAC_STREAMINFO_SIZE;
1767 p += track->codec_priv.size;
1768 size -= track->codec_priv.size;
1770 /* parse the remaining metadata blocks if present */
1772 int block_last, block_type, block_size;
1774 flac_parse_block_header(p, &block_last, &block_type, &block_size);
1778 if (block_size > size)
1781 /* check for the channel mask */
1782 if (block_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
1783 AVDictionary *dict = NULL;
1784 AVDictionaryEntry *chmask;
1786 ff_vorbis_comment(s, &dict, p, block_size, 0);
1787 chmask = av_dict_get(dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
1789 uint64_t mask = strtol(chmask->value, NULL, 0);
1790 if (!mask || mask & ~0x3ffffULL) {
1791 av_log(s, AV_LOG_WARNING,
1792 "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
1794 st->codecpar->channel_layout = mask;
1796 av_dict_free(&dict);
1806 static int mkv_field_order(MatroskaDemuxContext *matroska, int64_t field_order)
1808 int major, minor, micro, bttb = 0;
1810 /* workaround a bug in our Matroska muxer, introduced in version 57.36 alongside
1811 * this function, and fixed in 57.52 */
1812 if (matroska->muxingapp && sscanf(matroska->muxingapp, "Lavf%d.%d.%d", &major, &minor, µ) == 3)
1813 bttb = (major == 57 && minor >= 36 && minor <= 51 && micro >= 100);
1815 switch (field_order) {
1816 case MATROSKA_VIDEO_FIELDORDER_PROGRESSIVE:
1817 return AV_FIELD_PROGRESSIVE;
1818 case MATROSKA_VIDEO_FIELDORDER_UNDETERMINED:
1819 return AV_FIELD_UNKNOWN;
1820 case MATROSKA_VIDEO_FIELDORDER_TT:
1822 case MATROSKA_VIDEO_FIELDORDER_BB:
1824 case MATROSKA_VIDEO_FIELDORDER_BT:
1825 return bttb ? AV_FIELD_TB : AV_FIELD_BT;
1826 case MATROSKA_VIDEO_FIELDORDER_TB:
1827 return bttb ? AV_FIELD_BT : AV_FIELD_TB;
1829 return AV_FIELD_UNKNOWN;
1833 static void mkv_stereo_mode_display_mul(int stereo_mode,
1834 int *h_width, int *h_height)
1836 switch (stereo_mode) {
1837 case MATROSKA_VIDEO_STEREOMODE_TYPE_MONO:
1838 case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_RL:
1839 case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR:
1840 case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_RL:
1841 case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR:
1843 case MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT:
1844 case MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT:
1845 case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_RL:
1846 case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR:
1849 case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTTOM_TOP:
1850 case MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM:
1851 case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_RL:
1852 case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR:
1858 static int mkv_parse_video_color(AVStream *st, const MatroskaTrack *track) {
1859 const MatroskaTrackVideoColor *color = track->video.color.elem;
1860 const MatroskaMasteringMeta *mastering_meta;
1861 int has_mastering_primaries, has_mastering_luminance;
1863 if (!track->video.color.nb_elem)
1866 mastering_meta = &color->mastering_meta;
1867 // Mastering primaries are CIE 1931 coords, and must be > 0.
1868 has_mastering_primaries =
1869 mastering_meta->r_x > 0 && mastering_meta->r_y > 0 &&
1870 mastering_meta->g_x > 0 && mastering_meta->g_y > 0 &&
1871 mastering_meta->b_x > 0 && mastering_meta->b_y > 0 &&
1872 mastering_meta->white_x > 0 && mastering_meta->white_y > 0;
1873 has_mastering_luminance = mastering_meta->max_luminance > 0;
1875 if (color->matrix_coefficients != AVCOL_SPC_RESERVED)
1876 st->codecpar->color_space = color->matrix_coefficients;
1877 if (color->primaries != AVCOL_PRI_RESERVED &&
1878 color->primaries != AVCOL_PRI_RESERVED0)
1879 st->codecpar->color_primaries = color->primaries;
1880 if (color->transfer_characteristics != AVCOL_TRC_RESERVED &&
1881 color->transfer_characteristics != AVCOL_TRC_RESERVED0)
1882 st->codecpar->color_trc = color->transfer_characteristics;
1883 if (color->range != AVCOL_RANGE_UNSPECIFIED &&
1884 color->range <= AVCOL_RANGE_JPEG)
1885 st->codecpar->color_range = color->range;
1886 if (color->chroma_siting_horz != MATROSKA_COLOUR_CHROMASITINGHORZ_UNDETERMINED &&
1887 color->chroma_siting_vert != MATROSKA_COLOUR_CHROMASITINGVERT_UNDETERMINED &&
1888 color->chroma_siting_horz < MATROSKA_COLOUR_CHROMASITINGHORZ_NB &&
1889 color->chroma_siting_vert < MATROSKA_COLOUR_CHROMASITINGVERT_NB) {
1890 st->codecpar->chroma_location =
1891 avcodec_chroma_pos_to_enum((color->chroma_siting_horz - 1) << 7,
1892 (color->chroma_siting_vert - 1) << 7);
1894 if (color->max_cll && color->max_fall) {
1897 AVContentLightMetadata *metadata = av_content_light_metadata_alloc(&size);
1899 return AVERROR(ENOMEM);
1900 ret = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
1901 (uint8_t *)metadata, size);
1903 av_freep(&metadata);
1906 metadata->MaxCLL = color->max_cll;
1907 metadata->MaxFALL = color->max_fall;
1910 if (has_mastering_primaries || has_mastering_luminance) {
1911 // Use similar rationals as other standards.
1912 const int chroma_den = 50000;
1913 const int luma_den = 10000;
1914 AVMasteringDisplayMetadata *metadata =
1915 (AVMasteringDisplayMetadata*) av_stream_new_side_data(
1916 st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
1917 sizeof(AVMasteringDisplayMetadata));
1919 return AVERROR(ENOMEM);
1921 memset(metadata, 0, sizeof(AVMasteringDisplayMetadata));
1922 if (has_mastering_primaries) {
1923 metadata->display_primaries[0][0] = av_make_q(
1924 round(mastering_meta->r_x * chroma_den), chroma_den);
1925 metadata->display_primaries[0][1] = av_make_q(
1926 round(mastering_meta->r_y * chroma_den), chroma_den);
1927 metadata->display_primaries[1][0] = av_make_q(
1928 round(mastering_meta->g_x * chroma_den), chroma_den);
1929 metadata->display_primaries[1][1] = av_make_q(
1930 round(mastering_meta->g_y * chroma_den), chroma_den);
1931 metadata->display_primaries[2][0] = av_make_q(
1932 round(mastering_meta->b_x * chroma_den), chroma_den);
1933 metadata->display_primaries[2][1] = av_make_q(
1934 round(mastering_meta->b_y * chroma_den), chroma_den);
1935 metadata->white_point[0] = av_make_q(
1936 round(mastering_meta->white_x * chroma_den), chroma_den);
1937 metadata->white_point[1] = av_make_q(
1938 round(mastering_meta->white_y * chroma_den), chroma_den);
1939 metadata->has_primaries = 1;
1941 if (has_mastering_luminance) {
1942 metadata->max_luminance = av_make_q(
1943 round(mastering_meta->max_luminance * luma_den), luma_den);
1944 metadata->min_luminance = av_make_q(
1945 round(mastering_meta->min_luminance * luma_den), luma_den);
1946 metadata->has_luminance = 1;
1952 static int mkv_parse_video_projection(AVStream *st, const MatroskaTrack *track) {
1953 AVSphericalMapping *spherical;
1954 enum AVSphericalProjection projection;
1955 size_t spherical_size;
1956 uint32_t l = 0, t = 0, r = 0, b = 0;
1957 uint32_t padding = 0;
1961 bytestream2_init(&gb, track->video.projection.private.data,
1962 track->video.projection.private.size);
1964 if (bytestream2_get_byte(&gb) != 0) {
1965 av_log(NULL, AV_LOG_WARNING, "Unknown spherical metadata\n");
1969 bytestream2_skip(&gb, 3); // flags
1971 switch (track->video.projection.type) {
1972 case MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR:
1973 if (track->video.projection.private.size == 20) {
1974 t = bytestream2_get_be32(&gb);
1975 b = bytestream2_get_be32(&gb);
1976 l = bytestream2_get_be32(&gb);
1977 r = bytestream2_get_be32(&gb);
1979 if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
1980 av_log(NULL, AV_LOG_ERROR,
1981 "Invalid bounding rectangle coordinates "
1982 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n",
1984 return AVERROR_INVALIDDATA;
1986 } else if (track->video.projection.private.size != 0) {
1987 av_log(NULL, AV_LOG_ERROR, "Unknown spherical metadata\n");
1988 return AVERROR_INVALIDDATA;
1991 if (l || t || r || b)
1992 projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
1994 projection = AV_SPHERICAL_EQUIRECTANGULAR;
1996 case MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP:
1997 if (track->video.projection.private.size < 4) {
1998 av_log(NULL, AV_LOG_ERROR, "Missing projection private properties\n");
1999 return AVERROR_INVALIDDATA;
2000 } else if (track->video.projection.private.size == 12) {
2001 uint32_t layout = bytestream2_get_be32(&gb);
2003 av_log(NULL, AV_LOG_WARNING,
2004 "Unknown spherical cubemap layout %"PRIu32"\n", layout);
2007 projection = AV_SPHERICAL_CUBEMAP;
2008 padding = bytestream2_get_be32(&gb);
2010 av_log(NULL, AV_LOG_ERROR, "Unknown spherical metadata\n");
2011 return AVERROR_INVALIDDATA;
2014 case MATROSKA_VIDEO_PROJECTION_TYPE_RECTANGULAR:
2015 /* No Spherical metadata */
2018 av_log(NULL, AV_LOG_WARNING,
2019 "Unknown spherical metadata type %"PRIu64"\n",
2020 track->video.projection.type);
2024 spherical = av_spherical_alloc(&spherical_size);
2026 return AVERROR(ENOMEM);
2028 spherical->projection = projection;
2030 spherical->yaw = (int32_t) (track->video.projection.yaw * (1 << 16));
2031 spherical->pitch = (int32_t) (track->video.projection.pitch * (1 << 16));
2032 spherical->roll = (int32_t) (track->video.projection.roll * (1 << 16));
2034 spherical->padding = padding;
2036 spherical->bound_left = l;
2037 spherical->bound_top = t;
2038 spherical->bound_right = r;
2039 spherical->bound_bottom = b;
2041 ret = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL, (uint8_t *)spherical,
2044 av_freep(&spherical);
2051 static int get_qt_codec(MatroskaTrack *track, uint32_t *fourcc, enum AVCodecID *codec_id)
2053 const AVCodecTag *codec_tags;
2055 codec_tags = track->type == MATROSKA_TRACK_TYPE_VIDEO ?
2056 ff_codec_movvideo_tags : ff_codec_movaudio_tags;
2058 /* Normalize noncompliant private data that starts with the fourcc
2059 * by expanding/shifting the data by 4 bytes and storing the data
2060 * size at the start. */
2061 if (ff_codec_get_id(codec_tags, AV_RL32(track->codec_priv.data))) {
2062 int ret = av_buffer_realloc(&track->codec_priv.buf,
2063 track->codec_priv.size + 4 + AV_INPUT_BUFFER_PADDING_SIZE);
2067 track->codec_priv.data = track->codec_priv.buf->data;
2068 memmove(track->codec_priv.data + 4, track->codec_priv.data, track->codec_priv.size);
2069 track->codec_priv.size += 4;
2070 AV_WB32(track->codec_priv.data, track->codec_priv.size);
2073 *fourcc = AV_RL32(track->codec_priv.data + 4);
2074 *codec_id = ff_codec_get_id(codec_tags, *fourcc);
2079 static int matroska_parse_tracks(AVFormatContext *s)
2081 MatroskaDemuxContext *matroska = s->priv_data;
2082 MatroskaTrack *tracks = matroska->tracks.elem;
2087 for (i = 0; i < matroska->tracks.nb_elem; i++) {
2088 MatroskaTrack *track = &tracks[i];
2089 enum AVCodecID codec_id = AV_CODEC_ID_NONE;
2090 EbmlList *encodings_list = &track->encodings;
2091 MatroskaTrackEncoding *encodings = encodings_list->elem;
2092 uint8_t *extradata = NULL;
2093 int extradata_size = 0;
2094 int extradata_offset = 0;
2095 uint32_t fourcc = 0;
2097 char* key_id_base64 = NULL;
2100 /* Apply some sanity checks. */
2101 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
2102 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
2103 track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
2104 track->type != MATROSKA_TRACK_TYPE_METADATA) {
2105 av_log(matroska->ctx, AV_LOG_INFO,
2106 "Unknown or unsupported track type %"PRIu64"\n",
2110 if (!track->codec_id)
2113 if (track->audio.samplerate < 0 || track->audio.samplerate > INT_MAX ||
2114 isnan(track->audio.samplerate)) {
2115 av_log(matroska->ctx, AV_LOG_WARNING,
2116 "Invalid sample rate %f, defaulting to 8000 instead.\n",
2117 track->audio.samplerate);
2118 track->audio.samplerate = 8000;
2121 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2122 if (!track->default_duration && track->video.frame_rate > 0) {
2123 double default_duration = 1000000000 / track->video.frame_rate;
2124 if (default_duration > UINT64_MAX || default_duration < 0) {
2125 av_log(matroska->ctx, AV_LOG_WARNING,
2126 "Invalid frame rate %e. Cannot calculate default duration.\n",
2127 track->video.frame_rate);
2129 track->default_duration = default_duration;
2132 if (track->video.display_width == -1)
2133 track->video.display_width = track->video.pixel_width;
2134 if (track->video.display_height == -1)
2135 track->video.display_height = track->video.pixel_height;
2136 if (track->video.color_space.size == 4)
2137 fourcc = AV_RL32(track->video.color_space.data);
2138 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2139 if (!track->audio.out_samplerate)
2140 track->audio.out_samplerate = track->audio.samplerate;
2142 if (encodings_list->nb_elem > 1) {
2143 av_log(matroska->ctx, AV_LOG_ERROR,
2144 "Multiple combined encodings not supported");
2145 } else if (encodings_list->nb_elem == 1) {
2146 if (encodings[0].type) {
2147 if (encodings[0].encryption.key_id.size > 0) {
2148 /* Save the encryption key id to be stored later as a
2150 const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
2151 key_id_base64 = av_malloc(b64_size);
2152 if (key_id_base64 == NULL)
2153 return AVERROR(ENOMEM);
2155 av_base64_encode(key_id_base64, b64_size,
2156 encodings[0].encryption.key_id.data,
2157 encodings[0].encryption.key_id.size);
2159 encodings[0].scope = 0;
2160 av_log(matroska->ctx, AV_LOG_ERROR,
2161 "Unsupported encoding type");
2165 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
2168 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
2171 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
2173 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
2174 encodings[0].scope = 0;
2175 av_log(matroska->ctx, AV_LOG_ERROR,
2176 "Unsupported encoding type");
2177 } else if (track->codec_priv.size && encodings[0].scope & 2) {
2178 uint8_t *codec_priv = track->codec_priv.data;
2179 int ret = matroska_decode_buffer(&track->codec_priv.data,
2180 &track->codec_priv.size,
2183 track->codec_priv.data = NULL;
2184 track->codec_priv.size = 0;
2185 av_log(matroska->ctx, AV_LOG_ERROR,
2186 "Failed to decode codec private data\n");
2189 if (codec_priv != track->codec_priv.data) {
2190 av_buffer_unref(&track->codec_priv.buf);
2191 if (track->codec_priv.data) {
2192 track->codec_priv.buf = av_buffer_create(track->codec_priv.data,
2193 track->codec_priv.size + AV_INPUT_BUFFER_PADDING_SIZE,
2195 if (!track->codec_priv.buf) {
2196 av_freep(&track->codec_priv.data);
2197 track->codec_priv.size = 0;
2198 return AVERROR(ENOMEM);
2205 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
2206 if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2207 strlen(ff_mkv_codec_tags[j].str))) {
2208 codec_id = ff_mkv_codec_tags[j].id;
2213 st = track->stream = avformat_new_stream(s, NULL);
2215 av_free(key_id_base64);
2216 return AVERROR(ENOMEM);
2219 if (key_id_base64) {
2220 /* export encryption key id as base64 metadata tag */
2221 av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
2222 av_freep(&key_id_base64);
2225 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
2226 track->codec_priv.size >= 40 &&
2227 track->codec_priv.data) {
2228 track->ms_compat = 1;
2229 bit_depth = AV_RL16(track->codec_priv.data + 14);
2230 fourcc = AV_RL32(track->codec_priv.data + 16);
2231 codec_id = ff_codec_get_id(ff_codec_bmp_tags,
2234 codec_id = ff_codec_get_id(ff_codec_movvideo_tags,
2236 extradata_offset = 40;
2237 } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
2238 track->codec_priv.size >= 14 &&
2239 track->codec_priv.data) {
2241 ffio_init_context(&b, track->codec_priv.data,
2242 track->codec_priv.size,
2243 0, NULL, NULL, NULL, NULL);
2244 ret = ff_get_wav_header(s, &b, st->codecpar, track->codec_priv.size, 0);
2247 codec_id = st->codecpar->codec_id;
2248 fourcc = st->codecpar->codec_tag;
2249 extradata_offset = FFMIN(track->codec_priv.size, 18);
2250 } else if (!strcmp(track->codec_id, "A_QUICKTIME")
2251 /* Normally 36, but allow noncompliant private data */
2252 && (track->codec_priv.size >= 32)
2253 && (track->codec_priv.data)) {
2254 uint16_t sample_size;
2255 int ret = get_qt_codec(track, &fourcc, &codec_id);
2258 sample_size = AV_RB16(track->codec_priv.data + 26);
2260 if (sample_size == 8) {
2261 fourcc = MKTAG('r','a','w',' ');
2262 codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
2263 } else if (sample_size == 16) {
2264 fourcc = MKTAG('t','w','o','s');
2265 codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
2268 if ((fourcc == MKTAG('t','w','o','s') ||
2269 fourcc == MKTAG('s','o','w','t')) &&
2271 codec_id = AV_CODEC_ID_PCM_S8;
2272 } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
2273 (track->codec_priv.size >= 21) &&
2274 (track->codec_priv.data)) {
2275 int ret = get_qt_codec(track, &fourcc, &codec_id);
2278 if (codec_id == AV_CODEC_ID_NONE && AV_RL32(track->codec_priv.data+4) == AV_RL32("SMI ")) {
2279 fourcc = MKTAG('S','V','Q','3');
2280 codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
2282 if (codec_id == AV_CODEC_ID_NONE)
2283 av_log(matroska->ctx, AV_LOG_ERROR,
2284 "mov FourCC not found %s.\n", av_fourcc2str(fourcc));
2285 if (track->codec_priv.size >= 86) {
2286 bit_depth = AV_RB16(track->codec_priv.data + 82);
2287 ffio_init_context(&b, track->codec_priv.data,
2288 track->codec_priv.size,
2289 0, NULL, NULL, NULL, NULL);
2290 if (ff_get_qtpalette(codec_id, &b, track->palette)) {
2292 track->has_palette = 1;
2295 } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
2296 switch (track->audio.bitdepth) {
2298 codec_id = AV_CODEC_ID_PCM_U8;
2301 codec_id = AV_CODEC_ID_PCM_S24BE;
2304 codec_id = AV_CODEC_ID_PCM_S32BE;
2307 } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
2308 switch (track->audio.bitdepth) {
2310 codec_id = AV_CODEC_ID_PCM_U8;
2313 codec_id = AV_CODEC_ID_PCM_S24LE;
2316 codec_id = AV_CODEC_ID_PCM_S32LE;
2319 } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
2320 track->audio.bitdepth == 64) {
2321 codec_id = AV_CODEC_ID_PCM_F64LE;
2322 } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
2323 int profile = matroska_aac_profile(track->codec_id);
2324 int sri = matroska_aac_sri(track->audio.samplerate);
2325 extradata = av_mallocz(5 + AV_INPUT_BUFFER_PADDING_SIZE);
2327 return AVERROR(ENOMEM);
2328 extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
2329 extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
2330 if (strstr(track->codec_id, "SBR")) {
2331 sri = matroska_aac_sri(track->audio.out_samplerate);
2332 extradata[2] = 0x56;
2333 extradata[3] = 0xE5;
2334 extradata[4] = 0x80 | (sri << 3);
2338 } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - AV_INPUT_BUFFER_PADDING_SIZE) {
2339 /* Only ALAC's magic cookie is stored in Matroska's track headers.
2340 * Create the "atom size", "tag", and "tag version" fields the
2341 * decoder expects manually. */
2342 extradata_size = 12 + track->codec_priv.size;
2343 extradata = av_mallocz(extradata_size +
2344 AV_INPUT_BUFFER_PADDING_SIZE);
2346 return AVERROR(ENOMEM);
2347 AV_WB32(extradata, extradata_size);
2348 memcpy(&extradata[4], "alac", 4);
2349 AV_WB32(&extradata[8], 0);
2350 memcpy(&extradata[12], track->codec_priv.data,
2351 track->codec_priv.size);
2352 } else if (codec_id == AV_CODEC_ID_TTA) {
2353 extradata_size = 30;
2354 extradata = av_mallocz(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2356 return AVERROR(ENOMEM);
2357 ffio_init_context(&b, extradata, extradata_size, 1,
2358 NULL, NULL, NULL, NULL);
2359 avio_write(&b, "TTA1", 4);
2361 if (track->audio.channels > UINT16_MAX ||
2362 track->audio.bitdepth > UINT16_MAX) {
2363 av_log(matroska->ctx, AV_LOG_WARNING,
2364 "Too large audio channel number %"PRIu64
2365 " or bitdepth %"PRIu64". Skipping track.\n",
2366 track->audio.channels, track->audio.bitdepth);
2367 av_freep(&extradata);
2368 if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
2369 return AVERROR_INVALIDDATA;
2373 avio_wl16(&b, track->audio.channels);
2374 avio_wl16(&b, track->audio.bitdepth);
2375 if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
2376 return AVERROR_INVALIDDATA;
2377 avio_wl32(&b, track->audio.out_samplerate);
2378 avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale),
2379 track->audio.out_samplerate,
2380 AV_TIME_BASE * 1000));
2381 } else if (codec_id == AV_CODEC_ID_RV10 ||
2382 codec_id == AV_CODEC_ID_RV20 ||
2383 codec_id == AV_CODEC_ID_RV30 ||
2384 codec_id == AV_CODEC_ID_RV40) {
2385 extradata_offset = 26;
2386 } else if (codec_id == AV_CODEC_ID_RA_144) {
2387 track->audio.out_samplerate = 8000;
2388 track->audio.channels = 1;
2389 } else if ((codec_id == AV_CODEC_ID_RA_288 ||
2390 codec_id == AV_CODEC_ID_COOK ||
2391 codec_id == AV_CODEC_ID_ATRAC3 ||
2392 codec_id == AV_CODEC_ID_SIPR)
2393 && track->codec_priv.data) {
2396 ffio_init_context(&b, track->codec_priv.data,
2397 track->codec_priv.size,
2398 0, NULL, NULL, NULL, NULL);
2400 flavor = avio_rb16(&b);
2401 track->audio.coded_framesize = avio_rb32(&b);
2403 track->audio.sub_packet_h = avio_rb16(&b);
2404 track->audio.frame_size = avio_rb16(&b);
2405 track->audio.sub_packet_size = avio_rb16(&b);
2407 track->audio.coded_framesize <= 0 ||
2408 track->audio.sub_packet_h <= 0 ||
2409 track->audio.frame_size <= 0 ||
2410 track->audio.sub_packet_size <= 0 && codec_id != AV_CODEC_ID_SIPR)
2411 return AVERROR_INVALIDDATA;
2412 track->audio.buf = av_malloc_array(track->audio.sub_packet_h,
2413 track->audio.frame_size);
2414 if (!track->audio.buf)
2415 return AVERROR(ENOMEM);
2416 if (codec_id == AV_CODEC_ID_RA_288) {
2417 st->codecpar->block_align = track->audio.coded_framesize;
2418 track->codec_priv.size = 0;
2420 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
2421 static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
2422 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
2423 st->codecpar->bit_rate = sipr_bit_rate[flavor];
2425 st->codecpar->block_align = track->audio.sub_packet_size;
2426 extradata_offset = 78;
2428 } else if (codec_id == AV_CODEC_ID_FLAC && track->codec_priv.size) {
2429 ret = matroska_parse_flac(s, track, &extradata_offset);
2432 } else if (codec_id == AV_CODEC_ID_PRORES && track->codec_priv.size == 4) {
2433 fourcc = AV_RL32(track->codec_priv.data);
2434 } else if (codec_id == AV_CODEC_ID_VP9 && track->codec_priv.size) {
2435 /* we don't need any value stored in CodecPrivate.
2436 make sure that it's not exported as extradata. */
2437 track->codec_priv.size = 0;
2438 } else if (codec_id == AV_CODEC_ID_AV1 && track->codec_priv.size) {
2439 /* For now, propagate only the OBUs, if any. Once libavcodec is
2440 updated to handle isobmff style extradata this can be removed. */
2441 extradata_offset = 4;
2443 track->codec_priv.size -= extradata_offset;
2445 if (codec_id == AV_CODEC_ID_NONE)
2446 av_log(matroska->ctx, AV_LOG_INFO,
2447 "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
2449 if (track->time_scale < 0.01)
2450 track->time_scale = 1.0;
2451 avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
2452 1000 * 1000 * 1000); /* 64 bit pts in ns */
2454 /* convert the delay from ns to the track timebase */
2455 track->codec_delay_in_track_tb = av_rescale_q(track->codec_delay,
2456 (AVRational){ 1, 1000000000 },
2459 st->codecpar->codec_id = codec_id;
2461 if (strcmp(track->language, "und"))
2462 av_dict_set(&st->metadata, "language", track->language, 0);
2463 av_dict_set(&st->metadata, "title", track->name, 0);
2465 if (track->flag_default)
2466 st->disposition |= AV_DISPOSITION_DEFAULT;
2467 if (track->flag_forced)
2468 st->disposition |= AV_DISPOSITION_FORCED;
2470 if (!st->codecpar->extradata) {
2472 st->codecpar->extradata = extradata;
2473 st->codecpar->extradata_size = extradata_size;
2474 } else if (track->codec_priv.data && track->codec_priv.size > 0) {
2475 if (ff_alloc_extradata(st->codecpar, track->codec_priv.size))
2476 return AVERROR(ENOMEM);
2477 memcpy(st->codecpar->extradata,
2478 track->codec_priv.data + extradata_offset,
2479 track->codec_priv.size);
2483 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2484 MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
2485 int display_width_mul = 1;
2486 int display_height_mul = 1;
2488 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2489 st->codecpar->codec_tag = fourcc;
2491 st->codecpar->bits_per_coded_sample = bit_depth;
2492 st->codecpar->width = track->video.pixel_width;
2493 st->codecpar->height = track->video.pixel_height;
2495 if (track->video.interlaced == MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED)
2496 st->codecpar->field_order = mkv_field_order(matroska, track->video.field_order);
2497 else if (track->video.interlaced == MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE)
2498 st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
2500 if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
2501 mkv_stereo_mode_display_mul(track->video.stereo_mode, &display_width_mul, &display_height_mul);
2503 if (track->video.display_unit < MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN) {
2504 av_reduce(&st->sample_aspect_ratio.num,
2505 &st->sample_aspect_ratio.den,
2506 st->codecpar->height * track->video.display_width * display_width_mul,
2507 st->codecpar->width * track->video.display_height * display_height_mul,
2510 if (st->codecpar->codec_id != AV_CODEC_ID_HEVC)
2511 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2513 if (track->default_duration) {
2514 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2515 1000000000, track->default_duration, 30000);
2516 #if FF_API_R_FRAME_RATE
2517 if ( st->avg_frame_rate.num < st->avg_frame_rate.den * 1000LL
2518 && st->avg_frame_rate.num > st->avg_frame_rate.den * 5LL)
2519 st->r_frame_rate = st->avg_frame_rate;
2523 /* export stereo mode flag as metadata tag */
2524 if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
2525 av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
2527 /* export alpha mode flag as metadata tag */
2528 if (track->video.alpha_mode)
2529 av_dict_set(&st->metadata, "alpha_mode", "1", 0);
2531 /* if we have virtual track, mark the real tracks */
2532 for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
2534 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
2536 snprintf(buf, sizeof(buf), "%s_%d",
2537 ff_matroska_video_stereo_plane[planes[j].type], i);
2538 for (k=0; k < matroska->tracks.nb_elem; k++)
2539 if (planes[j].uid == tracks[k].uid && tracks[k].stream) {
2540 av_dict_set(&tracks[k].stream->metadata,
2541 "stereo_mode", buf, 0);
2545 // add stream level stereo3d side data if it is a supported format
2546 if (track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
2547 track->video.stereo_mode != 10 && track->video.stereo_mode != 12) {
2548 int ret = ff_mkv_stereo3d_conv(st, track->video.stereo_mode);
2553 ret = mkv_parse_video_color(st, track);
2556 ret = mkv_parse_video_projection(st, track);
2559 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2560 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2561 st->codecpar->codec_tag = fourcc;
2562 st->codecpar->sample_rate = track->audio.out_samplerate;
2563 st->codecpar->channels = track->audio.channels;
2564 if (!st->codecpar->bits_per_coded_sample)
2565 st->codecpar->bits_per_coded_sample = track->audio.bitdepth;
2566 if (st->codecpar->codec_id == AV_CODEC_ID_MP3 ||
2567 st->codecpar->codec_id == AV_CODEC_ID_MLP ||
2568 st->codecpar->codec_id == AV_CODEC_ID_TRUEHD)
2569 st->need_parsing = AVSTREAM_PARSE_FULL;
2570 else if (st->codecpar->codec_id != AV_CODEC_ID_AAC)
2571 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2572 if (track->codec_delay > 0) {
2573 st->codecpar->initial_padding = av_rescale_q(track->codec_delay,
2574 (AVRational){1, 1000000000},
2575 (AVRational){1, st->codecpar->codec_id == AV_CODEC_ID_OPUS ?
2576 48000 : st->codecpar->sample_rate});
2578 if (track->seek_preroll > 0) {
2579 st->codecpar->seek_preroll = av_rescale_q(track->seek_preroll,
2580 (AVRational){1, 1000000000},
2581 (AVRational){1, st->codecpar->sample_rate});
2583 } else if (codec_id == AV_CODEC_ID_WEBVTT) {
2584 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2586 if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
2587 st->disposition |= AV_DISPOSITION_CAPTIONS;
2588 } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
2589 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2590 } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
2591 st->disposition |= AV_DISPOSITION_METADATA;
2593 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2594 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2595 if (st->codecpar->codec_id == AV_CODEC_ID_ASS)
2596 matroska->contains_ssa = 1;
2603 static int matroska_read_header(AVFormatContext *s)
2605 MatroskaDemuxContext *matroska = s->priv_data;
2606 EbmlList *attachments_list = &matroska->attachments;
2607 EbmlList *chapters_list = &matroska->chapters;
2608 MatroskaAttachment *attachments;
2609 MatroskaChapter *chapters;
2610 uint64_t max_start = 0;
2616 matroska->cues_parsing_deferred = 1;
2618 /* First read the EBML header. */
2619 if (ebml_parse(matroska, ebml_syntax, &ebml) || !ebml.doctype) {
2620 av_log(matroska->ctx, AV_LOG_ERROR, "EBML header parsing failed\n");
2621 ebml_free(ebml_syntax, &ebml);
2622 return AVERROR_INVALIDDATA;
2624 if (ebml.version > EBML_VERSION ||
2625 ebml.max_size > sizeof(uint64_t) ||
2626 ebml.id_length > sizeof(uint32_t) ||
2627 ebml.doctype_version > 3) {
2628 avpriv_report_missing_feature(matroska->ctx,
2629 "EBML version %"PRIu64", doctype %s, doc version %"PRIu64,
2630 ebml.version, ebml.doctype, ebml.doctype_version);
2631 ebml_free(ebml_syntax, &ebml);
2632 return AVERROR_PATCHWELCOME;
2633 } else if (ebml.doctype_version == 3) {
2634 av_log(matroska->ctx, AV_LOG_WARNING,
2635 "EBML header using unsupported features\n"
2636 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
2637 ebml.version, ebml.doctype, ebml.doctype_version);
2639 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
2640 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
2642 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
2643 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
2644 if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
2645 ebml_free(ebml_syntax, &ebml);
2646 return AVERROR_INVALIDDATA;
2649 ebml_free(ebml_syntax, &ebml);
2651 /* The next thing is a segment. */
2652 pos = avio_tell(matroska->ctx->pb);
2653 res = ebml_parse(matroska, matroska_segments, matroska);
2654 // try resyncing until we find a EBML_STOP type element.
2656 res = matroska_resync(matroska, pos);
2659 pos = avio_tell(matroska->ctx->pb);
2660 res = ebml_parse(matroska, matroska_segment, matroska);
2662 matroska_execute_seekhead(matroska);
2664 if (!matroska->time_scale)
2665 matroska->time_scale = 1000000;
2666 if (matroska->duration)
2667 matroska->ctx->duration = matroska->duration * matroska->time_scale *
2668 1000 / AV_TIME_BASE;
2669 av_dict_set(&s->metadata, "title", matroska->title, 0);
2670 av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
2672 if (matroska->date_utc.size == 8)
2673 matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
2675 res = matroska_parse_tracks(s);
2679 attachments = attachments_list->elem;
2680 for (j = 0; j < attachments_list->nb_elem; j++) {
2681 if (!(attachments[j].filename && attachments[j].mime &&
2682 attachments[j].bin.data && attachments[j].bin.size > 0)) {
2683 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2685 AVStream *st = avformat_new_stream(s, NULL);
2688 av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
2689 av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
2690 st->codecpar->codec_id = AV_CODEC_ID_NONE;
2692 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2693 if (!strncmp(ff_mkv_image_mime_tags[i].str, attachments[j].mime,
2694 strlen(ff_mkv_image_mime_tags[i].str))) {
2695 st->codecpar->codec_id = ff_mkv_image_mime_tags[i].id;
2700 attachments[j].stream = st;
2702 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
2703 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
2704 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2706 av_init_packet(&st->attached_pic);
2707 if ((res = av_new_packet(&st->attached_pic, attachments[j].bin.size)) < 0)
2709 memcpy(st->attached_pic.data, attachments[j].bin.data, attachments[j].bin.size);
2710 st->attached_pic.stream_index = st->index;
2711 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
2713 st->codecpar->codec_type = AVMEDIA_TYPE_ATTACHMENT;
2714 if (ff_alloc_extradata(st->codecpar, attachments[j].bin.size))
2716 memcpy(st->codecpar->extradata, attachments[j].bin.data,
2717 attachments[j].bin.size);
2719 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2720 if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
2721 strlen(ff_mkv_mime_tags[i].str))) {
2722 st->codecpar->codec_id = ff_mkv_mime_tags[i].id;
2730 chapters = chapters_list->elem;
2731 for (i = 0; i < chapters_list->nb_elem; i++)
2732 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
2733 (max_start == 0 || chapters[i].start > max_start)) {
2734 chapters[i].chapter =
2735 avpriv_new_chapter(s, chapters[i].uid,
2736 (AVRational) { 1, 1000000000 },
2737 chapters[i].start, chapters[i].end,
2739 if (chapters[i].chapter) {
2740 av_dict_set(&chapters[i].chapter->metadata,
2741 "title", chapters[i].title, 0);
2743 max_start = chapters[i].start;
2746 matroska_add_index_entries(matroska);
2748 matroska_convert_tags(s);
2752 matroska_read_close(s);
2757 * Put one packet in an application-supplied AVPacket struct.
2758 * Returns 0 on success or -1 on failure.
2760 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
2763 if (matroska->queue) {
2764 MatroskaTrack *tracks = matroska->tracks.elem;
2765 MatroskaTrack *track;
2767 ff_packet_list_get(&matroska->queue, &matroska->queue_end, pkt);
2768 track = &tracks[pkt->stream_index];
2769 if (track->has_palette) {
2770 uint8_t *pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2772 av_log(matroska->ctx, AV_LOG_ERROR, "Cannot append palette to packet\n");
2774 memcpy(pal, track->palette, AVPALETTE_SIZE);
2776 track->has_palette = 0;
2785 * Free all packets in our internal queue.
2787 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2789 ff_packet_list_free(&matroska->queue, &matroska->queue_end);
2792 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2793 int *buf_size, int type,
2794 uint32_t **lace_buf, int *laces)
2796 int res = 0, n, size = *buf_size;
2797 uint8_t *data = *buf;
2798 uint32_t *lace_size;
2802 *lace_buf = av_mallocz(sizeof(int));
2804 return AVERROR(ENOMEM);
2806 *lace_buf[0] = size;
2810 av_assert0(size > 0);
2814 lace_size = av_mallocz(*laces * sizeof(int));
2816 return AVERROR(ENOMEM);
2819 case 0x1: /* Xiph lacing */
2823 for (n = 0; res == 0 && n < *laces - 1; n++) {
2825 if (size <= total) {
2826 res = AVERROR_INVALIDDATA;
2831 lace_size[n] += temp;
2838 if (size <= total) {
2839 res = AVERROR_INVALIDDATA;
2843 lace_size[n] = size - total;
2847 case 0x2: /* fixed-size lacing */
2848 if (size % (*laces)) {
2849 res = AVERROR_INVALIDDATA;
2852 for (n = 0; n < *laces; n++)
2853 lace_size[n] = size / *laces;
2856 case 0x3: /* EBML lacing */
2860 n = matroska_ebmlnum_uint(matroska, data, size, &num);
2861 if (n < 0 || num > INT_MAX) {
2862 av_log(matroska->ctx, AV_LOG_INFO,
2863 "EBML block data error\n");
2864 res = n<0 ? n : AVERROR_INVALIDDATA;
2869 total = lace_size[0] = num;
2870 for (n = 1; res == 0 && n < *laces - 1; n++) {
2873 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2874 if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
2875 av_log(matroska->ctx, AV_LOG_INFO,
2876 "EBML block data error\n");
2877 res = r<0 ? r : AVERROR_INVALIDDATA;
2882 lace_size[n] = lace_size[n - 1] + snum;
2883 total += lace_size[n];
2885 if (size <= total) {
2886 res = AVERROR_INVALIDDATA;
2889 lace_size[*laces - 1] = size - total;
2895 *lace_buf = lace_size;
2901 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2902 MatroskaTrack *track, AVStream *st,
2903 uint8_t *data, int size, uint64_t timecode,
2906 int a = st->codecpar->block_align;
2907 int sps = track->audio.sub_packet_size;
2908 int cfs = track->audio.coded_framesize;
2909 int h = track->audio.sub_packet_h;
2910 int y = track->audio.sub_packet_cnt;
2911 int w = track->audio.frame_size;
2914 if (!track->audio.pkt_cnt) {
2915 if (track->audio.sub_packet_cnt == 0)
2916 track->audio.buf_timecode = timecode;
2917 if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
2918 if (size < cfs * h / 2) {
2919 av_log(matroska->ctx, AV_LOG_ERROR,
2920 "Corrupt int4 RM-style audio packet size\n");
2921 return AVERROR_INVALIDDATA;
2923 for (x = 0; x < h / 2; x++)
2924 memcpy(track->audio.buf + x * 2 * w + y * cfs,
2925 data + x * cfs, cfs);
2926 } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
2928 av_log(matroska->ctx, AV_LOG_ERROR,
2929 "Corrupt sipr RM-style audio packet size\n");
2930 return AVERROR_INVALIDDATA;
2932 memcpy(track->audio.buf + y * w, data, w);
2934 if (size < sps * w / sps || h<=0 || w%sps) {
2935 av_log(matroska->ctx, AV_LOG_ERROR,
2936 "Corrupt generic RM-style audio packet size\n");
2937 return AVERROR_INVALIDDATA;
2939 for (x = 0; x < w / sps; x++)
2940 memcpy(track->audio.buf +
2941 sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
2942 data + x * sps, sps);
2945 if (++track->audio.sub_packet_cnt >= h) {
2946 if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
2947 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2948 track->audio.sub_packet_cnt = 0;
2949 track->audio.pkt_cnt = h * w / a;
2953 while (track->audio.pkt_cnt) {
2955 AVPacket pktl, *pkt = &pktl;
2957 ret = av_new_packet(pkt, a);
2962 track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
2964 pkt->pts = track->audio.buf_timecode;
2965 track->audio.buf_timecode = AV_NOPTS_VALUE;
2967 pkt->stream_index = st->index;
2968 ret = ff_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, 0);
2970 av_packet_unref(pkt);
2971 return AVERROR(ENOMEM);
2978 /* reconstruct full wavpack blocks from mangled matroska ones */
2979 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
2980 uint8_t **pdst, int *size)
2982 uint8_t *dst = NULL;
2987 int ret, offset = 0;
2989 if (srclen < 12 || track->stream->codecpar->extradata_size < 2)
2990 return AVERROR_INVALIDDATA;
2992 ver = AV_RL16(track->stream->codecpar->extradata);
2994 samples = AV_RL32(src);
2998 while (srclen >= 8) {
3003 uint32_t flags = AV_RL32(src);
3004 uint32_t crc = AV_RL32(src + 4);
3008 multiblock = (flags & 0x1800) != 0x1800;
3011 ret = AVERROR_INVALIDDATA;
3014 blocksize = AV_RL32(src);
3020 if (blocksize > srclen) {
3021 ret = AVERROR_INVALIDDATA;
3025 tmp = av_realloc(dst, dstlen + blocksize + 32 + AV_INPUT_BUFFER_PADDING_SIZE);
3027 ret = AVERROR(ENOMEM);
3031 dstlen += blocksize + 32;
3033 AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
3034 AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
3035 AV_WL16(dst + offset + 8, ver); // version
3036 AV_WL16(dst + offset + 10, 0); // track/index_no
3037 AV_WL32(dst + offset + 12, 0); // total samples
3038 AV_WL32(dst + offset + 16, 0); // block index
3039 AV_WL32(dst + offset + 20, samples); // number of samples
3040 AV_WL32(dst + offset + 24, flags); // flags
3041 AV_WL32(dst + offset + 28, crc); // crc
3042 memcpy(dst + offset + 32, src, blocksize); // block data
3045 srclen -= blocksize;
3046 offset += blocksize + 32;
3049 memset(dst + dstlen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3061 static int matroska_parse_prores(MatroskaTrack *track, uint8_t *src,
3062 uint8_t **pdst, int *size)
3067 if (AV_RB32(&src[4]) != MKBETAG('i', 'c', 'p', 'f')) {
3068 dst = av_malloc(dstlen + 8 + AV_INPUT_BUFFER_PADDING_SIZE);
3070 return AVERROR(ENOMEM);
3072 AV_WB32(dst, dstlen);
3073 AV_WB32(dst + 4, MKBETAG('i', 'c', 'p', 'f'));
3074 memcpy(dst + 8, src, dstlen);
3075 memset(dst + 8 + dstlen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3085 static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
3086 MatroskaTrack *track,
3088 uint8_t *data, int data_len,
3093 AVPacket pktl, *pkt = &pktl;
3094 uint8_t *id, *settings, *text, *buf;
3095 int id_len, settings_len, text_len;
3100 return AVERROR_INVALIDDATA;
3103 q = data + data_len;
3108 if (*p == '\r' || *p == '\n') {
3117 if (p >= q || *p != '\n')
3118 return AVERROR_INVALIDDATA;
3124 if (*p == '\r' || *p == '\n') {
3125 settings_len = p - settings;
3133 if (p >= q || *p != '\n')
3134 return AVERROR_INVALIDDATA;
3139 while (text_len > 0) {
3140 const int len = text_len - 1;
3141 const uint8_t c = p[len];
3142 if (c != '\r' && c != '\n')
3148 return AVERROR_INVALIDDATA;
3150 err = av_new_packet(pkt, text_len);
3155 memcpy(pkt->data, text, text_len);
3158 buf = av_packet_new_side_data(pkt,
3159 AV_PKT_DATA_WEBVTT_IDENTIFIER,
3162 av_packet_unref(pkt);
3163 return AVERROR(ENOMEM);
3165 memcpy(buf, id, id_len);
3168 if (settings_len > 0) {
3169 buf = av_packet_new_side_data(pkt,
3170 AV_PKT_DATA_WEBVTT_SETTINGS,
3173 av_packet_unref(pkt);
3174 return AVERROR(ENOMEM);
3176 memcpy(buf, settings, settings_len);
3179 // Do we need this for subtitles?
3180 // pkt->flags = AV_PKT_FLAG_KEY;
3182 pkt->stream_index = st->index;
3183 pkt->pts = timecode;
3185 // Do we need this for subtitles?
3186 // pkt->dts = timecode;
3188 pkt->duration = duration;
3191 err = ff_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, 0);
3193 av_packet_unref(pkt);
3194 return AVERROR(ENOMEM);
3200 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
3201 MatroskaTrack *track, AVStream *st,
3202 AVBufferRef *buf, uint8_t *data, int pkt_size,
3203 uint64_t timecode, uint64_t lace_duration,
3204 int64_t pos, int is_keyframe,
3205 uint8_t *additional, uint64_t additional_id, int additional_size,
3206 int64_t discard_padding)
3208 MatroskaTrackEncoding *encodings = track->encodings.elem;
3209 uint8_t *pkt_data = data;
3211 AVPacket pktl, *pkt = &pktl;
3213 if (encodings && !encodings->type && encodings->scope & 1) {
3214 res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
3219 if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
3221 res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
3223 av_log(matroska->ctx, AV_LOG_ERROR,
3224 "Error parsing a wavpack block.\n");
3227 if (pkt_data != data)
3228 av_freep(&pkt_data);
3232 if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
3234 res = matroska_parse_prores(track, pkt_data, &pr_data, &pkt_size);
3236 av_log(matroska->ctx, AV_LOG_ERROR,
3237 "Error parsing a prores block.\n");
3240 if (pkt_data != data)
3241 av_freep(&pkt_data);
3245 av_init_packet(pkt);
3246 if (pkt_data != data)
3247 pkt->buf = av_buffer_create(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE,
3250 pkt->buf = av_buffer_ref(buf);
3253 res = AVERROR(ENOMEM);
3257 pkt->data = pkt_data;
3258 pkt->size = pkt_size;
3259 pkt->flags = is_keyframe;
3260 pkt->stream_index = st->index;
3262 if (additional_size > 0) {
3263 uint8_t *side_data = av_packet_new_side_data(pkt,
3264 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
3265 additional_size + 8);
3267 av_packet_unref(pkt);
3268 return AVERROR(ENOMEM);
3270 AV_WB64(side_data, additional_id);
3271 memcpy(side_data + 8, additional, additional_size);
3274 if (discard_padding) {
3275 uint8_t *side_data = av_packet_new_side_data(pkt,
3276 AV_PKT_DATA_SKIP_SAMPLES,
3279 av_packet_unref(pkt);
3280 return AVERROR(ENOMEM);
3282 discard_padding = av_rescale_q(discard_padding,
3283 (AVRational){1, 1000000000},
3284 (AVRational){1, st->codecpar->sample_rate});
3285 if (discard_padding > 0) {
3286 AV_WL32(side_data + 4, discard_padding);
3288 AV_WL32(side_data, -discard_padding);
3292 if (track->ms_compat)
3293 pkt->dts = timecode;
3295 pkt->pts = timecode;
3297 pkt->duration = lace_duration;
3299 #if FF_API_CONVERGENCE_DURATION
3300 FF_DISABLE_DEPRECATION_WARNINGS
3301 if (st->codecpar->codec_id == AV_CODEC_ID_SUBRIP) {
3302 pkt->convergence_duration = lace_duration;
3304 FF_ENABLE_DEPRECATION_WARNINGS
3307 res = ff_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, 0);
3309 av_packet_unref(pkt);
3310 return AVERROR(ENOMEM);
3316 if (pkt_data != data)
3317 av_freep(&pkt_data);
3321 static int matroska_parse_block(MatroskaDemuxContext *matroska, AVBufferRef *buf, uint8_t *data,
3322 int size, int64_t pos, uint64_t cluster_time,
3323 uint64_t block_duration, int is_keyframe,
3324 uint8_t *additional, uint64_t additional_id, int additional_size,
3325 int64_t cluster_pos, int64_t discard_padding)
3327 uint64_t timecode = AV_NOPTS_VALUE;
3328 MatroskaTrack *track;
3332 uint32_t *lace_size = NULL;
3333 int n, flags, laces = 0;
3335 int trust_default_duration = 1;
3337 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
3338 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
3344 track = matroska_find_track_by_num(matroska, num);
3345 if (!track || !track->stream) {
3346 av_log(matroska->ctx, AV_LOG_INFO,
3347 "Invalid stream %"PRIu64" or size %u\n", num, size);
3348 return AVERROR_INVALIDDATA;
3349 } else if (size <= 3)
3352 if (st->discard >= AVDISCARD_ALL)
3354 av_assert1(block_duration != AV_NOPTS_VALUE);
3356 block_time = sign_extend(AV_RB16(data), 16);
3360 if (is_keyframe == -1)
3361 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
3363 if (cluster_time != (uint64_t) -1 &&
3364 (block_time >= 0 || cluster_time >= -block_time)) {
3365 timecode = cluster_time + block_time - track->codec_delay_in_track_tb;
3366 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
3367 timecode < track->end_timecode)
3368 is_keyframe = 0; /* overlapping subtitles are not key frame */
3370 ff_reduce_index(matroska->ctx, st->index);
3371 av_add_index_entry(st, cluster_pos, timecode, 0, 0,
3376 if (matroska->skip_to_keyframe &&
3377 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
3378 // Compare signed timecodes. Timecode may be negative due to codec delay
3379 // offset. We don't support timestamps greater than int64_t anyway - see
3381 if ((int64_t)timecode < (int64_t)matroska->skip_to_timecode)
3384 matroska->skip_to_keyframe = 0;
3385 else if (!st->skip_to_keyframe) {
3386 av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
3387 matroska->skip_to_keyframe = 0;
3391 res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
3392 &lace_size, &laces);
3397 if (track->audio.samplerate == 8000) {
3398 // If this is needed for more codecs, then add them here
3399 if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
3400 if (track->audio.samplerate != st->codecpar->sample_rate || !st->codecpar->frame_size)
3401 trust_default_duration = 0;
3405 if (!block_duration && trust_default_duration)
3406 block_duration = track->default_duration * laces / matroska->time_scale;
3408 if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
3409 track->end_timecode =
3410 FFMAX(track->end_timecode, timecode + block_duration);
3412 for (n = 0; n < laces; n++) {
3413 int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
3415 if (lace_size[n] > size) {
3416 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
3420 if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
3421 st->codecpar->codec_id == AV_CODEC_ID_COOK ||
3422 st->codecpar->codec_id == AV_CODEC_ID_SIPR ||
3423 st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) &&
3424 st->codecpar->block_align && track->audio.sub_packet_size) {
3425 res = matroska_parse_rm_audio(matroska, track, st, data,
3431 } else if (st->codecpar->codec_id == AV_CODEC_ID_WEBVTT) {
3432 res = matroska_parse_webvtt(matroska, track, st,
3434 timecode, lace_duration,
3439 res = matroska_parse_frame(matroska, track, st, buf, data, lace_size[n],
3440 timecode, lace_duration, pos,
3441 !n ? is_keyframe : 0,
3442 additional, additional_id, additional_size,
3448 if (timecode != AV_NOPTS_VALUE)
3449 timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
3450 data += lace_size[n];
3451 size -= lace_size[n];
3459 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
3461 EbmlList *blocks_list;
3462 MatroskaBlock *blocks;
3464 res = ebml_parse(matroska,
3465 matroska_cluster_incremental_parsing,
3466 &matroska->current_cluster);
3469 if (matroska->current_cluster_pos)
3470 ebml_level_end(matroska);
3471 ebml_free(matroska_cluster, &matroska->current_cluster);
3472 memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
3473 matroska->current_cluster_num_blocks = 0;
3474 matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
3475 /* sizeof the ID which was already read */
3476 if (matroska->current_id)
3477 matroska->current_cluster_pos -= 4;
3478 res = ebml_parse(matroska,
3479 matroska_clusters_incremental,
3480 &matroska->current_cluster);
3481 /* Try parsing the block again. */
3483 res = ebml_parse(matroska,
3484 matroska_cluster_incremental_parsing,
3485 &matroska->current_cluster);
3489 matroska->current_cluster_num_blocks <
3490 matroska->current_cluster.blocks.nb_elem) {
3491 blocks_list = &matroska->current_cluster.blocks;
3492 blocks = blocks_list->elem;
3494 matroska->current_cluster_num_blocks = blocks_list->nb_elem;
3495 i = blocks_list->nb_elem - 1;
3496 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
3497 int is_keyframe = blocks[i].non_simple ? blocks[i].reference == INT64_MIN : -1;
3498 uint8_t* additional = blocks[i].additional.size > 0 ?
3499 blocks[i].additional.data : NULL;
3500 if (!blocks[i].non_simple)
3501 blocks[i].duration = 0;
3502 res = matroska_parse_block(matroska, blocks[i].bin.buf, blocks[i].bin.data,
3503 blocks[i].bin.size, blocks[i].bin.pos,
3504 matroska->current_cluster.timecode,
3505 blocks[i].duration, is_keyframe,
3506 additional, blocks[i].additional_id,
3507 blocks[i].additional.size,
3508 matroska->current_cluster_pos,
3509 blocks[i].discard_padding);
3516 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
3518 MatroskaCluster cluster = { 0 };
3519 EbmlList *blocks_list;
3520 MatroskaBlock *blocks;
3524 if (!matroska->contains_ssa)
3525 return matroska_parse_cluster_incremental(matroska);
3526 pos = avio_tell(matroska->ctx->pb);
3527 if (matroska->current_id)
3528 pos -= 4; /* sizeof the ID which was already read */
3529 res = ebml_parse(matroska, matroska_clusters, &cluster);
3530 blocks_list = &cluster.blocks;
3531 blocks = blocks_list->elem;
3532 for (i = 0; i < blocks_list->nb_elem; i++)
3533 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
3534 int is_keyframe = blocks[i].non_simple ? blocks[i].reference == INT64_MIN : -1;
3535 res = matroska_parse_block(matroska, blocks[i].bin.buf, blocks[i].bin.data,
3536 blocks[i].bin.size, blocks[i].bin.pos,
3537 cluster.timecode, blocks[i].duration,
3538 is_keyframe, NULL, 0, 0, pos,
3539 blocks[i].discard_padding);
3541 ebml_free(matroska_cluster, &cluster);
3545 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
3547 MatroskaDemuxContext *matroska = s->priv_data;
3550 while (matroska_deliver_packet(matroska, pkt)) {
3551 int64_t pos = avio_tell(matroska->ctx->pb);
3553 return (ret < 0) ? ret : AVERROR_EOF;
3554 if (matroska_parse_cluster(matroska) < 0)
3555 ret = matroska_resync(matroska, pos);
3561 static int matroska_read_seek(AVFormatContext *s, int stream_index,
3562 int64_t timestamp, int flags)
3564 MatroskaDemuxContext *matroska = s->priv_data;
3565 MatroskaTrack *tracks = NULL;
3566 AVStream *st = s->streams[stream_index];
3567 int i, index, index_min;
3569 /* Parse the CUES now since we need the index data to seek. */
3570 if (matroska->cues_parsing_deferred > 0) {
3571 matroska->cues_parsing_deferred = 0;
3572 matroska_parse_cues(matroska);
3575 if (!st->nb_index_entries)
3577 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
3579 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
3580 avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
3582 matroska->current_id = 0;
3583 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
3584 matroska_clear_queue(matroska);
3585 if (matroska_parse_cluster(matroska) < 0)
3590 matroska_clear_queue(matroska);
3591 if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
3595 tracks = matroska->tracks.elem;
3596 for (i = 0; i < matroska->tracks.nb_elem; i++) {
3597 tracks[i].audio.pkt_cnt = 0;
3598 tracks[i].audio.sub_packet_cnt = 0;
3599 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
3600 tracks[i].end_timecode = 0;
3603 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
3604 matroska->current_id = 0;
3605 if (flags & AVSEEK_FLAG_ANY) {
3606 st->skip_to_keyframe = 0;
3607 matroska->skip_to_timecode = timestamp;
3609 st->skip_to_keyframe = 1;
3610 matroska->skip_to_timecode = st->index_entries[index].timestamp;
3612 matroska->skip_to_keyframe = 1;
3614 matroska->num_levels = 0;
3615 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
3618 // slightly hackish but allows proper fallback to
3619 // the generic seeking code.
3620 matroska_clear_queue(matroska);
3621 matroska->current_id = 0;
3622 st->skip_to_keyframe =
3623 matroska->skip_to_keyframe = 0;
3625 matroska->num_levels = 0;
3629 static int matroska_read_close(AVFormatContext *s)
3631 MatroskaDemuxContext *matroska = s->priv_data;
3632 MatroskaTrack *tracks = matroska->tracks.elem;
3635 matroska_clear_queue(matroska);
3637 for (n = 0; n < matroska->tracks.nb_elem; n++)
3638 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
3639 av_freep(&tracks[n].audio.buf);
3640 ebml_free(matroska_cluster, &matroska->current_cluster);
3641 ebml_free(matroska_segment, matroska);
3647 int64_t start_time_ns;
3648 int64_t end_time_ns;
3649 int64_t start_offset;
3653 /* This function searches all the Cues and returns the CueDesc corresponding to
3654 * the timestamp ts. Returned CueDesc will be such that start_time_ns <= ts <
3655 * end_time_ns. All 4 fields will be set to -1 if ts >= file's duration.
3657 static CueDesc get_cue_desc(AVFormatContext *s, int64_t ts, int64_t cues_start) {
3658 MatroskaDemuxContext *matroska = s->priv_data;
3661 int nb_index_entries = s->streams[0]->nb_index_entries;
3662 AVIndexEntry *index_entries = s->streams[0]->index_entries;
3663 if (ts >= matroska->duration * matroska->time_scale) return (CueDesc) {-1, -1, -1, -1};
3664 for (i = 1; i < nb_index_entries; i++) {
3665 if (index_entries[i - 1].timestamp * matroska->time_scale <= ts &&
3666 index_entries[i].timestamp * matroska->time_scale > ts) {
3671 cue_desc.start_time_ns = index_entries[i].timestamp * matroska->time_scale;
3672 cue_desc.start_offset = index_entries[i].pos - matroska->segment_start;
3673 if (i != nb_index_entries - 1) {
3674 cue_desc.end_time_ns = index_entries[i + 1].timestamp * matroska->time_scale;
3675 cue_desc.end_offset = index_entries[i + 1].pos - matroska->segment_start;
3677 cue_desc.end_time_ns = matroska->duration * matroska->time_scale;
3678 // FIXME: this needs special handling for files where Cues appear
3679 // before Clusters. the current logic assumes Cues appear after
3681 cue_desc.end_offset = cues_start - matroska->segment_start;
3686 static int webm_clusters_start_with_keyframe(AVFormatContext *s)
3688 MatroskaDemuxContext *matroska = s->priv_data;
3689 int64_t cluster_pos, before_pos;
3691 if (s->streams[0]->nb_index_entries <= 0) return 0;
3692 // seek to the first cluster using cues.
3693 index = av_index_search_timestamp(s->streams[0], 0, 0);
3694 if (index < 0) return 0;
3695 cluster_pos = s->streams[0]->index_entries[index].pos;
3696 before_pos = avio_tell(s->pb);
3698 int64_t cluster_id = 0, cluster_length = 0;
3700 avio_seek(s->pb, cluster_pos, SEEK_SET);
3701 // read cluster id and length
3702 ebml_read_num(matroska, matroska->ctx->pb, 4, &cluster_id);
3703 ebml_read_length(matroska, matroska->ctx->pb, &cluster_length);
3704 if (cluster_id != 0xF43B675) { // done with all clusters
3707 avio_seek(s->pb, cluster_pos, SEEK_SET);
3708 matroska->current_id = 0;
3709 matroska_clear_queue(matroska);
3710 if (matroska_parse_cluster(matroska) < 0 ||
3714 pkt = &matroska->queue->pkt;
3715 cluster_pos += cluster_length + 12; // 12 is the offset of the cluster id and length.
3716 if (!(pkt->flags & AV_PKT_FLAG_KEY)) {
3721 avio_seek(s->pb, before_pos, SEEK_SET);
3725 static int buffer_size_after_time_downloaded(int64_t time_ns, double search_sec, int64_t bps,
3726 double min_buffer, double* buffer,
3727 double* sec_to_download, AVFormatContext *s,
3730 double nano_seconds_per_second = 1000000000.0;
3731 double time_sec = time_ns / nano_seconds_per_second;
3733 int64_t time_to_search_ns = (int64_t)(search_sec * nano_seconds_per_second);
3734 int64_t end_time_ns = time_ns + time_to_search_ns;
3735 double sec_downloaded = 0.0;
3736 CueDesc desc_curr = get_cue_desc(s, time_ns, cues_start);
3737 if (desc_curr.start_time_ns == -1)
3739 *sec_to_download = 0.0;
3741 // Check for non cue start time.
3742 if (time_ns > desc_curr.start_time_ns) {
3743 int64_t cue_nano = desc_curr.end_time_ns - time_ns;
3744 double percent = (double)(cue_nano) / (desc_curr.end_time_ns - desc_curr.start_time_ns);
3745 double cueBytes = (desc_curr.end_offset - desc_curr.start_offset) * percent;
3746 double timeToDownload = (cueBytes * 8.0) / bps;
3748 sec_downloaded += (cue_nano / nano_seconds_per_second) - timeToDownload;
3749 *sec_to_download += timeToDownload;
3751 // Check if the search ends within the first cue.
3752 if (desc_curr.end_time_ns >= end_time_ns) {
3753 double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
3754 double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
3755 sec_downloaded = percent_to_sub * sec_downloaded;
3756 *sec_to_download = percent_to_sub * *sec_to_download;
3759 if ((sec_downloaded + *buffer) <= min_buffer) {
3763 // Get the next Cue.
3764 desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
3767 while (desc_curr.start_time_ns != -1) {
3768 int64_t desc_bytes = desc_curr.end_offset - desc_curr.start_offset;
3769 int64_t desc_ns = desc_curr.end_time_ns - desc_curr.start_time_ns;
3770 double desc_sec = desc_ns / nano_seconds_per_second;
3771 double bits = (desc_bytes * 8.0);
3772 double time_to_download = bits / bps;
3774 sec_downloaded += desc_sec - time_to_download;
3775 *sec_to_download += time_to_download;
3777 if (desc_curr.end_time_ns >= end_time_ns) {
3778 double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
3779 double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
3780 sec_downloaded = percent_to_sub * sec_downloaded;
3781 *sec_to_download = percent_to_sub * *sec_to_download;
3783 if ((sec_downloaded + *buffer) <= min_buffer)
3788 if ((sec_downloaded + *buffer) <= min_buffer) {
3793 desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
3795 *buffer = *buffer + sec_downloaded;
3799 /* This function computes the bandwidth of the WebM file with the help of
3800 * buffer_size_after_time_downloaded() function. Both of these functions are
3801 * adapted from WebM Tools project and are adapted to work with FFmpeg's
3802 * Matroska parsing mechanism.
3804 * Returns the bandwidth of the file on success; -1 on error.
3806 static int64_t webm_dash_manifest_compute_bandwidth(AVFormatContext *s, int64_t cues_start)
3808 MatroskaDemuxContext *matroska = s->priv_data;
3809 AVStream *st = s->streams[0];
3810 double bandwidth = 0.0;
3813 for (i = 0; i < st->nb_index_entries; i++) {
3814 int64_t prebuffer_ns = 1000000000;
3815 int64_t time_ns = st->index_entries[i].timestamp * matroska->time_scale;
3816 double nano_seconds_per_second = 1000000000.0;
3817 int64_t prebuffered_ns = time_ns + prebuffer_ns;
3818 double prebuffer_bytes = 0.0;
3819 int64_t temp_prebuffer_ns = prebuffer_ns;
3820 int64_t pre_bytes, pre_ns;
3821 double pre_sec, prebuffer, bits_per_second;
3822 CueDesc desc_beg = get_cue_desc(s, time_ns, cues_start);
3824 // Start with the first Cue.
3825 CueDesc desc_end = desc_beg;
3827 // Figure out how much data we have downloaded for the prebuffer. This will
3828 // be used later to adjust the bits per sample to try.
3829 while (desc_end.start_time_ns != -1 && desc_end.end_time_ns < prebuffered_ns) {
3830 // Prebuffered the entire Cue.
3831 prebuffer_bytes += desc_end.end_offset - desc_end.start_offset;
3832 temp_prebuffer_ns -= desc_end.end_time_ns - desc_end.start_time_ns;
3833 desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
3835 if (desc_end.start_time_ns == -1) {
3836 // The prebuffer is larger than the duration.
3837 if (matroska->duration * matroska->time_scale >= prebuffered_ns)
3839 bits_per_second = 0.0;
3841 // The prebuffer ends in the last Cue. Estimate how much data was
3843 pre_bytes = desc_end.end_offset - desc_end.start_offset;
3844 pre_ns = desc_end.end_time_ns - desc_end.start_time_ns;
3845 pre_sec = pre_ns / nano_seconds_per_second;
3847 pre_bytes * ((temp_prebuffer_ns / nano_seconds_per_second) / pre_sec);
3849 prebuffer = prebuffer_ns / nano_seconds_per_second;
3851 // Set this to 0.0 in case our prebuffer buffers the entire video.
3852 bits_per_second = 0.0;
3854 int64_t desc_bytes = desc_end.end_offset - desc_beg.start_offset;
3855 int64_t desc_ns = desc_end.end_time_ns - desc_beg.start_time_ns;
3856 double desc_sec = desc_ns / nano_seconds_per_second;
3857 double calc_bits_per_second = (desc_bytes * 8) / desc_sec;
3859 // Drop the bps by the percentage of bytes buffered.
3860 double percent = (desc_bytes - prebuffer_bytes) / desc_bytes;
3861 double mod_bits_per_second = calc_bits_per_second * percent;
3863 if (prebuffer < desc_sec) {
3865 (double)(matroska->duration * matroska->time_scale) / nano_seconds_per_second;
3867 // Add 1 so the bits per second should be a little bit greater than file
3869 int64_t bps = (int64_t)(mod_bits_per_second) + 1;
3870 const double min_buffer = 0.0;
3871 double buffer = prebuffer;
3872 double sec_to_download = 0.0;
3874 int rv = buffer_size_after_time_downloaded(prebuffered_ns, search_sec, bps,
3875 min_buffer, &buffer, &sec_to_download,
3879 } else if (rv == 0) {
3880 bits_per_second = (double)(bps);
3885 desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
3886 } while (desc_end.start_time_ns != -1);
3888 if (bandwidth < bits_per_second) bandwidth = bits_per_second;
3890 return (int64_t)bandwidth;
3893 static int webm_dash_manifest_cues(AVFormatContext *s, int64_t init_range)
3895 MatroskaDemuxContext *matroska = s->priv_data;
3896 EbmlList *seekhead_list = &matroska->seekhead;
3897 MatroskaSeekhead *seekhead = seekhead_list->elem;
3899 int64_t cues_start = -1, cues_end = -1, before_pos, bandwidth;
3903 // determine cues start and end positions
3904 for (i = 0; i < seekhead_list->nb_elem; i++)
3905 if (seekhead[i].id == MATROSKA_ID_CUES)
3908 if (i >= seekhead_list->nb_elem) return -1;
3910 before_pos = avio_tell(matroska->ctx->pb);
3911 cues_start = seekhead[i].pos + matroska->segment_start;
3912 if (avio_seek(matroska->ctx->pb, cues_start, SEEK_SET) == cues_start) {
3913 // cues_end is computed as cues_start + cues_length + length of the
3914 // Cues element ID + EBML length of the Cues element. cues_end is
3915 // inclusive and the above sum is reduced by 1.
3916 uint64_t cues_length = 0, cues_id = 0, bytes_read = 0;
3917 bytes_read += ebml_read_num(matroska, matroska->ctx->pb, 4, &cues_id);
3918 bytes_read += ebml_read_length(matroska, matroska->ctx->pb, &cues_length);
3919 cues_end = cues_start + cues_length + bytes_read - 1;
3921 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
3922 if (cues_start == -1 || cues_end == -1) return -1;
3925 matroska_parse_cues(matroska);
3928 av_dict_set_int(&s->streams[0]->metadata, CUES_START, cues_start, 0);
3931 av_dict_set_int(&s->streams[0]->metadata, CUES_END, cues_end, 0);
3933 // if the file has cues at the start, fix up the init range so tht
3934 // it does not include it
3935 if (cues_start <= init_range)
3936 av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, cues_start - 1, 0);
3939 bandwidth = webm_dash_manifest_compute_bandwidth(s, cues_start);
3940 if (bandwidth < 0) return -1;
3941 av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH, bandwidth, 0);
3943 // check if all clusters start with key frames
3944 av_dict_set_int(&s->streams[0]->metadata, CLUSTER_KEYFRAME, webm_clusters_start_with_keyframe(s), 0);
3946 // store cue point timestamps as a comma separated list for checking subsegment alignment in
3947 // the muxer. assumes that each timestamp cannot be more than 20 characters long.
3948 buf = av_malloc_array(s->streams[0]->nb_index_entries, 20);
3949 if (!buf) return -1;
3951 for (i = 0; i < s->streams[0]->nb_index_entries; i++) {
3952 int ret = snprintf(buf + end, 20,
3953 "%" PRId64"%s", s->streams[0]->index_entries[i].timestamp,
3954 i != s->streams[0]->nb_index_entries - 1 ? "," : "");
3955 if (ret <= 0 || (ret == 20 && i == s->streams[0]->nb_index_entries - 1)) {
3956 av_log(s, AV_LOG_ERROR, "timestamp too long.\n");
3958 return AVERROR_INVALIDDATA;
3962 av_dict_set(&s->streams[0]->metadata, CUE_TIMESTAMPS, buf, 0);
3968 static int webm_dash_manifest_read_header(AVFormatContext *s)
3971 int ret = matroska_read_header(s);
3973 MatroskaTrack *tracks;
3974 MatroskaDemuxContext *matroska = s->priv_data;
3976 av_log(s, AV_LOG_ERROR, "Failed to read file headers\n");
3979 if (!s->nb_streams) {
3980 matroska_read_close(s);
3981 av_log(s, AV_LOG_ERROR, "No streams found\n");
3982 return AVERROR_INVALIDDATA;
3985 if (!matroska->is_live) {
3986 buf = av_asprintf("%g", matroska->duration);
3987 if (!buf) return AVERROR(ENOMEM);
3988 av_dict_set(&s->streams[0]->metadata, DURATION, buf, 0);
3991 // initialization range
3992 // 5 is the offset of Cluster ID.
3993 init_range = avio_tell(s->pb) - 5;
3994 av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, init_range, 0);
3997 // basename of the file
3998 buf = strrchr(s->url, '/');
3999 av_dict_set(&s->streams[0]->metadata, FILENAME, buf ? ++buf : s->url, 0);
4002 tracks = matroska->tracks.elem;
4003 av_dict_set_int(&s->streams[0]->metadata, TRACK_NUMBER, tracks[0].num, 0);
4005 // parse the cues and populate Cue related fields
4006 if (!matroska->is_live) {
4007 ret = webm_dash_manifest_cues(s, init_range);
4009 av_log(s, AV_LOG_ERROR, "Error parsing Cues\n");
4014 // use the bandwidth from the command line if it was provided
4015 if (matroska->bandwidth > 0) {
4016 av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH,
4017 matroska->bandwidth, 0);
4022 static int webm_dash_manifest_read_packet(AVFormatContext *s, AVPacket *pkt)
4027 #define OFFSET(x) offsetof(MatroskaDemuxContext, x)
4028 static const AVOption options[] = {
4029 { "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 },
4030 { "bandwidth", "bandwidth of this stream to be specified in the DASH manifest.", OFFSET(bandwidth), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
4034 static const AVClass webm_dash_class = {
4035 .class_name = "WebM DASH Manifest demuxer",
4036 .item_name = av_default_item_name,
4038 .version = LIBAVUTIL_VERSION_INT,
4041 AVInputFormat ff_matroska_demuxer = {
4042 .name = "matroska,webm",
4043 .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
4044 .extensions = "mkv,mk3d,mka,mks",
4045 .priv_data_size = sizeof(MatroskaDemuxContext),
4046 .read_probe = matroska_probe,
4047 .read_header = matroska_read_header,
4048 .read_packet = matroska_read_packet,
4049 .read_close = matroska_read_close,
4050 .read_seek = matroska_read_seek,
4051 .mime_type = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
4054 AVInputFormat ff_webm_dash_manifest_demuxer = {
4055 .name = "webm_dash_manifest",
4056 .long_name = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
4057 .priv_data_size = sizeof(MatroskaDemuxContext),
4058 .read_header = webm_dash_manifest_read_header,
4059 .read_packet = webm_dash_manifest_read_packet,
4060 .read_close = matroska_read_close,
4061 .priv_class = &webm_dash_class,