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