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