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