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