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