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