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