2 * Matroska file demuxer (no muxer yet)
3 * Copyright (c) 2003-2004 The ffmpeg Project
5 * This file is part of FFmpeg.
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.
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.
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
24 * Matroska file demuxer
25 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * Specs available on the matroska project page:
28 * http://www.matroska.org/.
32 /* For codec_get_id(). */
36 #include "libavcodec/mpeg4audio.h"
37 #include "libavutil/intfloat_readwrite.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/lzo.h"
59 typedef const struct EbmlSyntax {
68 const struct EbmlSyntax *n;
88 uint64_t doctype_version;
94 } MatroskaTrackCompression;
99 MatroskaTrackCompression compression;
100 } MatroskaTrackEncoding;
104 uint64_t display_width;
105 uint64_t display_height;
106 uint64_t pixel_width;
107 uint64_t pixel_height;
109 } MatroskaTrackVideo;
113 double out_samplerate;
117 /* real audio header (extracted from extradata) */
125 } MatroskaTrackAudio;
134 uint64_t default_duration;
135 uint64_t flag_default;
136 MatroskaTrackVideo video;
137 MatroskaTrackAudio audio;
147 } MatroskaAttachement;
177 AVFormatContext *ctx;
181 MatroskaLevel levels[EBML_MAX_DEPTH];
188 EbmlList attachments;
193 /* num_streams is the number of streams that av_new_stream() was called
194 * for ( = that are available to the calling program). */
197 /* byte position of the segment inside the stream */
198 offset_t segment_start;
200 /* The packet queue. */
207 /* What to skip before effectively reading a packet. */
208 int skip_to_keyframe;
209 AVStream *skip_to_stream;
210 } MatroskaDemuxContext;
223 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
225 static EbmlSyntax ebml_header[] = {
226 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
227 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
228 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
229 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
230 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
231 { EBML_ID_EBMLVERSION, EBML_NONE },
232 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
233 { EBML_ID_VOID, EBML_NONE },
237 static EbmlSyntax ebml_syntax[] = {
238 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
242 static EbmlSyntax matroska_info[] = {
243 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
244 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
245 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
246 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
247 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
248 { MATROSKA_ID_DATEUTC, EBML_NONE },
249 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
250 { EBML_ID_VOID, EBML_NONE },
254 static EbmlSyntax matroska_track_video[] = {
255 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
256 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
257 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
258 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
259 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
260 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
261 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
262 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
263 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
264 { EBML_ID_VOID, EBML_NONE },
268 static EbmlSyntax matroska_track_audio[] = {
269 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
270 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
271 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
272 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
273 { EBML_ID_VOID, EBML_NONE },
277 static EbmlSyntax matroska_track_encoding_compression[] = {
278 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
279 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
280 { EBML_ID_VOID, EBML_NONE },
284 static EbmlSyntax matroska_track_encoding[] = {
285 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
286 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
287 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
288 { EBML_ID_VOID, EBML_NONE },
292 static EbmlSyntax matroska_track_encodings[] = {
293 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
294 { EBML_ID_VOID, EBML_NONE },
298 static EbmlSyntax matroska_track[] = {
299 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
300 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
301 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
302 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
303 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
304 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
305 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
306 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
307 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
308 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
309 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
310 { MATROSKA_ID_TRACKUID, EBML_NONE },
311 { MATROSKA_ID_TRACKNAME, EBML_NONE },
312 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
313 { MATROSKA_ID_TRACKFLAGFORCED, EBML_NONE },
314 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
315 { MATROSKA_ID_CODECNAME, EBML_NONE },
316 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
317 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
318 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
319 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
320 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
321 { EBML_ID_VOID, EBML_NONE },
325 static EbmlSyntax matroska_tracks[] = {
326 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
327 { EBML_ID_VOID, EBML_NONE },
331 static EbmlSyntax matroska_attachment[] = {
332 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
333 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
334 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
335 { MATROSKA_ID_FILEUID, EBML_NONE },
336 { EBML_ID_VOID, EBML_NONE },
340 static EbmlSyntax matroska_attachments[] = {
341 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
342 { EBML_ID_VOID, EBML_NONE },
346 static EbmlSyntax matroska_chapter_display[] = {
347 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
348 { EBML_ID_VOID, EBML_NONE },
352 static EbmlSyntax matroska_chapter_entry[] = {
353 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
354 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
355 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
356 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
357 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
358 { EBML_ID_VOID, EBML_NONE },
362 static EbmlSyntax matroska_chapter[] = {
363 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
364 { MATROSKA_ID_EDITIONUID, EBML_NONE },
365 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
366 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
367 { EBML_ID_VOID, EBML_NONE },
371 static EbmlSyntax matroska_chapters[] = {
372 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
373 { EBML_ID_VOID, EBML_NONE },
377 static EbmlSyntax matroska_index_pos[] = {
378 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
379 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
380 { EBML_ID_VOID, EBML_NONE },
384 static EbmlSyntax matroska_index_entry[] = {
385 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
386 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
387 { EBML_ID_VOID, EBML_NONE },
391 static EbmlSyntax matroska_index[] = {
392 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
393 { EBML_ID_VOID, EBML_NONE },
397 static EbmlSyntax matroska_tags[] = {
398 { EBML_ID_VOID, EBML_NONE },
402 static EbmlSyntax matroska_seekhead_entry[] = {
403 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
404 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
405 { EBML_ID_VOID, EBML_NONE },
409 static EbmlSyntax matroska_seekhead[] = {
410 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
411 { EBML_ID_VOID, EBML_NONE },
415 static EbmlSyntax matroska_segment[] = {
416 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
417 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
418 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
419 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
420 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
421 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
422 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
423 { MATROSKA_ID_CLUSTER, EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
424 { EBML_ID_VOID, EBML_NONE },
428 static EbmlSyntax matroska_segments[] = {
429 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
433 static EbmlSyntax matroska_blockgroup[] = {
434 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
435 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
436 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
437 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
438 { EBML_ID_VOID, EBML_NONE },
442 static EbmlSyntax matroska_cluster[] = {
443 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
444 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
445 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
446 { EBML_ID_VOID, EBML_NONE },
450 static EbmlSyntax matroska_clusters[] = {
451 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
456 * Return: whether we reached the end of a level in the hierarchy or not
458 static int ebml_level_end(MatroskaDemuxContext *matroska)
460 ByteIOContext *pb = matroska->ctx->pb;
461 offset_t pos = url_ftell(pb);
463 if (matroska->num_levels > 0) {
464 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
465 if (pos - level->start >= level->length) {
466 matroska->num_levels--;
474 * Read: an "EBML number", which is defined as a variable-length
475 * array of bytes. The first byte indicates the length by giving a
476 * number of 0-bits followed by a one. The position of the first
477 * "one" bit inside the first byte indicates the length of this
479 * Returns: num. of bytes read. < 0 on error.
481 static int ebml_read_num(MatroskaDemuxContext *matroska,
482 int max_size, uint64_t *number)
484 ByteIOContext *pb = matroska->ctx->pb;
485 int len_mask = 0x80, read = 1, n = 1;
488 /* the first byte tells us the length in bytes - get_byte() can normally
489 * return 0, but since that's not a valid first ebmlID byte, we can
490 * use it safely here to catch EOS. */
491 if (!(total = get_byte(pb))) {
492 /* we might encounter EOS here */
494 offset_t pos = url_ftell(pb);
495 av_log(matroska->ctx, AV_LOG_ERROR,
496 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
499 return AVERROR(EIO); /* EOS or actual I/O error */
502 /* get the length of the EBML number */
503 while (read <= max_size && !(total & len_mask)) {
507 if (read > max_size) {
508 offset_t pos = url_ftell(pb) - 1;
509 av_log(matroska->ctx, AV_LOG_ERROR,
510 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
511 (uint8_t) total, pos, pos);
512 return AVERROR_INVALIDDATA;
515 /* read out length */
518 total = (total << 8) | get_byte(pb);
526 * Read: the element content data ID.
527 * 0 is success, < 0 is failure.
529 static int ebml_read_element_id(MatroskaDemuxContext *matroska, uint32_t *id)
534 /* read out the "EBML number", include tag in ID */
535 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
537 *id = total | (1 << (read * 7));
543 * Read the next element as an unsigned int.
544 * 0 is success, < 0 is failure.
546 static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
550 if (size < 1 || size > 8)
551 return AVERROR_INVALIDDATA;
553 /* big-endian ordening; build up number */
556 *num = (*num << 8) | get_byte(pb);
562 * Read the next element as a float.
563 * 0 is success, < 0 is failure.
565 static int ebml_read_float(ByteIOContext *pb, int size, double *num)
568 *num= av_int2flt(get_be32(pb));
570 *num= av_int2dbl(get_be64(pb));
572 return AVERROR_INVALIDDATA;
578 * Read the next element as an ASCII string.
579 * 0 is success, < 0 is failure.
581 static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
584 /* ebml strings are usually not 0-terminated, so we allocate one
585 * byte more, read the string and NULL-terminate it ourselves. */
586 if (!(*str = av_malloc(size + 1)))
587 return AVERROR(ENOMEM);
588 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
598 * Read the next element, but only the header. The contents
599 * are supposed to be sub-elements which can be read separately.
600 * 0 is success, < 0 is failure.
602 static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
604 ByteIOContext *pb = matroska->ctx->pb;
605 MatroskaLevel *level;
607 if (matroska->num_levels >= EBML_MAX_DEPTH) {
608 av_log(matroska->ctx, AV_LOG_ERROR,
609 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
610 return AVERROR(ENOSYS);
613 level = &matroska->levels[matroska->num_levels++];
614 level->start = url_ftell(pb);
615 level->length = length;
621 * Read the next element as binary data.
622 * 0 is success, < 0 is failure.
624 static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
627 if (!(bin->data = av_malloc(length)))
628 return AVERROR(ENOMEM);
631 bin->pos = url_ftell(pb);
632 if (get_buffer(pb, bin->data, length) != length)
639 * Read signed/unsigned "EBML" numbers.
640 * Return: number of bytes processed, < 0 on error.
641 * XXX: use ebml_read_num().
643 static int matroska_ebmlnum_uint(uint8_t *data, uint32_t size, uint64_t *num)
645 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
649 return AVERROR_INVALIDDATA;
652 while (read <= 8 && !(total & len_mask)) {
657 return AVERROR_INVALIDDATA;
659 if ((total &= (len_mask - 1)) == len_mask - 1)
662 return AVERROR_INVALIDDATA;
666 total = (total << 8) | data[n];
679 * Same as above, but signed.
681 static int matroska_ebmlnum_sint(uint8_t *data, uint32_t size, int64_t *num)
686 /* read as unsigned number first */
687 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
690 /* make signed (weird way) */
691 if (unum == (uint64_t)-1)
694 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
700 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
703 MatroskaTrack *tracks = matroska->tracks.elem;
706 for (i=0; i < matroska->tracks.nb_elem; i++)
707 if (tracks[i].num == num)
710 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
716 * Put one packet in an application-supplied AVPacket struct.
717 * Returns 0 on success or -1 on failure.
719 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
722 if (matroska->num_packets > 0) {
723 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
724 av_free(matroska->packets[0]);
725 if (matroska->num_packets > 1) {
726 memmove(&matroska->packets[0], &matroska->packets[1],
727 (matroska->num_packets - 1) * sizeof(AVPacket *));
729 av_realloc(matroska->packets, (matroska->num_packets - 1) *
732 av_freep(&matroska->packets);
734 matroska->num_packets--;
742 * Put a packet into our internal queue. Will be delivered to the
743 * user/application during the next get_packet() call.
745 static void matroska_queue_packet(MatroskaDemuxContext *matroska, AVPacket *pkt)
748 av_realloc(matroska->packets, (matroska->num_packets + 1) *
750 matroska->packets[matroska->num_packets] = pkt;
751 matroska->num_packets++;
755 * Free all packets in our internal queue.
757 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
759 if (matroska->packets) {
761 for (n = 0; n < matroska->num_packets; n++) {
762 av_free_packet(matroska->packets[n]);
763 av_free(matroska->packets[n]);
765 av_free(matroska->packets);
766 matroska->packets = NULL;
767 matroska->num_packets = 0;
775 static int matroska_probe(AVProbeData *p)
778 int len_mask = 0x80, size = 1, n = 1;
779 char probe_data[] = "matroska";
782 if (AV_RB32(p->buf) != EBML_ID_HEADER)
785 /* length of header */
787 while (size <= 8 && !(total & len_mask)) {
793 total &= (len_mask - 1);
795 total = (total << 8) | p->buf[4 + n++];
797 /* does the probe data contain the whole header? */
798 if (p->buf_size < 4 + size + total)
801 /* the header must contain the document type 'matroska'. For now,
802 * we don't parse the whole header but simply check for the
803 * availability of that array of characters inside the header.
804 * Not fully fool-proof, but good enough. */
805 for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
806 if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
807 return AVPROBE_SCORE_MAX;
812 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
813 uint32_t id, void *data);
814 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
817 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
818 EbmlSyntax *syntax, void *data)
820 ByteIOContext *pb = matroska->ctx->pb;
821 uint32_t id = syntax->id;
825 data = (char *)data + syntax->data_offset;
826 if (syntax->list_elem_size) {
827 EbmlList *list = data;
828 list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
829 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
830 memset(data, 0, syntax->list_elem_size);
834 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
835 if ((res = ebml_read_num(matroska, 8, &length)) < 0)
838 switch (syntax->type) {
839 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
840 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
842 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
843 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
844 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
846 if (id == MATROSKA_ID_SEGMENT)
847 matroska->segment_start = url_ftell(matroska->ctx->pb);
848 return ebml_parse_nest(matroska, syntax->def.n, data);
849 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
850 case EBML_STOP: *(int *)data = 1; return 1;
851 default: url_fskip(pb, length); return 0;
853 if (res == AVERROR_INVALIDDATA)
854 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
855 else if (res == AVERROR(EIO))
856 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
860 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
861 uint32_t id, void *data)
864 for (i=0; syntax[i].id; i++)
865 if (id == syntax[i].id)
868 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
869 return ebml_parse_elem(matroska, &syntax[i], data);
872 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
876 int res = ebml_read_element_id(matroska, &id);
877 return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
880 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
885 for (i=0; syntax[i].id; i++)
886 switch (syntax[i].type) {
888 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
891 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
895 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
899 while (!res && !ebml_level_end(matroska))
900 res = ebml_parse(matroska, syntax, data);
905 static void ebml_free(EbmlSyntax *syntax, void *data)
908 for (i=0; syntax[i].id; i++) {
909 void *data_off = (char *)data + syntax[i].data_offset;
910 switch (syntax[i].type) {
912 case EBML_UTF8: av_freep(data_off); break;
913 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
915 if (syntax[i].list_elem_size) {
916 EbmlList *list = data_off;
917 char *ptr = list->elem;
918 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
919 ebml_free(syntax[i].def.n, ptr);
922 ebml_free(syntax[i].def.n, data_off);
928 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
929 MatroskaTrack *track)
931 MatroskaTrackEncoding *encodings = track->encodings.elem;
932 uint8_t* data = *buf;
933 int isize = *buf_size;
934 uint8_t* pkt_data = NULL;
935 int pkt_size = isize;
939 switch (encodings[0].compression.algo) {
940 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
941 return encodings[0].compression.settings.size;
942 case MATROSKA_TRACK_ENCODING_COMP_LZO:
944 olen = pkt_size *= 3;
945 pkt_data = av_realloc(pkt_data,
946 pkt_size+LZO_OUTPUT_PADDING);
947 result = lzo1x_decode(pkt_data, &olen, data, &isize);
948 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
954 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
955 z_stream zstream = {0};
956 if (inflateInit(&zstream) != Z_OK)
958 zstream.next_in = data;
959 zstream.avail_in = isize;
962 pkt_data = av_realloc(pkt_data, pkt_size);
963 zstream.avail_out = pkt_size - zstream.total_out;
964 zstream.next_out = pkt_data + zstream.total_out;
965 result = inflate(&zstream, Z_NO_FLUSH);
966 } while (result==Z_OK && pkt_size<10000000);
967 pkt_size = zstream.total_out;
968 inflateEnd(&zstream);
969 if (result != Z_STREAM_END)
975 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
976 bz_stream bzstream = {0};
977 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
979 bzstream.next_in = data;
980 bzstream.avail_in = isize;
983 pkt_data = av_realloc(pkt_data, pkt_size);
984 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
985 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
986 result = BZ2_bzDecompress(&bzstream);
987 } while (result==BZ_OK && pkt_size<10000000);
988 pkt_size = bzstream.total_out_lo32;
989 BZ2_bzDecompressEnd(&bzstream);
990 if (result != BZ_STREAM_END)
998 *buf_size = pkt_size;
1005 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1007 EbmlList *seekhead_list = &matroska->seekhead;
1008 MatroskaSeekhead *seekhead = seekhead_list->elem;
1009 uint32_t level_up = matroska->level_up;
1010 offset_t before_pos = url_ftell(matroska->ctx->pb);
1011 MatroskaLevel level;
1014 for (i=0; i<seekhead_list->nb_elem; i++) {
1015 offset_t offset = seekhead[i].pos + matroska->segment_start;
1017 if (seekhead[i].pos <= before_pos
1018 || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1019 || seekhead[i].id == MATROSKA_ID_CLUSTER)
1023 if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1026 /* we don't want to lose our seekhead level, so we add
1027 * a dummy. This is a crude hack. */
1028 if (matroska->num_levels == EBML_MAX_DEPTH) {
1029 av_log(matroska->ctx, AV_LOG_INFO,
1030 "Max EBML element depth (%d) reached, "
1031 "cannot parse further.\n", EBML_MAX_DEPTH);
1036 level.length = (uint64_t)-1;
1037 matroska->levels[matroska->num_levels] = level;
1038 matroska->num_levels++;
1040 ebml_parse(matroska, matroska_segment, matroska);
1042 /* remove dummy level */
1043 while (matroska->num_levels) {
1044 uint64_t length = matroska->levels[--matroska->num_levels].length;
1045 if (length == (uint64_t)-1)
1051 url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1052 matroska->level_up = level_up;
1055 static int matroska_aac_profile(char *codec_id)
1057 static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1060 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1061 if (strstr(codec_id, aac_profiles[profile]))
1066 static int matroska_aac_sri(int samplerate)
1070 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1071 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1076 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1078 MatroskaDemuxContext *matroska = s->priv_data;
1079 EbmlList *attachements_list = &matroska->attachments;
1080 MatroskaAttachement *attachements;
1081 EbmlList *chapters_list = &matroska->chapters;
1082 MatroskaChapter *chapters;
1083 MatroskaTrack *tracks;
1084 EbmlList *index_list;
1085 MatroskaIndex *index;
1092 /* First read the EBML header. */
1093 if (ebml_parse(matroska, ebml_syntax, &ebml)
1094 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1095 || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1096 || ebml.doctype_version > 2) {
1097 av_log(matroska->ctx, AV_LOG_ERROR,
1098 "EBML header using unsupported features\n"
1099 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1100 ebml.version, ebml.doctype, ebml.doctype_version);
1101 return AVERROR_NOFMT;
1103 ebml_free(ebml_syntax, &ebml);
1105 /* The next thing is a segment. */
1106 if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1108 matroska_execute_seekhead(matroska);
1110 if (matroska->duration)
1111 matroska->ctx->duration = matroska->duration * matroska->time_scale
1112 * 1000 / AV_TIME_BASE;
1113 if (matroska->title)
1114 strncpy(matroska->ctx->title, matroska->title,
1115 sizeof(matroska->ctx->title)-1);
1117 tracks = matroska->tracks.elem;
1118 for (i=0; i < matroska->tracks.nb_elem; i++) {
1119 MatroskaTrack *track = &tracks[i];
1120 enum CodecID codec_id = CODEC_ID_NONE;
1121 EbmlList *encodings_list = &tracks->encodings;
1122 MatroskaTrackEncoding *encodings = encodings_list->elem;
1123 uint8_t *extradata = NULL;
1124 int extradata_size = 0;
1125 int extradata_offset = 0;
1127 /* Apply some sanity checks. */
1128 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1129 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1130 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1131 av_log(matroska->ctx, AV_LOG_INFO,
1132 "Unknown or unsupported track type %"PRIu64"\n",
1136 if (track->codec_id == NULL)
1139 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1140 if (!track->default_duration)
1141 track->default_duration = 1000000000/track->video.frame_rate;
1142 if (!track->video.display_width)
1143 track->video.display_width = track->video.pixel_width;
1144 if (!track->video.display_height)
1145 track->video.display_height = track->video.pixel_height;
1146 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1147 if (!track->audio.out_samplerate)
1148 track->audio.out_samplerate = track->audio.samplerate;
1150 if (encodings_list->nb_elem > 1) {
1151 av_log(matroska->ctx, AV_LOG_ERROR,
1152 "Multiple combined encodings no supported");
1153 } else if (encodings_list->nb_elem == 1) {
1154 if (encodings[0].type ||
1155 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1157 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1160 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1162 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1163 encodings[0].scope = 0;
1164 av_log(matroska->ctx, AV_LOG_ERROR,
1165 "Unsupported encoding type");
1166 } else if (track->codec_priv.size && encodings[0].scope&2) {
1167 uint8_t *codec_priv = track->codec_priv.data;
1168 int offset = matroska_decode_buffer(&track->codec_priv.data,
1169 &track->codec_priv.size,
1172 track->codec_priv.data = NULL;
1173 track->codec_priv.size = 0;
1174 av_log(matroska->ctx, AV_LOG_ERROR,
1175 "Failed to decode codec private data\n");
1176 } else if (offset > 0) {
1177 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1178 memcpy(track->codec_priv.data,
1179 encodings[0].compression.settings.data, offset);
1180 memcpy(track->codec_priv.data+offset, codec_priv,
1181 track->codec_priv.size);
1182 track->codec_priv.size += offset;
1184 if (codec_priv != track->codec_priv.data)
1185 av_free(codec_priv);
1189 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1190 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1191 strlen(ff_mkv_codec_tags[j].str))){
1192 codec_id= ff_mkv_codec_tags[j].id;
1197 st = track->stream = av_new_stream(s, matroska->num_streams++);
1199 return AVERROR(ENOMEM);
1201 if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)
1202 && track->codec_priv.size >= 40
1203 && track->codec_priv.data != NULL) {
1204 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1205 codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1206 } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_AUDIO_ACM)
1207 && track->codec_priv.size >= 18
1208 && track->codec_priv.data != NULL) {
1209 uint16_t tag = AV_RL16(track->codec_priv.data);
1210 codec_id = codec_get_id(codec_wav_tags, tag);
1211 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1212 && (track->codec_priv.size >= 86)
1213 && (track->codec_priv.data != NULL)) {
1214 track->video.fourcc = AV_RL32(track->codec_priv.data);
1215 codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1216 } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1217 int profile = matroska_aac_profile(track->codec_id);
1218 int sri = matroska_aac_sri(track->audio.samplerate);
1219 extradata = av_malloc(5);
1220 if (extradata == NULL)
1221 return AVERROR(ENOMEM);
1222 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1223 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1224 if (strstr(track->codec_id, "SBR")) {
1225 sri = matroska_aac_sri(track->audio.out_samplerate);
1226 extradata[2] = 0x56;
1227 extradata[3] = 0xE5;
1228 extradata[4] = 0x80 | (sri<<3);
1232 } else if (codec_id == CODEC_ID_TTA) {
1234 extradata_size = 30;
1235 extradata = av_mallocz(extradata_size);
1236 if (extradata == NULL)
1237 return AVERROR(ENOMEM);
1238 init_put_byte(&b, extradata, extradata_size, 1,
1239 NULL, NULL, NULL, NULL);
1240 put_buffer(&b, "TTA1", 4);
1242 put_le16(&b, track->audio.channels);
1243 put_le16(&b, track->audio.bitdepth);
1244 put_le32(&b, track->audio.out_samplerate);
1245 put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1246 } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1247 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1248 extradata_offset = 26;
1249 track->codec_priv.size -= extradata_offset;
1250 } else if (codec_id == CODEC_ID_RA_144) {
1251 track->audio.out_samplerate = 8000;
1252 track->audio.channels = 1;
1253 } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1254 codec_id == CODEC_ID_ATRAC3) {
1257 init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1258 0, NULL, NULL, NULL, NULL);
1260 track->audio.coded_framesize = get_be32(&b);
1262 track->audio.sub_packet_h = get_be16(&b);
1263 track->audio.frame_size = get_be16(&b);
1264 track->audio.sub_packet_size = get_be16(&b);
1265 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1266 if (codec_id == CODEC_ID_RA_288) {
1267 st->codec->block_align = track->audio.coded_framesize;
1268 track->codec_priv.size = 0;
1270 st->codec->block_align = track->audio.sub_packet_size;
1271 extradata_offset = 78;
1272 track->codec_priv.size -= extradata_offset;
1276 if (codec_id == CODEC_ID_NONE)
1277 av_log(matroska->ctx, AV_LOG_INFO,
1278 "Unknown/unsupported CodecID %s.\n", track->codec_id);
1280 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1282 st->codec->codec_id = codec_id;
1284 if (strcmp(track->language, "und"))
1285 av_strlcpy(st->language, track->language, 4);
1287 if (track->flag_default)
1288 st->disposition |= AV_DISPOSITION_DEFAULT;
1290 if (track->default_duration)
1291 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1292 track->default_duration, 1000000000, 30000);
1295 st->codec->extradata = extradata;
1296 st->codec->extradata_size = extradata_size;
1297 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1298 st->codec->extradata = av_malloc(track->codec_priv.size);
1299 if(st->codec->extradata == NULL)
1300 return AVERROR(ENOMEM);
1301 st->codec->extradata_size = track->codec_priv.size;
1302 memcpy(st->codec->extradata,
1303 track->codec_priv.data + extradata_offset,
1304 track->codec_priv.size);
1307 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1308 st->codec->codec_type = CODEC_TYPE_VIDEO;
1309 st->codec->codec_tag = track->video.fourcc;
1310 st->codec->width = track->video.pixel_width;
1311 st->codec->height = track->video.pixel_height;
1312 av_reduce(&st->codec->sample_aspect_ratio.num,
1313 &st->codec->sample_aspect_ratio.den,
1314 st->codec->height * track->video.display_width,
1315 st->codec-> width * track->video.display_height,
1317 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1318 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1319 st->codec->codec_type = CODEC_TYPE_AUDIO;
1320 st->codec->sample_rate = track->audio.out_samplerate;
1321 st->codec->channels = track->audio.channels;
1322 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1323 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1327 attachements = attachements_list->elem;
1328 for (j=0; j<attachements_list->nb_elem; j++) {
1329 if (!(attachements[j].filename && attachements[j].mime &&
1330 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1331 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1333 AVStream *st = av_new_stream(s, matroska->num_streams++);
1336 st->filename = av_strdup(attachements[j].filename);
1337 st->codec->codec_id = CODEC_ID_NONE;
1338 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1339 st->codec->extradata = av_malloc(attachements[j].bin.size);
1340 if(st->codec->extradata == NULL)
1342 st->codec->extradata_size = attachements[j].bin.size;
1343 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1345 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1346 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1347 strlen(ff_mkv_mime_tags[i].str))) {
1348 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1355 chapters = chapters_list->elem;
1356 for (i=0; i<chapters_list->nb_elem; i++)
1357 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1358 ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1359 chapters[i].start, chapters[i].end,
1362 index_list = &matroska->index;
1363 index = index_list->elem;
1364 for (i=0; i<index_list->nb_elem; i++) {
1365 EbmlList *pos_list = &index[i].pos;
1366 MatroskaIndexPos *pos = pos_list->elem;
1367 for (j=0; j<pos_list->nb_elem; j++) {
1368 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1370 if (track && track->stream)
1371 av_add_index_entry(track->stream,
1372 pos[j].pos + matroska->segment_start,
1373 index[i].time*matroska->time_scale/AV_TIME_BASE,
1374 0, 0, AVINDEX_KEYFRAME);
1381 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1382 int size, int64_t pos, uint64_t cluster_time,
1383 uint64_t duration, int is_keyframe)
1385 MatroskaTrack *track;
1390 uint32_t *lace_size = NULL;
1391 int n, flags, laces = 0;
1394 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1395 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1401 track = matroska_find_track_by_num(matroska, num);
1402 if (size <= 3 || !track || !track->stream) {
1403 av_log(matroska->ctx, AV_LOG_INFO,
1404 "Invalid stream %"PRIu64" or size %u\n", num, size);
1408 if (st->discard >= AVDISCARD_ALL)
1410 if (duration == AV_NOPTS_VALUE)
1411 duration = track->default_duration / matroska->time_scale;
1413 block_time = AV_RB16(data);
1417 if (is_keyframe == -1)
1418 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1420 if (matroska->skip_to_keyframe) {
1421 if (!is_keyframe || st != matroska->skip_to_stream)
1423 matroska->skip_to_keyframe = 0;
1426 switch ((flags & 0x06) >> 1) {
1427 case 0x0: /* no lacing */
1429 lace_size = av_mallocz(sizeof(int));
1430 lace_size[0] = size;
1433 case 0x1: /* xiph lacing */
1434 case 0x2: /* fixed-size lacing */
1435 case 0x3: /* EBML lacing */
1436 assert(size>0); // size <=3 is checked before size-=3 above
1437 laces = (*data) + 1;
1440 lace_size = av_mallocz(laces * sizeof(int));
1442 switch ((flags & 0x06) >> 1) {
1443 case 0x1: /* xiph lacing */ {
1446 for (n = 0; res == 0 && n < laces - 1; n++) {
1453 lace_size[n] += temp;
1459 total += lace_size[n];
1461 lace_size[n] = size - total;
1465 case 0x2: /* fixed-size lacing */
1466 for (n = 0; n < laces; n++)
1467 lace_size[n] = size / laces;
1470 case 0x3: /* EBML lacing */ {
1472 n = matroska_ebmlnum_uint(data, size, &num);
1474 av_log(matroska->ctx, AV_LOG_INFO,
1475 "EBML block data error\n");
1480 total = lace_size[0] = num;
1481 for (n = 1; res == 0 && n < laces - 1; n++) {
1484 r = matroska_ebmlnum_sint (data, size, &snum);
1486 av_log(matroska->ctx, AV_LOG_INFO,
1487 "EBML block data error\n");
1492 lace_size[n] = lace_size[n - 1] + snum;
1493 total += lace_size[n];
1495 lace_size[n] = size - total;
1503 uint64_t timecode = AV_NOPTS_VALUE;
1505 if (cluster_time != (uint64_t)-1
1506 && (block_time >= 0 || cluster_time >= -block_time))
1507 timecode = cluster_time + block_time;
1509 for (n = 0; n < laces; n++) {
1510 if (st->codec->codec_id == CODEC_ID_RA_288 ||
1511 st->codec->codec_id == CODEC_ID_COOK ||
1512 st->codec->codec_id == CODEC_ID_ATRAC3) {
1513 int a = st->codec->block_align;
1514 int sps = track->audio.sub_packet_size;
1515 int cfs = track->audio.coded_framesize;
1516 int h = track->audio.sub_packet_h;
1517 int y = track->audio.sub_packet_cnt;
1518 int w = track->audio.frame_size;
1521 if (!track->audio.pkt_cnt) {
1522 if (st->codec->codec_id == CODEC_ID_RA_288)
1523 for (x=0; x<h/2; x++)
1524 memcpy(track->audio.buf+x*2*w+y*cfs,
1527 for (x=0; x<w/sps; x++)
1528 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1530 if (++track->audio.sub_packet_cnt >= h) {
1531 track->audio.sub_packet_cnt = 0;
1532 track->audio.pkt_cnt = h*w / a;
1535 while (track->audio.pkt_cnt) {
1536 pkt = av_mallocz(sizeof(AVPacket));
1537 av_new_packet(pkt, a);
1538 memcpy(pkt->data, track->audio.buf
1539 + a * (h*w / a - track->audio.pkt_cnt--), a);
1541 pkt->stream_index = st->index;
1542 matroska_queue_packet(matroska, pkt);
1545 MatroskaTrackEncoding *encodings = track->encodings.elem;
1546 int offset = 0, pkt_size = lace_size[n];
1547 uint8_t *pkt_data = data;
1549 if (encodings && encodings->scope & 1) {
1550 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1555 pkt = av_mallocz(sizeof(AVPacket));
1556 /* XXX: prevent data copy... */
1557 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1559 res = AVERROR(ENOMEM);
1564 memcpy (pkt->data, encodings->compression.settings.data, offset);
1565 memcpy (pkt->data+offset, pkt_data, pkt_size);
1567 if (pkt_data != data)
1571 pkt->flags = is_keyframe;
1572 pkt->stream_index = st->index;
1574 pkt->pts = timecode;
1576 pkt->duration = duration;
1578 matroska_queue_packet(matroska, pkt);
1581 if (timecode != AV_NOPTS_VALUE)
1582 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1583 data += lace_size[n];
1591 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1593 MatroskaCluster cluster = { 0 };
1594 EbmlList *blocks_list;
1595 MatroskaBlock *blocks;
1597 if (matroska->has_cluster_id){
1598 /* For the first cluster we parse, it's ID was already read as
1599 part of matroska_read_header(), so don't read it again */
1600 res = ebml_parse_id(matroska, matroska_clusters,
1601 MATROSKA_ID_CLUSTER, &cluster);
1602 matroska->has_cluster_id = 0;
1604 res = ebml_parse(matroska, matroska_clusters, &cluster);
1605 blocks_list = &cluster.blocks;
1606 blocks = blocks_list->elem;
1607 for (i=0; !res && i<blocks_list->nb_elem; i++)
1608 if (blocks[i].bin.size > 0)
1609 res=matroska_parse_block(matroska,
1610 blocks[i].bin.data, blocks[i].bin.size,
1611 blocks[i].bin.pos, cluster.timecode,
1612 blocks[i].duration, !blocks[i].reference);
1613 ebml_free(matroska_cluster, &cluster);
1617 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1619 MatroskaDemuxContext *matroska = s->priv_data;
1621 while (matroska_deliver_packet(matroska, pkt)) {
1623 return AVERROR(EIO);
1624 if (matroska_parse_cluster(matroska) < 0)
1631 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1632 int64_t timestamp, int flags)
1634 MatroskaDemuxContext *matroska = s->priv_data;
1635 AVStream *st = s->streams[stream_index];
1638 index = av_index_search_timestamp(st, timestamp, flags);
1642 matroska_clear_queue(matroska);
1644 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1645 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1646 matroska->skip_to_stream = st;
1647 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1651 static int matroska_read_close(AVFormatContext *s)
1653 MatroskaDemuxContext *matroska = s->priv_data;
1654 MatroskaTrack *tracks = matroska->tracks.elem;
1657 matroska_clear_queue(matroska);
1659 for (n=0; n < matroska->tracks.nb_elem; n++)
1660 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1661 av_free(tracks[n].audio.buf);
1662 ebml_free(matroska_segment, matroska);
1667 AVInputFormat matroska_demuxer = {
1669 NULL_IF_CONFIG_SMALL("Matroska file format"),
1670 sizeof(MatroskaDemuxContext),
1672 matroska_read_header,
1673 matroska_read_packet,
1674 matroska_read_close,