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