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