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