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