Rename var
[FFMpeg-mirror/DVCPRO-HD.git] / libavformat / matroskadec.c
blob69208a8f0b60b6324a0999a1fcb238450602a4c2
1 /*
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
22 /**
23 * @file matroskadec.c
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/.
31 #include "avformat.h"
32 /* For codec_get_id(). */
33 #include "riff.h"
34 #include "matroska.h"
35 #include "libavcodec/mpeg4audio.h"
36 #include "libavutil/intfloat_readwrite.h"
37 #include "libavutil/lzo.h"
38 #ifdef CONFIG_ZLIB
39 #include <zlib.h>
40 #endif
41 #ifdef CONFIG_BZLIB
42 #include <bzlib.h>
43 #endif
45 typedef struct Track {
46 MatroskaTrackType type;
48 /* Unique track number and track ID. stream_index is the index that
49 * the calling app uses for this track. */
50 uint32_t num;
51 uint32_t uid;
52 int stream_index;
54 char *name;
55 char language[4];
57 char *codec_id;
59 unsigned char *codec_priv;
60 int codec_priv_size;
62 double time_scale;
63 uint64_t default_duration;
64 MatroskaTrackFlags flags;
66 int encoding_scope;
67 MatroskaTrackEncodingCompAlgo encoding_algo;
68 uint8_t *encoding_settings;
69 int encoding_settings_len;
70 } MatroskaTrack;
72 typedef struct MatroskaVideoTrack {
73 MatroskaTrack track;
75 int pixel_width;
76 int pixel_height;
77 int display_width;
78 int display_height;
80 uint32_t fourcc;
82 //..
83 } MatroskaVideoTrack;
85 typedef struct MatroskaAudioTrack {
86 MatroskaTrack track;
88 int channels;
89 int bitdepth;
90 int internal_samplerate;
91 int samplerate;
92 int block_align;
94 /* real audio header */
95 int coded_framesize;
96 int sub_packet_h;
97 int frame_size;
98 int sub_packet_size;
99 int sub_packet_cnt;
100 int pkt_cnt;
101 uint8_t *buf;
102 //..
103 } MatroskaAudioTrack;
105 typedef struct MatroskaSubtitleTrack {
106 MatroskaTrack track;
107 //..
108 } MatroskaSubtitleTrack;
110 #define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
111 sizeof(MatroskaAudioTrack), \
112 sizeof(MatroskaSubtitleTrack)))
114 typedef struct MatroskaLevel {
115 uint64_t start;
116 uint64_t length;
117 } MatroskaLevel;
119 typedef struct MatroskaDemuxIndex {
120 uint64_t pos; /* of the corresponding *cluster*! */
121 uint16_t track; /* reference to 'num' */
122 uint64_t time; /* in nanoseconds */
123 } MatroskaDemuxIndex;
125 typedef struct MatroskaDemuxContext {
126 AVFormatContext *ctx;
128 /* ebml stuff */
129 int num_levels;
130 MatroskaLevel levels[EBML_MAX_DEPTH];
131 int level_up;
133 /* timescale in the file */
134 int64_t time_scale;
136 /* num_streams is the number of streams that av_new_stream() was called
137 * for ( = that are available to the calling program). */
138 int num_tracks;
139 int num_streams;
140 MatroskaTrack *tracks[MAX_STREAMS];
142 /* cache for ID peeking */
143 uint32_t peek_id;
145 /* byte position of the segment inside the stream */
146 offset_t segment_start;
148 /* The packet queue. */
149 AVPacket **packets;
150 int num_packets;
152 /* have we already parse metadata/cues/clusters? */
153 int metadata_parsed;
154 int index_parsed;
155 int done;
157 /* The index for seeking. */
158 int num_indexes;
159 MatroskaDemuxIndex *index;
161 /* What to skip before effectively reading a packet. */
162 int skip_to_keyframe;
163 AVStream *skip_to_stream;
164 } MatroskaDemuxContext;
166 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
169 * The first few functions handle EBML file parsing. The rest
170 * is the document interpretation. Matroska really just is a
171 * EBML file.
175 * Return: the amount of levels in the hierarchy that the
176 * current element lies higher than the previous one.
177 * The opposite isn't done - that's auto-done using master
178 * element reading.
181 static int
182 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
184 ByteIOContext *pb = matroska->ctx->pb;
185 offset_t pos = url_ftell(pb);
186 int num = 0;
188 while (matroska->num_levels > 0) {
189 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
191 if (pos >= level->start + level->length) {
192 matroska->num_levels--;
193 num++;
194 } else {
195 break;
199 return num;
203 * Read: an "EBML number", which is defined as a variable-length
204 * array of bytes. The first byte indicates the length by giving a
205 * number of 0-bits followed by a one. The position of the first
206 * "one" bit inside the first byte indicates the length of this
207 * number.
208 * Returns: num. of bytes read. < 0 on error.
211 static int
212 ebml_read_num (MatroskaDemuxContext *matroska,
213 int max_size,
214 uint64_t *number)
216 ByteIOContext *pb = matroska->ctx->pb;
217 int len_mask = 0x80, read = 1, n = 1;
218 int64_t total = 0;
220 /* the first byte tells us the length in bytes - get_byte() can normally
221 * return 0, but since that's not a valid first ebmlID byte, we can
222 * use it safely here to catch EOS. */
223 if (!(total = get_byte(pb))) {
224 /* we might encounter EOS here */
225 if (!url_feof(pb)) {
226 offset_t pos = url_ftell(pb);
227 av_log(matroska->ctx, AV_LOG_ERROR,
228 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
229 pos, pos);
231 return AVERROR(EIO); /* EOS or actual I/O error */
234 /* get the length of the EBML number */
235 while (read <= max_size && !(total & len_mask)) {
236 read++;
237 len_mask >>= 1;
239 if (read > max_size) {
240 offset_t pos = url_ftell(pb) - 1;
241 av_log(matroska->ctx, AV_LOG_ERROR,
242 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
243 (uint8_t) total, pos, pos);
244 return AVERROR_INVALIDDATA;
247 /* read out length */
248 total &= ~len_mask;
249 while (n++ < read)
250 total = (total << 8) | get_byte(pb);
252 *number = total;
254 return read;
258 * Read: the element content data ID.
259 * Return: the number of bytes read or < 0 on error.
262 static int
263 ebml_read_element_id (MatroskaDemuxContext *matroska,
264 uint32_t *id,
265 int *level_up)
267 int read;
268 uint64_t total;
270 /* if we re-call this, use our cached ID */
271 if (matroska->peek_id != 0) {
272 if (level_up)
273 *level_up = 0;
274 *id = matroska->peek_id;
275 return 0;
278 /* read out the "EBML number", include tag in ID */
279 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
280 return read;
281 *id = matroska->peek_id = total | (1 << (read * 7));
283 /* level tracking */
284 if (level_up)
285 *level_up = ebml_read_element_level_up(matroska);
287 return read;
291 * Read: element content length.
292 * Return: the number of bytes read or < 0 on error.
295 static int
296 ebml_read_element_length (MatroskaDemuxContext *matroska,
297 uint64_t *length)
299 /* clear cache since we're now beyond that data point */
300 matroska->peek_id = 0;
302 /* read out the "EBML number", include tag in ID */
303 return ebml_read_num(matroska, 8, length);
307 * Return: the ID of the next element, or 0 on error.
308 * Level_up contains the amount of levels that this
309 * next element lies higher than the previous one.
312 static uint32_t
313 ebml_peek_id (MatroskaDemuxContext *matroska,
314 int *level_up)
316 uint32_t id;
318 if (ebml_read_element_id(matroska, &id, level_up) < 0)
319 return 0;
321 return id;
325 * Seek to a given offset.
326 * 0 is success, -1 is failure.
329 static int
330 ebml_read_seek (MatroskaDemuxContext *matroska,
331 offset_t offset)
333 ByteIOContext *pb = matroska->ctx->pb;
335 /* clear ID cache, if any */
336 matroska->peek_id = 0;
338 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
342 * Skip the next element.
343 * 0 is success, -1 is failure.
346 static int
347 ebml_read_skip (MatroskaDemuxContext *matroska)
349 ByteIOContext *pb = matroska->ctx->pb;
350 uint32_t id;
351 uint64_t length;
352 int res;
354 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
355 (res = ebml_read_element_length(matroska, &length)) < 0)
356 return res;
358 url_fskip(pb, length);
360 return 0;
364 * Read the next element as an unsigned int.
365 * 0 is success, < 0 is failure.
368 static int
369 ebml_read_uint (MatroskaDemuxContext *matroska,
370 uint32_t *id,
371 uint64_t *num)
373 ByteIOContext *pb = matroska->ctx->pb;
374 int n = 0, size, res;
375 uint64_t rlength;
377 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
378 (res = ebml_read_element_length(matroska, &rlength)) < 0)
379 return res;
380 size = rlength;
381 if (size < 1 || size > 8) {
382 offset_t pos = url_ftell(pb);
383 av_log(matroska->ctx, AV_LOG_ERROR,
384 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
385 size, pos, pos);
386 return AVERROR_INVALIDDATA;
389 /* big-endian ordening; build up number */
390 *num = 0;
391 while (n++ < size)
392 *num = (*num << 8) | get_byte(pb);
394 return 0;
398 * Read the next element as a signed int.
399 * 0 is success, < 0 is failure.
402 static int
403 ebml_read_sint (MatroskaDemuxContext *matroska,
404 uint32_t *id,
405 int64_t *num)
407 ByteIOContext *pb = matroska->ctx->pb;
408 int size, n = 1, negative = 0, res;
409 uint64_t rlength;
411 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
412 (res = ebml_read_element_length(matroska, &rlength)) < 0)
413 return res;
414 size = rlength;
415 if (size < 1 || size > 8) {
416 offset_t pos = url_ftell(pb);
417 av_log(matroska->ctx, AV_LOG_ERROR,
418 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
419 size, pos, pos);
420 return AVERROR_INVALIDDATA;
422 if ((*num = get_byte(pb)) & 0x80) {
423 negative = 1;
424 *num &= ~0x80;
426 while (n++ < size)
427 *num = (*num << 8) | get_byte(pb);
429 /* make signed */
430 if (negative)
431 *num = *num - (1LL << ((8 * size) - 1));
433 return 0;
437 * Read the next element as a float.
438 * 0 is success, < 0 is failure.
441 static int
442 ebml_read_float (MatroskaDemuxContext *matroska,
443 uint32_t *id,
444 double *num)
446 ByteIOContext *pb = matroska->ctx->pb;
447 int size, res;
448 uint64_t rlength;
450 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
451 (res = ebml_read_element_length(matroska, &rlength)) < 0)
452 return res;
453 size = rlength;
455 if (size == 4) {
456 *num= av_int2flt(get_be32(pb));
457 } else if(size==8){
458 *num= av_int2dbl(get_be64(pb));
459 } else{
460 offset_t pos = url_ftell(pb);
461 av_log(matroska->ctx, AV_LOG_ERROR,
462 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
463 size, pos, pos);
464 return AVERROR_INVALIDDATA;
467 return 0;
471 * Read the next element as an ASCII string.
472 * 0 is success, < 0 is failure.
475 static int
476 ebml_read_ascii (MatroskaDemuxContext *matroska,
477 uint32_t *id,
478 char **str)
480 ByteIOContext *pb = matroska->ctx->pb;
481 int size, res;
482 uint64_t rlength;
484 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
485 (res = ebml_read_element_length(matroska, &rlength)) < 0)
486 return res;
487 size = rlength;
489 /* ebml strings are usually not 0-terminated, so we allocate one
490 * byte more, read the string and NULL-terminate it ourselves. */
491 if (size < 0 || !(*str = av_malloc(size + 1))) {
492 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
493 return AVERROR(ENOMEM);
495 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
496 offset_t pos = url_ftell(pb);
497 av_log(matroska->ctx, AV_LOG_ERROR,
498 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
499 av_free(*str);
500 return AVERROR(EIO);
502 (*str)[size] = '\0';
504 return 0;
508 * Read the next element as a UTF-8 string.
509 * 0 is success, < 0 is failure.
512 static int
513 ebml_read_utf8 (MatroskaDemuxContext *matroska,
514 uint32_t *id,
515 char **str)
517 return ebml_read_ascii(matroska, id, str);
521 * Read the next element, but only the header. The contents
522 * are supposed to be sub-elements which can be read separately.
523 * 0 is success, < 0 is failure.
526 static int
527 ebml_read_master (MatroskaDemuxContext *matroska,
528 uint32_t *id)
530 ByteIOContext *pb = matroska->ctx->pb;
531 uint64_t length;
532 MatroskaLevel *level;
533 int res;
535 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
536 (res = ebml_read_element_length(matroska, &length)) < 0)
537 return res;
539 /* protect... (Heaven forbids that the '>' is true) */
540 if (matroska->num_levels >= EBML_MAX_DEPTH) {
541 av_log(matroska->ctx, AV_LOG_ERROR,
542 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
543 return AVERROR(ENOSYS);
546 /* remember level */
547 level = &matroska->levels[matroska->num_levels++];
548 level->start = url_ftell(pb);
549 level->length = length;
551 return 0;
555 * Read the next element as binary data.
556 * 0 is success, < 0 is failure.
559 static int
560 ebml_read_binary (MatroskaDemuxContext *matroska,
561 uint32_t *id,
562 uint8_t **binary,
563 int *size)
565 ByteIOContext *pb = matroska->ctx->pb;
566 uint64_t rlength;
567 int res;
569 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
570 (res = ebml_read_element_length(matroska, &rlength)) < 0)
571 return res;
572 *size = rlength;
574 if (!(*binary = av_malloc(*size))) {
575 av_log(matroska->ctx, AV_LOG_ERROR,
576 "Memory allocation error\n");
577 return AVERROR(ENOMEM);
580 if (get_buffer(pb, *binary, *size) != *size) {
581 offset_t pos = url_ftell(pb);
582 av_log(matroska->ctx, AV_LOG_ERROR,
583 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
584 return AVERROR(EIO);
587 return 0;
591 * Read signed/unsigned "EBML" numbers.
592 * Return: number of bytes processed, < 0 on error.
593 * XXX: use ebml_read_num().
596 static int
597 matroska_ebmlnum_uint (uint8_t *data,
598 uint32_t size,
599 uint64_t *num)
601 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
602 uint64_t total;
604 if (size <= 0)
605 return AVERROR_INVALIDDATA;
607 total = data[0];
608 while (read <= 8 && !(total & len_mask)) {
609 read++;
610 len_mask >>= 1;
612 if (read > 8)
613 return AVERROR_INVALIDDATA;
615 if ((total &= (len_mask - 1)) == len_mask - 1)
616 num_ffs++;
617 if (size < read)
618 return AVERROR_INVALIDDATA;
619 while (n < read) {
620 if (data[n] == 0xff)
621 num_ffs++;
622 total = (total << 8) | data[n];
623 n++;
626 if (read == num_ffs)
627 *num = (uint64_t)-1;
628 else
629 *num = total;
631 return read;
635 * Same as above, but signed.
638 static int
639 matroska_ebmlnum_sint (uint8_t *data,
640 uint32_t size,
641 int64_t *num)
643 uint64_t unum;
644 int res;
646 /* read as unsigned number first */
647 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
648 return res;
650 /* make signed (weird way) */
651 if (unum == (uint64_t)-1)
652 *num = INT64_MAX;
653 else
654 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
656 return res;
660 * Read an EBML header.
661 * 0 is success, < 0 is failure.
664 static int
665 ebml_read_header (MatroskaDemuxContext *matroska,
666 char **doctype,
667 int *version)
669 uint32_t id;
670 int level_up, res = 0;
672 /* default init */
673 if (doctype)
674 *doctype = NULL;
675 if (version)
676 *version = 1;
678 if (!(id = ebml_peek_id(matroska, &level_up)) ||
679 level_up != 0 || id != EBML_ID_HEADER) {
680 av_log(matroska->ctx, AV_LOG_ERROR,
681 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
682 return AVERROR_INVALIDDATA;
684 if ((res = ebml_read_master(matroska, &id)) < 0)
685 return res;
687 while (res == 0) {
688 if (!(id = ebml_peek_id(matroska, &level_up)))
689 return AVERROR(EIO);
691 /* end-of-header */
692 if (level_up)
693 break;
695 switch (id) {
696 /* is our read version uptodate? */
697 case EBML_ID_EBMLREADVERSION: {
698 uint64_t num;
700 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
701 return res;
702 if (num > EBML_VERSION) {
703 av_log(matroska->ctx, AV_LOG_ERROR,
704 "EBML version %"PRIu64" (> %d) is not supported\n",
705 num, EBML_VERSION);
706 return AVERROR_INVALIDDATA;
708 break;
711 /* we only handle 8 byte lengths at max */
712 case EBML_ID_EBMLMAXSIZELENGTH: {
713 uint64_t num;
715 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
716 return res;
717 if (num > sizeof(uint64_t)) {
718 av_log(matroska->ctx, AV_LOG_ERROR,
719 "Integers of size %"PRIu64" (> %zd) not supported\n",
720 num, sizeof(uint64_t));
721 return AVERROR_INVALIDDATA;
723 break;
726 /* we handle 4 byte IDs at max */
727 case EBML_ID_EBMLMAXIDLENGTH: {
728 uint64_t num;
730 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
731 return res;
732 if (num > sizeof(uint32_t)) {
733 av_log(matroska->ctx, AV_LOG_ERROR,
734 "IDs of size %"PRIu64" (> %zu) not supported\n",
735 num, sizeof(uint32_t));
736 return AVERROR_INVALIDDATA;
738 break;
741 case EBML_ID_DOCTYPE: {
742 char *text;
744 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
745 return res;
746 if (doctype) {
747 if (*doctype)
748 av_free(*doctype);
749 *doctype = text;
750 } else
751 av_free(text);
752 break;
755 case EBML_ID_DOCTYPEREADVERSION: {
756 uint64_t num;
758 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
759 return res;
760 if (version)
761 *version = num;
762 break;
765 default:
766 av_log(matroska->ctx, AV_LOG_INFO,
767 "Unknown data type 0x%x in EBML header", id);
768 /* pass-through */
770 case EBML_ID_VOID:
771 /* we ignore these two, as they don't tell us anything we
772 * care about */
773 case EBML_ID_EBMLVERSION:
774 case EBML_ID_DOCTYPEVERSION:
775 res = ebml_read_skip (matroska);
776 break;
780 return 0;
784 static int
785 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
786 int num)
788 int i;
790 for (i = 0; i < matroska->num_tracks; i++)
791 if (matroska->tracks[i]->num == num)
792 return i;
794 return -1;
799 * Put one packet in an application-supplied AVPacket struct.
800 * Returns 0 on success or -1 on failure.
803 static int
804 matroska_deliver_packet (MatroskaDemuxContext *matroska,
805 AVPacket *pkt)
807 if (matroska->num_packets > 0) {
808 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
809 av_free(matroska->packets[0]);
810 if (matroska->num_packets > 1) {
811 memmove(&matroska->packets[0], &matroska->packets[1],
812 (matroska->num_packets - 1) * sizeof(AVPacket *));
813 matroska->packets =
814 av_realloc(matroska->packets, (matroska->num_packets - 1) *
815 sizeof(AVPacket *));
816 } else {
817 av_freep(&matroska->packets);
819 matroska->num_packets--;
820 return 0;
823 return -1;
827 * Put a packet into our internal queue. Will be delivered to the
828 * user/application during the next get_packet() call.
831 static void
832 matroska_queue_packet (MatroskaDemuxContext *matroska,
833 AVPacket *pkt)
835 matroska->packets =
836 av_realloc(matroska->packets, (matroska->num_packets + 1) *
837 sizeof(AVPacket *));
838 matroska->packets[matroska->num_packets] = pkt;
839 matroska->num_packets++;
843 * Free all packets in our internal queue.
845 static void
846 matroska_clear_queue (MatroskaDemuxContext *matroska)
848 if (matroska->packets) {
849 int n;
850 for (n = 0; n < matroska->num_packets; n++) {
851 av_free_packet(matroska->packets[n]);
852 av_free(matroska->packets[n]);
854 av_free(matroska->packets);
855 matroska->packets = NULL;
856 matroska->num_packets = 0;
862 * Autodetecting...
865 static int
866 matroska_probe (AVProbeData *p)
868 uint64_t total = 0;
869 int len_mask = 0x80, size = 1, n = 1;
870 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
872 /* ebml header? */
873 if (AV_RB32(p->buf) != EBML_ID_HEADER)
874 return 0;
876 /* length of header */
877 total = p->buf[4];
878 while (size <= 8 && !(total & len_mask)) {
879 size++;
880 len_mask >>= 1;
882 if (size > 8)
883 return 0;
884 total &= (len_mask - 1);
885 while (n < size)
886 total = (total << 8) | p->buf[4 + n++];
888 /* does the probe data contain the whole header? */
889 if (p->buf_size < 4 + size + total)
890 return 0;
892 /* the header must contain the document type 'matroska'. For now,
893 * we don't parse the whole header but simply check for the
894 * availability of that array of characters inside the header.
895 * Not fully fool-proof, but good enough. */
896 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
897 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
898 return AVPROBE_SCORE_MAX;
900 return 0;
904 * From here on, it's all XML-style DTD stuff... Needs no comments.
907 static int
908 matroska_parse_info (MatroskaDemuxContext *matroska)
910 int res = 0;
911 uint32_t id;
913 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
915 while (res == 0) {
916 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
917 res = AVERROR(EIO);
918 break;
919 } else if (matroska->level_up) {
920 matroska->level_up--;
921 break;
924 switch (id) {
925 /* cluster timecode */
926 case MATROSKA_ID_TIMECODESCALE: {
927 uint64_t num;
928 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
929 break;
930 matroska->time_scale = num;
931 break;
934 case MATROSKA_ID_DURATION: {
935 double num;
936 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
937 break;
938 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
939 break;
942 case MATROSKA_ID_TITLE: {
943 char *text;
944 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
945 break;
946 strncpy(matroska->ctx->title, text,
947 sizeof(matroska->ctx->title)-1);
948 av_free(text);
949 break;
952 default:
953 av_log(matroska->ctx, AV_LOG_INFO,
954 "Unknown entry 0x%x in info header\n", id);
955 /* fall-through */
957 case MATROSKA_ID_WRITINGAPP:
958 case MATROSKA_ID_MUXINGAPP:
959 case MATROSKA_ID_DATEUTC:
960 case MATROSKA_ID_SEGMENTUID:
961 case EBML_ID_VOID:
962 res = ebml_read_skip(matroska);
963 break;
966 if (matroska->level_up) {
967 matroska->level_up--;
968 break;
972 return res;
975 static int
976 matroska_add_stream (MatroskaDemuxContext *matroska)
978 int res = 0;
979 uint32_t id;
980 MatroskaTrack *track;
982 /* start with the master */
983 if ((res = ebml_read_master(matroska, &id)) < 0)
984 return res;
986 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
988 /* Allocate a generic track. */
989 track = av_mallocz(MAX_TRACK_SIZE);
990 track->time_scale = 1.0;
991 strcpy(track->language, "eng");
993 /* try reading the trackentry headers */
994 while (res == 0) {
995 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
996 res = AVERROR(EIO);
997 break;
998 } else if (matroska->level_up > 0) {
999 matroska->level_up--;
1000 break;
1003 switch (id) {
1004 /* track number (unique stream ID) */
1005 case MATROSKA_ID_TRACKNUMBER: {
1006 uint64_t num;
1007 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1008 break;
1009 track->num = num;
1010 break;
1013 /* track UID (unique identifier) */
1014 case MATROSKA_ID_TRACKUID: {
1015 uint64_t num;
1016 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1017 break;
1018 track->uid = num;
1019 break;
1022 /* track type (video, audio, combined, subtitle, etc.) */
1023 case MATROSKA_ID_TRACKTYPE: {
1024 uint64_t num;
1025 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1026 break;
1027 if (track->type && track->type != num) {
1028 av_log(matroska->ctx, AV_LOG_INFO,
1029 "More than one tracktype in an entry - skip\n");
1030 break;
1032 track->type = num;
1034 switch (track->type) {
1035 case MATROSKA_TRACK_TYPE_VIDEO:
1036 case MATROSKA_TRACK_TYPE_AUDIO:
1037 case MATROSKA_TRACK_TYPE_SUBTITLE:
1038 break;
1039 case MATROSKA_TRACK_TYPE_COMPLEX:
1040 case MATROSKA_TRACK_TYPE_LOGO:
1041 case MATROSKA_TRACK_TYPE_CONTROL:
1042 default:
1043 av_log(matroska->ctx, AV_LOG_INFO,
1044 "Unknown or unsupported track type 0x%x\n",
1045 track->type);
1046 track->type = MATROSKA_TRACK_TYPE_NONE;
1047 break;
1049 break;
1052 /* tracktype specific stuff for video */
1053 case MATROSKA_ID_TRACKVIDEO: {
1054 MatroskaVideoTrack *videotrack;
1055 if (!track->type)
1056 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1057 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1058 av_log(matroska->ctx, AV_LOG_INFO,
1059 "video data in non-video track - ignoring\n");
1060 res = AVERROR_INVALIDDATA;
1061 break;
1062 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1063 break;
1064 videotrack = (MatroskaVideoTrack *)track;
1066 while (res == 0) {
1067 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1068 res = AVERROR(EIO);
1069 break;
1070 } else if (matroska->level_up > 0) {
1071 matroska->level_up--;
1072 break;
1075 switch (id) {
1076 /* fixme, this should be one-up, but I get it here */
1077 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1078 uint64_t num;
1079 if ((res = ebml_read_uint (matroska, &id,
1080 &num)) < 0)
1081 break;
1082 track->default_duration = num;
1083 break;
1086 /* video framerate */
1087 case MATROSKA_ID_VIDEOFRAMERATE: {
1088 double num;
1089 if ((res = ebml_read_float(matroska, &id,
1090 &num)) < 0)
1091 break;
1092 if (!track->default_duration)
1093 track->default_duration = 1000000000/num;
1094 break;
1097 /* width of the size to display the video at */
1098 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1099 uint64_t num;
1100 if ((res = ebml_read_uint(matroska, &id,
1101 &num)) < 0)
1102 break;
1103 videotrack->display_width = num;
1104 break;
1107 /* height of the size to display the video at */
1108 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1109 uint64_t num;
1110 if ((res = ebml_read_uint(matroska, &id,
1111 &num)) < 0)
1112 break;
1113 videotrack->display_height = num;
1114 break;
1117 /* width of the video in the file */
1118 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1119 uint64_t num;
1120 if ((res = ebml_read_uint(matroska, &id,
1121 &num)) < 0)
1122 break;
1123 videotrack->pixel_width = num;
1124 break;
1127 /* height of the video in the file */
1128 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1129 uint64_t num;
1130 if ((res = ebml_read_uint(matroska, &id,
1131 &num)) < 0)
1132 break;
1133 videotrack->pixel_height = num;
1134 break;
1137 /* whether the video is interlaced */
1138 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1139 uint64_t num;
1140 if ((res = ebml_read_uint(matroska, &id,
1141 &num)) < 0)
1142 break;
1143 if (num)
1144 track->flags |=
1145 MATROSKA_VIDEOTRACK_INTERLACED;
1146 else
1147 track->flags &=
1148 ~MATROSKA_VIDEOTRACK_INTERLACED;
1149 break;
1152 /* colorspace (only matters for raw video)
1153 * fourcc */
1154 case MATROSKA_ID_VIDEOCOLORSPACE: {
1155 uint64_t num;
1156 if ((res = ebml_read_uint(matroska, &id,
1157 &num)) < 0)
1158 break;
1159 videotrack->fourcc = num;
1160 break;
1163 default:
1164 av_log(matroska->ctx, AV_LOG_INFO,
1165 "Unknown video track header entry "
1166 "0x%x - ignoring\n", id);
1167 /* pass-through */
1169 case MATROSKA_ID_VIDEOSTEREOMODE:
1170 case MATROSKA_ID_VIDEOASPECTRATIO:
1171 case EBML_ID_VOID:
1172 res = ebml_read_skip(matroska);
1173 break;
1176 if (matroska->level_up) {
1177 matroska->level_up--;
1178 break;
1181 break;
1184 /* tracktype specific stuff for audio */
1185 case MATROSKA_ID_TRACKAUDIO: {
1186 MatroskaAudioTrack *audiotrack;
1187 if (!track->type)
1188 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1189 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1190 av_log(matroska->ctx, AV_LOG_INFO,
1191 "audio data in non-audio track - ignoring\n");
1192 res = AVERROR_INVALIDDATA;
1193 break;
1194 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1195 break;
1196 audiotrack = (MatroskaAudioTrack *)track;
1197 audiotrack->channels = 1;
1198 audiotrack->samplerate = 8000;
1200 while (res == 0) {
1201 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1202 res = AVERROR(EIO);
1203 break;
1204 } else if (matroska->level_up > 0) {
1205 matroska->level_up--;
1206 break;
1209 switch (id) {
1210 /* samplerate */
1211 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1212 double num;
1213 if ((res = ebml_read_float(matroska, &id,
1214 &num)) < 0)
1215 break;
1216 audiotrack->internal_samplerate =
1217 audiotrack->samplerate = num;
1218 break;
1221 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1222 double num;
1223 if ((res = ebml_read_float(matroska, &id,
1224 &num)) < 0)
1225 break;
1226 audiotrack->samplerate = num;
1227 break;
1230 /* bitdepth */
1231 case MATROSKA_ID_AUDIOBITDEPTH: {
1232 uint64_t num;
1233 if ((res = ebml_read_uint(matroska, &id,
1234 &num)) < 0)
1235 break;
1236 audiotrack->bitdepth = num;
1237 break;
1240 /* channels */
1241 case MATROSKA_ID_AUDIOCHANNELS: {
1242 uint64_t num;
1243 if ((res = ebml_read_uint(matroska, &id,
1244 &num)) < 0)
1245 break;
1246 audiotrack->channels = num;
1247 break;
1250 default:
1251 av_log(matroska->ctx, AV_LOG_INFO,
1252 "Unknown audio track header entry "
1253 "0x%x - ignoring\n", id);
1254 /* pass-through */
1256 case EBML_ID_VOID:
1257 res = ebml_read_skip(matroska);
1258 break;
1261 if (matroska->level_up) {
1262 matroska->level_up--;
1263 break;
1266 break;
1269 /* codec identifier */
1270 case MATROSKA_ID_CODECID: {
1271 char *text;
1272 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1273 break;
1274 track->codec_id = text;
1275 break;
1278 /* codec private data */
1279 case MATROSKA_ID_CODECPRIVATE: {
1280 uint8_t *data;
1281 int size;
1282 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1283 break;
1284 track->codec_priv = data;
1285 track->codec_priv_size = size;
1286 break;
1289 /* name of this track */
1290 case MATROSKA_ID_TRACKNAME: {
1291 char *text;
1292 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1293 break;
1294 track->name = text;
1295 break;
1298 /* language (matters for audio/subtitles, mostly) */
1299 case MATROSKA_ID_TRACKLANGUAGE: {
1300 char *text, *end;
1301 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1302 break;
1303 if ((end = strchr(text, '-')))
1304 *end = '\0';
1305 if (strlen(text) == 3)
1306 strcpy(track->language, text);
1307 av_free(text);
1308 break;
1311 /* whether this is actually used */
1312 case MATROSKA_ID_TRACKFLAGENABLED: {
1313 uint64_t num;
1314 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1315 break;
1316 if (num)
1317 track->flags |= MATROSKA_TRACK_ENABLED;
1318 else
1319 track->flags &= ~MATROSKA_TRACK_ENABLED;
1320 break;
1323 /* whether it's the default for this track type */
1324 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1325 uint64_t num;
1326 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1327 break;
1328 if (num)
1329 track->flags |= MATROSKA_TRACK_DEFAULT;
1330 else
1331 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1332 break;
1335 /* lacing (like MPEG, where blocks don't end/start on frame
1336 * boundaries) */
1337 case MATROSKA_ID_TRACKFLAGLACING: {
1338 uint64_t num;
1339 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1340 break;
1341 if (num)
1342 track->flags |= MATROSKA_TRACK_LACING;
1343 else
1344 track->flags &= ~MATROSKA_TRACK_LACING;
1345 break;
1348 /* default length (in time) of one data block in this track */
1349 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1350 uint64_t num;
1351 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1352 break;
1353 track->default_duration = num;
1354 break;
1357 case MATROSKA_ID_TRACKCONTENTENCODINGS: {
1358 if ((res = ebml_read_master(matroska, &id)) < 0)
1359 break;
1361 while (res == 0) {
1362 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1363 res = AVERROR(EIO);
1364 break;
1365 } else if (matroska->level_up > 0) {
1366 matroska->level_up--;
1367 break;
1370 switch (id) {
1371 case MATROSKA_ID_TRACKCONTENTENCODING: {
1372 int encoding_scope = 1;
1373 if ((res = ebml_read_master(matroska, &id)) < 0)
1374 break;
1376 while (res == 0) {
1377 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1378 res = AVERROR(EIO);
1379 break;
1380 } else if (matroska->level_up > 0) {
1381 matroska->level_up--;
1382 break;
1385 switch (id) {
1386 case MATROSKA_ID_ENCODINGSCOPE: {
1387 uint64_t num;
1388 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1389 break;
1390 encoding_scope = num;
1391 break;
1394 case MATROSKA_ID_ENCODINGTYPE: {
1395 uint64_t num;
1396 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1397 break;
1398 if (num)
1399 av_log(matroska->ctx, AV_LOG_ERROR,
1400 "Unsupported encoding type");
1401 break;
1404 case MATROSKA_ID_ENCODINGCOMPRESSION: {
1405 if ((res = ebml_read_master(matroska, &id)) < 0)
1406 break;
1408 while (res == 0) {
1409 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1410 res = AVERROR(EIO);
1411 break;
1412 } else if (matroska->level_up > 0) {
1413 matroska->level_up--;
1414 break;
1417 switch (id) {
1418 case MATROSKA_ID_ENCODINGCOMPALGO: {
1419 uint64_t num;
1420 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1421 break;
1422 if (num != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1423 #ifdef CONFIG_ZLIB
1424 num != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1425 #endif
1426 #ifdef CONFIG_BZLIB
1427 num != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1428 #endif
1429 num != MATROSKA_TRACK_ENCODING_COMP_LZO)
1430 av_log(matroska->ctx, AV_LOG_ERROR,
1431 "Unsupported compression algo\n");
1432 track->encoding_algo = num;
1433 break;
1436 case MATROSKA_ID_ENCODINGCOMPSETTINGS: {
1437 uint8_t *data;
1438 int size;
1439 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1440 break;
1441 track->encoding_settings = data;
1442 track->encoding_settings_len = size;
1443 break;
1446 default:
1447 av_log(matroska->ctx, AV_LOG_INFO,
1448 "Unknown compression header entry "
1449 "0x%x - ignoring\n", id);
1450 /* pass-through */
1452 case EBML_ID_VOID:
1453 res = ebml_read_skip(matroska);
1454 break;
1457 if (matroska->level_up) {
1458 matroska->level_up--;
1459 break;
1462 break;
1465 default:
1466 av_log(matroska->ctx, AV_LOG_INFO,
1467 "Unknown content encoding header entry "
1468 "0x%x - ignoring\n", id);
1469 /* pass-through */
1471 case EBML_ID_VOID:
1472 res = ebml_read_skip(matroska);
1473 break;
1476 if (matroska->level_up) {
1477 matroska->level_up--;
1478 break;
1482 track->encoding_scope = encoding_scope;
1483 break;
1486 default:
1487 av_log(matroska->ctx, AV_LOG_INFO,
1488 "Unknown content encodings header entry "
1489 "0x%x - ignoring\n", id);
1490 /* pass-through */
1492 case EBML_ID_VOID:
1493 res = ebml_read_skip(matroska);
1494 break;
1497 if (matroska->level_up) {
1498 matroska->level_up--;
1499 break;
1502 break;
1505 case MATROSKA_ID_TRACKTIMECODESCALE: {
1506 double num;
1507 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1508 break;
1509 track->time_scale = num;
1510 break;
1513 default:
1514 av_log(matroska->ctx, AV_LOG_INFO,
1515 "Unknown track header entry 0x%x - ignoring\n", id);
1516 /* pass-through */
1518 case EBML_ID_VOID:
1519 /* we ignore these because they're nothing useful. */
1520 case MATROSKA_ID_TRACKFLAGFORCED:
1521 case MATROSKA_ID_CODECNAME:
1522 case MATROSKA_ID_CODECDECODEALL:
1523 case MATROSKA_ID_CODECINFOURL:
1524 case MATROSKA_ID_CODECDOWNLOADURL:
1525 case MATROSKA_ID_TRACKMINCACHE:
1526 case MATROSKA_ID_TRACKMAXCACHE:
1527 res = ebml_read_skip(matroska);
1528 break;
1531 if (matroska->level_up) {
1532 matroska->level_up--;
1533 break;
1537 if (track->type && matroska->num_tracks < ARRAY_SIZE(matroska->tracks)) {
1538 matroska->tracks[matroska->num_tracks++] = track;
1539 } else {
1540 av_free(track);
1542 return res;
1545 static int
1546 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1548 int res = 0;
1549 uint32_t id;
1551 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1553 while (res == 0) {
1554 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1555 res = AVERROR(EIO);
1556 break;
1557 } else if (matroska->level_up) {
1558 matroska->level_up--;
1559 break;
1562 switch (id) {
1563 /* one track within the "all-tracks" header */
1564 case MATROSKA_ID_TRACKENTRY:
1565 res = matroska_add_stream(matroska);
1566 break;
1568 default:
1569 av_log(matroska->ctx, AV_LOG_INFO,
1570 "Unknown entry 0x%x in track header\n", id);
1571 /* fall-through */
1573 case EBML_ID_VOID:
1574 res = ebml_read_skip(matroska);
1575 break;
1578 if (matroska->level_up) {
1579 matroska->level_up--;
1580 break;
1584 return res;
1587 static int
1588 matroska_parse_index (MatroskaDemuxContext *matroska)
1590 int res = 0;
1591 uint32_t id;
1592 MatroskaDemuxIndex idx;
1594 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1596 while (res == 0) {
1597 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1598 res = AVERROR(EIO);
1599 break;
1600 } else if (matroska->level_up) {
1601 matroska->level_up--;
1602 break;
1605 switch (id) {
1606 /* one single index entry ('point') */
1607 case MATROSKA_ID_POINTENTRY:
1608 if ((res = ebml_read_master(matroska, &id)) < 0)
1609 break;
1611 /* in the end, we hope to fill one entry with a
1612 * timestamp, a file position and a tracknum */
1613 idx.pos = (uint64_t) -1;
1614 idx.time = (uint64_t) -1;
1615 idx.track = (uint16_t) -1;
1617 while (res == 0) {
1618 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1619 res = AVERROR(EIO);
1620 break;
1621 } else if (matroska->level_up) {
1622 matroska->level_up--;
1623 break;
1626 switch (id) {
1627 /* one single index entry ('point') */
1628 case MATROSKA_ID_CUETIME: {
1629 uint64_t time;
1630 if ((res = ebml_read_uint(matroska, &id,
1631 &time)) < 0)
1632 break;
1633 idx.time = time * matroska->time_scale;
1634 break;
1637 /* position in the file + track to which it
1638 * belongs */
1639 case MATROSKA_ID_CUETRACKPOSITION:
1640 if ((res = ebml_read_master(matroska, &id)) < 0)
1641 break;
1643 while (res == 0) {
1644 if (!(id = ebml_peek_id (matroska,
1645 &matroska->level_up))) {
1646 res = AVERROR(EIO);
1647 break;
1648 } else if (matroska->level_up) {
1649 matroska->level_up--;
1650 break;
1653 switch (id) {
1654 /* track number */
1655 case MATROSKA_ID_CUETRACK: {
1656 uint64_t num;
1657 if ((res = ebml_read_uint(matroska,
1658 &id, &num)) < 0)
1659 break;
1660 idx.track = num;
1661 break;
1664 /* position in file */
1665 case MATROSKA_ID_CUECLUSTERPOSITION: {
1666 uint64_t num;
1667 if ((res = ebml_read_uint(matroska,
1668 &id, &num)) < 0)
1669 break;
1670 idx.pos = num+matroska->segment_start;
1671 break;
1674 default:
1675 av_log(matroska->ctx, AV_LOG_INFO,
1676 "Unknown entry 0x%x in "
1677 "CuesTrackPositions\n", id);
1678 /* fall-through */
1680 case EBML_ID_VOID:
1681 res = ebml_read_skip(matroska);
1682 break;
1685 if (matroska->level_up) {
1686 matroska->level_up--;
1687 break;
1691 break;
1693 default:
1694 av_log(matroska->ctx, AV_LOG_INFO,
1695 "Unknown entry 0x%x in cuespoint "
1696 "index\n", id);
1697 /* fall-through */
1699 case EBML_ID_VOID:
1700 res = ebml_read_skip(matroska);
1701 break;
1704 if (matroska->level_up) {
1705 matroska->level_up--;
1706 break;
1710 /* so let's see if we got what we wanted */
1711 if (idx.pos != (uint64_t) -1 &&
1712 idx.time != (uint64_t) -1 &&
1713 idx.track != (uint16_t) -1) {
1714 if (matroska->num_indexes % 32 == 0) {
1715 /* re-allocate bigger index */
1716 matroska->index =
1717 av_realloc(matroska->index,
1718 (matroska->num_indexes + 32) *
1719 sizeof(MatroskaDemuxIndex));
1721 matroska->index[matroska->num_indexes] = idx;
1722 matroska->num_indexes++;
1724 break;
1726 default:
1727 av_log(matroska->ctx, AV_LOG_INFO,
1728 "Unknown entry 0x%x in cues header\n", id);
1729 /* fall-through */
1731 case EBML_ID_VOID:
1732 res = ebml_read_skip(matroska);
1733 break;
1736 if (matroska->level_up) {
1737 matroska->level_up--;
1738 break;
1742 return res;
1745 static int
1746 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1748 int res = 0;
1749 uint32_t id;
1751 while (res == 0) {
1752 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1753 res = AVERROR(EIO);
1754 break;
1755 } else if (matroska->level_up) {
1756 matroska->level_up--;
1757 break;
1760 switch (id) {
1761 /* Hm, this is unsupported... */
1762 default:
1763 av_log(matroska->ctx, AV_LOG_INFO,
1764 "Unknown entry 0x%x in metadata header\n", id);
1765 /* fall-through */
1767 case EBML_ID_VOID:
1768 res = ebml_read_skip(matroska);
1769 break;
1772 if (matroska->level_up) {
1773 matroska->level_up--;
1774 break;
1778 return res;
1781 static int
1782 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1784 int res = 0;
1785 uint32_t id;
1787 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1789 while (res == 0) {
1790 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1791 res = AVERROR(EIO);
1792 break;
1793 } else if (matroska->level_up) {
1794 matroska->level_up--;
1795 break;
1798 switch (id) {
1799 case MATROSKA_ID_SEEKENTRY: {
1800 uint32_t seek_id = 0, peek_id_cache = 0;
1801 uint64_t seek_pos = (uint64_t) -1, t;
1802 int dummy_level = 0;
1804 if ((res = ebml_read_master(matroska, &id)) < 0)
1805 break;
1807 while (res == 0) {
1808 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1809 res = AVERROR(EIO);
1810 break;
1811 } else if (matroska->level_up) {
1812 matroska->level_up--;
1813 break;
1816 switch (id) {
1817 case MATROSKA_ID_SEEKID:
1818 res = ebml_read_uint(matroska, &id, &t);
1819 seek_id = t;
1820 break;
1822 case MATROSKA_ID_SEEKPOSITION:
1823 res = ebml_read_uint(matroska, &id, &seek_pos);
1824 break;
1826 default:
1827 av_log(matroska->ctx, AV_LOG_INFO,
1828 "Unknown seekhead ID 0x%x\n", id);
1829 /* fall-through */
1831 case EBML_ID_VOID:
1832 res = ebml_read_skip(matroska);
1833 break;
1836 if (matroska->level_up) {
1837 matroska->level_up--;
1838 break;
1842 if (!seek_id || seek_pos == (uint64_t) -1) {
1843 av_log(matroska->ctx, AV_LOG_INFO,
1844 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1845 seek_id, seek_pos);
1846 break;
1849 switch (seek_id) {
1850 case MATROSKA_ID_CUES:
1851 case MATROSKA_ID_TAGS: {
1852 uint32_t level_up = matroska->level_up;
1853 offset_t before_pos;
1854 uint64_t length;
1855 MatroskaLevel level;
1857 /* remember the peeked ID and the current position */
1858 peek_id_cache = matroska->peek_id;
1859 before_pos = url_ftell(matroska->ctx->pb);
1861 /* seek */
1862 if ((res = ebml_read_seek(matroska, seek_pos +
1863 matroska->segment_start)) < 0)
1864 goto finish;
1866 /* we don't want to lose our seekhead level, so we add
1867 * a dummy. This is a crude hack. */
1868 if (matroska->num_levels == EBML_MAX_DEPTH) {
1869 av_log(matroska->ctx, AV_LOG_INFO,
1870 "Max EBML element depth (%d) reached, "
1871 "cannot parse further.\n", EBML_MAX_DEPTH);
1872 return AVERROR_UNKNOWN;
1875 level.start = 0;
1876 level.length = (uint64_t)-1;
1877 matroska->levels[matroska->num_levels] = level;
1878 matroska->num_levels++;
1879 dummy_level = 1;
1881 /* check ID */
1882 if (!(id = ebml_peek_id (matroska,
1883 &matroska->level_up)))
1884 goto finish;
1885 if (id != seek_id) {
1886 av_log(matroska->ctx, AV_LOG_INFO,
1887 "We looked for ID=0x%x but got "
1888 "ID=0x%x (pos=%"PRIu64")",
1889 seek_id, id, seek_pos +
1890 matroska->segment_start);
1891 goto finish;
1894 /* read master + parse */
1895 if ((res = ebml_read_master(matroska, &id)) < 0)
1896 goto finish;
1897 switch (id) {
1898 case MATROSKA_ID_CUES:
1899 if (!(res = matroska_parse_index(matroska)) ||
1900 url_feof(matroska->ctx->pb)) {
1901 matroska->index_parsed = 1;
1902 res = 0;
1904 break;
1905 case MATROSKA_ID_TAGS:
1906 if (!(res = matroska_parse_metadata(matroska)) ||
1907 url_feof(matroska->ctx->pb)) {
1908 matroska->metadata_parsed = 1;
1909 res = 0;
1911 break;
1914 finish:
1915 /* remove dummy level */
1916 if (dummy_level)
1917 while (matroska->num_levels) {
1918 matroska->num_levels--;
1919 length =
1920 matroska->levels[matroska->num_levels].length;
1921 if (length == (uint64_t)-1)
1922 break;
1925 /* seek back */
1926 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1927 return res;
1928 matroska->peek_id = peek_id_cache;
1929 matroska->level_up = level_up;
1930 break;
1933 default:
1934 av_log(matroska->ctx, AV_LOG_INFO,
1935 "Ignoring seekhead entry for ID=0x%x\n",
1936 seek_id);
1937 break;
1940 break;
1943 default:
1944 av_log(matroska->ctx, AV_LOG_INFO,
1945 "Unknown seekhead ID 0x%x\n", id);
1946 /* fall-through */
1948 case EBML_ID_VOID:
1949 res = ebml_read_skip(matroska);
1950 break;
1953 if (matroska->level_up) {
1954 matroska->level_up--;
1955 break;
1959 return res;
1962 static int
1963 matroska_parse_attachments(AVFormatContext *s)
1965 MatroskaDemuxContext *matroska = s->priv_data;
1966 int res = 0;
1967 uint32_t id;
1969 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
1971 while (res == 0) {
1972 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1973 res = AVERROR(EIO);
1974 break;
1975 } else if (matroska->level_up) {
1976 matroska->level_up--;
1977 break;
1980 switch (id) {
1981 case MATROSKA_ID_ATTACHEDFILE: {
1982 char* name = NULL;
1983 char* mime = NULL;
1984 uint8_t* data = NULL;
1985 int i, data_size = 0;
1986 AVStream *st;
1988 if ((res = ebml_read_master(matroska, &id)) < 0)
1989 break;
1991 while (res == 0) {
1992 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1993 res = AVERROR(EIO);
1994 break;
1995 } else if (matroska->level_up) {
1996 matroska->level_up--;
1997 break;
2000 switch (id) {
2001 case MATROSKA_ID_FILENAME:
2002 res = ebml_read_utf8 (matroska, &id, &name);
2003 break;
2005 case MATROSKA_ID_FILEMIMETYPE:
2006 res = ebml_read_ascii (matroska, &id, &mime);
2007 break;
2009 case MATROSKA_ID_FILEDATA:
2010 res = ebml_read_binary(matroska, &id, &data, &data_size);
2011 break;
2013 default:
2014 av_log(matroska->ctx, AV_LOG_INFO,
2015 "Unknown attachedfile ID 0x%x\n", id);
2016 case MATROSKA_ID_FILEUID:
2017 case EBML_ID_VOID:
2018 res = ebml_read_skip(matroska);
2019 break;
2022 if (matroska->level_up) {
2023 matroska->level_up--;
2024 break;
2028 if (!(name && mime && data && data_size > 0)) {
2029 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2030 break;
2033 st = av_new_stream(s, matroska->num_streams++);
2034 if (st == NULL)
2035 return AVERROR(ENOMEM);
2036 st->filename = av_strdup(name);
2037 st->codec->codec_id = CODEC_ID_NONE;
2038 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
2039 st->codec->extradata = av_malloc(data_size);
2040 if(st->codec->extradata == NULL)
2041 return AVERROR(ENOMEM);
2042 st->codec->extradata_size = data_size;
2043 memcpy(st->codec->extradata, data, data_size);
2045 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
2046 if (!strncmp(ff_mkv_mime_tags[i].str, mime,
2047 strlen(ff_mkv_mime_tags[i].str))) {
2048 st->codec->codec_id = ff_mkv_mime_tags[i].id;
2049 break;
2053 av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
2054 break;
2057 default:
2058 av_log(matroska->ctx, AV_LOG_INFO,
2059 "Unknown attachments ID 0x%x\n", id);
2060 /* fall-through */
2062 case EBML_ID_VOID:
2063 res = ebml_read_skip(matroska);
2064 break;
2067 if (matroska->level_up) {
2068 matroska->level_up--;
2069 break;
2073 return res;
2076 static int
2077 matroska_parse_chapters(AVFormatContext *s)
2079 MatroskaDemuxContext *matroska = s->priv_data;
2080 int res = 0;
2081 uint32_t id;
2083 av_log(s, AV_LOG_DEBUG, "parsing chapters...\n");
2085 while (res == 0) {
2086 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2087 res = AVERROR(EIO);
2088 break;
2089 } else if (matroska->level_up) {
2090 matroska->level_up--;
2091 break;
2094 switch (id) {
2095 case MATROSKA_ID_EDITIONENTRY: {
2096 uint64_t end = AV_NOPTS_VALUE, start = AV_NOPTS_VALUE;
2097 int64_t uid= -1;
2098 char* title = NULL;
2099 /* if there is more than one chapter edition
2100 we take only the first one */
2101 if(s->chapters) {
2102 ebml_read_skip(matroska);
2103 break;
2106 if ((res = ebml_read_master(matroska, &id)) < 0)
2107 break;
2109 while (res == 0) {
2110 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2111 res = AVERROR(EIO);
2112 break;
2113 } else if (matroska->level_up) {
2114 matroska->level_up--;
2115 break;
2118 switch (id) {
2119 case MATROSKA_ID_CHAPTERATOM:
2120 if ((res = ebml_read_master(matroska, &id)) < 0)
2121 break;
2123 while (res == 0) {
2124 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2125 res = AVERROR(EIO);
2126 break;
2127 } else if (matroska->level_up) {
2128 matroska->level_up--;
2129 break;
2132 switch (id) {
2133 case MATROSKA_ID_CHAPTERTIMEEND:
2134 res = ebml_read_uint(matroska, &id, &end);
2135 break;
2137 case MATROSKA_ID_CHAPTERTIMESTART:
2138 res = ebml_read_uint(matroska, &id, &start);
2139 break;
2141 case MATROSKA_ID_CHAPTERDISPLAY:
2142 if ((res = ebml_read_master(matroska, &id)) < 0)
2143 break;
2145 while (res == 0) {
2146 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2147 res = AVERROR(EIO);
2148 break;
2149 } else if (matroska->level_up) {
2150 matroska->level_up--;
2151 break;
2154 switch (id) {
2155 case MATROSKA_ID_CHAPSTRING:
2156 res = ebml_read_utf8(matroska, &id, &title);
2157 break;
2159 default:
2160 av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter display ID 0x%x\n", id);
2161 case EBML_ID_VOID:
2162 res = ebml_read_skip(matroska);
2163 break;
2166 if (matroska->level_up) {
2167 matroska->level_up--;
2168 break;
2171 break;
2173 case MATROSKA_ID_CHAPTERUID:
2174 res = ebml_read_uint(matroska, &id, &uid);
2175 break;
2176 default:
2177 av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter atom ID 0x%x\n", id);
2178 case MATROSKA_ID_CHAPTERFLAGHIDDEN:
2179 case EBML_ID_VOID:
2180 res = ebml_read_skip(matroska);
2181 break;
2184 if (matroska->level_up) {
2185 matroska->level_up--;
2186 break;
2190 if (start != AV_NOPTS_VALUE && uid != -1) {
2191 if(!ff_new_chapter(s, uid, (AVRational){1, 1000000000}, start, end, title))
2192 res= AVERROR(ENOMEM);
2194 av_free(title);
2195 break;
2197 default:
2198 av_log(s, AV_LOG_INFO, "Ignoring unknown Edition entry ID 0x%x\n", id);
2199 case MATROSKA_ID_EDITIONUID:
2200 case MATROSKA_ID_EDITIONFLAGHIDDEN:
2201 case MATROSKA_ID_EDITIONFLAGDEFAULT:
2202 case EBML_ID_VOID:
2203 res = ebml_read_skip(matroska);
2204 break;
2208 if (matroska->level_up) {
2209 matroska->level_up--;
2210 break;
2213 break;
2216 default:
2217 av_log(s, AV_LOG_INFO, "Expected an Edition entry (0x%x), but found 0x%x\n", MATROSKA_ID_EDITIONENTRY, id);
2218 case EBML_ID_VOID:
2219 res = ebml_read_skip(matroska);
2220 break;
2223 if (matroska->level_up) {
2224 matroska->level_up--;
2225 break;
2229 return res;
2232 static int
2233 matroska_aac_profile (char *codec_id)
2235 static const char *aac_profiles[] = {
2236 "MAIN", "LC", "SSR"
2238 int profile;
2240 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2241 if (strstr(codec_id, aac_profiles[profile]))
2242 break;
2243 return profile + 1;
2246 static int
2247 matroska_aac_sri (int samplerate)
2249 int sri;
2251 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2252 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2253 break;
2254 return sri;
2257 static int
2258 matroska_read_header (AVFormatContext *s,
2259 AVFormatParameters *ap)
2261 MatroskaDemuxContext *matroska = s->priv_data;
2262 char *doctype;
2263 int version, last_level, res = 0;
2264 uint32_t id;
2266 matroska->ctx = s;
2268 /* First read the EBML header. */
2269 doctype = NULL;
2270 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2271 return res;
2272 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2273 av_log(matroska->ctx, AV_LOG_ERROR,
2274 "Wrong EBML doctype ('%s' != 'matroska').\n",
2275 doctype ? doctype : "(none)");
2276 if (doctype)
2277 av_free(doctype);
2278 return AVERROR_NOFMT;
2280 av_free(doctype);
2281 if (version > 2) {
2282 av_log(matroska->ctx, AV_LOG_ERROR,
2283 "Matroska demuxer version 2 too old for file version %d\n",
2284 version);
2285 return AVERROR_NOFMT;
2288 /* The next thing is a segment. */
2289 while (1) {
2290 if (!(id = ebml_peek_id(matroska, &last_level)))
2291 return AVERROR(EIO);
2292 if (id == MATROSKA_ID_SEGMENT)
2293 break;
2295 /* oi! */
2296 av_log(matroska->ctx, AV_LOG_INFO,
2297 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2298 MATROSKA_ID_SEGMENT, id);
2299 if ((res = ebml_read_skip(matroska)) < 0)
2300 return res;
2303 /* We now have a Matroska segment.
2304 * Seeks are from the beginning of the segment,
2305 * after the segment ID/length. */
2306 if ((res = ebml_read_master(matroska, &id)) < 0)
2307 return res;
2308 matroska->segment_start = url_ftell(s->pb);
2310 matroska->time_scale = 1000000;
2311 /* we've found our segment, start reading the different contents in here */
2312 while (res == 0) {
2313 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2314 res = AVERROR(EIO);
2315 break;
2316 } else if (matroska->level_up) {
2317 matroska->level_up--;
2318 break;
2321 switch (id) {
2322 /* stream info */
2323 case MATROSKA_ID_INFO: {
2324 if ((res = ebml_read_master(matroska, &id)) < 0)
2325 break;
2326 res = matroska_parse_info(matroska);
2327 break;
2330 /* track info headers */
2331 case MATROSKA_ID_TRACKS: {
2332 if ((res = ebml_read_master(matroska, &id)) < 0)
2333 break;
2334 res = matroska_parse_tracks(matroska);
2335 break;
2338 /* stream index */
2339 case MATROSKA_ID_CUES: {
2340 if (!matroska->index_parsed) {
2341 if ((res = ebml_read_master(matroska, &id)) < 0)
2342 break;
2343 res = matroska_parse_index(matroska);
2344 } else
2345 res = ebml_read_skip(matroska);
2346 break;
2349 /* metadata */
2350 case MATROSKA_ID_TAGS: {
2351 if (!matroska->metadata_parsed) {
2352 if ((res = ebml_read_master(matroska, &id)) < 0)
2353 break;
2354 res = matroska_parse_metadata(matroska);
2355 } else
2356 res = ebml_read_skip(matroska);
2357 break;
2360 /* file index (if seekable, seek to Cues/Tags to parse it) */
2361 case MATROSKA_ID_SEEKHEAD: {
2362 if ((res = ebml_read_master(matroska, &id)) < 0)
2363 break;
2364 res = matroska_parse_seekhead(matroska);
2365 break;
2368 case MATROSKA_ID_ATTACHMENTS: {
2369 if ((res = ebml_read_master(matroska, &id)) < 0)
2370 break;
2371 res = matroska_parse_attachments(s);
2372 break;
2375 case MATROSKA_ID_CLUSTER: {
2376 /* Do not read the master - this will be done in the next
2377 * call to matroska_read_packet. */
2378 res = 1;
2379 break;
2382 case MATROSKA_ID_CHAPTERS: {
2383 if ((res = ebml_read_master(matroska, &id)) < 0)
2384 return res;
2385 res = matroska_parse_chapters(s);
2386 break;
2389 default:
2390 av_log(matroska->ctx, AV_LOG_INFO,
2391 "Unknown matroska file header ID 0x%x\n", id);
2392 /* fall-through */
2394 case EBML_ID_VOID:
2395 res = ebml_read_skip(matroska);
2396 break;
2399 if (matroska->level_up) {
2400 matroska->level_up--;
2401 break;
2405 /* Have we found a cluster? */
2406 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2407 int i, j;
2408 MatroskaTrack *track;
2409 AVStream *st;
2411 for (i = 0; i < matroska->num_tracks; i++) {
2412 enum CodecID codec_id = CODEC_ID_NONE;
2413 uint8_t *extradata = NULL;
2414 int extradata_size = 0;
2415 int extradata_offset = 0;
2416 track = matroska->tracks[i];
2417 track->stream_index = -1;
2419 /* Apply some sanity checks. */
2420 if (track->codec_id == NULL)
2421 continue;
2423 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2424 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2425 strlen(ff_mkv_codec_tags[j].str))){
2426 codec_id= ff_mkv_codec_tags[j].id;
2427 break;
2431 /* Set the FourCC from the CodecID. */
2432 /* This is the MS compatibility mode which stores a
2433 * BITMAPINFOHEADER in the CodecPrivate. */
2434 if (!strcmp(track->codec_id,
2435 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2436 (track->codec_priv_size >= 40) &&
2437 (track->codec_priv != NULL)) {
2438 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2440 /* Offset of biCompression. Stored in LE. */
2441 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2442 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2446 /* This is the MS compatibility mode which stores a
2447 * WAVEFORMATEX in the CodecPrivate. */
2448 else if (!strcmp(track->codec_id,
2449 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2450 (track->codec_priv_size >= 18) &&
2451 (track->codec_priv != NULL)) {
2452 uint16_t tag;
2454 /* Offset of wFormatTag. Stored in LE. */
2455 tag = AV_RL16(track->codec_priv);
2456 codec_id = codec_get_id(codec_wav_tags, tag);
2460 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2461 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2462 int profile = matroska_aac_profile(track->codec_id);
2463 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2464 extradata = av_malloc(5);
2465 if (extradata == NULL)
2466 return AVERROR(ENOMEM);
2467 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2468 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2469 if (strstr(track->codec_id, "SBR")) {
2470 sri = matroska_aac_sri(audiotrack->samplerate);
2471 extradata[2] = 0x56;
2472 extradata[3] = 0xE5;
2473 extradata[4] = 0x80 | (sri<<3);
2474 extradata_size = 5;
2475 } else {
2476 extradata_size = 2;
2480 else if (codec_id == CODEC_ID_TTA) {
2481 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2482 ByteIOContext b;
2483 extradata_size = 30;
2484 extradata = av_mallocz(extradata_size);
2485 if (extradata == NULL)
2486 return AVERROR(ENOMEM);
2487 init_put_byte(&b, extradata, extradata_size, 1,
2488 NULL, NULL, NULL, NULL);
2489 put_buffer(&b, "TTA1", 4);
2490 put_le16(&b, 1);
2491 put_le16(&b, audiotrack->channels);
2492 put_le16(&b, audiotrack->bitdepth);
2493 put_le32(&b, audiotrack->samplerate);
2494 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2497 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2498 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2499 extradata_offset = 26;
2500 track->codec_priv_size -= extradata_offset;
2503 else if (codec_id == CODEC_ID_RA_144) {
2504 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2505 audiotrack->samplerate = 8000;
2506 audiotrack->channels = 1;
2509 else if (codec_id == CODEC_ID_RA_288 ||
2510 codec_id == CODEC_ID_COOK ||
2511 codec_id == CODEC_ID_ATRAC3) {
2512 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2513 ByteIOContext b;
2515 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2516 NULL, NULL, NULL, NULL);
2517 url_fskip(&b, 24);
2518 audiotrack->coded_framesize = get_be32(&b);
2519 url_fskip(&b, 12);
2520 audiotrack->sub_packet_h = get_be16(&b);
2521 audiotrack->frame_size = get_be16(&b);
2522 audiotrack->sub_packet_size = get_be16(&b);
2523 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2524 if (codec_id == CODEC_ID_RA_288) {
2525 audiotrack->block_align = audiotrack->coded_framesize;
2526 track->codec_priv_size = 0;
2527 } else {
2528 audiotrack->block_align = audiotrack->sub_packet_size;
2529 extradata_offset = 78;
2530 track->codec_priv_size -= extradata_offset;
2534 if (codec_id == CODEC_ID_NONE) {
2535 av_log(matroska->ctx, AV_LOG_INFO,
2536 "Unknown/unsupported CodecID %s.\n",
2537 track->codec_id);
2540 track->stream_index = matroska->num_streams;
2542 matroska->num_streams++;
2543 st = av_new_stream(s, track->stream_index);
2544 if (st == NULL)
2545 return AVERROR(ENOMEM);
2546 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2548 st->codec->codec_id = codec_id;
2549 st->start_time = 0;
2550 if (strcmp(track->language, "und"))
2551 strcpy(st->language, track->language);
2553 if (track->flags & MATROSKA_TRACK_DEFAULT)
2554 st->disposition |= AV_DISPOSITION_DEFAULT;
2556 if (track->default_duration)
2557 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2558 track->default_duration, 1000000000, 30000);
2560 if(extradata){
2561 st->codec->extradata = extradata;
2562 st->codec->extradata_size = extradata_size;
2563 } else if(track->codec_priv && track->codec_priv_size > 0){
2564 st->codec->extradata = av_malloc(track->codec_priv_size);
2565 if(st->codec->extradata == NULL)
2566 return AVERROR(ENOMEM);
2567 st->codec->extradata_size = track->codec_priv_size;
2568 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2569 track->codec_priv_size);
2572 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2573 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2575 st->codec->codec_type = CODEC_TYPE_VIDEO;
2576 st->codec->codec_tag = videotrack->fourcc;
2577 st->codec->width = videotrack->pixel_width;
2578 st->codec->height = videotrack->pixel_height;
2579 if (videotrack->display_width == 0)
2580 videotrack->display_width= videotrack->pixel_width;
2581 if (videotrack->display_height == 0)
2582 videotrack->display_height= videotrack->pixel_height;
2583 av_reduce(&st->codec->sample_aspect_ratio.num,
2584 &st->codec->sample_aspect_ratio.den,
2585 st->codec->height * videotrack->display_width,
2586 st->codec-> width * videotrack->display_height,
2587 255);
2588 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2589 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2590 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2592 st->codec->codec_type = CODEC_TYPE_AUDIO;
2593 st->codec->sample_rate = audiotrack->samplerate;
2594 st->codec->channels = audiotrack->channels;
2595 st->codec->block_align = audiotrack->block_align;
2596 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2597 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2600 /* What do we do with private data? E.g. for Vorbis. */
2602 res = 0;
2605 if (matroska->index_parsed) {
2606 int i, track, stream;
2607 for (i=0; i<matroska->num_indexes; i++) {
2608 MatroskaDemuxIndex *idx = &matroska->index[i];
2609 track = matroska_find_track_by_num(matroska, idx->track);
2610 if (track < 0) continue;
2611 stream = matroska->tracks[track]->stream_index;
2612 if (stream >= 0 && stream < matroska->ctx->nb_streams)
2613 av_add_index_entry(matroska->ctx->streams[stream],
2614 idx->pos, idx->time/AV_TIME_BASE,
2615 0, 0, AVINDEX_KEYFRAME);
2619 return res;
2622 static int
2623 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2624 int64_t pos, uint64_t cluster_time, uint64_t duration,
2625 int is_keyframe, int is_bframe)
2627 int res = 0;
2628 int track;
2629 AVStream *st;
2630 AVPacket *pkt;
2631 uint8_t *origdata = data;
2632 int16_t block_time;
2633 uint32_t *lace_size = NULL;
2634 int n, flags, laces = 0;
2635 uint64_t num;
2636 int stream_index;
2638 /* first byte(s): tracknum */
2639 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2640 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2641 av_free(origdata);
2642 return res;
2644 data += n;
2645 size -= n;
2647 /* fetch track from num */
2648 track = matroska_find_track_by_num(matroska, num);
2649 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2650 av_log(matroska->ctx, AV_LOG_INFO,
2651 "Invalid stream %d or size %u\n", track, size);
2652 av_free(origdata);
2653 return res;
2655 stream_index = matroska->tracks[track]->stream_index;
2656 if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2657 av_free(origdata);
2658 return res;
2660 st = matroska->ctx->streams[stream_index];
2661 if (st->discard >= AVDISCARD_ALL) {
2662 av_free(origdata);
2663 return res;
2665 if (duration == AV_NOPTS_VALUE)
2666 duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2668 /* block_time (relative to cluster time) */
2669 block_time = AV_RB16(data);
2670 data += 2;
2671 flags = *data++;
2672 size -= 3;
2673 if (is_keyframe == -1)
2674 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2676 if (matroska->skip_to_keyframe) {
2677 if (!is_keyframe || st != matroska->skip_to_stream) {
2678 av_free(origdata);
2679 return res;
2681 matroska->skip_to_keyframe = 0;
2684 switch ((flags & 0x06) >> 1) {
2685 case 0x0: /* no lacing */
2686 laces = 1;
2687 lace_size = av_mallocz(sizeof(int));
2688 lace_size[0] = size;
2689 break;
2691 case 0x1: /* xiph lacing */
2692 case 0x2: /* fixed-size lacing */
2693 case 0x3: /* EBML lacing */
2694 assert(size>0); // size <=3 is checked before size-=3 above
2695 laces = (*data) + 1;
2696 data += 1;
2697 size -= 1;
2698 lace_size = av_mallocz(laces * sizeof(int));
2700 switch ((flags & 0x06) >> 1) {
2701 case 0x1: /* xiph lacing */ {
2702 uint8_t temp;
2703 uint32_t total = 0;
2704 for (n = 0; res == 0 && n < laces - 1; n++) {
2705 while (1) {
2706 if (size == 0) {
2707 res = -1;
2708 break;
2710 temp = *data;
2711 lace_size[n] += temp;
2712 data += 1;
2713 size -= 1;
2714 if (temp != 0xff)
2715 break;
2717 total += lace_size[n];
2719 lace_size[n] = size - total;
2720 break;
2723 case 0x2: /* fixed-size lacing */
2724 for (n = 0; n < laces; n++)
2725 lace_size[n] = size / laces;
2726 break;
2728 case 0x3: /* EBML lacing */ {
2729 uint32_t total;
2730 n = matroska_ebmlnum_uint(data, size, &num);
2731 if (n < 0) {
2732 av_log(matroska->ctx, AV_LOG_INFO,
2733 "EBML block data error\n");
2734 break;
2736 data += n;
2737 size -= n;
2738 total = lace_size[0] = num;
2739 for (n = 1; res == 0 && n < laces - 1; n++) {
2740 int64_t snum;
2741 int r;
2742 r = matroska_ebmlnum_sint (data, size, &snum);
2743 if (r < 0) {
2744 av_log(matroska->ctx, AV_LOG_INFO,
2745 "EBML block data error\n");
2746 break;
2748 data += r;
2749 size -= r;
2750 lace_size[n] = lace_size[n - 1] + snum;
2751 total += lace_size[n];
2753 lace_size[n] = size - total;
2754 break;
2757 break;
2760 if (res == 0) {
2761 uint64_t timecode = AV_NOPTS_VALUE;
2763 if (cluster_time != (uint64_t)-1
2764 && (block_time >= 0 || cluster_time >= -block_time))
2765 timecode = cluster_time + block_time;
2767 for (n = 0; n < laces; n++) {
2768 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2769 st->codec->codec_id == CODEC_ID_COOK ||
2770 st->codec->codec_id == CODEC_ID_ATRAC3) {
2771 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2772 int a = st->codec->block_align;
2773 int sps = audiotrack->sub_packet_size;
2774 int cfs = audiotrack->coded_framesize;
2775 int h = audiotrack->sub_packet_h;
2776 int y = audiotrack->sub_packet_cnt;
2777 int w = audiotrack->frame_size;
2778 int x;
2780 if (!audiotrack->pkt_cnt) {
2781 if (st->codec->codec_id == CODEC_ID_RA_288)
2782 for (x=0; x<h/2; x++)
2783 memcpy(audiotrack->buf+x*2*w+y*cfs,
2784 data+x*cfs, cfs);
2785 else
2786 for (x=0; x<w/sps; x++)
2787 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2789 if (++audiotrack->sub_packet_cnt >= h) {
2790 audiotrack->sub_packet_cnt = 0;
2791 audiotrack->pkt_cnt = h*w / a;
2794 while (audiotrack->pkt_cnt) {
2795 pkt = av_mallocz(sizeof(AVPacket));
2796 av_new_packet(pkt, a);
2797 memcpy(pkt->data, audiotrack->buf
2798 + a * (h*w / a - audiotrack->pkt_cnt--), a);
2799 pkt->pos = pos;
2800 pkt->stream_index = stream_index;
2801 matroska_queue_packet(matroska, pkt);
2803 } else {
2804 int result, offset = 0, ilen, olen, pkt_size = lace_size[n];
2805 uint8_t *pkt_data = data;
2807 if (matroska->tracks[track]->encoding_scope & 1) {
2808 switch (matroska->tracks[track]->encoding_algo) {
2809 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
2810 offset = matroska->tracks[track]->encoding_settings_len;
2811 break;
2812 case MATROSKA_TRACK_ENCODING_COMP_LZO:
2813 pkt_data = NULL;
2814 do {
2815 ilen = lace_size[n];
2816 olen = pkt_size *= 3;
2817 pkt_data = av_realloc(pkt_data,
2818 pkt_size+LZO_OUTPUT_PADDING);
2819 result = lzo1x_decode(pkt_data, &olen, data, &ilen);
2820 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
2821 if (result) {
2822 av_free(pkt_data);
2823 continue;
2825 pkt_size -= olen;
2826 break;
2827 #ifdef CONFIG_ZLIB
2828 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
2829 z_stream zstream = {0};
2830 pkt_data = NULL;
2831 if (inflateInit(&zstream) != Z_OK)
2832 continue;
2833 zstream.next_in = data;
2834 zstream.avail_in = lace_size[n];
2835 do {
2836 pkt_size *= 3;
2837 pkt_data = av_realloc(pkt_data, pkt_size);
2838 zstream.avail_out = pkt_size - zstream.total_out;
2839 zstream.next_out = pkt_data + zstream.total_out;
2840 result = inflate(&zstream, Z_NO_FLUSH);
2841 } while (result==Z_OK && pkt_size<10000000);
2842 pkt_size = zstream.total_out;
2843 inflateEnd(&zstream);
2844 if (result != Z_STREAM_END) {
2845 av_free(pkt_data);
2846 continue;
2848 break;
2850 #endif
2851 #ifdef CONFIG_BZLIB
2852 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
2853 bz_stream bzstream = {0};
2854 pkt_data = NULL;
2855 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
2856 continue;
2857 bzstream.next_in = data;
2858 bzstream.avail_in = lace_size[n];
2859 do {
2860 pkt_size *= 3;
2861 pkt_data = av_realloc(pkt_data, pkt_size);
2862 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
2863 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
2864 result = BZ2_bzDecompress(&bzstream);
2865 } while (result==BZ_OK && pkt_size<10000000);
2866 pkt_size = bzstream.total_out_lo32;
2867 BZ2_bzDecompressEnd(&bzstream);
2868 if (result != BZ_STREAM_END) {
2869 av_free(pkt_data);
2870 continue;
2872 break;
2874 #endif
2878 pkt = av_mallocz(sizeof(AVPacket));
2879 /* XXX: prevent data copy... */
2880 if (av_new_packet(pkt, pkt_size+offset) < 0) {
2881 av_free(pkt);
2882 res = AVERROR(ENOMEM);
2883 n = laces-1;
2884 break;
2886 if (offset)
2887 memcpy (pkt->data, matroska->tracks[track]->encoding_settings, offset);
2888 memcpy (pkt->data+offset, pkt_data, pkt_size);
2890 if (n == 0)
2891 pkt->flags = is_keyframe;
2892 pkt->stream_index = stream_index;
2894 pkt->pts = timecode;
2895 pkt->pos = pos;
2896 pkt->duration = duration;
2898 matroska_queue_packet(matroska, pkt);
2901 if (timecode != AV_NOPTS_VALUE)
2902 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2903 data += lace_size[n];
2907 av_free(lace_size);
2908 av_free(origdata);
2909 return res;
2912 static int
2913 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2914 uint64_t cluster_time)
2916 int res = 0;
2917 uint32_t id;
2918 int is_bframe = 0;
2919 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2920 uint64_t duration = AV_NOPTS_VALUE;
2921 uint8_t *data;
2922 int size = 0;
2923 int64_t pos = 0;
2925 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2927 while (res == 0) {
2928 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2929 res = AVERROR(EIO);
2930 break;
2931 } else if (matroska->level_up) {
2932 matroska->level_up--;
2933 break;
2936 switch (id) {
2937 /* one block inside the group. Note, block parsing is one
2938 * of the harder things, so this code is a bit complicated.
2939 * See http://www.matroska.org/ for documentation. */
2940 case MATROSKA_ID_BLOCK: {
2941 pos = url_ftell(matroska->ctx->pb);
2942 res = ebml_read_binary(matroska, &id, &data, &size);
2943 break;
2946 case MATROSKA_ID_BLOCKDURATION: {
2947 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2948 break;
2949 break;
2952 case MATROSKA_ID_BLOCKREFERENCE: {
2953 int64_t num;
2954 /* We've found a reference, so not even the first frame in
2955 * the lace is a key frame. */
2956 is_keyframe = 0;
2957 if (last_num_packets != matroska->num_packets)
2958 matroska->packets[last_num_packets]->flags = 0;
2959 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2960 break;
2961 if (num > 0)
2962 is_bframe = 1;
2963 break;
2966 default:
2967 av_log(matroska->ctx, AV_LOG_INFO,
2968 "Unknown entry 0x%x in blockgroup data\n", id);
2969 /* fall-through */
2971 case EBML_ID_VOID:
2972 res = ebml_read_skip(matroska);
2973 break;
2976 if (matroska->level_up) {
2977 matroska->level_up--;
2978 break;
2982 if (res)
2983 return res;
2985 if (size > 0)
2986 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2987 duration, is_keyframe, is_bframe);
2989 return res;
2992 static int
2993 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2995 int res = 0;
2996 uint32_t id;
2997 uint64_t cluster_time = 0;
2998 uint8_t *data;
2999 int64_t pos;
3000 int size;
3002 av_log(matroska->ctx, AV_LOG_DEBUG,
3003 "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
3005 while (res == 0) {
3006 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3007 res = AVERROR(EIO);
3008 break;
3009 } else if (matroska->level_up) {
3010 matroska->level_up--;
3011 break;
3014 switch (id) {
3015 /* cluster timecode */
3016 case MATROSKA_ID_CLUSTERTIMECODE: {
3017 uint64_t num;
3018 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
3019 break;
3020 cluster_time = num;
3021 break;
3024 /* a group of blocks inside a cluster */
3025 case MATROSKA_ID_BLOCKGROUP:
3026 if ((res = ebml_read_master(matroska, &id)) < 0)
3027 break;
3028 res = matroska_parse_blockgroup(matroska, cluster_time);
3029 break;
3031 case MATROSKA_ID_SIMPLEBLOCK:
3032 pos = url_ftell(matroska->ctx->pb);
3033 res = ebml_read_binary(matroska, &id, &data, &size);
3034 if (res == 0)
3035 res = matroska_parse_block(matroska, data, size, pos,
3036 cluster_time, AV_NOPTS_VALUE,
3037 -1, 0);
3038 break;
3040 default:
3041 av_log(matroska->ctx, AV_LOG_INFO,
3042 "Unknown entry 0x%x in cluster data\n", id);
3043 /* fall-through */
3045 case EBML_ID_VOID:
3046 res = ebml_read_skip(matroska);
3047 break;
3050 if (matroska->level_up) {
3051 matroska->level_up--;
3052 break;
3056 return res;
3059 static int
3060 matroska_read_packet (AVFormatContext *s,
3061 AVPacket *pkt)
3063 MatroskaDemuxContext *matroska = s->priv_data;
3064 int res;
3065 uint32_t id;
3067 /* Read stream until we have a packet queued. */
3068 while (matroska_deliver_packet(matroska, pkt)) {
3070 /* Have we already reached the end? */
3071 if (matroska->done)
3072 return AVERROR(EIO);
3074 res = 0;
3075 while (res == 0) {
3076 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3077 return AVERROR(EIO);
3078 } else if (matroska->level_up) {
3079 matroska->level_up--;
3080 break;
3083 switch (id) {
3084 case MATROSKA_ID_CLUSTER:
3085 if ((res = ebml_read_master(matroska, &id)) < 0)
3086 break;
3087 if ((res = matroska_parse_cluster(matroska)) == 0)
3088 res = 1; /* Parsed one cluster, let's get out. */
3089 break;
3091 default:
3092 case EBML_ID_VOID:
3093 res = ebml_read_skip(matroska);
3094 break;
3097 if (matroska->level_up) {
3098 matroska->level_up--;
3099 break;
3103 if (res == -1)
3104 matroska->done = 1;
3107 return 0;
3110 static int
3111 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
3112 int flags)
3114 MatroskaDemuxContext *matroska = s->priv_data;
3115 AVStream *st = s->streams[stream_index];
3116 int index;
3118 /* find index entry */
3119 index = av_index_search_timestamp(st, timestamp, flags);
3120 if (index < 0)
3121 return 0;
3123 matroska_clear_queue(matroska);
3125 /* do the seek */
3126 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
3127 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
3128 matroska->skip_to_stream = st;
3129 matroska->peek_id = 0;
3130 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
3131 return 0;
3134 static int
3135 matroska_read_close (AVFormatContext *s)
3137 MatroskaDemuxContext *matroska = s->priv_data;
3138 int n = 0;
3140 av_free(matroska->index);
3142 matroska_clear_queue(matroska);
3144 for (n = 0; n < matroska->num_tracks; n++) {
3145 MatroskaTrack *track = matroska->tracks[n];
3146 av_free(track->codec_id);
3147 av_free(track->codec_priv);
3148 av_free(track->name);
3150 if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
3151 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
3152 av_free(audiotrack->buf);
3155 av_free(track);
3158 return 0;
3161 AVInputFormat matroska_demuxer = {
3162 "matroska",
3163 NULL_IF_CONFIG_SMALL("Matroska file format"),
3164 sizeof(MatroskaDemuxContext),
3165 matroska_probe,
3166 matroska_read_header,
3167 matroska_read_packet,
3168 matroska_read_close,
3169 matroska_read_seek,