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