FFmpeg
matroskadec.c
Go to the documentation of this file.
1 /*
2  * Matroska file demuxer
3  * Copyright (c) 2003-2008 The FFmpeg Project
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21 
22 /**
23  * @file
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/
29  */
30 
31 #include "config.h"
32 
33 #include <inttypes.h>
34 #include <stdio.h>
35 
36 #include "libavutil/avstring.h"
37 #include "libavutil/base64.h"
38 #include "libavutil/bprint.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/intfloat.h"
41 #include "libavutil/intreadwrite.h"
42 #include "libavutil/lzo.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/opt.h"
47 #include "libavutil/spherical.h"
48 
49 #include "libavcodec/bytestream.h"
50 #include "libavcodec/flac.h"
51 #include "libavcodec/mpeg4audio.h"
53 
54 #include "avformat.h"
55 #include "avio_internal.h"
56 #include "internal.h"
57 #include "isom.h"
58 #include "matroska.h"
59 #include "oggdec.h"
60 /* For ff_codec_get_id(). */
61 #include "riff.h"
62 #include "rmsipr.h"
63 
64 #if CONFIG_BZLIB
65 #include <bzlib.h>
66 #endif
67 #if CONFIG_ZLIB
68 #include <zlib.h>
69 #endif
70 
71 #include "qtpalette.h"
72 
73 #define EBML_UNKNOWN_LENGTH UINT64_MAX /* EBML unknown length, in uint64_t */
74 #define NEEDS_CHECKING 2 /* Indicates that some error checks
75  * still need to be performed */
76 #define LEVEL_ENDED 3 /* return value of ebml_parse when the
77  * syntax level used for parsing ended. */
78 #define SKIP_THRESHOLD 1024 * 1024 /* In non-seekable mode, if more than SKIP_THRESHOLD
79  * of unkown, potentially damaged data is encountered,
80  * it is considered an error. */
81 #define UNKNOWN_EQUIV 50 * 1024 /* An unknown element is considered equivalent
82  * to this many bytes of unknown data for the
83  * SKIP_THRESHOLD check. */
84 
85 typedef enum {
91  EBML_UTF8,
92  EBML_BIN,
98 
99 typedef struct CountedElement {
100  union {
101  uint64_t u;
102  int64_t i;
103  double f;
104  char *s;
105  } el;
106  unsigned count;
108 
109 typedef const struct EbmlSyntax {
110  uint32_t id;
111  uint8_t type;
112  uint8_t is_counted;
114  size_t data_offset;
115  union {
116  int64_t i;
117  uint64_t u;
118  double f;
119  const char *s;
120  const struct EbmlSyntax *n;
121  } def;
122 } EbmlSyntax;
123 
124 typedef struct EbmlList {
125  int nb_elem;
126  unsigned int alloc_elem_size;
127  void *elem;
129 
130 typedef struct EbmlBin {
131  int size;
133  uint8_t *data;
134  int64_t pos;
136 
137 typedef struct Ebml {
138  uint64_t version;
139  uint64_t max_size;
140  uint64_t id_length;
141  char *doctype;
142  uint64_t doctype_version;
143 } Ebml;
144 
145 typedef struct MatroskaTrackCompression {
146  uint64_t algo;
149 
150 typedef struct MatroskaTrackEncryption {
151  uint64_t algo;
154 
155 typedef struct MatroskaTrackEncoding {
156  uint64_t scope;
157  uint64_t type;
161 
162 typedef struct MatroskaMasteringMeta {
163  double r_x;
164  double r_y;
165  double g_x;
166  double g_y;
167  double b_x;
168  double b_y;
169  double white_x;
170  double white_y;
174 
175 typedef struct MatroskaTrackVideoColor {
178  uint64_t chroma_sub_horz;
179  uint64_t chroma_sub_vert;
180  uint64_t cb_sub_horz;
181  uint64_t cb_sub_vert;
184  uint64_t range;
185  uint64_t transfer_characteristics;
186  uint64_t primaries;
187  uint64_t max_cll;
188  uint64_t max_fall;
191 
192 typedef struct MatroskaTrackVideoProjection {
193  uint64_t type;
194  EbmlBin private;
195  double yaw;
196  double pitch;
197  double roll;
199 
200 typedef struct MatroskaTrackVideo {
201  double frame_rate;
202  uint64_t display_width;
203  uint64_t display_height;
204  uint64_t pixel_width;
205  uint64_t pixel_height;
207  uint64_t display_unit;
208  uint64_t interlaced;
209  uint64_t field_order;
210  uint64_t stereo_mode;
211  uint64_t alpha_mode;
215 
216 typedef struct MatroskaTrackAudio {
217  double samplerate;
219  uint64_t bitdepth;
220  uint64_t channels;
221 
222  /* real audio header (extracted from extradata) */
225  int frame_size;
226  int sub_packet_size;
228  int pkt_cnt;
229  uint64_t buf_timecode;
230  uint8_t *buf;
232 
233 typedef struct MatroskaTrackPlane {
234  uint64_t uid;
235  uint64_t type;
237 
238 typedef struct MatroskaTrackOperation {
241 
242 typedef struct MatroskaTrack {
243  uint64_t num;
244  uint64_t uid;
245  uint64_t type;
246  char *name;
247  char *codec_id;
249  char *language;
250  double time_scale;
252  uint64_t flag_default;
253  uint64_t flag_forced;
254  uint64_t flag_comment;
259  uint64_t seek_preroll;
264  uint64_t codec_delay;
266 
268  int64_t end_timecode;
269  int ms_compat;
270  int needs_decoding;
272 
276 
277 typedef struct MatroskaAttachment {
278  uint64_t uid;
279  char *filename;
280  char *description;
281  char *mime;
283 
286 
287 typedef struct MatroskaChapter {
288  uint64_t start;
289  uint64_t end;
290  uint64_t uid;
291  char *title;
292 
295 
296 typedef struct MatroskaIndexPos {
297  uint64_t track;
298  uint64_t pos;
300 
301 typedef struct MatroskaIndex {
302  uint64_t time;
305 
306 typedef struct MatroskaTag {
307  char *name;
308  char *string;
309  char *lang;
310  uint64_t def;
313 
314 typedef struct MatroskaTagTarget {
315  char *type;
316  uint64_t typevalue;
317  uint64_t trackuid;
318  uint64_t chapteruid;
319  uint64_t attachuid;
321 
322 typedef struct MatroskaTags {
324  EbmlList tag;
325 } MatroskaTags;
326 
327 typedef struct MatroskaSeekhead {
328  uint64_t id;
329  uint64_t pos;
331 
332 typedef struct MatroskaLevel {
333  uint64_t start;
334  uint64_t length;
336 
337 typedef struct MatroskaBlock {
338  uint64_t duration;
340  uint64_t non_simple;
342  uint64_t additional_id;
345 } MatroskaBlock;
346 
347 typedef struct MatroskaCluster {
349  uint64_t timecode;
350  int64_t pos;
352 
353 typedef struct MatroskaLevel1Element {
354  int64_t pos;
355  uint32_t id;
356  int parsed;
358 
359 typedef struct MatroskaDemuxContext {
360  const AVClass *class;
362 
363  /* EBML stuff */
366  uint32_t current_id;
367  int64_t resync_pos;
369 
370  uint64_t time_scale;
371  double duration;
372  char *title;
373  char *muxingapp;
378  EbmlList index;
379  EbmlList tags;
381 
382  /* byte position of the segment inside the stream */
383  int64_t segment_start;
384 
385  /* This packet coincides with FFFormatContext.parse_pkt
386  * and is not owned by us. */
388 
389  /* the packet queue */
392 
393  int done;
394 
395  /* What to skip before effectively reading a packet. */
396  int skip_to_keyframe;
398 
399  /* File has a CUES element, but we defer parsing until it is needed. */
401 
402  /* Level1 elements and whether they were read yet */
404  int num_level1_elems;
405 
407 
408  /* WebM DASH Manifest live flag */
409  int is_live;
410 
411  /* Bandwidth value for WebM DASH Manifest */
412  int bandwidth;
414 
415 #define CHILD_OF(parent) { .def = { .n = parent } }
416 
417 // The following forward declarations need their size because
418 // a tentative definition with internal linkage must not be an
419 // incomplete type (6.7.2 in C90, 6.9.2 in C99).
420 // Removing the sizes breaks MSVC.
427 
428 static EbmlSyntax ebml_header[] = {
429  { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, 0, offsetof(Ebml, version), { .u = EBML_VERSION } },
430  { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, 0, offsetof(Ebml, max_size), { .u = 8 } },
431  { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, 0, offsetof(Ebml, id_length), { .u = 4 } },
432  { EBML_ID_DOCTYPE, EBML_STR, 0, 0, offsetof(Ebml, doctype), { .s = "(none)" } },
433  { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
437 };
438 
440  { EBML_ID_HEADER, EBML_NEST, 0, 0, 0, { .n = ebml_header } },
442  { 0 }
443 };
444 
445 static EbmlSyntax matroska_info[] = {
446  { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, 0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
448  { MATROSKA_ID_TITLE, EBML_UTF8, 0, 0, offsetof(MatroskaDemuxContext, title) },
450  { MATROSKA_ID_MUXINGAPP, EBML_UTF8, 0, 0, offsetof(MatroskaDemuxContext, muxingapp) },
451  { MATROSKA_ID_DATEUTC, EBML_BIN, 0, 0, offsetof(MatroskaDemuxContext, date_utc) },
454 };
455 
463  { MATROSKA_ID_VIDEOCOLOR_WHITEX, EBML_FLOAT, 0, 0, offsetof(MatroskaMasteringMeta, white_x) },
464  { MATROSKA_ID_VIDEOCOLOR_WHITEY, EBML_FLOAT, 0, 0, offsetof(MatroskaMasteringMeta, white_y) },
465  { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN, EBML_FLOAT, 1, 0, offsetof(MatroskaMasteringMeta, min_luminance) },
466  { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX, EBML_FLOAT, 0, 0, offsetof(MatroskaMasteringMeta, max_luminance) },
468 };
469 
471  { MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideoColor, matrix_coefficients), { .u = AVCOL_SPC_UNSPECIFIED } },
472  { MATROSKA_ID_VIDEOCOLORBITSPERCHANNEL, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideoColor, bits_per_channel), { .u = 0 } },
473  { MATROSKA_ID_VIDEOCOLORCHROMASUBHORZ, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_horz) },
474  { MATROSKA_ID_VIDEOCOLORCHROMASUBVERT, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_vert) },
475  { MATROSKA_ID_VIDEOCOLORCBSUBHORZ, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideoColor, cb_sub_horz) },
476  { MATROSKA_ID_VIDEOCOLORCBSUBVERT, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideoColor, cb_sub_vert) },
483  { MATROSKA_ID_VIDEOCOLORMAXFALL, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideoColor, max_fall) },
486 };
487 
491  { MATROSKA_ID_VIDEOPROJECTIONPOSEYAW, EBML_FLOAT, 0, 0, offsetof(MatroskaTrackVideoProjection, yaw), { .f = 0.0 } },
492  { MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH, EBML_FLOAT, 0, 0, offsetof(MatroskaTrackVideoProjection, pitch), { .f = 0.0 } },
493  { MATROSKA_ID_VIDEOPROJECTIONPOSEROLL, EBML_FLOAT, 0, 0, offsetof(MatroskaTrackVideoProjection, roll), { .f = 0.0 } },
495 };
496 
497 static EbmlSyntax matroska_track_video[] = {
498  { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT, 0, 0, offsetof(MatroskaTrackVideo, frame_rate) },
499  { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideo, display_width), { .u=-1 } },
500  { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideo, display_height), { .u=-1 } },
501  { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideo, pixel_width) },
502  { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideo, pixel_height) },
503  { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, 0, offsetof(MatroskaTrackVideo, color_space) },
504  { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, 0, offsetof(MatroskaTrackVideo, alpha_mode), { .u = 0 } },
517 };
518 
519 static EbmlSyntax matroska_track_audio[] = {
520  { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT, 0, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
521  { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
522  { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, 0, offsetof(MatroskaTrackAudio, bitdepth) },
523  { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, 0, offsetof(MatroskaTrackAudio, channels), { .u = 1 } },
525 };
526 
531 };
532 
534  { MATROSKA_ID_ENCODINGENCALGO, EBML_UINT, 0, 0, offsetof(MatroskaTrackEncryption,algo), {.u = 0} },
542 };
544  { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, 0, offsetof(MatroskaTrackEncoding, scope), { .u = 1 } },
545  { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, 0, offsetof(MatroskaTrackEncoding, type), { .u = 0 } },
550 };
551 
555 };
556 
557 static EbmlSyntax matroska_track_plane[] = {
561 };
562 
564  { MATROSKA_ID_TRACKPLANE, EBML_NEST, 0, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n = matroska_track_plane} },
566 };
567 
571 };
572 
573 static EbmlSyntax matroska_track[] = {
574  { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, 0, offsetof(MatroskaTrack, num) },
575  { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, 0, offsetof(MatroskaTrack, name) },
576  { MATROSKA_ID_TRACKUID, EBML_UINT, 0, 0, offsetof(MatroskaTrack, uid) },
577  { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, 0, offsetof(MatroskaTrack, type) },
578  { MATROSKA_ID_CODECID, EBML_STR, 0, 0, offsetof(MatroskaTrack, codec_id) },
579  { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, 0, offsetof(MatroskaTrack, codec_priv) },
580  { MATROSKA_ID_CODECDELAY, EBML_UINT, 0, 0, offsetof(MatroskaTrack, codec_delay), { .u = 0 } },
581  { MATROSKA_ID_TRACKLANGUAGE, EBML_STR, 0, 0, offsetof(MatroskaTrack, language), { .s = "eng" } },
582  { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, 0, offsetof(MatroskaTrack, default_duration) },
583  { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT, 0, 0, offsetof(MatroskaTrack, time_scale), { .f = 1.0 } },
584  { MATROSKA_ID_TRACKFLAGCOMMENTARY, EBML_UINT, 0, 0, offsetof(MatroskaTrack, flag_comment), { .u = 0 } },
585  { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, 0, offsetof(MatroskaTrack, flag_default), { .u = 1 } },
586  { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, 0, offsetof(MatroskaTrack, flag_forced), { .u = 0 } },
587  { MATROSKA_ID_TRACKFLAGHEARINGIMPAIRED, EBML_UINT, 0, 0, offsetof(MatroskaTrack, flag_hearingimpaired), { .u = 0 } },
588  { MATROSKA_ID_TRACKFLAGVISUALIMPAIRED, EBML_UINT, 0, 0, offsetof(MatroskaTrack, flag_visualimpaired), { .u = 0 } },
589  { MATROSKA_ID_TRACKFLAGTEXTDESCRIPTIONS, EBML_UINT, 0, 0, offsetof(MatroskaTrack, flag_textdescriptions), { .u = 0 } },
590  { MATROSKA_ID_TRACKFLAGORIGINAL, EBML_UINT, 1, 0, offsetof(MatroskaTrack, flag_original), {.u = 0 } },
592  { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, 0, offsetof(MatroskaTrack, audio), { .n = matroska_track_audio } },
593  { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, 0, offsetof(MatroskaTrack, operation), { .n = matroska_track_operation } },
595  { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, 0, offsetof(MatroskaTrack, max_block_additional_id), { .u = 0 } },
596  { MATROSKA_ID_SEEKPREROLL, EBML_UINT, 0, 0, offsetof(MatroskaTrack, seek_preroll), { .u = 0 } },
606 };
607 
608 static EbmlSyntax matroska_tracks[] = {
609  { MATROSKA_ID_TRACKENTRY, EBML_NEST, 0, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
611 };
612 
613 static EbmlSyntax matroska_attachment[] = {
614  { MATROSKA_ID_FILEUID, EBML_UINT, 0, 0, offsetof(MatroskaAttachment, uid) },
615  { MATROSKA_ID_FILENAME, EBML_UTF8, 0, 0, offsetof(MatroskaAttachment, filename) },
616  { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, 0, offsetof(MatroskaAttachment, mime) },
617  { MATROSKA_ID_FILEDATA, EBML_BIN, 0, 0, offsetof(MatroskaAttachment, bin) },
620 };
621 
622 static EbmlSyntax matroska_attachments[] = {
623  { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, 0, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
625 };
626 
628  { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, 0, offsetof(MatroskaChapter, title) },
632 };
633 
635  { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
636  { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, 0, offsetof(MatroskaChapter, end), { .u = AV_NOPTS_VALUE } },
637  { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, 0, offsetof(MatroskaChapter, uid) },
644 };
645 
646 static EbmlSyntax matroska_chapter[] = {
647  { MATROSKA_ID_CHAPTERATOM, EBML_NEST, 0, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
653 };
654 
655 static EbmlSyntax matroska_chapters[] = {
656  { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, 0, { .n = matroska_chapter } },
658 };
659 
660 static EbmlSyntax matroska_index_pos[] = {
661  { MATROSKA_ID_CUETRACK, EBML_UINT, 0, 0, offsetof(MatroskaIndexPos, track) },
667 };
668 
669 static EbmlSyntax matroska_index_entry[] = {
670  { MATROSKA_ID_CUETIME, EBML_UINT, 0, 0, offsetof(MatroskaIndex, time) },
673 };
674 
675 static EbmlSyntax matroska_index[] = {
678 };
679 
680 static EbmlSyntax matroska_simpletag[] = {
681  { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, 0, offsetof(MatroskaTag, name) },
682  { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, 0, offsetof(MatroskaTag, string) },
683  { MATROSKA_ID_TAGLANG, EBML_STR, 0, 0, offsetof(MatroskaTag, lang), { .s = "und" } },
684  { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, 0, offsetof(MatroskaTag, def) },
685  { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, 0, offsetof(MatroskaTag, def) },
686  { MATROSKA_ID_SIMPLETAG, EBML_NEST, 0, sizeof(MatroskaTag), offsetof(MatroskaTag, sub), { .n = matroska_simpletag } },
688 };
689 
690 static EbmlSyntax matroska_tagtargets[] = {
692  { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
693  { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, 0, offsetof(MatroskaTagTarget, trackuid), { .u = 0 } },
694  { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, 0, offsetof(MatroskaTagTarget, chapteruid), { .u = 0 } },
695  { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, 0, offsetof(MatroskaTagTarget, attachuid), { .u = 0 } },
697 };
698 
699 static EbmlSyntax matroska_tag[] = {
700  { MATROSKA_ID_SIMPLETAG, EBML_NEST, 0, sizeof(MatroskaTag), offsetof(MatroskaTags, tag), { .n = matroska_simpletag } },
701  { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, 0, offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
703 };
704 
705 static EbmlSyntax matroska_tags[] = {
706  { MATROSKA_ID_TAG, EBML_NEST, 0, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
708 };
709 
711  { MATROSKA_ID_SEEKID, EBML_UINT, 0, 0, offsetof(MatroskaSeekhead, id) },
712  { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
714 };
715 
716 static EbmlSyntax matroska_seekhead[] = {
717  { MATROSKA_ID_SEEKENTRY, EBML_NEST, 0, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
719 };
720 
721 static EbmlSyntax matroska_segment[] = {
723  { MATROSKA_ID_INFO, EBML_LEVEL1, 0, 0, 0, { .n = matroska_info } },
724  { MATROSKA_ID_TRACKS, EBML_LEVEL1, 0, 0, 0, { .n = matroska_tracks } },
726  { MATROSKA_ID_CHAPTERS, EBML_LEVEL1, 0, 0, 0, { .n = matroska_chapters } },
727  { MATROSKA_ID_CUES, EBML_LEVEL1, 0, 0, 0, { .n = matroska_index } },
728  { MATROSKA_ID_TAGS, EBML_LEVEL1, 0, 0, 0, { .n = matroska_tags } },
729  { MATROSKA_ID_SEEKHEAD, EBML_LEVEL1, 0, 0, 0, { .n = matroska_seekhead } },
730  { 0 } /* We don't want to go back to level 0, so don't add the parent. */
731 };
732 
733 static EbmlSyntax matroska_segments[] = {
734  { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, 0, { .n = matroska_segment } },
735  { 0 }
736 };
737 
738 static EbmlSyntax matroska_blockmore[] = {
739  { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, 0, offsetof(MatroskaBlock,additional_id), { .u = 1 } },
740  { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, 0, offsetof(MatroskaBlock,additional) },
742 };
743 
745  { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, 0, {.n = matroska_blockmore} },
747 };
748 
749 static EbmlSyntax matroska_blockgroup[] = {
750  { MATROSKA_ID_BLOCK, EBML_BIN, 0, 0, offsetof(MatroskaBlock, bin) },
753  { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, 0, offsetof(MatroskaBlock, discard_padding) },
754  { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 1, 0, offsetof(MatroskaBlock, reference) },
756  { 1, EBML_UINT, 0, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
758 };
759 
760 // The following array contains SimpleBlock and BlockGroup twice
761 // in order to reuse the other values for matroska_cluster_enter.
763  { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, 0, offsetof(MatroskaBlock, bin) },
764  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, 0, 0, 0, { .n = matroska_blockgroup } },
765  { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, 0, offsetof(MatroskaCluster, timecode) },
771 };
772 
774  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, 0, { .n = &matroska_cluster_parsing[2] } },
775  { 0 }
776 };
777 #undef CHILD_OF
778 
779 static const CodecMime mkv_image_mime_tags[] = {
780  {"image/gif" , AV_CODEC_ID_GIF},
781  {"image/jpeg" , AV_CODEC_ID_MJPEG},
782  {"image/png" , AV_CODEC_ID_PNG},
783  {"image/tiff" , AV_CODEC_ID_TIFF},
784 
785  {"" , AV_CODEC_ID_NONE}
786 };
787 
788 static const CodecMime mkv_mime_tags[] = {
789  {"text/plain" , AV_CODEC_ID_TEXT},
790  {"application/x-truetype-font", AV_CODEC_ID_TTF},
791  {"application/x-font" , AV_CODEC_ID_TTF},
792  {"application/vnd.ms-opentype", AV_CODEC_ID_OTF},
793  {"binary" , AV_CODEC_ID_BIN_DATA},
794 
795  {"" , AV_CODEC_ID_NONE}
796 };
797 
798 static const char *const matroska_doctypes[] = { "matroska", "webm" };
799 
800 /*
801  * This function prepares the status for parsing of level 1 elements.
802  */
803 static int matroska_reset_status(MatroskaDemuxContext *matroska,
804  uint32_t id, int64_t position)
805 {
806  if (position >= 0) {
807  int64_t err = avio_seek(matroska->ctx->pb, position, SEEK_SET);
808  if (err < 0)
809  return err;
810  }
811 
812  matroska->current_id = id;
813  matroska->num_levels = 1;
814  matroska->unknown_count = 0;
815  matroska->resync_pos = avio_tell(matroska->ctx->pb);
816  if (id)
817  matroska->resync_pos -= (av_log2(id) + 7) / 8;
818 
819  return 0;
820 }
821 
822 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
823 {
824  AVIOContext *pb = matroska->ctx->pb;
825  uint32_t id;
826 
827  /* Try to seek to the last position to resync from. If this doesn't work,
828  * we resync from the earliest position available: The start of the buffer. */
829  if (last_pos < avio_tell(pb) && avio_seek(pb, last_pos + 1, SEEK_SET) < 0) {
830  av_log(matroska->ctx, AV_LOG_WARNING,
831  "Seek to desired resync point failed. Seeking to "
832  "earliest point available instead.\n");
833  avio_seek(pb, FFMAX(avio_tell(pb) + (pb->buffer - pb->buf_ptr),
834  last_pos + 1), SEEK_SET);
835  }
836 
837  id = avio_rb32(pb);
838 
839  // try to find a toplevel element
840  while (!avio_feof(pb)) {
841  if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
842  id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
844  id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
845  /* Prepare the context for parsing of a level 1 element. */
846  matroska_reset_status(matroska, id, -1);
847  /* Given that we are here means that an error has occurred,
848  * so treat the segment as unknown length in order not to
849  * discard valid data that happens to be beyond the designated
850  * end of the segment. */
851  matroska->levels[0].length = EBML_UNKNOWN_LENGTH;
852  return 0;
853  }
854  id = (id << 8) | avio_r8(pb);
855  }
856 
857  matroska->done = 1;
858  return pb->error ? pb->error : AVERROR_EOF;
859 }
860 
861 /*
862  * Read: an "EBML number", which is defined as a variable-length
863  * array of bytes. The first byte indicates the length by giving a
864  * number of 0-bits followed by a one. The position of the first
865  * "one" bit inside the first byte indicates the length of this
866  * number.
867  * Returns: number of bytes read, < 0 on error
868  */
869 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
870  int max_size, uint64_t *number, int eof_forbidden)
871 {
872  int read, n = 1;
873  uint64_t total;
874  int64_t pos;
875 
876  /* The first byte tells us the length in bytes - except when it is zero. */
877  total = avio_r8(pb);
878  if (pb->eof_reached)
879  goto err;
880 
881  /* get the length of the EBML number */
882  read = 8 - ff_log2_tab[total];
883 
884  if (!total || read > max_size) {
885  pos = avio_tell(pb) - 1;
886  if (!total) {
887  av_log(matroska->ctx, AV_LOG_ERROR,
888  "0x00 at pos %"PRId64" (0x%"PRIx64") invalid as first byte "
889  "of an EBML number\n", pos, pos);
890  } else {
891  av_log(matroska->ctx, AV_LOG_ERROR,
892  "Length %d indicated by an EBML number's first byte 0x%02x "
893  "at pos %"PRId64" (0x%"PRIx64") exceeds max length %d.\n",
894  read, (uint8_t) total, pos, pos, max_size);
895  }
896  return AVERROR_INVALIDDATA;
897  }
898 
899  /* read out length */
900  total ^= 1 << ff_log2_tab[total];
901  while (n++ < read)
902  total = (total << 8) | avio_r8(pb);
903 
904  if (pb->eof_reached) {
905  eof_forbidden = 1;
906  goto err;
907  }
908 
909  *number = total;
910 
911  return read;
912 
913 err:
914  pos = avio_tell(pb);
915  if (pb->error) {
916  av_log(matroska->ctx, AV_LOG_ERROR,
917  "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
918  pos, pos);
919  return pb->error;
920  }
921  if (eof_forbidden) {
922  av_log(matroska->ctx, AV_LOG_ERROR, "File ended prematurely "
923  "at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
924  return AVERROR(EIO);
925  }
926  return AVERROR_EOF;
927 }
928 
929 /**
930  * Read a EBML length value.
931  * This needs special handling for the "unknown length" case which has multiple
932  * encodings.
933  */
934 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
935  uint64_t *number)
936 {
937  int res = ebml_read_num(matroska, pb, 8, number, 1);
938  if (res > 0 && *number + 1 == 1ULL << (7 * res))
939  *number = EBML_UNKNOWN_LENGTH;
940  return res;
941 }
942 
943 /*
944  * Read the next element as an unsigned int.
945  * Returns NEEDS_CHECKING unless size == 0.
946  */
947 static int ebml_read_uint(AVIOContext *pb, int size,
948  uint64_t default_value, uint64_t *num)
949 {
950  int n = 0;
951 
952  if (size == 0) {
953  *num = default_value;
954  return 0;
955  }
956  /* big-endian ordering; build up number */
957  *num = 0;
958  while (n++ < size)
959  *num = (*num << 8) | avio_r8(pb);
960 
961  return NEEDS_CHECKING;
962 }
963 
964 /*
965  * Read the next element as a signed int.
966  * Returns NEEDS_CHECKING unless size == 0.
967  */
968 static int ebml_read_sint(AVIOContext *pb, int size,
969  int64_t default_value, int64_t *num)
970 {
971  int n = 1;
972 
973  if (size == 0) {
974  *num = default_value;
975  return 0;
976  } else {
977  *num = sign_extend(avio_r8(pb), 8);
978 
979  /* big-endian ordering; build up number */
980  while (n++ < size)
981  *num = ((uint64_t)*num << 8) | avio_r8(pb);
982  }
983 
984  return NEEDS_CHECKING;
985 }
986 
987 /*
988  * Read the next element as a float.
989  * Returns 0 if size == 0, NEEDS_CHECKING or < 0 on obvious failure.
990  */
991 static int ebml_read_float(AVIOContext *pb, int size,
992  double default_value, double *num)
993 {
994  if (size == 0) {
995  *num = default_value;
996  return 0;
997  } else if (size == 4) {
998  *num = av_int2float(avio_rb32(pb));
999  } else if (size == 8) {
1000  *num = av_int2double(avio_rb64(pb));
1001  } else
1002  return AVERROR_INVALIDDATA;
1003 
1004  return NEEDS_CHECKING;
1006 
1007 /*
1008  * Read the next element as an ASCII string.
1009  * 0 is success, < 0 or NEEDS_CHECKING is failure.
1010  */
1011 static int ebml_read_ascii(AVIOContext *pb, int size,
1012  const char *default_value, char **str)
1013 {
1014  char *res;
1015  int ret;
1016 
1017  if (size == 0 && default_value) {
1018  res = av_strdup(default_value);
1019  if (!res)
1020  return AVERROR(ENOMEM);
1021  } else {
1022  /* EBML strings are usually not 0-terminated, so we allocate one
1023  * byte more, read the string and NUL-terminate it ourselves. */
1024  if (!(res = av_malloc(size + 1)))
1025  return AVERROR(ENOMEM);
1026  if ((ret = avio_read(pb, (uint8_t *) res, size)) != size) {
1027  av_free(res);
1028  return ret < 0 ? ret : NEEDS_CHECKING;
1029  }
1030  (res)[size] = '\0';
1031  }
1032  av_free(*str);
1033  *str = res;
1034 
1035  return 0;
1037 
1038 /*
1039  * Read the next element as binary data.
1040  * 0 is success, < 0 or NEEDS_CHECKING is failure.
1041  */
1042 static int ebml_read_binary(AVIOContext *pb, int length,
1043  int64_t pos, EbmlBin *bin)
1044 {
1045  int ret;
1046 
1048  if (ret < 0)
1049  return ret;
1050  memset(bin->buf->data + length, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1051 
1052  bin->data = bin->buf->data;
1053  bin->size = length;
1054  bin->pos = pos;
1055  if ((ret = avio_read(pb, bin->data, length)) != length) {
1056  av_buffer_unref(&bin->buf);
1057  bin->data = NULL;
1058  bin->size = 0;
1059  return ret < 0 ? ret : NEEDS_CHECKING;
1060  }
1061 
1062  return 0;
1063 }
1065 /*
1066  * Read the next element, but only the header. The contents
1067  * are supposed to be sub-elements which can be read separately.
1068  * 0 is success, < 0 is failure.
1069  */
1070 static int ebml_read_master(MatroskaDemuxContext *matroska,
1071  uint64_t length, int64_t pos)
1072 {
1074 
1075  if (matroska->num_levels >= EBML_MAX_DEPTH) {
1076  av_log(matroska->ctx, AV_LOG_ERROR,
1077  "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
1078  return AVERROR(ENOSYS);
1079  }
1080 
1081  level = &matroska->levels[matroska->num_levels++];
1082  level->start = pos;
1083  level->length = length;
1084 
1085  return 0;
1087 
1088 /*
1089  * Read a signed "EBML number"
1090  * Return: number of bytes processed, < 0 on error
1091  */
1092 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
1093  AVIOContext *pb, int64_t *num)
1094 {
1095  uint64_t unum;
1096  int res;
1097 
1098  /* read as unsigned number first */
1099  if ((res = ebml_read_num(matroska, pb, 8, &unum, 1)) < 0)
1100  return res;
1101 
1102  /* make signed (weird way) */
1103  *num = unum - ((1LL << (7 * res - 1)) - 1);
1104 
1105  return res;
1106 }
1107 
1108 static int ebml_parse(MatroskaDemuxContext *matroska,
1109  EbmlSyntax *syntax, void *data);
1110 
1111 static EbmlSyntax *ebml_parse_id(EbmlSyntax *syntax, uint32_t id)
1112 {
1113  int i;
1114 
1115  // Whoever touches this should be aware of the duplication
1116  // existing in matroska_cluster_parsing.
1117  for (i = 0; syntax[i].id; i++)
1118  if (id == syntax[i].id)
1119  break;
1120 
1121  return &syntax[i];
1122 }
1123 
1124 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1125  void *data)
1126 {
1127  int res;
1128 
1129  if (data) {
1130  for (int i = 0; syntax[i].id; i++) {
1131  void *dst = (char *)data + syntax[i].data_offset;
1132  switch (syntax[i].type) {
1133  case EBML_UINT:
1134  *(uint64_t *)dst = syntax[i].def.u;
1135  break;
1136  case EBML_SINT:
1137  *(int64_t *) dst = syntax[i].def.i;
1138  break;
1139  case EBML_FLOAT:
1140  *(double *) dst = syntax[i].def.f;
1141  break;
1142  case EBML_STR:
1143  case EBML_UTF8:
1144  // the default may be NULL
1145  if (syntax[i].def.s) {
1146  *(char**)dst = av_strdup(syntax[i].def.s);
1147  if (!*(char**)dst)
1148  return AVERROR(ENOMEM);
1149  }
1150  break;
1151  }
1152  }
1153 
1154  if (!matroska->levels[matroska->num_levels - 1].length) {
1155  matroska->num_levels--;
1156  return 0;
1157  }
1158  }
1159 
1160  do {
1161  res = ebml_parse(matroska, syntax, data);
1162  } while (!res);
1163 
1164  return res == LEVEL_ENDED ? 0 : res;
1165 }
1166 
1167 static int is_ebml_id_valid(uint32_t id)
1168 {
1169  // Due to endian nonsense in Matroska, the highest byte with any bits set
1170  // will contain the leading length bit. This bit in turn identifies the
1171  // total byte length of the element by its position within the byte.
1172  unsigned int bits = av_log2(id);
1173  return id && (bits + 7) / 8 == (8 - bits % 8);
1175 
1176 /*
1177  * Allocate and return the entry for the level1 element with the given ID. If
1178  * an entry already exists, return the existing entry.
1179  */
1181  uint32_t id, int64_t pos)
1182 {
1183  int i;
1184  MatroskaLevel1Element *elem;
1185 
1186  if (!is_ebml_id_valid(id))
1187  return NULL;
1188 
1189  // Some files link to all clusters; useless.
1190  if (id == MATROSKA_ID_CLUSTER)
1191  return NULL;
1192 
1193  // There can be multiple SeekHeads and Tags.
1194  for (i = 0; i < matroska->num_level1_elems; i++) {
1195  if (matroska->level1_elems[i].id == id) {
1196  if (matroska->level1_elems[i].pos == pos ||
1197  id != MATROSKA_ID_SEEKHEAD && id != MATROSKA_ID_TAGS)
1198  return &matroska->level1_elems[i];
1199  }
1200  }
1201 
1202  // Only a completely broken file would have more elements.
1203  if (matroska->num_level1_elems >= FF_ARRAY_ELEMS(matroska->level1_elems)) {
1204  av_log(matroska->ctx, AV_LOG_ERROR, "Too many level1 elements.\n");
1205  return NULL;
1206  }
1207 
1208  elem = &matroska->level1_elems[matroska->num_level1_elems++];
1209  *elem = (MatroskaLevel1Element){.id = id};
1210 
1211  return elem;
1212 }
1213 
1214 static int ebml_parse(MatroskaDemuxContext *matroska,
1215  EbmlSyntax *syntax, void *data)
1216 {
1217  static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
1218  // Forbid unknown-length EBML_NONE elements.
1220  [EBML_UINT] = 8,
1221  [EBML_SINT] = 8,
1222  [EBML_FLOAT] = 8,
1223  // max. 16 MB for strings
1224  [EBML_STR] = 0x1000000,
1225  [EBML_UTF8] = 0x1000000,
1226  // max. 256 MB for binary data
1227  [EBML_BIN] = 0x10000000,
1228  // no limits for anything else
1229  };
1230  AVIOContext *pb = matroska->ctx->pb;
1231  uint32_t id;
1232  uint64_t length;
1233  int64_t pos = avio_tell(pb), pos_alt;
1234  int res, update_pos = 1, level_check;
1235  MatroskaLevel1Element *level1_elem;
1236  MatroskaLevel *level = matroska->num_levels ? &matroska->levels[matroska->num_levels - 1] : NULL;
1237 
1238  if (!matroska->current_id) {
1239  uint64_t id;
1240  res = ebml_read_num(matroska, pb, 4, &id, 0);
1241  if (res < 0) {
1242  if (pb->eof_reached && res == AVERROR_EOF) {
1243  if (matroska->is_live)
1244  // in live mode, finish parsing if EOF is reached.
1245  return 1;
1246  if (level && pos == avio_tell(pb)) {
1247  if (level->length == EBML_UNKNOWN_LENGTH) {
1248  // Unknown-length levels automatically end at EOF.
1249  matroska->num_levels--;
1250  return LEVEL_ENDED;
1251  } else {
1252  av_log(matroska->ctx, AV_LOG_ERROR, "File ended prematurely "
1253  "at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
1254  }
1255  }
1256  }
1257  return res;
1258  }
1259  matroska->current_id = id | 1 << 7 * res;
1260  pos_alt = pos + res;
1261  } else {
1262  pos_alt = pos;
1263  pos -= (av_log2(matroska->current_id) + 7) / 8;
1264  }
1265 
1266  id = matroska->current_id;
1267 
1268  syntax = ebml_parse_id(syntax, id);
1269  if (!syntax->id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
1270  if (level && level->length == EBML_UNKNOWN_LENGTH) {
1271  // Unknown-length levels end when an element from an upper level
1272  // in the hierarchy is encountered.
1273  while (syntax->def.n) {
1274  syntax = ebml_parse_id(syntax->def.n, id);
1275  if (syntax->id) {
1276  matroska->num_levels--;
1277  return LEVEL_ENDED;
1278  }
1279  };
1280  }
1281 
1282  av_log(matroska->ctx, AV_LOG_DEBUG, "Unknown entry 0x%"PRIX32" at pos. "
1283  "%"PRId64"\n", id, pos);
1284  update_pos = 0; /* Don't update resync_pos as an error might have happened. */
1285  }
1286 
1287  if (data) {
1288  data = (char *) data + syntax->data_offset;
1289  if (syntax->list_elem_size) {
1290  EbmlList *list = data;
1291  void *newelem;
1292 
1293  if ((unsigned)list->nb_elem + 1 >= UINT_MAX / syntax->list_elem_size)
1294  return AVERROR(ENOMEM);
1295  newelem = av_fast_realloc(list->elem,
1296  &list->alloc_elem_size,
1297  (list->nb_elem + 1) * syntax->list_elem_size);
1298  if (!newelem)
1299  return AVERROR(ENOMEM);
1300  list->elem = newelem;
1301  data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
1302  memset(data, 0, syntax->list_elem_size);
1303  list->nb_elem++;
1304  }
1305  }
1306 
1307  if (syntax->type != EBML_STOP) {
1308  matroska->current_id = 0;
1309  if ((res = ebml_read_length(matroska, pb, &length)) < 0)
1310  return res;
1311 
1312  pos_alt += res;
1313 
1314  if (matroska->num_levels > 0) {
1315  if (length != EBML_UNKNOWN_LENGTH &&
1316  level->length != EBML_UNKNOWN_LENGTH) {
1317  uint64_t elem_end = pos_alt + length,
1318  level_end = level->start + level->length;
1319 
1320  if (elem_end < level_end) {
1321  level_check = 0;
1322  } else if (elem_end == level_end) {
1323  level_check = LEVEL_ENDED;
1324  } else {
1325  av_log(matroska->ctx, AV_LOG_ERROR,
1326  "Element at 0x%"PRIx64" ending at 0x%"PRIx64" exceeds "
1327  "containing master element ending at 0x%"PRIx64"\n",
1328  pos, elem_end, level_end);
1329  return AVERROR_INVALIDDATA;
1330  }
1331  } else if (length != EBML_UNKNOWN_LENGTH) {
1332  level_check = 0;
1333  } else if (level->length != EBML_UNKNOWN_LENGTH) {
1334  av_log(matroska->ctx, AV_LOG_ERROR, "Unknown-sized element "
1335  "at 0x%"PRIx64" inside parent with finite size\n", pos);
1336  return AVERROR_INVALIDDATA;
1337  } else {
1338  level_check = 0;
1339  if (id != MATROSKA_ID_CLUSTER && (syntax->type == EBML_LEVEL1
1340  || syntax->type == EBML_NEST)) {
1341  // According to the current specifications only clusters and
1342  // segments are allowed to be unknown-length. We also accept
1343  // other unknown-length master elements.
1344  av_log(matroska->ctx, AV_LOG_WARNING,
1345  "Found unknown-length element 0x%"PRIX32" other than "
1346  "a cluster at 0x%"PRIx64". Spec-incompliant, but "
1347  "parsing will nevertheless be attempted.\n", id, pos);
1348  update_pos = -1;
1349  }
1350  }
1351  } else
1352  level_check = 0;
1353 
1354  if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
1355  if (length != EBML_UNKNOWN_LENGTH) {
1356  av_log(matroska->ctx, AV_LOG_ERROR,
1357  "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for element "
1358  "with ID 0x%"PRIX32" at 0x%"PRIx64"\n",
1359  length, max_lengths[syntax->type], id, pos);
1360  } else if (syntax->type != EBML_NONE) {
1361  av_log(matroska->ctx, AV_LOG_ERROR,
1362  "Element with ID 0x%"PRIX32" at pos. 0x%"PRIx64" has "
1363  "unknown length, yet the length of an element of its "
1364  "type must be known.\n", id, pos);
1365  } else {
1366  av_log(matroska->ctx, AV_LOG_ERROR,
1367  "Found unknown-length element with ID 0x%"PRIX32" at "
1368  "pos. 0x%"PRIx64" for which no syntax for parsing is "
1369  "available.\n", id, pos);
1370  }
1371  return AVERROR_INVALIDDATA;
1372  }
1373 
1374  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) {
1375  // Loosing sync will likely manifest itself as encountering unknown
1376  // elements which are not reliably distinguishable from elements
1377  // belonging to future extensions of the format.
1378  // We use a heuristic to detect such situations: If the current
1379  // element is not expected at the current syntax level and there
1380  // were only a few unknown elements in a row, then the element is
1381  // skipped or considered defective based upon the length of the
1382  // current element (i.e. how much would be skipped); if there were
1383  // more than a few skipped elements in a row and skipping the current
1384  // element would lead us more than SKIP_THRESHOLD away from the last
1385  // known good position, then it is inferred that an error occurred.
1386  // The dependency on the number of unknown elements in a row exists
1387  // because the distance to the last known good position is
1388  // automatically big if the last parsed element was big.
1389  // In both cases, each unknown element is considered equivalent to
1390  // UNKNOWN_EQUIV of skipped bytes for the check.
1391  // The whole check is only done for non-seekable output, because
1392  // in this situation skipped data can't simply be rechecked later.
1393  // This is especially important when using unkown length elements
1394  // as the check for whether a child exceeds its containing master
1395  // element is not effective in this situation.
1396  if (update_pos) {
1397  matroska->unknown_count = 0;
1398  } else {
1399  int64_t dist = length + UNKNOWN_EQUIV * matroska->unknown_count++;
1400 
1401  if (matroska->unknown_count > 3)
1402  dist += pos_alt - matroska->resync_pos;
1403 
1404  if (dist > SKIP_THRESHOLD) {
1405  av_log(matroska->ctx, AV_LOG_ERROR,
1406  "Unknown element %"PRIX32" at pos. 0x%"PRIx64" with "
1407  "length 0x%"PRIx64" considered as invalid data. Last "
1408  "known good position 0x%"PRIx64", %d unknown elements"
1409  " in a row\n", id, pos, length, matroska->resync_pos,
1410  matroska->unknown_count);
1411  return AVERROR_INVALIDDATA;
1412  }
1413  }
1414  }
1415 
1416  if (update_pos > 0) {
1417  // We have found an element that is allowed at this place
1418  // in the hierarchy and it passed all checks, so treat the beginning
1419  // of the element as the "last known good" position.
1420  matroska->resync_pos = pos;
1421  }
1422 
1423  if (!data && length != EBML_UNKNOWN_LENGTH)
1424  goto skip;
1425  }
1426 
1427  switch (syntax->type) {
1428  case EBML_UINT:
1429  res = ebml_read_uint(pb, length, syntax->def.u, data);
1430  break;
1431  case EBML_SINT:
1432  res = ebml_read_sint(pb, length, syntax->def.i, data);
1433  break;
1434  case EBML_FLOAT:
1435  res = ebml_read_float(pb, length, syntax->def.f, data);
1436  break;
1437  case EBML_STR:
1438  case EBML_UTF8:
1439  res = ebml_read_ascii(pb, length, syntax->def.s, data);
1440  break;
1441  case EBML_BIN:
1442  res = ebml_read_binary(pb, length, pos_alt, data);
1443  break;
1444  case EBML_LEVEL1:
1445  case EBML_NEST:
1446  if ((res = ebml_read_master(matroska, length, pos_alt)) < 0)
1447  return res;
1448  if (id == MATROSKA_ID_SEGMENT)
1449  matroska->segment_start = pos_alt;
1450  if (id == MATROSKA_ID_CUES)
1451  matroska->cues_parsing_deferred = 0;
1452  if (syntax->type == EBML_LEVEL1 &&
1453  (level1_elem = matroska_find_level1_elem(matroska, syntax->id, pos))) {
1454  if (!level1_elem->pos) {
1455  // Zero is not a valid position for a level 1 element.
1456  level1_elem->pos = pos;
1457  } else if (level1_elem->pos != pos)
1458  av_log(matroska->ctx, AV_LOG_ERROR, "Duplicate element\n");
1459  level1_elem->parsed = 1;
1460  }
1461  if (res = ebml_parse_nest(matroska, syntax->def.n, data))
1462  return res;
1463  break;
1464  case EBML_STOP:
1465  return 1;
1466  skip:
1467  default:
1468  if (length) {
1469  int64_t res2;
1470  if (ffio_limit(pb, length) != length) {
1471  // ffio_limit emits its own error message,
1472  // so we don't have to.
1473  return AVERROR(EIO);
1474  }
1475  if ((res2 = avio_skip(pb, length - 1)) >= 0) {
1476  // avio_skip might take us past EOF. We check for this
1477  // by skipping only length - 1 bytes, reading a byte and
1478  // checking the error flags. This is done in order to check
1479  // that the element has been properly skipped even when
1480  // no filesize (that ffio_limit relies on) is available.
1481  avio_r8(pb);
1482  res = NEEDS_CHECKING;
1483  } else
1484  res = res2;
1485  } else
1486  res = 0;
1487  }
1488  if (res) {
1489  if (res == NEEDS_CHECKING) {
1490  if (pb->eof_reached) {
1491  if (pb->error)
1492  res = pb->error;
1493  else
1494  res = AVERROR_EOF;
1495  } else
1496  goto level_check;
1497  }
1498 
1499  if (res == AVERROR_INVALIDDATA)
1500  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
1501  else if (res == AVERROR(EIO))
1502  av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
1503  else if (res == AVERROR_EOF) {
1504  av_log(matroska->ctx, AV_LOG_ERROR, "File ended prematurely\n");
1505  res = AVERROR(EIO);
1506  }
1507 
1508  return res;
1509  }
1510 
1511 level_check:
1512  if (syntax->is_counted && data) {
1513  CountedElement *elem = data;
1514  if (elem->count != UINT_MAX)
1515  elem->count++;
1516  }
1517 
1518  if (level_check == LEVEL_ENDED && matroska->num_levels) {
1519  level = &matroska->levels[matroska->num_levels - 1];
1520  pos = avio_tell(pb);
1521 
1522  // Given that pos >= level->start no check for
1523  // level->length != EBML_UNKNOWN_LENGTH is necessary.
1524  while (matroska->num_levels && pos == level->start + level->length) {
1525  matroska->num_levels--;
1526  level--;
1527  }
1528  }
1529 
1530  return level_check;
1531 }
1532 
1533 static void ebml_free(EbmlSyntax *syntax, void *data)
1534 {
1535  int i, j;
1536  for (i = 0; syntax[i].id; i++) {
1537  void *data_off = (char *) data + syntax[i].data_offset;
1538  switch (syntax[i].type) {
1539  case EBML_STR:
1540  case EBML_UTF8:
1541  av_freep(data_off);
1542  break;
1543  case EBML_BIN:
1544  av_buffer_unref(&((EbmlBin *) data_off)->buf);
1545  break;
1546  case EBML_LEVEL1:
1547  case EBML_NEST:
1548  if (syntax[i].list_elem_size) {
1549  EbmlList *list = data_off;
1550  char *ptr = list->elem;
1551  for (j = 0; j < list->nb_elem;
1552  j++, ptr += syntax[i].list_elem_size)
1553  ebml_free(syntax[i].def.n, ptr);
1554  av_freep(&list->elem);
1555  list->nb_elem = 0;
1556  list->alloc_elem_size = 0;
1557  } else
1558  ebml_free(syntax[i].def.n, data_off);
1559  default:
1560  break;
1561  }
1562  }
1563 }
1564 
1565 /*
1566  * Autodetecting...
1567  */
1568 static int matroska_probe(const AVProbeData *p)
1569 {
1570  uint64_t total = 0;
1571  int len_mask = 0x80, size = 1, n = 1, i;
1572 
1573  /* EBML header? */
1574  if (AV_RB32(p->buf) != EBML_ID_HEADER)
1575  return 0;
1576 
1577  /* length of header */
1578  total = p->buf[4];
1579  while (size <= 8 && !(total & len_mask)) {
1580  size++;
1581  len_mask >>= 1;
1582  }
1583  if (size > 8)
1584  return 0;
1585  total &= (len_mask - 1);
1586  while (n < size)
1587  total = (total << 8) | p->buf[4 + n++];
1588 
1589  if (total + 1 == 1ULL << (7 * size)){
1590  /* Unknown-length header - simply parse the whole buffer. */
1591  total = p->buf_size - 4 - size;
1592  } else {
1593  /* Does the probe data contain the whole header? */
1594  if (p->buf_size < 4 + size + total)
1595  return 0;
1596  }
1597 
1598  /* The header should contain a known document type. For now,
1599  * we don't parse the whole header but simply check for the
1600  * availability of that array of characters inside the header.
1601  * Not fully fool-proof, but good enough. */
1602  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1603  size_t probelen = strlen(matroska_doctypes[i]);
1604  if (total < probelen)
1605  continue;
1606  for (n = 4 + size; n <= 4 + size + total - probelen; n++)
1607  if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
1608  return AVPROBE_SCORE_MAX;
1609  }
1610 
1611  // probably valid EBML header but no recognized doctype
1612  return AVPROBE_SCORE_EXTENSION;
1613 }
1614 
1616  uint64_t num)
1617 {
1618  MatroskaTrack *tracks = matroska->tracks.elem;
1619  int i;
1620 
1621  for (i = 0; i < matroska->tracks.nb_elem; i++)
1622  if (tracks[i].num == num)
1623  return &tracks[i];
1624 
1625  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %"PRIu64"\n", num);
1626  return NULL;
1627 }
1628 
1629 static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
1630  MatroskaTrack *track)
1631 {
1632  MatroskaTrackEncoding *encodings = track->encodings.elem;
1633  uint8_t *data = *buf;
1634  int isize = *buf_size;
1635  uint8_t *pkt_data = NULL;
1636  uint8_t av_unused *newpktdata;
1637  int pkt_size = isize;
1638  int result = 0;
1639  int olen;
1640 
1641  if (pkt_size >= 10000000U)
1642  return AVERROR_INVALIDDATA;
1643 
1644  switch (encodings[0].compression.algo) {
1646  {
1647  int header_size = encodings[0].compression.settings.size;
1648  uint8_t *header = encodings[0].compression.settings.data;
1649 
1650  if (header_size && !header) {
1651  av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1652  return -1;
1653  }
1654 
1655  if (!header_size)
1656  return 0;
1657 
1658  pkt_size = isize + header_size;
1659  pkt_data = av_malloc(pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
1660  if (!pkt_data)
1661  return AVERROR(ENOMEM);
1662 
1663  memcpy(pkt_data, header, header_size);
1664  memcpy(pkt_data + header_size, data, isize);
1665  break;
1666  }
1667 #if CONFIG_LZO
1669  do {
1670  int insize = isize;
1671  olen = pkt_size *= 3;
1672  newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING
1674  if (!newpktdata) {
1675  result = AVERROR(ENOMEM);
1676  goto failed;
1677  }
1678  pkt_data = newpktdata;
1679  result = av_lzo1x_decode(pkt_data, &olen, data, &insize);
1680  } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
1681  if (result) {
1683  goto failed;
1684  }
1685  pkt_size -= olen;
1686  break;
1687 #endif
1688 #if CONFIG_ZLIB
1690  {
1691  z_stream zstream = { 0 };
1692  if (inflateInit(&zstream) != Z_OK)
1693  return -1;
1694  zstream.next_in = data;
1695  zstream.avail_in = isize;
1696  do {
1697  pkt_size *= 3;
1698  newpktdata = av_realloc(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
1699  if (!newpktdata) {
1700  inflateEnd(&zstream);
1701  result = AVERROR(ENOMEM);
1702  goto failed;
1703  }
1704  pkt_data = newpktdata;
1705  zstream.avail_out = pkt_size - zstream.total_out;
1706  zstream.next_out = pkt_data + zstream.total_out;
1707  result = inflate(&zstream, Z_NO_FLUSH);
1708  } while (result == Z_OK && pkt_size < 10000000);
1709  pkt_size = zstream.total_out;
1710  inflateEnd(&zstream);
1711  if (result != Z_STREAM_END) {
1712  if (result == Z_MEM_ERROR)
1713  result = AVERROR(ENOMEM);
1714  else
1716  goto failed;
1717  }
1718  break;
1719  }
1720 #endif
1721 #if CONFIG_BZLIB
1723  {
1724  bz_stream bzstream = { 0 };
1725  if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1726  return -1;
1727  bzstream.next_in = data;
1728  bzstream.avail_in = isize;
1729  do {
1730  pkt_size *= 3;
1731  newpktdata = av_realloc(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
1732  if (!newpktdata) {
1733  BZ2_bzDecompressEnd(&bzstream);
1734  result = AVERROR(ENOMEM);
1735  goto failed;
1736  }
1737  pkt_data = newpktdata;
1738  bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1739  bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1740  result = BZ2_bzDecompress(&bzstream);
1741  } while (result == BZ_OK && pkt_size < 10000000);
1742  pkt_size = bzstream.total_out_lo32;
1743  BZ2_bzDecompressEnd(&bzstream);
1744  if (result != BZ_STREAM_END) {
1745  if (result == BZ_MEM_ERROR)
1746  result = AVERROR(ENOMEM);
1747  else
1749  goto failed;
1750  }
1751  break;
1752  }
1753 #endif
1754  default:
1755  return AVERROR_INVALIDDATA;
1756  }
1757 
1758  memset(pkt_data + pkt_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1759 
1760  *buf = pkt_data;
1761  *buf_size = pkt_size;
1762  return 0;
1764 failed:
1765  av_free(pkt_data);
1766  return result;
1767 }
1768 
1770  AVDictionary **metadata, char *prefix)
1771 {
1772  MatroskaTag *tags = list->elem;
1773  char key[1024];
1774  int i;
1775 
1776  for (i = 0; i < list->nb_elem; i++) {
1777  const char *lang = tags[i].lang &&
1778  strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1779 
1780  if (!tags[i].name) {
1781  av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1782  continue;
1783  }
1784  if (prefix)
1785  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1786  else
1787  av_strlcpy(key, tags[i].name, sizeof(key));
1788  if (tags[i].def || !lang) {
1789  av_dict_set(metadata, key, tags[i].string, 0);
1790  if (tags[i].sub.nb_elem)
1791  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1792  }
1793  if (lang) {
1794  av_strlcat(key, "-", sizeof(key));
1795  av_strlcat(key, lang, sizeof(key));
1796  av_dict_set(metadata, key, tags[i].string, 0);
1797  if (tags[i].sub.nb_elem)
1798  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1799  }
1800  }
1802 }
1803 
1805 {
1806  MatroskaDemuxContext *matroska = s->priv_data;
1807  MatroskaTags *tags = matroska->tags.elem;
1808  int i, j;
1809 
1810  for (i = 0; i < matroska->tags.nb_elem; i++) {
1811  if (tags[i].target.attachuid) {
1812  MatroskaAttachment *attachment = matroska->attachments.elem;
1813  int found = 0;
1814  for (j = 0; j < matroska->attachments.nb_elem; j++) {
1815  if (attachment[j].uid == tags[i].target.attachuid &&
1816  attachment[j].stream) {
1817  matroska_convert_tag(s, &tags[i].tag,
1818  &attachment[j].stream->metadata, NULL);
1819  found = 1;
1820  }
1821  }
1822  if (!found) {
1824  "The tags at index %d refer to a "
1825  "non-existent attachment %"PRId64".\n",
1826  i, tags[i].target.attachuid);
1827  }
1828  } else if (tags[i].target.chapteruid) {
1829  MatroskaChapter *chapter = matroska->chapters.elem;
1830  int found = 0;
1831  for (j = 0; j < matroska->chapters.nb_elem; j++) {
1832  if (chapter[j].uid == tags[i].target.chapteruid &&
1833  chapter[j].chapter) {
1834  matroska_convert_tag(s, &tags[i].tag,
1835  &chapter[j].chapter->metadata, NULL);
1836  found = 1;
1837  }
1838  }
1839  if (!found) {
1841  "The tags at index %d refer to a non-existent chapter "
1842  "%"PRId64".\n",
1843  i, tags[i].target.chapteruid);
1844  }
1845  } else if (tags[i].target.trackuid) {
1846  MatroskaTrack *track = matroska->tracks.elem;
1847  int found = 0;
1848  for (j = 0; j < matroska->tracks.nb_elem; j++) {
1849  if (track[j].uid == tags[i].target.trackuid &&
1850  track[j].stream) {
1851  matroska_convert_tag(s, &tags[i].tag,
1852  &track[j].stream->metadata, NULL);
1853  found = 1;
1854  }
1855  }
1856  if (!found) {
1858  "The tags at index %d refer to a non-existent track "
1859  "%"PRId64".\n",
1860  i, tags[i].target.trackuid);
1861  }
1862  } else {
1863  matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1864  tags[i].target.type);
1865  }
1866  }
1867 }
1868 
1870  int64_t pos)
1871 {
1872  uint32_t saved_id = matroska->current_id;
1873  int64_t before_pos = avio_tell(matroska->ctx->pb);
1874  int ret = 0;
1875 
1876  /* seek */
1877  if (avio_seek(matroska->ctx->pb, pos, SEEK_SET) == pos) {
1878  /* We don't want to lose our seekhead level, so we add
1879  * a dummy. This is a crude hack. */
1880  if (matroska->num_levels == EBML_MAX_DEPTH) {
1881  av_log(matroska->ctx, AV_LOG_INFO,
1882  "Max EBML element depth (%d) reached, "
1883  "cannot parse further.\n", EBML_MAX_DEPTH);
1885  } else {
1886  matroska->levels[matroska->num_levels] = (MatroskaLevel) { 0, EBML_UNKNOWN_LENGTH };
1887  matroska->num_levels++;
1888  matroska->current_id = 0;
1889 
1890  ret = ebml_parse(matroska, matroska_segment, matroska);
1891  if (ret == LEVEL_ENDED) {
1892  /* This can only happen if the seek brought us beyond EOF. */
1893  ret = AVERROR_EOF;
1894  }
1895  }
1896  }
1897  /* Seek back - notice that in all instances where this is used
1898  * it is safe to set the level to 1. */
1899  matroska_reset_status(matroska, saved_id, before_pos);
1900 
1901  return ret;
1902 }
1903 
1904 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1905 {
1906  EbmlList *seekhead_list = &matroska->seekhead;
1907  int i;
1908 
1909  // we should not do any seeking in the streaming case
1910  if (!(matroska->ctx->pb->seekable & AVIO_SEEKABLE_NORMAL))
1911  return;
1912 
1913  for (i = 0; i < seekhead_list->nb_elem; i++) {
1914  MatroskaSeekhead *seekheads = seekhead_list->elem;
1915  uint32_t id = seekheads[i].id;
1916  int64_t pos = seekheads[i].pos + matroska->segment_start;
1917  MatroskaLevel1Element *elem;
1918 
1919  if (id != seekheads[i].id || pos < matroska->segment_start)
1920  continue;
1921 
1922  elem = matroska_find_level1_elem(matroska, id, pos);
1923  if (!elem || elem->parsed)
1924  continue;
1925 
1926  elem->pos = pos;
1927 
1928  // defer cues parsing until we actually need cue data.
1929  if (id == MATROSKA_ID_CUES)
1930  continue;
1931 
1932  if (matroska_parse_seekhead_entry(matroska, pos) < 0) {
1933  // mark index as broken
1934  matroska->cues_parsing_deferred = -1;
1935  break;
1936  }
1937 
1938  elem->parsed = 1;
1939  }
1940 }
1941 
1942 static void matroska_add_index_entries(MatroskaDemuxContext *matroska)
1943 {
1944  EbmlList *index_list;
1946  uint64_t index_scale = 1;
1947  int i, j;
1948 
1949  if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
1950  return;
1951 
1952  index_list = &matroska->index;
1953  index = index_list->elem;
1954  if (index_list->nb_elem < 2)
1955  return;
1956  if (index[1].time > 1E14 / matroska->time_scale) {
1957  av_log(matroska->ctx, AV_LOG_WARNING, "Dropping apparently-broken index.\n");
1958  return;
1959  }
1960  for (i = 0; i < index_list->nb_elem; i++) {
1961  EbmlList *pos_list = &index[i].pos;
1962  MatroskaIndexPos *pos = pos_list->elem;
1963  for (j = 0; j < pos_list->nb_elem; j++) {
1964  MatroskaTrack *track = matroska_find_track_by_num(matroska,
1965  pos[j].track);
1966  if (track && track->stream)
1967  av_add_index_entry(track->stream,
1968  pos[j].pos + matroska->segment_start,
1969  index[i].time / index_scale, 0, 0,
1971  }
1972  }
1973 }
1974 
1975 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1976  int i;
1977 
1978  if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
1979  return;
1980 
1981  for (i = 0; i < matroska->num_level1_elems; i++) {
1982  MatroskaLevel1Element *elem = &matroska->level1_elems[i];
1983  if (elem->id == MATROSKA_ID_CUES && !elem->parsed) {
1984  if (matroska_parse_seekhead_entry(matroska, elem->pos) < 0)
1985  matroska->cues_parsing_deferred = -1;
1986  elem->parsed = 1;
1987  break;
1988  }
1989  }
1990 
1991  matroska_add_index_entries(matroska);
1992 }
1993 
1994 static int matroska_aac_profile(char *codec_id)
1995 {
1996  static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
1997  int profile;
1998 
2000  if (strstr(codec_id, aac_profiles[profile]))
2001  break;
2002  return profile + 1;
2003 }
2004 
2005 static int matroska_aac_sri(int samplerate)
2006 {
2007  int sri;
2008 
2009  for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
2010  if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
2011  break;
2012  return sri;
2013 }
2014 
2015 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
2016 {
2017  /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
2018  avpriv_dict_set_timestamp(metadata, "creation_time", date_utc / 1000 + 978307200000000LL);
2019 }
2020 
2022  MatroskaTrack *track,
2023  int *offset)
2024 {
2025  AVStream *st = track->stream;
2026  uint8_t *p = track->codec_priv.data;
2027  int size = track->codec_priv.size;
2028 
2029  if (size < 8 + FLAC_STREAMINFO_SIZE || p[4] & 0x7f) {
2030  av_log(s, AV_LOG_WARNING, "Invalid FLAC private data\n");
2031  track->codec_priv.size = 0;
2032  return 0;
2033  }
2034  *offset = 8;
2035  track->codec_priv.size = 8 + FLAC_STREAMINFO_SIZE;
2036 
2037  p += track->codec_priv.size;
2038  size -= track->codec_priv.size;
2039 
2040  /* parse the remaining metadata blocks if present */
2041  while (size >= 4) {
2042  int block_last, block_type, block_size;
2043 
2044  flac_parse_block_header(p, &block_last, &block_type, &block_size);
2045 
2046  p += 4;
2047  size -= 4;
2048  if (block_size > size)
2049  return 0;
2050 
2051  /* check for the channel mask */
2052  if (block_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
2053  AVDictionary *dict = NULL;
2054  AVDictionaryEntry *chmask;
2055 
2056  ff_vorbis_comment(s, &dict, p, block_size, 0);
2057  chmask = av_dict_get(dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
2058  if (chmask) {
2059  uint64_t mask = strtol(chmask->value, NULL, 0);
2060  if (!mask || mask & ~0x3ffffULL) {
2062  "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
2063  } else
2064  st->codecpar->channel_layout = mask;
2065  }
2066  av_dict_free(&dict);
2067  }
2068 
2069  p += block_size;
2070  size -= block_size;
2071  }
2072 
2073  return 0;
2074 }
2075 
2076 static int mkv_field_order(MatroskaDemuxContext *matroska, int64_t field_order)
2077 {
2078  int minor, micro, bttb = 0;
2079 
2080  /* workaround a bug in our Matroska muxer, introduced in version 57.36 alongside
2081  * this function, and fixed in 57.52 */
2082  if (matroska->muxingapp && sscanf(matroska->muxingapp, "Lavf57.%d.%d", &minor, &micro) == 2)
2083  bttb = (minor >= 36 && minor <= 51 && micro >= 100);
2084 
2085  switch (field_order) {
2087  return AV_FIELD_PROGRESSIVE;
2089  return AV_FIELD_UNKNOWN;
2091  return AV_FIELD_TT;
2093  return AV_FIELD_BB;
2095  return bttb ? AV_FIELD_TB : AV_FIELD_BT;
2097  return bttb ? AV_FIELD_BT : AV_FIELD_TB;
2098  default:
2099  return AV_FIELD_UNKNOWN;
2100  }
2101 }
2102 
2103 static void mkv_stereo_mode_display_mul(int stereo_mode,
2104  int *h_width, int *h_height)
2105 {
2106  switch (stereo_mode) {
2112  break;
2117  *h_width = 2;
2118  break;
2123  *h_height = 2;
2124  break;
2125  }
2126 }
2127 
2128 static int mkv_parse_video_color(AVStream *st, const MatroskaTrack *track) {
2129  const MatroskaTrackVideoColor *color = track->video.color.elem;
2130  const MatroskaMasteringMeta *mastering_meta;
2131  int has_mastering_primaries, has_mastering_luminance;
2132 
2133  if (!track->video.color.nb_elem)
2134  return 0;
2135 
2136  mastering_meta = &color->mastering_meta;
2137  // Mastering primaries are CIE 1931 coords, and must be > 0.
2138  has_mastering_primaries =
2139  mastering_meta->r_x > 0 && mastering_meta->r_y > 0 &&
2140  mastering_meta->g_x > 0 && mastering_meta->g_y > 0 &&
2141  mastering_meta->b_x > 0 && mastering_meta->b_y > 0 &&
2142  mastering_meta->white_x > 0 && mastering_meta->white_y > 0;
2143  has_mastering_luminance = mastering_meta->max_luminance >
2144  mastering_meta->min_luminance.el.f &&
2145  mastering_meta->min_luminance.el.f >= 0 &&
2146  mastering_meta->min_luminance.count;
2147 
2148  if (color->matrix_coefficients != AVCOL_SPC_RESERVED)
2149  st->codecpar->color_space = color->matrix_coefficients;
2150  if (color->primaries != AVCOL_PRI_RESERVED &&
2151  color->primaries != AVCOL_PRI_RESERVED0)
2152  st->codecpar->color_primaries = color->primaries;
2153  if (color->transfer_characteristics != AVCOL_TRC_RESERVED &&
2154  color->transfer_characteristics != AVCOL_TRC_RESERVED0)
2155  st->codecpar->color_trc = color->transfer_characteristics;
2156  if (color->range != AVCOL_RANGE_UNSPECIFIED &&
2157  color->range <= AVCOL_RANGE_JPEG)
2158  st->codecpar->color_range = color->range;
2159  if (color->chroma_siting_horz != MATROSKA_COLOUR_CHROMASITINGHORZ_UNDETERMINED &&
2160  color->chroma_siting_vert != MATROSKA_COLOUR_CHROMASITINGVERT_UNDETERMINED &&
2161  color->chroma_siting_horz < MATROSKA_COLOUR_CHROMASITINGHORZ_NB &&
2162  color->chroma_siting_vert < MATROSKA_COLOUR_CHROMASITINGVERT_NB) {
2163  st->codecpar->chroma_location =
2164  avcodec_chroma_pos_to_enum((color->chroma_siting_horz - 1) << 7,
2165  (color->chroma_siting_vert - 1) << 7);
2166  }
2167  if (color->max_cll && color->max_fall) {
2168  size_t size = 0;
2169  int ret;
2171  if (!metadata)
2172  return AVERROR(ENOMEM);
2174  (uint8_t *)metadata, size);
2175  if (ret < 0) {
2176  av_freep(&metadata);
2177  return ret;
2178  }
2179  metadata->MaxCLL = color->max_cll;
2180  metadata->MaxFALL = color->max_fall;
2181  }
2182 
2183  if (has_mastering_primaries || has_mastering_luminance) {
2184  AVMasteringDisplayMetadata *metadata =
2187  sizeof(AVMasteringDisplayMetadata));
2188  if (!metadata) {
2189  return AVERROR(ENOMEM);
2190  }
2191  memset(metadata, 0, sizeof(AVMasteringDisplayMetadata));
2192  if (has_mastering_primaries) {
2193  metadata->display_primaries[0][0] = av_d2q(mastering_meta->r_x, INT_MAX);
2194  metadata->display_primaries[0][1] = av_d2q(mastering_meta->r_y, INT_MAX);
2195  metadata->display_primaries[1][0] = av_d2q(mastering_meta->g_x, INT_MAX);
2196  metadata->display_primaries[1][1] = av_d2q(mastering_meta->g_y, INT_MAX);
2197  metadata->display_primaries[2][0] = av_d2q(mastering_meta->b_x, INT_MAX);
2198  metadata->display_primaries[2][1] = av_d2q(mastering_meta->b_y, INT_MAX);
2199  metadata->white_point[0] = av_d2q(mastering_meta->white_x, INT_MAX);
2200  metadata->white_point[1] = av_d2q(mastering_meta->white_y, INT_MAX);
2201  metadata->has_primaries = 1;
2202  }
2203  if (has_mastering_luminance) {
2204  metadata->max_luminance = av_d2q(mastering_meta->max_luminance, INT_MAX);
2205  metadata->min_luminance = av_d2q(mastering_meta->min_luminance.el.f, INT_MAX);
2206  metadata->has_luminance = 1;
2207  }
2208  }
2209  return 0;
2210 }
2211 
2212 static int mkv_parse_video_projection(AVStream *st, const MatroskaTrack *track,
2213  void *logctx)
2214 {
2215  AVSphericalMapping *spherical;
2216  const MatroskaTrackVideoProjection *mkv_projection = &track->video.projection;
2217  const uint8_t *priv_data = mkv_projection->private.data;
2218  enum AVSphericalProjection projection;
2219  size_t spherical_size;
2220  uint32_t l = 0, t = 0, r = 0, b = 0;
2221  uint32_t padding = 0;
2222  int ret;
2223 
2224  if (mkv_projection->private.size && priv_data[0] != 0) {
2225  av_log(logctx, AV_LOG_WARNING, "Unknown spherical metadata\n");
2226  return 0;
2227  }
2228 
2229  switch (track->video.projection.type) {
2231  if (track->video.projection.private.size == 20) {
2232  t = AV_RB32(priv_data + 4);
2233  b = AV_RB32(priv_data + 8);
2234  l = AV_RB32(priv_data + 12);
2235  r = AV_RB32(priv_data + 16);
2236 
2237  if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
2238  av_log(logctx, AV_LOG_ERROR,
2239  "Invalid bounding rectangle coordinates "
2240  "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n",
2241  l, t, r, b);
2242  return AVERROR_INVALIDDATA;
2243  }
2244  } else if (track->video.projection.private.size != 0) {
2245  av_log(logctx, AV_LOG_ERROR, "Unknown spherical metadata\n");
2246  return AVERROR_INVALIDDATA;
2247  }
2248 
2249  if (l || t || r || b)
2250  projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
2251  else
2252  projection = AV_SPHERICAL_EQUIRECTANGULAR;
2253  break;
2255  if (track->video.projection.private.size < 4) {
2256  av_log(logctx, AV_LOG_ERROR, "Missing projection private properties\n");
2257  return AVERROR_INVALIDDATA;
2258  } else if (track->video.projection.private.size == 12) {
2259  uint32_t layout = AV_RB32(priv_data + 4);
2260  if (layout) {
2261  av_log(logctx, AV_LOG_WARNING,
2262  "Unknown spherical cubemap layout %"PRIu32"\n", layout);
2263  return 0;
2264  }
2265  projection = AV_SPHERICAL_CUBEMAP;
2266  padding = AV_RB32(priv_data + 8);
2267  } else {
2268  av_log(logctx, AV_LOG_ERROR, "Unknown spherical metadata\n");
2269  return AVERROR_INVALIDDATA;
2270  }
2271  break;
2273  /* No Spherical metadata */
2274  return 0;
2275  default:
2276  av_log(logctx, AV_LOG_WARNING,
2277  "Unknown spherical metadata type %"PRIu64"\n",
2278  track->video.projection.type);
2279  return 0;
2280  }
2281 
2282  spherical = av_spherical_alloc(&spherical_size);
2283  if (!spherical)
2284  return AVERROR(ENOMEM);
2285 
2286  spherical->projection = projection;
2287 
2288  spherical->yaw = (int32_t) (track->video.projection.yaw * (1 << 16));
2289  spherical->pitch = (int32_t) (track->video.projection.pitch * (1 << 16));
2290  spherical->roll = (int32_t) (track->video.projection.roll * (1 << 16));
2291 
2292  spherical->padding = padding;
2293 
2294  spherical->bound_left = l;
2295  spherical->bound_top = t;
2296  spherical->bound_right = r;
2297  spherical->bound_bottom = b;
2298 
2299  ret = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL, (uint8_t *)spherical,
2300  spherical_size);
2301  if (ret < 0) {
2302  av_freep(&spherical);
2303  return ret;
2304  }
2305 
2306  return 0;
2307 }
2308 
2309 static int get_qt_codec(MatroskaTrack *track, uint32_t *fourcc, enum AVCodecID *codec_id)
2310 {
2311  const AVCodecTag *codec_tags;
2312 
2313  codec_tags = track->type == MATROSKA_TRACK_TYPE_VIDEO ?
2315 
2316  /* Normalize noncompliant private data that starts with the fourcc
2317  * by expanding/shifting the data by 4 bytes and storing the data
2318  * size at the start. */
2319  if (ff_codec_get_id(codec_tags, AV_RL32(track->codec_priv.data))) {
2320  int ret = av_buffer_realloc(&track->codec_priv.buf,
2322  if (ret < 0)
2323  return ret;
2324 
2325  track->codec_priv.data = track->codec_priv.buf->data;
2326  memmove(track->codec_priv.data + 4, track->codec_priv.data, track->codec_priv.size);
2327  track->codec_priv.size += 4;
2328  AV_WB32(track->codec_priv.data, track->codec_priv.size);
2329  }
2330 
2331  *fourcc = AV_RL32(track->codec_priv.data + 4);
2332  *codec_id = ff_codec_get_id(codec_tags, *fourcc);
2333 
2334  return 0;
2335 }
2336 
2338 {
2339  MatroskaDemuxContext *matroska = s->priv_data;
2340  MatroskaTrack *tracks = matroska->tracks.elem;
2341  int i, j, ret;
2342  int k;
2343 
2344  for (i = 0; i < matroska->tracks.nb_elem; i++) {
2345  MatroskaTrack *track = &tracks[i];
2347  EbmlList *encodings_list = &track->encodings;
2348  MatroskaTrackEncoding *encodings = encodings_list->elem;
2349  uint8_t *extradata = NULL;
2350  int extradata_size = 0;
2351  int extradata_offset = 0;
2352  uint32_t fourcc = 0;
2353  FFIOContext b;
2354  AVStream *st;
2355  FFStream *sti;
2356  char* key_id_base64 = NULL;
2357  int bit_depth = -1;
2358 
2359  /* Apply some sanity checks. */
2360  if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
2361  track->type != MATROSKA_TRACK_TYPE_AUDIO &&
2362  track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
2363  track->type != MATROSKA_TRACK_TYPE_METADATA) {
2364  av_log(matroska->ctx, AV_LOG_INFO,
2365  "Unknown or unsupported track type %"PRIu64"\n",
2366  track->type);
2367  continue;
2368  }
2369  if (!track->codec_id)
2370  continue;
2371 
2372  if ( track->type == MATROSKA_TRACK_TYPE_AUDIO && track->codec_id[0] != 'A'
2373  || track->type == MATROSKA_TRACK_TYPE_VIDEO && track->codec_id[0] != 'V'
2374  || track->type == MATROSKA_TRACK_TYPE_SUBTITLE && track->codec_id[0] != 'D' && track->codec_id[0] != 'S'
2375  || track->type == MATROSKA_TRACK_TYPE_METADATA && track->codec_id[0] != 'D' && track->codec_id[0] != 'S'
2376  ) {
2377  av_log(matroska->ctx, AV_LOG_INFO, "Inconsistent track type\n");
2378  continue;
2379  }
2380 
2381  if (track->audio.samplerate < 0 || track->audio.samplerate > INT_MAX ||
2382  isnan(track->audio.samplerate)) {
2383  av_log(matroska->ctx, AV_LOG_WARNING,
2384  "Invalid sample rate %f, defaulting to 8000 instead.\n",
2385  track->audio.samplerate);
2386  track->audio.samplerate = 8000;
2387  }
2388 
2389  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2390  if (!track->default_duration && track->video.frame_rate > 0) {
2391  double default_duration = 1000000000 / track->video.frame_rate;
2392  if (default_duration > UINT64_MAX || default_duration < 0) {
2393  av_log(matroska->ctx, AV_LOG_WARNING,
2394  "Invalid frame rate %e. Cannot calculate default duration.\n",
2395  track->video.frame_rate);
2396  } else {
2397  track->default_duration = default_duration;
2398  }
2399  }
2400  if (track->video.display_width == -1)
2401  track->video.display_width = track->video.pixel_width;
2402  if (track->video.display_height == -1)
2403  track->video.display_height = track->video.pixel_height;
2404  if (track->video.color_space.size == 4)
2405  fourcc = AV_RL32(track->video.color_space.data);
2406  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2407  if (!track->audio.out_samplerate)
2408  track->audio.out_samplerate = track->audio.samplerate;
2409  }
2410  if (encodings_list->nb_elem > 1) {
2411  av_log(matroska->ctx, AV_LOG_ERROR,
2412  "Multiple combined encodings not supported");
2413  } else if (encodings_list->nb_elem == 1) {
2414  if (encodings[0].type) {
2415  if (encodings[0].encryption.key_id.size > 0) {
2416  /* Save the encryption key id to be stored later as a
2417  metadata tag. */
2418  const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
2419  key_id_base64 = av_malloc(b64_size);
2420  if (key_id_base64 == NULL)
2421  return AVERROR(ENOMEM);
2422 
2423  av_base64_encode(key_id_base64, b64_size,
2424  encodings[0].encryption.key_id.data,
2425  encodings[0].encryption.key_id.size);
2426  } else {
2427  encodings[0].scope = 0;
2428  av_log(matroska->ctx, AV_LOG_ERROR,
2429  "Unsupported encoding type");
2430  }
2431  } else if (
2432 #if CONFIG_ZLIB
2433  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
2434 #endif
2435 #if CONFIG_BZLIB
2436  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
2437 #endif
2438 #if CONFIG_LZO
2439  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
2440 #endif
2441  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
2442  encodings[0].scope = 0;
2443  av_log(matroska->ctx, AV_LOG_ERROR,
2444  "Unsupported encoding type");
2445  } else if (track->codec_priv.size && encodings[0].scope & 2) {
2446  uint8_t *codec_priv = track->codec_priv.data;
2447  int ret = matroska_decode_buffer(&track->codec_priv.data,
2448  &track->codec_priv.size,
2449  track);
2450  if (ret < 0) {
2451  track->codec_priv.data = NULL;
2452  track->codec_priv.size = 0;
2453  av_log(matroska->ctx, AV_LOG_ERROR,
2454  "Failed to decode codec private data\n");
2455  }
2456 
2457  if (codec_priv != track->codec_priv.data) {
2458  av_buffer_unref(&track->codec_priv.buf);
2459  if (track->codec_priv.data) {
2460  track->codec_priv.buf = av_buffer_create(track->codec_priv.data,
2462  NULL, NULL, 0);
2463  if (!track->codec_priv.buf) {
2464  av_freep(&track->codec_priv.data);
2465  track->codec_priv.size = 0;
2466  return AVERROR(ENOMEM);
2467  }
2468  }
2469  }
2470  }
2471  }
2472  track->needs_decoding = encodings && !encodings[0].type &&
2473  encodings[0].scope & 1 &&
2474  (encodings[0].compression.algo !=
2476  encodings[0].compression.settings.size);
2477 
2478  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
2479  if (av_strstart(track->codec_id, ff_mkv_codec_tags[j].str, NULL)) {
2481  break;
2482  }
2483  }
2484 
2485  st = track->stream = avformat_new_stream(s, NULL);
2486  if (!st) {
2487  av_free(key_id_base64);
2488  return AVERROR(ENOMEM);
2489  }
2490  sti = ffstream(st);
2491 
2492  if (key_id_base64) {
2493  /* export encryption key id as base64 metadata tag */
2494  av_dict_set(&st->metadata, "enc_key_id", key_id_base64,
2496  }
2497 
2498  if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
2499  track->codec_priv.size >= 40 &&
2500  track->codec_priv.data) {
2501  track->ms_compat = 1;
2502  bit_depth = AV_RL16(track->codec_priv.data + 14);
2503  fourcc = AV_RL32(track->codec_priv.data + 16);
2505  fourcc);
2506  if (!codec_id)
2508  fourcc);
2509  extradata_offset = 40;
2510  } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
2511  track->codec_priv.size >= 14 &&
2512  track->codec_priv.data) {
2513  int ret;
2515  track->codec_priv.size,
2516  0, NULL, NULL, NULL, NULL);
2517  ret = ff_get_wav_header(s, &b.pub, st->codecpar,
2518  track->codec_priv.size, 0);
2519  if (ret < 0)
2520  return ret;
2521  codec_id = st->codecpar->codec_id;
2522  fourcc = st->codecpar->codec_tag;
2523  extradata_offset = FFMIN(track->codec_priv.size, 18);
2524  } else if (!strcmp(track->codec_id, "A_QUICKTIME")
2525  /* Normally 36, but allow noncompliant private data */
2526  && (track->codec_priv.size >= 32)
2527  && (track->codec_priv.data)) {
2528  uint16_t sample_size;
2529  int ret = get_qt_codec(track, &fourcc, &codec_id);
2530  if (ret < 0)
2531  return ret;
2532  sample_size = AV_RB16(track->codec_priv.data + 26);
2533  if (fourcc == 0) {
2534  if (sample_size == 8) {
2535  fourcc = MKTAG('r','a','w',' ');
2537  } else if (sample_size == 16) {
2538  fourcc = MKTAG('t','w','o','s');
2540  }
2541  }
2542  if ((fourcc == MKTAG('t','w','o','s') ||
2543  fourcc == MKTAG('s','o','w','t')) &&
2544  sample_size == 8)
2546  } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
2547  (track->codec_priv.size >= 21) &&
2548  (track->codec_priv.data)) {
2549  int ret = get_qt_codec(track, &fourcc, &codec_id);
2550  if (ret < 0)
2551  return ret;
2552  if (codec_id == AV_CODEC_ID_NONE && AV_RL32(track->codec_priv.data+4) == AV_RL32("SMI ")) {
2553  fourcc = MKTAG('S','V','Q','3');
2555  }
2556  if (codec_id == AV_CODEC_ID_NONE)
2557  av_log(matroska->ctx, AV_LOG_ERROR,
2558  "mov FourCC not found %s.\n", av_fourcc2str(fourcc));
2559  if (track->codec_priv.size >= 86) {
2560  bit_depth = AV_RB16(track->codec_priv.data + 82);
2562  track->codec_priv.size,
2563  0, NULL, NULL, NULL, NULL);
2564  if (ff_get_qtpalette(codec_id, &b.pub, track->palette)) {
2565  bit_depth &= 0x1F;
2566  track->has_palette = 1;
2567  }
2568  }
2569  } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
2570  switch (track->audio.bitdepth) {
2571  case 8:
2573  break;
2574  case 24:
2576  break;
2577  case 32:
2579  break;
2580  }
2581  } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
2582  switch (track->audio.bitdepth) {
2583  case 8:
2585  break;
2586  case 24:
2588  break;
2589  case 32:
2591  break;
2592  }
2593  } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
2594  track->audio.bitdepth == 64) {
2596  } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
2597  int profile = matroska_aac_profile(track->codec_id);
2598  int sri = matroska_aac_sri(track->audio.samplerate);
2599  extradata = av_mallocz(5 + AV_INPUT_BUFFER_PADDING_SIZE);
2600  if (!extradata)
2601  return AVERROR(ENOMEM);
2602  extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
2603  extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
2604  if (strstr(track->codec_id, "SBR")) {
2605  sri = matroska_aac_sri(track->audio.out_samplerate);
2606  extradata[2] = 0x56;
2607  extradata[3] = 0xE5;
2608  extradata[4] = 0x80 | (sri << 3);
2609  extradata_size = 5;
2610  } else
2611  extradata_size = 2;
2612  } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - AV_INPUT_BUFFER_PADDING_SIZE) {
2613  /* Only ALAC's magic cookie is stored in Matroska's track headers.
2614  * Create the "atom size", "tag", and "tag version" fields the
2615  * decoder expects manually. */
2616  extradata_size = 12 + track->codec_priv.size;
2617  extradata = av_mallocz(extradata_size +
2619  if (!extradata)
2620  return AVERROR(ENOMEM);
2621  AV_WB32(extradata, extradata_size);
2622  memcpy(&extradata[4], "alac", 4);
2623  AV_WB32(&extradata[8], 0);
2624  memcpy(&extradata[12], track->codec_priv.data,
2625  track->codec_priv.size);
2626  } else if (codec_id == AV_CODEC_ID_TTA) {
2627  uint8_t *ptr;
2628  if (track->audio.channels > UINT16_MAX ||
2629  track->audio.bitdepth > UINT16_MAX) {
2630  av_log(matroska->ctx, AV_LOG_WARNING,
2631  "Too large audio channel number %"PRIu64
2632  " or bitdepth %"PRIu64". Skipping track.\n",
2633  track->audio.channels, track->audio.bitdepth);
2634  if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
2635  return AVERROR_INVALIDDATA;
2636  else
2637  continue;
2638  }
2639  if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
2640  return AVERROR_INVALIDDATA;
2641  extradata_size = 22;
2642  extradata = av_mallocz(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2643  if (!extradata)
2644  return AVERROR(ENOMEM);
2645  ptr = extradata;
2646  bytestream_put_be32(&ptr, AV_RB32("TTA1"));
2647  bytestream_put_le16(&ptr, 1);
2648  bytestream_put_le16(&ptr, track->audio.channels);
2649  bytestream_put_le16(&ptr, track->audio.bitdepth);
2650  bytestream_put_le32(&ptr, track->audio.out_samplerate);
2651  bytestream_put_le32(&ptr, av_rescale(matroska->duration * matroska->time_scale,
2652  track->audio.out_samplerate,
2653  AV_TIME_BASE * 1000));
2654  } else if (codec_id == AV_CODEC_ID_RV10 ||
2658  extradata_offset = 26;
2659  } else if (codec_id == AV_CODEC_ID_RA_144) {
2660  track->audio.out_samplerate = 8000;
2661  track->audio.channels = 1;
2662  } else if ((codec_id == AV_CODEC_ID_RA_288 ||
2666  && track->codec_priv.data) {
2667  const uint8_t *ptr = track->codec_priv.data;
2668  int flavor;
2669 
2670  if (track->codec_priv.size < 46)
2671  return AVERROR_INVALIDDATA;
2672  ptr += 22;
2673  flavor = bytestream_get_be16(&ptr);
2674  track->audio.coded_framesize = bytestream_get_be32(&ptr);
2675  ptr += 12;
2676  track->audio.sub_packet_h = bytestream_get_be16(&ptr);
2677  track->audio.frame_size = bytestream_get_be16(&ptr);
2678  track->audio.sub_packet_size = bytestream_get_be16(&ptr);
2679  if (track->audio.coded_framesize <= 0 ||
2680  track->audio.sub_packet_h <= 0 ||
2681  track->audio.frame_size <= 0)
2682  return AVERROR_INVALIDDATA;
2683 
2684  if (codec_id == AV_CODEC_ID_RA_288) {
2685  if (track->audio.sub_packet_h & 1 || 2 * track->audio.frame_size
2686  != (int64_t)track->audio.sub_packet_h * track->audio.coded_framesize)
2687  return AVERROR_INVALIDDATA;
2688  st->codecpar->block_align = track->audio.coded_framesize;
2689  track->codec_priv.size = 0;
2690  } else {
2691  if (codec_id == AV_CODEC_ID_SIPR) {
2692  static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
2693  if (flavor > 3)
2694  return AVERROR_INVALIDDATA;
2695  track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
2696  st->codecpar->bit_rate = sipr_bit_rate[flavor];
2697  } else if (track->audio.sub_packet_size <= 0 ||
2698  track->audio.frame_size % track->audio.sub_packet_size)
2699  return AVERROR_INVALIDDATA;
2700  st->codecpar->block_align = track->audio.sub_packet_size;
2701  extradata_offset = 78;
2702  }
2703  track->audio.buf = av_malloc_array(track->audio.sub_packet_h,
2704  track->audio.frame_size);
2705  if (!track->audio.buf)
2706  return AVERROR(ENOMEM);
2707  } else if (codec_id == AV_CODEC_ID_FLAC && track->codec_priv.size) {
2708  ret = matroska_parse_flac(s, track, &extradata_offset);
2709  if (ret < 0)
2710  return ret;
2711  } else if (codec_id == AV_CODEC_ID_WAVPACK && track->codec_priv.size < 2) {
2712  av_log(matroska->ctx, AV_LOG_INFO, "Assuming WavPack version 4.10 "
2713  "in absence of valid CodecPrivate.\n");
2714  extradata_size = 2;
2715  extradata = av_mallocz(2 + AV_INPUT_BUFFER_PADDING_SIZE);
2716  if (!extradata)
2717  return AVERROR(ENOMEM);
2718  AV_WL16(extradata, 0x410);
2719  } else if (codec_id == AV_CODEC_ID_PRORES && track->codec_priv.size == 4) {
2720  fourcc = AV_RL32(track->codec_priv.data);
2721  } else if (codec_id == AV_CODEC_ID_VP9 && track->codec_priv.size) {
2722  /* we don't need any value stored in CodecPrivate.
2723  make sure that it's not exported as extradata. */
2724  track->codec_priv.size = 0;
2725  }
2726  track->codec_priv.size -= extradata_offset;
2727 
2728  if (codec_id == AV_CODEC_ID_NONE)
2729  av_log(matroska->ctx, AV_LOG_INFO,
2730  "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
2731 
2732  if (track->time_scale < 0.01) {
2733  av_log(matroska->ctx, AV_LOG_WARNING,
2734  "Track TimestampScale too small %f, assuming 1.0.\n",
2735  track->time_scale);
2736  track->time_scale = 1.0;
2737  }
2738  avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
2739  1000 * 1000 * 1000); /* 64 bit pts in ns */
2740 
2741  /* convert the delay from ns to the track timebase */
2743  (AVRational){ 1, 1000000000 },
2744  st->time_base);
2745 
2746  st->codecpar->codec_id = codec_id;
2747 
2748  if (strcmp(track->language, "und"))
2749  av_dict_set(&st->metadata, "language", track->language, 0);
2750  av_dict_set(&st->metadata, "title", track->name, 0);
2751 
2752  if (track->flag_default)
2754  if (track->flag_forced)
2756  if (track->flag_comment)
2758  if (track->flag_hearingimpaired)
2760  if (track->flag_visualimpaired)
2762  if (track->flag_original.count > 0)
2765 
2766  if (!st->codecpar->extradata) {
2767  if (extradata) {
2768  st->codecpar->extradata = extradata;
2769  st->codecpar->extradata_size = extradata_size;
2770  } else if (track->codec_priv.data && track->codec_priv.size > 0) {
2771  if (ff_alloc_extradata(st->codecpar, track->codec_priv.size))
2772  return AVERROR(ENOMEM);
2773  memcpy(st->codecpar->extradata,
2774  track->codec_priv.data + extradata_offset,
2775  track->codec_priv.size);
2776  }
2777  }
2778 
2779  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2781  int display_width_mul = 1;
2782  int display_height_mul = 1;
2783 
2785  st->codecpar->codec_tag = fourcc;
2786  if (bit_depth >= 0)
2788  st->codecpar->width = track->video.pixel_width;
2789  st->codecpar->height = track->video.pixel_height;
2790 
2792  st->codecpar->field_order = mkv_field_order(matroska, track->video.field_order);
2795 
2797  mkv_stereo_mode_display_mul(track->video.stereo_mode, &display_width_mul, &display_height_mul);
2798 
2801  &st->sample_aspect_ratio.den,
2802  st->codecpar->height * track->video.display_width * display_width_mul,
2803  st->codecpar->width * track->video.display_height * display_height_mul,
2804  255);
2805  }
2806  if (st->codecpar->codec_id != AV_CODEC_ID_HEVC)
2808 
2809  if (track->default_duration) {
2810  int div = track->default_duration <= INT64_MAX ? 1 : 2;
2812  1000000000 / div, track->default_duration / div, 30000);
2813 #if FF_API_R_FRAME_RATE
2814  if ( st->avg_frame_rate.num < st->avg_frame_rate.den * 1000LL
2815  && st->avg_frame_rate.num > st->avg_frame_rate.den * 5LL)
2816  st->r_frame_rate = st->avg_frame_rate;
2817 #endif
2818  }
2819 
2820  /* export stereo mode flag as metadata tag */
2822  av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
2823 
2824  /* export alpha mode flag as metadata tag */
2825  if (track->video.alpha_mode)
2826  av_dict_set(&st->metadata, "alpha_mode", "1", 0);
2827 
2828  /* if we have virtual track, mark the real tracks */
2829  for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
2830  char buf[32];
2832  continue;
2833  snprintf(buf, sizeof(buf), "%s_%d",
2835  for (k=0; k < matroska->tracks.nb_elem; k++)
2836  if (planes[j].uid == tracks[k].uid && tracks[k].stream) {
2837  av_dict_set(&tracks[k].stream->metadata,
2838  "stereo_mode", buf, 0);
2839  break;
2840  }
2841  }
2842  // add stream level stereo3d side data if it is a supported format
2844  track->video.stereo_mode != 10 && track->video.stereo_mode != 12) {
2845  int ret = ff_mkv_stereo3d_conv(st, track->video.stereo_mode);
2846  if (ret < 0)
2847  return ret;
2848  }
2849 
2850  ret = mkv_parse_video_color(st, track);
2851  if (ret < 0)
2852  return ret;
2853  ret = mkv_parse_video_projection(st, track, matroska->ctx);
2854  if (ret < 0)
2855  return ret;
2856  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2858  st->codecpar->codec_tag = fourcc;
2859  st->codecpar->sample_rate = track->audio.out_samplerate;
2860  st->codecpar->channels = track->audio.channels;
2861  if (!st->codecpar->bits_per_coded_sample)
2863  if (st->codecpar->codec_id == AV_CODEC_ID_MP3 ||
2864  st->codecpar->codec_id == AV_CODEC_ID_MLP ||
2867  else if (st->codecpar->codec_id != AV_CODEC_ID_AAC)
2869  if (track->codec_delay > 0) {
2871  (AVRational){1, 1000000000},
2872  (AVRational){1, st->codecpar->codec_id == AV_CODEC_ID_OPUS ?
2873  48000 : st->codecpar->sample_rate});
2874  }
2875  if (track->seek_preroll > 0) {
2877  (AVRational){1, 1000000000},
2878  (AVRational){1, st->codecpar->sample_rate});
2879  }
2880  } else if (codec_id == AV_CODEC_ID_WEBVTT) {
2882 
2883  if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
2885  } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
2887  } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
2889  }
2890  } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2892 
2893  if (track->flag_textdescriptions)
2895  }
2896  }
2897 
2898  return 0;
2899 }
2900 
2902 {
2903  FFFormatContext *const si = ffformatcontext(s);
2904  MatroskaDemuxContext *matroska = s->priv_data;
2905  EbmlList *attachments_list = &matroska->attachments;
2906  EbmlList *chapters_list = &matroska->chapters;
2907  MatroskaAttachment *attachments;
2908  MatroskaChapter *chapters;
2909  uint64_t max_start = 0;
2910  int64_t pos;
2911  Ebml ebml = { 0 };
2912  int i, j, res;
2913 
2914  matroska->ctx = s;
2915  matroska->cues_parsing_deferred = 1;
2916 
2917  /* First read the EBML header. */
2918  if (ebml_parse(matroska, ebml_syntax, &ebml) || !ebml.doctype) {
2919  av_log(matroska->ctx, AV_LOG_ERROR, "EBML header parsing failed\n");
2920  ebml_free(ebml_syntax, &ebml);
2921  return AVERROR_INVALIDDATA;
2922  }
2923  if (ebml.version > EBML_VERSION ||
2924  ebml.max_size > sizeof(uint64_t) ||
2925  ebml.id_length > sizeof(uint32_t) ||
2926  ebml.doctype_version > 3) {
2928  "EBML version %"PRIu64", doctype %s, doc version %"PRIu64,
2929  ebml.version, ebml.doctype, ebml.doctype_version);
2930  ebml_free(ebml_syntax, &ebml);
2931  return AVERROR_PATCHWELCOME;
2932  } else if (ebml.doctype_version == 3) {
2933  av_log(matroska->ctx, AV_LOG_WARNING,
2934  "EBML header using unsupported features\n"
2935  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
2936  ebml.version, ebml.doctype, ebml.doctype_version);
2937  }
2938  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
2939  if (!strcmp(ebml.doctype, matroska_doctypes[i]))
2940  break;
2942  av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
2943  if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
2944  ebml_free(ebml_syntax, &ebml);
2945  return AVERROR_INVALIDDATA;
2946  }
2947  }
2948  ebml_free(ebml_syntax, &ebml);
2949 
2950  matroska->pkt = si->parse_pkt;
2951 
2952  /* The next thing is a segment. */
2953  pos = avio_tell(matroska->ctx->pb);
2954  res = ebml_parse(matroska, matroska_segments, matroska);
2955  // Try resyncing until we find an EBML_STOP type element.
2956  while (res != 1) {
2957  res = matroska_resync(matroska, pos);
2958  if (res < 0)
2959  return res;
2960  pos = avio_tell(matroska->ctx->pb);
2961  res = ebml_parse(matroska, matroska_segment, matroska);
2962  if (res == AVERROR(EIO)) // EOF is translated to EIO, this exists the loop on EOF
2963  return res;
2964  }
2965  /* Set data_offset as it might be needed later by seek_frame_generic. */
2966  if (matroska->current_id == MATROSKA_ID_CLUSTER)
2967  si->data_offset = avio_tell(matroska->ctx->pb) - 4;
2968  matroska_execute_seekhead(matroska);
2969 
2970  if (!matroska->time_scale)
2971  matroska->time_scale = 1000000;
2972  if (matroska->duration)
2973  matroska->ctx->duration = matroska->duration * matroska->time_scale *
2974  1000 / AV_TIME_BASE;
2975  av_dict_set(&s->metadata, "title", matroska->title, 0);
2976  av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
2977 
2978  if (matroska->date_utc.size == 8)
2979  matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
2980 
2981  res = matroska_parse_tracks(s);
2982  if (res < 0)
2983  return res;
2984 
2985  attachments = attachments_list->elem;
2986  for (j = 0; j < attachments_list->nb_elem; j++) {
2987  if (!(attachments[j].filename && attachments[j].mime &&
2988  attachments[j].bin.data && attachments[j].bin.size > 0)) {
2989  av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2990  } else {
2992  if (!st)
2993  break;
2994  av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
2995  av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
2996  if (attachments[j].description)
2997  av_dict_set(&st->metadata, "title", attachments[j].description, 0);
2999 
3000  for (i = 0; mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
3001  if (av_strstart(attachments[j].mime, mkv_image_mime_tags[i].str, NULL)) {
3003  break;
3004  }
3005  }
3006 
3007  attachments[j].stream = st;
3008 
3009  if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
3010  res = ff_add_attached_pic(s, st, NULL, &attachments[j].bin.buf, 0);
3011  if (res < 0)
3012  return res;
3013  } else {
3015  if (ff_alloc_extradata(st->codecpar, attachments[j].bin.size))
3016  break;
3017  memcpy(st->codecpar->extradata, attachments[j].bin.data,
3018  attachments[j].bin.size);
3019 
3020  for (i = 0; mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
3021  if (av_strstart(attachments[j].mime, mkv_mime_tags[i].str, NULL)) {
3023  break;
3024  }
3025  }
3026  }
3027  }
3028  }
3029 
3030  chapters = chapters_list->elem;
3031  for (i = 0; i < chapters_list->nb_elem; i++)
3032  if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
3033  (max_start == 0 || chapters[i].start > max_start)) {
3034  chapters[i].chapter =
3035  avpriv_new_chapter(s, chapters[i].uid,
3036  (AVRational) { 1, 1000000000 },
3037  chapters[i].start, chapters[i].end,
3038  chapters[i].title);
3039  max_start = chapters[i].start;
3040  }
3041 
3042  matroska_add_index_entries(matroska);
3043 
3045 
3046  return 0;
3048 
3049 /*
3050  * Put one packet in an application-supplied AVPacket struct.
3051  * Returns 0 on success or -1 on failure.
3052  */
3053 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
3054  AVPacket *pkt)
3055 {
3056  if (matroska->queue) {
3057  MatroskaTrack *tracks = matroska->tracks.elem;
3058  MatroskaTrack *track;
3059 
3060  avpriv_packet_list_get(&matroska->queue, &matroska->queue_end, pkt);
3061  track = &tracks[pkt->stream_index];
3062  if (track->has_palette) {
3064  if (!pal) {
3065  av_log(matroska->ctx, AV_LOG_ERROR, "Cannot append palette to packet\n");
3066  } else {
3067  memcpy(pal, track->palette, AVPALETTE_SIZE);
3068  }
3069  track->has_palette = 0;
3070  }
3071  return 0;
3072  }
3073 
3074  return -1;
3075 }
3076 
3077 /*
3078  * Free all packets in our internal queue.
3079  */
3080 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
3081 {
3082  avpriv_packet_list_free(&matroska->queue, &matroska->queue_end);
3083 }
3084 
3085 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
3086  int size, int type, AVIOContext *pb,
3087  uint32_t lace_size[256], int *laces)
3088 {
3089  int n;
3090  uint8_t *data = *buf;
3091 
3092  if (!type) {
3093  *laces = 1;
3094  lace_size[0] = size;
3095  return 0;
3096  }
3097 
3098  if (size <= 0)
3099  return AVERROR_INVALIDDATA;
3100 
3101  *laces = *data + 1;
3102  data += 1;
3103  size -= 1;
3104 
3105  switch (type) {
3106  case 0x1: /* Xiph lacing */
3107  {
3108  uint8_t temp;
3109  uint32_t total = 0;
3110  for (n = 0; n < *laces - 1; n++) {
3111  lace_size[n] = 0;
3112 
3113  do {
3114  if (size <= total)
3115  return AVERROR_INVALIDDATA;
3116  temp = *data;
3117  total += temp;
3118  lace_size[n] += temp;
3119  data += 1;
3120  size -= 1;
3121  } while (temp == 0xff);
3122  }
3123  if (size < total)
3124  return AVERROR_INVALIDDATA;
3125 
3126  lace_size[n] = size - total;
3127  break;
3128  }
3129 
3130  case 0x2: /* fixed-size lacing */
3131  if (size % (*laces))
3132  return AVERROR_INVALIDDATA;
3133  for (n = 0; n < *laces; n++)
3134  lace_size[n] = size / *laces;
3135  break;
3136 
3137  case 0x3: /* EBML lacing */
3138  {
3139  uint64_t num;
3140  uint64_t total;
3141  int offset;
3142 
3143  avio_skip(pb, 4);
3144 
3145  n = ebml_read_num(matroska, pb, 8, &num, 1);
3146  if (n < 0)
3147  return n;
3148  if (num > INT_MAX)
3149  return AVERROR_INVALIDDATA;
3150 
3151  total = lace_size[0] = num;
3152  offset = n;
3153  for (n = 1; n < *laces - 1; n++) {
3154  int64_t snum;
3155  int r;
3156  r = matroska_ebmlnum_sint(matroska, pb, &snum);
3157  if (r < 0)
3158  return r;
3159  if (lace_size[n - 1] + snum > (uint64_t)INT_MAX)
3160  return AVERROR_INVALIDDATA;
3161 
3162  lace_size[n] = lace_size[n - 1] + snum;
3163  total += lace_size[n];
3164  offset += r;
3165  }
3166  data += offset;
3167  size -= offset;
3168  if (size < total)
3169  return AVERROR_INVALIDDATA;
3170 
3171  lace_size[*laces - 1] = size - total;
3172  break;
3173  }
3174  }
3176  *buf = data;
3177 
3178  return 0;
3179 }
3180 
3181 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
3182  MatroskaTrack *track, AVStream *st,
3183  uint8_t *data, int size, uint64_t timecode,
3184  int64_t pos)
3185 {
3186  const int a = st->codecpar->block_align;
3187  const int sps = track->audio.sub_packet_size;
3188  const int cfs = track->audio.coded_framesize;
3189  const int h = track->audio.sub_packet_h;
3190  const int w = track->audio.frame_size;
3191  int y = track->audio.sub_packet_cnt;
3192  int x;
3193 
3194  if (!track->audio.pkt_cnt) {
3195  if (track->audio.sub_packet_cnt == 0)
3196  track->audio.buf_timecode = timecode;
3197  if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
3198  if (size < cfs * h / 2) {
3199  av_log(matroska->ctx, AV_LOG_ERROR,
3200  "Corrupt int4 RM-style audio packet size\n");
3201  return AVERROR_INVALIDDATA;
3202  }
3203  for (x = 0; x < h / 2; x++)
3204  memcpy(track->audio.buf + x * 2 * w + y * cfs,
3205  data + x * cfs, cfs);
3206  } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
3207  if (size < w) {
3208  av_log(matroska->ctx, AV_LOG_ERROR,
3209  "Corrupt sipr RM-style audio packet size\n");
3210  return AVERROR_INVALIDDATA;
3211  }
3212  memcpy(track->audio.buf + y * w, data, w);
3213  } else {
3214  if (size < w) {
3215  av_log(matroska->ctx, AV_LOG_ERROR,
3216  "Corrupt generic RM-style audio packet size\n");
3217  return AVERROR_INVALIDDATA;
3218  }
3219  for (x = 0; x < w / sps; x++)
3220  memcpy(track->audio.buf +
3221  sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
3222  data + x * sps, sps);
3223  }
3224 
3225  if (++track->audio.sub_packet_cnt >= h) {
3226  if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
3227  ff_rm_reorder_sipr_data(track->audio.buf, h, w);
3228  track->audio.sub_packet_cnt = 0;
3229  track->audio.pkt_cnt = h * w / a;
3230  }
3231  }
3232 
3233  while (track->audio.pkt_cnt) {
3234  int ret;
3235  AVPacket *pkt = matroska->pkt;
3236 
3237  ret = av_new_packet(pkt, a);
3238  if (ret < 0) {
3239  return ret;
3240  }
3241  memcpy(pkt->data,
3242  track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
3243  a);
3244  pkt->pts = track->audio.buf_timecode;
3246  pkt->pos = pos;
3247  pkt->stream_index = st->index;
3248  ret = avpriv_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, NULL, 0);
3249  if (ret < 0) {
3251  return AVERROR(ENOMEM);
3252  }
3253  }
3254 
3255  return 0;
3256 }
3257 
3258 /* reconstruct full wavpack blocks from mangled matroska ones */
3259 static int matroska_parse_wavpack(MatroskaTrack *track,
3260  uint8_t **data, int *size)
3261 {
3262  uint8_t *dst = NULL;
3263  uint8_t *src = *data;
3264  int dstlen = 0;
3265  int srclen = *size;
3266  uint32_t samples;
3267  uint16_t ver;
3268  int ret, offset = 0;
3269 
3270  if (srclen < 12)
3271  return AVERROR_INVALIDDATA;
3272 
3273  av_assert1(track->stream->codecpar->extradata_size >= 2);
3274  ver = AV_RL16(track->stream->codecpar->extradata);
3275 
3276  samples = AV_RL32(src);
3277  src += 4;
3278  srclen -= 4;
3279 
3280  while (srclen >= 8) {
3281  int multiblock;
3282  uint32_t blocksize;
3283  uint8_t *tmp;
3284 
3285  uint32_t flags = AV_RL32(src);
3286  uint32_t crc = AV_RL32(src + 4);
3287  src += 8;
3288  srclen -= 8;
3289 
3290  multiblock = (flags & 0x1800) != 0x1800;
3291  if (multiblock) {
3292  if (srclen < 4) {
3294  goto fail;
3295  }
3296  blocksize = AV_RL32(src);
3297  src += 4;
3298  srclen -= 4;
3299  } else
3300  blocksize = srclen;
3301 
3302  if (blocksize > srclen) {
3304  goto fail;
3305  }
3306 
3307  tmp = av_realloc(dst, dstlen + blocksize + 32 + AV_INPUT_BUFFER_PADDING_SIZE);
3308  if (!tmp) {
3309  ret = AVERROR(ENOMEM);
3310  goto fail;
3311  }
3312  dst = tmp;
3313  dstlen += blocksize + 32;
3314 
3315  AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
3316  AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
3317  AV_WL16(dst + offset + 8, ver); // version
3318  AV_WL16(dst + offset + 10, 0); // track/index_no
3319  AV_WL32(dst + offset + 12, 0); // total samples
3320  AV_WL32(dst + offset + 16, 0); // block index
3321  AV_WL32(dst + offset + 20, samples); // number of samples
3322  AV_WL32(dst + offset + 24, flags); // flags
3323  AV_WL32(dst + offset + 28, crc); // crc
3324  memcpy(dst + offset + 32, src, blocksize); // block data
3325 
3326  src += blocksize;
3327  srclen -= blocksize;
3328  offset += blocksize + 32;
3329  }
3330 
3331  memset(dst + dstlen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3332 
3333  *data = dst;
3334  *size = dstlen;
3335 
3336  return 0;
3338 fail:
3339  av_freep(&dst);
3340  return ret;
3341 }
3342 
3343 static int matroska_parse_prores(MatroskaTrack *track,
3344  uint8_t **data, int *size)
3345 {
3346  uint8_t *dst;
3347  int dstlen = *size + 8;
3348 
3349  dst = av_malloc(dstlen + AV_INPUT_BUFFER_PADDING_SIZE);
3350  if (!dst)
3351  return AVERROR(ENOMEM);
3352 
3353  AV_WB32(dst, dstlen);
3354  AV_WB32(dst + 4, MKBETAG('i', 'c', 'p', 'f'));
3355  memcpy(dst + 8, *data, dstlen - 8);
3356  memset(dst + dstlen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3357 
3358  *data = dst;
3359  *size = dstlen;
3360 
3361  return 0;
3362 }
3363 
3364 static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
3365  MatroskaTrack *track,
3366  AVStream *st,
3367  uint8_t *data, int data_len,
3368  uint64_t timecode,
3369  uint64_t duration,
3370  int64_t pos)
3371 {
3372  AVPacket *pkt = matroska->pkt;
3373  uint8_t *id, *settings, *text, *buf;
3374  int id_len, settings_len, text_len;
3375  uint8_t *p, *q;
3376  int err;
3377 
3378  if (data_len <= 0)
3379  return AVERROR_INVALIDDATA;
3380 
3381  p = data;
3382  q = data + data_len;
3383 
3384  id = p;
3385  id_len = -1;
3386  while (p < q) {
3387  if (*p == '\r' || *p == '\n') {
3388  id_len = p - id;
3389  if (*p == '\r')
3390  p++;
3391  break;
3392  }
3393  p++;
3394  }
3395 
3396  if (p >= q || *p != '\n')
3397  return AVERROR_INVALIDDATA;
3398  p++;
3399 
3400  settings = p;
3401  settings_len = -1;
3402  while (p < q) {
3403  if (*p == '\r' || *p == '\n') {
3404  settings_len = p - settings;
3405  if (*p == '\r')
3406  p++;
3407  break;
3408  }
3409  p++;
3410  }
3411 
3412  if (p >= q || *p != '\n')
3413  return AVERROR_INVALIDDATA;
3414  p++;
3415 
3416  text = p;
3417  text_len = q - p;
3418  while (text_len > 0) {
3419  const int len = text_len - 1;
3420  const uint8_t c = p[len];
3421  if (c != '\r' && c != '\n')
3422  break;
3423  text_len = len;
3424  }
3425 
3426  if (text_len <= 0)
3427  return AVERROR_INVALIDDATA;
3428 
3429  err = av_new_packet(pkt, text_len);
3430  if (err < 0) {
3431  return err;
3432  }
3433 
3434  memcpy(pkt->data, text, text_len);
3435 
3436  if (id_len > 0) {
3439  id_len);
3440  if (!buf) {
3442  return AVERROR(ENOMEM);
3443  }
3444  memcpy(buf, id, id_len);
3445  }
3446 
3447  if (settings_len > 0) {
3450  settings_len);
3451  if (!buf) {
3453  return AVERROR(ENOMEM);
3454  }
3455  memcpy(buf, settings, settings_len);
3456  }
3457 
3458  // Do we need this for subtitles?
3459  // pkt->flags = AV_PKT_FLAG_KEY;
3460 
3461  pkt->stream_index = st->index;
3462  pkt->pts = timecode;
3463 
3464  // Do we need this for subtitles?
3465  // pkt->dts = timecode;
3466 
3467  pkt->duration = duration;
3468  pkt->pos = pos;
3469 
3470  err = avpriv_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, NULL, 0);
3471  if (err < 0) {
3473  return AVERROR(ENOMEM);
3474  }
3475 
3476  return 0;
3477 }
3478 
3479 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
3480  MatroskaTrack *track, AVStream *st,
3481  AVBufferRef *buf, uint8_t *data, int pkt_size,
3482  uint64_t timecode, uint64_t lace_duration,
3483  int64_t pos, int is_keyframe,
3484  uint8_t *additional, uint64_t additional_id, int additional_size,
3485  int64_t discard_padding)
3486 {
3487  uint8_t *pkt_data = data;
3488  int res = 0;
3489  AVPacket *pkt = matroska->pkt;
3490 
3491  if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
3492  res = matroska_parse_wavpack(track, &pkt_data, &pkt_size);
3493  if (res < 0) {
3494  av_log(matroska->ctx, AV_LOG_ERROR,
3495  "Error parsing a wavpack block.\n");
3496  goto fail;
3497  }
3498  if (!buf)
3499  av_freep(&data);
3500  buf = NULL;
3501  }
3502 
3503  if (st->codecpar->codec_id == AV_CODEC_ID_PRORES &&
3504  AV_RB32(pkt_data + 4) != MKBETAG('i', 'c', 'p', 'f')) {
3505  res = matroska_parse_prores(track, &pkt_data, &pkt_size);
3506  if (res < 0) {
3507  av_log(matroska->ctx, AV_LOG_ERROR,
3508  "Error parsing a prores block.\n");
3509  goto fail;
3510  }
3511  if (!buf)
3512  av_freep(&data);
3513  buf = NULL;
3514  }
3515 
3516  if (!pkt_size && !additional_size)
3517  goto no_output;
3518 
3519  if (!buf)
3520  pkt->buf = av_buffer_create(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE,
3521  NULL, NULL, 0);
3522  else
3523  pkt->buf = av_buffer_ref(buf);
3524 
3525  if (!pkt->buf) {
3526  res = AVERROR(ENOMEM);
3527  goto fail;
3528  }
3529 
3530  pkt->data = pkt_data;
3531  pkt->size = pkt_size;
3532  pkt->flags = is_keyframe;
3533  pkt->stream_index = st->index;
3534 
3535  if (additional_size > 0) {
3536  uint8_t *side_data = av_packet_new_side_data(pkt,
3538  additional_size + 8);
3539  if (!side_data) {
3541  return AVERROR(ENOMEM);
3542  }
3543  AV_WB64(side_data, additional_id);
3544  memcpy(side_data + 8, additional, additional_size);
3545  }
3546 
3547  if (discard_padding) {
3548  uint8_t *side_data = av_packet_new_side_data(pkt,
3550  10);
3551  if (!side_data) {
3553  return AVERROR(ENOMEM);
3554  }
3555  discard_padding = av_rescale_q(discard_padding,
3556  (AVRational){1, 1000000000},
3557  (AVRational){1, st->codecpar->sample_rate});
3558  if (discard_padding > 0) {
3559  AV_WL32(side_data + 4, discard_padding);
3560  } else {
3561  AV_WL32(side_data, -discard_padding);
3562  }
3563  }
3564 
3565  if (track->ms_compat)
3566  pkt->dts = timecode;
3567  else
3568  pkt->pts = timecode;
3569  pkt->pos = pos;
3570  pkt->duration = lace_duration;
3571 
3572  res = avpriv_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, NULL, 0);
3573  if (res < 0) {
3575  return AVERROR(ENOMEM);
3576  }
3577 
3578  return 0;
3579 
3580 no_output:
3582  if (!buf)
3583  av_free(pkt_data);
3584  return res;
3585 }
3586 
3587 static int matroska_parse_block(MatroskaDemuxContext *matroska, AVBufferRef *buf, uint8_t *data,
3588  int size, int64_t pos, uint64_t cluster_time,
3589  uint64_t block_duration, int is_keyframe,
3590  uint8_t *additional, uint64_t additional_id, int additional_size,
3591  int64_t cluster_pos, int64_t discard_padding)
3592 {
3593  uint64_t timecode = AV_NOPTS_VALUE;
3594  MatroskaTrack *track;
3595  FFIOContext pb;
3596  int res = 0;
3597  AVStream *st;
3598  int16_t block_time;
3599  uint32_t lace_size[256];
3600  int n, flags, laces = 0;
3601  uint64_t num;
3602  int trust_default_duration;
3603 
3604  ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
3605 
3606  if ((n = ebml_read_num(matroska, &pb.pub, 8, &num, 1)) < 0)
3607  return n;
3608  data += n;
3609  size -= n;
3610 
3611  track = matroska_find_track_by_num(matroska, num);
3612  if (!track || size < 3)
3613  return AVERROR_INVALIDDATA;
3614 
3615  if (!(st = track->stream)) {
3616  av_log(matroska->ctx, AV_LOG_VERBOSE,
3617  "No stream associated to TrackNumber %"PRIu64". "
3618  "Ignoring Block with this TrackNumber.\n", num);
3619  return 0;
3620  }
3621 
3622  if (st->discard >= AVDISCARD_ALL)
3623  return res;
3624  if (block_duration > INT64_MAX)
3625  block_duration = INT64_MAX;
3626 
3627  block_time = sign_extend(AV_RB16(data), 16);
3628  data += 2;
3629  flags = *data++;
3630  size -= 3;
3631  if (is_keyframe == -1)
3632  is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
3633 
3634  if (cluster_time != (uint64_t) -1 &&
3635  (block_time >= 0 || cluster_time >= -block_time)) {
3636  uint64_t timecode_cluster_in_track_tb = (double) cluster_time / track->time_scale;
3637  timecode = timecode_cluster_in_track_tb + block_time - track->codec_delay_in_track_tb;
3638  if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
3639  timecode < track->end_timecode)
3640  is_keyframe = 0; /* overlapping subtitles are not key frame */
3641  if (is_keyframe) {
3642  ff_reduce_index(matroska->ctx, st->index);
3643  av_add_index_entry(st, cluster_pos, timecode, 0, 0,
3645  }
3646  }
3647 
3648  if (matroska->skip_to_keyframe &&
3649  track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
3650  // Compare signed timecodes. Timecode may be negative due to codec delay
3651  // offset. We don't support timestamps greater than int64_t anyway - see
3652  // AVPacket's pts.
3653  if ((int64_t)timecode < (int64_t)matroska->skip_to_timecode)
3654  return res;
3655  if (is_keyframe)
3656  matroska->skip_to_keyframe = 0;
3657  else if (!ffstream(st)->skip_to_keyframe) {
3658  av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
3659  matroska->skip_to_keyframe = 0;
3660  }
3661  }
3662 
3663  res = matroska_parse_laces(matroska, &data, size, (flags & 0x06) >> 1,
3664  &pb.pub, lace_size, &laces);
3665  if (res < 0) {
3666  av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing frame sizes.\n");
3667  return res;
3668  }
3669 
3670  trust_default_duration = track->default_duration != 0;
3671  if (track->audio.samplerate == 8000 && trust_default_duration) {
3672  // If this is needed for more codecs, then add them here
3673  if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
3674  if (track->audio.samplerate != st->codecpar->sample_rate || !st->codecpar->frame_size)
3675  trust_default_duration = 0;
3676  }
3677  }
3678 
3679  if (!block_duration && trust_default_duration)
3680  block_duration = track->default_duration * laces / matroska->time_scale;
3681 
3682  if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
3683  track->end_timecode =
3684  FFMAX(track->end_timecode, timecode + block_duration);
3685 
3686  for (n = 0; n < laces; n++) {
3687  int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
3688  uint8_t *out_data = data;
3689  int out_size = lace_size[n];
3690 
3691  if (track->needs_decoding) {
3692  res = matroska_decode_buffer(&out_data, &out_size, track);
3693  if (res < 0)
3694  return res;
3695  /* Given that we are here means that out_data is no longer
3696  * owned by buf, so set it to NULL. This depends upon
3697  * zero-length header removal compression being ignored. */
3698  av_assert1(out_data != data);
3699  buf = NULL;
3700  }
3701 
3702  if (track->audio.buf) {
3703  res = matroska_parse_rm_audio(matroska, track, st,
3704  out_data, out_size,
3705  timecode, pos);
3706  if (!buf)
3707  av_free(out_data);
3708  if (res)
3709  return res;
3710  } else if (st->codecpar->codec_id == AV_CODEC_ID_WEBVTT) {
3711  res = matroska_parse_webvtt(matroska, track, st,
3712  out_data, out_size,
3713  timecode, lace_duration,
3714  pos);
3715  if (!buf)
3716  av_free(out_data);
3717  if (res)
3718  return res;
3719  } else {
3720  res = matroska_parse_frame(matroska, track, st, buf, out_data,
3721  out_size, timecode, lace_duration,
3722  pos, !n ? is_keyframe : 0,
3723  additional, additional_id, additional_size,
3724  discard_padding);
3725  if (res)
3726  return res;
3727  }
3728 
3729  if (timecode != AV_NOPTS_VALUE)
3730  timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
3731  data += lace_size[n];
3732  }
3733 
3734  return 0;
3735 }
3736 
3737 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
3738 {
3739  MatroskaCluster *cluster = &matroska->current_cluster;
3740  MatroskaBlock *block = &cluster->block;
3741  int res;
3742 
3743  av_assert0(matroska->num_levels <= 2);
3744 
3745  if (matroska->num_levels == 1) {
3746  res = ebml_parse(matroska, matroska_segment, NULL);
3747 
3748  if (res == 1) {
3749  /* Found a cluster: subtract the size of the ID already read. */
3750  cluster->pos = avio_tell(matroska->ctx->pb) - 4;
3751 
3752  res = ebml_parse(matroska, matroska_cluster_enter, cluster);
3753  if (res < 0)
3754  return res;
3755  }
3756  }
3757 
3758  if (matroska->num_levels == 2) {
3759  /* We are inside a cluster. */
3760  res = ebml_parse(matroska, matroska_cluster_parsing, cluster);
3761 
3762  if (res >= 0 && block->bin.size > 0) {
3763  int is_keyframe = block->non_simple ? block->reference.count == 0 : -1;
3764  uint8_t* additional = block->additional.size > 0 ?
3765  block->additional.data : NULL;
3766 
3767  res = matroska_parse_block(matroska, block->bin.buf, block->bin.data,
3768  block->bin.size, block->bin.pos,
3769  cluster->timecode, block->duration,
3770  is_keyframe, additional, block->additional_id,
3771  block->additional.size, cluster->pos,
3772  block->discard_padding);
3773  }
3774 
3776  memset(block, 0, sizeof(*block));
3777  } else if (!matroska->num_levels) {
3778  if (!avio_feof(matroska->ctx->pb)) {
3779  avio_r8(matroska->ctx->pb);
3780  if (!avio_feof(matroska->ctx->pb)) {
3781  av_log(matroska->ctx, AV_LOG_WARNING, "File extends beyond "
3782  "end of segment.\n");
3783  return AVERROR_INVALIDDATA;
3784  }
3785  }
3786  matroska->done = 1;
3787  return AVERROR_EOF;
3788  }
3789 
3790  return res;
3791 }
3792 
3794 {
3795  MatroskaDemuxContext *matroska = s->priv_data;
3796  int ret = 0;
3797 
3798  if (matroska->resync_pos == -1) {
3799  // This can only happen if generic seeking has been used.
3800  matroska->resync_pos = avio_tell(s->pb);
3801  }
3802 
3803  while (matroska_deliver_packet(matroska, pkt)) {
3804  if (matroska->done)
3805  return (ret < 0) ? ret : AVERROR_EOF;
3806  if (matroska_parse_cluster(matroska) < 0 && !matroska->done)
3807  ret = matroska_resync(matroska, matroska->resync_pos);
3808  }
3809 
3810  return 0;
3811 }
3812 
3813 static int matroska_read_seek(AVFormatContext *s, int stream_index,
3814  int64_t timestamp, int flags)
3815 {
3816  MatroskaDemuxContext *matroska = s->priv_data;
3817  MatroskaTrack *tracks = NULL;
3818  AVStream *st = s->streams[stream_index];
3819  FFStream *const sti = ffstream(st);
3820  int i, index;
3821 
3822  /* Parse the CUES now since we need the index data to seek. */
3823  if (matroska->cues_parsing_deferred > 0) {
3824  matroska->cues_parsing_deferred = 0;
3825  matroska_parse_cues(matroska);
3826  }
3827 
3828  if (!sti->nb_index_entries)
3829  goto err;
3830  timestamp = FFMAX(timestamp, sti->index_entries[0].timestamp);
3831 
3832  if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 ||
3833  index == sti->nb_index_entries - 1) {
3834  matroska_reset_status(matroska, 0, sti->index_entries[sti->nb_index_entries - 1].pos);
3835  while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 ||
3836  index == sti->nb_index_entries - 1) {
3837  matroska_clear_queue(matroska);
3838  if (matroska_parse_cluster(matroska) < 0)
3839  break;
3840  }
3841  }
3842 
3843  matroska_clear_queue(matroska);
3844  if (index < 0 || (matroska->cues_parsing_deferred < 0 &&
3845  index == sti->nb_index_entries - 1))
3846  goto err;
3847 
3848  tracks = matroska->tracks.elem;
3849  for (i = 0; i < matroska->tracks.nb_elem; i++) {
3850  tracks[i].audio.pkt_cnt = 0;
3851  tracks[i].audio.sub_packet_cnt = 0;
3852  tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
3853  tracks[i].end_timecode = 0;
3854  }
3855 
3856  /* We seek to a level 1 element, so set the appropriate status. */
3857  matroska_reset_status(matroska, 0, sti->index_entries[index].pos);
3858  if (flags & AVSEEK_FLAG_ANY) {
3859  sti->skip_to_keyframe = 0;
3860  matroska->skip_to_timecode = timestamp;
3861  } else {
3862  sti->skip_to_keyframe = 1;
3863  matroska->skip_to_timecode = sti->index_entries[index].timestamp;
3864  }
3865  matroska->skip_to_keyframe = 1;
3866  matroska->done = 0;
3868  return 0;
3869 err:
3870  // slightly hackish but allows proper fallback to
3871  // the generic seeking code.
3872  matroska_reset_status(matroska, 0, -1);
3873  matroska->resync_pos = -1;
3874  matroska_clear_queue(matroska);
3876  matroska->skip_to_keyframe = 0;
3877  matroska->done = 0;
3878  return -1;
3879 }
3880 
3882 {
3883  MatroskaDemuxContext *matroska = s->priv_data;
3884  MatroskaTrack *tracks = matroska->tracks.elem;
3885  int n;
3886 
3887  matroska_clear_queue(matroska);
3888 
3889  for (n = 0; n < matroska->tracks.nb_elem; n++)
3890  if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
3891  av_freep(&tracks[n].audio.buf);
3892  ebml_free(matroska_segment, matroska);
3893 
3894  return 0;
3895 }
3896 
3897 #if CONFIG_WEBM_DASH_MANIFEST_DEMUXER
3898 typedef struct {
3899  int64_t start_time_ns;
3900  int64_t end_time_ns;
3901  int64_t start_offset;
3902  int64_t end_offset;
3903 } CueDesc;
3904 
3905 /* This function searches all the Cues and returns the CueDesc corresponding to
3906  * the timestamp ts. Returned CueDesc will be such that start_time_ns <= ts <
3907  * end_time_ns. All 4 fields will be set to -1 if ts >= file's duration.
3908  */
3909 static CueDesc get_cue_desc(AVFormatContext *s, int64_t ts, int64_t cues_start) {
3910  MatroskaDemuxContext *matroska = s->priv_data;
3911  FFStream *const sti = ffstream(s->streams[0]);
3912  AVIndexEntry *const index_entries = sti->index_entries;
3913  int nb_index_entries = sti->nb_index_entries;
3914  CueDesc cue_desc;
3915  int i;
3916 
3917  if (ts >= matroska->duration * matroska->time_scale) return (CueDesc) {-1, -1, -1, -1};
3918  for (i = 1; i < nb_index_entries; i++) {
3919  if (index_entries[i - 1].timestamp * matroska->time_scale <= ts &&
3920  index_entries[i].timestamp * matroska->time_scale > ts) {
3921  break;
3922  }
3923  }
3924  --i;
3925  cue_desc.start_time_ns = index_entries[i].timestamp * matroska->time_scale;
3926  cue_desc.start_offset = index_entries[i].pos - matroska->segment_start;
3927  if (i != nb_index_entries - 1) {
3928  cue_desc.end_time_ns = index_entries[i + 1].timestamp * matroska->time_scale;
3929  cue_desc.end_offset = index_entries[i + 1].pos - matroska->segment_start;
3930  } else {
3931  cue_desc.end_time_ns = matroska->duration * matroska->time_scale;
3932  // FIXME: this needs special handling for files where Cues appear
3933  // before Clusters. the current logic assumes Cues appear after
3934  // Clusters.
3935  cue_desc.end_offset = cues_start - matroska->segment_start;
3936  }
3937  return cue_desc;
3938 }
3939 
3940 static int webm_clusters_start_with_keyframe(AVFormatContext *s)
3941 {
3942  MatroskaDemuxContext *matroska = s->priv_data;
3943  AVStream *const st = s->streams[0];
3944  FFStream *const sti = ffstream(st);
3945  uint32_t id = matroska->current_id;
3946  int64_t cluster_pos, before_pos;
3947  int index, rv = 1;
3948 
3949  if (sti->nb_index_entries <= 0)
3950  return 0;
3951 
3952  // seek to the first cluster using cues.
3953  index = av_index_search_timestamp(st, 0, 0);
3954  if (index < 0)
3955  return 0;
3956  cluster_pos = sti->index_entries[index].pos;
3957  before_pos = avio_tell(s->pb);
3958  while (1) {
3959  uint64_t cluster_id, cluster_length;
3960  int read;
3961  AVPacket *pkt;
3962  avio_seek(s->pb, cluster_pos, SEEK_SET);
3963  // read cluster id and length
3964  read = ebml_read_num(matroska, matroska->ctx->pb, 4, &cluster_id, 1);
3965  if (read < 0 || cluster_id != 0xF43B675) // done with all clusters
3966  break;
3967  read = ebml_read_length(matroska, matroska->ctx->pb, &cluster_length);
3968  if (read < 0)
3969  break;
3970 
3971  matroska_reset_status(matroska, 0, cluster_pos);
3972  matroska_clear_queue(matroska);
3973  if (matroska_parse_cluster(matroska) < 0 ||
3974  !matroska->queue) {
3975  break;
3976  }
3977  pkt = &matroska->queue->pkt;
3978  // 4 + read is the length of the cluster id and the cluster length field.
3979  cluster_pos += 4 + read + cluster_length;
3980  if (!(pkt->flags & AV_PKT_FLAG_KEY)) {
3981  rv = 0;
3982  break;
3983  }
3984  }
3985 
3986  /* Restore the status after matroska_read_header: */
3987  matroska_reset_status(matroska, id, before_pos);
3988 
3989  return rv;
3990 }
3991 
3992 static int buffer_size_after_time_downloaded(int64_t time_ns, double search_sec, int64_t bps,
3993  double min_buffer, double* buffer,
3994  double* sec_to_download, AVFormatContext *s,
3995  int64_t cues_start)
3996 {
3997  double nano_seconds_per_second = 1000000000.0;
3998  double time_sec = time_ns / nano_seconds_per_second;
3999  int rv = 0;
4000  int64_t time_to_search_ns = (int64_t)(search_sec * nano_seconds_per_second);
4001  int64_t end_time_ns = time_ns + time_to_search_ns;
4002  double sec_downloaded = 0.0;
4003  CueDesc desc_curr = get_cue_desc(s, time_ns, cues_start);
4004  if (desc_curr.start_time_ns == -1)
4005  return -1;
4006  *sec_to_download = 0.0;
4007 
4008  // Check for non cue start time.
4009  if (time_ns > desc_curr.start_time_ns) {
4010  int64_t cue_nano = desc_curr.end_time_ns - time_ns;
4011  double percent = (double)(cue_nano) / (desc_curr.end_time_ns - desc_curr.start_time_ns);
4012  double cueBytes = (desc_curr.end_offset - desc_curr.start_offset) * percent;
4013  double timeToDownload = (cueBytes * 8.0) / bps;
4014 
4015  sec_downloaded += (cue_nano / nano_seconds_per_second) - timeToDownload;
4016  *sec_to_download += timeToDownload;
4017 
4018  // Check if the search ends within the first cue.
4019  if (desc_curr.end_time_ns >= end_time_ns) {
4020  double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
4021  double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
4022  sec_downloaded = percent_to_sub * sec_downloaded;
4023  *sec_to_download = percent_to_sub * *sec_to_download;
4024  }
4025 
4026  if ((sec_downloaded + *buffer) <= min_buffer) {
4027  return 1;
4028  }
4029 
4030  // Get the next Cue.
4031  desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
4032  }
4033 
4034  while (desc_curr.start_time_ns != -1) {
4035  int64_t desc_bytes = desc_curr.end_offset - desc_curr.start_offset;
4036  int64_t desc_ns = desc_curr.end_time_ns - desc_curr.start_time_ns;
4037  double desc_sec = desc_ns / nano_seconds_per_second;
4038  double bits = (desc_bytes * 8.0);
4039  double time_to_download = bits / bps;
4040 
4041  sec_downloaded += desc_sec - time_to_download;
4042  *sec_to_download += time_to_download;
4043 
4044  if (desc_curr.end_time_ns >= end_time_ns) {
4045  double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
4046  double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
4047  sec_downloaded = percent_to_sub * sec_downloaded;
4048  *sec_to_download = percent_to_sub * *sec_to_download;
4049 
4050  if ((sec_downloaded + *buffer) <= min_buffer)
4051  rv = 1;
4052  break;
4053  }
4054 
4055  if ((sec_downloaded + *buffer) <= min_buffer) {
4056  rv = 1;
4057  break;
4058  }
4059 
4060  desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
4061  }
4062  *buffer = *buffer + sec_downloaded;
4063  return rv;
4064 }
4065 
4066 /* This function computes the bandwidth of the WebM file with the help of
4067  * buffer_size_after_time_downloaded() function. Both of these functions are
4068  * adapted from WebM Tools project and are adapted to work with FFmpeg's
4069  * Matroska parsing mechanism.
4070  *
4071  * Returns the bandwidth of the file on success; -1 on error.
4072  * */
4073 static int64_t webm_dash_manifest_compute_bandwidth(AVFormatContext *s, int64_t cues_start)
4074 {
4075  MatroskaDemuxContext *matroska = s->priv_data;
4076  AVStream *st = s->streams[0];
4077  FFStream *const sti = ffstream(st);
4078  double bandwidth = 0.0;
4079 
4080  for (int i = 0; i < sti->nb_index_entries; i++) {
4081  int64_t prebuffer_ns = 1000000000;
4082  int64_t time_ns = sti->index_entries[i].timestamp * matroska->time_scale;
4083  double nano_seconds_per_second = 1000000000.0;
4084  int64_t prebuffered_ns = time_ns + prebuffer_ns;
4085  double prebuffer_bytes = 0.0;
4086  int64_t temp_prebuffer_ns = prebuffer_ns;
4087  int64_t pre_bytes, pre_ns;
4088  double pre_sec, prebuffer, bits_per_second;
4089  CueDesc desc_beg = get_cue_desc(s, time_ns, cues_start);
4090 
4091  // Start with the first Cue.
4092  CueDesc desc_end = desc_beg;
4093 
4094  // Figure out how much data we have downloaded for the prebuffer. This will
4095  // be used later to adjust the bits per sample to try.
4096  while (desc_end.start_time_ns != -1 && desc_end.end_time_ns < prebuffered_ns) {
4097  // Prebuffered the entire Cue.
4098  prebuffer_bytes += desc_end.end_offset - desc_end.start_offset;
4099  temp_prebuffer_ns -= desc_end.end_time_ns - desc_end.start_time_ns;
4100  desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
4101  }
4102  if (desc_end.start_time_ns == -1) {
4103  // The prebuffer is larger than the duration.
4104  if (matroska->duration * matroska->time_scale >= prebuffered_ns)
4105  return -1;
4106  bits_per_second = 0.0;
4107  } else {
4108  // The prebuffer ends in the last Cue. Estimate how much data was
4109  // prebuffered.
4110  pre_bytes = desc_end.end_offset - desc_end.start_offset;
4111  pre_ns = desc_end.end_time_ns - desc_end.start_time_ns;
4112  pre_sec = pre_ns / nano_seconds_per_second;
4113  prebuffer_bytes +=
4114  pre_bytes * ((temp_prebuffer_ns / nano_seconds_per_second) / pre_sec);
4115 
4116  prebuffer = prebuffer_ns / nano_seconds_per_second;
4117 
4118  // Set this to 0.0 in case our prebuffer buffers the entire video.
4119  bits_per_second = 0.0;
4120  do {
4121  int64_t desc_bytes = desc_end.end_offset - desc_beg.start_offset;
4122  int64_t desc_ns = desc_end.end_time_ns - desc_beg.start_time_ns;
4123  double desc_sec = desc_ns / nano_seconds_per_second;
4124  double calc_bits_per_second = (desc_bytes * 8) / desc_sec;
4125 
4126  // Drop the bps by the percentage of bytes buffered.
4127  double percent = (desc_bytes - prebuffer_bytes) / desc_bytes;
4128  double mod_bits_per_second = calc_bits_per_second * percent;
4129 
4130  if (prebuffer < desc_sec) {
4131  double search_sec =
4132  (double)(matroska->duration * matroska->time_scale) / nano_seconds_per_second;
4133 
4134  // Add 1 so the bits per second should be a little bit greater than file
4135  // datarate.
4136  int64_t bps = (int64_t)(mod_bits_per_second) + 1;
4137  const double min_buffer = 0.0;
4138  double buffer = prebuffer;
4139  double sec_to_download = 0.0;
4140 
4141  int rv = buffer_size_after_time_downloaded(prebuffered_ns, search_sec, bps,
4142  min_buffer, &buffer, &sec_to_download,
4143  s, cues_start);
4144  if (rv < 0) {
4145  return -1;
4146  } else if (rv == 0) {
4147  bits_per_second = (double)(bps);
4148  break;
4149  }
4150  }
4151 
4152  desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
4153  } while (desc_end.start_time_ns != -1);
4154  }
4155  if (bandwidth < bits_per_second) bandwidth = bits_per_second;
4156  }
4157  return (int64_t)bandwidth;
4158 }
4159 
4160 static int webm_dash_manifest_cues(AVFormatContext *s, int64_t init_range)
4161 {
4162  MatroskaDemuxContext *matroska = s->priv_data;
4163  EbmlList *seekhead_list = &matroska->seekhead;
4164  MatroskaSeekhead *seekhead = seekhead_list->elem;
4165  AVStream *const st = s->streams[0];
4166  FFStream *const sti = ffstream(st);
4167  AVBPrint bprint;
4168  char *buf;
4169  int64_t cues_start = -1, cues_end = -1, before_pos, bandwidth;
4170  int i;
4171  int ret;
4172 
4173  // determine cues start and end positions
4174  for (i = 0; i < seekhead_list->nb_elem; i++)
4175  if (seekhead[i].id == MATROSKA_ID_CUES)
4176  break;
4177 
4178  if (i >= seekhead_list->nb_elem) return -1;
4179 
4180  before_pos = avio_tell(matroska->ctx->pb);
4181  cues_start = seekhead[i].pos + matroska->segment_start;
4182  if (avio_seek(matroska->ctx->pb, cues_start, SEEK_SET) == cues_start) {
4183  // cues_end is computed as cues_start + cues_length + length of the
4184  // Cues element ID (i.e. 4) + EBML length of the Cues element.
4185  // cues_end is inclusive and the above sum is reduced by 1.
4186  uint64_t cues_length, cues_id;
4187  int bytes_read;
4188  bytes_read = ebml_read_num (matroska, matroska->ctx->pb, 4, &cues_id, 1);
4189  if (bytes_read < 0 || cues_id != (MATROSKA_ID_CUES & 0xfffffff))
4190  return bytes_read < 0 ? bytes_read : AVERROR_INVALIDDATA;
4191  bytes_read = ebml_read_length(matroska, matroska->ctx->pb, &cues_length);
4192  if (bytes_read < 0)
4193  return bytes_read;
4194  cues_end = cues_start + 4 + bytes_read + cues_length - 1;
4195  }
4196  avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
4197  if (cues_start == -1 || cues_end == -1) return -1;
4198 
4199  // parse the cues
4200  matroska_parse_cues(matroska);
4201 
4202  if (!sti->nb_index_entries)
4203  return AVERROR_INVALIDDATA;
4204 
4205  // cues start
4206  av_dict_set_int(&s->streams[0]->metadata, CUES_START, cues_start, 0);
4207 
4208  // cues end
4209  av_dict_set_int(&s->streams[0]->metadata, CUES_END, cues_end, 0);
4210 
4211  // if the file has cues at the start, fix up the init range so that
4212  // it does not include it
4213  if (cues_start <= init_range)
4214  av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, cues_start - 1, 0);
4215 
4216  // bandwidth
4217  bandwidth = webm_dash_manifest_compute_bandwidth(s, cues_start);
4218  if (bandwidth < 0) return -1;
4219  av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH, bandwidth, 0);
4220 
4221  // check if all clusters start with key frames
4222  av_dict_set_int(&s->streams[0]->metadata, CLUSTER_KEYFRAME, webm_clusters_start_with_keyframe(s), 0);
4223 
4224  // Store cue point timestamps as a comma separated list
4225  // for checking subsegment alignment in the muxer.
4227  for (int i = 0; i < sti->nb_index_entries; i++)
4228  av_bprintf(&bprint, "%" PRId64",", sti->index_entries[i].timestamp);
4229  if (!av_bprint_is_complete(&bprint)) {
4230  av_bprint_finalize(&bprint, NULL);
4231  return AVERROR(ENOMEM);
4232  }
4233  // Remove the trailing ','
4234  bprint.str[--bprint.len] = '\0';
4235  if ((ret = av_bprint_finalize(&bprint, &buf)) < 0)
4236  return ret;
4237  av_dict_set(&s->streams[0]->metadata, CUE_TIMESTAMPS,
4239 
4240  return 0;
4241 }
4242 
4243 static int webm_dash_manifest_read_header(AVFormatContext *s)
4244 {
4245  char *buf;
4246  int ret = matroska_read_header(s);
4247  int64_t init_range;
4248  MatroskaTrack *tracks;
4249  MatroskaDemuxContext *matroska = s->priv_data;
4250  if (ret) {
4251  av_log(s, AV_LOG_ERROR, "Failed to read file headers\n");
4252  return -1;
4253  }
4254  if (!matroska->tracks.nb_elem || !s->nb_streams) {
4255  av_log(s, AV_LOG_ERROR, "No track found\n");
4256  return AVERROR_INVALIDDATA;
4257  }
4258 
4259  if (!matroska->is_live) {
4260  buf = av_asprintf("%g", matroska->duration);
4261  if (!buf)
4262  return AVERROR(ENOMEM);
4263  av_dict_set(&s->streams[0]->metadata, DURATION,
4265 
4266  // initialization range
4267  // 5 is the offset of Cluster ID.
4268  init_range = avio_tell(s->pb) - 5;
4269  av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, init_range, 0);
4270  }
4271 
4272  // basename of the file
4273  buf = strrchr(s->url, '/');
4274  av_dict_set(&s->streams[0]->metadata, FILENAME, buf ? ++buf : s->url, 0);
4275 
4276  // track number
4277  tracks = matroska->tracks.elem;
4278  av_dict_set_int(&s->streams[0]->metadata, TRACK_NUMBER, tracks[0].num, 0);
4279 
4280  // parse the cues and populate Cue related fields
4281  if (!matroska->is_live) {
4282  ret = webm_dash_manifest_cues(s, init_range);
4283  if (ret < 0) {
4284  av_log(s, AV_LOG_ERROR, "Error parsing Cues\n");
4285  return ret;
4286  }
4287  }
4288 
4289  // use the bandwidth from the command line if it was provided
4290  if (matroska->bandwidth > 0) {
4291  av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH,
4292  matroska->bandwidth, 0);
4293  }
4294  return 0;
4295 }
4296 
4297 static int webm_dash_manifest_read_packet(AVFormatContext *s, AVPacket *pkt)
4298 {
4299  return AVERROR_EOF;
4300 }
4301 
4302 #define OFFSET(x) offsetof(MatroskaDemuxContext, x)
4303 static const AVOption options[] = {
4304  { "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 },
4305  { "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 },
4306  { NULL },
4307 };
4308 
4309 static const AVClass webm_dash_class = {
4310  .class_name = "WebM DASH Manifest demuxer",
4311  .item_name = av_default_item_name,
4312  .option = options,
4313  .version = LIBAVUTIL_VERSION_INT,
4314 };
4315 
4317  .name = "webm_dash_manifest",
4318  .long_name = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
4319  .priv_class = &webm_dash_class,
4320  .priv_data_size = sizeof(MatroskaDemuxContext),
4321  .flags_internal = FF_FMT_INIT_CLEANUP,
4322  .read_header = webm_dash_manifest_read_header,
4323  .read_packet = webm_dash_manifest_read_packet,
4325 };
4326 #endif
4327 
4329  .name = "matroska,webm",
4330  .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
4331  .extensions = "mkv,mk3d,mka,mks,webm",
4332  .priv_data_size = sizeof(MatroskaDemuxContext),
4333  .flags_internal = FF_FMT_INIT_CLEANUP,
4339  .mime_type = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
4340 };
AVCOL_PRI_RESERVED
@ AVCOL_PRI_RESERVED
Definition: pixfmt.h:455
MatroskaCluster::timecode
uint64_t timecode
Definition: matroskadec.c:343
MATROSKA_ID_ENCODINGENCRYPTION
#define MATROSKA_ID_ENCODINGENCRYPTION
Definition: matroska.h:183
MatroskaDemuxContext::segment_start
int64_t segment_start
Definition: matroskadec.c:377
AV_CODEC_ID_PCM_S16LE
@ AV_CODEC_ID_PCM_S16LE
Definition: codec_id.h:313
MATROSKA_ID_TAGTARGETS_ATTACHUID
#define MATROSKA_ID_TAGTARGETS_ATTACHUID
Definition: matroska.h:219
MatroskaDemuxContext::pkt
AVPacket * pkt
Definition: matroskadec.c:381
MATROSKA_ID_CHAPCOUNTRY
#define MATROSKA_ID_CHAPCOUNTRY
Definition: matroska.h:262
AVMasteringDisplayMetadata::has_primaries
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
Definition: mastering_display_metadata.h:62
ebml_read_master
static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length, int64_t pos)
Definition: matroskadec.c:1064
ebml_read_binary
static int ebml_read_binary(AVIOContext *pb, int length, int64_t pos, EbmlBin *bin)
Definition: matroskadec.c:1036
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:417
MATROSKA_ID_VIDEODISPLAYUNIT
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:125
mkv_image_mime_tags
static const CodecMime mkv_image_mime_tags[]
Definition: matroskadec.c:773
matroska_parse_laces
static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf, int size, int type, AVIOContext *pb, uint32_t lace_size[256], int *laces)
Definition: matroskadec.c:3079
MATROSKA_ID_CODECPRIVATE
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:89
MATROSKA_ID_TRACKNUMBER
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
MatroskaTag
Definition: matroskadec.c:300
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
MATROSKA_ID_TRACKFLAGVISUALIMPAIRED
#define MATROSKA_ID_TRACKFLAGVISUALIMPAIRED
Definition: matroska.h:102
bit_depth
static void bit_depth(AudioStatsContext *s, uint64_t mask, uint64_t imask, AVRational *depth)
Definition: af_astats.c:247
MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_RL
@ MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_RL
Definition: matroska.h:313
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AV_BPRINT_SIZE_UNLIMITED
#define AV_BPRINT_SIZE_UNLIMITED
MATROSKA_ID_CHAPSTRING
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:260
MATROSKA_ID_ENCODINGSIGHASHALGO
#define MATROSKA_ID_ENCODINGSIGHASHALGO
Definition: matroska.h:188
MatroskaTrack::codec_priv
EbmlBin codec_priv
Definition: matroskadec.c:242
MATROSKA_ID_TAGTARGETS
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:214
AVMasteringDisplayMetadata::max_luminance
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
Definition: mastering_display_metadata.h:57
MatroskaDemuxContext::queue
PacketList * queue
Definition: matroskadec.c:384
AVSphericalProjection
AVSphericalProjection
Projection of the video surface(s) on a sphere.
Definition: spherical.h:51
AVCodecParameters::extradata
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
EbmlSyntax::id
uint32_t id
Definition: matroskadec.c:104
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
MATROSKA_ID_CLUSTERTIMECODE
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:229
level
uint8_t level
Definition: svq3.c:204
matroska_attachment
static EbmlSyntax matroska_attachment[]
Definition: matroskadec.c:607
AV_CODEC_ID_AC3
@ AV_CODEC_ID_AC3
Definition: codec_id.h:425
ebml_header
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:422
FF_FMT_INIT_CLEANUP
#define FF_FMT_INIT_CLEANUP
For an AVInputFormat with this flag set read_close() needs to be called by the