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