]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
Merge commit '9fa888c02801fff2e8817c24068f5296bbe60000'
[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->codecpar->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->codecpar->color_space = track->video.color.matrix_coefficients;
1789     if (track->video.color.primaries != AVCOL_PRI_RESERVED)
1790         st->codecpar->color_primaries = track->video.color.primaries;
1791     if (track->video.color.transfer_characteristics != AVCOL_TRC_RESERVED)
1792         st->codecpar->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->codecpar->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->codecpar, track->codec_priv.size, 0);
2013             if (ret < 0)
2014                 return ret;
2015             codec_id         = st->codecpar->codec_id;
2016             fourcc           = st->codecpar->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->codecpar->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->codecpar->bit_rate          = sipr_bit_rate[flavor];
2195                 }
2196                 st->codecpar->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->codecpar->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->codecpar->extradata) {
2234             if (extradata) {
2235                 st->codecpar->extradata      = extradata;
2236                 st->codecpar->extradata_size = extradata_size;
2237             } else if (track->codec_priv.data && track->codec_priv.size > 0) {
2238                 if (ff_alloc_extradata(st->codecpar, track->codec_priv.size))
2239                     return AVERROR(ENOMEM);
2240                 memcpy(st->codecpar->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->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2252             st->codecpar->codec_tag  = fourcc;
2253             if (bit_depth >= 0)
2254                 st->codecpar->bits_per_coded_sample = bit_depth;
2255             st->codecpar->width      = track->video.pixel_width;
2256             st->codecpar->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->codecpar->height * track->video.display_width  * display_width_mul,
2264                       st->codecpar->width  * track->video.display_height * display_height_mul,
2265                       255);
2266             if (st->codecpar->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->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
2316             st->codecpar->codec_tag   = fourcc;
2317             st->codecpar->sample_rate = track->audio.out_samplerate;
2318             st->codecpar->channels    = track->audio.channels;
2319             if (!st->codecpar->bits_per_coded_sample)
2320                 st->codecpar->bits_per_coded_sample = track->audio.bitdepth;
2321             if (st->codecpar->codec_id == AV_CODEC_ID_MP3)
2322                 st->need_parsing = AVSTREAM_PARSE_FULL;
2323             else if (st->codecpar->codec_id != AV_CODEC_ID_AAC)
2324                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2325             if (track->codec_delay > 0) {
2326                 st->codecpar->initial_padding = av_rescale_q(track->codec_delay,
2327                                                              st->time_base,
2328                                                              (AVRational){1, st->codecpar->sample_rate});
2329             }
2330             if (track->seek_preroll > 0) {
2331                 st->codecpar->seek_preroll = av_rescale_q(track->seek_preroll,
2332                                                           (AVRational){1, 1000000000},
2333                                                           (AVRational){1, st->codecpar->sample_rate});
2334             }
2335         } else if (codec_id == AV_CODEC_ID_WEBVTT) {
2336             st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2337
2338             if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
2339                 st->disposition |= AV_DISPOSITION_CAPTIONS;
2340             } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
2341                 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2342             } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
2343                 st->disposition |= AV_DISPOSITION_METADATA;
2344             }
2345         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2346             st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2347             if (st->codecpar->codec_id == AV_CODEC_ID_ASS)
2348                 matroska->contains_ssa = 1;
2349         }
2350     }
2351
2352     return 0;
2353 }
2354
2355 static int matroska_read_header(AVFormatContext *s)
2356 {
2357     MatroskaDemuxContext *matroska = s->priv_data;
2358     EbmlList *attachments_list = &matroska->attachments;
2359     EbmlList *chapters_list    = &matroska->chapters;
2360     MatroskaAttachment *attachments;
2361     MatroskaChapter *chapters;
2362     uint64_t max_start = 0;
2363     int64_t pos;
2364     Ebml ebml = { 0 };
2365     int i, j, res;
2366
2367     matroska->ctx = s;
2368     matroska->cues_parsing_deferred = 1;
2369
2370     /* First read the EBML header. */
2371     if (ebml_parse(matroska, ebml_syntax, &ebml) || !ebml.doctype) {
2372         av_log(matroska->ctx, AV_LOG_ERROR, "EBML header parsing failed\n");
2373         ebml_free(ebml_syntax, &ebml);
2374         return AVERROR_INVALIDDATA;
2375     }
2376     if (ebml.version         > EBML_VERSION      ||
2377         ebml.max_size        > sizeof(uint64_t)  ||
2378         ebml.id_length       > sizeof(uint32_t)  ||
2379         ebml.doctype_version > 3) {
2380         av_log(matroska->ctx, AV_LOG_ERROR,
2381                "EBML header using unsupported features\n"
2382                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
2383                ebml.version, ebml.doctype, ebml.doctype_version);
2384         ebml_free(ebml_syntax, &ebml);
2385         return AVERROR_PATCHWELCOME;
2386     } else if (ebml.doctype_version == 3) {
2387         av_log(matroska->ctx, AV_LOG_WARNING,
2388                "EBML header using unsupported features\n"
2389                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
2390                ebml.version, ebml.doctype, ebml.doctype_version);
2391     }
2392     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
2393         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
2394             break;
2395     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
2396         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
2397         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
2398             ebml_free(ebml_syntax, &ebml);
2399             return AVERROR_INVALIDDATA;
2400         }
2401     }
2402     ebml_free(ebml_syntax, &ebml);
2403
2404     /* The next thing is a segment. */
2405     pos = avio_tell(matroska->ctx->pb);
2406     res = ebml_parse(matroska, matroska_segments, matroska);
2407     // try resyncing until we find a EBML_STOP type element.
2408     while (res != 1) {
2409         res = matroska_resync(matroska, pos);
2410         if (res < 0)
2411             return res;
2412         pos = avio_tell(matroska->ctx->pb);
2413         res = ebml_parse(matroska, matroska_segment, matroska);
2414     }
2415     matroska_execute_seekhead(matroska);
2416
2417     if (!matroska->time_scale)
2418         matroska->time_scale = 1000000;
2419     if (matroska->duration)
2420         matroska->ctx->duration = matroska->duration * matroska->time_scale *
2421                                   1000 / AV_TIME_BASE;
2422     av_dict_set(&s->metadata, "title", matroska->title, 0);
2423     av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
2424
2425     if (matroska->date_utc.size == 8)
2426         matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
2427
2428     res = matroska_parse_tracks(s);
2429     if (res < 0)
2430         return res;
2431
2432     attachments = attachments_list->elem;
2433     for (j = 0; j < attachments_list->nb_elem; j++) {
2434         if (!(attachments[j].filename && attachments[j].mime &&
2435               attachments[j].bin.data && attachments[j].bin.size > 0)) {
2436             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2437         } else {
2438             AVStream *st = avformat_new_stream(s, NULL);
2439             if (!st)
2440                 break;
2441             av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
2442             av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
2443             st->codecpar->codec_id   = AV_CODEC_ID_NONE;
2444
2445             for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2446                 if (!strncmp(ff_mkv_image_mime_tags[i].str, attachments[j].mime,
2447                              strlen(ff_mkv_image_mime_tags[i].str))) {
2448                     st->codecpar->codec_id = ff_mkv_image_mime_tags[i].id;
2449                     break;
2450                 }
2451             }
2452
2453             attachments[j].stream = st;
2454
2455             if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
2456                 st->disposition         |= AV_DISPOSITION_ATTACHED_PIC;
2457                 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2458
2459                 av_init_packet(&st->attached_pic);
2460                 if ((res = av_new_packet(&st->attached_pic, attachments[j].bin.size)) < 0)
2461                     return res;
2462                 memcpy(st->attached_pic.data, attachments[j].bin.data, attachments[j].bin.size);
2463                 st->attached_pic.stream_index = st->index;
2464                 st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
2465             } else {
2466                 st->codecpar->codec_type = AVMEDIA_TYPE_ATTACHMENT;
2467                 if (ff_alloc_extradata(st->codecpar, attachments[j].bin.size))
2468                     break;
2469                 memcpy(st->codecpar->extradata, attachments[j].bin.data,
2470                        attachments[j].bin.size);
2471
2472                 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2473                     if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
2474                                 strlen(ff_mkv_mime_tags[i].str))) {
2475                         st->codecpar->codec_id = ff_mkv_mime_tags[i].id;
2476                         break;
2477                     }
2478                 }
2479             }
2480         }
2481     }
2482
2483     chapters = chapters_list->elem;
2484     for (i = 0; i < chapters_list->nb_elem; i++)
2485         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
2486             (max_start == 0 || chapters[i].start > max_start)) {
2487             chapters[i].chapter =
2488                 avpriv_new_chapter(s, chapters[i].uid,
2489                                    (AVRational) { 1, 1000000000 },
2490                                    chapters[i].start, chapters[i].end,
2491                                    chapters[i].title);
2492             if (chapters[i].chapter) {
2493                 av_dict_set(&chapters[i].chapter->metadata,
2494                             "title", chapters[i].title, 0);
2495             }
2496             max_start = chapters[i].start;
2497         }
2498
2499     matroska_add_index_entries(matroska);
2500
2501     matroska_convert_tags(s);
2502
2503     return 0;
2504 }
2505
2506 /*
2507  * Put one packet in an application-supplied AVPacket struct.
2508  * Returns 0 on success or -1 on failure.
2509  */
2510 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
2511                                    AVPacket *pkt)
2512 {
2513     if (matroska->num_packets > 0) {
2514         MatroskaTrack *tracks = matroska->tracks.elem;
2515         MatroskaTrack *track;
2516         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
2517         av_freep(&matroska->packets[0]);
2518         track = &tracks[pkt->stream_index];
2519         if (track->has_palette) {
2520             uint8_t *pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2521             if (!pal) {
2522                 av_log(matroska->ctx, AV_LOG_ERROR, "Cannot append palette to packet\n");
2523             } else {
2524                 memcpy(pal, track->palette, AVPALETTE_SIZE);
2525             }
2526             track->has_palette = 0;
2527         }
2528         if (matroska->num_packets > 1) {
2529             void *newpackets;
2530             memmove(&matroska->packets[0], &matroska->packets[1],
2531                     (matroska->num_packets - 1) * sizeof(AVPacket *));
2532             newpackets = av_realloc(matroska->packets,
2533                                     (matroska->num_packets - 1) *
2534                                     sizeof(AVPacket *));
2535             if (newpackets)
2536                 matroska->packets = newpackets;
2537         } else {
2538             av_freep(&matroska->packets);
2539             matroska->prev_pkt = NULL;
2540         }
2541         matroska->num_packets--;
2542         return 0;
2543     }
2544
2545     return -1;
2546 }
2547
2548 /*
2549  * Free all packets in our internal queue.
2550  */
2551 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2552 {
2553     matroska->prev_pkt = NULL;
2554     if (matroska->packets) {
2555         int n;
2556         for (n = 0; n < matroska->num_packets; n++) {
2557             av_packet_unref(matroska->packets[n]);
2558             av_freep(&matroska->packets[n]);
2559         }
2560         av_freep(&matroska->packets);
2561         matroska->num_packets = 0;
2562     }
2563 }
2564
2565 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2566                                 int *buf_size, int type,
2567                                 uint32_t **lace_buf, int *laces)
2568 {
2569     int res = 0, n, size = *buf_size;
2570     uint8_t *data = *buf;
2571     uint32_t *lace_size;
2572
2573     if (!type) {
2574         *laces    = 1;
2575         *lace_buf = av_mallocz(sizeof(int));
2576         if (!*lace_buf)
2577             return AVERROR(ENOMEM);
2578
2579         *lace_buf[0] = size;
2580         return 0;
2581     }
2582
2583     av_assert0(size > 0);
2584     *laces    = *data + 1;
2585     data     += 1;
2586     size     -= 1;
2587     lace_size = av_mallocz(*laces * sizeof(int));
2588     if (!lace_size)
2589         return AVERROR(ENOMEM);
2590
2591     switch (type) {
2592     case 0x1: /* Xiph lacing */
2593     {
2594         uint8_t temp;
2595         uint32_t total = 0;
2596         for (n = 0; res == 0 && n < *laces - 1; n++) {
2597             while (1) {
2598                 if (size <= total) {
2599                     res = AVERROR_INVALIDDATA;
2600                     break;
2601                 }
2602                 temp          = *data;
2603                 total        += temp;
2604                 lace_size[n] += temp;
2605                 data         += 1;
2606                 size         -= 1;
2607                 if (temp != 0xff)
2608                     break;
2609             }
2610         }
2611         if (size <= total) {
2612             res = AVERROR_INVALIDDATA;
2613             break;
2614         }
2615
2616         lace_size[n] = size - total;
2617         break;
2618     }
2619
2620     case 0x2: /* fixed-size lacing */
2621         if (size % (*laces)) {
2622             res = AVERROR_INVALIDDATA;
2623             break;
2624         }
2625         for (n = 0; n < *laces; n++)
2626             lace_size[n] = size / *laces;
2627         break;
2628
2629     case 0x3: /* EBML lacing */
2630     {
2631         uint64_t num;
2632         uint64_t total;
2633         n = matroska_ebmlnum_uint(matroska, data, size, &num);
2634         if (n < 0 || num > INT_MAX) {
2635             av_log(matroska->ctx, AV_LOG_INFO,
2636                    "EBML block data error\n");
2637             res = n<0 ? n : AVERROR_INVALIDDATA;
2638             break;
2639         }
2640         data += n;
2641         size -= n;
2642         total = lace_size[0] = num;
2643         for (n = 1; res == 0 && n < *laces - 1; n++) {
2644             int64_t snum;
2645             int r;
2646             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2647             if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
2648                 av_log(matroska->ctx, AV_LOG_INFO,
2649                        "EBML block data error\n");
2650                 res = r<0 ? r : AVERROR_INVALIDDATA;
2651                 break;
2652             }
2653             data        += r;
2654             size        -= r;
2655             lace_size[n] = lace_size[n - 1] + snum;
2656             total       += lace_size[n];
2657         }
2658         if (size <= total) {
2659             res = AVERROR_INVALIDDATA;
2660             break;
2661         }
2662         lace_size[*laces - 1] = size - total;
2663         break;
2664     }
2665     }
2666
2667     *buf      = data;
2668     *lace_buf = lace_size;
2669     *buf_size = size;
2670
2671     return res;
2672 }
2673
2674 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2675                                    MatroskaTrack *track, AVStream *st,
2676                                    uint8_t *data, int size, uint64_t timecode,
2677                                    int64_t pos)
2678 {
2679     int a = st->codecpar->block_align;
2680     int sps = track->audio.sub_packet_size;
2681     int cfs = track->audio.coded_framesize;
2682     int h   = track->audio.sub_packet_h;
2683     int y   = track->audio.sub_packet_cnt;
2684     int w   = track->audio.frame_size;
2685     int x;
2686
2687     if (!track->audio.pkt_cnt) {
2688         if (track->audio.sub_packet_cnt == 0)
2689             track->audio.buf_timecode = timecode;
2690         if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
2691             if (size < cfs * h / 2) {
2692                 av_log(matroska->ctx, AV_LOG_ERROR,
2693                        "Corrupt int4 RM-style audio packet size\n");
2694                 return AVERROR_INVALIDDATA;
2695             }
2696             for (x = 0; x < h / 2; x++)
2697                 memcpy(track->audio.buf + x * 2 * w + y * cfs,
2698                        data + x * cfs, cfs);
2699         } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
2700             if (size < w) {
2701                 av_log(matroska->ctx, AV_LOG_ERROR,
2702                        "Corrupt sipr RM-style audio packet size\n");
2703                 return AVERROR_INVALIDDATA;
2704             }
2705             memcpy(track->audio.buf + y * w, data, w);
2706         } else {
2707             if (size < sps * w / sps || h<=0 || w%sps) {
2708                 av_log(matroska->ctx, AV_LOG_ERROR,
2709                        "Corrupt generic RM-style audio packet size\n");
2710                 return AVERROR_INVALIDDATA;
2711             }
2712             for (x = 0; x < w / sps; x++)
2713                 memcpy(track->audio.buf +
2714                        sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
2715                        data + x * sps, sps);
2716         }
2717
2718         if (++track->audio.sub_packet_cnt >= h) {
2719             if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
2720                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2721             track->audio.sub_packet_cnt = 0;
2722             track->audio.pkt_cnt        = h * w / a;
2723         }
2724     }
2725
2726     while (track->audio.pkt_cnt) {
2727         int ret;
2728         AVPacket *pkt = av_mallocz(sizeof(AVPacket));
2729         if (!pkt)
2730             return AVERROR(ENOMEM);
2731
2732         ret = av_new_packet(pkt, a);
2733         if (ret < 0) {
2734             av_free(pkt);
2735             return ret;
2736         }
2737         memcpy(pkt->data,
2738                track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
2739                a);
2740         pkt->pts                  = track->audio.buf_timecode;
2741         track->audio.buf_timecode = AV_NOPTS_VALUE;
2742         pkt->pos                  = pos;
2743         pkt->stream_index         = st->index;
2744         dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2745     }
2746
2747     return 0;
2748 }
2749
2750 /* reconstruct full wavpack blocks from mangled matroska ones */
2751 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
2752                                   uint8_t **pdst, int *size)
2753 {
2754     uint8_t *dst = NULL;
2755     int dstlen   = 0;
2756     int srclen   = *size;
2757     uint32_t samples;
2758     uint16_t ver;
2759     int ret, offset = 0;
2760
2761     if (srclen < 12 || track->stream->codecpar->extradata_size < 2)
2762         return AVERROR_INVALIDDATA;
2763
2764     ver = AV_RL16(track->stream->codecpar->extradata);
2765
2766     samples = AV_RL32(src);
2767     src    += 4;
2768     srclen -= 4;
2769
2770     while (srclen >= 8) {
2771         int multiblock;
2772         uint32_t blocksize;
2773         uint8_t *tmp;
2774
2775         uint32_t flags = AV_RL32(src);
2776         uint32_t crc   = AV_RL32(src + 4);
2777         src    += 8;
2778         srclen -= 8;
2779
2780         multiblock = (flags & 0x1800) != 0x1800;
2781         if (multiblock) {
2782             if (srclen < 4) {
2783                 ret = AVERROR_INVALIDDATA;
2784                 goto fail;
2785             }
2786             blocksize = AV_RL32(src);
2787             src      += 4;
2788             srclen   -= 4;
2789         } else
2790             blocksize = srclen;
2791
2792         if (blocksize > srclen) {
2793             ret = AVERROR_INVALIDDATA;
2794             goto fail;
2795         }
2796
2797         tmp = av_realloc(dst, dstlen + blocksize + 32);
2798         if (!tmp) {
2799             ret = AVERROR(ENOMEM);
2800             goto fail;
2801         }
2802         dst     = tmp;
2803         dstlen += blocksize + 32;
2804
2805         AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k'));   // tag
2806         AV_WL32(dst + offset +  4, blocksize + 24);         // blocksize - 8
2807         AV_WL16(dst + offset +  8, ver);                    // version
2808         AV_WL16(dst + offset + 10, 0);                      // track/index_no
2809         AV_WL32(dst + offset + 12, 0);                      // total samples
2810         AV_WL32(dst + offset + 16, 0);                      // block index
2811         AV_WL32(dst + offset + 20, samples);                // number of samples
2812         AV_WL32(dst + offset + 24, flags);                  // flags
2813         AV_WL32(dst + offset + 28, crc);                    // crc
2814         memcpy(dst + offset + 32, src, blocksize);          // block data
2815
2816         src    += blocksize;
2817         srclen -= blocksize;
2818         offset += blocksize + 32;
2819     }
2820
2821     *pdst = dst;
2822     *size = dstlen;
2823
2824     return 0;
2825
2826 fail:
2827     av_freep(&dst);
2828     return ret;
2829 }
2830
2831 static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
2832                                  MatroskaTrack *track,
2833                                  AVStream *st,
2834                                  uint8_t *data, int data_len,
2835                                  uint64_t timecode,
2836                                  uint64_t duration,
2837                                  int64_t pos)
2838 {
2839     AVPacket *pkt;
2840     uint8_t *id, *settings, *text, *buf;
2841     int id_len, settings_len, text_len;
2842     uint8_t *p, *q;
2843     int err;
2844
2845     if (data_len <= 0)
2846         return AVERROR_INVALIDDATA;
2847
2848     p = data;
2849     q = data + data_len;
2850
2851     id = p;
2852     id_len = -1;
2853     while (p < q) {
2854         if (*p == '\r' || *p == '\n') {
2855             id_len = p - id;
2856             if (*p == '\r')
2857                 p++;
2858             break;
2859         }
2860         p++;
2861     }
2862
2863     if (p >= q || *p != '\n')
2864         return AVERROR_INVALIDDATA;
2865     p++;
2866
2867     settings = p;
2868     settings_len = -1;
2869     while (p < q) {
2870         if (*p == '\r' || *p == '\n') {
2871             settings_len = p - settings;
2872             if (*p == '\r')
2873                 p++;
2874             break;
2875         }
2876         p++;
2877     }
2878
2879     if (p >= q || *p != '\n')
2880         return AVERROR_INVALIDDATA;
2881     p++;
2882
2883     text = p;
2884     text_len = q - p;
2885     while (text_len > 0) {
2886         const int len = text_len - 1;
2887         const uint8_t c = p[len];
2888         if (c != '\r' && c != '\n')
2889             break;
2890         text_len = len;
2891     }
2892
2893     if (text_len <= 0)
2894         return AVERROR_INVALIDDATA;
2895
2896     pkt = av_mallocz(sizeof(*pkt));
2897     if (!pkt)
2898         return AVERROR(ENOMEM);
2899     err = av_new_packet(pkt, text_len);
2900     if (err < 0) {
2901         av_free(pkt);
2902         return AVERROR(err);
2903     }
2904
2905     memcpy(pkt->data, text, text_len);
2906
2907     if (id_len > 0) {
2908         buf = av_packet_new_side_data(pkt,
2909                                       AV_PKT_DATA_WEBVTT_IDENTIFIER,
2910                                       id_len);
2911         if (!buf) {
2912             av_free(pkt);
2913             return AVERROR(ENOMEM);
2914         }
2915         memcpy(buf, id, id_len);
2916     }
2917
2918     if (settings_len > 0) {
2919         buf = av_packet_new_side_data(pkt,
2920                                       AV_PKT_DATA_WEBVTT_SETTINGS,
2921                                       settings_len);
2922         if (!buf) {
2923             av_free(pkt);
2924             return AVERROR(ENOMEM);
2925         }
2926         memcpy(buf, settings, settings_len);
2927     }
2928
2929     // Do we need this for subtitles?
2930     // pkt->flags = AV_PKT_FLAG_KEY;
2931
2932     pkt->stream_index = st->index;
2933     pkt->pts = timecode;
2934
2935     // Do we need this for subtitles?
2936     // pkt->dts = timecode;
2937
2938     pkt->duration = duration;
2939     pkt->pos = pos;
2940
2941     dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2942     matroska->prev_pkt = pkt;
2943
2944     return 0;
2945 }
2946
2947 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2948                                 MatroskaTrack *track, AVStream *st,
2949                                 uint8_t *data, int pkt_size,
2950                                 uint64_t timecode, uint64_t lace_duration,
2951                                 int64_t pos, int is_keyframe,
2952                                 uint8_t *additional, uint64_t additional_id, int additional_size,
2953                                 int64_t discard_padding)
2954 {
2955     MatroskaTrackEncoding *encodings = track->encodings.elem;
2956     uint8_t *pkt_data = data;
2957     int offset = 0, res;
2958     AVPacket *pkt;
2959
2960     if (encodings && !encodings->type && encodings->scope & 1) {
2961         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2962         if (res < 0)
2963             return res;
2964     }
2965
2966     if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
2967         uint8_t *wv_data;
2968         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2969         if (res < 0) {
2970             av_log(matroska->ctx, AV_LOG_ERROR,
2971                    "Error parsing a wavpack block.\n");
2972             goto fail;
2973         }
2974         if (pkt_data != data)
2975             av_freep(&pkt_data);
2976         pkt_data = wv_data;
2977     }
2978
2979     if (st->codecpar->codec_id == AV_CODEC_ID_PRORES &&
2980         AV_RB32(&data[4]) != MKBETAG('i', 'c', 'p', 'f'))
2981         offset = 8;
2982
2983     pkt = av_mallocz(sizeof(AVPacket));
2984     if (!pkt) {
2985         if (pkt_data != data)
2986             av_freep(&pkt_data);
2987         return AVERROR(ENOMEM);
2988     }
2989     /* XXX: prevent data copy... */
2990     if (av_new_packet(pkt, pkt_size + offset) < 0) {
2991         av_free(pkt);
2992         res = AVERROR(ENOMEM);
2993         goto fail;
2994     }
2995
2996     if (st->codecpar->codec_id == AV_CODEC_ID_PRORES && offset == 8) {
2997         uint8_t *buf = pkt->data;
2998         bytestream_put_be32(&buf, pkt_size);
2999         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
3000     }
3001
3002     memcpy(pkt->data + offset, pkt_data, pkt_size);
3003
3004     if (pkt_data != data)
3005         av_freep(&pkt_data);
3006
3007     pkt->flags        = is_keyframe;
3008     pkt->stream_index = st->index;
3009
3010     if (additional_size > 0) {
3011         uint8_t *side_data = av_packet_new_side_data(pkt,
3012                                                      AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
3013                                                      additional_size + 8);
3014         if (!side_data) {
3015             av_packet_unref(pkt);
3016             av_free(pkt);
3017             return AVERROR(ENOMEM);
3018         }
3019         AV_WB64(side_data, additional_id);
3020         memcpy(side_data + 8, additional, additional_size);
3021     }
3022
3023     if (discard_padding) {
3024         uint8_t *side_data = av_packet_new_side_data(pkt,
3025                                                      AV_PKT_DATA_SKIP_SAMPLES,
3026                                                      10);
3027         if (!side_data) {
3028             av_packet_unref(pkt);
3029             av_free(pkt);
3030             return AVERROR(ENOMEM);
3031         }
3032         AV_WL32(side_data, 0);
3033         AV_WL32(side_data + 4, av_rescale_q(discard_padding,
3034                                             (AVRational){1, 1000000000},
3035                                             (AVRational){1, st->codecpar->sample_rate}));
3036     }
3037
3038     if (track->ms_compat)
3039         pkt->dts = timecode;
3040     else
3041         pkt->pts = timecode;
3042     pkt->pos = pos;
3043     pkt->duration = lace_duration;
3044
3045 #if FF_API_CONVERGENCE_DURATION
3046 FF_DISABLE_DEPRECATION_WARNINGS
3047     if (st->codecpar->codec_id == AV_CODEC_ID_SUBRIP) {
3048         pkt->convergence_duration = lace_duration;
3049     }
3050 FF_ENABLE_DEPRECATION_WARNINGS
3051 #endif
3052
3053     dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
3054     matroska->prev_pkt = pkt;
3055
3056     return 0;
3057
3058 fail:
3059     if (pkt_data != data)
3060         av_freep(&pkt_data);
3061     return res;
3062 }
3063
3064 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
3065                                 int size, int64_t pos, uint64_t cluster_time,
3066                                 uint64_t block_duration, int is_keyframe,
3067                                 uint8_t *additional, uint64_t additional_id, int additional_size,
3068                                 int64_t cluster_pos, int64_t discard_padding)
3069 {
3070     uint64_t timecode = AV_NOPTS_VALUE;
3071     MatroskaTrack *track;
3072     int res = 0;
3073     AVStream *st;
3074     int16_t block_time;
3075     uint32_t *lace_size = NULL;
3076     int n, flags, laces = 0;
3077     uint64_t num;
3078     int trust_default_duration = 1;
3079
3080     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
3081         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
3082         return n;
3083     }
3084     data += n;
3085     size -= n;
3086
3087     track = matroska_find_track_by_num(matroska, num);
3088     if (!track || !track->stream) {
3089         av_log(matroska->ctx, AV_LOG_INFO,
3090                "Invalid stream %"PRIu64" or size %u\n", num, size);
3091         return AVERROR_INVALIDDATA;
3092     } else if (size <= 3)
3093         return 0;
3094     st = track->stream;
3095     if (st->discard >= AVDISCARD_ALL)
3096         return res;
3097     av_assert1(block_duration != AV_NOPTS_VALUE);
3098
3099     block_time = sign_extend(AV_RB16(data), 16);
3100     data      += 2;
3101     flags      = *data++;
3102     size      -= 3;
3103     if (is_keyframe == -1)
3104         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
3105
3106     if (cluster_time != (uint64_t) -1 &&
3107         (block_time >= 0 || cluster_time >= -block_time)) {
3108         timecode = cluster_time + block_time - track->codec_delay;
3109         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
3110             timecode < track->end_timecode)
3111             is_keyframe = 0;  /* overlapping subtitles are not key frame */
3112         if (is_keyframe)
3113             av_add_index_entry(st, cluster_pos, timecode, 0, 0,
3114                                AVINDEX_KEYFRAME);
3115     }
3116
3117     if (matroska->skip_to_keyframe &&
3118         track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
3119         if (timecode < matroska->skip_to_timecode)
3120             return res;
3121         if (is_keyframe)
3122             matroska->skip_to_keyframe = 0;
3123         else if (!st->skip_to_keyframe) {
3124             av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
3125             matroska->skip_to_keyframe = 0;
3126         }
3127     }
3128
3129     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
3130                                &lace_size, &laces);
3131
3132     if (res)
3133         goto end;
3134
3135     if (track->audio.samplerate == 8000) {
3136         // If this is needed for more codecs, then add them here
3137         if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
3138             if (track->audio.samplerate != st->codecpar->sample_rate || !st->codecpar->frame_size)
3139                 trust_default_duration = 0;
3140         }
3141     }
3142
3143     if (!block_duration && trust_default_duration)
3144         block_duration = track->default_duration * laces / matroska->time_scale;
3145
3146     if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
3147         track->end_timecode =
3148             FFMAX(track->end_timecode, timecode + block_duration);
3149
3150     for (n = 0; n < laces; n++) {
3151         int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
3152
3153         if (lace_size[n] > size) {
3154             av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
3155             break;
3156         }
3157
3158         if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
3159              st->codecpar->codec_id == AV_CODEC_ID_COOK   ||
3160              st->codecpar->codec_id == AV_CODEC_ID_SIPR   ||
3161              st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) &&
3162             st->codecpar->block_align && track->audio.sub_packet_size) {
3163             res = matroska_parse_rm_audio(matroska, track, st, data,
3164                                           lace_size[n],
3165                                           timecode, pos);
3166             if (res)
3167                 goto end;
3168
3169         } else if (st->codecpar->codec_id == AV_CODEC_ID_WEBVTT) {
3170             res = matroska_parse_webvtt(matroska, track, st,
3171                                         data, lace_size[n],
3172                                         timecode, lace_duration,
3173                                         pos);
3174             if (res)
3175                 goto end;
3176         } else {
3177             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
3178                                        timecode, lace_duration, pos,
3179                                        !n ? is_keyframe : 0,
3180                                        additional, additional_id, additional_size,
3181                                        discard_padding);
3182             if (res)
3183                 goto end;
3184         }
3185
3186         if (timecode != AV_NOPTS_VALUE)
3187             timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
3188         data += lace_size[n];
3189         size -= lace_size[n];
3190     }
3191
3192 end:
3193     av_free(lace_size);
3194     return res;
3195 }
3196
3197 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
3198 {
3199     EbmlList *blocks_list;
3200     MatroskaBlock *blocks;
3201     int i, res;
3202     res = ebml_parse(matroska,
3203                      matroska_cluster_incremental_parsing,
3204                      &matroska->current_cluster);
3205     if (res == 1) {
3206         /* New Cluster */
3207         if (matroska->current_cluster_pos)
3208             ebml_level_end(matroska);
3209         ebml_free(matroska_cluster, &matroska->current_cluster);
3210         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
3211         matroska->current_cluster_num_blocks = 0;
3212         matroska->current_cluster_pos        = avio_tell(matroska->ctx->pb);
3213         matroska->prev_pkt                   = NULL;
3214         /* sizeof the ID which was already read */
3215         if (matroska->current_id)
3216             matroska->current_cluster_pos -= 4;
3217         res = ebml_parse(matroska,
3218                          matroska_clusters_incremental,
3219                          &matroska->current_cluster);
3220         /* Try parsing the block again. */
3221         if (res == 1)
3222             res = ebml_parse(matroska,
3223                              matroska_cluster_incremental_parsing,
3224                              &matroska->current_cluster);
3225     }
3226
3227     if (!res &&
3228         matroska->current_cluster_num_blocks <
3229         matroska->current_cluster.blocks.nb_elem) {
3230         blocks_list = &matroska->current_cluster.blocks;
3231         blocks      = blocks_list->elem;
3232
3233         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
3234         i                                    = blocks_list->nb_elem - 1;
3235         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
3236             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
3237             uint8_t* additional = blocks[i].additional.size > 0 ?
3238                                     blocks[i].additional.data : NULL;
3239             if (!blocks[i].non_simple)
3240                 blocks[i].duration = 0;
3241             res = matroska_parse_block(matroska, blocks[i].bin.data,
3242                                        blocks[i].bin.size, blocks[i].bin.pos,
3243                                        matroska->current_cluster.timecode,
3244                                        blocks[i].duration, is_keyframe,
3245                                        additional, blocks[i].additional_id,
3246                                        blocks[i].additional.size,
3247                                        matroska->current_cluster_pos,
3248                                        blocks[i].discard_padding);
3249         }
3250     }
3251
3252     return res;
3253 }
3254
3255 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
3256 {
3257     MatroskaCluster cluster = { 0 };
3258     EbmlList *blocks_list;
3259     MatroskaBlock *blocks;
3260     int i, res;
3261     int64_t pos;
3262
3263     if (!matroska->contains_ssa)
3264         return matroska_parse_cluster_incremental(matroska);
3265     pos = avio_tell(matroska->ctx->pb);
3266     matroska->prev_pkt = NULL;
3267     if (matroska->current_id)
3268         pos -= 4;  /* sizeof the ID which was already read */
3269     res         = ebml_parse(matroska, matroska_clusters, &cluster);
3270     blocks_list = &cluster.blocks;
3271     blocks      = blocks_list->elem;
3272     for (i = 0; i < blocks_list->nb_elem; i++)
3273         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
3274             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
3275             res = matroska_parse_block(matroska, blocks[i].bin.data,
3276                                        blocks[i].bin.size, blocks[i].bin.pos,
3277                                        cluster.timecode, blocks[i].duration,
3278                                        is_keyframe, NULL, 0, 0, pos,
3279                                        blocks[i].discard_padding);
3280         }
3281     ebml_free(matroska_cluster, &cluster);
3282     return res;
3283 }
3284
3285 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
3286 {
3287     MatroskaDemuxContext *matroska = s->priv_data;
3288
3289     while (matroska_deliver_packet(matroska, pkt)) {
3290         int64_t pos = avio_tell(matroska->ctx->pb);
3291         if (matroska->done)
3292             return AVERROR_EOF;
3293         if (matroska_parse_cluster(matroska) < 0)
3294             matroska_resync(matroska, pos);
3295     }
3296
3297     return 0;
3298 }
3299
3300 static int matroska_read_seek(AVFormatContext *s, int stream_index,
3301                               int64_t timestamp, int flags)
3302 {
3303     MatroskaDemuxContext *matroska = s->priv_data;
3304     MatroskaTrack *tracks = NULL;
3305     AVStream *st = s->streams[stream_index];
3306     int i, index, index_sub, index_min;
3307
3308     /* Parse the CUES now since we need the index data to seek. */
3309     if (matroska->cues_parsing_deferred > 0) {
3310         matroska->cues_parsing_deferred = 0;
3311         matroska_parse_cues(matroska);
3312     }
3313
3314     if (!st->nb_index_entries)
3315         goto err;
3316     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
3317
3318     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
3319         avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
3320                   SEEK_SET);
3321         matroska->current_id = 0;
3322         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
3323             matroska_clear_queue(matroska);
3324             if (matroska_parse_cluster(matroska) < 0)
3325                 break;
3326         }
3327     }
3328
3329     matroska_clear_queue(matroska);
3330     if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
3331         goto err;
3332
3333     index_min = index;
3334     tracks = matroska->tracks.elem;
3335     for (i = 0; i < matroska->tracks.nb_elem; i++) {
3336         tracks[i].audio.pkt_cnt        = 0;
3337         tracks[i].audio.sub_packet_cnt = 0;
3338         tracks[i].audio.buf_timecode   = AV_NOPTS_VALUE;
3339         tracks[i].end_timecode         = 0;
3340         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
3341             tracks[i].stream &&
3342             tracks[i].stream->discard != AVDISCARD_ALL) {
3343             index_sub = av_index_search_timestamp(
3344                 tracks[i].stream, st->index_entries[index].timestamp,
3345                 AVSEEK_FLAG_BACKWARD);
3346             while (index_sub >= 0 &&
3347                   index_min > 0 &&
3348                   tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
3349                   st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
3350                 index_min--;
3351         }
3352     }
3353
3354     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
3355     matroska->current_id       = 0;
3356     if (flags & AVSEEK_FLAG_ANY) {
3357         st->skip_to_keyframe = 0;
3358         matroska->skip_to_timecode = timestamp;
3359     } else {
3360         st->skip_to_keyframe = 1;
3361         matroska->skip_to_timecode = st->index_entries[index].timestamp;
3362     }
3363     matroska->skip_to_keyframe = 1;
3364     matroska->done             = 0;
3365     matroska->num_levels       = 0;
3366     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
3367     return 0;
3368 err:
3369     // slightly hackish but allows proper fallback to
3370     // the generic seeking code.
3371     matroska_clear_queue(matroska);
3372     matroska->current_id = 0;
3373     st->skip_to_keyframe =
3374     matroska->skip_to_keyframe = 0;
3375     matroska->done = 0;
3376     matroska->num_levels = 0;
3377     return -1;
3378 }
3379
3380 static int matroska_read_close(AVFormatContext *s)
3381 {
3382     MatroskaDemuxContext *matroska = s->priv_data;
3383     MatroskaTrack *tracks = matroska->tracks.elem;
3384     int n;
3385
3386     matroska_clear_queue(matroska);
3387
3388     for (n = 0; n < matroska->tracks.nb_elem; n++)
3389         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
3390             av_freep(&tracks[n].audio.buf);
3391     ebml_free(matroska_cluster, &matroska->current_cluster);
3392     ebml_free(matroska_segment, matroska);
3393
3394     return 0;
3395 }
3396
3397 typedef struct {
3398     int64_t start_time_ns;
3399     int64_t end_time_ns;
3400     int64_t start_offset;
3401     int64_t end_offset;
3402 } CueDesc;
3403
3404 /* This function searches all the Cues and returns the CueDesc corresponding the
3405  * the timestamp ts. Returned CueDesc will be such that start_time_ns <= ts <
3406  * end_time_ns. All 4 fields will be set to -1 if ts >= file's duration.
3407  */
3408 static CueDesc get_cue_desc(AVFormatContext *s, int64_t ts, int64_t cues_start) {
3409     MatroskaDemuxContext *matroska = s->priv_data;
3410     CueDesc cue_desc;
3411     int i;
3412     int nb_index_entries = s->streams[0]->nb_index_entries;
3413     AVIndexEntry *index_entries = s->streams[0]->index_entries;
3414     if (ts >= matroska->duration * matroska->time_scale) return (CueDesc) {-1, -1, -1, -1};
3415     for (i = 1; i < nb_index_entries; i++) {
3416         if (index_entries[i - 1].timestamp * matroska->time_scale <= ts &&
3417             index_entries[i].timestamp * matroska->time_scale > ts) {
3418             break;
3419         }
3420     }
3421     --i;
3422     cue_desc.start_time_ns = index_entries[i].timestamp * matroska->time_scale;
3423     cue_desc.start_offset = index_entries[i].pos - matroska->segment_start;
3424     if (i != nb_index_entries - 1) {
3425         cue_desc.end_time_ns = index_entries[i + 1].timestamp * matroska->time_scale;
3426         cue_desc.end_offset = index_entries[i + 1].pos - matroska->segment_start;
3427     } else {
3428         cue_desc.end_time_ns = matroska->duration * matroska->time_scale;
3429         // FIXME: this needs special handling for files where Cues appear
3430         // before Clusters. the current logic assumes Cues appear after
3431         // Clusters.
3432         cue_desc.end_offset = cues_start - matroska->segment_start;
3433     }
3434     return cue_desc;
3435 }
3436
3437 static int webm_clusters_start_with_keyframe(AVFormatContext *s)
3438 {
3439     MatroskaDemuxContext *matroska = s->priv_data;
3440     int64_t cluster_pos, before_pos;
3441     int index, rv = 1;
3442     if (s->streams[0]->nb_index_entries <= 0) return 0;
3443     // seek to the first cluster using cues.
3444     index = av_index_search_timestamp(s->streams[0], 0, 0);
3445     if (index < 0)  return 0;
3446     cluster_pos = s->streams[0]->index_entries[index].pos;
3447     before_pos = avio_tell(s->pb);
3448     while (1) {
3449         int64_t cluster_id = 0, cluster_length = 0;
3450         AVPacket *pkt;
3451         avio_seek(s->pb, cluster_pos, SEEK_SET);
3452         // read cluster id and length
3453         ebml_read_num(matroska, matroska->ctx->pb, 4, &cluster_id);
3454         ebml_read_length(matroska, matroska->ctx->pb, &cluster_length);
3455         if (cluster_id != 0xF43B675) { // done with all clusters
3456             break;
3457         }
3458         avio_seek(s->pb, cluster_pos, SEEK_SET);
3459         matroska->current_id = 0;
3460         matroska_clear_queue(matroska);
3461         if (matroska_parse_cluster(matroska) < 0 ||
3462             matroska->num_packets <= 0) {
3463             break;
3464         }
3465         pkt = matroska->packets[0];
3466         cluster_pos += cluster_length + 12; // 12 is the offset of the cluster id and length.
3467         if (!(pkt->flags & AV_PKT_FLAG_KEY)) {
3468             rv = 0;
3469             break;
3470         }
3471     }
3472     avio_seek(s->pb, before_pos, SEEK_SET);
3473     return rv;
3474 }
3475
3476 static int buffer_size_after_time_downloaded(int64_t time_ns, double search_sec, int64_t bps,
3477                                              double min_buffer, double* buffer,
3478                                              double* sec_to_download, AVFormatContext *s,
3479                                              int64_t cues_start)
3480 {
3481     double nano_seconds_per_second = 1000000000.0;
3482     double time_sec = time_ns / nano_seconds_per_second;
3483     int rv = 0;
3484     int64_t time_to_search_ns = (int64_t)(search_sec * nano_seconds_per_second);
3485     int64_t end_time_ns = time_ns + time_to_search_ns;
3486     double sec_downloaded = 0.0;
3487     CueDesc desc_curr = get_cue_desc(s, time_ns, cues_start);
3488     if (desc_curr.start_time_ns == -1)
3489       return -1;
3490     *sec_to_download = 0.0;
3491
3492     // Check for non cue start time.
3493     if (time_ns > desc_curr.start_time_ns) {
3494       int64_t cue_nano = desc_curr.end_time_ns - time_ns;
3495       double percent = (double)(cue_nano) / (desc_curr.end_time_ns - desc_curr.start_time_ns);
3496       double cueBytes = (desc_curr.end_offset - desc_curr.start_offset) * percent;
3497       double timeToDownload = (cueBytes * 8.0) / bps;
3498
3499       sec_downloaded += (cue_nano / nano_seconds_per_second) - timeToDownload;
3500       *sec_to_download += timeToDownload;
3501
3502       // Check if the search ends within the first cue.
3503       if (desc_curr.end_time_ns >= end_time_ns) {
3504           double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
3505           double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
3506           sec_downloaded = percent_to_sub * sec_downloaded;
3507           *sec_to_download = percent_to_sub * *sec_to_download;
3508       }
3509
3510       if ((sec_downloaded + *buffer) <= min_buffer) {
3511           return 1;
3512       }
3513
3514       // Get the next Cue.
3515       desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
3516     }
3517
3518     while (desc_curr.start_time_ns != -1) {
3519         int64_t desc_bytes = desc_curr.end_offset - desc_curr.start_offset;
3520         int64_t desc_ns = desc_curr.end_time_ns - desc_curr.start_time_ns;
3521         double desc_sec = desc_ns / nano_seconds_per_second;
3522         double bits = (desc_bytes * 8.0);
3523         double time_to_download = bits / bps;
3524
3525         sec_downloaded += desc_sec - time_to_download;
3526         *sec_to_download += time_to_download;
3527
3528         if (desc_curr.end_time_ns >= end_time_ns) {
3529             double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
3530             double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
3531             sec_downloaded = percent_to_sub * sec_downloaded;
3532             *sec_to_download = percent_to_sub * *sec_to_download;
3533
3534             if ((sec_downloaded + *buffer) <= min_buffer)
3535                 rv = 1;
3536             break;
3537         }
3538
3539         if ((sec_downloaded + *buffer) <= min_buffer) {
3540             rv = 1;
3541             break;
3542         }
3543
3544         desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
3545     }
3546     *buffer = *buffer + sec_downloaded;
3547     return rv;
3548 }
3549
3550 /* This function computes the bandwidth of the WebM file with the help of
3551  * buffer_size_after_time_downloaded() function. Both of these functions are
3552  * adapted from WebM Tools project and are adapted to work with FFmpeg's
3553  * Matroska parsing mechanism.
3554  *
3555  * Returns the bandwidth of the file on success; -1 on error.
3556  * */
3557 static int64_t webm_dash_manifest_compute_bandwidth(AVFormatContext *s, int64_t cues_start)
3558 {
3559     MatroskaDemuxContext *matroska = s->priv_data;
3560     AVStream *st = s->streams[0];
3561     double bandwidth = 0.0;
3562     int i;
3563
3564     for (i = 0; i < st->nb_index_entries; i++) {
3565         int64_t prebuffer_ns = 1000000000;
3566         int64_t time_ns = st->index_entries[i].timestamp * matroska->time_scale;
3567         double nano_seconds_per_second = 1000000000.0;
3568         int64_t prebuffered_ns = time_ns + prebuffer_ns;
3569         double prebuffer_bytes = 0.0;
3570         int64_t temp_prebuffer_ns = prebuffer_ns;
3571         int64_t pre_bytes, pre_ns;
3572         double pre_sec, prebuffer, bits_per_second;
3573         CueDesc desc_beg = get_cue_desc(s, time_ns, cues_start);
3574
3575         // Start with the first Cue.
3576         CueDesc desc_end = desc_beg;
3577
3578         // Figure out how much data we have downloaded for the prebuffer. This will
3579         // be used later to adjust the bits per sample to try.
3580         while (desc_end.start_time_ns != -1 && desc_end.end_time_ns < prebuffered_ns) {
3581             // Prebuffered the entire Cue.
3582             prebuffer_bytes += desc_end.end_offset - desc_end.start_offset;
3583             temp_prebuffer_ns -= desc_end.end_time_ns - desc_end.start_time_ns;
3584             desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
3585         }
3586         if (desc_end.start_time_ns == -1) {
3587             // The prebuffer is larger than the duration.
3588             if (matroska->duration * matroska->time_scale >= prebuffered_ns)
3589               return -1;
3590             bits_per_second = 0.0;
3591         } else {
3592             // The prebuffer ends in the last Cue. Estimate how much data was
3593             // prebuffered.
3594             pre_bytes = desc_end.end_offset - desc_end.start_offset;
3595             pre_ns = desc_end.end_time_ns - desc_end.start_time_ns;
3596             pre_sec = pre_ns / nano_seconds_per_second;
3597             prebuffer_bytes +=
3598                 pre_bytes * ((temp_prebuffer_ns / nano_seconds_per_second) / pre_sec);
3599
3600             prebuffer = prebuffer_ns / nano_seconds_per_second;
3601
3602             // Set this to 0.0 in case our prebuffer buffers the entire video.
3603             bits_per_second = 0.0;
3604             do {
3605                 int64_t desc_bytes = desc_end.end_offset - desc_beg.start_offset;
3606                 int64_t desc_ns = desc_end.end_time_ns - desc_beg.start_time_ns;
3607                 double desc_sec = desc_ns / nano_seconds_per_second;
3608                 double calc_bits_per_second = (desc_bytes * 8) / desc_sec;
3609
3610                 // Drop the bps by the percentage of bytes buffered.
3611                 double percent = (desc_bytes - prebuffer_bytes) / desc_bytes;
3612                 double mod_bits_per_second = calc_bits_per_second * percent;
3613
3614                 if (prebuffer < desc_sec) {
3615                     double search_sec =
3616                         (double)(matroska->duration * matroska->time_scale) / nano_seconds_per_second;
3617
3618                     // Add 1 so the bits per second should be a little bit greater than file
3619                     // datarate.
3620                     int64_t bps = (int64_t)(mod_bits_per_second) + 1;
3621                     const double min_buffer = 0.0;
3622                     double buffer = prebuffer;
3623                     double sec_to_download = 0.0;
3624
3625                     int rv = buffer_size_after_time_downloaded(prebuffered_ns, search_sec, bps,
3626                                                                min_buffer, &buffer, &sec_to_download,
3627                                                                s, cues_start);
3628                     if (rv < 0) {
3629                         return -1;
3630                     } else if (rv == 0) {
3631                         bits_per_second = (double)(bps);
3632                         break;
3633                     }
3634                 }
3635
3636                 desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
3637             } while (desc_end.start_time_ns != -1);
3638         }
3639         if (bandwidth < bits_per_second) bandwidth = bits_per_second;
3640     }
3641     return (int64_t)bandwidth;
3642 }
3643
3644 static int webm_dash_manifest_cues(AVFormatContext *s)
3645 {
3646     MatroskaDemuxContext *matroska = s->priv_data;
3647     EbmlList *seekhead_list = &matroska->seekhead;
3648     MatroskaSeekhead *seekhead = seekhead_list->elem;
3649     char *buf;
3650     int64_t cues_start = -1, cues_end = -1, before_pos, bandwidth;
3651     int i;
3652
3653     // determine cues start and end positions
3654     for (i = 0; i < seekhead_list->nb_elem; i++)
3655         if (seekhead[i].id == MATROSKA_ID_CUES)
3656             break;
3657
3658     if (i >= seekhead_list->nb_elem) return -1;
3659
3660     before_pos = avio_tell(matroska->ctx->pb);
3661     cues_start = seekhead[i].pos + matroska->segment_start;
3662     if (avio_seek(matroska->ctx->pb, cues_start, SEEK_SET) == cues_start) {
3663         // cues_end is computed as cues_start + cues_length + length of the
3664         // Cues element ID + EBML length of the Cues element. cues_end is
3665         // inclusive and the above sum is reduced by 1.
3666         uint64_t cues_length = 0, cues_id = 0, bytes_read = 0;
3667         bytes_read += ebml_read_num(matroska, matroska->ctx->pb, 4, &cues_id);
3668         bytes_read += ebml_read_length(matroska, matroska->ctx->pb, &cues_length);
3669         cues_end = cues_start + cues_length + bytes_read - 1;
3670     }
3671     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
3672     if (cues_start == -1 || cues_end == -1) return -1;
3673
3674     // parse the cues
3675     matroska_parse_cues(matroska);
3676
3677     // cues start
3678     av_dict_set_int(&s->streams[0]->metadata, CUES_START, cues_start, 0);
3679
3680     // cues end
3681     av_dict_set_int(&s->streams[0]->metadata, CUES_END, cues_end, 0);
3682
3683     // bandwidth
3684     bandwidth = webm_dash_manifest_compute_bandwidth(s, cues_start);
3685     if (bandwidth < 0) return -1;
3686     av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH, bandwidth, 0);
3687
3688     // check if all clusters start with key frames
3689     av_dict_set_int(&s->streams[0]->metadata, CLUSTER_KEYFRAME, webm_clusters_start_with_keyframe(s), 0);
3690
3691     // store cue point timestamps as a comma separated list for checking subsegment alignment in
3692     // the muxer. assumes that each timestamp cannot be more than 20 characters long.
3693     buf = av_malloc_array(s->streams[0]->nb_index_entries, 20 * sizeof(char));
3694     if (!buf) return -1;
3695     strcpy(buf, "");
3696     for (i = 0; i < s->streams[0]->nb_index_entries; i++) {
3697         snprintf(buf, (i + 1) * 20 * sizeof(char),
3698                  "%s%" PRId64, buf, s->streams[0]->index_entries[i].timestamp);
3699         if (i != s->streams[0]->nb_index_entries - 1)
3700             strncat(buf, ",", sizeof(char));
3701     }
3702     av_dict_set(&s->streams[0]->metadata, CUE_TIMESTAMPS, buf, 0);
3703     av_free(buf);
3704
3705     return 0;
3706 }
3707
3708 static int webm_dash_manifest_read_header(AVFormatContext *s)
3709 {
3710     char *buf;
3711     int ret = matroska_read_header(s);
3712     MatroskaTrack *tracks;
3713     MatroskaDemuxContext *matroska = s->priv_data;
3714     if (ret) {
3715         av_log(s, AV_LOG_ERROR, "Failed to read file headers\n");
3716         return -1;
3717     }
3718
3719     if (!matroska->is_live) {
3720         buf = av_asprintf("%g", matroska->duration);
3721         if (!buf) return AVERROR(ENOMEM);
3722         av_dict_set(&s->streams[0]->metadata, DURATION, buf, 0);
3723         av_free(buf);
3724
3725         // initialization range
3726         // 5 is the offset of Cluster ID.
3727         av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, avio_tell(s->pb) - 5, 0);
3728     }
3729
3730     // basename of the file
3731     buf = strrchr(s->filename, '/');
3732     av_dict_set(&s->streams[0]->metadata, FILENAME, buf ? ++buf : s->filename, 0);
3733
3734     // track number
3735     tracks = matroska->tracks.elem;
3736     av_dict_set_int(&s->streams[0]->metadata, TRACK_NUMBER, tracks[0].num, 0);
3737
3738     // parse the cues and populate Cue related fields
3739     return matroska->is_live ? 0 : webm_dash_manifest_cues(s);
3740 }
3741
3742 static int webm_dash_manifest_read_packet(AVFormatContext *s, AVPacket *pkt)
3743 {
3744     return AVERROR_EOF;
3745 }
3746
3747 #define OFFSET(x) offsetof(MatroskaDemuxContext, x)
3748 static const AVOption options[] = {
3749     { "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 },
3750     { NULL },
3751 };
3752
3753 static const AVClass webm_dash_class = {
3754     .class_name = "WebM DASH Manifest demuxer",
3755     .item_name  = av_default_item_name,
3756     .option     = options,
3757     .version    = LIBAVUTIL_VERSION_INT,
3758 };
3759
3760 AVInputFormat ff_matroska_demuxer = {
3761     .name           = "matroska,webm",
3762     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
3763     .extensions     = "mkv,mk3d,mka,mks",
3764     .priv_data_size = sizeof(MatroskaDemuxContext),
3765     .read_probe     = matroska_probe,
3766     .read_header    = matroska_read_header,
3767     .read_packet    = matroska_read_packet,
3768     .read_close     = matroska_read_close,
3769     .read_seek      = matroska_read_seek,
3770     .mime_type      = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
3771 };
3772
3773 AVInputFormat ff_webm_dash_manifest_demuxer = {
3774     .name           = "webm_dash_manifest",
3775     .long_name      = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
3776     .priv_data_size = sizeof(MatroskaDemuxContext),
3777     .read_header    = webm_dash_manifest_read_header,
3778     .read_packet    = webm_dash_manifest_read_packet,
3779     .read_close     = matroska_read_close,
3780     .priv_class     = &webm_dash_class,
3781 };