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