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