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