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