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