matroskadec: don't warn about unknown spherical medata when none is present
[libav.git] / libavformat / matroskadec.c
1 /*
2 * Matroska file demuxer
3 * Copyright (c) 2003-2008 The Libav Project
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 /**
23 * @file
24 * Matroska file demuxer
25 * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28 * @see specs available on the Matroska project page: http://www.matroska.org/
29 */
30
31 #include "config.h"
32
33 #include <inttypes.h>
34 #include <stdio.h>
35 #if CONFIG_BZLIB
36 #include <bzlib.h>
37 #endif
38 #if CONFIG_ZLIB
39 #include <zlib.h>
40 #endif
41
42 #include "libavutil/avstring.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/intfloat.h"
45 #include "libavutil/intreadwrite.h"
46 #include "libavutil/lzo.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/spherical.h"
49
50 #include "libavcodec/bytestream.h"
51 #include "libavcodec/flac.h"
52 #include "libavcodec/mpeg4audio.h"
53
54 #include "avformat.h"
55 #include "avio_internal.h"
56 #include "internal.h"
57 #include "isom.h"
58 #include "matroska.h"
59 #include "oggdec.h"
60 /* For ff_codec_get_id(). */
61 #include "riff.h"
62 #include "rmsipr.h"
63
64 typedef 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,
74 EBML_TYPE_COUNT
75 } EbmlType;
76
77 typedef 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
90 typedef struct EbmlList {
91 int nb_elem;
92 void *elem;
93 } EbmlList;
94
95 typedef struct EbmlBin {
96 int size;
97 uint8_t *data;
98 int64_t pos;
99 } EbmlBin;
100
101 typedef struct Ebml {
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
109 typedef struct MatroskaTrackCompression {
110 uint64_t algo;
111 EbmlBin settings;
112 } MatroskaTrackCompression;
113
114 typedef struct MatroskaTrackEncoding {
115 uint64_t scope;
116 uint64_t type;
117 MatroskaTrackCompression compression;
118 } MatroskaTrackEncoding;
119
120 typedef struct MatroskaTrackVideoProjection {
121 uint64_t type;
122 EbmlBin private;
123 double yaw;
124 double pitch;
125 double roll;
126 } MatroskaTrackVideoProjection;
127
128 typedef struct MatroskaTrackVideo {
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;
135 uint64_t interlaced;
136 uint64_t field_order;
137 uint64_t stereo_mode;
138 MatroskaTrackVideoProjection projection;
139 } MatroskaTrackVideo;
140
141 typedef struct MatroskaTrackAudio {
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;
154 uint64_t buf_timecode;
155 uint8_t *buf;
156 } MatroskaTrackAudio;
157
158 typedef struct MatroskaTrack {
159 uint64_t num;
160 uint64_t uid;
161 uint64_t type;
162 char *name;
163 char *codec_id;
164 EbmlBin codec_priv;
165 char *language;
166 double time_scale;
167 uint64_t default_duration;
168 uint64_t flag_default;
169 uint64_t flag_forced;
170 MatroskaTrackVideo video;
171 MatroskaTrackAudio audio;
172 EbmlList encodings;
173 uint64_t codec_delay;
174
175 AVStream *stream;
176 int64_t end_timecode;
177 int ms_compat;
178 } MatroskaTrack;
179
180 typedef struct MatroskaAttachment {
181 uint64_t uid;
182 char *filename;
183 char *mime;
184 EbmlBin bin;
185
186 AVStream *stream;
187 } MatroskaAttachment;
188
189 typedef struct MatroskaChapter {
190 uint64_t start;
191 uint64_t end;
192 uint64_t uid;
193 char *title;
194
195 AVChapter *chapter;
196 } MatroskaChapter;
197
198 typedef struct MatroskaIndexPos {
199 uint64_t track;
200 uint64_t pos;
201 } MatroskaIndexPos;
202
203 typedef struct MatroskaIndex {
204 uint64_t time;
205 EbmlList pos;
206 } MatroskaIndex;
207
208 typedef struct MatroskaTag {
209 char *name;
210 char *string;
211 char *lang;
212 uint64_t def;
213 EbmlList sub;
214 } MatroskaTag;
215
216 typedef struct MatroskaTagTarget {
217 char *type;
218 uint64_t typevalue;
219 uint64_t trackuid;
220 uint64_t chapteruid;
221 uint64_t attachuid;
222 } MatroskaTagTarget;
223
224 typedef struct MatroskaTags {
225 MatroskaTagTarget target;
226 EbmlList tag;
227 } MatroskaTags;
228
229 typedef struct MatroskaSeekhead {
230 uint64_t id;
231 uint64_t pos;
232 } MatroskaSeekhead;
233
234 typedef struct MatroskaLevel {
235 uint64_t start;
236 uint64_t length;
237 } MatroskaLevel;
238
239 typedef struct MatroskaCluster {
240 uint64_t timecode;
241 EbmlList blocks;
242 } MatroskaCluster;
243
244 typedef struct MatroskaDemuxContext {
245 AVFormatContext *ctx;
246
247 /* EBML stuff */
248 int num_levels;
249 MatroskaLevel levels[EBML_MAX_DEPTH];
250 int level_up;
251 uint32_t current_id;
252
253 uint64_t time_scale;
254 double duration;
255 char *title;
256 EbmlList tracks;
257 EbmlList attachments;
258 EbmlList chapters;
259 EbmlList index;
260 EbmlList tags;
261 EbmlList seekhead;
262
263 /* byte position of the segment inside the stream */
264 int64_t segment_start;
265
266 /* the packet queue */
267 AVPacket **packets;
268 int num_packets;
269 AVPacket *prev_pkt;
270
271 int done;
272
273 /* What to skip before effectively reading a packet. */
274 int skip_to_keyframe;
275 uint64_t skip_to_timecode;
276
277 /* File has a CUES element, but we defer parsing until it is needed. */
278 int cues_parsing_deferred;
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;
286 } MatroskaDemuxContext;
287
288 typedef struct MatroskaBlock {
289 uint64_t duration;
290 int64_t reference;
291 uint64_t non_simple;
292 EbmlBin bin;
293 } MatroskaBlock;
294
295 static EbmlSyntax ebml_header[] = {
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 },
303 { 0 }
304 };
305
306 static EbmlSyntax ebml_syntax[] = {
307 { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
308 { 0 }
309 };
310
311 static EbmlSyntax matroska_info[] = {
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 },
319 { 0 }
320 };
321
322 static 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
331 static EbmlSyntax matroska_track_video[] = {
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) },
338 { MATROSKA_ID_VIDEOPROJECTION, EBML_NEST, 0, offsetof(MatroskaTrackVideo, projection), { .n = matroska_track_video_projection } },
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 },
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 } },
346 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo, stereo_mode), { .u = MATROSKA_VIDEO_STEREOMODE_TYPE_NB } },
347 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
348 { 0 }
349 };
350
351 static EbmlSyntax matroska_track_audio[] = {
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 } },
356 { 0 }
357 };
358
359 static EbmlSyntax matroska_track_encoding_compression[] = {
360 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
361 { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN, 0, offsetof(MatroskaTrackCompression, settings) },
362 { 0 }
363 };
364
365 static EbmlSyntax matroska_track_encoding[] = {
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 },
370 { 0 }
371 };
372
373 static EbmlSyntax matroska_track_encodings[] = {
374 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
375 { 0 }
376 };
377
378 static EbmlSyntax matroska_track[] = {
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) },
385 { MATROSKA_ID_CODECDELAY, EBML_UINT, 0, offsetof(MatroskaTrack, codec_delay) },
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 },
403 { 0 }
404 };
405
406 static EbmlSyntax matroska_tracks[] = {
407 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
408 { 0 }
409 };
410
411 static EbmlSyntax matroska_attachment[] = {
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) },
416 { MATROSKA_ID_FILEDESC, EBML_NONE },
417 { 0 }
418 };
419
420 static EbmlSyntax matroska_attachments[] = {
421 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
422 { 0 }
423 };
424
425 static EbmlSyntax matroska_chapter_display[] = {
426 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
427 { MATROSKA_ID_CHAPLANG, EBML_NONE },
428 { 0 }
429 };
430
431 static EbmlSyntax matroska_chapter_entry[] = {
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 } },
436 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
437 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
438 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
439 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
440 { 0 }
441 };
442
443 static EbmlSyntax matroska_chapter[] = {
444 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
445 { MATROSKA_ID_EDITIONUID, EBML_NONE },
446 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
447 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
448 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
449 { 0 }
450 };
451
452 static EbmlSyntax matroska_chapters[] = {
453 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
454 { 0 }
455 };
456
457 static EbmlSyntax matroska_index_pos[] = {
458 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
459 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
460 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
461 { 0 }
462 };
463
464 static EbmlSyntax matroska_index_entry[] = {
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 } },
467 { 0 }
468 };
469
470 static EbmlSyntax matroska_index[] = {
471 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
472 { 0 }
473 };
474
475 static EbmlSyntax matroska_simpletag[] = {
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 } },
482 { 0 }
483 };
484
485 static EbmlSyntax matroska_tagtargets[] = {
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) },
491 { 0 }
492 };
493
494 static EbmlSyntax matroska_tag[] = {
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 } },
497 { 0 }
498 };
499
500 static EbmlSyntax matroska_tags[] = {
501 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
502 { 0 }
503 };
504
505 static EbmlSyntax matroska_seekhead_entry[] = {
506 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
507 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
508 { 0 }
509 };
510
511 static EbmlSyntax matroska_seekhead[] = {
512 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
513 { 0 }
514 };
515
516 static EbmlSyntax matroska_segment[] = {
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 },
525 { 0 }
526 };
527
528 static EbmlSyntax matroska_segments[] = {
529 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
530 { 0 }
531 };
532
533 static EbmlSyntax matroska_blockgroup[] = {
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) },
538 { MATROSKA_ID_CODECSTATE, EBML_NONE },
539 { 1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
540 { 0 }
541 };
542
543 static EbmlSyntax matroska_cluster[] = {
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 },
549 { 0 }
550 };
551
552 static EbmlSyntax matroska_clusters[] = {
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 },
558 { 0 }
559 };
560
561 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
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 },
572 { 0 }
573 };
574
575 static EbmlSyntax matroska_cluster_incremental[] = {
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 },
581 { 0 }
582 };
583
584 static EbmlSyntax matroska_clusters_incremental[] = {
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 },
590 { 0 }
591 };
592
593 static const char *const matroska_doctypes[] = { "matroska", "webm" };
594
595 static 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) {
614 matroska->current_id = id;
615 return 0;
616 }
617 id = (id << 8) | avio_r8(pb);
618 }
619
620 eof:
621 matroska->done = 1;
622 return AVERROR_EOF;
623 }
624
625 /*
626 * Return: Whether we reached the end of a level in the hierarchy or not.
627 */
628 static int ebml_level_end(MatroskaDemuxContext *matroska)
629 {
630 AVIOContext *pb = matroska->ctx->pb;
631 int64_t pos = avio_tell(pb);
632
633 if (matroska->num_levels > 0) {
634 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
635 if (pos - level->start >= level->length || matroska->current_id) {
636 matroska->num_levels--;
637 return 1;
638 }
639 }
640 return 0;
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.
649 * Returns: number of bytes read, < 0 on error
650 */
651 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
652 int max_size, uint64_t *number)
653 {
654 int read = 1, n = 1;
655 uint64_t total = 0;
656
657 /* The first byte tells us the length in bytes - avio_r8() can normally
658 * return 0, but since that's not a valid first ebmlID byte, we can
659 * use it safely here to catch EOS. */
660 if (!(total = avio_r8(pb))) {
661 /* we might encounter EOS here */
662 if (!pb->eof_reached) {
663 int64_t pos = avio_tell(pb);
664 av_log(matroska->ctx, AV_LOG_ERROR,
665 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
666 pos, pos);
667 return pb->error ? pb->error : AVERROR(EIO);
668 }
669 return AVERROR_EOF;
670 }
671
672 /* get the length of the EBML number */
673 read = 8 - ff_log2_tab[total];
674 if (read > max_size) {
675 int64_t pos = avio_tell(pb) - 1;
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 */
683 total ^= 1 << ff_log2_tab[total];
684 while (n++ < read)
685 total = (total << 8) | avio_r8(pb);
686
687 *number = total;
688
689 return read;
690 }
691
692 /**
693 * Read a EBML length value.
694 * This needs special handling for the "unknown length" case which has multiple
695 * encodings.
696 */
697 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
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
706 /*
707 * Read the next element as an unsigned int.
708 * 0 is success, < 0 is failure.
709 */
710 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
711 {
712 int n = 0;
713
714 if (size > 8)
715 return AVERROR_INVALIDDATA;
716
717 /* big-endian ordering; build up number */
718 *num = 0;
719 while (n++ < size)
720 *num = (*num << 8) | avio_r8(pb);
721
722 return 0;
723 }
724
725 /*
726 * Read the next element as a float.
727 * 0 is success, < 0 is failure.
728 */
729 static int ebml_read_float(AVIOContext *pb, int size, double *num)
730 {
731 if (size == 0)
732 *num = 0;
733 else if (size == 4)
734 *num = av_int2float(avio_rb32(pb));
735 else if (size == 8)
736 *num = av_int2double(avio_rb64(pb));
737 else
738 return AVERROR_INVALIDDATA;
739
740 return 0;
741 }
742
743 /*
744 * Read the next element as an ASCII string.
745 * 0 is success, < 0 is failure.
746 */
747 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
748 {
749 char *res;
750
751 /* EBML strings are usually not 0-terminated, so we allocate one
752 * byte more, read the string and NULL-terminate it ourselves. */
753 if (!(res = av_malloc(size + 1)))
754 return AVERROR(ENOMEM);
755 if (avio_read(pb, (uint8_t *) res, size) != size) {
756 av_free(res);
757 return AVERROR(EIO);
758 }
759 (res)[size] = '\0';
760 av_free(*str);
761 *str = res;
762
763 return 0;
764 }
765
766 /*
767 * Read the next element as binary data.
768 * 0 is success, < 0 is failure.
769 */
770 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
771 {
772 av_free(bin->data);
773 bin->size = 0;
774
775 if (!(bin->data = av_mallocz(length + AV_INPUT_BUFFER_PADDING_SIZE)))
776 return AVERROR(ENOMEM);
777
778 bin->pos = avio_tell(pb);
779 if (avio_read(pb, bin->data, length) != length) {
780 av_freep(&bin->data);
781 return AVERROR(EIO);
782 }
783
784 bin->size = length;
785
786 return 0;
787 }
788
789 /*
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 */
794 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
795 {
796 AVIOContext *pb = matroska->ctx->pb;
797 MatroskaLevel *level;
798
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);
802 return AVERROR(ENOSYS);
803 }
804
805 level = &matroska->levels[matroska->num_levels++];
806 level->start = avio_tell(pb);
807 level->length = length;
808
809 return 0;
810 }
811
812 /*
813 * Read signed/unsigned "EBML" numbers.
814 * Return: number of bytes processed, < 0 on error
815 */
816 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
817 uint8_t *data, uint32_t size, uint64_t *num)
818 {
819 AVIOContext pb;
820 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
821 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
822 }
823
824 /*
825 * Same as above, but signed.
826 */
827 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
828 uint8_t *data, uint32_t size, int64_t *num)
829 {
830 uint64_t unum;
831 int res;
832
833 /* read as unsigned number first */
834 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
835 return res;
836
837 /* make signed (weird way) */
838 *num = unum - ((1LL << (7 * res - 1)) - 1);
839
840 return res;
841 }
842
843 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
844 EbmlSyntax *syntax, void *data);
845
846 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
847 uint32_t id, void *data)
848 {
849 int i;
850 for (i = 0; syntax[i].id; i++)
851 if (id == syntax[i].id)
852 break;
853 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
854 matroska->num_levels > 0 &&
855 matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
856 return 0; // we reached the end of an unknown size cluster
857 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
858 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%"PRIX32"\n", id);
859 if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
860 return AVERROR_INVALIDDATA;
861 }
862 return ebml_parse_elem(matroska, &syntax[i], data);
863 }
864
865 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
866 void *data)
867 {
868 if (!matroska->current_id) {
869 uint64_t id;
870 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
871 if (res < 0)
872 return res;
873 matroska->current_id = id | 1 << 7 * res;
874 }
875 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
876 }
877
878 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
879 void *data)
880 {
881 int i, res = 0;
882
883 for (i = 0; syntax[i].id; i++)
884 switch (syntax[i].type) {
885 case EBML_UINT:
886 *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
887 break;
888 case EBML_FLOAT:
889 *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
890 break;
891 case EBML_STR:
892 case EBML_UTF8:
893 // the default may be NULL
894 if (syntax[i].def.s) {
895 uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
896 *dst = av_strdup(syntax[i].def.s);
897 if (!*dst)
898 return AVERROR(ENOMEM);
899 }
900 break;
901 }
902
903 while (!res && !ebml_level_end(matroska))
904 res = ebml_parse(matroska, syntax, data);
905
906 return res;
907 }
908
909 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
910 EbmlSyntax *syntax, void *data)
911 {
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 };
922 AVIOContext *pb = matroska->ctx->pb;
923 uint32_t id = syntax->id;
924 uint64_t length;
925 int res;
926
927 data = (char *) data + syntax->data_offset;
928 if (syntax->list_elem_size) {
929 EbmlList *list = data;
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 }
936 data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
937 memset(data, 0, syntax->list_elem_size);
938 list->nb_elem++;
939 }
940
941 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
942 matroska->current_id = 0;
943 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
944 return res;
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 }
951 }
952
953 switch (syntax->type) {
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;
960 case EBML_STR:
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;
979 }
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;
985 }
986
987 static void ebml_free(EbmlSyntax *syntax, void *data)
988 {
989 int i, j;
990 for (i = 0; syntax[i].id; i++) {
991 void *data_off = (char *) data + syntax[i].data_offset;
992 switch (syntax[i].type) {
993 case EBML_STR:
994 case EBML_UTF8:
995 av_freep(data_off);
996 break;
997 case EBML_BIN:
998 av_freep(&((EbmlBin *) data_off)->data);
999 break;
1000 case EBML_NEST:
1001 if (syntax[i].list_elem_size) {
1002 EbmlList *list = data_off;
1003 char *ptr = list->elem;
1004 for (j = 0; j < list->nb_elem;
1005 j++, ptr += syntax[i].list_elem_size)
1006 ebml_free(syntax[i].def.n, ptr);
1007 av_free(list->elem);
1008 } else
1009 ebml_free(syntax[i].def.n, data_off);
1010 default:
1011 break;
1012 }
1013 }
1014 }
1015
1016 /*
1017 * Autodetecting...
1018 */
1019 static int matroska_probe(AVProbeData *p)
1020 {
1021 uint64_t total = 0;
1022 int len_mask = 0x80, size = 1, n = 1, i;
1023
1024 /* EBML header? */
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)
1035 return 0;
1036 total &= (len_mask - 1);
1037 while (n < size)
1038 total = (total << 8) | p->buf[4 + n++];
1039
1040 /* Does the probe data contain the whole header? */
1041 if (p->buf_size < 4 + size + total)
1042 return 0;
1043
1044 /* The header should contain a known document type. For now,
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. */
1048 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1049 int probelen = strlen(matroska_doctypes[i]);
1050 if (total < probelen)
1051 continue;
1052 for (n = 4 + size; n <= 4 + size + total - probelen; n++)
1053 if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
1054 return AVPROBE_SCORE_MAX;
1055 }
1056
1057 // probably valid EBML header but no recognized doctype
1058 return AVPROBE_SCORE_EXTENSION;
1059 }
1060
1061 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1062 int num)
1063 {
1064 MatroskaTrack *tracks = matroska->tracks.elem;
1065 int i;
1066
1067 for (i = 0; i < matroska->tracks.nb_elem; i++)
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
1075 static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
1076 MatroskaTrack *track)
1077 {
1078 MatroskaTrackEncoding *encodings = track->encodings.elem;
1079 uint8_t *data = *buf;
1080 int isize = *buf_size;
1081 uint8_t *pkt_data = NULL;
1082 uint8_t av_unused *newpktdata;
1083 int pkt_size = isize;
1084 int result = 0;
1085 int olen;
1086
1087 if (pkt_size >= 10000000)
1088 return AVERROR_INVALIDDATA;
1089
1090 switch (encodings[0].compression.algo) {
1091 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1092 {
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 }
1108 #if CONFIG_LZO
1109 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1110 do {
1111 olen = pkt_size *= 3;
1112 newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1113 if (!newpktdata) {
1114 result = AVERROR(ENOMEM);
1115 goto failed;
1116 }
1117 pkt_data = newpktdata;
1118 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1119 } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
1120 if (result) {
1121 result = AVERROR_INVALIDDATA;
1122 goto failed;
1123 }
1124 pkt_size -= olen;
1125 break;
1126 #endif
1127 #if CONFIG_ZLIB
1128 case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
1129 {
1130 z_stream zstream = { 0 };
1131 if (inflateInit(&zstream) != Z_OK)
1132 return -1;
1133 zstream.next_in = data;
1134 zstream.avail_in = isize;
1135 do {
1136 pkt_size *= 3;
1137 newpktdata = av_realloc(pkt_data, pkt_size);
1138 if (!newpktdata) {
1139 inflateEnd(&zstream);
1140 goto failed;
1141 }
1142 pkt_data = newpktdata;
1143 zstream.avail_out = pkt_size - zstream.total_out;
1144 zstream.next_out = pkt_data + zstream.total_out;
1145 result = inflate(&zstream, Z_NO_FLUSH);
1146 } while (result == Z_OK && pkt_size < 10000000);
1147 pkt_size = zstream.total_out;
1148 inflateEnd(&zstream);
1149 if (result != Z_STREAM_END) {
1150 if (result == Z_MEM_ERROR)
1151 result = AVERROR(ENOMEM);
1152 else
1153 result = AVERROR_INVALIDDATA;
1154 goto failed;
1155 }
1156 break;
1157 }
1158 #endif
1159 #if CONFIG_BZLIB
1160 case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
1161 {
1162 bz_stream bzstream = { 0 };
1163 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1164 return -1;
1165 bzstream.next_in = data;
1166 bzstream.avail_in = isize;
1167 do {
1168 pkt_size *= 3;
1169 newpktdata = av_realloc(pkt_data, pkt_size);
1170 if (!newpktdata) {
1171 BZ2_bzDecompressEnd(&bzstream);
1172 goto failed;
1173 }
1174 pkt_data = newpktdata;
1175 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1176 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1177 result = BZ2_bzDecompress(&bzstream);
1178 } while (result == BZ_OK && pkt_size < 10000000);
1179 pkt_size = bzstream.total_out_lo32;
1180 BZ2_bzDecompressEnd(&bzstream);
1181 if (result != BZ_STREAM_END) {
1182 if (result == BZ_MEM_ERROR)
1183 result = AVERROR(ENOMEM);
1184 else
1185 result = AVERROR_INVALIDDATA;
1186 goto failed;
1187 }
1188 break;
1189 }
1190 #endif
1191 default:
1192 return AVERROR_INVALIDDATA;
1193 }
1194
1195 *buf = pkt_data;
1196 *buf_size = pkt_size;
1197 return 0;
1198
1199 failed:
1200 av_free(pkt_data);
1201 return result;
1202 }
1203
1204 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1205 AVPacket *pkt, uint64_t display_duration)
1206 {
1207 AVBufferRef *line;
1208 char *layer, *ptr = pkt->data, *end = ptr + pkt->size;
1209
1210 for (; *ptr != ',' && ptr < end - 1; ptr++)
1211 ;
1212 if (*ptr == ',')
1213 layer = ++ptr;
1214 for (; *ptr != ',' && ptr < end - 1; ptr++)
1215 ;
1216 if (*ptr == ',') {
1217 int64_t end_pts = pkt->pts + display_duration;
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;
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;
1233 *ptr++ = '\0';
1234 len = 50 + end - ptr + AV_INPUT_BUFFER_PADDING_SIZE;
1235 if (!(line = av_buffer_alloc(len)))
1236 return;
1237 snprintf(line->data, len,
1238 "Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1239 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1240 av_buffer_unref(&pkt->buf);
1241 pkt->buf = line;
1242 pkt->data = line->data;
1243 pkt->size = strlen(line->data);
1244 }
1245 }
1246
1247 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1248 {
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
1256 av_packet_unref(in);
1257 av_free(in);
1258 return 0;
1259 }
1260
1261 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1262 AVDictionary **metadata, char *prefix)
1263 {
1264 MatroskaTag *tags = list->elem;
1265 char key[1024];
1266 int i;
1267
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;
1271
1272 if (!tags[i].name) {
1273 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1274 continue;
1275 }
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));
1280 if (tags[i].def || !lang) {
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);
1284 }
1285 if (lang) {
1286 av_strlcat(key, "-", sizeof(key));
1287 av_strlcat(key, lang, sizeof(key));
1288 av_dict_set(metadata, key, tags[i].string, 0);
1289 if (tags[i].sub.nb_elem)
1290 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1291 }
1292 }
1293 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1294 }
1295
1296 static void matroska_convert_tags(AVFormatContext *s)
1297 {
1298 MatroskaDemuxContext *matroska = s->priv_data;
1299 MatroskaTags *tags = matroska->tags.elem;
1300 int i, j;
1301
1302 for (i = 0; i < matroska->tags.nb_elem; i++) {
1303 if (tags[i].target.attachuid) {
1304 MatroskaAttachment *attachment = matroska->attachments.elem;
1305 int found = 0;
1306 for (j = 0; j < matroska->attachments.nb_elem; j++) {
1307 if (attachment[j].uid == tags[i].target.attachuid &&
1308 attachment[j].stream) {
1309 matroska_convert_tag(s, &tags[i].tag,
1310 &attachment[j].stream->metadata, NULL);
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 }
1320 } else if (tags[i].target.chapteruid) {
1321 MatroskaChapter *chapter = matroska->chapters.elem;
1322 int found = 0;
1323 for (j = 0; j < matroska->chapters.nb_elem; j++) {
1324 if (chapter[j].uid == tags[i].target.chapteruid &&
1325 chapter[j].chapter) {
1326 matroska_convert_tag(s, &tags[i].tag,
1327 &chapter[j].chapter->metadata, NULL);
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 }
1337 } else if (tags[i].target.trackuid) {
1338 MatroskaTrack *track = matroska->tracks.elem;
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) {
1343 matroska_convert_tag(s, &tags[i].tag,
1344 &track[j].stream->metadata, NULL);
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 }
1354 } else {
1355 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1356 tags[i].target.type);
1357 }
1358 }
1359 }
1360
1361 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
1362 int idx)
1363 {
1364 EbmlList *seekhead_list = &matroska->seekhead;
1365 uint32_t level_up = matroska->level_up;
1366 uint32_t saved_id = matroska->current_id;
1367 MatroskaSeekhead *seekhead = seekhead_list->elem;
1368 int64_t before_pos = avio_tell(matroska->ctx->pb);
1369 MatroskaLevel level;
1370 int64_t offset;
1371 int ret = 0;
1372
1373 if (idx >= seekhead_list->nb_elem ||
1374 seekhead[idx].id == MATROSKA_ID_SEEKHEAD ||
1375 seekhead[idx].id == MATROSKA_ID_CLUSTER)
1376 return 0;
1377
1378 /* seek */
1379 offset = seekhead[idx].pos + matroska->segment_start;
1380 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1381 /* We don't want to lose our seekhead level, so we add
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);
1387 ret = AVERROR_INVALIDDATA;
1388 } else {
1389 level.start = 0;
1390 level.length = (uint64_t) -1;
1391 matroska->levels[matroska->num_levels] = level;
1392 matroska->num_levels++;
1393 matroska->current_id = 0;
1394
1395 ret = ebml_parse(matroska, matroska_segment, matroska);
1396
1397 /* remove dummy level */
1398 while (matroska->num_levels) {
1399 uint64_t length = matroska->levels[--matroska->num_levels].length;
1400 if (length == (uint64_t) -1)
1401 break;
1402 }
1403 }
1404 }
1405 /* seek back */
1406 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1407 matroska->level_up = level_up;
1408 matroska->current_id = saved_id;
1409
1410 return ret;
1411 }
1412
1413 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1414 {
1415 EbmlList *seekhead_list = &matroska->seekhead;
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
1420 if (!(matroska->ctx->pb->seekable & AVIO_SEEKABLE_NORMAL) ||
1421 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1422 return;
1423
1424 for (i = 0; i < seekhead_list->nb_elem; i++) {
1425 MatroskaSeekhead *seekhead = seekhead_list->elem;
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
1440 static void matroska_parse_cues(MatroskaDemuxContext *matroska)
1441 {
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++)
1450 if (seekhead[i].id == MATROSKA_ID_CUES)
1451 break;
1452 assert(i <= seekhead_list->nb_elem);
1453
1454 matroska_parse_seekhead_entry(matroska, i);
1455
1456 index_list = &matroska->index;
1457 index = index_list->elem;
1458 if (index_list->nb_elem &&
1459 index[0].time > 1E14 / matroska->time_scale) {
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++) {
1464 EbmlList *pos_list = &index[i].pos;
1465 MatroskaIndexPos *pos = pos_list->elem;
1466 for (j = 0; j < pos_list->nb_elem; j++) {
1467 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1468 pos[j].track);
1469 if (track && track->stream)
1470 av_add_index_entry(track->stream,
1471 pos[j].pos + matroska->segment_start,
1472 index[i].time / index_scale, 0, 0,
1473 AVINDEX_KEYFRAME);
1474 }
1475 }
1476 }
1477
1478 static int matroska_aac_profile(char *codec_id)
1479 {
1480 static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
1481 int profile;
1482
1483 for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
1484 if (strstr(codec_id, aac_profiles[profile]))
1485 break;
1486 return profile + 1;
1487 }
1488
1489 static int matroska_aac_sri(int samplerate)
1490 {
1491 int sri;
1492
1493 for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1494 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1495 break;
1496 return sri;
1497 }
1498
1499 static int matroska_parse_flac(AVFormatContext *s,
1500 MatroskaTrack *track,
1501 int *offset)
1502 {
1503 AVStream *st = track->stream;
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
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
1542 st->codecpar->channel_layout = mask;
1543 }
1544 av_dict_free(&dict);
1545 }
1546
1547 p += block_size;
1548 size -= block_size;
1549 }
1550
1551 return 0;
1552 }
1553
1554 static 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
1574 static 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
1599 static int mkv_parse_video_projection(AVStream *st, const MatroskaTrack *track)
1600 {
1601 AVSphericalMapping *spherical;
1602 enum AVSphericalProjection projection;
1603 size_t spherical_size;
1604 uint32_t l = 0, t = 0, r = 0, b = 0;
1605 uint32_t padding = 0;
1606 int ret;
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
1618
1619 switch (track->video.projection.type) {
1620 case MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR:
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 "
1630 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
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;
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;
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;
1659 }
1660 break;
1661 case MATROSKA_VIDEO_PROJECTION_TYPE_RECTANGULAR:
1662 /* No Spherical metadata */
1663 return 0;
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
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
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
1698 static int matroska_parse_tracks(AVFormatContext *s)
1699 {
1700 MatroskaDemuxContext *matroska = s->priv_data;
1701 MatroskaTrack *tracks = matroska->tracks.elem;
1702 AVStream *st;
1703 int i, j, ret;
1704
1705 for (i = 0; i < matroska->tracks.nb_elem; i++) {
1706 MatroskaTrack *track = &tracks[i];
1707 enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1708 EbmlList *encodings_list = &track->encodings;
1709 MatroskaTrackEncoding *encodings = encodings_list->elem;
1710 uint8_t *extradata = NULL;
1711 int extradata_size = 0;
1712 int extradata_offset = 0;
1713 AVIOContext b;
1714
1715 /* Apply some sanity checks. */
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 }
1724 if (!track->codec_id)
1725 continue;
1726
1727 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1728 if (!track->default_duration && track->video.frame_rate > 0)
1729 track->default_duration = 1000000000 / track->video.frame_rate;
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,
1740 "Multiple combined encodings not supported");
1741 } else if (encodings_list->nb_elem == 1) {
1742 if (encodings[0].type ||
1743 (
1744 #if CONFIG_ZLIB
1745 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1746 #endif
1747 #if CONFIG_BZLIB
1748 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1749 #endif
1750 #if CONFIG_LZO
1751 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1752 #endif
1753 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
1754 encodings[0].scope = 0;
1755 av_log(matroska->ctx, AV_LOG_ERROR,
1756 "Unsupported encoding type");
1757 } else if (track->codec_priv.size && encodings[0].scope & 2) {
1758 uint8_t *codec_priv = track->codec_priv.data;
1759 int ret = matroska_decode_buffer(&track->codec_priv.data,
1760 &track->codec_priv.size,
1761 track);
1762 if (ret < 0) {
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");
1767 }
1768
1769 if (codec_priv != track->codec_priv.data)
1770 av_free(codec_priv);
1771 }
1772 }
1773
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;
1778 break;
1779 }
1780 }
1781
1782 st = track->stream = avformat_new_stream(s, NULL);
1783 if (!st)
1784 return AVERROR(ENOMEM);
1785
1786 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
1787 track->codec_priv.size >= 40 &&
1788 track->codec_priv.data) {
1789 track->ms_compat = 1;
1790 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
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 &&
1796 track->codec_priv.data) {
1797 int ret;
1798 ffio_init_context(&b, track->codec_priv.data,
1799 track->codec_priv.size,
1800 0, NULL, NULL, NULL, NULL);
1801 ret = ff_get_wav_header(s, &b, st->codecpar, track->codec_priv.size);
1802 if (ret < 0)
1803 return ret;
1804 codec_id = st->codecpar->codec_id;
1805 extradata_offset = FFMIN(track->codec_priv.size, 18);
1806 } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1807 (track->codec_priv.size >= 86) &&
1808 (track->codec_priv.data)) {
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 }
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 }
1825 } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1826 switch (track->audio.bitdepth) {
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;
1836 }
1837 } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1838 switch (track->audio.bitdepth) {
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;
1848 }
1849 } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
1850 track->audio.bitdepth == 64) {
1851 codec_id = AV_CODEC_ID_PCM_F64LE;
1852 } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1853 int profile = matroska_aac_profile(track->codec_id);
1854 int sri = matroska_aac_sri(track->audio.samplerate);
1855 extradata = av_mallocz(5 + AV_INPUT_BUFFER_PADDING_SIZE);
1856 if (!extradata)
1857 return AVERROR(ENOMEM);
1858 extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
1859 extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
1860 if (strstr(track->codec_id, "SBR")) {
1861 sri = matroska_aac_sri(track->audio.out_samplerate);
1862 extradata[2] = 0x56;
1863 extradata[3] = 0xE5;
1864 extradata[4] = 0x80 | (sri << 3);
1865 extradata_size = 5;
1866 } else
1867 extradata_size = 2;
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.
1870 * Create the "atom size", "tag", and "tag version" fields the
1871 * decoder expects manually. */
1872 extradata_size = 12 + track->codec_priv.size;
1873 extradata = av_mallocz(extradata_size +
1874 AV_INPUT_BUFFER_PADDING_SIZE);
1875 if (!extradata)
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,
1881 track->codec_priv.size);
1882 } else if (codec_id == AV_CODEC_ID_TTA) {
1883 extradata_size = 30;
1884 extradata = av_mallocz(extradata_size);
1885 if (!extradata)
1886 return AVERROR(ENOMEM);
1887 ffio_init_context(&b, extradata, extradata_size, 1,
1888 NULL, NULL, NULL, NULL);
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);
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) {
1900 extradata_offset = 26;
1901 } else if (codec_id == AV_CODEC_ID_RA_144) {
1902 track->audio.out_samplerate = 8000;
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) {
1908 int flavor;
1909 ffio_init_context(&b, track->codec_priv.data,
1910 track->codec_priv.size,
1911 0, NULL, NULL, NULL, NULL);
1912 avio_skip(&b, 22);
1913 flavor = avio_rb16(&b);
1914 track->audio.coded_framesize = avio_rb32(&b);
1915 avio_skip(&b, 12);
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);
1919 if (flavor <= 0 ||
1920 track->audio.coded_framesize <= 0 ||
1921 track->audio.sub_packet_h <= 0 ||
1922 track->audio.frame_size <= 0 ||
1923 track->audio.sub_packet_size <= 0)
1924 return AVERROR_INVALIDDATA;
1925 track->audio.buf = av_malloc(track->audio.frame_size *
1926 track->audio.sub_packet_h);
1927 if (!track->audio.buf)
1928 return AVERROR(ENOMEM);
1929 if (codec_id == AV_CODEC_ID_RA_288) {
1930 st->codecpar->block_align = track->audio.coded_framesize;
1931 track->codec_priv.size = 0;
1932 } else {
1933 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1934 static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1935 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1936 st->codecpar->bit_rate = sipr_bit_rate[flavor];
1937 }
1938 st->codecpar->block_align = track->audio.sub_packet_size;
1939 extradata_offset = 78;
1940 }
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;
1945 }
1946 track->codec_priv.size -= extradata_offset;
1947
1948 if (codec_id == AV_CODEC_ID_NONE)
1949 av_log(matroska->ctx, AV_LOG_INFO,
1950 "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1951
1952 if (track->time_scale < 0.01)
1953 track->time_scale = 1.0;
1954 avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
1955 1000 * 1000 * 1000); /* 64 bit pts in ns */
1956
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
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
1969 st->codecpar->codec_id = codec_id;
1970 st->start_time = 0;
1971 if (strcmp(track->language, "und"))
1972 av_dict_set(&st->metadata, "language", track->language, 0);
1973 av_dict_set(&st->metadata, "title", track->name, 0);
1974
1975 if (track->flag_default)
1976 st->disposition |= AV_DISPOSITION_DEFAULT;
1977 if (track->flag_forced)
1978 st->disposition |= AV_DISPOSITION_FORCED;
1979
1980 if (!st->codecpar->extradata) {
1981 if (extradata) {
1982 st->codecpar->extradata = extradata;
1983 st->codecpar->extradata_size = extradata_size;
1984 } else if (track->codec_priv.data && track->codec_priv.size > 0) {
1985 st->codecpar->extradata = av_mallocz(track->codec_priv.size +
1986 AV_INPUT_BUFFER_PADDING_SIZE);
1987 if (!st->codecpar->extradata)
1988 return AVERROR(ENOMEM);
1989 st->codecpar->extradata_size = track->codec_priv.size;
1990 memcpy(st->codecpar->extradata,
1991 track->codec_priv.data + extradata_offset,
1992 track->codec_priv.size);
1993 }
1994 }
1995
1996 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1997 int display_width_mul = 1;
1998 int display_height_mul = 1;
1999
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;
2004
2005 if (track->video.interlaced == MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED)
2006 st->codecpar->field_order = mkv_field_order(track->video.field_order);
2007
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
2011 av_reduce(&st->sample_aspect_ratio.num,
2012 &st->sample_aspect_ratio.den,
2013 st->codecpar->height * track->video.display_width * display_width_mul,
2014 st->codecpar->width * track->video.display_height * display_height_mul,
2015 255);
2016 if (st->codecpar->codec_id != AV_CODEC_ID_H264 &&
2017 st->codecpar->codec_id != AV_CODEC_ID_HEVC)
2018 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2019 if (track->default_duration) {
2020 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2021 1000000000, track->default_duration, 30000);
2022 }
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 }
2030
2031 ret = mkv_parse_video_projection(st, track);
2032 if (ret < 0)
2033 return ret;
2034 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
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)
2039 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2040 if (st->codecpar->codec_id == AV_CODEC_ID_MP3)
2041 st->need_parsing = AVSTREAM_PARSE_FULL;
2042 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2043 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2044 if (st->codecpar->codec_id == AV_CODEC_ID_SSA)
2045 matroska->contains_ssa = 1;
2046 }
2047 }
2048
2049 return 0;
2050 }
2051
2052 static 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. */
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 ||
2073 ebml.max_size > sizeof(uint64_t) ||
2074 ebml.id_length > sizeof(uint32_t) ||
2075 ebml.doctype_version > 3) {
2076 avpriv_report_missing_feature(matroska->ctx,
2077 "EBML version %"PRIu64", doctype %s, doc version %"PRIu64,
2078 ebml.version, ebml.doctype, ebml.doctype_version);
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
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)) {
2122 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2123 } else {
2124 AVStream *st = avformat_new_stream(s, NULL);
2125 if (!st)
2126 break;
2127 av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
2128 av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
2129 st->codecpar->codec_id = AV_CODEC_ID_NONE;
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))) {
2134 st->codecpar->codec_id = ff_mkv_image_mime_tags[i].id;
2135 break;
2136 }
2137 }
2138
2139 attachments[j].stream = st;
2140
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;
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 {
2152 st->codecpar->codec_type = AVMEDIA_TYPE_ATTACHMENT;
2153 st->codecpar->extradata = av_malloc(attachments[j].bin.size);
2154 if (!st->codecpar->extradata)
2155 break;
2156
2157 st->codecpar->extradata_size = attachments[j].bin.size;
2158 memcpy(st->codecpar->extradata, attachments[j].bin.data,
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))) {
2164 st->codecpar->codec_id = ff_mkv_mime_tags[i].id;
2165 break;
2166 }
2167 }
2168 }
2169 }
2170 }
2171
2172 chapters = chapters_list->elem;
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)) {
2176 chapters[i].chapter =
2177 avpriv_new_chapter(s, chapters[i].uid,
2178 (AVRational) { 1, 1000000000 },
2179 chapters[i].start, chapters[i].end,
2180 chapters[i].title);
2181 av_dict_set(&chapters[i].chapter->metadata,
2182 "title", chapters[i].title, 0);
2183 max_start = chapters[i].start;
2184 }
2185
2186 matroska_convert_tags(s);
2187
2188 return 0;
2189 }
2190
2191 /*
2192 * Put one packet in an application-supplied AVPacket struct.
2193 * Returns 0 on success or -1 on failure.
2194 */
2195 static 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) {
2202 void *newpackets;
2203 memmove(&matroska->packets[0], &matroska->packets[1],
2204 (matroska->num_packets - 1) * sizeof(AVPacket *));
2205 newpackets = av_realloc(matroska->packets,
2206 (matroska->num_packets - 1) *
2207 sizeof(AVPacket *));
2208 if (newpackets)
2209 matroska->packets = newpackets;
2210 } else {
2211 av_freep(&matroska->packets);
2212 matroska->prev_pkt = NULL;
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 */
2224 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2225 {
2226 matroska->prev_pkt = NULL;
2227 if (matroska->packets) {
2228 int n;
2229 for (n = 0; n < matroska->num_packets; n++) {
2230 av_packet_unref(matroska->packets[n]);
2231 av_free(matroska->packets[n]);
2232 }
2233 av_freep(&matroska->packets);
2234 matroska->num_packets = 0;
2235 }
2236 }
2237
2238 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2239 int *buf_size, int type,
2240 uint32_t **lace_buf, int *laces)
2241 {
2242 int res = 0, n, size = *buf_size;
2243 uint8_t *data = *buf;
2244 uint32_t *lace_size;
2245
2246 if (!type) {
2247 *laces = 1;
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);
2257 *laces = *data + 1;
2258 data += 1;
2259 size -= 1;
2260 lace_size = av_mallocz(*laces * sizeof(int));
2261 if (!lace_size)
2262 return AVERROR(ENOMEM);
2263
2264 switch (type) {
2265 case 0x1: /* Xiph lacing */
2266 {
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 }
2275 temp = *data;
2276 lace_size[n] += temp;
2277 data += 1;
2278 size -= 1;
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 */
2294 if (size % (*laces)) {
2295 res = AVERROR_INVALIDDATA;
2296 break;
2297 }
2298 for (n = 0; n < *laces; n++)
2299 lace_size[n] = size / *laces;
2300 break;
2301
2302 case 0x3: /* EBML lacing */
2303 {
2304 uint64_t num;
2305 uint64_t total;
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 }
2326 data += r;
2327 size -= r;
2328 lace_size[n] = lace_size[n - 1] + snum;
2329 total += lace_size[n];
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;
2342 *buf_size = size;
2343
2344 return res;
2345 }
2346
2347 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2348 MatroskaTrack *track, AVStream *st,
2349 uint8_t *data, int size, uint64_t timecode,
2350 uint64_t duration, int64_t pos)
2351 {
2352 int a = st->codecpar->block_align;
2353 int sps = track->audio.sub_packet_size;
2354 int cfs = track->audio.coded_framesize;
2355 int h = track->audio.sub_packet_h;
2356 int y = track->audio.sub_packet_cnt;
2357 int w = track->audio.frame_size;
2358 int x;
2359
2360 if (!track->audio.pkt_cnt) {
2361 if (track->audio.sub_packet_cnt == 0)
2362 track->audio.buf_timecode = timecode;
2363 if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
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 }
2369 for (x = 0; x < h / 2; x++)
2370 memcpy(track->audio.buf + x * 2 * w + y * cfs,
2371 data + x * cfs, cfs);
2372 } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
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 }
2378 memcpy(track->audio.buf + y * w, data, w);
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 }
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);
2389 }
2390
2391 if (++track->audio.sub_packet_cnt >= h) {
2392 if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
2393 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2394 track->audio.sub_packet_cnt = 0;
2395 track->audio.pkt_cnt = h * w / a;
2396 }
2397 }
2398
2399 while (track->audio.pkt_cnt) {
2400 int ret;
2401 AVPacket *pkt = av_mallocz(sizeof(AVPacket));
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 }
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;
2414 track->audio.buf_timecode = AV_NOPTS_VALUE;
2415 pkt->pos = pos;
2416 pkt->stream_index = st->index;
2417 dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2418 }
2419
2420 return 0;
2421 }
2422
2423 /* reconstruct full wavpack blocks from mangled matroska ones */
2424 static 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
2434 if (srclen < 12 || track->stream->codecpar->extradata_size < 2)
2435 return AVERROR_INVALIDDATA;
2436
2437 ver = AV_RL16(track->stream->codecpar->extradata);
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);
2460 src += 4;
2461 srclen -= 4;
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
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
2488
2489 src += blocksize;
2490 srclen -= blocksize;
2491 offset += blocksize + 32;
2492 }
2493
2494 *pdst = dst;
2495 *size = dstlen;
2496
2497 return 0;
2498
2499 fail:
2500 av_freep(&dst);
2501 return ret;
2502 }
2503
2504 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2505 MatroskaTrack *track, AVStream *st,
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
2521 if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
2522 uint8_t *wv_data;
2523 res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2524 if (res < 0) {
2525 av_log(matroska->ctx, AV_LOG_ERROR,
2526 "Error parsing a wavpack block.\n");
2527 goto fail;
2528 }
2529 if (pkt_data != data)
2530 av_freep(&pkt_data);
2531 pkt_data = wv_data;
2532 }
2533
2534 if (st->codecpar->codec_id == AV_CODEC_ID_PRORES)
2535 offset = 8;
2536
2537 pkt = av_mallocz(sizeof(AVPacket));
2538 if (!pkt) {
2539 av_freep(&pkt_data);
2540 return AVERROR(ENOMEM);
2541 }
2542 /* XXX: prevent data copy... */
2543 if (av_new_packet(pkt, pkt_size + offset) < 0) {
2544 av_free(pkt);
2545 av_freep(&pkt_data);
2546 return AVERROR(ENOMEM);
2547 }
2548
2549 if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
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
2560 pkt->flags = is_keyframe;
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;
2568 if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE || st->codecpar->codec_id == AV_CODEC_ID_SRT)
2569 pkt->duration = duration;
2570 #if FF_API_CONVERGENCE_DURATION
2571 FF_DISABLE_DEPRECATION_WARNINGS
2572 if (st->codecpar->codec_id == AV_CODEC_ID_SRT)
2573 pkt->convergence_duration = duration;
2574 FF_ENABLE_DEPRECATION_WARNINGS
2575 #endif
2576
2577 if (st->codecpar->codec_id == AV_CODEC_ID_SSA)
2578 matroska_fix_ass_packet(matroska, pkt, duration);
2579
2580 if (matroska->prev_pkt &&
2581 timecode != AV_NOPTS_VALUE &&
2582 matroska->prev_pkt->pts == timecode &&
2583 matroska->prev_pkt->stream_index == st->index &&
2584 st->codecpar->codec_id == AV_CODEC_ID_SSA)
2585 matroska_merge_packets(matroska->prev_pkt, pkt);
2586 else {
2587 dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2588 matroska->prev_pkt = pkt;
2589 }
2590
2591 return 0;
2592
2593 fail:
2594 if (pkt_data != data)
2595 av_freep(&pkt_data);
2596 return res;
2597 }
2598
2599 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2600 int size, int64_t pos, uint64_t cluster_time,
2601 uint64_t block_duration, int is_keyframe,
2602 int64_t cluster_pos)
2603 {
2604 uint64_t timecode = AV_NOPTS_VALUE;
2605 MatroskaTrack *track;
2606 int res = 0;
2607 AVStream *st;
2608 int16_t block_time;
2609 uint32_t *lace_size = NULL;
2610 int n, flags, laces = 0;
2611 uint64_t num, duration;
2612
2613 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2614 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2615 return n;
2616 }
2617 data += n;
2618 size -= n;
2619
2620 track = matroska_find_track_by_num(matroska, num);
2621 if (!track || !track->stream) {
2622 av_log(matroska->ctx, AV_LOG_INFO,
2623 "Invalid stream %"PRIu64" or size %u\n", num, size);
2624 return AVERROR_INVALIDDATA;
2625 } else if (size <= 3)
2626 return 0;
2627 st = track->stream;
2628 if (st->discard >= AVDISCARD_ALL)
2629 return res;
2630
2631 block_time = AV_RB16(data);
2632 data += 2;
2633 flags = *data++;
2634 size -= 3;
2635 if (is_keyframe == -1)
2636 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2637
2638 if (cluster_time != (uint64_t) -1 &&
2639 (block_time >= 0 || cluster_time >= -block_time)) {
2640 timecode = cluster_time + block_time - track->codec_delay;
2641 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
2642 timecode < track->end_timecode)
2643 is_keyframe = 0; /* overlapping subtitles are not key frame */
2644 if (is_keyframe)
2645 av_add_index_entry(st, cluster_pos, timecode, 0, 0,
2646 AVINDEX_KEYFRAME);
2647 }
2648
2649 if (matroska->skip_to_keyframe &&
2650 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2651 if (!is_keyframe || timecode < matroska->skip_to_timecode)
2652 return res;
2653 matroska->skip_to_keyframe = 0;
2654 }
2655
2656 res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2657 &lace_size, &laces);
2658
2659 if (res)
2660 goto end;
2661
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 {
2669 duration = track->default_duration / matroska->time_scale;
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
2677 for (n = 0; n < laces; n++) {
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) {
2683 res = matroska_parse_rm_audio(matroska, track, st, data,
2684 lace_size[n],
2685 timecode, duration, pos);
2686 if (res)
2687 goto end;
2688 } else {
2689 res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2690 timecode, duration, pos,
2691 !n ? is_keyframe : 0);
2692 if (res)
2693 goto end;
2694 }
2695
2696 if (timecode != AV_NOPTS_VALUE)
2697 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2698 data += lace_size[n];
2699 }
2700
2701 end:
2702 av_free(lace_size);
2703 return res;
2704 }
2705
2706 static 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;
2721 matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2722 matroska->prev_pkt = NULL;
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 <
2738 matroska->current_cluster.blocks.nb_elem) {
2739 blocks_list = &matroska->current_cluster.blocks;
2740 blocks = blocks_list->elem;
2741
2742 matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2743 i = blocks_list->nb_elem - 1;
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;
2748 res = matroska_parse_block(matroska, blocks[i].bin.data,
2749 blocks[i].bin.size, blocks[i].bin.pos,
2750 matroska->current_cluster.timecode,
2751 blocks[i].duration, is_keyframe,
2752 matroska->current_cluster_pos);
2753 }
2754 }
2755
2756 if (res < 0)
2757 matroska->done = 1;
2758 return res;
2759 }
2760
2761 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2762 {
2763 MatroskaCluster cluster = { 0 };
2764 EbmlList *blocks_list;
2765 MatroskaBlock *blocks;
2766 int i, res;
2767 int64_t pos;
2768
2769 if (!matroska->contains_ssa)
2770 return matroska_parse_cluster_incremental(matroska);
2771 pos = avio_tell(matroska->ctx->pb);
2772 matroska->prev_pkt = NULL;
2773 if (matroska->current_id)
2774 pos -= 4; /* sizeof the ID which was already read */
2775 res = ebml_parse(matroska, matroska_clusters, &cluster);
2776 blocks_list = &cluster.blocks;
2777 blocks = blocks_list->elem;
2778 for (i = 0; i < blocks_list->nb_elem && !res; i++)
2779 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2780 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2781 if (!blocks[i].non_simple)
2782 blocks[i].duration = AV_NOPTS_VALUE;
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);
2787 }
2788 ebml_free(matroska_cluster, &cluster);
2789 return res;
2790 }
2791
2792 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2793 {
2794 MatroskaDemuxContext *matroska = s->priv_data;
2795 int ret = 0;
2796
2797 while (!ret && matroska_deliver_packet(matroska, pkt)) {
2798 int64_t pos = avio_tell(matroska->ctx->pb);
2799 if (matroska->done)
2800 return AVERROR_EOF;
2801 if (matroska_parse_cluster(matroska) < 0)
2802 ret = matroska_resync(matroska, pos);
2803 }
2804
2805 if (ret == AVERROR_INVALIDDATA && pkt->data) {
2806 pkt->flags |= AV_PKT_FLAG_CORRUPT;
2807 return 0;
2808 }
2809
2810 return ret;
2811 }
2812
2813 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2814 int64_t timestamp, int flags)
2815 {
2816 MatroskaDemuxContext *matroska = s->priv_data;
2817 MatroskaTrack *tracks = NULL;
2818 AVStream *st = s->streams[stream_index];
2819 int i, index, index_sub, index_min;
2820
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
2827 if (!st->nb_index_entries)
2828 return 0;
2829 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2830
2831 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2832 avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
2833 SEEK_SET);
2834 matroska->current_id = 0;
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 }
2840 }
2841
2842 matroska_clear_queue(matroska);
2843 if (index < 0)
2844 return 0;
2845
2846 index_min = index;
2847 tracks = matroska->tracks.elem;
2848 for (i = 0; i < matroska->tracks.nb_elem; i++) {
2849 tracks[i].audio.pkt_cnt = 0;
2850 tracks[i].audio.sub_packet_cnt = 0;
2851 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2852 tracks[i].end_timecode = 0;
2853 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
2854 tracks[i].stream->discard != AVDISCARD_ALL) {
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)
2862 index_min = index_sub;
2863 }
2864 }
2865
2866 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2867 matroska->current_id = 0;
2868 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2869 matroska->skip_to_timecode = st->index_entries[index].timestamp;
2870 matroska->done = 0;
2871 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2872 return 0;
2873 }
2874
2875 static int matroska_read_close(AVFormatContext *s)
2876 {
2877 MatroskaDemuxContext *matroska = s->priv_data;
2878 MatroskaTrack *tracks = matroska->tracks.elem;
2879 int n;
2880
2881 matroska_clear_queue(matroska);
2882
2883 for (n = 0; n < matroska->tracks.nb_elem; n++)
2884 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2885 av_free(tracks[n].audio.buf);
2886 ebml_free(matroska_cluster, &matroska->current_cluster);
2887 ebml_free(matroska_segment, matroska);
2888
2889 return 0;
2890 }
2891
2892 AVInputFormat ff_matroska_demuxer = {
2893 .name = "matroska,webm",
2894 .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2895 .extensions = "mkv,mk3d,mka,mks",
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,
2902 .mime_type = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
2903 };