misc Doxygen markup improvements
[libav.git] / libavformat / matroskadec.c
CommitLineData
b061d892 1/*
ff33c5c5 2 * Matroska file demuxer
2912e87a 3 * Copyright (c) 2003-2008 The Libav Project
b061d892 4 *
2912e87a 5 * This file is part of Libav.
b061d892 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
b061d892
DC
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
b061d892
DC
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
2912e87a 18 * License along with Libav; if not, write to the Free Software
b061d892
DC
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
ba87f080 23 * @file
b061d892 24 * Matroska file demuxer
e873c03a
DB
25 * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28 * @see specs available on the Matroska project page: http://www.matroska.org/
b061d892
DC
29 */
30
3eb9bfbb 31#include <stdio.h>
b061d892 32#include "avformat.h"
9a2cb05f 33#include "internal.h"
e731b8d8 34#include "avio_internal.h"
1a40491e 35/* For ff_codec_get_id(). */
b061d892 36#include "riff.h"
f009e36f 37#include "isom.h"
6b10228a 38#include "rm.h"
b061d892 39#include "matroska.h"
7bfacd4e 40#include "libavcodec/mpeg4audio.h"
245976da 41#include "libavutil/intfloat_readwrite.h"
6a5d31ac 42#include "libavutil/intreadwrite.h"
5f8e0227 43#include "libavutil/avstring.h"
de3230fb 44#include "libavutil/lzo.h"
d2d67e42 45#include "libavutil/dict.h"
b250f9c6 46#if CONFIG_ZLIB
fbb878ce
AJ
47#include <zlib.h>
48#endif
b250f9c6 49#if CONFIG_BZLIB
54dddf09
AJ
50#include <bzlib.h>
51#endif
b061d892 52
789ed100
AJ
53typedef enum {
54 EBML_NONE,
55 EBML_UINT,
56 EBML_FLOAT,
57 EBML_STR,
58 EBML_UTF8,
59 EBML_BIN,
60 EBML_NEST,
61 EBML_PASS,
62 EBML_STOP,
95ec3d4c 63 EBML_TYPE_COUNT
789ed100
AJ
64} EbmlType;
65
66typedef const struct EbmlSyntax {
67 uint32_t id;
68 EbmlType type;
69 int list_elem_size;
70 int data_offset;
71 union {
72 uint64_t u;
73 double f;
74 const char *s;
75 const struct EbmlSyntax *n;
76 } def;
77} EbmlSyntax;
78
79typedef struct {
80 int nb_elem;
81 void *elem;
82} EbmlList;
83
84typedef struct {
85 int size;
86 uint8_t *data;
87 int64_t pos;
88} EbmlBin;
89
63511324
AJ
90typedef struct {
91 uint64_t version;
92 uint64_t max_size;
93 uint64_t id_length;
94 char *doctype;
95 uint64_t doctype_version;
96} Ebml;
97
2cbc8811
AJ
98typedef struct {
99 uint64_t algo;
100 EbmlBin settings;
101} MatroskaTrackCompression;
b061d892 102
2cbc8811
AJ
103typedef struct {
104 uint64_t scope;
105 uint64_t type;
106 MatroskaTrackCompression compression;
107} MatroskaTrackEncoding;
b061d892 108
2cbc8811
AJ
109typedef struct {
110 double frame_rate;
111 uint64_t display_width;
112 uint64_t display_height;
113 uint64_t pixel_width;
114 uint64_t pixel_height;
115 uint64_t fourcc;
116} MatroskaTrackVideo;
b061d892 117
2cbc8811
AJ
118typedef struct {
119 double samplerate;
120 double out_samplerate;
121 uint64_t bitdepth;
122 uint64_t channels;
123
124 /* real audio header (extracted from extradata) */
125 int coded_framesize;
126 int sub_packet_h;
127 int frame_size;
128 int sub_packet_size;
129 int sub_packet_cnt;
130 int pkt_cnt;
46544204 131 uint64_t buf_timecode;
2cbc8811
AJ
132 uint8_t *buf;
133} MatroskaTrackAudio;
b061d892 134
2cbc8811
AJ
135typedef struct {
136 uint64_t num;
325ace3e 137 uint64_t uid;
2cbc8811 138 uint64_t type;
38766e08 139 char *name;
2cbc8811
AJ
140 char *codec_id;
141 EbmlBin codec_priv;
142 char *language;
7ff97085 143 double time_scale;
b061d892 144 uint64_t default_duration;
4eff9743 145 uint64_t flag_default;
7a617a86 146 uint64_t flag_forced;
2cbc8811
AJ
147 MatroskaTrackVideo video;
148 MatroskaTrackAudio audio;
149 EbmlList encodings;
fc4d335f
AJ
150
151 AVStream *stream;
82360e67 152 int64_t end_timecode;
3e93c8ed 153 int ms_compat;
b061d892
DC
154} MatroskaTrack;
155
e5929fdf 156typedef struct {
325ace3e 157 uint64_t uid;
b414cb89
AJ
158 char *filename;
159 char *mime;
160 EbmlBin bin;
929e9de7
AJ
161
162 AVStream *stream;
b414cb89
AJ
163} MatroskaAttachement;
164
165typedef struct {
6bbd7c7b
AJ
166 uint64_t start;
167 uint64_t end;
168 uint64_t uid;
169 char *title;
6cb6e159
AJ
170
171 AVChapter *chapter;
6bbd7c7b
AJ
172} MatroskaChapter;
173
174typedef struct {
e5929fdf
AJ
175 uint64_t track;
176 uint64_t pos;
177} MatroskaIndexPos;
178
179typedef struct {
180 uint64_t time;
181 EbmlList pos;
182} MatroskaIndex;
183
13b350a3 184typedef struct {
44015c56
AJ
185 char *name;
186 char *string;
f702df39
AJ
187 char *lang;
188 uint64_t def;
44015c56
AJ
189 EbmlList sub;
190} MatroskaTag;
191
192typedef struct {
929e9de7
AJ
193 char *type;
194 uint64_t typevalue;
195 uint64_t trackuid;
196 uint64_t chapteruid;
197 uint64_t attachuid;
198} MatroskaTagTarget;
199
200typedef struct {
201 MatroskaTagTarget target;
202 EbmlList tag;
203} MatroskaTags;
204
205typedef struct {
13b350a3
AJ
206 uint64_t id;
207 uint64_t pos;
208} MatroskaSeekhead;
209
c171af9b 210typedef struct {
8d75b5a2
AJ
211 uint64_t start;
212 uint64_t length;
b061d892
DC
213} MatroskaLevel;
214
c171af9b 215typedef struct {
b061d892
DC
216 AVFormatContext *ctx;
217
5968d2dd 218 /* EBML stuff */
b061d892
DC
219 int num_levels;
220 MatroskaLevel levels[EBML_MAX_DEPTH];
221 int level_up;
c3ade62c 222 uint32_t current_id;
b061d892 223
29708581
AJ
224 uint64_t time_scale;
225 double duration;
226 char *title;
2cbc8811 227 EbmlList tracks;
b414cb89 228 EbmlList attachments;
6bbd7c7b 229 EbmlList chapters;
e5929fdf 230 EbmlList index;
44015c56 231 EbmlList tags;
13b350a3 232 EbmlList seekhead;
b061d892 233
b061d892 234 /* byte position of the segment inside the stream */
bc5c918e 235 int64_t segment_start;
b061d892 236
5968d2dd 237 /* the packet queue */
b061d892
DC
238 AVPacket **packets;
239 int num_packets;
d5e34dcb 240 AVPacket *prev_pkt;
b061d892 241
8d75b5a2 242 int done;
b061d892 243
b061d892
DC
244 /* What to skip before effectively reading a packet. */
245 int skip_to_keyframe;
20f74665 246 uint64_t skip_to_timecode;
31ad14c2
AC
247
248 /* File has a CUES element, but we defer parsing until it is needed. */
249 int cues_parsing_deferred;
b061d892
DC
250} MatroskaDemuxContext;
251
209472b4
AJ
252typedef struct {
253 uint64_t duration;
254 int64_t reference;
194d4b49 255 uint64_t non_simple;
209472b4
AJ
256 EbmlBin bin;
257} MatroskaBlock;
258
259typedef struct {
260 uint64_t timecode;
261 EbmlList blocks;
262} MatroskaCluster;
263
63511324
AJ
264static EbmlSyntax ebml_header[] = {
265 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
266 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
267 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
268 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
269 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
270 { EBML_ID_EBMLVERSION, EBML_NONE },
271 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
63511324
AJ
272 { 0 }
273};
274
275static EbmlSyntax ebml_syntax[] = {
276 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
277 { 0 }
278};
279
29708581
AJ
280static EbmlSyntax matroska_info[] = {
281 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
282 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
283 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
284 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
285 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
286 { MATROSKA_ID_DATEUTC, EBML_NONE },
287 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
29708581
AJ
288 { 0 }
289};
290
2cbc8811
AJ
291static EbmlSyntax matroska_track_video[] = {
292 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
293 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
294 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
295 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
296 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
297 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
5df3cc6f
AJ
298 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
299 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
300 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
301 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
302 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
2cbc8811
AJ
303 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
304 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
305 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
2cbc8811
AJ
306 { 0 }
307};
308
309static EbmlSyntax matroska_track_audio[] = {
310 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
311 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
312 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
313 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
2cbc8811
AJ
314 { 0 }
315};
316
317static EbmlSyntax matroska_track_encoding_compression[] = {
318 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
319 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
2cbc8811
AJ
320 { 0 }
321};
322
323static EbmlSyntax matroska_track_encoding[] = {
324 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
325 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
326 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
5df3cc6f 327 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
2cbc8811
AJ
328 { 0 }
329};
330
331static EbmlSyntax matroska_track_encodings[] = {
332 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
2cbc8811
AJ
333 { 0 }
334};
335
336static EbmlSyntax matroska_track[] = {
337 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
38766e08 338 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
325ace3e 339 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
2cbc8811
AJ
340 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
341 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
342 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
343 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
344 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
345 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
346 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
7a617a86 347 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
2cbc8811
AJ
348 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
349 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
350 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
2cbc8811 351 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
2cbc8811
AJ
352 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
353 { MATROSKA_ID_CODECNAME, EBML_NONE },
354 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
355 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
356 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
357 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
358 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
5df3cc6f 359 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
2cbc8811
AJ
360 { 0 }
361};
362
363static EbmlSyntax matroska_tracks[] = {
364 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
2cbc8811
AJ
365 { 0 }
366};
367
b414cb89 368static EbmlSyntax matroska_attachment[] = {
325ace3e 369 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
b414cb89
AJ
370 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
371 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
372 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
5df3cc6f 373 { MATROSKA_ID_FILEDESC, EBML_NONE },
b414cb89
AJ
374 { 0 }
375};
376
377static EbmlSyntax matroska_attachments[] = {
378 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
b414cb89
AJ
379 { 0 }
380};
381
6bbd7c7b
AJ
382static EbmlSyntax matroska_chapter_display[] = {
383 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
5df3cc6f 384 { MATROSKA_ID_CHAPLANG, EBML_NONE },
6bbd7c7b
AJ
385 { 0 }
386};
387
388static EbmlSyntax matroska_chapter_entry[] = {
389 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
390 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
391 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
392 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
393 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
5df3cc6f
AJ
394 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
395 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
396 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
6bbd7c7b
AJ
397 { 0 }
398};
399
400static EbmlSyntax matroska_chapter[] = {
401 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
402 { MATROSKA_ID_EDITIONUID, EBML_NONE },
403 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
404 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
5df3cc6f 405 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
6bbd7c7b
AJ
406 { 0 }
407};
408
409static EbmlSyntax matroska_chapters[] = {
410 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
6bbd7c7b
AJ
411 { 0 }
412};
413
e5929fdf
AJ
414static EbmlSyntax matroska_index_pos[] = {
415 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
416 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
5df3cc6f 417 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
e5929fdf
AJ
418 { 0 }
419};
420
421static EbmlSyntax matroska_index_entry[] = {
422 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
423 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
e5929fdf
AJ
424 { 0 }
425};
426
427static EbmlSyntax matroska_index[] = {
428 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
e5929fdf
AJ
429 { 0 }
430};
431
44015c56
AJ
432static EbmlSyntax matroska_simpletag[] = {
433 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
434 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
f702df39
AJ
435 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
436 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
c31f00ed 437 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
44015c56 438 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
44015c56
AJ
439 { 0 }
440};
441
929e9de7
AJ
442static EbmlSyntax matroska_tagtargets[] = {
443 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
444 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
445 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
446 { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
447 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
448 { 0 }
449};
450
44015c56 451static EbmlSyntax matroska_tag[] = {
929e9de7
AJ
452 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
453 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
44015c56
AJ
454 { 0 }
455};
456
434d496a 457static EbmlSyntax matroska_tags[] = {
929e9de7 458 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
434d496a
AJ
459 { 0 }
460};
461
13b350a3
AJ
462static EbmlSyntax matroska_seekhead_entry[] = {
463 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
464 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
13b350a3
AJ
465 { 0 }
466};
467
468static EbmlSyntax matroska_seekhead[] = {
469 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
13b350a3
AJ
470 { 0 }
471};
472
ce6f28bd
AJ
473static EbmlSyntax matroska_segment[] = {
474 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
475 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
476 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
477 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
478 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
479 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
480 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
80702035 481 { MATROSKA_ID_CLUSTER, EBML_STOP },
ce6f28bd
AJ
482 { 0 }
483};
484
485static EbmlSyntax matroska_segments[] = {
486 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
487 { 0 }
488};
489
209472b4
AJ
490static EbmlSyntax matroska_blockgroup[] = {
491 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
492 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
493 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
494 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
194d4b49 495 { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
209472b4
AJ
496 { 0 }
497};
498
499static EbmlSyntax matroska_cluster[] = {
500 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
501 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
502 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
5df3cc6f
AJ
503 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
504 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
209472b4
AJ
505 { 0 }
506};
507
508static EbmlSyntax matroska_clusters[] = {
509 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
5df3cc6f
AJ
510 { MATROSKA_ID_INFO, EBML_NONE },
511 { MATROSKA_ID_CUES, EBML_NONE },
512 { MATROSKA_ID_TAGS, EBML_NONE },
513 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
209472b4
AJ
514 { 0 }
515};
516
470491fa
JZ
517static const char *matroska_doctypes[] = { "matroska", "webm" };
518
b061d892 519/*
5968d2dd 520 * Return: Whether we reached the end of a level in the hierarchy or not.
b061d892 521 */
592110c2 522static int ebml_level_end(MatroskaDemuxContext *matroska)
b061d892 523{
ae628ec1 524 AVIOContext *pb = matroska->ctx->pb;
a2704c97 525 int64_t pos = avio_tell(pb);
b061d892 526
592110c2 527 if (matroska->num_levels > 0) {
b061d892 528 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
8dbe48fc 529 if (pos - level->start >= level->length || matroska->current_id) {
b061d892 530 matroska->num_levels--;
592110c2 531 return 1;
b061d892
DC
532 }
533 }
592110c2 534 return 0;
b061d892
DC
535}
536
537/*
538 * Read: an "EBML number", which is defined as a variable-length
539 * array of bytes. The first byte indicates the length by giving a
540 * number of 0-bits followed by a one. The position of the first
541 * "one" bit inside the first byte indicates the length of this
542 * number.
5968d2dd 543 * Returns: number of bytes read, < 0 on error
b061d892 544 */
ae628ec1 545static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
f7b9687c 546 int max_size, uint64_t *number)
b061d892 547{
ff6a5fc1
RD
548 int read = 1, n = 1;
549 uint64_t total = 0;
b061d892 550
b7effd4e 551 /* The first byte tells us the length in bytes - avio_r8() can normally
b061d892
DC
552 * return 0, but since that's not a valid first ebmlID byte, we can
553 * use it safely here to catch EOS. */
b7effd4e 554 if (!(total = avio_r8(pb))) {
b061d892 555 /* we might encounter EOS here */
66e5b1df 556 if (!pb->eof_reached) {
a2704c97 557 int64_t pos = avio_tell(pb);
b061d892
DC
558 av_log(matroska->ctx, AV_LOG_ERROR,
559 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
560 pos, pos);
561 }
6f3e0b21 562 return AVERROR(EIO); /* EOS or actual I/O error */
b061d892
DC
563 }
564
565 /* get the length of the EBML number */
ff6a5fc1 566 read = 8 - ff_log2_tab[total];
b061d892 567 if (read > max_size) {
a2704c97 568 int64_t pos = avio_tell(pb) - 1;
b061d892
DC
569 av_log(matroska->ctx, AV_LOG_ERROR,
570 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
571 (uint8_t) total, pos, pos);
572 return AVERROR_INVALIDDATA;
573 }
574
575 /* read out length */
ff6a5fc1 576 total ^= 1 << ff_log2_tab[total];
b061d892 577 while (n++ < read)
b7effd4e 578 total = (total << 8) | avio_r8(pb);
b061d892
DC
579
580 *number = total;
581
582 return read;
583}
584
1b4d327b
RD
585/**
586 * Read a EBML length value.
587 * This needs special handling for the "unknown length" case which has multiple
588 * encodings.
589 */
ae628ec1 590static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
1b4d327b
RD
591 uint64_t *number)
592{
593 int res = ebml_read_num(matroska, pb, 8, number);
594 if (res > 0 && *number + 1 == 1ULL << (7 * res))
595 *number = 0xffffffffffffffULL;
596 return res;
597}
598
b061d892 599/*
b061d892
DC
600 * Read the next element as an unsigned int.
601 * 0 is success, < 0 is failure.
602 */
ae628ec1 603static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
b061d892 604{
c6cd2b3d 605 int n = 0;
b061d892 606
4a194c8f 607 if (size > 8)
b061d892 608 return AVERROR_INVALIDDATA;
b061d892 609
5968d2dd 610 /* big-endian ordering; build up number */
b061d892
DC
611 *num = 0;
612 while (n++ < size)
b7effd4e 613 *num = (*num << 8) | avio_r8(pb);
b061d892
DC
614
615 return 0;
616}
617
618/*
b061d892
DC
619 * Read the next element as a float.
620 * 0 is success, < 0 is failure.
621 */
ae628ec1 622static int ebml_read_float(AVIOContext *pb, int size, double *num)
b061d892 623{
4a194c8f
AJ
624 if (size == 0) {
625 *num = 0;
626 } else if (size == 4) {
b7effd4e 627 *num= av_int2flt(avio_rb32(pb));
b061d892 628 } else if(size==8){
b7effd4e 629 *num= av_int2dbl(avio_rb64(pb));
ba5a1f99 630 } else
b061d892 631 return AVERROR_INVALIDDATA;
b061d892
DC
632
633 return 0;
634}
635
636/*
637 * Read the next element as an ASCII string.
638 * 0 is success, < 0 is failure.
639 */
ae628ec1 640static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
b061d892 641{
c6cd2b3d 642 av_free(*str);
5968d2dd 643 /* EBML strings are usually not 0-terminated, so we allocate one
b061d892 644 * byte more, read the string and NULL-terminate it ourselves. */
c6cd2b3d 645 if (!(*str = av_malloc(size + 1)))
769e10f0 646 return AVERROR(ENOMEM);
b7effd4e 647 if (avio_read(pb, (uint8_t *) *str, size) != size) {
1c664b23 648 av_freep(str);
6f3e0b21 649 return AVERROR(EIO);
b061d892
DC
650 }
651 (*str)[size] = '\0';
652
653 return 0;
654}
655
656/*
737c40da
AJ
657 * Read the next element as binary data.
658 * 0 is success, < 0 is failure.
659 */
ae628ec1 660static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
737c40da
AJ
661{
662 av_free(bin->data);
663 if (!(bin->data = av_malloc(length)))
664 return AVERROR(ENOMEM);
665
666 bin->size = length;
a2704c97 667 bin->pos = avio_tell(pb);
b7effd4e 668 if (avio_read(pb, bin->data, length) != length) {
5549aa6d 669 av_freep(&bin->data);
737c40da 670 return AVERROR(EIO);
5549aa6d 671 }
737c40da
AJ
672
673 return 0;
674}
675
676/*
b061d892
DC
677 * Read the next element, but only the header. The contents
678 * are supposed to be sub-elements which can be read separately.
679 * 0 is success, < 0 is failure.
680 */
bddd1d93 681static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
b061d892 682{
ae628ec1 683 AVIOContext *pb = matroska->ctx->pb;
b061d892 684 MatroskaLevel *level;
b061d892 685
b061d892
DC
686 if (matroska->num_levels >= EBML_MAX_DEPTH) {
687 av_log(matroska->ctx, AV_LOG_ERROR,
688 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
85565db0 689 return AVERROR(ENOSYS);
b061d892
DC
690 }
691
b061d892 692 level = &matroska->levels[matroska->num_levels++];
a2704c97 693 level->start = avio_tell(pb);
b061d892
DC
694 level->length = length;
695
696 return 0;
697}
698
699/*
b061d892 700 * Read signed/unsigned "EBML" numbers.
5968d2dd 701 * Return: number of bytes processed, < 0 on error
b061d892 702 */
c1e01133
AJ
703static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
704 uint8_t *data, uint32_t size, uint64_t *num)
b061d892 705{
ae628ec1 706 AVIOContext pb;
e731b8d8 707 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
465c28b6 708 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
b061d892
DC
709}
710
711/*
712 * Same as above, but signed.
713 */
c1e01133
AJ
714static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
715 uint8_t *data, uint32_t size, int64_t *num)
b061d892
DC
716{
717 uint64_t unum;
718 int res;
719
720 /* read as unsigned number first */
c1e01133 721 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
b061d892
DC
722 return res;
723
724 /* make signed (weird way) */
33ac07ea 725 *num = unum - ((1LL << (7*res - 1)) - 1);
b061d892
DC
726
727 return res;
728}
729
737c40da
AJ
730static int ebml_parse_elem(MatroskaDemuxContext *matroska,
731 EbmlSyntax *syntax, void *data);
b061d892 732
737c40da
AJ
733static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
734 uint32_t id, void *data)
b061d892
DC
735{
736 int i;
737c40da
AJ
737 for (i=0; syntax[i].id; i++)
738 if (id == syntax[i].id)
739 break;
8dbe48fc
AJ
740 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
741 matroska->num_levels > 0 &&
bddd1d93 742 matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
8dbe48fc 743 return 0; // we reached the end of an unknown size cluster
b49d17b7 744 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
737c40da
AJ
745 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
746 return ebml_parse_elem(matroska, &syntax[i], data);
b061d892
DC
747}
748
737c40da
AJ
749static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
750 void *data)
b061d892 751{
c3ade62c 752 if (!matroska->current_id) {
73917810
AJ
753 uint64_t id;
754 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
755 if (res < 0)
756 return res;
757 matroska->current_id = id | 1 << 7*res;
c3ade62c
AJ
758 }
759 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
b061d892
DC
760}
761
737c40da
AJ
762static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
763 void *data)
b061d892 764{
737c40da 765 int i, res = 0;
b061d892 766
737c40da
AJ
767 for (i=0; syntax[i].id; i++)
768 switch (syntax[i].type) {
769 case EBML_UINT:
770 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
771 break;
772 case EBML_FLOAT:
773 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
774 break;
775 case EBML_STR:
776 case EBML_UTF8:
777 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
778 break;
34c9c1ba 779 }
b061d892 780
737c40da
AJ
781 while (!res && !ebml_level_end(matroska))
782 res = ebml_parse(matroska, syntax, data);
b061d892 783
737c40da 784 return res;
b061d892
DC
785}
786
789ed100
AJ
787static int ebml_parse_elem(MatroskaDemuxContext *matroska,
788 EbmlSyntax *syntax, void *data)
789{
95ec3d4c
RD
790 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
791 [EBML_UINT] = 8,
792 [EBML_FLOAT] = 8,
793 // max. 16 MB for strings
794 [EBML_STR] = 0x1000000,
795 [EBML_UTF8] = 0x1000000,
796 // max. 256 MB for binary data
797 [EBML_BIN] = 0x10000000,
798 // no limits for anything else
799 };
ae628ec1 800 AVIOContext *pb = matroska->ctx->pb;
789ed100 801 uint32_t id = syntax->id;
c6cd2b3d 802 uint64_t length;
789ed100 803 int res;
77d2ef13 804 void *newelem;
789ed100
AJ
805
806 data = (char *)data + syntax->data_offset;
807 if (syntax->list_elem_size) {
808 EbmlList *list = data;
77d2ef13
MN
809 newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
810 if (!newelem)
811 return AVERROR(ENOMEM);
812 list->elem = newelem;
789ed100
AJ
813 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
814 memset(data, 0, syntax->list_elem_size);
815 list->nb_elem++;
816 }
789ed100 817
c3ade62c
AJ
818 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
819 matroska->current_id = 0;
1b4d327b 820 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
c6cd2b3d 821 return res;
95ec3d4c
RD
822 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
823 av_log(matroska->ctx, AV_LOG_ERROR,
824 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
825 length, max_lengths[syntax->type], syntax->type);
826 return AVERROR_INVALIDDATA;
827 }
c3ade62c 828 }
c6cd2b3d 829
789ed100 830 switch (syntax->type) {
c6cd2b3d
AJ
831 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
832 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
789ed100 833 case EBML_STR:
c6cd2b3d 834 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
eb05cacc 835 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
c6cd2b3d 836 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
789ed100
AJ
837 return res;
838 if (id == MATROSKA_ID_SEGMENT)
a2704c97 839 matroska->segment_start = avio_tell(matroska->ctx->pb);
6314cca0 840 return ebml_parse_nest(matroska, syntax->def.n, data);
c4d3d9ba 841 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
80702035 842 case EBML_STOP: return 1;
45a8a02a 843 default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
789ed100 844 }
ba5a1f99
AJ
845 if (res == AVERROR_INVALIDDATA)
846 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
847 else if (res == AVERROR(EIO))
848 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
849 return res;
789ed100
AJ
850}
851
789ed100
AJ
852static void ebml_free(EbmlSyntax *syntax, void *data)
853{
854 int i, j;
855 for (i=0; syntax[i].id; i++) {
856 void *data_off = (char *)data + syntax[i].data_offset;
857 switch (syntax[i].type) {
858 case EBML_STR:
859 case EBML_UTF8: av_freep(data_off); break;
860 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
861 case EBML_NEST:
862 if (syntax[i].list_elem_size) {
863 EbmlList *list = data_off;
864 char *ptr = list->elem;
865 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
866 ebml_free(syntax[i].def.n, ptr);
867 av_free(list->elem);
868 } else
869 ebml_free(syntax[i].def.n, data_off);
870 default: break;
871 }
872 }
873}
874
737c40da
AJ
875
876/*
877 * Autodetecting...
878 */
879static int matroska_probe(AVProbeData *p)
880{
881 uint64_t total = 0;
470491fa 882 int len_mask = 0x80, size = 1, n = 1, i;
737c40da 883
5968d2dd 884 /* EBML header? */
737c40da
AJ
885 if (AV_RB32(p->buf) != EBML_ID_HEADER)
886 return 0;
887
888 /* length of header */
889 total = p->buf[4];
890 while (size <= 8 && !(total & len_mask)) {
891 size++;
892 len_mask >>= 1;
893 }
894 if (size > 8)
895 return 0;
896 total &= (len_mask - 1);
897 while (n < size)
898 total = (total << 8) | p->buf[4 + n++];
899
5968d2dd 900 /* Does the probe data contain the whole header? */
737c40da
AJ
901 if (p->buf_size < 4 + size + total)
902 return 0;
903
470491fa 904 /* The header should contain a known document type. For now,
737c40da
AJ
905 * we don't parse the whole header but simply check for the
906 * availability of that array of characters inside the header.
907 * Not fully fool-proof, but good enough. */
470491fa
JZ
908 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
909 int probelen = strlen(matroska_doctypes[i]);
69619a13
CE
910 if (total < probelen)
911 continue;
470491fa
JZ
912 for (n = 4+size; n <= 4+size+total-probelen; n++)
913 if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
914 return AVPROBE_SCORE_MAX;
915 }
737c40da 916
c7b913c8
DC
917 // probably valid EBML header but no recognized doctype
918 return AVPROBE_SCORE_MAX/2;
737c40da
AJ
919}
920
921static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
922 int num)
923{
924 MatroskaTrack *tracks = matroska->tracks.elem;
925 int i;
926
927 for (i=0; i < matroska->tracks.nb_elem; i++)
928 if (tracks[i].num == num)
929 return &tracks[i];
930
931 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
932 return NULL;
933}
934
f7b9687c
AJ
935static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
936 MatroskaTrack *track)
935ec5a1 937{
2cbc8811 938 MatroskaTrackEncoding *encodings = track->encodings.elem;
935ec5a1
ES
939 uint8_t* data = *buf;
940 int isize = *buf_size;
941 uint8_t* pkt_data = NULL;
77d2ef13 942 uint8_t* newpktdata;
935ec5a1
ES
943 int pkt_size = isize;
944 int result = 0;
945 int olen;
946
4f90688b
AJ
947 if (pkt_size >= 10000000)
948 return -1;
949
2cbc8811 950 switch (encodings[0].compression.algo) {
935ec5a1 951 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
2cbc8811 952 return encodings[0].compression.settings.size;
935ec5a1
ES
953 case MATROSKA_TRACK_ENCODING_COMP_LZO:
954 do {
955 olen = pkt_size *= 3;
69b6d53b 956 pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
0b178e56
RD
957 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
958 } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
935ec5a1
ES
959 if (result)
960 goto failed;
961 pkt_size -= olen;
962 break;
b250f9c6 963#if CONFIG_ZLIB
935ec5a1
ES
964 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
965 z_stream zstream = {0};
966 if (inflateInit(&zstream) != Z_OK)
967 return -1;
968 zstream.next_in = data;
969 zstream.avail_in = isize;
970 do {
971 pkt_size *= 3;
77d2ef13
MN
972 newpktdata = av_realloc(pkt_data, pkt_size);
973 if (!newpktdata) {
974 inflateEnd(&zstream);
975 goto failed;
976 }
977 pkt_data = newpktdata;
935ec5a1
ES
978 zstream.avail_out = pkt_size - zstream.total_out;
979 zstream.next_out = pkt_data + zstream.total_out;
980 result = inflate(&zstream, Z_NO_FLUSH);
981 } while (result==Z_OK && pkt_size<10000000);
982 pkt_size = zstream.total_out;
983 inflateEnd(&zstream);
984 if (result != Z_STREAM_END)
985 goto failed;
986 break;
987 }
988#endif
b250f9c6 989#if CONFIG_BZLIB
935ec5a1
ES
990 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
991 bz_stream bzstream = {0};
992 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
993 return -1;
994 bzstream.next_in = data;
995 bzstream.avail_in = isize;
996 do {
997 pkt_size *= 3;
77d2ef13
MN
998 newpktdata = av_realloc(pkt_data, pkt_size);
999 if (!newpktdata) {
1000 BZ2_bzDecompressEnd(&bzstream);
1001 goto failed;
1002 }
1003 pkt_data = newpktdata;
935ec5a1
ES
1004 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1005 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1006 result = BZ2_bzDecompress(&bzstream);
1007 } while (result==BZ_OK && pkt_size<10000000);
1008 pkt_size = bzstream.total_out_lo32;
1009 BZ2_bzDecompressEnd(&bzstream);
1010 if (result != BZ_STREAM_END)
1011 goto failed;
1012 break;
1013 }
1014#endif
28f27e0c
AJ
1015 default:
1016 return -1;
935ec5a1
ES
1017 }
1018
1019 *buf = pkt_data;
1020 *buf_size = pkt_size;
1021 return 0;
1022 failed:
1023 av_free(pkt_data);
1024 return -1;
1025}
1026
3eb9bfbb 1027static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
e7d4b743 1028 AVPacket *pkt, uint64_t display_duration)
3eb9bfbb
AJ
1029{
1030 char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1031 for (; *ptr!=',' && ptr<end-1; ptr++);
1032 if (*ptr == ',')
1033 layer = ++ptr;
1034 for (; *ptr!=',' && ptr<end-1; ptr++);
1035 if (*ptr == ',') {
e7d4b743 1036 int64_t end_pts = pkt->pts + display_duration;
3eb9bfbb
AJ
1037 int sc = matroska->time_scale * pkt->pts / 10000000;
1038 int ec = matroska->time_scale * end_pts / 10000000;
1039 int sh, sm, ss, eh, em, es, len;
1040 sh = sc/360000; sc -= 360000*sh;
1041 sm = sc/ 6000; sc -= 6000*sm;
1042 ss = sc/ 100; sc -= 100*ss;
1043 eh = ec/360000; ec -= 360000*eh;
1044 em = ec/ 6000; ec -= 6000*em;
1045 es = ec/ 100; ec -= 100*es;
1046 *ptr++ = '\0';
1047 len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1048 if (!(line = av_malloc(len)))
1049 return;
3df2be9f 1050 snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
3eb9bfbb
AJ
1051 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1052 av_free(pkt->data);
1053 pkt->data = line;
1054 pkt->size = strlen(line);
1055 }
1056}
1057
77d2ef13 1058static int matroska_merge_packets(AVPacket *out, AVPacket *in)
d5e34dcb 1059{
77d2ef13
MN
1060 void *newdata = av_realloc(out->data, out->size+in->size);
1061 if (!newdata)
1062 return AVERROR(ENOMEM);
1063 out->data = newdata;
d5e34dcb
AJ
1064 memcpy(out->data+out->size, in->data, in->size);
1065 out->size += in->size;
1066 av_destruct_packet(in);
1067 av_free(in);
77d2ef13 1068 return 0;
d5e34dcb
AJ
1069}
1070
929e9de7 1071static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
d2d67e42 1072 AVDictionary **metadata, char *prefix)
44015c56
AJ
1073{
1074 MatroskaTag *tags = list->elem;
929e9de7
AJ
1075 char key[1024];
1076 int i;
44015c56
AJ
1077
1078 for (i=0; i < list->nb_elem; i++) {
f702df39 1079 const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
bf800c7d
AK
1080
1081 if (!tags[i].name) {
1082 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1083 continue;
1084 }
929e9de7
AJ
1085 if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1086 else av_strlcpy(key, tags[i].name, sizeof(key));
f702df39 1087 if (tags[i].def || !lang) {
d2d67e42 1088 av_dict_set(metadata, key, tags[i].string, 0);
44015c56 1089 if (tags[i].sub.nb_elem)
929e9de7 1090 matroska_convert_tag(s, &tags[i].sub, metadata, key);
f702df39
AJ
1091 }
1092 if (lang) {
1093 av_strlcat(key, "-", sizeof(key));
1094 av_strlcat(key, lang, sizeof(key));
d2d67e42 1095 av_dict_set(metadata, key, tags[i].string, 0);
f702df39
AJ
1096 if (tags[i].sub.nb_elem)
1097 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1098 }
929e9de7 1099 }
ad7768f4 1100 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
929e9de7
AJ
1101}
1102
1103static void matroska_convert_tags(AVFormatContext *s)
1104{
1105 MatroskaDemuxContext *matroska = s->priv_data;
1106 MatroskaTags *tags = matroska->tags.elem;
1107 int i, j;
1108
1109 for (i=0; i < matroska->tags.nb_elem; i++) {
1110 if (tags[i].target.attachuid) {
1111 MatroskaAttachement *attachment = matroska->attachments.elem;
1112 for (j=0; j<matroska->attachments.nb_elem; j++)
9c569ef7
AJ
1113 if (attachment[j].uid == tags[i].target.attachuid
1114 && attachment[j].stream)
929e9de7
AJ
1115 matroska_convert_tag(s, &tags[i].tag,
1116 &attachment[j].stream->metadata, NULL);
1117 } else if (tags[i].target.chapteruid) {
1118 MatroskaChapter *chapter = matroska->chapters.elem;
1119 for (j=0; j<matroska->chapters.nb_elem; j++)
9c569ef7
AJ
1120 if (chapter[j].uid == tags[i].target.chapteruid
1121 && chapter[j].chapter)
929e9de7
AJ
1122 matroska_convert_tag(s, &tags[i].tag,
1123 &chapter[j].chapter->metadata, NULL);
1124 } else if (tags[i].target.trackuid) {
1125 MatroskaTrack *track = matroska->tracks.elem;
1126 for (j=0; j<matroska->tracks.nb_elem; j++)
9c569ef7 1127 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
929e9de7
AJ
1128 matroska_convert_tag(s, &tags[i].tag,
1129 &track[j].stream->metadata, NULL);
1130 } else {
4f909c76
AJ
1131 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1132 tags[i].target.type);
929e9de7 1133 }
44015c56
AJ
1134 }
1135}
1136
31ad14c2 1137static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
13b350a3
AJ
1138{
1139 EbmlList *seekhead_list = &matroska->seekhead;
1140 MatroskaSeekhead *seekhead = seekhead_list->elem;
13b350a3 1141 uint32_t level_up = matroska->level_up;
a2704c97 1142 int64_t before_pos = avio_tell(matroska->ctx->pb);
c3ade62c 1143 uint32_t saved_id = matroska->current_id;
13b350a3 1144 MatroskaLevel level;
31ad14c2
AC
1145 int64_t offset;
1146 int ret = 0;
66cfc385 1147
31ad14c2
AC
1148 if (idx >= seekhead_list->nb_elem
1149 || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1150 || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1151 return 0;
b061d892 1152
f47ac3c6 1153 /* seek */
31ad14c2
AC
1154 offset = seekhead[idx].pos + matroska->segment_start;
1155 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
5968d2dd 1156 /* We don't want to lose our seekhead level, so we add
4348571b
AJ
1157 * a dummy. This is a crude hack. */
1158 if (matroska->num_levels == EBML_MAX_DEPTH) {
1159 av_log(matroska->ctx, AV_LOG_INFO,
1160 "Max EBML element depth (%d) reached, "
1161 "cannot parse further.\n", EBML_MAX_DEPTH);
31ad14c2
AC
1162 ret = AVERROR_INVALIDDATA;
1163 } else {
f47ac3c6
AK
1164 level.start = 0;
1165 level.length = (uint64_t)-1;
1166 matroska->levels[matroska->num_levels] = level;
1167 matroska->num_levels++;
1168 matroska->current_id = 0;
1169
4a9628f2 1170 ret = ebml_parse(matroska, matroska_segment, matroska);
f47ac3c6
AK
1171
1172 /* remove dummy level */
1173 while (matroska->num_levels) {
1174 uint64_t length = matroska->levels[--matroska->num_levels].length;
1175 if (length == (uint64_t)-1)
1176 break;
1177 }
4348571b 1178 }
13b350a3 1179 }
4348571b 1180 /* seek back */
6b4aa5da 1181 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
4348571b 1182 matroska->level_up = level_up;
c3ade62c 1183 matroska->current_id = saved_id;
31ad14c2
AC
1184
1185 return ret;
1186}
1187
1188static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1189{
1190 EbmlList *seekhead_list = &matroska->seekhead;
1191 MatroskaSeekhead *seekhead = seekhead_list->elem;
1192 int64_t before_pos = avio_tell(matroska->ctx->pb);
1193 int i;
1194
1195 // we should not do any seeking in the streaming case
1196 if (!matroska->ctx->pb->seekable ||
1197 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1198 return;
1199
1200 for (i = 0; i < seekhead_list->nb_elem; i++) {
1201 if (seekhead[i].pos <= before_pos)
1202 continue;
1203
1204 // defer cues parsing until we actually need cue data.
1205 if (seekhead[i].id == MATROSKA_ID_CUES) {
1206 matroska->cues_parsing_deferred = 1;
1207 continue;
1208 }
1209
1210 if (matroska_parse_seekhead_entry(matroska, i) < 0)
1211 break;
1212 }
1213}
1214
1215static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1216 EbmlList *seekhead_list = &matroska->seekhead;
1217 MatroskaSeekhead *seekhead = seekhead_list->elem;
1218 EbmlList *index_list;
1219 MatroskaIndex *index;
1220 int index_scale = 1;
1221 int i, j;
1222
1223 for (i = 0; i < seekhead_list->nb_elem; i++)
fdb94444 1224 if (seekhead[i].id == MATROSKA_ID_CUES)
31ad14c2
AC
1225 break;
1226 assert(i <= seekhead_list->nb_elem);
1227
1228 matroska_parse_seekhead_entry(matroska, i);
1229
1230 index_list = &matroska->index;
1231 index = index_list->elem;
1232 if (index_list->nb_elem
1233 && index[0].time > 1E14/matroska->time_scale) {
1234 av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1235 index_scale = matroska->time_scale;
1236 }
1237 for (i = 0; i < index_list->nb_elem; i++) {
1238 EbmlList *pos_list = &index[i].pos;
1239 MatroskaIndexPos *pos = pos_list->elem;
1240 for (j = 0; j < pos_list->nb_elem; j++) {
1241 MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1242 if (track && track->stream)
1243 av_add_index_entry(track->stream,
1244 pos[j].pos + matroska->segment_start,
1245 index[i].time/index_scale, 0, 0,
1246 AVINDEX_KEYFRAME);
1247 }
1248 }
b061d892
DC
1249}
1250
f7b9687c 1251static int matroska_aac_profile(char *codec_id)
b061d892 1252{
ba18b99f 1253 static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
b061d892
DC
1254 int profile;
1255
37d3e066 1256 for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
b061d892
DC
1257 if (strstr(codec_id, aac_profiles[profile]))
1258 break;
1259 return profile + 1;
1260}
1261
f7b9687c 1262static int matroska_aac_sri(int samplerate)
b061d892 1263{
b061d892
DC
1264 int sri;
1265
59a9a235
AK
1266 for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1267 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
b061d892
DC
1268 break;
1269 return sri;
1270}
1271
f7b9687c 1272static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
b061d892
DC
1273{
1274 MatroskaDemuxContext *matroska = s->priv_data;
9c25bafa
AJ
1275 EbmlList *attachements_list = &matroska->attachments;
1276 MatroskaAttachement *attachements;
1277 EbmlList *chapters_list = &matroska->chapters;
1278 MatroskaChapter *chapters;
9a9a3b03 1279 MatroskaTrack *tracks;
e0e4be59 1280 uint64_t max_start = 0;
63511324 1281 Ebml ebml = { 0 };
9a9a3b03 1282 AVStream *st;
0ade7bb6 1283 int i, j, res;
b061d892
DC
1284
1285 matroska->ctx = s;
1286
1287 /* First read the EBML header. */
c4d3d9ba 1288 if (ebml_parse(matroska, ebml_syntax, &ebml)
63511324 1289 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
470491fa 1290 || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
b061d892 1291 av_log(matroska->ctx, AV_LOG_ERROR,
63511324
AJ
1292 "EBML header using unsupported features\n"
1293 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1294 ebml.version, ebml.doctype, ebml.doctype_version);
470491fa
JZ
1295 ebml_free(ebml_syntax, &ebml);
1296 return AVERROR_PATCHWELCOME;
1297 }
1298 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1299 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1300 break;
1301 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
c7b913c8 1302 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
b061d892 1303 }
63511324 1304 ebml_free(ebml_syntax, &ebml);
b061d892
DC
1305
1306 /* The next thing is a segment. */
0ade7bb6
AJ
1307 if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1308 return res;
13b350a3 1309 matroska_execute_seekhead(matroska);
b061d892 1310
d98bd80e
DC
1311 if (!matroska->time_scale)
1312 matroska->time_scale = 1000000;
9c25bafa
AJ
1313 if (matroska->duration)
1314 matroska->ctx->duration = matroska->duration * matroska->time_scale
1315 * 1000 / AV_TIME_BASE;
d2d67e42 1316 av_dict_set(&s->metadata, "title", matroska->title, 0);
9c25bafa 1317
d88d806b
AJ
1318 tracks = matroska->tracks.elem;
1319 for (i=0; i < matroska->tracks.nb_elem; i++) {
1320 MatroskaTrack *track = &tracks[i];
1321 enum CodecID codec_id = CODEC_ID_NONE;
9c25bafa
AJ
1322 EbmlList *encodings_list = &tracks->encodings;
1323 MatroskaTrackEncoding *encodings = encodings_list->elem;
d88d806b
AJ
1324 uint8_t *extradata = NULL;
1325 int extradata_size = 0;
1326 int extradata_offset = 0;
ae628ec1 1327 AVIOContext b;
d88d806b
AJ
1328
1329 /* Apply some sanity checks. */
9c25bafa
AJ
1330 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1331 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1332 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1333 av_log(matroska->ctx, AV_LOG_INFO,
1334 "Unknown or unsupported track type %"PRIu64"\n",
1335 track->type);
1336 continue;
1337 }
d88d806b
AJ
1338 if (track->codec_id == NULL)
1339 continue;
1340
9c25bafa
AJ
1341 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1342 if (!track->default_duration)
1343 track->default_duration = 1000000000/track->video.frame_rate;
1344 if (!track->video.display_width)
1345 track->video.display_width = track->video.pixel_width;
1346 if (!track->video.display_height)
1347 track->video.display_height = track->video.pixel_height;
1348 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1349 if (!track->audio.out_samplerate)
1350 track->audio.out_samplerate = track->audio.samplerate;
1351 }
1352 if (encodings_list->nb_elem > 1) {
1353 av_log(matroska->ctx, AV_LOG_ERROR,
d7d2f0e6 1354 "Multiple combined encodings not supported");
9c25bafa
AJ
1355 } else if (encodings_list->nb_elem == 1) {
1356 if (encodings[0].type ||
1357 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
b250f9c6 1358#if CONFIG_ZLIB
9c25bafa
AJ
1359 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1360#endif
b250f9c6 1361#if CONFIG_BZLIB
9c25bafa
AJ
1362 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1363#endif
1364 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1365 encodings[0].scope = 0;
1366 av_log(matroska->ctx, AV_LOG_ERROR,
1367 "Unsupported encoding type");
1368 } else if (track->codec_priv.size && encodings[0].scope&2) {
1369 uint8_t *codec_priv = track->codec_priv.data;
1370 int offset = matroska_decode_buffer(&track->codec_priv.data,
1371 &track->codec_priv.size,
1372 track);
1373 if (offset < 0) {
1374 track->codec_priv.data = NULL;
1375 track->codec_priv.size = 0;
1376 av_log(matroska->ctx, AV_LOG_ERROR,
1377 "Failed to decode codec private data\n");
1378 } else if (offset > 0) {
1379 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1380 memcpy(track->codec_priv.data,
1381 encodings[0].compression.settings.data, offset);
1382 memcpy(track->codec_priv.data+offset, codec_priv,
1383 track->codec_priv.size);
1384 track->codec_priv.size += offset;
1385 }
1386 if (codec_priv != track->codec_priv.data)
1387 av_free(codec_priv);
1388 }
1389 }
1390
d88d806b
AJ
1391 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1392 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1393 strlen(ff_mkv_codec_tags[j].str))){
1394 codec_id= ff_mkv_codec_tags[j].id;
1395 break;
b061d892 1396 }
d88d806b 1397 }
b061d892 1398
3b3bbdd3 1399 st = track->stream = avformat_new_stream(s, NULL);
d88d806b
AJ
1400 if (st == NULL)
1401 return AVERROR(ENOMEM);
1402
cc8be506 1403 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
28ba69e0
AJ
1404 && track->codec_priv.size >= 40
1405 && track->codec_priv.data != NULL) {
3e93c8ed 1406 track->ms_compat = 1;
d88d806b 1407 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1a40491e 1408 codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
429eeecd 1409 extradata_offset = 40;
cc8be506 1410 } else if (!strcmp(track->codec_id, "A_MS/ACM")
038146e9 1411 && track->codec_priv.size >= 14
28ba69e0 1412 && track->codec_priv.data != NULL) {
ca402f32 1413 int ret;
e731b8d8 1414 ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
59d96941 1415 AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
ca402f32
MH
1416 ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1417 if (ret < 0)
1418 return ret;
68a71451 1419 codec_id = st->codec->codec_id;
038146e9 1420 extradata_offset = FFMIN(track->codec_priv.size, 18);
28ba69e0
AJ
1421 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1422 && (track->codec_priv.size >= 86)
1423 && (track->codec_priv.data != NULL)) {
d88d806b 1424 track->video.fourcc = AV_RL32(track->codec_priv.data);
1a40491e 1425 codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
eb9cf50a
AJ
1426 } else if (codec_id == CODEC_ID_PCM_S16BE) {
1427 switch (track->audio.bitdepth) {
1428 case 8: codec_id = CODEC_ID_PCM_U8; break;
1429 case 24: codec_id = CODEC_ID_PCM_S24BE; break;
1430 case 32: codec_id = CODEC_ID_PCM_S32BE; break;
1431 }
1432 } else if (codec_id == CODEC_ID_PCM_S16LE) {
1433 switch (track->audio.bitdepth) {
1434 case 8: codec_id = CODEC_ID_PCM_U8; break;
1435 case 24: codec_id = CODEC_ID_PCM_S24LE; break;
1436 case 32: codec_id = CODEC_ID_PCM_S32LE; break;
1437 }
1438 } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1439 codec_id = CODEC_ID_PCM_F64LE;
28ba69e0 1440 } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
d88d806b
AJ
1441 int profile = matroska_aac_profile(track->codec_id);
1442 int sri = matroska_aac_sri(track->audio.samplerate);
1443 extradata = av_malloc(5);
1444 if (extradata == NULL)
1445 return AVERROR(ENOMEM);
1446 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1447 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1448 if (strstr(track->codec_id, "SBR")) {
1449 sri = matroska_aac_sri(track->audio.out_samplerate);
1450 extradata[2] = 0x56;
1451 extradata[3] = 0xE5;
1452 extradata[4] = 0x80 | (sri<<3);
1453 extradata_size = 5;
16f97ab0 1454 } else
d88d806b 1455 extradata_size = 2;
28ba69e0 1456 } else if (codec_id == CODEC_ID_TTA) {
d88d806b
AJ
1457 extradata_size = 30;
1458 extradata = av_mallocz(extradata_size);
1459 if (extradata == NULL)
1460 return AVERROR(ENOMEM);
e731b8d8 1461 ffio_init_context(&b, extradata, extradata_size, 1,
d88d806b 1462 NULL, NULL, NULL, NULL);
77eb5504
AK
1463 avio_write(&b, "TTA1", 4);
1464 avio_wl16(&b, 1);
1465 avio_wl16(&b, track->audio.channels);
1466 avio_wl16(&b, track->audio.bitdepth);
1467 avio_wl32(&b, track->audio.out_samplerate);
1468 avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
28ba69e0
AJ
1469 } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1470 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
d88d806b 1471 extradata_offset = 26;
28ba69e0 1472 } else if (codec_id == CODEC_ID_RA_144) {
d88d806b
AJ
1473 track->audio.out_samplerate = 8000;
1474 track->audio.channels = 1;
28ba69e0 1475 } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
6b10228a
AJ
1476 codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1477 int flavor;
e731b8d8 1478 ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
d88d806b 1479 0, NULL, NULL, NULL, NULL);
45a8a02a 1480 avio_skip(&b, 22);
b7effd4e
AK
1481 flavor = avio_rb16(&b);
1482 track->audio.coded_framesize = avio_rb32(&b);
45a8a02a 1483 avio_skip(&b, 12);
b7effd4e
AK
1484 track->audio.sub_packet_h = avio_rb16(&b);
1485 track->audio.frame_size = avio_rb16(&b);
1486 track->audio.sub_packet_size = avio_rb16(&b);
d88d806b
AJ
1487 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1488 if (codec_id == CODEC_ID_RA_288) {
1489 st->codec->block_align = track->audio.coded_framesize;
1490 track->codec_priv.size = 0;
1491 } else {
6b10228a
AJ
1492 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1493 const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1494 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1495 st->codec->bit_rate = sipr_bit_rate[flavor];
1496 }
d88d806b
AJ
1497 st->codec->block_align = track->audio.sub_packet_size;
1498 extradata_offset = 78;
b061d892 1499 }
d88d806b 1500 }
e2644407 1501 track->codec_priv.size -= extradata_offset;
b061d892 1502
16f97ab0 1503 if (codec_id == CODEC_ID_NONE)
d88d806b 1504 av_log(matroska->ctx, AV_LOG_INFO,
8f35a2c0 1505 "Unknown/unsupported CodecID %s.\n", track->codec_id);
eabb8ba4 1506
3fc9d7ce
AJ
1507 if (track->time_scale < 0.01)
1508 track->time_scale = 1.0;
c3f9ebf7 1509 avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
eabb8ba4 1510
d88d806b
AJ
1511 st->codec->codec_id = codec_id;
1512 st->start_time = 0;
1513 if (strcmp(track->language, "und"))
d2d67e42
AK
1514 av_dict_set(&st->metadata, "language", track->language, 0);
1515 av_dict_set(&st->metadata, "title", track->name, 0);
b061d892 1516
d88d806b
AJ
1517 if (track->flag_default)
1518 st->disposition |= AV_DISPOSITION_DEFAULT;
7a617a86
AJ
1519 if (track->flag_forced)
1520 st->disposition |= AV_DISPOSITION_FORCED;
b061d892 1521
ff0d5a74 1522 if (!st->codec->extradata) {
553e9f75
AJ
1523 if(extradata){
1524 st->codec->extradata = extradata;
1525 st->codec->extradata_size = extradata_size;
1526 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1527 st->codec->extradata = av_mallocz(track->codec_priv.size +
1528 FF_INPUT_BUFFER_PADDING_SIZE);
1529 if(st->codec->extradata == NULL)
1530 return AVERROR(ENOMEM);
1531 st->codec->extradata_size = track->codec_priv.size;
1532 memcpy(st->codec->extradata,
1533 track->codec_priv.data + extradata_offset,
1534 track->codec_priv.size);
1535 }
ff0d5a74 1536 }
d88d806b
AJ
1537
1538 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
72415b2a 1539 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
d88d806b
AJ
1540 st->codec->codec_tag = track->video.fourcc;
1541 st->codec->width = track->video.pixel_width;
1542 st->codec->height = track->video.pixel_height;
59729451
AJ
1543 av_reduce(&st->sample_aspect_ratio.num,
1544 &st->sample_aspect_ratio.den,
d88d806b
AJ
1545 st->codec->height * track->video.display_width,
1546 st->codec-> width * track->video.display_height,
1547 255);
8306be9c 1548 if (st->codec->codec_id != CODEC_ID_H264)
d88d806b 1549 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1095d442
BC
1550 if (track->default_duration)
1551 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
d88d806b 1552 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
72415b2a 1553 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
d88d806b
AJ
1554 st->codec->sample_rate = track->audio.out_samplerate;
1555 st->codec->channels = track->audio.channels;
f7501a71 1556 if (st->codec->codec_id != CODEC_ID_AAC)
dc1c26dc 1557 st->need_parsing = AVSTREAM_PARSE_HEADERS;
d88d806b 1558 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
72415b2a 1559 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
d88d806b 1560 }
b061d892
DC
1561 }
1562
9c25bafa
AJ
1563 attachements = attachements_list->elem;
1564 for (j=0; j<attachements_list->nb_elem; j++) {
1565 if (!(attachements[j].filename && attachements[j].mime &&
1566 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1567 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1568 } else {
3b3bbdd3 1569 AVStream *st = avformat_new_stream(s, NULL);
9c25bafa
AJ
1570 if (st == NULL)
1571 break;
d2d67e42 1572 av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
98cfe22b 1573 av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
9c25bafa 1574 st->codec->codec_id = CODEC_ID_NONE;
72415b2a 1575 st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
9c25bafa
AJ
1576 st->codec->extradata = av_malloc(attachements[j].bin.size);
1577 if(st->codec->extradata == NULL)
1578 break;
1579 st->codec->extradata_size = attachements[j].bin.size;
1580 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1581
1582 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1583 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1584 strlen(ff_mkv_mime_tags[i].str))) {
1585 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1586 break;
1587 }
1588 }
929e9de7 1589 attachements[j].stream = st;
9c25bafa
AJ
1590 }
1591 }
1592
1593 chapters = chapters_list->elem;
1594 for (i=0; i<chapters_list->nb_elem; i++)
e0e4be59
AJ
1595 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1596 && (max_start==0 || chapters[i].start > max_start)) {
6cb6e159 1597 chapters[i].chapter =
1fa395e4 1598 avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
9c25bafa
AJ
1599 chapters[i].start, chapters[i].end,
1600 chapters[i].title);
d2d67e42 1601 av_dict_set(&chapters[i].chapter->metadata,
2ef6c124 1602 "title", chapters[i].title, 0);
e0e4be59
AJ
1603 max_start = chapters[i].start;
1604 }
9c25bafa 1605
929e9de7
AJ
1606 matroska_convert_tags(s);
1607
ce6f28bd 1608 return 0;
b061d892
DC
1609}
1610
737c40da 1611/*
737c40da
AJ
1612 * Put one packet in an application-supplied AVPacket struct.
1613 * Returns 0 on success or -1 on failure.
1614 */
1615static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1616 AVPacket *pkt)
1617{
1618 if (matroska->num_packets > 0) {
1619 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1620 av_free(matroska->packets[0]);
1621 if (matroska->num_packets > 1) {
77d2ef13 1622 void *newpackets;
737c40da
AJ
1623 memmove(&matroska->packets[0], &matroska->packets[1],
1624 (matroska->num_packets - 1) * sizeof(AVPacket *));
77d2ef13
MN
1625 newpackets = av_realloc(matroska->packets,
1626 (matroska->num_packets - 1) * sizeof(AVPacket *));
1627 if (newpackets)
1628 matroska->packets = newpackets;
737c40da
AJ
1629 } else {
1630 av_freep(&matroska->packets);
1631 }
1632 matroska->num_packets--;
1633 return 0;
1634 }
1635
1636 return -1;
1637}
1638
1639/*
1640 * Free all packets in our internal queue.
1641 */
1642static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1643{
1644 if (matroska->packets) {
1645 int n;
1646 for (n = 0; n < matroska->num_packets; n++) {
1647 av_free_packet(matroska->packets[n]);
1648 av_free(matroska->packets[n]);
1649 }
00a3431c 1650 av_freep(&matroska->packets);
737c40da
AJ
1651 matroska->num_packets = 0;
1652 }
1653}
1654
f7b9687c
AJ
1655static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1656 int size, int64_t pos, uint64_t cluster_time,
24c3da16
AJ
1657 uint64_t duration, int is_keyframe,
1658 int64_t cluster_pos)
b061d892 1659{
f14a201b 1660 uint64_t timecode = AV_NOPTS_VALUE;
009ecd50 1661 MatroskaTrack *track;
a3467f86 1662 int res = 0;
b061d892
DC
1663 AVStream *st;
1664 AVPacket *pkt;
b061d892
DC
1665 int16_t block_time;
1666 uint32_t *lace_size = NULL;
1667 int n, flags, laces = 0;
1668 uint64_t num;
1669
c1e01133 1670 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
b061d892 1671 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
b061d892
DC
1672 return res;
1673 }
1674 data += n;
1675 size -= n;
1676
b061d892 1677 track = matroska_find_track_by_num(matroska, num);
d31fb1a9 1678 if (!track || !track->stream) {
b061d892 1679 av_log(matroska->ctx, AV_LOG_INFO,
009ecd50 1680 "Invalid stream %"PRIu64" or size %u\n", num, size);
5dd514af 1681 return AVERROR_INVALIDDATA;
d31fb1a9
RB
1682 } else if (size <= 3)
1683 return 0;
009ecd50 1684 st = track->stream;
16f97ab0 1685 if (st->discard >= AVDISCARD_ALL)
b061d892 1686 return res;
b061d892 1687 if (duration == AV_NOPTS_VALUE)
009ecd50 1688 duration = track->default_duration / matroska->time_scale;
b061d892 1689
2ce746c6 1690 block_time = AV_RB16(data);
b061d892 1691 data += 2;
1607c534
AJ
1692 flags = *data++;
1693 size -= 3;
b061d892 1694 if (is_keyframe == -1)
cc947f04 1695 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
b061d892 1696
f14a201b
AJ
1697 if (cluster_time != (uint64_t)-1
1698 && (block_time >= 0 || cluster_time >= -block_time)) {
1699 timecode = cluster_time + block_time;
82360e67
AJ
1700 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1701 && timecode < track->end_timecode)
1702 is_keyframe = 0; /* overlapping subtitles are not key frame */
a8fd7e76 1703 if (is_keyframe)
f14a201b 1704 av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
82360e67 1705 track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
f14a201b
AJ
1706 }
1707
c1658257 1708 if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
20f74665 1709 if (!is_keyframe || timecode < matroska->skip_to_timecode)
b061d892
DC
1710 return res;
1711 matroska->skip_to_keyframe = 0;
1712 }
1713
1714 switch ((flags & 0x06) >> 1) {
1715 case 0x0: /* no lacing */
1716 laces = 1;
1717 lace_size = av_mallocz(sizeof(int));
1718 lace_size[0] = size;
1719 break;
1720
5968d2dd 1721 case 0x1: /* Xiph lacing */
b061d892
DC
1722 case 0x2: /* fixed-size lacing */
1723 case 0x3: /* EBML lacing */
9bf8b562 1724 assert(size>0); // size <=3 is checked before size-=3 above
b061d892
DC
1725 laces = (*data) + 1;
1726 data += 1;
1727 size -= 1;
1728 lace_size = av_mallocz(laces * sizeof(int));
1729
1730 switch ((flags & 0x06) >> 1) {
5968d2dd 1731 case 0x1: /* Xiph lacing */ {
b061d892
DC
1732 uint8_t temp;
1733 uint32_t total = 0;
1734 for (n = 0; res == 0 && n < laces - 1; n++) {
1735 while (1) {
1736 if (size == 0) {
1737 res = -1;
1738 break;
1739 }
1740 temp = *data;
1741 lace_size[n] += temp;
1742 data += 1;
1743 size -= 1;
1744 if (temp != 0xff)
1745 break;
1746 }
1747 total += lace_size[n];
1748 }
1749 lace_size[n] = size - total;
1750 break;
1751 }
1752
1753 case 0x2: /* fixed-size lacing */
1754 for (n = 0; n < laces; n++)
1755 lace_size[n] = size / laces;
1756 break;
1757
1758 case 0x3: /* EBML lacing */ {
1759 uint32_t total;
c1e01133 1760 n = matroska_ebmlnum_uint(matroska, data, size, &num);
b061d892
DC
1761 if (n < 0) {
1762 av_log(matroska->ctx, AV_LOG_INFO,
1763 "EBML block data error\n");
1764 break;
1765 }
1766 data += n;
1767 size -= n;
1768 total = lace_size[0] = num;
1769 for (n = 1; res == 0 && n < laces - 1; n++) {
1770 int64_t snum;
1771 int r;
c1e01133 1772 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
b061d892
DC
1773 if (r < 0) {
1774 av_log(matroska->ctx, AV_LOG_INFO,
1775 "EBML block data error\n");
1776 break;
1777 }
1778 data += r;
1779 size -= r;
1780 lace_size[n] = lace_size[n - 1] + snum;
1781 total += lace_size[n];
1782 }
723229c1 1783 lace_size[laces - 1] = size - total;
b061d892
DC
1784 break;
1785 }
1786 }
1787 break;
1788 }
1789
1790 if (res == 0) {
b061d892 1791 for (n = 0; n < laces; n++) {
18ca491b
DC
1792 if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1793 st->codec->codec_id == CODEC_ID_COOK ||
6b10228a 1794 st->codec->codec_id == CODEC_ID_SIPR ||
18ca491b
DC
1795 st->codec->codec_id == CODEC_ID_ATRAC3) &&
1796 st->codec->block_align && track->audio.sub_packet_size) {
ba8a76b8 1797 int a = st->codec->block_align;
2cbc8811
AJ
1798 int sps = track->audio.sub_packet_size;
1799 int cfs = track->audio.coded_framesize;
1800 int h = track->audio.sub_packet_h;
1801 int y = track->audio.sub_packet_cnt;
1802 int w = track->audio.frame_size;
ba8a76b8
AJ
1803 int x;
1804
2cbc8811 1805 if (!track->audio.pkt_cnt) {
46544204
RD
1806 if (track->audio.sub_packet_cnt == 0)
1807 track->audio.buf_timecode = timecode;
ba8a76b8
AJ
1808 if (st->codec->codec_id == CODEC_ID_RA_288)
1809 for (x=0; x<h/2; x++)
2cbc8811 1810 memcpy(track->audio.buf+x*2*w+y*cfs,
ba8a76b8 1811 data+x*cfs, cfs);
6b10228a
AJ
1812 else if (st->codec->codec_id == CODEC_ID_SIPR)
1813 memcpy(track->audio.buf + y*w, data, w);
ba8a76b8
AJ
1814 else
1815 for (x=0; x<w/sps; x++)
2cbc8811 1816 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
ba8a76b8 1817
2cbc8811 1818 if (++track->audio.sub_packet_cnt >= h) {
6b10228a
AJ
1819 if (st->codec->codec_id == CODEC_ID_SIPR)
1820 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2cbc8811
AJ
1821 track->audio.sub_packet_cnt = 0;
1822 track->audio.pkt_cnt = h*w / a;
979c0910 1823 }
ba8a76b8 1824 }
2cbc8811 1825 while (track->audio.pkt_cnt) {
77abe5e8 1826 pkt = av_mallocz(sizeof(AVPacket));
ba8a76b8 1827 av_new_packet(pkt, a);
2cbc8811
AJ
1828 memcpy(pkt->data, track->audio.buf
1829 + a * (h*w / a - track->audio.pkt_cnt--), a);
46544204
RD
1830 pkt->pts = track->audio.buf_timecode;
1831 track->audio.buf_timecode = AV_NOPTS_VALUE;
77abe5e8 1832 pkt->pos = pos;
fc4d335f 1833 pkt->stream_index = st->index;
b8702539 1834 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
eabb8ba4 1835 }
ba8a76b8 1836 } else {
2cbc8811 1837 MatroskaTrackEncoding *encodings = track->encodings.elem;
935ec5a1 1838 int offset = 0, pkt_size = lace_size[n];
de3230fb 1839 uint8_t *pkt_data = data;
ba8a76b8 1840
e110e968 1841 if (pkt_size > size) {
e48f7ff3
DC
1842 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1843 break;
1844 }
1845
2cbc8811 1846 if (encodings && encodings->scope & 1) {
8f35a2c0 1847 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
935ec5a1
ES
1848 if (offset < 0)
1849 continue;
53a1e82b
AJ
1850 }
1851
ba8a76b8
AJ
1852 pkt = av_mallocz(sizeof(AVPacket));
1853 /* XXX: prevent data copy... */
de3230fb 1854 if (av_new_packet(pkt, pkt_size+offset) < 0) {
34ae4097 1855 av_free(pkt);
ba8a76b8 1856 res = AVERROR(ENOMEM);
ba8a76b8
AJ
1857 break;
1858 }
53a1e82b 1859 if (offset)
2cbc8811 1860 memcpy (pkt->data, encodings->compression.settings.data, offset);
de3230fb 1861 memcpy (pkt->data+offset, pkt_data, pkt_size);
ba8a76b8 1862
51e1cc16
AJ
1863 if (pkt_data != data)
1864 av_free(pkt_data);
1865
ba8a76b8
AJ
1866 if (n == 0)
1867 pkt->flags = is_keyframe;
fc4d335f 1868 pkt->stream_index = st->index;
ba8a76b8 1869
3e93c8ed
JP
1870 if (track->ms_compat)
1871 pkt->dts = timecode;
1872 else
68b0fd7c 1873 pkt->pts = timecode;
ba8a76b8 1874 pkt->pos = pos;
1bb4a1a1 1875 if (st->codec->codec_id == CODEC_ID_TEXT)
62c24705 1876 pkt->convergence_duration = duration;
1bb4a1a1 1877 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
62c24705 1878 pkt->duration = duration;
ba8a76b8 1879
3eb9bfbb 1880 if (st->codec->codec_id == CODEC_ID_SSA)
e7d4b743 1881 matroska_fix_ass_packet(matroska, pkt, duration);
3eb9bfbb 1882
d5e34dcb 1883 if (matroska->prev_pkt &&
21a115d1 1884 timecode != AV_NOPTS_VALUE &&
d5e34dcb 1885 matroska->prev_pkt->pts == timecode &&
41c1ccc3
DC
1886 matroska->prev_pkt->stream_index == st->index &&
1887 st->codec->codec_id == CODEC_ID_SSA)
d5e34dcb
AJ
1888 matroska_merge_packets(matroska->prev_pkt, pkt);
1889 else {
c58e8bd3 1890 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
d5e34dcb
AJ
1891 matroska->prev_pkt = pkt;
1892 }
ba8a76b8 1893 }
b061d892 1894
ba8a76b8
AJ
1895 if (timecode != AV_NOPTS_VALUE)
1896 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
b061d892 1897 data += lace_size[n];
e48f7ff3 1898 size -= lace_size[n];
b061d892
DC
1899 }
1900 }
1901
1902 av_free(lace_size);
a3467f86 1903 return res;
b061d892
DC
1904}
1905
f7b9687c 1906static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
b061d892 1907{
209472b4
AJ
1908 MatroskaCluster cluster = { 0 };
1909 EbmlList *blocks_list;
1910 MatroskaBlock *blocks;
24c3da16 1911 int i, res;
a2704c97 1912 int64_t pos = avio_tell(matroska->ctx->pb);
d5e34dcb 1913 matroska->prev_pkt = NULL;
80702035 1914 if (matroska->current_id)
8bc98ba9 1915 pos -= 4; /* sizeof the ID which was already read */
73917810 1916 res = ebml_parse(matroska, matroska_clusters, &cluster);
209472b4
AJ
1917 blocks_list = &cluster.blocks;
1918 blocks = blocks_list->elem;
5dd514af 1919 for (i=0; i<blocks_list->nb_elem && !res; i++)
37dd2356 1920 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
194d4b49 1921 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
98a7d560
JS
1922 if (!blocks[i].non_simple)
1923 blocks[i].duration = AV_NOPTS_VALUE;
209472b4
AJ
1924 res=matroska_parse_block(matroska,
1925 blocks[i].bin.data, blocks[i].bin.size,
1926 blocks[i].bin.pos, cluster.timecode,
194d4b49 1927 blocks[i].duration, is_keyframe,
24c3da16 1928 pos);
194d4b49 1929 }
209472b4 1930 ebml_free(matroska_cluster, &cluster);
653fb2f8 1931 if (res < 0) matroska->done = 1;
b061d892
DC
1932 return res;
1933}
1934
f7b9687c 1935static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
b061d892
DC
1936{
1937 MatroskaDemuxContext *matroska = s->priv_data;
5dd514af 1938 int ret = 0;
b061d892 1939
5dd514af 1940 while (!ret && matroska_deliver_packet(matroska, pkt)) {
b061d892 1941 if (matroska->done)
9ebeea82 1942 return AVERROR_EOF;
5dd514af 1943 ret = matroska_parse_cluster(matroska);
b061d892
DC
1944 }
1945
5dd514af 1946 return ret;
b061d892
DC
1947}
1948
f7b9687c
AJ
1949static int matroska_read_seek(AVFormatContext *s, int stream_index,
1950 int64_t timestamp, int flags)
b061d892
DC
1951{
1952 MatroskaDemuxContext *matroska = s->priv_data;
c1658257 1953 MatroskaTrack *tracks = matroska->tracks.elem;
b061d892 1954 AVStream *st = s->streams[stream_index];
c1658257 1955 int i, index, index_sub, index_min;
b061d892 1956
31ad14c2
AC
1957 /* Parse the CUES now since we need the index data to seek. */
1958 if (matroska->cues_parsing_deferred) {
1959 matroska_parse_cues(matroska);
1960 matroska->cues_parsing_deferred = 0;
1961 }
1962
a8fd7e76
AJ
1963 if (!st->nb_index_entries)
1964 return 0;
1965 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
dfbbbdc0 1966
6bef5f9b 1967 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
6b4aa5da 1968 avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
cdc2c1c5 1969 matroska->current_id = 0;
0dbddda3
AJ
1970 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1971 matroska_clear_queue(matroska);
1972 if (matroska_parse_cluster(matroska) < 0)
1973 break;
1974 }
6bef5f9b 1975 }
b061d892 1976
243cc4c3 1977 matroska_clear_queue(matroska);
0f646a22
AJ
1978 if (index < 0)
1979 return 0;
243cc4c3 1980
c1658257
AJ
1981 index_min = index;
1982 for (i=0; i < matroska->tracks.nb_elem; i++) {
46544204
RD
1983 tracks[i].audio.pkt_cnt = 0;
1984 tracks[i].audio.sub_packet_cnt = 0;
1985 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
c1658257
AJ
1986 tracks[i].end_timecode = 0;
1987 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1988 && !tracks[i].stream->discard != AVDISCARD_ALL) {
1989 index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1990 if (index_sub >= 0
1991 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1992 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1993 index_min = index_sub;
1994 }
1995 }
1996
6b4aa5da 1997 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
cdc2c1c5 1998 matroska->current_id = 0;
b061d892 1999 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
20f74665 2000 matroska->skip_to_timecode = st->index_entries[index].timestamp;
244ee48a 2001 matroska->done = 0;
a2faa951 2002 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
b061d892
DC
2003 return 0;
2004}
2005
f7b9687c 2006static int matroska_read_close(AVFormatContext *s)
b061d892
DC
2007{
2008 MatroskaDemuxContext *matroska = s->priv_data;
2cbc8811 2009 MatroskaTrack *tracks = matroska->tracks.elem;
70109c0d 2010 int n;
b061d892 2011
34c9c1ba 2012 matroska_clear_queue(matroska);
b061d892 2013
2cbc8811
AJ
2014 for (n=0; n < matroska->tracks.nb_elem; n++)
2015 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2016 av_free(tracks[n].audio.buf);
ce6f28bd 2017 ebml_free(matroska_segment, matroska);
b061d892
DC
2018
2019 return 0;
2020}
2021
c6610a21 2022AVInputFormat ff_matroska_demuxer = {
dfc2c4d9
AK
2023 .name = "matroska,webm",
2024 .long_name = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
2025 .priv_data_size = sizeof(MatroskaDemuxContext),
2026 .read_probe = matroska_probe,
2027 .read_header = matroska_read_header,
2028 .read_packet = matroska_read_packet,
2029 .read_close = matroska_read_close,
2030 .read_seek = matroska_read_seek,
b061d892 2031};