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