blob: 50a9784601fc2fdde82b82c8bb50e86e4f05fc32 [file] [log] [blame]
David Conradb061d892007-06-04 22:10:541/*
2 * Matroska file demuxer (no muxer yet)
3 * Copyright (c) 2003-2004 The ffmpeg Project
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
Reimar Döffinger6de4aec2007-06-20 17:37:1123 * @file matroskadec.c
David Conradb061d892007-06-04 22:10:5424 * Matroska file demuxer
25 * by Ronald Bultje <[email protected]>
26 * with a little help from Moritz Bunkus <[email protected]>
27 * Specs available on the matroska project page:
28 * http://www.matroska.org/.
29 */
30
31#include "avformat.h"
32/* For codec_get_id(). */
33#include "riff.h"
Aurelien Jacobsf009e362008-07-27 15:11:0434#include "isom.h"
David Conradb061d892007-06-04 22:10:5435#include "matroska.h"
Aurelien Jacobs7bfacd42008-04-02 21:41:4836#include "libavcodec/mpeg4audio.h"
Diego Biurrun245976d2008-05-09 11:56:3637#include "libavutil/intfloat_readwrite.h"
Aurelien Jacobs5f8e0222008-08-05 00:39:4738#include "libavutil/avstring.h"
Aurelien Jacobsde3230f2008-05-09 01:53:5939#include "libavutil/lzo.h"
Aurelien Jacobsfbb878c2008-05-13 23:32:1340#ifdef CONFIG_ZLIB
41#include <zlib.h>
42#endif
Aurelien Jacobs54dddf02008-05-15 23:12:4143#ifdef CONFIG_BZLIB
44#include <bzlib.h>
45#endif
David Conradb061d892007-06-04 22:10:5446
Aurelien Jacobs789ed102008-08-05 00:40:0047typedef enum {
48 EBML_NONE,
49 EBML_UINT,
50 EBML_FLOAT,
51 EBML_STR,
52 EBML_UTF8,
53 EBML_BIN,
54 EBML_NEST,
55 EBML_PASS,
56 EBML_STOP,
57} EbmlType;
58
59typedef const struct EbmlSyntax {
60 uint32_t id;
61 EbmlType type;
62 int list_elem_size;
63 int data_offset;
64 union {
65 uint64_t u;
66 double f;
67 const char *s;
68 const struct EbmlSyntax *n;
69 } def;
70} EbmlSyntax;
71
72typedef struct {
73 int nb_elem;
74 void *elem;
75} EbmlList;
76
77typedef struct {
78 int size;
79 uint8_t *data;
80 int64_t pos;
81} EbmlBin;
82
Aurelien Jacobs63511322008-08-05 00:40:0283typedef struct {
84 uint64_t version;
85 uint64_t max_size;
86 uint64_t id_length;
87 char *doctype;
88 uint64_t doctype_version;
89} Ebml;
90
Aurelien Jacobs2cbc8812008-08-05 00:40:3191typedef struct {
92 uint64_t algo;
93 EbmlBin settings;
94} MatroskaTrackCompression;
David Conradb061d892007-06-04 22:10:5495
Aurelien Jacobs2cbc8812008-08-05 00:40:3196typedef struct {
97 uint64_t scope;
98 uint64_t type;
99 MatroskaTrackCompression compression;
100} MatroskaTrackEncoding;
David Conradb061d892007-06-04 22:10:54101
Aurelien Jacobs2cbc8812008-08-05 00:40:31102typedef struct {
103 double frame_rate;
104 uint64_t display_width;
105 uint64_t display_height;
106 uint64_t pixel_width;
107 uint64_t pixel_height;
108 uint64_t fourcc;
109} MatroskaTrackVideo;
David Conradb061d892007-06-04 22:10:54110
Aurelien Jacobs2cbc8812008-08-05 00:40:31111typedef struct {
112 double samplerate;
113 double out_samplerate;
114 uint64_t bitdepth;
115 uint64_t channels;
David Conradb061d892007-06-04 22:10:54116
Aurelien Jacobs2cbc8812008-08-05 00:40:31117 /* real audio header (extracted from extradata) */
118 int coded_framesize;
119 int sub_packet_h;
120 int frame_size;
121 int sub_packet_size;
122 int sub_packet_cnt;
123 int pkt_cnt;
124 uint8_t *buf;
125} MatroskaTrackAudio;
David Conradb061d892007-06-04 22:10:54126
Aurelien Jacobs2cbc8812008-08-05 00:40:31127typedef struct {
128 uint64_t num;
129 uint64_t type;
130 char *codec_id;
131 EbmlBin codec_priv;
132 char *language;
Anton Khirnov7ff97082008-06-01 13:54:11133 double time_scale;
David Conradb061d892007-06-04 22:10:54134 uint64_t default_duration;
Aurelien Jacobs4eff9742008-08-05 00:39:53135 uint64_t flag_default;
Aurelien Jacobs2cbc8812008-08-05 00:40:31136 MatroskaTrackVideo video;
137 MatroskaTrackAudio audio;
138 EbmlList encodings;
Aurelien Jacobsfc4d3352008-08-05 00:40:06139
140 AVStream *stream;
David Conradb061d892007-06-04 22:10:54141} MatroskaTrack;
142
Aurelien Jacobse5929fd2008-08-05 00:40:15143typedef struct {
Aurelien Jacobsb414cb82008-08-05 00:40:24144 char *filename;
145 char *mime;
146 EbmlBin bin;
147} MatroskaAttachement;
148
149typedef struct {
Aurelien Jacobs6bbd7c72008-08-05 00:40:21150 uint64_t start;
151 uint64_t end;
152 uint64_t uid;
153 char *title;
154} MatroskaChapter;
155
156typedef struct {
Aurelien Jacobse5929fd2008-08-05 00:40:15157 uint64_t track;
158 uint64_t pos;
159} MatroskaIndexPos;
160
161typedef struct {
162 uint64_t time;
163 EbmlList pos;
164} MatroskaIndex;
165
Aurelien Jacobs13b350a2008-08-05 00:40:36166typedef struct {
167 uint64_t id;
168 uint64_t pos;
169} MatroskaSeekhead;
170
Aurelien Jacobsc171af92008-08-05 00:41:19171typedef struct {
Aurelien Jacobs8d75b5a2007-06-04 22:35:16172 uint64_t start;
173 uint64_t length;
David Conradb061d892007-06-04 22:10:54174} MatroskaLevel;
175
Aurelien Jacobsc171af92008-08-05 00:41:19176typedef struct {
David Conradb061d892007-06-04 22:10:54177 AVFormatContext *ctx;
178
179 /* ebml stuff */
180 int num_levels;
181 MatroskaLevel levels[EBML_MAX_DEPTH];
182 int level_up;
183
David Conradb061d892007-06-04 22:10:54184 /* timescale in the file */
Aurelien Jacobs29708582008-08-05 00:40:27185 uint64_t time_scale;
186 double duration;
187 char *title;
Aurelien Jacobs2cbc8812008-08-05 00:40:31188 EbmlList tracks;
Aurelien Jacobsb414cb82008-08-05 00:40:24189 EbmlList attachments;
Aurelien Jacobs6bbd7c72008-08-05 00:40:21190 EbmlList chapters;
Aurelien Jacobse5929fd2008-08-05 00:40:15191 EbmlList index;
Aurelien Jacobs13b350a2008-08-05 00:40:36192 EbmlList seekhead;
David Conradb061d892007-06-04 22:10:54193
194 /* num_streams is the number of streams that av_new_stream() was called
195 * for ( = that are available to the calling program). */
Aurelien Jacobs8d75b5a2007-06-04 22:35:16196 int num_streams;
David Conradb061d892007-06-04 22:10:54197
198 /* cache for ID peeking */
199 uint32_t peek_id;
200
201 /* byte position of the segment inside the stream */
202 offset_t segment_start;
203
204 /* The packet queue. */
205 AVPacket **packets;
206 int num_packets;
207
Aurelien Jacobs8d75b5a2007-06-04 22:35:16208 int done;
Aurelien Jacobsce6f28b2008-08-05 00:40:58209 int has_cluster_id;
David Conradb061d892007-06-04 22:10:54210
David Conradb061d892007-06-04 22:10:54211 /* What to skip before effectively reading a packet. */
212 int skip_to_keyframe;
213 AVStream *skip_to_stream;
214} MatroskaDemuxContext;
215
Aurelien Jacobs209472b2008-08-05 00:41:05216typedef struct {
217 uint64_t duration;
218 int64_t reference;
219 EbmlBin bin;
220} MatroskaBlock;
221
222typedef struct {
223 uint64_t timecode;
224 EbmlList blocks;
225} MatroskaCluster;
226
Aurelien Jacobs4b3dc522008-06-02 23:01:14227#define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
228
Aurelien Jacobs63511322008-08-05 00:40:02229static EbmlSyntax ebml_header[] = {
230 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
231 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
232 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
233 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
234 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
235 { EBML_ID_EBMLVERSION, EBML_NONE },
236 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
237 { EBML_ID_VOID, EBML_NONE },
238 { 0 }
239};
240
241static EbmlSyntax ebml_syntax[] = {
242 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
243 { 0 }
244};
245
Aurelien Jacobs29708582008-08-05 00:40:27246static EbmlSyntax matroska_info[] = {
247 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
248 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
249 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
250 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
251 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
252 { MATROSKA_ID_DATEUTC, EBML_NONE },
253 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
254 { EBML_ID_VOID, EBML_NONE },
255 { 0 }
256};
257
Aurelien Jacobs2cbc8812008-08-05 00:40:31258static EbmlSyntax matroska_track_video[] = {
259 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
260 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
261 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
262 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
263 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
264 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
265 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
266 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
267 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
268 { EBML_ID_VOID, EBML_NONE },
269 { 0 }
270};
271
272static EbmlSyntax matroska_track_audio[] = {
273 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
274 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
275 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
276 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
277 { EBML_ID_VOID, EBML_NONE },
278 { 0 }
279};
280
281static EbmlSyntax matroska_track_encoding_compression[] = {
282 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
283 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
284 { EBML_ID_VOID, EBML_NONE },
285 { 0 }
286};
287
288static EbmlSyntax matroska_track_encoding[] = {
289 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
290 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
291 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
292 { EBML_ID_VOID, EBML_NONE },
293 { 0 }
294};
295
296static EbmlSyntax matroska_track_encodings[] = {
297 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
298 { EBML_ID_VOID, EBML_NONE },
299 { 0 }
300};
301
302static EbmlSyntax matroska_track[] = {
303 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
304 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
305 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
306 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
307 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
308 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
309 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
310 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
311 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
312 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
313 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
314 { MATROSKA_ID_TRACKUID, EBML_NONE },
315 { MATROSKA_ID_TRACKNAME, EBML_NONE },
316 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
317 { MATROSKA_ID_TRACKFLAGFORCED, EBML_NONE },
318 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
319 { MATROSKA_ID_CODECNAME, EBML_NONE },
320 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
321 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
322 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
323 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
324 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
325 { EBML_ID_VOID, EBML_NONE },
326 { 0 }
327};
328
329static EbmlSyntax matroska_tracks[] = {
330 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
331 { EBML_ID_VOID, EBML_NONE },
332 { 0 }
333};
334
Aurelien Jacobsb414cb82008-08-05 00:40:24335static EbmlSyntax matroska_attachment[] = {
336 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
337 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
338 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
339 { MATROSKA_ID_FILEUID, EBML_NONE },
340 { EBML_ID_VOID, EBML_NONE },
341 { 0 }
342};
343
344static EbmlSyntax matroska_attachments[] = {
345 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
346 { EBML_ID_VOID, EBML_NONE },
347 { 0 }
348};
349
Aurelien Jacobs6bbd7c72008-08-05 00:40:21350static EbmlSyntax matroska_chapter_display[] = {
351 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
352 { EBML_ID_VOID, EBML_NONE },
353 { 0 }
354};
355
356static EbmlSyntax matroska_chapter_entry[] = {
357 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
358 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
359 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
360 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
361 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
362 { EBML_ID_VOID, EBML_NONE },
363 { 0 }
364};
365
366static EbmlSyntax matroska_chapter[] = {
367 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
368 { MATROSKA_ID_EDITIONUID, EBML_NONE },
369 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
370 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
371 { EBML_ID_VOID, EBML_NONE },
372 { 0 }
373};
374
375static EbmlSyntax matroska_chapters[] = {
376 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
377 { EBML_ID_VOID, EBML_NONE },
378 { 0 }
379};
380
Aurelien Jacobse5929fd2008-08-05 00:40:15381static EbmlSyntax matroska_index_pos[] = {
382 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
383 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
384 { EBML_ID_VOID, EBML_NONE },
385 { 0 }
386};
387
388static EbmlSyntax matroska_index_entry[] = {
389 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
390 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
391 { EBML_ID_VOID, EBML_NONE },
392 { 0 }
393};
394
395static EbmlSyntax matroska_index[] = {
396 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
397 { EBML_ID_VOID, EBML_NONE },
398 { 0 }
399};
400
Aurelien Jacobs434d4962008-08-05 00:40:18401static EbmlSyntax matroska_tags[] = {
402 { EBML_ID_VOID, EBML_NONE },
403 { 0 }
404};
405
Aurelien Jacobs13b350a2008-08-05 00:40:36406static EbmlSyntax matroska_seekhead_entry[] = {
407 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
408 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
409 { EBML_ID_VOID, EBML_NONE },
410 { 0 }
411};
412
413static EbmlSyntax matroska_seekhead[] = {
414 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
415 { EBML_ID_VOID, EBML_NONE },
416 { 0 }
417};
418
Aurelien Jacobsce6f28b2008-08-05 00:40:58419static EbmlSyntax matroska_segment[] = {
420 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
421 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
422 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
423 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
424 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
425 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
426 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
427 { MATROSKA_ID_CLUSTER, EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
428 { EBML_ID_VOID, EBML_NONE },
429 { 0 }
430};
431
432static EbmlSyntax matroska_segments[] = {
433 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
434 { 0 }
435};
436
Aurelien Jacobs209472b2008-08-05 00:41:05437static EbmlSyntax matroska_blockgroup[] = {
438 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
439 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
440 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
441 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
442 { EBML_ID_VOID, EBML_NONE },
443 { 0 }
444};
445
446static EbmlSyntax matroska_cluster[] = {
447 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
448 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
449 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
450 { EBML_ID_VOID, EBML_NONE },
451 { 0 }
452};
453
454static EbmlSyntax matroska_clusters[] = {
455 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
456 { 0 }
457};
458
David Conradb061d892007-06-04 22:10:54459/*
460 * The first few functions handle EBML file parsing. The rest
461 * is the document interpretation. Matroska really just is a
462 * EBML file.
463 */
464
465/*
466 * Return: the amount of levels in the hierarchy that the
467 * current element lies higher than the previous one.
468 * The opposite isn't done - that's auto-done using master
469 * element reading.
470 */
471
472static int
473ebml_read_element_level_up (MatroskaDemuxContext *matroska)
474{
Björn Axelsson899681c2007-11-21 07:41:00475 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54476 offset_t pos = url_ftell(pb);
477 int num = 0;
478
479 while (matroska->num_levels > 0) {
480 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
481
482 if (pos >= level->start + level->length) {
483 matroska->num_levels--;
484 num++;
485 } else {
486 break;
487 }
488 }
489
490 return num;
491}
492
493/*
494 * Read: an "EBML number", which is defined as a variable-length
495 * array of bytes. The first byte indicates the length by giving a
496 * number of 0-bits followed by a one. The position of the first
497 * "one" bit inside the first byte indicates the length of this
498 * number.
499 * Returns: num. of bytes read. < 0 on error.
500 */
501
502static int
503ebml_read_num (MatroskaDemuxContext *matroska,
504 int max_size,
505 uint64_t *number)
506{
Björn Axelsson899681c2007-11-21 07:41:00507 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54508 int len_mask = 0x80, read = 1, n = 1;
509 int64_t total = 0;
510
511 /* the first byte tells us the length in bytes - get_byte() can normally
512 * return 0, but since that's not a valid first ebmlID byte, we can
513 * use it safely here to catch EOS. */
514 if (!(total = get_byte(pb))) {
515 /* we might encounter EOS here */
516 if (!url_feof(pb)) {
517 offset_t pos = url_ftell(pb);
518 av_log(matroska->ctx, AV_LOG_ERROR,
519 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
520 pos, pos);
521 }
Panagiotis Issaris6f3e0b22007-07-19 15:23:32522 return AVERROR(EIO); /* EOS or actual I/O error */
David Conradb061d892007-06-04 22:10:54523 }
524
525 /* get the length of the EBML number */
526 while (read <= max_size && !(total & len_mask)) {
527 read++;
528 len_mask >>= 1;
529 }
530 if (read > max_size) {
531 offset_t pos = url_ftell(pb) - 1;
532 av_log(matroska->ctx, AV_LOG_ERROR,
533 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
534 (uint8_t) total, pos, pos);
535 return AVERROR_INVALIDDATA;
536 }
537
538 /* read out length */
539 total &= ~len_mask;
540 while (n++ < read)
541 total = (total << 8) | get_byte(pb);
542
543 *number = total;
544
545 return read;
546}
547
548/*
549 * Read: the element content data ID.
550 * Return: the number of bytes read or < 0 on error.
551 */
552
553static int
554ebml_read_element_id (MatroskaDemuxContext *matroska,
555 uint32_t *id,
556 int *level_up)
557{
558 int read;
559 uint64_t total;
560
561 /* if we re-call this, use our cached ID */
562 if (matroska->peek_id != 0) {
563 if (level_up)
564 *level_up = 0;
565 *id = matroska->peek_id;
566 return 0;
567 }
568
569 /* read out the "EBML number", include tag in ID */
570 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
571 return read;
572 *id = matroska->peek_id = total | (1 << (read * 7));
573
574 /* level tracking */
575 if (level_up)
576 *level_up = ebml_read_element_level_up(matroska);
577
578 return read;
579}
580
581/*
582 * Read: element content length.
583 * Return: the number of bytes read or < 0 on error.
584 */
585
586static int
587ebml_read_element_length (MatroskaDemuxContext *matroska,
588 uint64_t *length)
589{
590 /* clear cache since we're now beyond that data point */
591 matroska->peek_id = 0;
592
593 /* read out the "EBML number", include tag in ID */
594 return ebml_read_num(matroska, 8, length);
595}
596
597/*
598 * Return: the ID of the next element, or 0 on error.
599 * Level_up contains the amount of levels that this
600 * next element lies higher than the previous one.
601 */
602
603static uint32_t
604ebml_peek_id (MatroskaDemuxContext *matroska,
605 int *level_up)
606{
607 uint32_t id;
608
David Conradb061d892007-06-04 22:10:54609 if (ebml_read_element_id(matroska, &id, level_up) < 0)
610 return 0;
611
612 return id;
613}
614
615/*
616 * Seek to a given offset.
617 * 0 is success, -1 is failure.
618 */
619
620static int
621ebml_read_seek (MatroskaDemuxContext *matroska,
622 offset_t offset)
623{
Björn Axelsson899681c2007-11-21 07:41:00624 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54625
626 /* clear ID cache, if any */
627 matroska->peek_id = 0;
628
629 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
630}
631
632/*
633 * Skip the next element.
634 * 0 is success, -1 is failure.
635 */
636
637static int
638ebml_read_skip (MatroskaDemuxContext *matroska)
639{
Björn Axelsson899681c2007-11-21 07:41:00640 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54641 uint32_t id;
642 uint64_t length;
643 int res;
644
645 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
646 (res = ebml_read_element_length(matroska, &length)) < 0)
647 return res;
648
649 url_fskip(pb, length);
650
651 return 0;
652}
653
654/*
655 * Read the next element as an unsigned int.
656 * 0 is success, < 0 is failure.
657 */
658
659static int
660ebml_read_uint (MatroskaDemuxContext *matroska,
661 uint32_t *id,
662 uint64_t *num)
663{
Björn Axelsson899681c2007-11-21 07:41:00664 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54665 int n = 0, size, res;
666 uint64_t rlength;
667
668 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
669 (res = ebml_read_element_length(matroska, &rlength)) < 0)
670 return res;
671 size = rlength;
672 if (size < 1 || size > 8) {
673 offset_t pos = url_ftell(pb);
674 av_log(matroska->ctx, AV_LOG_ERROR,
675 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
676 size, pos, pos);
677 return AVERROR_INVALIDDATA;
678 }
679
680 /* big-endian ordening; build up number */
681 *num = 0;
682 while (n++ < size)
683 *num = (*num << 8) | get_byte(pb);
684
685 return 0;
686}
687
688/*
David Conradb061d892007-06-04 22:10:54689 * Read the next element as a float.
690 * 0 is success, < 0 is failure.
691 */
692
693static int
694ebml_read_float (MatroskaDemuxContext *matroska,
695 uint32_t *id,
696 double *num)
697{
Björn Axelsson899681c2007-11-21 07:41:00698 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54699 int size, res;
700 uint64_t rlength;
701
702 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
703 (res = ebml_read_element_length(matroska, &rlength)) < 0)
704 return res;
705 size = rlength;
706
707 if (size == 4) {
708 *num= av_int2flt(get_be32(pb));
709 } else if(size==8){
710 *num= av_int2dbl(get_be64(pb));
711 } else{
712 offset_t pos = url_ftell(pb);
713 av_log(matroska->ctx, AV_LOG_ERROR,
714 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
715 size, pos, pos);
716 return AVERROR_INVALIDDATA;
717 }
718
719 return 0;
720}
721
722/*
723 * Read the next element as an ASCII string.
724 * 0 is success, < 0 is failure.
725 */
726
727static int
728ebml_read_ascii (MatroskaDemuxContext *matroska,
729 uint32_t *id,
730 char **str)
731{
Björn Axelsson899681c2007-11-21 07:41:00732 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54733 int size, res;
734 uint64_t rlength;
735
736 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
737 (res = ebml_read_element_length(matroska, &rlength)) < 0)
738 return res;
739 size = rlength;
740
741 /* ebml strings are usually not 0-terminated, so we allocate one
742 * byte more, read the string and NULL-terminate it ourselves. */
743 if (size < 0 || !(*str = av_malloc(size + 1))) {
744 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
Panagiotis Issaris769e10f2007-07-19 15:21:30745 return AVERROR(ENOMEM);
David Conradb061d892007-06-04 22:10:54746 }
747 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
748 offset_t pos = url_ftell(pb);
749 av_log(matroska->ctx, AV_LOG_ERROR,
750 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
Aurelien Jacobsff2c2222008-06-02 23:37:14751 av_free(*str);
Panagiotis Issaris6f3e0b22007-07-19 15:23:32752 return AVERROR(EIO);
David Conradb061d892007-06-04 22:10:54753 }
754 (*str)[size] = '\0';
755
756 return 0;
757}
758
759/*
David Conradb061d892007-06-04 22:10:54760 * Read the next element, but only the header. The contents
761 * are supposed to be sub-elements which can be read separately.
762 * 0 is success, < 0 is failure.
763 */
764
765static int
766ebml_read_master (MatroskaDemuxContext *matroska,
767 uint32_t *id)
768{
Björn Axelsson899681c2007-11-21 07:41:00769 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54770 uint64_t length;
771 MatroskaLevel *level;
772 int res;
773
774 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
775 (res = ebml_read_element_length(matroska, &length)) < 0)
776 return res;
777
778 /* protect... (Heaven forbids that the '>' is true) */
779 if (matroska->num_levels >= EBML_MAX_DEPTH) {
780 av_log(matroska->ctx, AV_LOG_ERROR,
781 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
Panagiotis Issaris85565db2007-07-19 15:38:33782 return AVERROR(ENOSYS);
David Conradb061d892007-06-04 22:10:54783 }
784
785 /* remember level */
786 level = &matroska->levels[matroska->num_levels++];
787 level->start = url_ftell(pb);
788 level->length = length;
789
790 return 0;
791}
792
793/*
794 * Read the next element as binary data.
795 * 0 is success, < 0 is failure.
796 */
797
798static int
799ebml_read_binary (MatroskaDemuxContext *matroska,
800 uint32_t *id,
801 uint8_t **binary,
802 int *size)
803{
Björn Axelsson899681c2007-11-21 07:41:00804 ByteIOContext *pb = matroska->ctx->pb;
David Conradb061d892007-06-04 22:10:54805 uint64_t rlength;
806 int res;
807
808 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
809 (res = ebml_read_element_length(matroska, &rlength)) < 0)
810 return res;
811 *size = rlength;
812
813 if (!(*binary = av_malloc(*size))) {
814 av_log(matroska->ctx, AV_LOG_ERROR,
815 "Memory allocation error\n");
Panagiotis Issaris769e10f2007-07-19 15:21:30816 return AVERROR(ENOMEM);
David Conradb061d892007-06-04 22:10:54817 }
818
819 if (get_buffer(pb, *binary, *size) != *size) {
820 offset_t pos = url_ftell(pb);
821 av_log(matroska->ctx, AV_LOG_ERROR,
822 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
Panagiotis Issaris6f3e0b22007-07-19 15:23:32823 return AVERROR(EIO);
David Conradb061d892007-06-04 22:10:54824 }
825
826 return 0;
827}
828
829/*
830 * Read signed/unsigned "EBML" numbers.
831 * Return: number of bytes processed, < 0 on error.
832 * XXX: use ebml_read_num().
833 */
834
835static int
836matroska_ebmlnum_uint (uint8_t *data,
837 uint32_t size,
838 uint64_t *num)
839{
840 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
841 uint64_t total;
842
843 if (size <= 0)
844 return AVERROR_INVALIDDATA;
845
846 total = data[0];
847 while (read <= 8 && !(total & len_mask)) {
848 read++;
849 len_mask >>= 1;
850 }
851 if (read > 8)
852 return AVERROR_INVALIDDATA;
853
854 if ((total &= (len_mask - 1)) == len_mask - 1)
855 num_ffs++;
856 if (size < read)
857 return AVERROR_INVALIDDATA;
858 while (n < read) {
859 if (data[n] == 0xff)
860 num_ffs++;
861 total = (total << 8) | data[n];
862 n++;
863 }
864
865 if (read == num_ffs)
866 *num = (uint64_t)-1;
867 else
868 *num = total;
869
870 return read;
871}
872
873/*
874 * Same as above, but signed.
875 */
876
877static int
878matroska_ebmlnum_sint (uint8_t *data,
879 uint32_t size,
880 int64_t *num)
881{
882 uint64_t unum;
883 int res;
884
885 /* read as unsigned number first */
886 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
887 return res;
888
889 /* make signed (weird way) */
890 if (unum == (uint64_t)-1)
891 *num = INT64_MAX;
892 else
893 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
894
895 return res;
896}
897
David Conradb061d892007-06-04 22:10:54898
Aurelien Jacobs009ecd52008-08-05 00:40:12899static MatroskaTrack *
David Conradb061d892007-06-04 22:10:54900matroska_find_track_by_num (MatroskaDemuxContext *matroska,
901 int num)
902{
Aurelien Jacobs2cbc8812008-08-05 00:40:31903 MatroskaTrack *tracks = matroska->tracks.elem;
David Conradb061d892007-06-04 22:10:54904 int i;
905
Aurelien Jacobs2cbc8812008-08-05 00:40:31906 for (i=0; i < matroska->tracks.nb_elem; i++)
907 if (tracks[i].num == num)
908 return &tracks[i];
David Conradb061d892007-06-04 22:10:54909
Aurelien Jacobs009ecd52008-08-05 00:40:12910 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
911 return NULL;
David Conradb061d892007-06-04 22:10:54912}
913
914
915/*
916 * Put one packet in an application-supplied AVPacket struct.
917 * Returns 0 on success or -1 on failure.
918 */
919
920static int
921matroska_deliver_packet (MatroskaDemuxContext *matroska,
922 AVPacket *pkt)
923{
924 if (matroska->num_packets > 0) {
925 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
926 av_free(matroska->packets[0]);
927 if (matroska->num_packets > 1) {
928 memmove(&matroska->packets[0], &matroska->packets[1],
929 (matroska->num_packets - 1) * sizeof(AVPacket *));
930 matroska->packets =
931 av_realloc(matroska->packets, (matroska->num_packets - 1) *
932 sizeof(AVPacket *));
933 } else {
934 av_freep(&matroska->packets);
935 }
936 matroska->num_packets--;
937 return 0;
938 }
939
940 return -1;
941}
942
943/*
944 * Put a packet into our internal queue. Will be delivered to the
945 * user/application during the next get_packet() call.
946 */
947
948static void
949matroska_queue_packet (MatroskaDemuxContext *matroska,
950 AVPacket *pkt)
951{
952 matroska->packets =
953 av_realloc(matroska->packets, (matroska->num_packets + 1) *
954 sizeof(AVPacket *));
955 matroska->packets[matroska->num_packets] = pkt;
956 matroska->num_packets++;
957}
958
Aurelien Jacobs34c9c1b2007-12-29 18:32:47959/*
960 * Free all packets in our internal queue.
961 */
962static void
963matroska_clear_queue (MatroskaDemuxContext *matroska)
964{
965 if (matroska->packets) {
966 int n;
967 for (n = 0; n < matroska->num_packets; n++) {
968 av_free_packet(matroska->packets[n]);
969 av_free(matroska->packets[n]);
970 }
971 av_free(matroska->packets);
972 matroska->packets = NULL;
Aurelien Jacobse2997272008-01-02 17:17:56973 matroska->num_packets = 0;
Aurelien Jacobs34c9c1b2007-12-29 18:32:47974 }
975}
976
David Conradb061d892007-06-04 22:10:54977
978/*
979 * Autodetecting...
980 */
981
982static int
983matroska_probe (AVProbeData *p)
984{
985 uint64_t total = 0;
986 int len_mask = 0x80, size = 1, n = 1;
987 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
988
989 /* ebml header? */
Aurelien Jacobs2ce746c2007-06-23 12:32:19990 if (AV_RB32(p->buf) != EBML_ID_HEADER)
David Conradb061d892007-06-04 22:10:54991 return 0;
992
993 /* length of header */
994 total = p->buf[4];
995 while (size <= 8 && !(total & len_mask)) {
996 size++;
997 len_mask >>= 1;
998 }
999 if (size > 8)
1000 return 0;
1001 total &= (len_mask - 1);
1002 while (n < size)
1003 total = (total << 8) | p->buf[4 + n++];
1004
1005 /* does the probe data contain the whole header? */
1006 if (p->buf_size < 4 + size + total)
1007 return 0;
1008
1009 /* the header must contain the document type 'matroska'. For now,
1010 * we don't parse the whole header but simply check for the
1011 * availability of that array of characters inside the header.
1012 * Not fully fool-proof, but good enough. */
1013 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
1014 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1015 return AVPROBE_SCORE_MAX;
1016
1017 return 0;
1018}
1019
1020/*
1021 * From here on, it's all XML-style DTD stuff... Needs no comments.
1022 */
1023
Aurelien Jacobs789ed102008-08-05 00:40:001024static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1025 void *data, uint32_t expected_id, int once);
1026
1027static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1028 EbmlSyntax *syntax, void *data)
1029{
1030 uint32_t id = syntax->id;
1031 EbmlBin *bin;
1032 int res;
1033
1034 data = (char *)data + syntax->data_offset;
1035 if (syntax->list_elem_size) {
1036 EbmlList *list = data;
1037 list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1038 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1039 memset(data, 0, syntax->list_elem_size);
1040 list->nb_elem++;
1041 }
1042 bin = data;
1043
1044 switch (syntax->type) {
1045 case EBML_UINT: return ebml_read_uint (matroska, &id, data);
1046 case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1047 case EBML_STR:
1048 case EBML_UTF8: av_free(*(char **)data);
1049 return ebml_read_ascii(matroska, &id, data);
1050 case EBML_BIN: av_free(bin->data);
1051 bin->pos = url_ftell(matroska->ctx->pb);
1052 return ebml_read_binary(matroska, &id, &bin->data,
1053 &bin->size);
1054 case EBML_NEST: if ((res=ebml_read_master(matroska, &id)) < 0)
1055 return res;
1056 if (id == MATROSKA_ID_SEGMENT)
1057 matroska->segment_start = url_ftell(matroska->ctx->pb);
1058 return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1059 case EBML_PASS: return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1060 case EBML_STOP: *(int *)data = 1; return 1;
1061 default: return ebml_read_skip(matroska);
1062 }
1063}
1064
1065static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1066 uint32_t id, void *data)
1067{
1068 int i;
1069 for (i=0; syntax[i].id; i++)
1070 if (id == syntax[i].id)
1071 break;
1072 if (!syntax[i].id)
1073 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1074 return ebml_parse_elem(matroska, &syntax[i], data);
1075}
1076
1077static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1078 void *data, uint32_t expected_id, int once)
1079{
1080 int i, res = 0;
1081 uint32_t id = 0;
1082
1083 for (i=0; syntax[i].id; i++)
1084 switch (syntax[i].type) {
1085 case EBML_UINT:
1086 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1087 break;
1088 case EBML_FLOAT:
1089 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1090 break;
1091 case EBML_STR:
1092 case EBML_UTF8:
1093 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1094 break;
1095 }
1096
1097 if (expected_id) {
1098 res = ebml_read_master(matroska, &id);
1099 if (id != expected_id)
1100 return AVERROR_INVALIDDATA;
1101 if (id == MATROSKA_ID_SEGMENT)
1102 matroska->segment_start = url_ftell(matroska->ctx->pb);
1103 }
1104
1105 while (!res) {
1106 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1107 res = AVERROR(EIO);
1108 break;
1109 } else if (matroska->level_up) {
1110 matroska->level_up--;
1111 break;
1112 }
1113
1114 res = ebml_parse_id(matroska, syntax, id, data);
1115 if (once)
1116 break;
1117
1118
1119 if (matroska->level_up) {
1120 matroska->level_up--;
1121 break;
1122 }
1123 }
1124
1125 return res;
1126}
1127
1128static void ebml_free(EbmlSyntax *syntax, void *data)
1129{
1130 int i, j;
1131 for (i=0; syntax[i].id; i++) {
1132 void *data_off = (char *)data + syntax[i].data_offset;
1133 switch (syntax[i].type) {
1134 case EBML_STR:
1135 case EBML_UTF8: av_freep(data_off); break;
1136 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
1137 case EBML_NEST:
1138 if (syntax[i].list_elem_size) {
1139 EbmlList *list = data_off;
1140 char *ptr = list->elem;
1141 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1142 ebml_free(syntax[i].def.n, ptr);
1143 av_free(list->elem);
1144 } else
1145 ebml_free(syntax[i].def.n, data_off);
1146 default: break;
1147 }
1148 }
1149}
1150
David Conradb061d892007-06-04 22:10:541151static int
Evgeniy Stepanov935ec5a2008-06-22 15:49:441152matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1153{
Aurelien Jacobs2cbc8812008-08-05 00:40:311154 MatroskaTrackEncoding *encodings = track->encodings.elem;
Evgeniy Stepanov935ec5a2008-06-22 15:49:441155 uint8_t* data = *buf;
1156 int isize = *buf_size;
1157 uint8_t* pkt_data = NULL;
1158 int pkt_size = isize;
1159 int result = 0;
1160 int olen;
1161
Aurelien Jacobs2cbc8812008-08-05 00:40:311162 switch (encodings[0].compression.algo) {
Evgeniy Stepanov935ec5a2008-06-22 15:49:441163 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
Aurelien Jacobs2cbc8812008-08-05 00:40:311164 return encodings[0].compression.settings.size;
Evgeniy Stepanov935ec5a2008-06-22 15:49:441165 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1166 do {
1167 olen = pkt_size *= 3;
1168 pkt_data = av_realloc(pkt_data,
1169 pkt_size+LZO_OUTPUT_PADDING);
1170 result = lzo1x_decode(pkt_data, &olen, data, &isize);
1171 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1172 if (result)
1173 goto failed;
1174 pkt_size -= olen;
1175 break;
1176#ifdef CONFIG_ZLIB
1177 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1178 z_stream zstream = {0};
1179 if (inflateInit(&zstream) != Z_OK)
1180 return -1;
1181 zstream.next_in = data;
1182 zstream.avail_in = isize;
1183 do {
1184 pkt_size *= 3;
1185 pkt_data = av_realloc(pkt_data, pkt_size);
1186 zstream.avail_out = pkt_size - zstream.total_out;
1187 zstream.next_out = pkt_data + zstream.total_out;
1188 result = inflate(&zstream, Z_NO_FLUSH);
1189 } while (result==Z_OK && pkt_size<10000000);
1190 pkt_size = zstream.total_out;
1191 inflateEnd(&zstream);
1192 if (result != Z_STREAM_END)
1193 goto failed;
1194 break;
1195 }
1196#endif
1197#ifdef CONFIG_BZLIB
1198 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1199 bz_stream bzstream = {0};
1200 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1201 return -1;
1202 bzstream.next_in = data;
1203 bzstream.avail_in = isize;
1204 do {
1205 pkt_size *= 3;
1206 pkt_data = av_realloc(pkt_data, pkt_size);
1207 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1208 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1209 result = BZ2_bzDecompress(&bzstream);
1210 } while (result==BZ_OK && pkt_size<10000000);
1211 pkt_size = bzstream.total_out_lo32;
1212 BZ2_bzDecompressEnd(&bzstream);
1213 if (result != BZ_STREAM_END)
1214 goto failed;
1215 break;
1216 }
1217#endif
1218 }
1219
1220 *buf = pkt_data;
1221 *buf_size = pkt_size;
1222 return 0;
1223 failed:
1224 av_free(pkt_data);
1225 return -1;
1226}
1227
Aurelien Jacobs13b350a2008-08-05 00:40:361228static void
1229matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1230{
1231 EbmlList *seekhead_list = &matroska->seekhead;
1232 MatroskaSeekhead *seekhead = seekhead_list->elem;
1233 uint32_t peek_id_cache = matroska->peek_id;
1234 uint32_t level_up = matroska->level_up;
1235 offset_t before_pos = url_ftell(matroska->ctx->pb);
Aurelien Jacobs13b350a2008-08-05 00:40:361236 MatroskaLevel level;
Aurelien Jacobsf06a4882008-08-05 00:41:011237 int i;
David Conradb061d892007-06-04 22:10:541238
Aurelien Jacobs13b350a2008-08-05 00:40:361239 for (i=0; i<seekhead_list->nb_elem; i++) {
1240 if (seekhead[i].pos <= before_pos
1241 || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1242 || seekhead[i].id == MATROSKA_ID_CLUSTER)
1243 continue;
David Conradb061d892007-06-04 22:10:541244
Aurelien Jacobs43485712008-08-05 00:40:431245 /* seek */
1246 if (ebml_read_seek(matroska,
1247 seekhead[i].pos+matroska->segment_start) < 0)
1248 continue;
David Conradb061d892007-06-04 22:10:541249
Aurelien Jacobs43485712008-08-05 00:40:431250 /* we don't want to lose our seekhead level, so we add
1251 * a dummy. This is a crude hack. */
1252 if (matroska->num_levels == EBML_MAX_DEPTH) {
1253 av_log(matroska->ctx, AV_LOG_INFO,
1254 "Max EBML element depth (%d) reached, "
1255 "cannot parse further.\n", EBML_MAX_DEPTH);
1256 break;
1257 }
David Conradb061d892007-06-04 22:10:541258
Aurelien Jacobs43485712008-08-05 00:40:431259 level.start = 0;
1260 level.length = (uint64_t)-1;
1261 matroska->levels[matroska->num_levels] = level;
1262 matroska->num_levels++;
David Conradb061d892007-06-04 22:10:541263
Aurelien Jacobsf06a4882008-08-05 00:41:011264 ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
David Conradb061d892007-06-04 22:10:541265
Aurelien Jacobs43485712008-08-05 00:40:431266 /* remove dummy level */
1267 while (matroska->num_levels) {
1268 uint64_t length = matroska->levels[--matroska->num_levels].length;
1269 if (length == (uint64_t)-1)
1270 break;
1271 }
David Conradb061d892007-06-04 22:10:541272 }
1273
Aurelien Jacobs43485712008-08-05 00:40:431274 /* seek back */
1275 ebml_read_seek(matroska, before_pos);
1276 matroska->peek_id = peek_id_cache;
1277 matroska->level_up = level_up;
David Conradb061d892007-06-04 22:10:541278}
1279
Evgeniy Stepanovf8d7c9d2008-01-27 15:43:171280static int
David Conradb061d892007-06-04 22:10:541281matroska_aac_profile (char *codec_id)
1282{
Aurelien Jacobs8f35a2c2008-08-05 00:41:221283 static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
David Conradb061d892007-06-04 22:10:541284 int profile;
1285
1286 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1287 if (strstr(codec_id, aac_profiles[profile]))
1288 break;
1289 return profile + 1;
1290}
1291
1292static int
1293matroska_aac_sri (int samplerate)
1294{
David Conradb061d892007-06-04 22:10:541295 int sri;
1296
Aurelien Jacobs7bfacd42008-04-02 21:41:481297 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1298 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
David Conradb061d892007-06-04 22:10:541299 break;
1300 return sri;
1301}
1302
1303static int
1304matroska_read_header (AVFormatContext *s,
1305 AVFormatParameters *ap)
1306{
1307 MatroskaDemuxContext *matroska = s->priv_data;
Aurelien Jacobs9c25baf2008-08-05 00:40:551308 EbmlList *attachements_list = &matroska->attachments;
1309 MatroskaAttachement *attachements;
1310 EbmlList *chapters_list = &matroska->chapters;
1311 MatroskaChapter *chapters;
Aurelien Jacobs9a9a3b02008-08-05 00:40:491312 MatroskaTrack *tracks;
Aurelien Jacobse5929fd2008-08-05 00:40:151313 EbmlList *index_list;
1314 MatroskaIndex *index;
Aurelien Jacobs63511322008-08-05 00:40:021315 Ebml ebml = { 0 };
Aurelien Jacobs9a9a3b02008-08-05 00:40:491316 AVStream *st;
Aurelien Jacobsce6f28b2008-08-05 00:40:581317 int i, j;
David Conradb061d892007-06-04 22:10:541318
1319 matroska->ctx = s;
1320
1321 /* First read the EBML header. */
Aurelien Jacobs63511322008-08-05 00:40:021322 if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1323 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1324 || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1325 || ebml.doctype_version > 2) {
David Conradb061d892007-06-04 22:10:541326 av_log(matroska->ctx, AV_LOG_ERROR,
Aurelien Jacobs63511322008-08-05 00:40:021327 "EBML header using unsupported features\n"
1328 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1329 ebml.version, ebml.doctype, ebml.doctype_version);
David Conradb061d892007-06-04 22:10:541330 return AVERROR_NOFMT;
1331 }
Aurelien Jacobs63511322008-08-05 00:40:021332 ebml_free(ebml_syntax, &ebml);
David Conradb061d892007-06-04 22:10:541333
1334 /* The next thing is a segment. */
Aurelien Jacobsce6f28b2008-08-05 00:40:581335 if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1336 return -1;
Aurelien Jacobs13b350a2008-08-05 00:40:361337 matroska_execute_seekhead(matroska);
David Conradb061d892007-06-04 22:10:541338
1339 /* Have we found a cluster? */
Aurelien Jacobsa636a562008-08-05 00:40:461340 if (ebml_peek_id(matroska, NULL) != MATROSKA_ID_CLUSTER)
1341 return -1;
1342
Aurelien Jacobs9c25baf2008-08-05 00:40:551343 if (matroska->duration)
1344 matroska->ctx->duration = matroska->duration * matroska->time_scale
1345 * 1000 / AV_TIME_BASE;
1346 if (matroska->title)
1347 strncpy(matroska->ctx->title, matroska->title,
1348 sizeof(matroska->ctx->title)-1);
1349
Aurelien Jacobsd88d8062008-08-05 00:40:521350 tracks = matroska->tracks.elem;
1351 for (i=0; i < matroska->tracks.nb_elem; i++) {
1352 MatroskaTrack *track = &tracks[i];
1353 enum CodecID codec_id = CODEC_ID_NONE;
Aurelien Jacobs9c25baf2008-08-05 00:40:551354 EbmlList *encodings_list = &tracks->encodings;
1355 MatroskaTrackEncoding *encodings = encodings_list->elem;
Aurelien Jacobsd88d8062008-08-05 00:40:521356 uint8_t *extradata = NULL;
1357 int extradata_size = 0;
1358 int extradata_offset = 0;
David Conradb061d892007-06-04 22:10:541359
Aurelien Jacobsd88d8062008-08-05 00:40:521360 /* Apply some sanity checks. */
Aurelien Jacobs9c25baf2008-08-05 00:40:551361 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1362 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1363 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1364 av_log(matroska->ctx, AV_LOG_INFO,
1365 "Unknown or unsupported track type %"PRIu64"\n",
1366 track->type);
1367 continue;
1368 }
Aurelien Jacobsd88d8062008-08-05 00:40:521369 if (track->codec_id == NULL)
1370 continue;
David Conradb061d892007-06-04 22:10:541371
Aurelien Jacobs9c25baf2008-08-05 00:40:551372 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1373 if (!track->default_duration)
1374 track->default_duration = 1000000000/track->video.frame_rate;
1375 if (!track->video.display_width)
1376 track->video.display_width = track->video.pixel_width;
1377 if (!track->video.display_height)
1378 track->video.display_height = track->video.pixel_height;
1379 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1380 if (!track->audio.out_samplerate)
1381 track->audio.out_samplerate = track->audio.samplerate;
1382 }
1383 if (encodings_list->nb_elem > 1) {
1384 av_log(matroska->ctx, AV_LOG_ERROR,
1385 "Multiple combined encodings no supported");
1386 } else if (encodings_list->nb_elem == 1) {
1387 if (encodings[0].type ||
1388 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1389#ifdef CONFIG_ZLIB
1390 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1391#endif
1392#ifdef CONFIG_BZLIB
1393 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1394#endif
1395 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1396 encodings[0].scope = 0;
1397 av_log(matroska->ctx, AV_LOG_ERROR,
1398 "Unsupported encoding type");
1399 } else if (track->codec_priv.size && encodings[0].scope&2) {
1400 uint8_t *codec_priv = track->codec_priv.data;
1401 int offset = matroska_decode_buffer(&track->codec_priv.data,
1402 &track->codec_priv.size,
1403 track);
1404 if (offset < 0) {
1405 track->codec_priv.data = NULL;
1406 track->codec_priv.size = 0;
1407 av_log(matroska->ctx, AV_LOG_ERROR,
1408 "Failed to decode codec private data\n");
1409 } else if (offset > 0) {
1410 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1411 memcpy(track->codec_priv.data,
1412 encodings[0].compression.settings.data, offset);
1413 memcpy(track->codec_priv.data+offset, codec_priv,
1414 track->codec_priv.size);
1415 track->codec_priv.size += offset;
1416 }
1417 if (codec_priv != track->codec_priv.data)
1418 av_free(codec_priv);
1419 }
1420 }
1421
Aurelien Jacobsd88d8062008-08-05 00:40:521422 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1423 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1424 strlen(ff_mkv_codec_tags[j].str))){
1425 codec_id= ff_mkv_codec_tags[j].id;
1426 break;
David Conradb061d892007-06-04 22:10:541427 }
Aurelien Jacobsd88d8062008-08-05 00:40:521428 }
David Conradb061d892007-06-04 22:10:541429
Aurelien Jacobsd88d8062008-08-05 00:40:521430 st = track->stream = av_new_stream(s, matroska->num_streams++);
1431 if (st == NULL)
1432 return AVERROR(ENOMEM);
1433
1434 /* Set the FourCC from the CodecID. */
1435 /* This is the MS compatibility mode which stores a
1436 * BITMAPINFOHEADER in the CodecPrivate. */
1437 if (!strcmp(track->codec_id,
1438 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
1439 (track->codec_priv.size >= 40) &&
1440 (track->codec_priv.data != NULL)) {
1441 /* Offset of biCompression. Stored in LE. */
1442 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1443 codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1444
1445 }
1446
1447 /* This is the MS compatibility mode which stores a
1448 * WAVEFORMATEX in the CodecPrivate. */
1449 else if (!strcmp(track->codec_id,
1450 MATROSKA_CODEC_ID_AUDIO_ACM) &&
1451 (track->codec_priv.size >= 18) &&
1452 (track->codec_priv.data != NULL)) {
1453 /* Offset of wFormatTag. Stored in LE. */
1454 uint16_t tag = AV_RL16(track->codec_priv.data);
1455 codec_id = codec_get_id(codec_wav_tags, tag);
1456
1457 }
1458
1459 else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1460 (track->codec_priv.size >= 86) &&
1461 (track->codec_priv.data != NULL)) {
1462 track->video.fourcc = AV_RL32(track->codec_priv.data);
1463 codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1464 }
1465
1466 else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1467 int profile = matroska_aac_profile(track->codec_id);
1468 int sri = matroska_aac_sri(track->audio.samplerate);
1469 extradata = av_malloc(5);
1470 if (extradata == NULL)
Aurelien Jacobs28f450a2008-08-05 00:40:091471 return AVERROR(ENOMEM);
Aurelien Jacobsd88d8062008-08-05 00:40:521472 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1473 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1474 if (strstr(track->codec_id, "SBR")) {
1475 sri = matroska_aac_sri(track->audio.out_samplerate);
1476 extradata[2] = 0x56;
1477 extradata[3] = 0xE5;
1478 extradata[4] = 0x80 | (sri<<3);
1479 extradata_size = 5;
Aurelien Jacobs16f97ab2008-08-05 00:41:101480 } else
Aurelien Jacobsd88d8062008-08-05 00:40:521481 extradata_size = 2;
Aurelien Jacobsd88d8062008-08-05 00:40:521482 }
David Conradb061d892007-06-04 22:10:541483
Aurelien Jacobsd88d8062008-08-05 00:40:521484 else if (codec_id == CODEC_ID_TTA) {
1485 ByteIOContext b;
1486 extradata_size = 30;
1487 extradata = av_mallocz(extradata_size);
1488 if (extradata == NULL)
1489 return AVERROR(ENOMEM);
1490 init_put_byte(&b, extradata, extradata_size, 1,
1491 NULL, NULL, NULL, NULL);
1492 put_buffer(&b, "TTA1", 4);
1493 put_le16(&b, 1);
1494 put_le16(&b, track->audio.channels);
1495 put_le16(&b, track->audio.bitdepth);
1496 put_le32(&b, track->audio.out_samplerate);
1497 put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1498 }
David Conradb061d892007-06-04 22:10:541499
Aurelien Jacobsd88d8062008-08-05 00:40:521500 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1501 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1502 extradata_offset = 26;
1503 track->codec_priv.size -= extradata_offset;
1504 }
David Conradb061d892007-06-04 22:10:541505
Aurelien Jacobsd88d8062008-08-05 00:40:521506 else if (codec_id == CODEC_ID_RA_144) {
1507 track->audio.out_samplerate = 8000;
1508 track->audio.channels = 1;
1509 }
Aurelien Jacobsf009e362008-07-27 15:11:041510
Aurelien Jacobsd88d8062008-08-05 00:40:521511 else if (codec_id == CODEC_ID_RA_288 ||
1512 codec_id == CODEC_ID_COOK ||
1513 codec_id == CODEC_ID_ATRAC3) {
1514 ByteIOContext b;
David Conradb061d892007-06-04 22:10:541515
Aurelien Jacobsd88d8062008-08-05 00:40:521516 init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1517 0, NULL, NULL, NULL, NULL);
1518 url_fskip(&b, 24);
1519 track->audio.coded_framesize = get_be32(&b);
1520 url_fskip(&b, 12);
1521 track->audio.sub_packet_h = get_be16(&b);
1522 track->audio.frame_size = get_be16(&b);
1523 track->audio.sub_packet_size = get_be16(&b);
1524 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1525 if (codec_id == CODEC_ID_RA_288) {
1526 st->codec->block_align = track->audio.coded_framesize;
1527 track->codec_priv.size = 0;
1528 } else {
1529 st->codec->block_align = track->audio.sub_packet_size;
1530 extradata_offset = 78;
Aurelien Jacobs2cbc8812008-08-05 00:40:311531 track->codec_priv.size -= extradata_offset;
David Conradb061d892007-06-04 22:10:541532 }
David Conradb061d892007-06-04 22:10:541533 }
Aurelien Jacobsd88d8062008-08-05 00:40:521534
Aurelien Jacobs16f97ab2008-08-05 00:41:101535 if (codec_id == CODEC_ID_NONE)
Aurelien Jacobsd88d8062008-08-05 00:40:521536 av_log(matroska->ctx, AV_LOG_INFO,
Aurelien Jacobs8f35a2c2008-08-05 00:41:221537 "Unknown/unsupported CodecID %s.\n", track->codec_id);
Aurelien Jacobsd88d8062008-08-05 00:40:521538
1539 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1540
1541 st->codec->codec_id = codec_id;
1542 st->start_time = 0;
1543 if (strcmp(track->language, "und"))
1544 av_strlcpy(st->language, track->language, 4);
1545
1546 if (track->flag_default)
1547 st->disposition |= AV_DISPOSITION_DEFAULT;
1548
1549 if (track->default_duration)
1550 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1551 track->default_duration, 1000000000, 30000);
1552
1553 if(extradata){
1554 st->codec->extradata = extradata;
1555 st->codec->extradata_size = extradata_size;
1556 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1557 st->codec->extradata = av_malloc(track->codec_priv.size);
1558 if(st->codec->extradata == NULL)
1559 return AVERROR(ENOMEM);
1560 st->codec->extradata_size = track->codec_priv.size;
1561 memcpy(st->codec->extradata,
1562 track->codec_priv.data + extradata_offset,
1563 track->codec_priv.size);
1564 }
1565
1566 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1567 st->codec->codec_type = CODEC_TYPE_VIDEO;
1568 st->codec->codec_tag = track->video.fourcc;
1569 st->codec->width = track->video.pixel_width;
1570 st->codec->height = track->video.pixel_height;
1571 av_reduce(&st->codec->sample_aspect_ratio.num,
1572 &st->codec->sample_aspect_ratio.den,
1573 st->codec->height * track->video.display_width,
1574 st->codec-> width * track->video.display_height,
1575 255);
1576 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1577 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1578 st->codec->codec_type = CODEC_TYPE_AUDIO;
1579 st->codec->sample_rate = track->audio.out_samplerate;
1580 st->codec->channels = track->audio.channels;
1581 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1582 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1583 }
1584
1585 /* What do we do with private data? E.g. for Vorbis. */
David Conradb061d892007-06-04 22:10:541586 }
1587
Aurelien Jacobs9c25baf2008-08-05 00:40:551588 attachements = attachements_list->elem;
1589 for (j=0; j<attachements_list->nb_elem; j++) {
1590 if (!(attachements[j].filename && attachements[j].mime &&
1591 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1592 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1593 } else {
1594 AVStream *st = av_new_stream(s, matroska->num_streams++);
1595 if (st == NULL)
1596 break;
1597 st->filename = av_strdup(attachements[j].filename);
1598 st->codec->codec_id = CODEC_ID_NONE;
1599 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1600 st->codec->extradata = av_malloc(attachements[j].bin.size);
1601 if(st->codec->extradata == NULL)
1602 break;
1603 st->codec->extradata_size = attachements[j].bin.size;
1604 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1605
1606 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1607 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1608 strlen(ff_mkv_mime_tags[i].str))) {
1609 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1610 break;
1611 }
1612 }
1613 }
1614 }
1615
1616 chapters = chapters_list->elem;
1617 for (i=0; i<chapters_list->nb_elem; i++)
1618 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1619 ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1620 chapters[i].start, chapters[i].end,
1621 chapters[i].title);
1622
Aurelien Jacobse5929fd2008-08-05 00:40:151623 index_list = &matroska->index;
1624 index = index_list->elem;
1625 for (i=0; i<index_list->nb_elem; i++) {
1626 EbmlList *pos_list = &index[i].pos;
1627 MatroskaIndexPos *pos = pos_list->elem;
1628 for (j=0; j<pos_list->nb_elem; j++) {
Aurelien Jacobs009ecd52008-08-05 00:40:121629 MatroskaTrack *track = matroska_find_track_by_num(matroska,
Aurelien Jacobse5929fd2008-08-05 00:40:151630 pos[j].track);
Aurelien Jacobs009ecd52008-08-05 00:40:121631 if (track && track->stream)
1632 av_add_index_entry(track->stream,
Aurelien Jacobse5929fd2008-08-05 00:40:151633 pos[j].pos + matroska->segment_start,
1634 index[i].time*matroska->time_scale/AV_TIME_BASE,
Aurelien Jacobsffaa3ec2007-06-24 21:50:091635 0, 0, AVINDEX_KEYFRAME);
David Conradb061d892007-06-04 22:10:541636 }
1637 }
1638
Aurelien Jacobsce6f28b2008-08-05 00:40:581639 return 0;
David Conradb061d892007-06-04 22:10:541640}
1641
David Conradb061d892007-06-04 22:10:541642static int
1643matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1644 int64_t pos, uint64_t cluster_time, uint64_t duration,
Aurelien Jacobs6e35ae22008-08-05 00:39:551645 int is_keyframe)
David Conradb061d892007-06-04 22:10:541646{
Aurelien Jacobs009ecd52008-08-05 00:40:121647 MatroskaTrack *track;
David Conradb061d892007-06-04 22:10:541648 int res = 0;
David Conradb061d892007-06-04 22:10:541649 AVStream *st;
1650 AVPacket *pkt;
David Conradb061d892007-06-04 22:10:541651 int16_t block_time;
1652 uint32_t *lace_size = NULL;
1653 int n, flags, laces = 0;
1654 uint64_t num;
1655
1656 /* first byte(s): tracknum */
1657 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1658 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
David Conradb061d892007-06-04 22:10:541659 return res;
1660 }
1661 data += n;
1662 size -= n;
1663
1664 /* fetch track from num */
1665 track = matroska_find_track_by_num(matroska, num);
Aurelien Jacobs009ecd52008-08-05 00:40:121666 if (size <= 3 || !track || !track->stream) {
David Conradb061d892007-06-04 22:10:541667 av_log(matroska->ctx, AV_LOG_INFO,
Aurelien Jacobs009ecd52008-08-05 00:40:121668 "Invalid stream %"PRIu64" or size %u\n", num, size);
David Conradb061d892007-06-04 22:10:541669 return res;
1670 }
Aurelien Jacobs009ecd52008-08-05 00:40:121671 st = track->stream;
Aurelien Jacobs16f97ab2008-08-05 00:41:101672 if (st->discard >= AVDISCARD_ALL)
David Conradb061d892007-06-04 22:10:541673 return res;
David Conradb061d892007-06-04 22:10:541674 if (duration == AV_NOPTS_VALUE)
Aurelien Jacobs009ecd52008-08-05 00:40:121675 duration = track->default_duration / matroska->time_scale;
David Conradb061d892007-06-04 22:10:541676
1677 /* block_time (relative to cluster time) */
Aurelien Jacobs2ce746c2007-06-23 12:32:191678 block_time = AV_RB16(data);
David Conradb061d892007-06-04 22:10:541679 data += 2;
Aurelien Jacobs1607c532007-06-23 12:49:361680 flags = *data++;
1681 size -= 3;
David Conradb061d892007-06-04 22:10:541682 if (is_keyframe == -1)
David Conrad84fa6e22007-08-31 18:24:091683 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
David Conradb061d892007-06-04 22:10:541684
1685 if (matroska->skip_to_keyframe) {
Aurelien Jacobs16f97ab2008-08-05 00:41:101686 if (!is_keyframe || st != matroska->skip_to_stream)
David Conradb061d892007-06-04 22:10:541687 return res;
1688 matroska->skip_to_keyframe = 0;
1689 }
1690
1691 switch ((flags & 0x06) >> 1) {
1692 case 0x0: /* no lacing */
1693 laces = 1;
1694 lace_size = av_mallocz(sizeof(int));
1695 lace_size[0] = size;
1696 break;
1697
1698 case 0x1: /* xiph lacing */
1699 case 0x2: /* fixed-size lacing */
1700 case 0x3: /* EBML lacing */
Michael Niedermayer9bf8b562008-05-28 21:22:081701 assert(size>0); // size <=3 is checked before size-=3 above
David Conradb061d892007-06-04 22:10:541702 laces = (*data) + 1;
1703 data += 1;
1704 size -= 1;
1705 lace_size = av_mallocz(laces * sizeof(int));
1706
1707 switch ((flags & 0x06) >> 1) {
1708 case 0x1: /* xiph lacing */ {
1709 uint8_t temp;
1710 uint32_t total = 0;
1711 for (n = 0; res == 0 && n < laces - 1; n++) {
1712 while (1) {
1713 if (size == 0) {
1714 res = -1;
1715 break;
1716 }
1717 temp = *data;
1718 lace_size[n] += temp;
1719 data += 1;
1720 size -= 1;
1721 if (temp != 0xff)
1722 break;
1723 }
1724 total += lace_size[n];
1725 }
1726 lace_size[n] = size - total;
1727 break;
1728 }
1729
1730 case 0x2: /* fixed-size lacing */
1731 for (n = 0; n < laces; n++)
1732 lace_size[n] = size / laces;
1733 break;
1734
1735 case 0x3: /* EBML lacing */ {
1736 uint32_t total;
1737 n = matroska_ebmlnum_uint(data, size, &num);
1738 if (n < 0) {
1739 av_log(matroska->ctx, AV_LOG_INFO,
1740 "EBML block data error\n");
1741 break;
1742 }
1743 data += n;
1744 size -= n;
1745 total = lace_size[0] = num;
1746 for (n = 1; res == 0 && n < laces - 1; n++) {
1747 int64_t snum;
1748 int r;
1749 r = matroska_ebmlnum_sint (data, size, &snum);
1750 if (r < 0) {
1751 av_log(matroska->ctx, AV_LOG_INFO,
1752 "EBML block data error\n");
1753 break;
1754 }
1755 data += r;
1756 size -= r;
1757 lace_size[n] = lace_size[n - 1] + snum;
1758 total += lace_size[n];
1759 }
1760 lace_size[n] = size - total;
1761 break;
1762 }
1763 }
1764 break;
1765 }
1766
1767 if (res == 0) {
David Conradb061d892007-06-04 22:10:541768 uint64_t timecode = AV_NOPTS_VALUE;
1769
Aurelien Jacobs9c3e2f72007-08-10 15:37:551770 if (cluster_time != (uint64_t)-1
1771 && (block_time >= 0 || cluster_time >= -block_time))
David Conradb061d892007-06-04 22:10:541772 timecode = cluster_time + block_time;
1773
1774 for (n = 0; n < laces; n++) {
Aurelien Jacobsba8a76b2007-10-21 22:27:241775 if (st->codec->codec_id == CODEC_ID_RA_288 ||
1776 st->codec->codec_id == CODEC_ID_COOK ||
1777 st->codec->codec_id == CODEC_ID_ATRAC3) {
Aurelien Jacobsba8a76b2007-10-21 22:27:241778 int a = st->codec->block_align;
Aurelien Jacobs2cbc8812008-08-05 00:40:311779 int sps = track->audio.sub_packet_size;
1780 int cfs = track->audio.coded_framesize;
1781 int h = track->audio.sub_packet_h;
1782 int y = track->audio.sub_packet_cnt;
1783 int w = track->audio.frame_size;
Aurelien Jacobsba8a76b2007-10-21 22:27:241784 int x;
Aurelien Jacobseabb8ba2007-06-04 22:19:171785
Aurelien Jacobs2cbc8812008-08-05 00:40:311786 if (!track->audio.pkt_cnt) {
Aurelien Jacobsba8a76b2007-10-21 22:27:241787 if (st->codec->codec_id == CODEC_ID_RA_288)
1788 for (x=0; x<h/2; x++)
Aurelien Jacobs2cbc8812008-08-05 00:40:311789 memcpy(track->audio.buf+x*2*w+y*cfs,
Aurelien Jacobsba8a76b2007-10-21 22:27:241790 data+x*cfs, cfs);
1791 else
1792 for (x=0; x<w/sps; x++)
Aurelien Jacobs2cbc8812008-08-05 00:40:311793 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
Aurelien Jacobseabb8ba2007-06-04 22:19:171794
Aurelien Jacobs2cbc8812008-08-05 00:40:311795 if (++track->audio.sub_packet_cnt >= h) {
1796 track->audio.sub_packet_cnt = 0;
1797 track->audio.pkt_cnt = h*w / a;
Aurelien Jacobseabb8ba2007-06-04 22:19:171798 }
Aurelien Jacobsba8a76b2007-10-21 22:27:241799 }
Aurelien Jacobs2cbc8812008-08-05 00:40:311800 while (track->audio.pkt_cnt) {
Aurelien Jacobs77abe5e2007-06-04 22:21:291801 pkt = av_mallocz(sizeof(AVPacket));
Aurelien Jacobsba8a76b2007-10-21 22:27:241802 av_new_packet(pkt, a);
Aurelien Jacobs2cbc8812008-08-05 00:40:311803 memcpy(pkt->data, track->audio.buf
1804 + a * (h*w / a - track->audio.pkt_cnt--), a);
Aurelien Jacobs77abe5e2007-06-04 22:21:291805 pkt->pos = pos;
Aurelien Jacobsfc4d3352008-08-05 00:40:061806 pkt->stream_index = st->index;
Aurelien Jacobs77abe5e2007-06-04 22:21:291807 matroska_queue_packet(matroska, pkt);
Aurelien Jacobseabb8ba2007-06-04 22:19:171808 }
Aurelien Jacobsba8a76b2007-10-21 22:27:241809 } else {
Aurelien Jacobs2cbc8812008-08-05 00:40:311810 MatroskaTrackEncoding *encodings = track->encodings.elem;
Evgeniy Stepanov935ec5a2008-06-22 15:49:441811 int offset = 0, pkt_size = lace_size[n];
Aurelien Jacobsde3230f2008-05-09 01:53:591812 uint8_t *pkt_data = data;
David Conradb061d892007-06-04 22:10:541813
Aurelien Jacobs2cbc8812008-08-05 00:40:311814 if (encodings && encodings->scope & 1) {
Aurelien Jacobs8f35a2c2008-08-05 00:41:221815 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
Evgeniy Stepanov935ec5a2008-06-22 15:49:441816 if (offset < 0)
1817 continue;
Aurelien Jacobs53a1e822008-05-08 21:47:311818 }
1819
Aurelien Jacobsba8a76b2007-10-21 22:27:241820 pkt = av_mallocz(sizeof(AVPacket));
1821 /* XXX: prevent data copy... */
Aurelien Jacobsde3230f2008-05-09 01:53:591822 if (av_new_packet(pkt, pkt_size+offset) < 0) {
Aurelien Jacobs34ae4092008-06-02 23:27:141823 av_free(pkt);
Aurelien Jacobsba8a76b2007-10-21 22:27:241824 res = AVERROR(ENOMEM);
1825 n = laces-1;
1826 break;
1827 }
Aurelien Jacobs53a1e822008-05-08 21:47:311828 if (offset)
Aurelien Jacobs2cbc8812008-08-05 00:40:311829 memcpy (pkt->data, encodings->compression.settings.data, offset);
Aurelien Jacobsde3230f2008-05-09 01:53:591830 memcpy (pkt->data+offset, pkt_data, pkt_size);
Aurelien Jacobsba8a76b2007-10-21 22:27:241831
Aurelien Jacobs51e1cc12008-06-22 15:46:361832 if (pkt_data != data)
1833 av_free(pkt_data);
1834
Aurelien Jacobsba8a76b2007-10-21 22:27:241835 if (n == 0)
1836 pkt->flags = is_keyframe;
Aurelien Jacobsfc4d3352008-08-05 00:40:061837 pkt->stream_index = st->index;
Aurelien Jacobsba8a76b2007-10-21 22:27:241838
1839 pkt->pts = timecode;
1840 pkt->pos = pos;
1841 pkt->duration = duration;
1842
1843 matroska_queue_packet(matroska, pkt);
1844 }
1845
1846 if (timecode != AV_NOPTS_VALUE)
1847 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
David Conradb061d892007-06-04 22:10:541848 data += lace_size[n];
1849 }
1850 }
1851
1852 av_free(lace_size);
David Conradb061d892007-06-04 22:10:541853 return res;
1854}
1855
1856static int
1857matroska_parse_cluster (MatroskaDemuxContext *matroska)
1858{
Aurelien Jacobs209472b2008-08-05 00:41:051859 MatroskaCluster cluster = { 0 };
1860 EbmlList *blocks_list;
1861 MatroskaBlock *blocks;
1862 int i, res = ebml_parse(matroska, matroska_clusters, &cluster, 0, 1);
1863 blocks_list = &cluster.blocks;
1864 blocks = blocks_list->elem;
1865 for (i=0; !res && i<blocks_list->nb_elem; i++)
1866 if (blocks[i].bin.size > 0)
1867 res=matroska_parse_block(matroska,
1868 blocks[i].bin.data, blocks[i].bin.size,
1869 blocks[i].bin.pos, cluster.timecode,
1870 blocks[i].duration, !blocks[i].reference);
1871 ebml_free(matroska_cluster, &cluster);
David Conradb061d892007-06-04 22:10:541872 return res;
1873}
1874
1875static int
1876matroska_read_packet (AVFormatContext *s,
1877 AVPacket *pkt)
1878{
1879 MatroskaDemuxContext *matroska = s->priv_data;
David Conradb061d892007-06-04 22:10:541880
1881 /* Read stream until we have a packet queued. */
1882 while (matroska_deliver_packet(matroska, pkt)) {
1883
1884 /* Have we already reached the end? */
1885 if (matroska->done)
Panagiotis Issaris6f3e0b22007-07-19 15:23:321886 return AVERROR(EIO);
David Conradb061d892007-06-04 22:10:541887
Aurelien Jacobs209472b2008-08-05 00:41:051888 if (matroska_parse_cluster(matroska) < 0)
David Conradb061d892007-06-04 22:10:541889 matroska->done = 1;
1890 }
1891
1892 return 0;
1893}
1894
1895static int
1896matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
1897 int flags)
1898{
1899 MatroskaDemuxContext *matroska = s->priv_data;
1900 AVStream *st = s->streams[stream_index];
1901 int index;
1902
1903 /* find index entry */
1904 index = av_index_search_timestamp(st, timestamp, flags);
1905 if (index < 0)
1906 return 0;
1907
Aurelien Jacobs243cc4c2007-12-29 18:35:381908 matroska_clear_queue(matroska);
1909
David Conradb061d892007-06-04 22:10:541910 /* do the seek */
Björn Axelsson899681c2007-11-21 07:41:001911 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
David Conradb061d892007-06-04 22:10:541912 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1913 matroska->skip_to_stream = st;
David Conradb061d892007-06-04 22:10:541914 matroska->peek_id = 0;
Joakim Platede6a9a22008-06-11 19:54:171915 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
David Conradb061d892007-06-04 22:10:541916 return 0;
1917}
1918
1919static int
1920matroska_read_close (AVFormatContext *s)
1921{
1922 MatroskaDemuxContext *matroska = s->priv_data;
Aurelien Jacobs2cbc8812008-08-05 00:40:311923 MatroskaTrack *tracks = matroska->tracks.elem;
Aurelien Jacobs70109c02008-08-05 00:41:131924 int n;
David Conradb061d892007-06-04 22:10:541925
Aurelien Jacobs34c9c1b2007-12-29 18:32:471926 matroska_clear_queue(matroska);
David Conradb061d892007-06-04 22:10:541927
Aurelien Jacobs2cbc8812008-08-05 00:40:311928 for (n=0; n < matroska->tracks.nb_elem; n++)
1929 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1930 av_free(tracks[n].audio.buf);
Aurelien Jacobsce6f28b2008-08-05 00:40:581931 ebml_free(matroska_segment, matroska);
David Conradb061d892007-06-04 22:10:541932
1933 return 0;
1934}
1935
1936AVInputFormat matroska_demuxer = {
1937 "matroska",
Stefano Sabatinibde15e72008-06-03 16:20:541938 NULL_IF_CONFIG_SMALL("Matroska file format"),
David Conradb061d892007-06-04 22:10:541939 sizeof(MatroskaDemuxContext),
1940 matroska_probe,
1941 matroska_read_header,
1942 matroska_read_packet,
1943 matroska_read_close,
1944 matroska_read_seek,
1945};