]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
Merge commit '3c84f6b5d20cd345fac706f8cfb70c55e541ffb5'
[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 #if CONFIG_BZLIB
36 #include <bzlib.h>
37 #endif
38 #if CONFIG_ZLIB
39 #include <zlib.h>
40 #endif
41
42 #include "libavutil/avstring.h"
43 #include "libavutil/base64.h"
44 #include "libavutil/dict.h"
45 #include "libavutil/intfloat.h"
46 #include "libavutil/intreadwrite.h"
47 #include "libavutil/lzo.h"
48
49 #include "libavcodec/bytestream.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 /* For ff_codec_get_id(). */
58 #include "riff.h"
59 #include "rmsipr.h"
60
61 typedef enum {
62     EBML_NONE,
63     EBML_UINT,
64     EBML_FLOAT,
65     EBML_STR,
66     EBML_UTF8,
67     EBML_BIN,
68     EBML_NEST,
69     EBML_PASS,
70     EBML_STOP,
71     EBML_SINT,
72     EBML_TYPE_COUNT
73 } EbmlType;
74
75 typedef const struct EbmlSyntax {
76     uint32_t id;
77     EbmlType type;
78     int list_elem_size;
79     int data_offset;
80     union {
81         uint64_t    u;
82         double      f;
83         const char *s;
84         const struct EbmlSyntax *n;
85     } def;
86 } EbmlSyntax;
87
88 typedef struct {
89     int nb_elem;
90     void *elem;
91 } EbmlList;
92
93 typedef struct {
94     int      size;
95     uint8_t *data;
96     int64_t  pos;
97 } EbmlBin;
98
99 typedef struct {
100     uint64_t version;
101     uint64_t max_size;
102     uint64_t id_length;
103     char    *doctype;
104     uint64_t doctype_version;
105 } Ebml;
106
107 typedef struct {
108     uint64_t algo;
109     EbmlBin  settings;
110 } MatroskaTrackCompression;
111
112 typedef struct {
113     uint64_t algo;
114     EbmlBin  key_id;
115 } MatroskaTrackEncryption;
116
117 typedef struct {
118     uint64_t scope;
119     uint64_t type;
120     MatroskaTrackCompression compression;
121     MatroskaTrackEncryption encryption;
122 } MatroskaTrackEncoding;
123
124 typedef struct {
125     double   frame_rate;
126     uint64_t display_width;
127     uint64_t display_height;
128     uint64_t pixel_width;
129     uint64_t pixel_height;
130     EbmlBin color_space;
131     uint64_t stereo_mode;
132     uint64_t alpha_mode;
133 } MatroskaTrackVideo;
134
135 typedef struct {
136     double   samplerate;
137     double   out_samplerate;
138     uint64_t bitdepth;
139     uint64_t channels;
140
141     /* real audio header (extracted from extradata) */
142     int      coded_framesize;
143     int      sub_packet_h;
144     int      frame_size;
145     int      sub_packet_size;
146     int      sub_packet_cnt;
147     int      pkt_cnt;
148     uint64_t buf_timecode;
149     uint8_t *buf;
150 } MatroskaTrackAudio;
151
152 typedef struct {
153     uint64_t uid;
154     uint64_t type;
155 } MatroskaTrackPlane;
156
157 typedef struct {
158     EbmlList combine_planes;
159 } MatroskaTrackOperation;
160
161 typedef struct {
162     uint64_t num;
163     uint64_t uid;
164     uint64_t type;
165     char    *name;
166     char    *codec_id;
167     EbmlBin  codec_priv;
168     char    *language;
169     double time_scale;
170     uint64_t default_duration;
171     uint64_t flag_default;
172     uint64_t flag_forced;
173     uint64_t codec_delay;
174     uint64_t seek_preroll;
175     MatroskaTrackVideo video;
176     MatroskaTrackAudio audio;
177     MatroskaTrackOperation operation;
178     EbmlList encodings;
179
180     AVStream *stream;
181     int64_t end_timecode;
182     int ms_compat;
183     uint64_t max_block_additional_id;
184 } MatroskaTrack;
185
186 typedef struct {
187     uint64_t uid;
188     char *filename;
189     char *mime;
190     EbmlBin bin;
191
192     AVStream *stream;
193 } MatroskaAttachment;
194
195 typedef struct {
196     uint64_t start;
197     uint64_t end;
198     uint64_t uid;
199     char    *title;
200
201     AVChapter *chapter;
202 } MatroskaChapter;
203
204 typedef struct {
205     uint64_t track;
206     uint64_t pos;
207 } MatroskaIndexPos;
208
209 typedef struct {
210     uint64_t time;
211     EbmlList pos;
212 } MatroskaIndex;
213
214 typedef struct {
215     char *name;
216     char *string;
217     char *lang;
218     uint64_t def;
219     EbmlList sub;
220 } MatroskaTag;
221
222 typedef struct {
223     char    *type;
224     uint64_t typevalue;
225     uint64_t trackuid;
226     uint64_t chapteruid;
227     uint64_t attachuid;
228 } MatroskaTagTarget;
229
230 typedef struct {
231     MatroskaTagTarget target;
232     EbmlList tag;
233 } MatroskaTags;
234
235 typedef struct {
236     uint64_t id;
237     uint64_t pos;
238 } MatroskaSeekhead;
239
240 typedef struct {
241     uint64_t start;
242     uint64_t length;
243 } MatroskaLevel;
244
245 typedef struct {
246     uint64_t timecode;
247     EbmlList blocks;
248 } MatroskaCluster;
249
250 typedef struct {
251     AVFormatContext *ctx;
252
253     /* EBML stuff */
254     int num_levels;
255     MatroskaLevel levels[EBML_MAX_DEPTH];
256     int level_up;
257     uint32_t current_id;
258
259     uint64_t time_scale;
260     double   duration;
261     char    *title;
262     char    *muxingapp;
263     EbmlBin date_utc;
264     EbmlList tracks;
265     EbmlList attachments;
266     EbmlList chapters;
267     EbmlList index;
268     EbmlList tags;
269     EbmlList seekhead;
270
271     /* byte position of the segment inside the stream */
272     int64_t segment_start;
273
274     /* the packet queue */
275     AVPacket **packets;
276     int num_packets;
277     AVPacket *prev_pkt;
278
279     int done;
280
281     /* What to skip before effectively reading a packet. */
282     int skip_to_keyframe;
283     uint64_t skip_to_timecode;
284
285     /* File has a CUES element, but we defer parsing until it is needed. */
286     int cues_parsing_deferred;
287
288     int current_cluster_num_blocks;
289     int64_t current_cluster_pos;
290     MatroskaCluster current_cluster;
291
292     /* File has SSA subtitles which prevent incremental cluster parsing. */
293     int contains_ssa;
294 } MatroskaDemuxContext;
295
296 typedef struct {
297     uint64_t duration;
298     int64_t  reference;
299     uint64_t non_simple;
300     EbmlBin  bin;
301     uint64_t additional_id;
302     EbmlBin  additional;
303     int64_t discard_padding;
304 } MatroskaBlock;
305
306 static EbmlSyntax ebml_header[] = {
307     { EBML_ID_EBMLREADVERSION,    EBML_UINT, 0, offsetof(Ebml, version),         { .u = EBML_VERSION } },
308     { EBML_ID_EBMLMAXSIZELENGTH,  EBML_UINT, 0, offsetof(Ebml, max_size),        { .u = 8 } },
309     { EBML_ID_EBMLMAXIDLENGTH,    EBML_UINT, 0, offsetof(Ebml, id_length),       { .u = 4 } },
310     { EBML_ID_DOCTYPE,            EBML_STR,  0, offsetof(Ebml, doctype),         { .s = "(none)" } },
311     { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
312     { EBML_ID_EBMLVERSION,        EBML_NONE },
313     { EBML_ID_DOCTYPEVERSION,     EBML_NONE },
314     { 0 }
315 };
316
317 static EbmlSyntax ebml_syntax[] = {
318     { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
319     { 0 }
320 };
321
322 static EbmlSyntax matroska_info[] = {
323     { MATROSKA_ID_TIMECODESCALE, EBML_UINT,  0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
324     { MATROSKA_ID_DURATION,      EBML_FLOAT, 0, offsetof(MatroskaDemuxContext, duration) },
325     { MATROSKA_ID_TITLE,         EBML_UTF8,  0, offsetof(MatroskaDemuxContext, title) },
326     { MATROSKA_ID_WRITINGAPP,    EBML_NONE },
327     { MATROSKA_ID_MUXINGAPP,     EBML_UTF8, 0, offsetof(MatroskaDemuxContext, muxingapp) },
328     { MATROSKA_ID_DATEUTC,       EBML_BIN,  0, offsetof(MatroskaDemuxContext, date_utc) },
329     { MATROSKA_ID_SEGMENTUID,    EBML_NONE },
330     { 0 }
331 };
332
333 static EbmlSyntax matroska_track_video[] = {
334     { MATROSKA_ID_VIDEOFRAMERATE,      EBML_FLOAT, 0, offsetof(MatroskaTrackVideo, frame_rate) },
335     { MATROSKA_ID_VIDEODISPLAYWIDTH,   EBML_UINT,  0, offsetof(MatroskaTrackVideo, display_width), { .u=-1 } },
336     { MATROSKA_ID_VIDEODISPLAYHEIGHT,  EBML_UINT,  0, offsetof(MatroskaTrackVideo, display_height), { .u=-1 } },
337     { MATROSKA_ID_VIDEOPIXELWIDTH,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, pixel_width) },
338     { MATROSKA_ID_VIDEOPIXELHEIGHT,    EBML_UINT,  0, offsetof(MatroskaTrackVideo, pixel_height) },
339     { MATROSKA_ID_VIDEOCOLORSPACE,     EBML_BIN,   0, offsetof(MatroskaTrackVideo, color_space) },
340     { MATROSKA_ID_VIDEOSTEREOMODE,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, stereo_mode) },
341     { MATROSKA_ID_VIDEOALPHAMODE,      EBML_UINT,  0, offsetof(MatroskaTrackVideo, alpha_mode) },
342     { MATROSKA_ID_VIDEOPIXELCROPB,     EBML_NONE },
343     { MATROSKA_ID_VIDEOPIXELCROPT,     EBML_NONE },
344     { MATROSKA_ID_VIDEOPIXELCROPL,     EBML_NONE },
345     { MATROSKA_ID_VIDEOPIXELCROPR,     EBML_NONE },
346     { MATROSKA_ID_VIDEODISPLAYUNIT,    EBML_NONE },
347     { MATROSKA_ID_VIDEOFLAGINTERLACED, EBML_NONE },
348     { MATROSKA_ID_VIDEOASPECTRATIO,    EBML_NONE },
349     { 0 }
350 };
351
352 static EbmlSyntax matroska_track_audio[] = {
353     { MATROSKA_ID_AUDIOSAMPLINGFREQ,    EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
354     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
355     { MATROSKA_ID_AUDIOBITDEPTH,        EBML_UINT,  0, offsetof(MatroskaTrackAudio, bitdepth) },
356     { MATROSKA_ID_AUDIOCHANNELS,        EBML_UINT,  0, offsetof(MatroskaTrackAudio, channels),   { .u = 1 } },
357     { 0 }
358 };
359
360 static EbmlSyntax matroska_track_encoding_compression[] = {
361     { MATROSKA_ID_ENCODINGCOMPALGO,     EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
362     { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN,  0, offsetof(MatroskaTrackCompression, settings) },
363     { 0 }
364 };
365
366 static EbmlSyntax matroska_track_encoding_encryption[] = {
367     { MATROSKA_ID_ENCODINGENCALGO,        EBML_UINT, 0, offsetof(MatroskaTrackEncryption,algo), {.u = 0} },
368     { MATROSKA_ID_ENCODINGENCKEYID,       EBML_BIN, 0, offsetof(MatroskaTrackEncryption,key_id) },
369     { MATROSKA_ID_ENCODINGENCAESSETTINGS, EBML_NONE },
370     { MATROSKA_ID_ENCODINGSIGALGO,        EBML_NONE },
371     { MATROSKA_ID_ENCODINGSIGHASHALGO,    EBML_NONE },
372     { MATROSKA_ID_ENCODINGSIGKEYID,       EBML_NONE },
373     { MATROSKA_ID_ENCODINGSIGNATURE,      EBML_NONE },
374     { 0 }
375 };
376 static EbmlSyntax matroska_track_encoding[] = {
377     { MATROSKA_ID_ENCODINGSCOPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding, scope),       { .u = 1 } },
378     { MATROSKA_ID_ENCODINGTYPE,        EBML_UINT, 0, offsetof(MatroskaTrackEncoding, type),        { .u = 0 } },
379     { MATROSKA_ID_ENCODINGCOMPRESSION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, compression), { .n = matroska_track_encoding_compression } },
380     { MATROSKA_ID_ENCODINGENCRYPTION,  EBML_NEST, 0, offsetof(MatroskaTrackEncoding, encryption),  { .n = matroska_track_encoding_encryption } },
381     { MATROSKA_ID_ENCODINGORDER,       EBML_NONE },
382     { 0 }
383 };
384
385 static EbmlSyntax matroska_track_encodings[] = {
386     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
387     { 0 }
388 };
389
390 static EbmlSyntax matroska_track_plane[] = {
391     { MATROSKA_ID_TRACKPLANEUID,  EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
392     { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
393     { 0 }
394 };
395
396 static EbmlSyntax matroska_track_combine_planes[] = {
397     { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n = matroska_track_plane} },
398     { 0 }
399 };
400
401 static EbmlSyntax matroska_track_operation[] = {
402     { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n = matroska_track_combine_planes} },
403     { 0 }
404 };
405
406 static EbmlSyntax matroska_track[] = {
407     { MATROSKA_ID_TRACKNUMBER,           EBML_UINT,  0, offsetof(MatroskaTrack, num) },
408     { MATROSKA_ID_TRACKNAME,             EBML_UTF8,  0, offsetof(MatroskaTrack, name) },
409     { MATROSKA_ID_TRACKUID,              EBML_UINT,  0, offsetof(MatroskaTrack, uid) },
410     { MATROSKA_ID_TRACKTYPE,             EBML_UINT,  0, offsetof(MatroskaTrack, type) },
411     { MATROSKA_ID_CODECID,               EBML_STR,   0, offsetof(MatroskaTrack, codec_id) },
412     { MATROSKA_ID_CODECPRIVATE,          EBML_BIN,   0, offsetof(MatroskaTrack, codec_priv) },
413     { MATROSKA_ID_TRACKLANGUAGE,         EBML_UTF8,  0, offsetof(MatroskaTrack, language),     { .s = "eng" } },
414     { MATROSKA_ID_TRACKDEFAULTDURATION,  EBML_UINT,  0, offsetof(MatroskaTrack, default_duration) },
415     { MATROSKA_ID_TRACKTIMECODESCALE,    EBML_FLOAT, 0, offsetof(MatroskaTrack, time_scale),   { .f = 1.0 } },
416     { MATROSKA_ID_TRACKFLAGDEFAULT,      EBML_UINT,  0, offsetof(MatroskaTrack, flag_default), { .u = 1 } },
417     { MATROSKA_ID_TRACKFLAGFORCED,       EBML_UINT,  0, offsetof(MatroskaTrack, flag_forced),  { .u = 0 } },
418     { MATROSKA_ID_TRACKVIDEO,            EBML_NEST,  0, offsetof(MatroskaTrack, video),        { .n = matroska_track_video } },
419     { MATROSKA_ID_TRACKAUDIO,            EBML_NEST,  0, offsetof(MatroskaTrack, audio),        { .n = matroska_track_audio } },
420     { MATROSKA_ID_TRACKOPERATION,        EBML_NEST,  0, offsetof(MatroskaTrack, operation),    { .n = matroska_track_operation } },
421     { MATROSKA_ID_TRACKCONTENTENCODINGS, EBML_NEST,  0, 0,                                     { .n = matroska_track_encodings } },
422     { MATROSKA_ID_TRACKMAXBLKADDID,      EBML_UINT,  0, offsetof(MatroskaTrack, max_block_additional_id) },
423     { MATROSKA_ID_CODECDELAY,            EBML_UINT,  0, offsetof(MatroskaTrack, codec_delay) },
424     { MATROSKA_ID_SEEKPREROLL,           EBML_UINT,  0, offsetof(MatroskaTrack, seek_preroll) },
425     { MATROSKA_ID_TRACKFLAGENABLED,      EBML_NONE },
426     { MATROSKA_ID_TRACKFLAGLACING,       EBML_NONE },
427     { MATROSKA_ID_CODECNAME,             EBML_NONE },
428     { MATROSKA_ID_CODECDECODEALL,        EBML_NONE },
429     { MATROSKA_ID_CODECINFOURL,          EBML_NONE },
430     { MATROSKA_ID_CODECDOWNLOADURL,      EBML_NONE },
431     { MATROSKA_ID_TRACKMINCACHE,         EBML_NONE },
432     { MATROSKA_ID_TRACKMAXCACHE,         EBML_NONE },
433     { 0 }
434 };
435
436 static EbmlSyntax matroska_tracks[] = {
437     { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
438     { 0 }
439 };
440
441 static EbmlSyntax matroska_attachment[] = {
442     { MATROSKA_ID_FILEUID,      EBML_UINT, 0, offsetof(MatroskaAttachment, uid) },
443     { MATROSKA_ID_FILENAME,     EBML_UTF8, 0, offsetof(MatroskaAttachment, filename) },
444     { MATROSKA_ID_FILEMIMETYPE, EBML_STR,  0, offsetof(MatroskaAttachment, mime) },
445     { MATROSKA_ID_FILEDATA,     EBML_BIN,  0, offsetof(MatroskaAttachment, bin) },
446     { MATROSKA_ID_FILEDESC,     EBML_NONE },
447     { 0 }
448 };
449
450 static EbmlSyntax matroska_attachments[] = {
451     { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
452     { 0 }
453 };
454
455 static EbmlSyntax matroska_chapter_display[] = {
456     { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
457     { MATROSKA_ID_CHAPLANG,   EBML_NONE },
458     { 0 }
459 };
460
461 static EbmlSyntax matroska_chapter_entry[] = {
462     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
463     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter, end),   { .u = AV_NOPTS_VALUE } },
464     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter, uid) },
465     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0,                        0,         { .n = matroska_chapter_display } },
466     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
467     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
468     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
469     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
470     { 0 }
471 };
472
473 static EbmlSyntax matroska_chapter[] = {
474     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
475     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
476     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
477     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
478     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
479     { 0 }
480 };
481
482 static EbmlSyntax matroska_chapters[] = {
483     { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
484     { 0 }
485 };
486
487 static EbmlSyntax matroska_index_pos[] = {
488     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
489     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
490     { MATROSKA_ID_CUERELATIVEPOSITION,EBML_NONE },
491     { MATROSKA_ID_CUEDURATION,        EBML_NONE },
492     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
493     { 0 }
494 };
495
496 static EbmlSyntax matroska_index_entry[] = {
497     { MATROSKA_ID_CUETIME,          EBML_UINT, 0,                        offsetof(MatroskaIndex, time) },
498     { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex, pos), { .n = matroska_index_pos } },
499     { 0 }
500 };
501
502 static EbmlSyntax matroska_index[] = {
503     { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
504     { 0 }
505 };
506
507 static EbmlSyntax matroska_simpletag[] = {
508     { MATROSKA_ID_TAGNAME,        EBML_UTF8, 0,                   offsetof(MatroskaTag, name) },
509     { MATROSKA_ID_TAGSTRING,      EBML_UTF8, 0,                   offsetof(MatroskaTag, string) },
510     { MATROSKA_ID_TAGLANG,        EBML_STR,  0,                   offsetof(MatroskaTag, lang), { .s = "und" } },
511     { MATROSKA_ID_TAGDEFAULT,     EBML_UINT, 0,                   offsetof(MatroskaTag, def) },
512     { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0,                   offsetof(MatroskaTag, def) },
513     { MATROSKA_ID_SIMPLETAG,      EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag, sub),  { .n = matroska_simpletag } },
514     { 0 }
515 };
516
517 static EbmlSyntax matroska_tagtargets[] = {
518     { MATROSKA_ID_TAGTARGETS_TYPE,       EBML_STR,  0, offsetof(MatroskaTagTarget, type) },
519     { MATROSKA_ID_TAGTARGETS_TYPEVALUE,  EBML_UINT, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
520     { MATROSKA_ID_TAGTARGETS_TRACKUID,   EBML_UINT, 0, offsetof(MatroskaTagTarget, trackuid) },
521     { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, chapteruid) },
522     { MATROSKA_ID_TAGTARGETS_ATTACHUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget, attachuid) },
523     { 0 }
524 };
525
526 static EbmlSyntax matroska_tag[] = {
527     { MATROSKA_ID_SIMPLETAG,  EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags, tag),    { .n = matroska_simpletag } },
528     { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0,                   offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
529     { 0 }
530 };
531
532 static EbmlSyntax matroska_tags[] = {
533     { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
534     { 0 }
535 };
536
537 static EbmlSyntax matroska_seekhead_entry[] = {
538     { MATROSKA_ID_SEEKID,       EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
539     { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
540     { 0 }
541 };
542
543 static EbmlSyntax matroska_seekhead[] = {
544     { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
545     { 0 }
546 };
547
548 static EbmlSyntax matroska_segment[] = {
549     { MATROSKA_ID_INFO,        EBML_NEST, 0, 0, { .n = matroska_info } },
550     { MATROSKA_ID_TRACKS,      EBML_NEST, 0, 0, { .n = matroska_tracks } },
551     { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, { .n = matroska_attachments } },
552     { MATROSKA_ID_CHAPTERS,    EBML_NEST, 0, 0, { .n = matroska_chapters } },
553     { MATROSKA_ID_CUES,        EBML_NEST, 0, 0, { .n = matroska_index } },
554     { MATROSKA_ID_TAGS,        EBML_NEST, 0, 0, { .n = matroska_tags } },
555     { MATROSKA_ID_SEEKHEAD,    EBML_NEST, 0, 0, { .n = matroska_seekhead } },
556     { MATROSKA_ID_CLUSTER,     EBML_STOP },
557     { 0 }
558 };
559
560 static EbmlSyntax matroska_segments[] = {
561     { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
562     { 0 }
563 };
564
565 static EbmlSyntax matroska_blockmore[] = {
566     { MATROSKA_ID_BLOCKADDID,      EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
567     { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN,  0, offsetof(MatroskaBlock,additional) },
568     { 0 }
569 };
570
571 static EbmlSyntax matroska_blockadditions[] = {
572     { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n = matroska_blockmore} },
573     { 0 }
574 };
575
576 static EbmlSyntax matroska_blockgroup[] = {
577     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock, bin) },
578     { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, { .n = matroska_blockadditions} },
579     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock, bin) },
580     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock, duration) },
581     { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, offsetof(MatroskaBlock, discard_padding) },
582     { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock, reference) },
583     { MATROSKA_ID_CODECSTATE,     EBML_NONE },
584     {                          1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
585     { 0 }
586 };
587
588 static EbmlSyntax matroska_cluster[] = {
589     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0,                     offsetof(MatroskaCluster, timecode) },
590     { MATROSKA_ID_BLOCKGROUP,      EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
591     { MATROSKA_ID_SIMPLEBLOCK,     EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
592     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
593     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
594     { 0 }
595 };
596
597 static EbmlSyntax matroska_clusters[] = {
598     { MATROSKA_ID_CLUSTER,  EBML_NEST, 0, 0, { .n = matroska_cluster } },
599     { MATROSKA_ID_INFO,     EBML_NONE },
600     { MATROSKA_ID_CUES,     EBML_NONE },
601     { MATROSKA_ID_TAGS,     EBML_NONE },
602     { MATROSKA_ID_SEEKHEAD, EBML_NONE },
603     { 0 }
604 };
605
606 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
607     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0,                     offsetof(MatroskaCluster, timecode) },
608     { MATROSKA_ID_BLOCKGROUP,      EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
609     { MATROSKA_ID_SIMPLEBLOCK,     EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
610     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
611     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
612     { MATROSKA_ID_INFO,            EBML_NONE },
613     { MATROSKA_ID_CUES,            EBML_NONE },
614     { MATROSKA_ID_TAGS,            EBML_NONE },
615     { MATROSKA_ID_SEEKHEAD,        EBML_NONE },
616     { MATROSKA_ID_CLUSTER,         EBML_STOP },
617     { 0 }
618 };
619
620 static EbmlSyntax matroska_cluster_incremental[] = {
621     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
622     { MATROSKA_ID_BLOCKGROUP,      EBML_STOP },
623     { MATROSKA_ID_SIMPLEBLOCK,     EBML_STOP },
624     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
625     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
626     { 0 }
627 };
628
629 static EbmlSyntax matroska_clusters_incremental[] = {
630     { MATROSKA_ID_CLUSTER,  EBML_NEST, 0, 0, { .n = matroska_cluster_incremental } },
631     { MATROSKA_ID_INFO,     EBML_NONE },
632     { MATROSKA_ID_CUES,     EBML_NONE },
633     { MATROSKA_ID_TAGS,     EBML_NONE },
634     { MATROSKA_ID_SEEKHEAD, EBML_NONE },
635     { 0 }
636 };
637
638 static const char *const matroska_doctypes[] = { "matroska", "webm" };
639
640 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
641 {
642     AVIOContext *pb = matroska->ctx->pb;
643     uint32_t id;
644     matroska->current_id = 0;
645     matroska->num_levels = 0;
646
647     /* seek to next position to resync from */
648     if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
649         goto eof;
650
651     id = avio_rb32(pb);
652
653     // try to find a toplevel element
654     while (!url_feof(pb)) {
655         if (id == MATROSKA_ID_INFO     || id == MATROSKA_ID_TRACKS      ||
656             id == MATROSKA_ID_CUES     || id == MATROSKA_ID_TAGS        ||
657             id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
658             id == MATROSKA_ID_CLUSTER  || id == MATROSKA_ID_CHAPTERS) {
659             matroska->current_id = id;
660             return 0;
661         }
662         id = (id << 8) | avio_r8(pb);
663     }
664
665 eof:
666     matroska->done = 1;
667     return AVERROR_EOF;
668 }
669
670 /*
671  * Return: Whether we reached the end of a level in the hierarchy or not.
672  */
673 static int ebml_level_end(MatroskaDemuxContext *matroska)
674 {
675     AVIOContext *pb = matroska->ctx->pb;
676     int64_t pos = avio_tell(pb);
677
678     if (matroska->num_levels > 0) {
679         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
680         if (pos - level->start >= level->length || matroska->current_id) {
681             matroska->num_levels--;
682             return 1;
683         }
684     }
685     return 0;
686 }
687
688 /*
689  * Read: an "EBML number", which is defined as a variable-length
690  * array of bytes. The first byte indicates the length by giving a
691  * number of 0-bits followed by a one. The position of the first
692  * "one" bit inside the first byte indicates the length of this
693  * number.
694  * Returns: number of bytes read, < 0 on error
695  */
696 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
697                          int max_size, uint64_t *number)
698 {
699     int read = 1, n = 1;
700     uint64_t total = 0;
701
702     /* The first byte tells us the length in bytes - avio_r8() can normally
703      * return 0, but since that's not a valid first ebmlID byte, we can
704      * use it safely here to catch EOS. */
705     if (!(total = avio_r8(pb))) {
706         /* we might encounter EOS here */
707         if (!url_feof(pb)) {
708             int64_t pos = avio_tell(pb);
709             av_log(matroska->ctx, AV_LOG_ERROR,
710                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
711                    pos, pos);
712             return pb->error ? pb->error : AVERROR(EIO);
713         }
714         return AVERROR_EOF;
715     }
716
717     /* get the length of the EBML number */
718     read = 8 - ff_log2_tab[total];
719     if (read > max_size) {
720         int64_t pos = avio_tell(pb) - 1;
721         av_log(matroska->ctx, AV_LOG_ERROR,
722                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
723                (uint8_t) total, pos, pos);
724         return AVERROR_INVALIDDATA;
725     }
726
727     /* read out length */
728     total ^= 1 << ff_log2_tab[total];
729     while (n++ < read)
730         total = (total << 8) | avio_r8(pb);
731
732     *number = total;
733
734     return read;
735 }
736
737 /**
738  * Read a EBML length value.
739  * This needs special handling for the "unknown length" case which has multiple
740  * encodings.
741  */
742 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
743                             uint64_t *number)
744 {
745     int res = ebml_read_num(matroska, pb, 8, number);
746     if (res > 0 && *number + 1 == 1ULL << (7 * res))
747         *number = 0xffffffffffffffULL;
748     return res;
749 }
750
751 /*
752  * Read the next element as an unsigned int.
753  * 0 is success, < 0 is failure.
754  */
755 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
756 {
757     int n = 0;
758
759     if (size > 8)
760         return AVERROR_INVALIDDATA;
761
762     /* big-endian ordering; build up number */
763     *num = 0;
764     while (n++ < size)
765         *num = (*num << 8) | avio_r8(pb);
766
767     return 0;
768 }
769
770 /*
771  * Read the next element as a signed int.
772  * 0 is success, < 0 is failure.
773  */
774 static int ebml_read_sint(AVIOContext *pb, int size, int64_t *num)
775 {
776     int n = 1;
777
778     if (size > 8)
779         return AVERROR_INVALIDDATA;
780
781     if (size == 0) {
782         *num = 0;
783     } else {
784         *num = sign_extend(avio_r8(pb), 8);
785
786         /* big-endian ordering; build up number */
787         while (n++ < size)
788             *num = (*num << 8) | avio_r8(pb);
789     }
790
791     return 0;
792 }
793
794 /*
795  * Read the next element as a float.
796  * 0 is success, < 0 is failure.
797  */
798 static int ebml_read_float(AVIOContext *pb, int size, double *num)
799 {
800     if (size == 0)
801         *num = 0;
802     else if (size == 4)
803         *num = av_int2float(avio_rb32(pb));
804     else if (size == 8)
805         *num = av_int2double(avio_rb64(pb));
806     else
807         return AVERROR_INVALIDDATA;
808
809     return 0;
810 }
811
812 /*
813  * Read the next element as an ASCII string.
814  * 0 is success, < 0 is failure.
815  */
816 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
817 {
818     char *res;
819
820     /* EBML strings are usually not 0-terminated, so we allocate one
821      * byte more, read the string and NULL-terminate it ourselves. */
822     if (!(res = av_malloc(size + 1)))
823         return AVERROR(ENOMEM);
824     if (avio_read(pb, (uint8_t *) res, size) != size) {
825         av_free(res);
826         return AVERROR(EIO);
827     }
828     (res)[size] = '\0';
829     av_free(*str);
830     *str = res;
831
832     return 0;
833 }
834
835 /*
836  * Read the next element as binary data.
837  * 0 is success, < 0 is failure.
838  */
839 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
840 {
841     av_fast_padded_malloc(&bin->data, &bin->size, length);
842     if (!bin->data)
843         return AVERROR(ENOMEM);
844
845     bin->size = length;
846     bin->pos  = avio_tell(pb);
847     if (avio_read(pb, bin->data, length) != length) {
848         av_freep(&bin->data);
849         bin->size = 0;
850         return AVERROR(EIO);
851     }
852
853     return 0;
854 }
855
856 /*
857  * Read the next element, but only the header. The contents
858  * are supposed to be sub-elements which can be read separately.
859  * 0 is success, < 0 is failure.
860  */
861 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
862 {
863     AVIOContext *pb = matroska->ctx->pb;
864     MatroskaLevel *level;
865
866     if (matroska->num_levels >= EBML_MAX_DEPTH) {
867         av_log(matroska->ctx, AV_LOG_ERROR,
868                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
869         return AVERROR(ENOSYS);
870     }
871
872     level         = &matroska->levels[matroska->num_levels++];
873     level->start  = avio_tell(pb);
874     level->length = length;
875
876     return 0;
877 }
878
879 /*
880  * Read signed/unsigned "EBML" numbers.
881  * Return: number of bytes processed, < 0 on error
882  */
883 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
884                                  uint8_t *data, uint32_t size, uint64_t *num)
885 {
886     AVIOContext pb;
887     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
888     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
889 }
890
891 /*
892  * Same as above, but signed.
893  */
894 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
895                                  uint8_t *data, uint32_t size, int64_t *num)
896 {
897     uint64_t unum;
898     int res;
899
900     /* read as unsigned number first */
901     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
902         return res;
903
904     /* make signed (weird way) */
905     *num = unum - ((1LL << (7 * res - 1)) - 1);
906
907     return res;
908 }
909
910 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
911                            EbmlSyntax *syntax, void *data);
912
913 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
914                          uint32_t id, void *data)
915 {
916     int i;
917     for (i = 0; syntax[i].id; i++)
918         if (id == syntax[i].id)
919             break;
920     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
921         matroska->num_levels > 0                   &&
922         matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
923         return 0;  // we reached the end of an unknown size cluster
924     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
925         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%"PRIX32"\n", id);
926         if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
927             return AVERROR_INVALIDDATA;
928     }
929     return ebml_parse_elem(matroska, &syntax[i], data);
930 }
931
932 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
933                       void *data)
934 {
935     if (!matroska->current_id) {
936         uint64_t id;
937         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
938         if (res < 0)
939             return res;
940         matroska->current_id = id | 1 << 7 * res;
941     }
942     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
943 }
944
945 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
946                            void *data)
947 {
948     int i, res = 0;
949
950     for (i = 0; syntax[i].id; i++)
951         switch (syntax[i].type) {
952         case EBML_UINT:
953             *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
954             break;
955         case EBML_FLOAT:
956             *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
957             break;
958         case EBML_STR:
959         case EBML_UTF8:
960             // the default may be NULL
961             if (syntax[i].def.s) {
962                 uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
963                 *dst = av_strdup(syntax[i].def.s);
964                 if (!*dst)
965                     return AVERROR(ENOMEM);
966             }
967             break;
968         }
969
970     while (!res && !ebml_level_end(matroska))
971         res = ebml_parse(matroska, syntax, data);
972
973     return res;
974 }
975
976 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
977                            EbmlSyntax *syntax, void *data)
978 {
979     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
980         [EBML_UINT]  = 8,
981         [EBML_FLOAT] = 8,
982         // max. 16 MB for strings
983         [EBML_STR]   = 0x1000000,
984         [EBML_UTF8]  = 0x1000000,
985         // max. 256 MB for binary data
986         [EBML_BIN]   = 0x10000000,
987         // no limits for anything else
988     };
989     AVIOContext *pb = matroska->ctx->pb;
990     uint32_t id = syntax->id;
991     uint64_t length;
992     int res;
993     void *newelem;
994
995     data = (char *) data + syntax->data_offset;
996     if (syntax->list_elem_size) {
997         EbmlList *list = data;
998         newelem = av_realloc_array(list->elem, list->nb_elem + 1, syntax->list_elem_size);
999         if (!newelem)
1000             return AVERROR(ENOMEM);
1001         list->elem = newelem;
1002         data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
1003         memset(data, 0, syntax->list_elem_size);
1004         list->nb_elem++;
1005     }
1006
1007     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
1008         matroska->current_id = 0;
1009         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
1010             return res;
1011         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
1012             av_log(matroska->ctx, AV_LOG_ERROR,
1013                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
1014                    length, max_lengths[syntax->type], syntax->type);
1015             return AVERROR_INVALIDDATA;
1016         }
1017     }
1018
1019     switch (syntax->type) {
1020     case EBML_UINT:
1021         res = ebml_read_uint(pb, length, data);
1022         break;
1023     case EBML_SINT:
1024         res = ebml_read_sint(pb, length, data);
1025         break;
1026     case EBML_FLOAT:
1027         res = ebml_read_float(pb, length, data);
1028         break;
1029     case EBML_STR:
1030     case EBML_UTF8:
1031         res = ebml_read_ascii(pb, length, data);
1032         break;
1033     case EBML_BIN:
1034         res = ebml_read_binary(pb, length, data);
1035         break;
1036     case EBML_NEST:
1037         if ((res = ebml_read_master(matroska, length)) < 0)
1038             return res;
1039         if (id == MATROSKA_ID_SEGMENT)
1040             matroska->segment_start = avio_tell(matroska->ctx->pb);
1041         return ebml_parse_nest(matroska, syntax->def.n, data);
1042     case EBML_PASS:
1043         return ebml_parse_id(matroska, syntax->def.n, id, data);
1044     case EBML_STOP:
1045         return 1;
1046     default:
1047         if (ffio_limit(pb, length) != length)
1048             return AVERROR(EIO);
1049         return avio_skip(pb, length) < 0 ? AVERROR(EIO) : 0;
1050     }
1051     if (res == AVERROR_INVALIDDATA)
1052         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
1053     else if (res == AVERROR(EIO))
1054         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
1055     return res;
1056 }
1057
1058 static void ebml_free(EbmlSyntax *syntax, void *data)
1059 {
1060     int i, j;
1061     for (i = 0; syntax[i].id; i++) {
1062         void *data_off = (char *) data + syntax[i].data_offset;
1063         switch (syntax[i].type) {
1064         case EBML_STR:
1065         case EBML_UTF8:
1066             av_freep(data_off);
1067             break;
1068         case EBML_BIN:
1069             av_freep(&((EbmlBin *) data_off)->data);
1070             break;
1071         case EBML_NEST:
1072             if (syntax[i].list_elem_size) {
1073                 EbmlList *list = data_off;
1074                 char *ptr = list->elem;
1075                 for (j = 0; j < list->nb_elem;
1076                      j++, ptr += syntax[i].list_elem_size)
1077                     ebml_free(syntax[i].def.n, ptr);
1078                 av_free(list->elem);
1079             } else
1080                 ebml_free(syntax[i].def.n, data_off);
1081         default:
1082             break;
1083         }
1084     }
1085 }
1086
1087 /*
1088  * Autodetecting...
1089  */
1090 static int matroska_probe(AVProbeData *p)
1091 {
1092     uint64_t total = 0;
1093     int len_mask = 0x80, size = 1, n = 1, i;
1094
1095     /* EBML header? */
1096     if (AV_RB32(p->buf) != EBML_ID_HEADER)
1097         return 0;
1098
1099     /* length of header */
1100     total = p->buf[4];
1101     while (size <= 8 && !(total & len_mask)) {
1102         size++;
1103         len_mask >>= 1;
1104     }
1105     if (size > 8)
1106         return 0;
1107     total &= (len_mask - 1);
1108     while (n < size)
1109         total = (total << 8) | p->buf[4 + n++];
1110
1111     /* Does the probe data contain the whole header? */
1112     if (p->buf_size < 4 + size + total)
1113         return 0;
1114
1115     /* The header should contain a known document type. For now,
1116      * we don't parse the whole header but simply check for the
1117      * availability of that array of characters inside the header.
1118      * Not fully fool-proof, but good enough. */
1119     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1120         int probelen = strlen(matroska_doctypes[i]);
1121         if (total < probelen)
1122             continue;
1123         for (n = 4 + size; n <= 4 + size + total - probelen; n++)
1124             if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
1125                 return AVPROBE_SCORE_MAX;
1126     }
1127
1128     // probably valid EBML header but no recognized doctype
1129     return AVPROBE_SCORE_EXTENSION;
1130 }
1131
1132 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1133                                                  int num)
1134 {
1135     MatroskaTrack *tracks = matroska->tracks.elem;
1136     int i;
1137
1138     for (i = 0; i < matroska->tracks.nb_elem; i++)
1139         if (tracks[i].num == num)
1140             return &tracks[i];
1141
1142     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1143     return NULL;
1144 }
1145
1146 static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
1147                                   MatroskaTrack *track)
1148 {
1149     MatroskaTrackEncoding *encodings = track->encodings.elem;
1150     uint8_t *data = *buf;
1151     int isize = *buf_size;
1152     uint8_t *pkt_data = NULL;
1153     uint8_t av_unused *newpktdata;
1154     int pkt_size = isize;
1155     int result = 0;
1156     int olen;
1157
1158     if (pkt_size >= 10000000U)
1159         return AVERROR_INVALIDDATA;
1160
1161     switch (encodings[0].compression.algo) {
1162     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1163     {
1164         int header_size = encodings[0].compression.settings.size;
1165         uint8_t *header = encodings[0].compression.settings.data;
1166
1167         if (header_size && !header) {
1168             av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1169             return -1;
1170         }
1171
1172         if (!header_size)
1173             return 0;
1174
1175         pkt_size = isize + header_size;
1176         pkt_data = av_malloc(pkt_size);
1177         if (!pkt_data)
1178             return AVERROR(ENOMEM);
1179
1180         memcpy(pkt_data, header, header_size);
1181         memcpy(pkt_data + header_size, data, isize);
1182         break;
1183     }
1184 #if CONFIG_LZO
1185     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1186         do {
1187             olen       = pkt_size *= 3;
1188             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1189             if (!newpktdata) {
1190                 result = AVERROR(ENOMEM);
1191                 goto failed;
1192             }
1193             pkt_data = newpktdata;
1194             result   = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1195         } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
1196         if (result) {
1197             result = AVERROR_INVALIDDATA;
1198             goto failed;
1199         }
1200         pkt_size -= olen;
1201         break;
1202 #endif
1203 #if CONFIG_ZLIB
1204     case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
1205     {
1206         z_stream zstream = { 0 };
1207         if (inflateInit(&zstream) != Z_OK)
1208             return -1;
1209         zstream.next_in  = data;
1210         zstream.avail_in = isize;
1211         do {
1212             pkt_size  *= 3;
1213             newpktdata = av_realloc(pkt_data, pkt_size);
1214             if (!newpktdata) {
1215                 inflateEnd(&zstream);
1216                 goto failed;
1217             }
1218             pkt_data          = newpktdata;
1219             zstream.avail_out = pkt_size - zstream.total_out;
1220             zstream.next_out  = pkt_data + zstream.total_out;
1221             if (pkt_data) {
1222                 result = inflate(&zstream, Z_NO_FLUSH);
1223             } else
1224                 result = Z_MEM_ERROR;
1225         } while (result == Z_OK && pkt_size < 10000000);
1226         pkt_size = zstream.total_out;
1227         inflateEnd(&zstream);
1228         if (result != Z_STREAM_END) {
1229             if (result == Z_MEM_ERROR)
1230                 result = AVERROR(ENOMEM);
1231             else
1232                 result = AVERROR_INVALIDDATA;
1233             goto failed;
1234         }
1235         break;
1236     }
1237 #endif
1238 #if CONFIG_BZLIB
1239     case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
1240     {
1241         bz_stream bzstream = { 0 };
1242         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1243             return -1;
1244         bzstream.next_in  = data;
1245         bzstream.avail_in = isize;
1246         do {
1247             pkt_size  *= 3;
1248             newpktdata = av_realloc(pkt_data, pkt_size);
1249             if (!newpktdata) {
1250                 BZ2_bzDecompressEnd(&bzstream);
1251                 goto failed;
1252             }
1253             pkt_data           = newpktdata;
1254             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1255             bzstream.next_out  = pkt_data + bzstream.total_out_lo32;
1256             if (pkt_data) {
1257                 result = BZ2_bzDecompress(&bzstream);
1258             } else
1259                 result = BZ_MEM_ERROR;
1260         } while (result == BZ_OK && pkt_size < 10000000);
1261         pkt_size = bzstream.total_out_lo32;
1262         BZ2_bzDecompressEnd(&bzstream);
1263         if (result != BZ_STREAM_END) {
1264             if (result == BZ_MEM_ERROR)
1265                 result = AVERROR(ENOMEM);
1266             else
1267                 result = AVERROR_INVALIDDATA;
1268             goto failed;
1269         }
1270         break;
1271     }
1272 #endif
1273     default:
1274         return AVERROR_INVALIDDATA;
1275     }
1276
1277     *buf      = pkt_data;
1278     *buf_size = pkt_size;
1279     return 0;
1280
1281 failed:
1282     av_free(pkt_data);
1283     return result;
1284 }
1285
1286 #if FF_API_ASS_SSA
1287 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1288                                     AVPacket *pkt, uint64_t display_duration)
1289 {
1290     AVBufferRef *line;
1291     char *layer, *ptr = pkt->data, *end = ptr + pkt->size;
1292
1293     for (; *ptr != ',' && ptr < end - 1; ptr++)
1294         ;
1295     if (*ptr == ',')
1296         ptr++;
1297     layer = ptr;
1298     for (; *ptr != ',' && ptr < end - 1; ptr++)
1299         ;
1300     if (*ptr == ',') {
1301         int64_t end_pts = pkt->pts + display_duration;
1302         int sc = matroska->time_scale * pkt->pts / 10000000;
1303         int ec = matroska->time_scale * end_pts  / 10000000;
1304         int sh, sm, ss, eh, em, es, len;
1305         sh     = sc / 360000;
1306         sc    -= 360000 * sh;
1307         sm     = sc / 6000;
1308         sc    -= 6000 * sm;
1309         ss     = sc / 100;
1310         sc    -= 100 * ss;
1311         eh     = ec / 360000;
1312         ec    -= 360000 * eh;
1313         em     = ec / 6000;
1314         ec    -= 6000 * em;
1315         es     = ec / 100;
1316         ec    -= 100 * es;
1317         *ptr++ = '\0';
1318         len    = 50 + end - ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1319         if (!(line = av_buffer_alloc(len)))
1320             return;
1321         snprintf(line->data, len,
1322                  "Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1323                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1324         av_buffer_unref(&pkt->buf);
1325         pkt->buf  = line;
1326         pkt->data = line->data;
1327         pkt->size = strlen(line->data);
1328     }
1329 }
1330
1331 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1332 {
1333     int ret = av_grow_packet(out, in->size);
1334     if (ret < 0)
1335         return ret;
1336
1337     memcpy(out->data + out->size - in->size, in->data, in->size);
1338
1339     av_free_packet(in);
1340     av_free(in);
1341     return 0;
1342 }
1343 #endif
1344
1345 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1346                                  AVDictionary **metadata, char *prefix)
1347 {
1348     MatroskaTag *tags = list->elem;
1349     char key[1024];
1350     int i;
1351
1352     for (i = 0; i < list->nb_elem; i++) {
1353         const char *lang = tags[i].lang &&
1354                            strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1355
1356         if (!tags[i].name) {
1357             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1358             continue;
1359         }
1360         if (prefix)
1361             snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1362         else
1363             av_strlcpy(key, tags[i].name, sizeof(key));
1364         if (tags[i].def || !lang) {
1365             av_dict_set(metadata, key, tags[i].string, 0);
1366             if (tags[i].sub.nb_elem)
1367                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1368         }
1369         if (lang) {
1370             av_strlcat(key, "-", sizeof(key));
1371             av_strlcat(key, lang, sizeof(key));
1372             av_dict_set(metadata, key, tags[i].string, 0);
1373             if (tags[i].sub.nb_elem)
1374                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1375         }
1376     }
1377     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1378 }
1379
1380 static void matroska_convert_tags(AVFormatContext *s)
1381 {
1382     MatroskaDemuxContext *matroska = s->priv_data;
1383     MatroskaTags *tags = matroska->tags.elem;
1384     int i, j;
1385
1386     for (i = 0; i < matroska->tags.nb_elem; i++) {
1387         if (tags[i].target.attachuid) {
1388             MatroskaAttachment *attachment = matroska->attachments.elem;
1389             for (j = 0; j < matroska->attachments.nb_elem; j++)
1390                 if (attachment[j].uid == tags[i].target.attachuid &&
1391                     attachment[j].stream)
1392                     matroska_convert_tag(s, &tags[i].tag,
1393                                          &attachment[j].stream->metadata, NULL);
1394         } else if (tags[i].target.chapteruid) {
1395             MatroskaChapter *chapter = matroska->chapters.elem;
1396             for (j = 0; j < matroska->chapters.nb_elem; j++)
1397                 if (chapter[j].uid == tags[i].target.chapteruid &&
1398                     chapter[j].chapter)
1399                     matroska_convert_tag(s, &tags[i].tag,
1400                                          &chapter[j].chapter->metadata, NULL);
1401         } else if (tags[i].target.trackuid) {
1402             MatroskaTrack *track = matroska->tracks.elem;
1403             for (j = 0; j < matroska->tracks.nb_elem; j++)
1404                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1405                     matroska_convert_tag(s, &tags[i].tag,
1406                                          &track[j].stream->metadata, NULL);
1407         } else {
1408             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1409                                  tags[i].target.type);
1410         }
1411     }
1412 }
1413
1414 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
1415                                          int idx)
1416 {
1417     EbmlList *seekhead_list = &matroska->seekhead;
1418     uint32_t level_up       = matroska->level_up;
1419     uint32_t saved_id       = matroska->current_id;
1420     MatroskaSeekhead *seekhead = seekhead_list->elem;
1421     int64_t before_pos = avio_tell(matroska->ctx->pb);
1422     MatroskaLevel level;
1423     int64_t offset;
1424     int ret = 0;
1425
1426     if (idx >= seekhead_list->nb_elem            ||
1427         seekhead[idx].id == MATROSKA_ID_SEEKHEAD ||
1428         seekhead[idx].id == MATROSKA_ID_CLUSTER)
1429         return 0;
1430
1431     /* seek */
1432     offset = seekhead[idx].pos + matroska->segment_start;
1433     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1434         /* We don't want to lose our seekhead level, so we add
1435          * a dummy. This is a crude hack. */
1436         if (matroska->num_levels == EBML_MAX_DEPTH) {
1437             av_log(matroska->ctx, AV_LOG_INFO,
1438                    "Max EBML element depth (%d) reached, "
1439                    "cannot parse further.\n", EBML_MAX_DEPTH);
1440             ret = AVERROR_INVALIDDATA;
1441         } else {
1442             level.start  = 0;
1443             level.length = (uint64_t) -1;
1444             matroska->levels[matroska->num_levels] = level;
1445             matroska->num_levels++;
1446             matroska->current_id                   = 0;
1447
1448             ret = ebml_parse(matroska, matroska_segment, matroska);
1449
1450             /* remove dummy level */
1451             while (matroska->num_levels) {
1452                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1453                 if (length == (uint64_t) -1)
1454                     break;
1455             }
1456         }
1457     }
1458     /* seek back */
1459     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1460     matroska->level_up   = level_up;
1461     matroska->current_id = saved_id;
1462
1463     return ret;
1464 }
1465
1466 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1467 {
1468     EbmlList *seekhead_list = &matroska->seekhead;
1469     int64_t before_pos = avio_tell(matroska->ctx->pb);
1470     int i;
1471
1472     // we should not do any seeking in the streaming case
1473     if (!matroska->ctx->pb->seekable ||
1474         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1475         return;
1476
1477     for (i = 0; i < seekhead_list->nb_elem; i++) {
1478         MatroskaSeekhead *seekhead = seekhead_list->elem;
1479         if (seekhead[i].pos <= before_pos)
1480             continue;
1481
1482         // defer cues parsing until we actually need cue data.
1483         if (seekhead[i].id == MATROSKA_ID_CUES) {
1484             matroska->cues_parsing_deferred = 1;
1485             continue;
1486         }
1487
1488         if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1489             // mark index as broken
1490             matroska->cues_parsing_deferred = -1;
1491             break;
1492         }
1493     }
1494 }
1495
1496 static void matroska_add_index_entries(MatroskaDemuxContext *matroska)
1497 {
1498     EbmlList *index_list;
1499     MatroskaIndex *index;
1500     int index_scale = 1;
1501     int i, j;
1502
1503     index_list = &matroska->index;
1504     index      = index_list->elem;
1505     if (index_list->nb_elem &&
1506         index[0].time > 1E14 / matroska->time_scale) {
1507         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1508         index_scale = matroska->time_scale;
1509     }
1510     for (i = 0; i < index_list->nb_elem; i++) {
1511         EbmlList *pos_list    = &index[i].pos;
1512         MatroskaIndexPos *pos = pos_list->elem;
1513         for (j = 0; j < pos_list->nb_elem; j++) {
1514             MatroskaTrack *track = matroska_find_track_by_num(matroska,
1515                                                               pos[j].track);
1516             if (track && track->stream)
1517                 av_add_index_entry(track->stream,
1518                                    pos[j].pos + matroska->segment_start,
1519                                    index[i].time / index_scale, 0, 0,
1520                                    AVINDEX_KEYFRAME);
1521         }
1522     }
1523 }
1524
1525 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1526     EbmlList *seekhead_list = &matroska->seekhead;
1527     MatroskaSeekhead *seekhead = seekhead_list->elem;
1528     int i;
1529
1530     for (i = 0; i < seekhead_list->nb_elem; i++)
1531         if (seekhead[i].id == MATROSKA_ID_CUES)
1532             break;
1533     av_assert1(i <= seekhead_list->nb_elem);
1534
1535     if (matroska_parse_seekhead_entry(matroska, i) < 0)
1536        matroska->cues_parsing_deferred = -1;
1537     matroska_add_index_entries(matroska);
1538 }
1539
1540 static int matroska_aac_profile(char *codec_id)
1541 {
1542     static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
1543     int profile;
1544
1545     for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
1546         if (strstr(codec_id, aac_profiles[profile]))
1547             break;
1548     return profile + 1;
1549 }
1550
1551 static int matroska_aac_sri(int samplerate)
1552 {
1553     int sri;
1554
1555     for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1556         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1557             break;
1558     return sri;
1559 }
1560
1561 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1562 {
1563     char buffer[32];
1564     /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1565     time_t creation_time = date_utc / 1000000000 + 978307200;
1566     struct tm *ptm = gmtime(&creation_time);
1567     if (!ptm) return;
1568     strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1569     av_dict_set(metadata, "creation_time", buffer, 0);
1570 }
1571
1572 static int matroska_read_header(AVFormatContext *s)
1573 {
1574     MatroskaDemuxContext *matroska = s->priv_data;
1575     EbmlList *attachments_list = &matroska->attachments;
1576     EbmlList *chapters_list    = &matroska->chapters;
1577     MatroskaAttachment *attachments;
1578     MatroskaChapter *chapters;
1579     MatroskaTrack *tracks;
1580     uint64_t max_start = 0;
1581     int64_t pos;
1582     Ebml ebml = { 0 };
1583     AVStream *st;
1584     int i, j, k, res;
1585
1586     matroska->ctx = s;
1587
1588     /* First read the EBML header. */
1589     if (ebml_parse(matroska, ebml_syntax, &ebml) ||
1590         ebml.version         > EBML_VERSION      ||
1591         ebml.max_size        > sizeof(uint64_t)  ||
1592         ebml.id_length       > sizeof(uint32_t)  ||
1593         ebml.doctype_version > 3                 ||
1594         !ebml.doctype) {
1595         av_log(matroska->ctx, AV_LOG_ERROR,
1596                "EBML header using unsupported features\n"
1597                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1598                ebml.version, ebml.doctype, ebml.doctype_version);
1599         ebml_free(ebml_syntax, &ebml);
1600         return AVERROR_PATCHWELCOME;
1601     } else if (ebml.doctype_version == 3) {
1602         av_log(matroska->ctx, AV_LOG_WARNING,
1603                "EBML header using unsupported features\n"
1604                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1605                ebml.version, ebml.doctype, ebml.doctype_version);
1606     }
1607     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1608         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1609             break;
1610     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1611         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1612         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1613             ebml_free(ebml_syntax, &ebml);
1614             return AVERROR_INVALIDDATA;
1615         }
1616     }
1617     ebml_free(ebml_syntax, &ebml);
1618
1619     /* The next thing is a segment. */
1620     pos = avio_tell(matroska->ctx->pb);
1621     res = ebml_parse(matroska, matroska_segments, matroska);
1622     // try resyncing until we find a EBML_STOP type element.
1623     while (res != 1) {
1624         res = matroska_resync(matroska, pos);
1625         if (res < 0)
1626             return res;
1627         pos = avio_tell(matroska->ctx->pb);
1628         res = ebml_parse(matroska, matroska_segment, matroska);
1629     }
1630     matroska_execute_seekhead(matroska);
1631
1632     if (!matroska->time_scale)
1633         matroska->time_scale = 1000000;
1634     if (matroska->duration)
1635         matroska->ctx->duration = matroska->duration * matroska->time_scale *
1636                                   1000 / AV_TIME_BASE;
1637     av_dict_set(&s->metadata, "title", matroska->title, 0);
1638     av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
1639
1640     if (matroska->date_utc.size == 8)
1641         matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
1642
1643     tracks = matroska->tracks.elem;
1644     for (i = 0; i < matroska->tracks.nb_elem; i++) {
1645         MatroskaTrack *track = &tracks[i];
1646         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1647         EbmlList *encodings_list = &track->encodings;
1648         MatroskaTrackEncoding *encodings = encodings_list->elem;
1649         uint8_t *extradata = NULL;
1650         int extradata_size = 0;
1651         int extradata_offset = 0;
1652         uint32_t fourcc = 0;
1653         AVIOContext b;
1654         char* key_id_base64 = NULL;
1655         int bit_depth = -1;
1656
1657         /* Apply some sanity checks. */
1658         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1659             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1660             track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
1661             track->type != MATROSKA_TRACK_TYPE_METADATA) {
1662             av_log(matroska->ctx, AV_LOG_INFO,
1663                    "Unknown or unsupported track type %"PRIu64"\n",
1664                    track->type);
1665             continue;
1666         }
1667         if (track->codec_id == NULL)
1668             continue;
1669
1670         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1671             if (!track->default_duration && track->video.frame_rate > 0)
1672                 track->default_duration = 1000000000 / track->video.frame_rate;
1673             if (track->video.display_width == -1)
1674                 track->video.display_width = track->video.pixel_width;
1675             if (track->video.display_height == -1)
1676                 track->video.display_height = track->video.pixel_height;
1677             if (track->video.color_space.size == 4)
1678                 fourcc = AV_RL32(track->video.color_space.data);
1679         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1680             if (!track->audio.out_samplerate)
1681                 track->audio.out_samplerate = track->audio.samplerate;
1682         }
1683         if (encodings_list->nb_elem > 1) {
1684             av_log(matroska->ctx, AV_LOG_ERROR,
1685                    "Multiple combined encodings not supported");
1686         } else if (encodings_list->nb_elem == 1) {
1687             if (encodings[0].type) {
1688                 if (encodings[0].encryption.key_id.size > 0) {
1689                     /* Save the encryption key id to be stored later as a
1690                        metadata tag. */
1691                     const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
1692                     key_id_base64 = av_malloc(b64_size);
1693                     if (key_id_base64 == NULL)
1694                         return AVERROR(ENOMEM);
1695
1696                     av_base64_encode(key_id_base64, b64_size,
1697                                      encodings[0].encryption.key_id.data,
1698                                      encodings[0].encryption.key_id.size);
1699                 } else {
1700                     encodings[0].scope = 0;
1701                     av_log(matroska->ctx, AV_LOG_ERROR,
1702                            "Unsupported encoding type");
1703                 }
1704             } else if (
1705 #if CONFIG_ZLIB
1706                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB  &&
1707 #endif
1708 #if CONFIG_BZLIB
1709                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1710 #endif
1711 #if CONFIG_LZO
1712                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO   &&
1713 #endif
1714                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
1715                 encodings[0].scope = 0;
1716                 av_log(matroska->ctx, AV_LOG_ERROR,
1717                        "Unsupported encoding type");
1718             } else if (track->codec_priv.size && encodings[0].scope & 2) {
1719                 uint8_t *codec_priv = track->codec_priv.data;
1720                 int ret = matroska_decode_buffer(&track->codec_priv.data,
1721                                                  &track->codec_priv.size,
1722                                                  track);
1723                 if (ret < 0) {
1724                     track->codec_priv.data = NULL;
1725                     track->codec_priv.size = 0;
1726                     av_log(matroska->ctx, AV_LOG_ERROR,
1727                            "Failed to decode codec private data\n");
1728                 }
1729
1730                 if (codec_priv != track->codec_priv.data)
1731                     av_free(codec_priv);
1732             }
1733         }
1734
1735         for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1736             if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1737                          strlen(ff_mkv_codec_tags[j].str))) {
1738                 codec_id = ff_mkv_codec_tags[j].id;
1739                 break;
1740             }
1741         }
1742
1743         st = track->stream = avformat_new_stream(s, NULL);
1744         if (st == NULL) {
1745             av_free(key_id_base64);
1746             return AVERROR(ENOMEM);
1747         }
1748
1749         if (key_id_base64) {
1750             /* export encryption key id as base64 metadata tag */
1751             av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
1752             av_freep(&key_id_base64);
1753         }
1754
1755         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
1756              track->codec_priv.size >= 40               &&
1757             track->codec_priv.data != NULL) {
1758             track->ms_compat    = 1;
1759             bit_depth           = AV_RL16(track->codec_priv.data + 14);
1760             fourcc              = AV_RL32(track->codec_priv.data + 16);
1761             codec_id            = ff_codec_get_id(ff_codec_bmp_tags,
1762                                                   fourcc);
1763             extradata_offset    = 40;
1764         } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
1765                    track->codec_priv.size >= 14         &&
1766                    track->codec_priv.data != NULL) {
1767             int ret;
1768             ffio_init_context(&b, track->codec_priv.data,
1769                               track->codec_priv.size,
1770                               0, NULL, NULL, NULL, NULL);
1771             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1772             if (ret < 0)
1773                 return ret;
1774             codec_id         = st->codec->codec_id;
1775             extradata_offset = FFMIN(track->codec_priv.size, 18);
1776         } else if (!strcmp(track->codec_id, "A_QUICKTIME")
1777                    && (track->codec_priv.size >= 86)
1778                    && (track->codec_priv.data != NULL)) {
1779             fourcc = AV_RL32(track->codec_priv.data + 4);
1780             codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
1781             if (ff_codec_get_id(ff_codec_movaudio_tags, AV_RL32(track->codec_priv.data))) {
1782                 fourcc = AV_RL32(track->codec_priv.data);
1783                 codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
1784             }
1785         } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1786                    (track->codec_priv.size >= 21)          &&
1787                    (track->codec_priv.data != NULL)) {
1788             fourcc   = AV_RL32(track->codec_priv.data + 4);
1789             codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1790             if (ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(track->codec_priv.data))) {
1791                 fourcc   = AV_RL32(track->codec_priv.data);
1792                 codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1793             }
1794             if (codec_id == AV_CODEC_ID_NONE && AV_RL32(track->codec_priv.data+4) == AV_RL32("SMI "))
1795                 codec_id = AV_CODEC_ID_SVQ3;
1796         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1797             switch (track->audio.bitdepth) {
1798             case  8:
1799                 codec_id = AV_CODEC_ID_PCM_U8;
1800                 break;
1801             case 24:
1802                 codec_id = AV_CODEC_ID_PCM_S24BE;
1803                 break;
1804             case 32:
1805                 codec_id = AV_CODEC_ID_PCM_S32BE;
1806                 break;
1807             }
1808         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1809             switch (track->audio.bitdepth) {
1810             case  8:
1811                 codec_id = AV_CODEC_ID_PCM_U8;
1812                 break;
1813             case 24:
1814                 codec_id = AV_CODEC_ID_PCM_S24LE;
1815                 break;
1816             case 32:
1817                 codec_id = AV_CODEC_ID_PCM_S32LE;
1818                 break;
1819             }
1820         } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
1821                    track->audio.bitdepth == 64) {
1822             codec_id = AV_CODEC_ID_PCM_F64LE;
1823         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1824             int profile = matroska_aac_profile(track->codec_id);
1825             int sri     = matroska_aac_sri(track->audio.samplerate);
1826             extradata   = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1827             if (extradata == NULL)
1828                 return AVERROR(ENOMEM);
1829             extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
1830             extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
1831             if (strstr(track->codec_id, "SBR")) {
1832                 sri            = matroska_aac_sri(track->audio.out_samplerate);
1833                 extradata[2]   = 0x56;
1834                 extradata[3]   = 0xE5;
1835                 extradata[4]   = 0x80 | (sri << 3);
1836                 extradata_size = 5;
1837             } else
1838                 extradata_size = 2;
1839         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - FF_INPUT_BUFFER_PADDING_SIZE) {
1840             /* Only ALAC's magic cookie is stored in Matroska's track headers.
1841              * Create the "atom size", "tag", and "tag version" fields the
1842              * decoder expects manually. */
1843             extradata_size = 12 + track->codec_priv.size;
1844             extradata      = av_mallocz(extradata_size +
1845                                         FF_INPUT_BUFFER_PADDING_SIZE);
1846             if (extradata == NULL)
1847                 return AVERROR(ENOMEM);
1848             AV_WB32(extradata, extradata_size);
1849             memcpy(&extradata[4], "alac", 4);
1850             AV_WB32(&extradata[8], 0);
1851             memcpy(&extradata[12], track->codec_priv.data,
1852                    track->codec_priv.size);
1853         } else if (codec_id == AV_CODEC_ID_TTA) {
1854             extradata_size = 30;
1855             extradata      = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1856             if (extradata == NULL)
1857                 return AVERROR(ENOMEM);
1858             ffio_init_context(&b, extradata, extradata_size, 1,
1859                               NULL, NULL, NULL, NULL);
1860             avio_write(&b, "TTA1", 4);
1861             avio_wl16(&b, 1);
1862             avio_wl16(&b, track->audio.channels);
1863             avio_wl16(&b, track->audio.bitdepth);
1864             if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
1865                 return AVERROR_INVALIDDATA;
1866             avio_wl32(&b, track->audio.out_samplerate);
1867             avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale),
1868                                      track->audio.out_samplerate,
1869                                      AV_TIME_BASE * 1000));
1870         } else if (codec_id == AV_CODEC_ID_RV10 ||
1871                    codec_id == AV_CODEC_ID_RV20 ||
1872                    codec_id == AV_CODEC_ID_RV30 ||
1873                    codec_id == AV_CODEC_ID_RV40) {
1874             extradata_offset = 26;
1875         } else if (codec_id == AV_CODEC_ID_RA_144) {
1876             track->audio.out_samplerate = 8000;
1877             track->audio.channels       = 1;
1878         } else if ((codec_id == AV_CODEC_ID_RA_288 ||
1879                     codec_id == AV_CODEC_ID_COOK   ||
1880                     codec_id == AV_CODEC_ID_ATRAC3 ||
1881                     codec_id == AV_CODEC_ID_SIPR)
1882                       && track->codec_priv.data) {
1883             int flavor;
1884
1885             ffio_init_context(&b, track->codec_priv.data,
1886                               track->codec_priv.size,
1887                               0, NULL, NULL, NULL, NULL);
1888             avio_skip(&b, 22);
1889             flavor                       = avio_rb16(&b);
1890             track->audio.coded_framesize = avio_rb32(&b);
1891             avio_skip(&b, 12);
1892             track->audio.sub_packet_h    = avio_rb16(&b);
1893             track->audio.frame_size      = avio_rb16(&b);
1894             track->audio.sub_packet_size = avio_rb16(&b);
1895             if (flavor                        < 0 ||
1896                 track->audio.coded_framesize <= 0 ||
1897                 track->audio.sub_packet_h    <= 0 ||
1898                 track->audio.frame_size      <= 0 ||
1899                 track->audio.sub_packet_size <= 0)
1900                 return AVERROR_INVALIDDATA;
1901             track->audio.buf = av_malloc_array(track->audio.sub_packet_h,
1902                                                track->audio.frame_size);
1903             if (!track->audio.buf)
1904                 return AVERROR(ENOMEM);
1905             if (codec_id == AV_CODEC_ID_RA_288) {
1906                 st->codec->block_align = track->audio.coded_framesize;
1907                 track->codec_priv.size = 0;
1908             } else {
1909                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1910                     static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1911                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1912                     st->codec->bit_rate          = sipr_bit_rate[flavor];
1913                 }
1914                 st->codec->block_align = track->audio.sub_packet_size;
1915                 extradata_offset       = 78;
1916             }
1917         } else if (codec_id == AV_CODEC_ID_PRORES && track->codec_priv.size == 4) {
1918             fourcc = AV_RL32(track->codec_priv.data);
1919         }
1920         track->codec_priv.size -= extradata_offset;
1921
1922         if (codec_id == AV_CODEC_ID_NONE)
1923             av_log(matroska->ctx, AV_LOG_INFO,
1924                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1925
1926         if (track->time_scale < 0.01)
1927             track->time_scale = 1.0;
1928         avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
1929                             1000 * 1000 * 1000);    /* 64 bit pts in ns */
1930
1931         st->codec->codec_id = codec_id;
1932
1933         if (strcmp(track->language, "und"))
1934             av_dict_set(&st->metadata, "language", track->language, 0);
1935         av_dict_set(&st->metadata, "title", track->name, 0);
1936
1937         if (track->flag_default)
1938             st->disposition |= AV_DISPOSITION_DEFAULT;
1939         if (track->flag_forced)
1940             st->disposition |= AV_DISPOSITION_FORCED;
1941
1942         if (!st->codec->extradata) {
1943             if (extradata) {
1944                 st->codec->extradata      = extradata;
1945                 st->codec->extradata_size = extradata_size;
1946             } else if (track->codec_priv.data && track->codec_priv.size > 0) {
1947                 if (ff_alloc_extradata(st->codec, track->codec_priv.size))
1948                     return AVERROR(ENOMEM);
1949                 memcpy(st->codec->extradata,
1950                        track->codec_priv.data + extradata_offset,
1951                        track->codec_priv.size);
1952             }
1953         }
1954
1955         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1956             MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1957
1958             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1959             st->codec->codec_tag  = fourcc;
1960             if (bit_depth >= 0)
1961                 st->codec->bits_per_coded_sample = bit_depth;
1962             st->codec->width      = track->video.pixel_width;
1963             st->codec->height     = track->video.pixel_height;
1964             av_reduce(&st->sample_aspect_ratio.num,
1965                       &st->sample_aspect_ratio.den,
1966                       st->codec->height * track->video.display_width,
1967                       st->codec->width  * track->video.display_height,
1968                       255);
1969             if (st->codec->codec_id != AV_CODEC_ID_HEVC)
1970                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1971
1972             if (track->default_duration) {
1973                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1974                           1000000000, track->default_duration, 30000);
1975 #if FF_API_R_FRAME_RATE
1976                 if (st->avg_frame_rate.num < st->avg_frame_rate.den * 1000L)
1977                     st->r_frame_rate = st->avg_frame_rate;
1978 #endif
1979             }
1980
1981             /* export stereo mode flag as metadata tag */
1982             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1983                 av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
1984
1985             /* export alpha mode flag as metadata tag  */
1986             if (track->video.alpha_mode)
1987                 av_dict_set(&st->metadata, "alpha_mode", "1", 0);
1988
1989             /* if we have virtual track, mark the real tracks */
1990             for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1991                 char buf[32];
1992                 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1993                     continue;
1994                 snprintf(buf, sizeof(buf), "%s_%d",
1995                          ff_matroska_video_stereo_plane[planes[j].type], i);
1996                 for (k=0; k < matroska->tracks.nb_elem; k++)
1997                     if (planes[j].uid == tracks[k].uid) {
1998                         av_dict_set(&s->streams[k]->metadata,
1999                                     "stereo_mode", buf, 0);
2000                         break;
2001                     }
2002             }
2003         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2004             st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
2005             st->codec->sample_rate = track->audio.out_samplerate;
2006             st->codec->channels    = track->audio.channels;
2007             if (!st->codec->bits_per_coded_sample)
2008                 st->codec->bits_per_coded_sample = track->audio.bitdepth;
2009             if (st->codec->codec_id != AV_CODEC_ID_AAC)
2010                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2011             if (track->codec_delay > 0) {
2012                 st->codec->delay = av_rescale_q(track->codec_delay,
2013                                                 (AVRational){1, 1000000000},
2014                                                 (AVRational){1, st->codec->sample_rate});
2015             }
2016             if (track->seek_preroll > 0) {
2017                 av_codec_set_seek_preroll(st->codec,
2018                                           av_rescale_q(track->seek_preroll,
2019                                                        (AVRational){1, 1000000000},
2020                                                        (AVRational){1, st->codec->sample_rate}));
2021             }
2022         } else if (codec_id == AV_CODEC_ID_WEBVTT) {
2023             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
2024
2025             if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
2026                 st->disposition |= AV_DISPOSITION_CAPTIONS;
2027             } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
2028                 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2029             } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
2030                 st->disposition |= AV_DISPOSITION_METADATA;
2031             }
2032         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2033             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
2034 #if FF_API_ASS_SSA
2035             if (st->codec->codec_id == AV_CODEC_ID_SSA ||
2036                 st->codec->codec_id == AV_CODEC_ID_ASS)
2037 #else
2038             if (st->codec->codec_id == AV_CODEC_ID_ASS)
2039 #endif
2040                 matroska->contains_ssa = 1;
2041         }
2042     }
2043
2044     attachments = attachments_list->elem;
2045     for (j = 0; j < attachments_list->nb_elem; j++) {
2046         if (!(attachments[j].filename && attachments[j].mime &&
2047               attachments[j].bin.data && attachments[j].bin.size > 0)) {
2048             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2049         } else {
2050             AVStream *st = avformat_new_stream(s, NULL);
2051             if (st == NULL)
2052                 break;
2053             av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
2054             av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
2055             st->codec->codec_id   = AV_CODEC_ID_NONE;
2056             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
2057             if (ff_alloc_extradata(st->codec, attachments[j].bin.size))
2058                 break;
2059             memcpy(st->codec->extradata, attachments[j].bin.data,
2060                    attachments[j].bin.size);
2061
2062             for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2063                 if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
2064                              strlen(ff_mkv_mime_tags[i].str))) {
2065                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
2066                     break;
2067                 }
2068             }
2069             attachments[j].stream = st;
2070         }
2071     }
2072
2073     chapters = chapters_list->elem;
2074     for (i = 0; i < chapters_list->nb_elem; i++)
2075         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
2076             (max_start == 0 || chapters[i].start > max_start)) {
2077             chapters[i].chapter =
2078                 avpriv_new_chapter(s, chapters[i].uid,
2079                                    (AVRational) { 1, 1000000000 },
2080                                    chapters[i].start, chapters[i].end,
2081                                    chapters[i].title);
2082             av_dict_set(&chapters[i].chapter->metadata,
2083                         "title", chapters[i].title, 0);
2084             max_start = chapters[i].start;
2085         }
2086
2087     matroska_add_index_entries(matroska);
2088
2089     matroska_convert_tags(s);
2090
2091     return 0;
2092 }
2093
2094 /*
2095  * Put one packet in an application-supplied AVPacket struct.
2096  * Returns 0 on success or -1 on failure.
2097  */
2098 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
2099                                    AVPacket *pkt)
2100 {
2101     if (matroska->num_packets > 0) {
2102         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
2103         av_free(matroska->packets[0]);
2104         if (matroska->num_packets > 1) {
2105             void *newpackets;
2106             memmove(&matroska->packets[0], &matroska->packets[1],
2107                     (matroska->num_packets - 1) * sizeof(AVPacket *));
2108             newpackets = av_realloc(matroska->packets,
2109                                     (matroska->num_packets - 1) *
2110                                     sizeof(AVPacket *));
2111             if (newpackets)
2112                 matroska->packets = newpackets;
2113         } else {
2114             av_freep(&matroska->packets);
2115             matroska->prev_pkt = NULL;
2116         }
2117         matroska->num_packets--;
2118         return 0;
2119     }
2120
2121     return -1;
2122 }
2123
2124 /*
2125  * Free all packets in our internal queue.
2126  */
2127 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2128 {
2129     matroska->prev_pkt = NULL;
2130     if (matroska->packets) {
2131         int n;
2132         for (n = 0; n < matroska->num_packets; n++) {
2133             av_free_packet(matroska->packets[n]);
2134             av_free(matroska->packets[n]);
2135         }
2136         av_freep(&matroska->packets);
2137         matroska->num_packets = 0;
2138     }
2139 }
2140
2141 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2142                                 int *buf_size, int type,
2143                                 uint32_t **lace_buf, int *laces)
2144 {
2145     int res = 0, n, size = *buf_size;
2146     uint8_t *data = *buf;
2147     uint32_t *lace_size;
2148
2149     if (!type) {
2150         *laces    = 1;
2151         *lace_buf = av_mallocz(sizeof(int));
2152         if (!*lace_buf)
2153             return AVERROR(ENOMEM);
2154
2155         *lace_buf[0] = size;
2156         return 0;
2157     }
2158
2159     av_assert0(size > 0);
2160     *laces    = *data + 1;
2161     data     += 1;
2162     size     -= 1;
2163     lace_size = av_mallocz(*laces * sizeof(int));
2164     if (!lace_size)
2165         return AVERROR(ENOMEM);
2166
2167     switch (type) {
2168     case 0x1: /* Xiph lacing */
2169     {
2170         uint8_t temp;
2171         uint32_t total = 0;
2172         for (n = 0; res == 0 && n < *laces - 1; n++) {
2173             while (1) {
2174                 if (size <= total) {
2175                     res = AVERROR_INVALIDDATA;
2176                     break;
2177                 }
2178                 temp          = *data;
2179                 total        += temp;
2180                 lace_size[n] += temp;
2181                 data         += 1;
2182                 size         -= 1;
2183                 if (temp != 0xff)
2184                     break;
2185             }
2186         }
2187         if (size <= total) {
2188             res = AVERROR_INVALIDDATA;
2189             break;
2190         }
2191
2192         lace_size[n] = size - total;
2193         break;
2194     }
2195
2196     case 0x2: /* fixed-size lacing */
2197         if (size % (*laces)) {
2198             res = AVERROR_INVALIDDATA;
2199             break;
2200         }
2201         for (n = 0; n < *laces; n++)
2202             lace_size[n] = size / *laces;
2203         break;
2204
2205     case 0x3: /* EBML lacing */
2206     {
2207         uint64_t num;
2208         uint64_t total;
2209         n = matroska_ebmlnum_uint(matroska, data, size, &num);
2210         if (n < 0 || num > INT_MAX) {
2211             av_log(matroska->ctx, AV_LOG_INFO,
2212                    "EBML block data error\n");
2213             res = n<0 ? n : AVERROR_INVALIDDATA;
2214             break;
2215         }
2216         data += n;
2217         size -= n;
2218         total = lace_size[0] = num;
2219         for (n = 1; res == 0 && n < *laces - 1; n++) {
2220             int64_t snum;
2221             int r;
2222             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2223             if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
2224                 av_log(matroska->ctx, AV_LOG_INFO,
2225                        "EBML block data error\n");
2226                 res = r<0 ? r : AVERROR_INVALIDDATA;
2227                 break;
2228             }
2229             data        += r;
2230             size        -= r;
2231             lace_size[n] = lace_size[n - 1] + snum;
2232             total       += lace_size[n];
2233         }
2234         if (size <= total) {
2235             res = AVERROR_INVALIDDATA;
2236             break;
2237         }
2238         lace_size[*laces - 1] = size - total;
2239         break;
2240     }
2241     }
2242
2243     *buf      = data;
2244     *lace_buf = lace_size;
2245     *buf_size = size;
2246
2247     return res;
2248 }
2249
2250 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2251                                    MatroskaTrack *track, AVStream *st,
2252                                    uint8_t *data, int size, uint64_t timecode,
2253                                    int64_t pos)
2254 {
2255     int a = st->codec->block_align;
2256     int sps = track->audio.sub_packet_size;
2257     int cfs = track->audio.coded_framesize;
2258     int h   = track->audio.sub_packet_h;
2259     int y   = track->audio.sub_packet_cnt;
2260     int w   = track->audio.frame_size;
2261     int x;
2262
2263     if (!track->audio.pkt_cnt) {
2264         if (track->audio.sub_packet_cnt == 0)
2265             track->audio.buf_timecode = timecode;
2266         if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
2267             if (size < cfs * h / 2) {
2268                 av_log(matroska->ctx, AV_LOG_ERROR,
2269                        "Corrupt int4 RM-style audio packet size\n");
2270                 return AVERROR_INVALIDDATA;
2271             }
2272             for (x = 0; x < h / 2; x++)
2273                 memcpy(track->audio.buf + x * 2 * w + y * cfs,
2274                        data + x * cfs, cfs);
2275         } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
2276             if (size < w) {
2277                 av_log(matroska->ctx, AV_LOG_ERROR,
2278                        "Corrupt sipr RM-style audio packet size\n");
2279                 return AVERROR_INVALIDDATA;
2280             }
2281             memcpy(track->audio.buf + y * w, data, w);
2282         } else {
2283             if (size < sps * w / sps || h<=0 || w%sps) {
2284                 av_log(matroska->ctx, AV_LOG_ERROR,
2285                        "Corrupt generic RM-style audio packet size\n");
2286                 return AVERROR_INVALIDDATA;
2287             }
2288             for (x = 0; x < w / sps; x++)
2289                 memcpy(track->audio.buf +
2290                        sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
2291                        data + x * sps, sps);
2292         }
2293
2294         if (++track->audio.sub_packet_cnt >= h) {
2295             if (st->codec->codec_id == AV_CODEC_ID_SIPR)
2296                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2297             track->audio.sub_packet_cnt = 0;
2298             track->audio.pkt_cnt        = h * w / a;
2299         }
2300     }
2301
2302     while (track->audio.pkt_cnt) {
2303         AVPacket *pkt = NULL;
2304         if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0) {
2305             av_free(pkt);
2306             return AVERROR(ENOMEM);
2307         }
2308         memcpy(pkt->data,
2309                track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
2310                a);
2311         pkt->pts                  = track->audio.buf_timecode;
2312         track->audio.buf_timecode = AV_NOPTS_VALUE;
2313         pkt->pos                  = pos;
2314         pkt->stream_index         = st->index;
2315         dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2316     }
2317
2318     return 0;
2319 }
2320
2321 /* reconstruct full wavpack blocks from mangled matroska ones */
2322 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
2323                                   uint8_t **pdst, int *size)
2324 {
2325     uint8_t *dst = NULL;
2326     int dstlen   = 0;
2327     int srclen   = *size;
2328     uint32_t samples;
2329     uint16_t ver;
2330     int ret, offset = 0;
2331
2332     if (srclen < 12 || track->stream->codec->extradata_size < 2)
2333         return AVERROR_INVALIDDATA;
2334
2335     ver = AV_RL16(track->stream->codec->extradata);
2336
2337     samples = AV_RL32(src);
2338     src    += 4;
2339     srclen -= 4;
2340
2341     while (srclen >= 8) {
2342         int multiblock;
2343         uint32_t blocksize;
2344         uint8_t *tmp;
2345
2346         uint32_t flags = AV_RL32(src);
2347         uint32_t crc   = AV_RL32(src + 4);
2348         src    += 8;
2349         srclen -= 8;
2350
2351         multiblock = (flags & 0x1800) != 0x1800;
2352         if (multiblock) {
2353             if (srclen < 4) {
2354                 ret = AVERROR_INVALIDDATA;
2355                 goto fail;
2356             }
2357             blocksize = AV_RL32(src);
2358             src      += 4;
2359             srclen   -= 4;
2360         } else
2361             blocksize = srclen;
2362
2363         if (blocksize > srclen) {
2364             ret = AVERROR_INVALIDDATA;
2365             goto fail;
2366         }
2367
2368         tmp = av_realloc(dst, dstlen + blocksize + 32);
2369         if (!tmp) {
2370             ret = AVERROR(ENOMEM);
2371             goto fail;
2372         }
2373         dst     = tmp;
2374         dstlen += blocksize + 32;
2375
2376         AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k'));   // tag
2377         AV_WL32(dst + offset +  4, blocksize + 24);         // blocksize - 8
2378         AV_WL16(dst + offset +  8, ver);                    // version
2379         AV_WL16(dst + offset + 10, 0);                      // track/index_no
2380         AV_WL32(dst + offset + 12, 0);                      // total samples
2381         AV_WL32(dst + offset + 16, 0);                      // block index
2382         AV_WL32(dst + offset + 20, samples);                // number of samples
2383         AV_WL32(dst + offset + 24, flags);                  // flags
2384         AV_WL32(dst + offset + 28, crc);                    // crc
2385         memcpy(dst + offset + 32, src, blocksize);          // block data
2386
2387         src    += blocksize;
2388         srclen -= blocksize;
2389         offset += blocksize + 32;
2390     }
2391
2392     *pdst = dst;
2393     *size = dstlen;
2394
2395     return 0;
2396
2397 fail:
2398     av_freep(&dst);
2399     return ret;
2400 }
2401
2402 static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
2403                                  MatroskaTrack *track,
2404                                  AVStream *st,
2405                                  uint8_t *data, int data_len,
2406                                  uint64_t timecode,
2407                                  uint64_t duration,
2408                                  int64_t pos)
2409 {
2410     AVPacket *pkt;
2411     uint8_t *id, *settings, *text, *buf;
2412     int id_len, settings_len, text_len;
2413     uint8_t *p, *q;
2414     int err;
2415
2416     if (data_len <= 0)
2417         return AVERROR_INVALIDDATA;
2418
2419     p = data;
2420     q = data + data_len;
2421
2422     id = p;
2423     id_len = -1;
2424     while (p < q) {
2425         if (*p == '\r' || *p == '\n') {
2426             id_len = p - id;
2427             if (*p == '\r')
2428                 p++;
2429             break;
2430         }
2431         p++;
2432     }
2433
2434     if (p >= q || *p != '\n')
2435         return AVERROR_INVALIDDATA;
2436     p++;
2437
2438     settings = p;
2439     settings_len = -1;
2440     while (p < q) {
2441         if (*p == '\r' || *p == '\n') {
2442             settings_len = p - settings;
2443             if (*p == '\r')
2444                 p++;
2445             break;
2446         }
2447         p++;
2448     }
2449
2450     if (p >= q || *p != '\n')
2451         return AVERROR_INVALIDDATA;
2452     p++;
2453
2454     text = p;
2455     text_len = q - p;
2456     while (text_len > 0) {
2457         const int len = text_len - 1;
2458         const uint8_t c = p[len];
2459         if (c != '\r' && c != '\n')
2460             break;
2461         text_len = len;
2462     }
2463
2464     if (text_len <= 0)
2465         return AVERROR_INVALIDDATA;
2466
2467     pkt = av_mallocz(sizeof(*pkt));
2468     err = av_new_packet(pkt, text_len);
2469     if (err < 0) {
2470         av_free(pkt);
2471         return AVERROR(err);
2472     }
2473
2474     memcpy(pkt->data, text, text_len);
2475
2476     if (id_len > 0) {
2477         buf = av_packet_new_side_data(pkt,
2478                                       AV_PKT_DATA_WEBVTT_IDENTIFIER,
2479                                       id_len);
2480         if (buf == NULL) {
2481             av_free(pkt);
2482             return AVERROR(ENOMEM);
2483         }
2484         memcpy(buf, id, id_len);
2485     }
2486
2487     if (settings_len > 0) {
2488         buf = av_packet_new_side_data(pkt,
2489                                       AV_PKT_DATA_WEBVTT_SETTINGS,
2490                                       settings_len);
2491         if (buf == NULL) {
2492             av_free(pkt);
2493             return AVERROR(ENOMEM);
2494         }
2495         memcpy(buf, settings, settings_len);
2496     }
2497
2498     // Do we need this for subtitles?
2499     // pkt->flags = AV_PKT_FLAG_KEY;
2500
2501     pkt->stream_index = st->index;
2502     pkt->pts = timecode;
2503
2504     // Do we need this for subtitles?
2505     // pkt->dts = timecode;
2506
2507     pkt->duration = duration;
2508     pkt->pos = pos;
2509
2510     dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2511     matroska->prev_pkt = pkt;
2512
2513     return 0;
2514 }
2515
2516 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2517                                 MatroskaTrack *track, AVStream *st,
2518                                 uint8_t *data, int pkt_size,
2519                                 uint64_t timecode, uint64_t lace_duration,
2520                                 int64_t pos, int is_keyframe,
2521                                 uint8_t *additional, uint64_t additional_id, int additional_size,
2522                                 int64_t discard_padding)
2523 {
2524     MatroskaTrackEncoding *encodings = track->encodings.elem;
2525     uint8_t *pkt_data = data;
2526     int offset = 0, res;
2527     AVPacket *pkt;
2528
2529     if (encodings && !encodings->type && encodings->scope & 1) {
2530         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2531         if (res < 0)
2532             return res;
2533     }
2534
2535     if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
2536         uint8_t *wv_data;
2537         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2538         if (res < 0) {
2539             av_log(matroska->ctx, AV_LOG_ERROR,
2540                    "Error parsing a wavpack block.\n");
2541             goto fail;
2542         }
2543         if (pkt_data != data)
2544             av_freep(&pkt_data);
2545         pkt_data = wv_data;
2546     }
2547
2548     if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2549         offset = 8;
2550
2551     pkt = av_mallocz(sizeof(AVPacket));
2552     /* XXX: prevent data copy... */
2553     if (av_new_packet(pkt, pkt_size + offset) < 0) {
2554         av_free(pkt);
2555         res = AVERROR(ENOMEM);
2556         goto fail;
2557     }
2558
2559     if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2560         uint8_t *buf = pkt->data;
2561         bytestream_put_be32(&buf, pkt_size);
2562         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2563     }
2564
2565     memcpy(pkt->data + offset, pkt_data, pkt_size);
2566
2567     if (pkt_data != data)
2568         av_freep(&pkt_data);
2569
2570     pkt->flags        = is_keyframe;
2571     pkt->stream_index = st->index;
2572
2573     if (additional_size > 0) {
2574         uint8_t *side_data = av_packet_new_side_data(pkt,
2575                                                      AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
2576                                                      additional_size + 8);
2577         if (side_data == NULL) {
2578             av_free_packet(pkt);
2579             av_free(pkt);
2580             return AVERROR(ENOMEM);
2581         }
2582         AV_WB64(side_data, additional_id);
2583         memcpy(side_data + 8, additional, additional_size);
2584     }
2585
2586     if (discard_padding) {
2587         uint8_t *side_data = av_packet_new_side_data(pkt,
2588                                                      AV_PKT_DATA_SKIP_SAMPLES,
2589                                                      10);
2590         if (side_data == NULL) {
2591             av_free_packet(pkt);
2592             av_free(pkt);
2593             return AVERROR(ENOMEM);
2594         }
2595         AV_WL32(side_data, 0);
2596         AV_WL32(side_data + 4, av_rescale_q(discard_padding,
2597                                             (AVRational){1, 1000000000},
2598                                             (AVRational){1, st->codec->sample_rate}));
2599     }
2600
2601     if (track->ms_compat)
2602         pkt->dts = timecode;
2603     else
2604         pkt->pts = timecode;
2605     pkt->pos = pos;
2606     if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
2607         /*
2608          * For backward compatibility.
2609          * Historically, we have put subtitle duration
2610          * in convergence_duration, on the off chance
2611          * that the time_scale is less than 1us, which
2612          * could result in a 32bit overflow on the
2613          * normal duration field.
2614          */
2615         pkt->convergence_duration = lace_duration;
2616     }
2617
2618     if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
2619         lace_duration <= INT_MAX) {
2620         /*
2621          * For non subtitle tracks, just store the duration
2622          * as normal.
2623          *
2624          * If it's a subtitle track and duration value does
2625          * not overflow a uint32, then also store it normally.
2626          */
2627         pkt->duration = lace_duration;
2628     }
2629
2630 #if FF_API_ASS_SSA
2631     if (st->codec->codec_id == AV_CODEC_ID_SSA)
2632         matroska_fix_ass_packet(matroska, pkt, lace_duration);
2633
2634     if (matroska->prev_pkt                                 &&
2635         timecode                         != AV_NOPTS_VALUE &&
2636         matroska->prev_pkt->pts          == timecode       &&
2637         matroska->prev_pkt->stream_index == st->index      &&
2638         st->codec->codec_id == AV_CODEC_ID_SSA)
2639         matroska_merge_packets(matroska->prev_pkt, pkt);
2640     else {
2641         dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2642         matroska->prev_pkt = pkt;
2643     }
2644 #else
2645     dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2646     matroska->prev_pkt = pkt;
2647 #endif
2648
2649     return 0;
2650
2651 fail:
2652     if (pkt_data != data)
2653         av_freep(&pkt_data);
2654     return res;
2655 }
2656
2657 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2658                                 int size, int64_t pos, uint64_t cluster_time,
2659                                 uint64_t block_duration, int is_keyframe,
2660                                 uint8_t *additional, uint64_t additional_id, int additional_size,
2661                                 int64_t cluster_pos, int64_t discard_padding)
2662 {
2663     uint64_t timecode = AV_NOPTS_VALUE;
2664     MatroskaTrack *track;
2665     int res = 0;
2666     AVStream *st;
2667     int16_t block_time;
2668     uint32_t *lace_size = NULL;
2669     int n, flags, laces = 0;
2670     uint64_t num;
2671     int trust_default_duration = 1;
2672
2673     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2674         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2675         return n;
2676     }
2677     data += n;
2678     size -= n;
2679
2680     track = matroska_find_track_by_num(matroska, num);
2681     if (!track || !track->stream) {
2682         av_log(matroska->ctx, AV_LOG_INFO,
2683                "Invalid stream %"PRIu64" or size %u\n", num, size);
2684         return AVERROR_INVALIDDATA;
2685     } else if (size <= 3)
2686         return 0;
2687     st = track->stream;
2688     if (st->discard >= AVDISCARD_ALL)
2689         return res;
2690     av_assert1(block_duration != AV_NOPTS_VALUE);
2691
2692     block_time = sign_extend(AV_RB16(data), 16);
2693     data      += 2;
2694     flags      = *data++;
2695     size      -= 3;
2696     if (is_keyframe == -1)
2697         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2698
2699     if (cluster_time != (uint64_t) -1 &&
2700         (block_time >= 0 || cluster_time >= -block_time)) {
2701         timecode = cluster_time + block_time;
2702         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
2703             timecode < track->end_timecode)
2704             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2705         if (is_keyframe)
2706             av_add_index_entry(st, cluster_pos, timecode, 0, 0,
2707                                AVINDEX_KEYFRAME);
2708     }
2709
2710     if (matroska->skip_to_keyframe &&
2711         track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2712         if (timecode < matroska->skip_to_timecode)
2713             return res;
2714         if (is_keyframe)
2715             matroska->skip_to_keyframe = 0;
2716         else if (!st->skip_to_keyframe) {
2717             av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
2718             matroska->skip_to_keyframe = 0;
2719         }
2720     }
2721
2722     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2723                                &lace_size, &laces);
2724
2725     if (res)
2726         goto end;
2727
2728     if (track->audio.samplerate == 8000) {
2729         // If this is needed for more codecs, then add them here
2730         if (st->codec->codec_id == AV_CODEC_ID_AC3) {
2731             if (track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
2732                 trust_default_duration = 0;
2733         }
2734     }
2735
2736     if (!block_duration && trust_default_duration)
2737         block_duration = track->default_duration * laces / matroska->time_scale;
2738
2739     if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
2740         track->end_timecode =
2741             FFMAX(track->end_timecode, timecode + block_duration);
2742
2743     for (n = 0; n < laces; n++) {
2744         int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
2745
2746         if (lace_size[n] > size) {
2747             av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
2748             break;
2749         }
2750
2751         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2752              st->codec->codec_id == AV_CODEC_ID_COOK   ||
2753              st->codec->codec_id == AV_CODEC_ID_SIPR   ||
2754              st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2755             st->codec->block_align && track->audio.sub_packet_size) {
2756             res = matroska_parse_rm_audio(matroska, track, st, data,
2757                                           lace_size[n],
2758                                           timecode, pos);
2759             if (res)
2760                 goto end;
2761
2762         } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
2763             res = matroska_parse_webvtt(matroska, track, st,
2764                                         data, lace_size[n],
2765                                         timecode, lace_duration,
2766                                         pos);
2767             if (res)
2768                 goto end;
2769         } else {
2770             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2771                                        timecode, lace_duration, pos,
2772                                        !n ? is_keyframe : 0,
2773                                        additional, additional_id, additional_size,
2774                                        discard_padding);
2775             if (res)
2776                 goto end;
2777         }
2778
2779         if (timecode != AV_NOPTS_VALUE)
2780             timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
2781         data += lace_size[n];
2782         size -= lace_size[n];
2783     }
2784
2785 end:
2786     av_free(lace_size);
2787     return res;
2788 }
2789
2790 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2791 {
2792     EbmlList *blocks_list;
2793     MatroskaBlock *blocks;
2794     int i, res;
2795     res = ebml_parse(matroska,
2796                      matroska_cluster_incremental_parsing,
2797                      &matroska->current_cluster);
2798     if (res == 1) {
2799         /* New Cluster */
2800         if (matroska->current_cluster_pos)
2801             ebml_level_end(matroska);
2802         ebml_free(matroska_cluster, &matroska->current_cluster);
2803         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2804         matroska->current_cluster_num_blocks = 0;
2805         matroska->current_cluster_pos        = avio_tell(matroska->ctx->pb);
2806         matroska->prev_pkt                   = NULL;
2807         /* sizeof the ID which was already read */
2808         if (matroska->current_id)
2809             matroska->current_cluster_pos -= 4;
2810         res = ebml_parse(matroska,
2811                          matroska_clusters_incremental,
2812                          &matroska->current_cluster);
2813         /* Try parsing the block again. */
2814         if (res == 1)
2815             res = ebml_parse(matroska,
2816                              matroska_cluster_incremental_parsing,
2817                              &matroska->current_cluster);
2818     }
2819
2820     if (!res &&
2821         matroska->current_cluster_num_blocks <
2822         matroska->current_cluster.blocks.nb_elem) {
2823         blocks_list = &matroska->current_cluster.blocks;
2824         blocks      = blocks_list->elem;
2825
2826         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2827         i                                    = blocks_list->nb_elem - 1;
2828         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2829             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2830             uint8_t* additional = blocks[i].additional.size > 0 ?
2831                                     blocks[i].additional.data : NULL;
2832             if (!blocks[i].non_simple)
2833                 blocks[i].duration = 0;
2834             res = matroska_parse_block(matroska, blocks[i].bin.data,
2835                                        blocks[i].bin.size, blocks[i].bin.pos,
2836                                        matroska->current_cluster.timecode,
2837                                        blocks[i].duration, is_keyframe,
2838                                        additional, blocks[i].additional_id,
2839                                        blocks[i].additional.size,
2840                                        matroska->current_cluster_pos,
2841                                        blocks[i].discard_padding);
2842         }
2843     }
2844
2845     return res;
2846 }
2847
2848 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2849 {
2850     MatroskaCluster cluster = { 0 };
2851     EbmlList *blocks_list;
2852     MatroskaBlock *blocks;
2853     int i, res;
2854     int64_t pos;
2855
2856     if (!matroska->contains_ssa)
2857         return matroska_parse_cluster_incremental(matroska);
2858     pos = avio_tell(matroska->ctx->pb);
2859     matroska->prev_pkt = NULL;
2860     if (matroska->current_id)
2861         pos -= 4;  /* sizeof the ID which was already read */
2862     res         = ebml_parse(matroska, matroska_clusters, &cluster);
2863     blocks_list = &cluster.blocks;
2864     blocks      = blocks_list->elem;
2865     for (i = 0; i < blocks_list->nb_elem; i++)
2866         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2867             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2868             res = matroska_parse_block(matroska, blocks[i].bin.data,
2869                                        blocks[i].bin.size, blocks[i].bin.pos,
2870                                        cluster.timecode, blocks[i].duration,
2871                                        is_keyframe, NULL, 0, 0, pos,
2872                                        blocks[i].discard_padding);
2873         }
2874     ebml_free(matroska_cluster, &cluster);
2875     return res;
2876 }
2877
2878 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2879 {
2880     MatroskaDemuxContext *matroska = s->priv_data;
2881
2882     while (matroska_deliver_packet(matroska, pkt)) {
2883         int64_t pos = avio_tell(matroska->ctx->pb);
2884         if (matroska->done)
2885             return AVERROR_EOF;
2886         if (matroska_parse_cluster(matroska) < 0)
2887             matroska_resync(matroska, pos);
2888     }
2889
2890     return 0;
2891 }
2892
2893 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2894                               int64_t timestamp, int flags)
2895 {
2896     MatroskaDemuxContext *matroska = s->priv_data;
2897     MatroskaTrack *tracks = matroska->tracks.elem;
2898     AVStream *st = s->streams[stream_index];
2899     int i, index, index_sub, index_min;
2900
2901     /* Parse the CUES now since we need the index data to seek. */
2902     if (matroska->cues_parsing_deferred > 0) {
2903         matroska->cues_parsing_deferred = 0;
2904         matroska_parse_cues(matroska);
2905     }
2906
2907     if (!st->nb_index_entries)
2908         goto err;
2909     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2910
2911     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2912         avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
2913                   SEEK_SET);
2914         matroska->current_id = 0;
2915         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2916             matroska_clear_queue(matroska);
2917             if (matroska_parse_cluster(matroska) < 0)
2918                 break;
2919         }
2920     }
2921
2922     matroska_clear_queue(matroska);
2923     if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2924         goto err;
2925
2926     index_min = index;
2927     for (i = 0; i < matroska->tracks.nb_elem; i++) {
2928         tracks[i].audio.pkt_cnt        = 0;
2929         tracks[i].audio.sub_packet_cnt = 0;
2930         tracks[i].audio.buf_timecode   = AV_NOPTS_VALUE;
2931         tracks[i].end_timecode         = 0;
2932         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
2933             tracks[i].stream->discard != AVDISCARD_ALL) {
2934             index_sub = av_index_search_timestamp(
2935                 tracks[i].stream, st->index_entries[index].timestamp,
2936                 AVSEEK_FLAG_BACKWARD);
2937             while (index_sub >= 0 &&
2938                   index_min >= 0 &&
2939                   tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
2940                   st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
2941                 index_min--;
2942         }
2943     }
2944
2945     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2946     matroska->current_id       = 0;
2947     if (flags & AVSEEK_FLAG_ANY) {
2948         st->skip_to_keyframe = 0;
2949         matroska->skip_to_timecode = timestamp;
2950     } else {
2951         st->skip_to_keyframe = 1;
2952         matroska->skip_to_timecode = st->index_entries[index].timestamp;
2953     }
2954     matroska->skip_to_keyframe = 1;
2955     matroska->done             = 0;
2956     matroska->num_levels       = 0;
2957     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2958     return 0;
2959 err:
2960     // slightly hackish but allows proper fallback to
2961     // the generic seeking code.
2962     matroska_clear_queue(matroska);
2963     matroska->current_id = 0;
2964     st->skip_to_keyframe =
2965     matroska->skip_to_keyframe = 0;
2966     matroska->done = 0;
2967     matroska->num_levels = 0;
2968     return -1;
2969 }
2970
2971 static int matroska_read_close(AVFormatContext *s)
2972 {
2973     MatroskaDemuxContext *matroska = s->priv_data;
2974     MatroskaTrack *tracks = matroska->tracks.elem;
2975     int n;
2976
2977     matroska_clear_queue(matroska);
2978
2979     for (n = 0; n < matroska->tracks.nb_elem; n++)
2980         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2981             av_free(tracks[n].audio.buf);
2982     ebml_free(matroska_cluster, &matroska->current_cluster);
2983     ebml_free(matroska_segment, matroska);
2984
2985     return 0;
2986 }
2987
2988 AVInputFormat ff_matroska_demuxer = {
2989     .name           = "matroska,webm",
2990     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2991     .priv_data_size = sizeof(MatroskaDemuxContext),
2992     .read_probe     = matroska_probe,
2993     .read_header    = matroska_read_header,
2994     .read_packet    = matroska_read_packet,
2995     .read_close     = matroska_read_close,
2996     .read_seek      = matroska_read_seek,
2997 };