]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
hwcontext_vaapi: Return all formats for constraints without config
[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 ||
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         /* convert the delay from ns to the track timebase */
1836         track->codec_delay = av_rescale_q(track->codec_delay,
1837                                           (AVRational){ 1, 1000000000 },
1838                                           st->time_base);
1839
1840         st->codecpar->codec_id = codec_id;
1841         st->start_time      = 0;
1842         if (strcmp(track->language, "und"))
1843             av_dict_set(&st->metadata, "language", track->language, 0);
1844         av_dict_set(&st->metadata, "title", track->name, 0);
1845
1846         if (track->flag_default)
1847             st->disposition |= AV_DISPOSITION_DEFAULT;
1848         if (track->flag_forced)
1849             st->disposition |= AV_DISPOSITION_FORCED;
1850
1851         if (!st->codecpar->extradata) {
1852             if (extradata) {
1853                 st->codecpar->extradata      = extradata;
1854                 st->codecpar->extradata_size = extradata_size;
1855             } else if (track->codec_priv.data && track->codec_priv.size > 0) {
1856                 st->codecpar->extradata = av_mallocz(track->codec_priv.size +
1857                                                      AV_INPUT_BUFFER_PADDING_SIZE);
1858                 if (!st->codecpar->extradata)
1859                     return AVERROR(ENOMEM);
1860                 st->codecpar->extradata_size = track->codec_priv.size;
1861                 memcpy(st->codecpar->extradata,
1862                        track->codec_priv.data + extradata_offset,
1863                        track->codec_priv.size);
1864             }
1865         }
1866
1867         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1868             int display_width_mul  = 1;
1869             int display_height_mul = 1;
1870
1871             st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1872             st->codecpar->codec_tag  = track->video.fourcc;
1873             st->codecpar->width      = track->video.pixel_width;
1874             st->codecpar->height     = track->video.pixel_height;
1875
1876             if (track->video.interlaced == MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED)
1877                 st->codecpar->field_order = mkv_field_order(track->video.field_order);
1878
1879             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
1880                 mkv_stereo_mode_display_mul(track->video.stereo_mode, &display_width_mul, &display_height_mul);
1881
1882             av_reduce(&st->sample_aspect_ratio.num,
1883                       &st->sample_aspect_ratio.den,
1884                       st->codecpar->height * track->video.display_width  * display_width_mul,
1885                       st->codecpar->width  * track->video.display_height * display_height_mul,
1886                       255);
1887             if (st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1888                 st->codecpar->codec_id != AV_CODEC_ID_HEVC)
1889                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1890             if (track->default_duration) {
1891                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1892                           1000000000, track->default_duration, 30000);
1893             }
1894             // add stream level stereo3d side data if it is a supported format
1895             if (track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
1896                 track->video.stereo_mode != 10 && track->video.stereo_mode != 12) {
1897                 int ret = ff_mkv_stereo3d_conv(st, track->video.stereo_mode);
1898                 if (ret < 0)
1899                     return ret;
1900             }
1901         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1902             st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
1903             st->codecpar->sample_rate = track->audio.out_samplerate;
1904             st->codecpar->channels    = track->audio.channels;
1905             if (st->codecpar->codec_id != AV_CODEC_ID_AAC)
1906                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1907             if (st->codecpar->codec_id == AV_CODEC_ID_MP3)
1908                 st->need_parsing = AVSTREAM_PARSE_FULL;
1909         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1910             st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1911             if (st->codecpar->codec_id == AV_CODEC_ID_SSA)
1912                 matroska->contains_ssa = 1;
1913         }
1914     }
1915
1916     return 0;
1917 }
1918
1919 static int matroska_read_header(AVFormatContext *s)
1920 {
1921     MatroskaDemuxContext *matroska = s->priv_data;
1922     EbmlList *attachments_list = &matroska->attachments;
1923     EbmlList *chapters_list    = &matroska->chapters;
1924     MatroskaAttachment *attachments;
1925     MatroskaChapter *chapters;
1926     uint64_t max_start = 0;
1927     int64_t pos;
1928     Ebml ebml = { 0 };
1929     int i, j, res;
1930
1931     matroska->ctx = s;
1932
1933     /* First read the EBML header. */
1934     if (ebml_parse(matroska, ebml_syntax, &ebml) || !ebml.doctype) {
1935         av_log(matroska->ctx, AV_LOG_ERROR, "EBML header parsing failed\n");
1936         ebml_free(ebml_syntax, &ebml);
1937         return AVERROR_INVALIDDATA;
1938     }
1939     if (ebml.version         > EBML_VERSION      ||
1940         ebml.max_size        > sizeof(uint64_t)  ||
1941         ebml.id_length       > sizeof(uint32_t)  ||
1942         ebml.doctype_version > 3) {
1943         av_log(matroska->ctx, AV_LOG_ERROR,
1944                "EBML header using unsupported features\n"
1945                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1946                ebml.version, ebml.doctype, ebml.doctype_version);
1947         ebml_free(ebml_syntax, &ebml);
1948         return AVERROR_PATCHWELCOME;
1949     }
1950     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1951         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1952             break;
1953     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1954         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1955         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1956             ebml_free(ebml_syntax, &ebml);
1957             return AVERROR_INVALIDDATA;
1958         }
1959     }
1960     ebml_free(ebml_syntax, &ebml);
1961
1962     /* The next thing is a segment. */
1963     pos = avio_tell(matroska->ctx->pb);
1964     res = ebml_parse(matroska, matroska_segments, matroska);
1965     // try resyncing until we find a EBML_STOP type element.
1966     while (res != 1) {
1967         res = matroska_resync(matroska, pos);
1968         if (res < 0)
1969             return res;
1970         pos = avio_tell(matroska->ctx->pb);
1971         res = ebml_parse(matroska, matroska_segment, matroska);
1972     }
1973     matroska_execute_seekhead(matroska);
1974
1975     if (!matroska->time_scale)
1976         matroska->time_scale = 1000000;
1977     if (matroska->duration)
1978         matroska->ctx->duration = matroska->duration * matroska->time_scale *
1979                                   1000 / AV_TIME_BASE;
1980     av_dict_set(&s->metadata, "title", matroska->title, 0);
1981
1982     res = matroska_parse_tracks(s);
1983     if (res < 0)
1984         return res;
1985
1986     attachments = attachments_list->elem;
1987     for (j = 0; j < attachments_list->nb_elem; j++) {
1988         if (!(attachments[j].filename && attachments[j].mime &&
1989               attachments[j].bin.data && attachments[j].bin.size > 0)) {
1990             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1991         } else {
1992             AVStream *st = avformat_new_stream(s, NULL);
1993             if (!st)
1994                 break;
1995             av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
1996             av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
1997             st->codecpar->codec_id   = AV_CODEC_ID_NONE;
1998
1999             for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2000                 if (!strncmp(ff_mkv_image_mime_tags[i].str, attachments[j].mime,
2001                              strlen(ff_mkv_image_mime_tags[i].str))) {
2002                     st->codecpar->codec_id = ff_mkv_image_mime_tags[i].id;
2003                     break;
2004                 }
2005             }
2006
2007             attachments[j].stream = st;
2008
2009             if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
2010                 st->disposition         |= AV_DISPOSITION_ATTACHED_PIC;
2011                 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2012
2013                 av_init_packet(&st->attached_pic);
2014                 if ((res = av_new_packet(&st->attached_pic, attachments[j].bin.size)) < 0)
2015                     return res;
2016                 memcpy(st->attached_pic.data, attachments[j].bin.data, attachments[j].bin.size);
2017                 st->attached_pic.stream_index = st->index;
2018                 st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
2019             } else {
2020                 st->codecpar->codec_type = AVMEDIA_TYPE_ATTACHMENT;
2021                 st->codecpar->extradata  = av_malloc(attachments[j].bin.size);
2022                 if (!st->codecpar->extradata)
2023                     break;
2024
2025                 st->codecpar->extradata_size = attachments[j].bin.size;
2026                 memcpy(st->codecpar->extradata, attachments[j].bin.data,
2027                        attachments[j].bin.size);
2028
2029                 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
2030                     if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
2031                                 strlen(ff_mkv_mime_tags[i].str))) {
2032                         st->codecpar->codec_id = ff_mkv_mime_tags[i].id;
2033                         break;
2034                     }
2035                 }
2036             }
2037         }
2038     }
2039
2040     chapters = chapters_list->elem;
2041     for (i = 0; i < chapters_list->nb_elem; i++)
2042         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
2043             (max_start == 0 || chapters[i].start > max_start)) {
2044             chapters[i].chapter =
2045                 avpriv_new_chapter(s, chapters[i].uid,
2046                                    (AVRational) { 1, 1000000000 },
2047                                    chapters[i].start, chapters[i].end,
2048                                    chapters[i].title);
2049             av_dict_set(&chapters[i].chapter->metadata,
2050                         "title", chapters[i].title, 0);
2051             max_start = chapters[i].start;
2052         }
2053
2054     matroska_convert_tags(s);
2055
2056     return 0;
2057 }
2058
2059 /*
2060  * Put one packet in an application-supplied AVPacket struct.
2061  * Returns 0 on success or -1 on failure.
2062  */
2063 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
2064                                    AVPacket *pkt)
2065 {
2066     if (matroska->num_packets > 0) {
2067         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
2068         av_free(matroska->packets[0]);
2069         if (matroska->num_packets > 1) {
2070             void *newpackets;
2071             memmove(&matroska->packets[0], &matroska->packets[1],
2072                     (matroska->num_packets - 1) * sizeof(AVPacket *));
2073             newpackets = av_realloc(matroska->packets,
2074                                     (matroska->num_packets - 1) *
2075                                     sizeof(AVPacket *));
2076             if (newpackets)
2077                 matroska->packets = newpackets;
2078         } else {
2079             av_freep(&matroska->packets);
2080             matroska->prev_pkt = NULL;
2081         }
2082         matroska->num_packets--;
2083         return 0;
2084     }
2085
2086     return -1;
2087 }
2088
2089 /*
2090  * Free all packets in our internal queue.
2091  */
2092 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2093 {
2094     matroska->prev_pkt = NULL;
2095     if (matroska->packets) {
2096         int n;
2097         for (n = 0; n < matroska->num_packets; n++) {
2098             av_packet_unref(matroska->packets[n]);
2099             av_free(matroska->packets[n]);
2100         }
2101         av_freep(&matroska->packets);
2102         matroska->num_packets = 0;
2103     }
2104 }
2105
2106 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2107                                 int *buf_size, int type,
2108                                 uint32_t **lace_buf, int *laces)
2109 {
2110     int res = 0, n, size = *buf_size;
2111     uint8_t *data = *buf;
2112     uint32_t *lace_size;
2113
2114     if (!type) {
2115         *laces    = 1;
2116         *lace_buf = av_mallocz(sizeof(int));
2117         if (!*lace_buf)
2118             return AVERROR(ENOMEM);
2119
2120         *lace_buf[0] = size;
2121         return 0;
2122     }
2123
2124     assert(size > 0);
2125     *laces    = *data + 1;
2126     data     += 1;
2127     size     -= 1;
2128     lace_size = av_mallocz(*laces * sizeof(int));
2129     if (!lace_size)
2130         return AVERROR(ENOMEM);
2131
2132     switch (type) {
2133     case 0x1: /* Xiph lacing */
2134     {
2135         uint8_t temp;
2136         uint32_t total = 0;
2137         for (n = 0; res == 0 && n < *laces - 1; n++) {
2138             while (1) {
2139                 if (size == 0) {
2140                     res = AVERROR_EOF;
2141                     break;
2142                 }
2143                 temp          = *data;
2144                 lace_size[n] += temp;
2145                 data         += 1;
2146                 size         -= 1;
2147                 if (temp != 0xff)
2148                     break;
2149             }
2150             total += lace_size[n];
2151         }
2152         if (size <= total) {
2153             res = AVERROR_INVALIDDATA;
2154             break;
2155         }
2156
2157         lace_size[n] = size - total;
2158         break;
2159     }
2160
2161     case 0x2: /* fixed-size lacing */
2162         if (size % (*laces)) {
2163             res = AVERROR_INVALIDDATA;
2164             break;
2165         }
2166         for (n = 0; n < *laces; n++)
2167             lace_size[n] = size / *laces;
2168         break;
2169
2170     case 0x3: /* EBML lacing */
2171     {
2172         uint64_t num;
2173         uint64_t total;
2174         n = matroska_ebmlnum_uint(matroska, data, size, &num);
2175         if (n < 0) {
2176             av_log(matroska->ctx, AV_LOG_INFO,
2177                    "EBML block data error\n");
2178             res = n;
2179             break;
2180         }
2181         data += n;
2182         size -= n;
2183         total = lace_size[0] = num;
2184         for (n = 1; res == 0 && n < *laces - 1; n++) {
2185             int64_t snum;
2186             int r;
2187             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2188             if (r < 0) {
2189                 av_log(matroska->ctx, AV_LOG_INFO,
2190                        "EBML block data error\n");
2191                 res = r;
2192                 break;
2193             }
2194             data        += r;
2195             size        -= r;
2196             lace_size[n] = lace_size[n - 1] + snum;
2197             total       += lace_size[n];
2198         }
2199         if (size <= total) {
2200             res = AVERROR_INVALIDDATA;
2201             break;
2202         }
2203         lace_size[*laces - 1] = size - total;
2204         break;
2205     }
2206     }
2207
2208     *buf      = data;
2209     *lace_buf = lace_size;
2210     *buf_size = size;
2211
2212     return res;
2213 }
2214
2215 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2216                                    MatroskaTrack *track, AVStream *st,
2217                                    uint8_t *data, int size, uint64_t timecode,
2218                                    uint64_t duration, int64_t pos)
2219 {
2220     int a = st->codecpar->block_align;
2221     int sps = track->audio.sub_packet_size;
2222     int cfs = track->audio.coded_framesize;
2223     int h   = track->audio.sub_packet_h;
2224     int y   = track->audio.sub_packet_cnt;
2225     int w   = track->audio.frame_size;
2226     int x;
2227
2228     if (!track->audio.pkt_cnt) {
2229         if (track->audio.sub_packet_cnt == 0)
2230             track->audio.buf_timecode = timecode;
2231         if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
2232             if (size < cfs * h / 2) {
2233                 av_log(matroska->ctx, AV_LOG_ERROR,
2234                        "Corrupt int4 RM-style audio packet size\n");
2235                 return AVERROR_INVALIDDATA;
2236             }
2237             for (x = 0; x < h / 2; x++)
2238                 memcpy(track->audio.buf + x * 2 * w + y * cfs,
2239                        data + x * cfs, cfs);
2240         } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
2241             if (size < w) {
2242                 av_log(matroska->ctx, AV_LOG_ERROR,
2243                        "Corrupt sipr RM-style audio packet size\n");
2244                 return AVERROR_INVALIDDATA;
2245             }
2246             memcpy(track->audio.buf + y * w, data, w);
2247         } else {
2248             if (size < sps * w / sps) {
2249                 av_log(matroska->ctx, AV_LOG_ERROR,
2250                        "Corrupt generic RM-style audio packet size\n");
2251                 return AVERROR_INVALIDDATA;
2252             }
2253             for (x = 0; x < w / sps; x++)
2254                 memcpy(track->audio.buf +
2255                        sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
2256                        data + x * sps, sps);
2257         }
2258
2259         if (++track->audio.sub_packet_cnt >= h) {
2260             if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
2261                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2262             track->audio.sub_packet_cnt = 0;
2263             track->audio.pkt_cnt        = h * w / a;
2264         }
2265     }
2266
2267     while (track->audio.pkt_cnt) {
2268         int ret;
2269         AVPacket *pkt = av_mallocz(sizeof(AVPacket));
2270         if (!pkt)
2271             return AVERROR(ENOMEM);
2272
2273         ret = av_new_packet(pkt, a);
2274         if (ret < 0) {
2275             av_free(pkt);
2276             return ret;
2277         }
2278         memcpy(pkt->data,
2279                track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
2280                a);
2281         pkt->pts                  = track->audio.buf_timecode;
2282         track->audio.buf_timecode = AV_NOPTS_VALUE;
2283         pkt->pos                  = pos;
2284         pkt->stream_index         = st->index;
2285         dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2286     }
2287
2288     return 0;
2289 }
2290
2291 /* reconstruct full wavpack blocks from mangled matroska ones */
2292 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
2293                                   uint8_t **pdst, int *size)
2294 {
2295     uint8_t *dst = NULL;
2296     int dstlen   = 0;
2297     int srclen   = *size;
2298     uint32_t samples;
2299     uint16_t ver;
2300     int ret, offset = 0;
2301
2302     if (srclen < 12 || track->stream->codecpar->extradata_size < 2)
2303         return AVERROR_INVALIDDATA;
2304
2305     ver = AV_RL16(track->stream->codecpar->extradata);
2306
2307     samples = AV_RL32(src);
2308     src    += 4;
2309     srclen -= 4;
2310
2311     while (srclen >= 8) {
2312         int multiblock;
2313         uint32_t blocksize;
2314         uint8_t *tmp;
2315
2316         uint32_t flags = AV_RL32(src);
2317         uint32_t crc   = AV_RL32(src + 4);
2318         src    += 8;
2319         srclen -= 8;
2320
2321         multiblock = (flags & 0x1800) != 0x1800;
2322         if (multiblock) {
2323             if (srclen < 4) {
2324                 ret = AVERROR_INVALIDDATA;
2325                 goto fail;
2326             }
2327             blocksize = AV_RL32(src);
2328             src      += 4;
2329             srclen   -= 4;
2330         } else
2331             blocksize = srclen;
2332
2333         if (blocksize > srclen) {
2334             ret = AVERROR_INVALIDDATA;
2335             goto fail;
2336         }
2337
2338         tmp = av_realloc(dst, dstlen + blocksize + 32);
2339         if (!tmp) {
2340             ret = AVERROR(ENOMEM);
2341             goto fail;
2342         }
2343         dst     = tmp;
2344         dstlen += blocksize + 32;
2345
2346         AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k'));   // tag
2347         AV_WL32(dst + offset +  4, blocksize + 24);         // blocksize - 8
2348         AV_WL16(dst + offset +  8, ver);                    // version
2349         AV_WL16(dst + offset + 10, 0);                      // track/index_no
2350         AV_WL32(dst + offset + 12, 0);                      // total samples
2351         AV_WL32(dst + offset + 16, 0);                      // block index
2352         AV_WL32(dst + offset + 20, samples);                // number of samples
2353         AV_WL32(dst + offset + 24, flags);                  // flags
2354         AV_WL32(dst + offset + 28, crc);                    // crc
2355         memcpy(dst + offset + 32, src, blocksize);          // block data
2356
2357         src    += blocksize;
2358         srclen -= blocksize;
2359         offset += blocksize + 32;
2360     }
2361
2362     *pdst = dst;
2363     *size = dstlen;
2364
2365     return 0;
2366
2367 fail:
2368     av_freep(&dst);
2369     return ret;
2370 }
2371
2372 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2373                                 MatroskaTrack *track, AVStream *st,
2374                                 uint8_t *data, int pkt_size,
2375                                 uint64_t timecode, uint64_t duration,
2376                                 int64_t pos, int is_keyframe)
2377 {
2378     MatroskaTrackEncoding *encodings = track->encodings.elem;
2379     uint8_t *pkt_data = data;
2380     int offset = 0, res;
2381     AVPacket *pkt;
2382
2383     if (encodings && encodings->scope & 1) {
2384         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2385         if (res < 0)
2386             return res;
2387     }
2388
2389     if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
2390         uint8_t *wv_data;
2391         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2392         if (res < 0) {
2393             av_log(matroska->ctx, AV_LOG_ERROR,
2394                    "Error parsing a wavpack block.\n");
2395             goto fail;
2396         }
2397         if (pkt_data != data)
2398             av_freep(&pkt_data);
2399         pkt_data = wv_data;
2400     }
2401
2402     if (st->codecpar->codec_id == AV_CODEC_ID_PRORES)
2403         offset = 8;
2404
2405     pkt = av_mallocz(sizeof(AVPacket));
2406     if (!pkt) {
2407         av_freep(&pkt_data);
2408         return AVERROR(ENOMEM);
2409     }
2410     /* XXX: prevent data copy... */
2411     if (av_new_packet(pkt, pkt_size + offset) < 0) {
2412         av_free(pkt);
2413         av_freep(&pkt_data);
2414         return AVERROR(ENOMEM);
2415     }
2416
2417     if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2418         uint8_t *buf = pkt->data;
2419         bytestream_put_be32(&buf, pkt_size);
2420         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2421     }
2422
2423     memcpy(pkt->data + offset, pkt_data, pkt_size);
2424
2425     if (pkt_data != data)
2426         av_free(pkt_data);
2427
2428     pkt->flags        = is_keyframe;
2429     pkt->stream_index = st->index;
2430
2431     if (track->ms_compat)
2432         pkt->dts = timecode;
2433     else
2434         pkt->pts = timecode;
2435     pkt->pos = pos;
2436     if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE || st->codecpar->codec_id == AV_CODEC_ID_TEXT)
2437         pkt->duration = duration;
2438 #if FF_API_CONVERGENCE_DURATION
2439 FF_DISABLE_DEPRECATION_WARNINGS
2440     if (st->codecpar->codec_id == AV_CODEC_ID_TEXT)
2441         pkt->convergence_duration = duration;
2442 FF_ENABLE_DEPRECATION_WARNINGS
2443 #endif
2444
2445     if (st->codecpar->codec_id == AV_CODEC_ID_SSA)
2446         matroska_fix_ass_packet(matroska, pkt, duration);
2447
2448     if (matroska->prev_pkt                                 &&
2449         timecode                         != AV_NOPTS_VALUE &&
2450         matroska->prev_pkt->pts          == timecode       &&
2451         matroska->prev_pkt->stream_index == st->index      &&
2452         st->codecpar->codec_id == AV_CODEC_ID_SSA)
2453         matroska_merge_packets(matroska->prev_pkt, pkt);
2454     else {
2455         dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2456         matroska->prev_pkt = pkt;
2457     }
2458
2459     return 0;
2460
2461 fail:
2462     if (pkt_data != data)
2463         av_freep(&pkt_data);
2464     return res;
2465 }
2466
2467 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2468                                 int size, int64_t pos, uint64_t cluster_time,
2469                                 uint64_t block_duration, int is_keyframe,
2470                                 int64_t cluster_pos)
2471 {
2472     uint64_t timecode = AV_NOPTS_VALUE;
2473     MatroskaTrack *track;
2474     int res = 0;
2475     AVStream *st;
2476     int16_t block_time;
2477     uint32_t *lace_size = NULL;
2478     int n, flags, laces = 0;
2479     uint64_t num, duration;
2480
2481     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2482         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2483         return n;
2484     }
2485     data += n;
2486     size -= n;
2487
2488     track = matroska_find_track_by_num(matroska, num);
2489     if (!track || !track->stream) {
2490         av_log(matroska->ctx, AV_LOG_INFO,
2491                "Invalid stream %"PRIu64" or size %u\n", num, size);
2492         return AVERROR_INVALIDDATA;
2493     } else if (size <= 3)
2494         return 0;
2495     st = track->stream;
2496     if (st->discard >= AVDISCARD_ALL)
2497         return res;
2498
2499     block_time = AV_RB16(data);
2500     data      += 2;
2501     flags      = *data++;
2502     size      -= 3;
2503     if (is_keyframe == -1)
2504         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2505
2506     if (cluster_time != (uint64_t) -1 &&
2507         (block_time >= 0 || cluster_time >= -block_time)) {
2508         timecode = cluster_time + block_time - track->codec_delay;
2509         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
2510             timecode < track->end_timecode)
2511             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2512         if (is_keyframe)
2513             av_add_index_entry(st, cluster_pos, timecode, 0, 0,
2514                                AVINDEX_KEYFRAME);
2515     }
2516
2517     if (matroska->skip_to_keyframe &&
2518         track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2519         if (!is_keyframe || timecode < matroska->skip_to_timecode)
2520             return res;
2521         matroska->skip_to_keyframe = 0;
2522     }
2523
2524     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2525                                &lace_size, &laces);
2526
2527     if (res)
2528         goto end;
2529
2530     if (block_duration != AV_NOPTS_VALUE) {
2531         duration = block_duration / laces;
2532         if (block_duration != duration * laces) {
2533             av_log(matroska->ctx, AV_LOG_WARNING,
2534                    "Incorrect block_duration, possibly corrupted container");
2535         }
2536     } else {
2537         duration       = track->default_duration / matroska->time_scale;
2538         block_duration = duration * laces;
2539     }
2540
2541     if (timecode != AV_NOPTS_VALUE)
2542         track->end_timecode =
2543             FFMAX(track->end_timecode, timecode + block_duration);
2544
2545     for (n = 0; n < laces; n++) {
2546         if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
2547              st->codecpar->codec_id == AV_CODEC_ID_COOK   ||
2548              st->codecpar->codec_id == AV_CODEC_ID_SIPR   ||
2549              st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) &&
2550             st->codecpar->block_align && track->audio.sub_packet_size) {
2551             res = matroska_parse_rm_audio(matroska, track, st, data,
2552                                           lace_size[n],
2553                                           timecode, duration, pos);
2554             if (res)
2555                 goto end;
2556         } else {
2557             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2558                                        timecode, duration, pos,
2559                                        !n ? is_keyframe : 0);
2560             if (res)
2561                 goto end;
2562         }
2563
2564         if (timecode != AV_NOPTS_VALUE)
2565             timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2566         data += lace_size[n];
2567     }
2568
2569 end:
2570     av_free(lace_size);
2571     return res;
2572 }
2573
2574 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2575 {
2576     EbmlList *blocks_list;
2577     MatroskaBlock *blocks;
2578     int i, res;
2579     res = ebml_parse(matroska,
2580                      matroska_cluster_incremental_parsing,
2581                      &matroska->current_cluster);
2582     if (res == 1) {
2583         /* New Cluster */
2584         if (matroska->current_cluster_pos)
2585             ebml_level_end(matroska);
2586         ebml_free(matroska_cluster, &matroska->current_cluster);
2587         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2588         matroska->current_cluster_num_blocks = 0;
2589         matroska->current_cluster_pos        = avio_tell(matroska->ctx->pb);
2590         matroska->prev_pkt                   = NULL;
2591         /* sizeof the ID which was already read */
2592         if (matroska->current_id)
2593             matroska->current_cluster_pos -= 4;
2594         res = ebml_parse(matroska,
2595                          matroska_clusters_incremental,
2596                          &matroska->current_cluster);
2597         /* Try parsing the block again. */
2598         if (res == 1)
2599             res = ebml_parse(matroska,
2600                              matroska_cluster_incremental_parsing,
2601                              &matroska->current_cluster);
2602     }
2603
2604     if (!res &&
2605         matroska->current_cluster_num_blocks <
2606         matroska->current_cluster.blocks.nb_elem) {
2607         blocks_list = &matroska->current_cluster.blocks;
2608         blocks      = blocks_list->elem;
2609
2610         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2611         i                                    = blocks_list->nb_elem - 1;
2612         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2613             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2614             if (!blocks[i].non_simple)
2615                 blocks[i].duration = AV_NOPTS_VALUE;
2616             res = matroska_parse_block(matroska, blocks[i].bin.data,
2617                                        blocks[i].bin.size, blocks[i].bin.pos,
2618                                        matroska->current_cluster.timecode,
2619                                        blocks[i].duration, is_keyframe,
2620                                        matroska->current_cluster_pos);
2621         }
2622     }
2623
2624     if (res < 0)
2625         matroska->done = 1;
2626     return res;
2627 }
2628
2629 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2630 {
2631     MatroskaCluster cluster = { 0 };
2632     EbmlList *blocks_list;
2633     MatroskaBlock *blocks;
2634     int i, res;
2635     int64_t pos;
2636
2637     if (!matroska->contains_ssa)
2638         return matroska_parse_cluster_incremental(matroska);
2639     pos = avio_tell(matroska->ctx->pb);
2640     matroska->prev_pkt = NULL;
2641     if (matroska->current_id)
2642         pos -= 4;  /* sizeof the ID which was already read */
2643     res         = ebml_parse(matroska, matroska_clusters, &cluster);
2644     blocks_list = &cluster.blocks;
2645     blocks      = blocks_list->elem;
2646     for (i = 0; i < blocks_list->nb_elem && !res; i++)
2647         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2648             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2649             if (!blocks[i].non_simple)
2650                 blocks[i].duration = AV_NOPTS_VALUE;
2651             res = matroska_parse_block(matroska, blocks[i].bin.data,
2652                                        blocks[i].bin.size, blocks[i].bin.pos,
2653                                        cluster.timecode, blocks[i].duration,
2654                                        is_keyframe, pos);
2655         }
2656     ebml_free(matroska_cluster, &cluster);
2657     return res;
2658 }
2659
2660 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2661 {
2662     MatroskaDemuxContext *matroska = s->priv_data;
2663     int ret = 0;
2664
2665     while (!ret && matroska_deliver_packet(matroska, pkt)) {
2666         int64_t pos = avio_tell(matroska->ctx->pb);
2667         if (matroska->done)
2668             return AVERROR_EOF;
2669         if (matroska_parse_cluster(matroska) < 0)
2670             ret = matroska_resync(matroska, pos);
2671     }
2672
2673     if (ret == AVERROR_INVALIDDATA && pkt->data) {
2674         pkt->flags |= AV_PKT_FLAG_CORRUPT;
2675         return 0;
2676     }
2677
2678     return ret;
2679 }
2680
2681 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2682                               int64_t timestamp, int flags)
2683 {
2684     MatroskaDemuxContext *matroska = s->priv_data;
2685     MatroskaTrack *tracks = NULL;
2686     AVStream *st = s->streams[stream_index];
2687     int i, index, index_sub, index_min;
2688
2689     /* Parse the CUES now since we need the index data to seek. */
2690     if (matroska->cues_parsing_deferred) {
2691         matroska_parse_cues(matroska);
2692         matroska->cues_parsing_deferred = 0;
2693     }
2694
2695     if (!st->nb_index_entries)
2696         return 0;
2697     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2698
2699     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2700         avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
2701                   SEEK_SET);
2702         matroska->current_id = 0;
2703         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2704             matroska_clear_queue(matroska);
2705             if (matroska_parse_cluster(matroska) < 0)
2706                 break;
2707         }
2708     }
2709
2710     matroska_clear_queue(matroska);
2711     if (index < 0)
2712         return 0;
2713
2714     index_min = index;
2715     tracks = matroska->tracks.elem;
2716     for (i = 0; i < matroska->tracks.nb_elem; i++) {
2717         tracks[i].audio.pkt_cnt        = 0;
2718         tracks[i].audio.sub_packet_cnt = 0;
2719         tracks[i].audio.buf_timecode   = AV_NOPTS_VALUE;
2720         tracks[i].end_timecode         = 0;
2721         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
2722             tracks[i].stream->discard != AVDISCARD_ALL) {
2723             index_sub = av_index_search_timestamp(
2724                 tracks[i].stream, st->index_entries[index].timestamp,
2725                 AVSEEK_FLAG_BACKWARD);
2726             if (index_sub >= 0 &&
2727                 st->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
2728                 st->index_entries[index].timestamp -
2729                 st->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
2730                 index_min = index_sub;
2731         }
2732     }
2733
2734     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2735     matroska->current_id       = 0;
2736     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2737     matroska->skip_to_timecode = st->index_entries[index].timestamp;
2738     matroska->done             = 0;
2739     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2740     return 0;
2741 }
2742
2743 static int matroska_read_close(AVFormatContext *s)
2744 {
2745     MatroskaDemuxContext *matroska = s->priv_data;
2746     MatroskaTrack *tracks = matroska->tracks.elem;
2747     int n;
2748
2749     matroska_clear_queue(matroska);
2750
2751     for (n = 0; n < matroska->tracks.nb_elem; n++)
2752         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2753             av_free(tracks[n].audio.buf);
2754     ebml_free(matroska_cluster, &matroska->current_cluster);
2755     ebml_free(matroska_segment, matroska);
2756
2757     return 0;
2758 }
2759
2760 AVInputFormat ff_matroska_demuxer = {
2761     .name           = "matroska,webm",
2762     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2763     .extensions     = "mkv,mk3d,mka,mks",
2764     .priv_data_size = sizeof(MatroskaDemuxContext),
2765     .read_probe     = matroska_probe,
2766     .read_header    = matroska_read_header,
2767     .read_packet    = matroska_read_packet,
2768     .read_close     = matroska_read_close,
2769     .read_seek      = matroska_read_seek,
2770     .mime_type      = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
2771 };