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