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