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(). */
34 #include "intfloat_readwrite.h"
36 #include "libavcodec/mpeg4audio.h"
38 typedef struct Track {
39 MatroskaTrackType type;
41 /* Unique track number and track ID. stream_index is the index that
42 * the calling app uses for this track. */
53 unsigned char *codec_priv;
56 uint64_t default_duration;
57 MatroskaTrackFlags flags;
60 typedef struct MatroskaVideoTrack {
70 MatroskaAspectRatioMode ar_mode;
71 MatroskaEyeMode eye_mode;
76 typedef struct MatroskaAudioTrack {
81 int internal_samplerate;
85 /* real audio header */
96 typedef struct MatroskaSubtitleTrack {
99 } MatroskaSubtitleTrack;
101 #define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
102 sizeof(MatroskaAudioTrack), \
103 sizeof(MatroskaSubtitleTrack)))
105 typedef struct MatroskaLevel {
110 typedef struct MatroskaDemuxIndex {
111 uint64_t pos; /* of the corresponding *cluster*! */
112 uint16_t track; /* reference to 'num' */
113 uint64_t time; /* in nanoseconds */
114 } MatroskaDemuxIndex;
116 typedef struct MatroskaDemuxContext {
117 AVFormatContext *ctx;
121 MatroskaLevel levels[EBML_MAX_DEPTH];
129 /* timescale in the file */
132 /* num_streams is the number of streams that av_new_stream() was called
133 * for ( = that are available to the calling program). */
136 MatroskaTrack *tracks[MAX_STREAMS];
138 /* cache for ID peeking */
141 /* byte position of the segment inside the stream */
142 offset_t segment_start;
144 /* The packet queue. */
148 /* have we already parse metadata/cues/clusters? */
153 /* The index for seeking. */
155 MatroskaDemuxIndex *index;
157 /* What to skip before effectively reading a packet. */
158 int skip_to_keyframe;
159 AVStream *skip_to_stream;
160 } MatroskaDemuxContext;
163 * The first few functions handle EBML file parsing. The rest
164 * is the document interpretation. Matroska really just is a
169 * Return: the amount of levels in the hierarchy that the
170 * current element lies higher than the previous one.
171 * The opposite isn't done - that's auto-done using master
176 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
178 ByteIOContext *pb = matroska->ctx->pb;
179 offset_t pos = url_ftell(pb);
182 while (matroska->num_levels > 0) {
183 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
185 if (pos >= level->start + level->length) {
186 matroska->num_levels--;
197 * Read: an "EBML number", which is defined as a variable-length
198 * array of bytes. The first byte indicates the length by giving a
199 * number of 0-bits followed by a one. The position of the first
200 * "one" bit inside the first byte indicates the length of this
202 * Returns: num. of bytes read. < 0 on error.
206 ebml_read_num (MatroskaDemuxContext *matroska,
210 ByteIOContext *pb = matroska->ctx->pb;
211 int len_mask = 0x80, read = 1, n = 1;
214 /* the first byte tells us the length in bytes - get_byte() can normally
215 * return 0, but since that's not a valid first ebmlID byte, we can
216 * use it safely here to catch EOS. */
217 if (!(total = get_byte(pb))) {
218 /* we might encounter EOS here */
220 offset_t pos = url_ftell(pb);
221 av_log(matroska->ctx, AV_LOG_ERROR,
222 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
225 return AVERROR(EIO); /* EOS or actual I/O error */
228 /* get the length of the EBML number */
229 while (read <= max_size && !(total & len_mask)) {
233 if (read > max_size) {
234 offset_t pos = url_ftell(pb) - 1;
235 av_log(matroska->ctx, AV_LOG_ERROR,
236 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
237 (uint8_t) total, pos, pos);
238 return AVERROR_INVALIDDATA;
241 /* read out length */
244 total = (total << 8) | get_byte(pb);
252 * Read: the element content data ID.
253 * Return: the number of bytes read or < 0 on error.
257 ebml_read_element_id (MatroskaDemuxContext *matroska,
264 /* if we re-call this, use our cached ID */
265 if (matroska->peek_id != 0) {
268 *id = matroska->peek_id;
272 /* read out the "EBML number", include tag in ID */
273 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
275 *id = matroska->peek_id = total | (1 << (read * 7));
279 *level_up = ebml_read_element_level_up(matroska);
285 * Read: element content length.
286 * Return: the number of bytes read or < 0 on error.
290 ebml_read_element_length (MatroskaDemuxContext *matroska,
293 /* clear cache since we're now beyond that data point */
294 matroska->peek_id = 0;
296 /* read out the "EBML number", include tag in ID */
297 return ebml_read_num(matroska, 8, length);
301 * Return: the ID of the next element, or 0 on error.
302 * Level_up contains the amount of levels that this
303 * next element lies higher than the previous one.
307 ebml_peek_id (MatroskaDemuxContext *matroska,
312 if (ebml_read_element_id(matroska, &id, level_up) < 0)
319 * Seek to a given offset.
320 * 0 is success, -1 is failure.
324 ebml_read_seek (MatroskaDemuxContext *matroska,
327 ByteIOContext *pb = matroska->ctx->pb;
329 /* clear ID cache, if any */
330 matroska->peek_id = 0;
332 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
336 * Skip the next element.
337 * 0 is success, -1 is failure.
341 ebml_read_skip (MatroskaDemuxContext *matroska)
343 ByteIOContext *pb = matroska->ctx->pb;
348 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
349 (res = ebml_read_element_length(matroska, &length)) < 0)
352 url_fskip(pb, length);
358 * Read the next element as an unsigned int.
359 * 0 is success, < 0 is failure.
363 ebml_read_uint (MatroskaDemuxContext *matroska,
367 ByteIOContext *pb = matroska->ctx->pb;
368 int n = 0, size, res;
371 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
372 (res = ebml_read_element_length(matroska, &rlength)) < 0)
375 if (size < 1 || size > 8) {
376 offset_t pos = url_ftell(pb);
377 av_log(matroska->ctx, AV_LOG_ERROR,
378 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
380 return AVERROR_INVALIDDATA;
383 /* big-endian ordening; build up number */
386 *num = (*num << 8) | get_byte(pb);
392 * Read the next element as a signed int.
393 * 0 is success, < 0 is failure.
397 ebml_read_sint (MatroskaDemuxContext *matroska,
401 ByteIOContext *pb = matroska->ctx->pb;
402 int size, n = 1, negative = 0, res;
405 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
406 (res = ebml_read_element_length(matroska, &rlength)) < 0)
409 if (size < 1 || size > 8) {
410 offset_t pos = url_ftell(pb);
411 av_log(matroska->ctx, AV_LOG_ERROR,
412 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
414 return AVERROR_INVALIDDATA;
416 if ((*num = get_byte(pb)) & 0x80) {
421 *num = (*num << 8) | get_byte(pb);
425 *num = *num - (1LL << ((8 * size) - 1));
431 * Read the next element as a float.
432 * 0 is success, < 0 is failure.
436 ebml_read_float (MatroskaDemuxContext *matroska,
440 ByteIOContext *pb = matroska->ctx->pb;
444 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
445 (res = ebml_read_element_length(matroska, &rlength)) < 0)
450 *num= av_int2flt(get_be32(pb));
452 *num= av_int2dbl(get_be64(pb));
454 offset_t pos = url_ftell(pb);
455 av_log(matroska->ctx, AV_LOG_ERROR,
456 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
458 return AVERROR_INVALIDDATA;
465 * Read the next element as an ASCII string.
466 * 0 is success, < 0 is failure.
470 ebml_read_ascii (MatroskaDemuxContext *matroska,
474 ByteIOContext *pb = matroska->ctx->pb;
478 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
479 (res = ebml_read_element_length(matroska, &rlength)) < 0)
483 /* ebml strings are usually not 0-terminated, so we allocate one
484 * byte more, read the string and NULL-terminate it ourselves. */
485 if (size < 0 || !(*str = av_malloc(size + 1))) {
486 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
487 return AVERROR(ENOMEM);
489 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
490 offset_t pos = url_ftell(pb);
491 av_log(matroska->ctx, AV_LOG_ERROR,
492 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
501 * Read the next element as a UTF-8 string.
502 * 0 is success, < 0 is failure.
506 ebml_read_utf8 (MatroskaDemuxContext *matroska,
510 return ebml_read_ascii(matroska, id, str);
514 * Read the next element as a date (nanoseconds since 1/1/2000).
515 * 0 is success, < 0 is failure.
519 ebml_read_date (MatroskaDemuxContext *matroska,
523 return ebml_read_sint(matroska, id, date);
527 * Read the next element, but only the header. The contents
528 * are supposed to be sub-elements which can be read separately.
529 * 0 is success, < 0 is failure.
533 ebml_read_master (MatroskaDemuxContext *matroska,
536 ByteIOContext *pb = matroska->ctx->pb;
538 MatroskaLevel *level;
541 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
542 (res = ebml_read_element_length(matroska, &length)) < 0)
545 /* protect... (Heaven forbids that the '>' is true) */
546 if (matroska->num_levels >= EBML_MAX_DEPTH) {
547 av_log(matroska->ctx, AV_LOG_ERROR,
548 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
549 return AVERROR(ENOSYS);
553 level = &matroska->levels[matroska->num_levels++];
554 level->start = url_ftell(pb);
555 level->length = length;
561 * Read the next element as binary data.
562 * 0 is success, < 0 is failure.
566 ebml_read_binary (MatroskaDemuxContext *matroska,
571 ByteIOContext *pb = matroska->ctx->pb;
575 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
576 (res = ebml_read_element_length(matroska, &rlength)) < 0)
580 if (!(*binary = av_malloc(*size))) {
581 av_log(matroska->ctx, AV_LOG_ERROR,
582 "Memory allocation error\n");
583 return AVERROR(ENOMEM);
586 if (get_buffer(pb, *binary, *size) != *size) {
587 offset_t pos = url_ftell(pb);
588 av_log(matroska->ctx, AV_LOG_ERROR,
589 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
597 * Read signed/unsigned "EBML" numbers.
598 * Return: number of bytes processed, < 0 on error.
599 * XXX: use ebml_read_num().
603 matroska_ebmlnum_uint (uint8_t *data,
607 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
611 return AVERROR_INVALIDDATA;
614 while (read <= 8 && !(total & len_mask)) {
619 return AVERROR_INVALIDDATA;
621 if ((total &= (len_mask - 1)) == len_mask - 1)
624 return AVERROR_INVALIDDATA;
628 total = (total << 8) | data[n];
641 * Same as above, but signed.
645 matroska_ebmlnum_sint (uint8_t *data,
652 /* read as unsigned number first */
653 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
656 /* make signed (weird way) */
657 if (unum == (uint64_t)-1)
660 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
666 * Read an EBML header.
667 * 0 is success, < 0 is failure.
671 ebml_read_header (MatroskaDemuxContext *matroska,
676 int level_up, res = 0;
684 if (!(id = ebml_peek_id(matroska, &level_up)) ||
685 level_up != 0 || id != EBML_ID_HEADER) {
686 av_log(matroska->ctx, AV_LOG_ERROR,
687 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
688 return AVERROR_INVALIDDATA;
690 if ((res = ebml_read_master(matroska, &id)) < 0)
694 if (!(id = ebml_peek_id(matroska, &level_up)))
702 /* is our read version uptodate? */
703 case EBML_ID_EBMLREADVERSION: {
706 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
708 if (num > EBML_VERSION) {
709 av_log(matroska->ctx, AV_LOG_ERROR,
710 "EBML version %"PRIu64" (> %d) is not supported\n",
712 return AVERROR_INVALIDDATA;
717 /* we only handle 8 byte lengths at max */
718 case EBML_ID_EBMLMAXSIZELENGTH: {
721 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
723 if (num > sizeof(uint64_t)) {
724 av_log(matroska->ctx, AV_LOG_ERROR,
725 "Integers of size %"PRIu64" (> %zd) not supported\n",
726 num, sizeof(uint64_t));
727 return AVERROR_INVALIDDATA;
732 /* we handle 4 byte IDs at max */
733 case EBML_ID_EBMLMAXIDLENGTH: {
736 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
738 if (num > sizeof(uint32_t)) {
739 av_log(matroska->ctx, AV_LOG_ERROR,
740 "IDs of size %"PRIu64" (> %zu) not supported\n",
741 num, sizeof(uint32_t));
742 return AVERROR_INVALIDDATA;
747 case EBML_ID_DOCTYPE: {
750 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
761 case EBML_ID_DOCTYPEREADVERSION: {
764 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
772 av_log(matroska->ctx, AV_LOG_INFO,
773 "Unknown data type 0x%x in EBML header", id);
777 /* we ignore these two, as they don't tell us anything we
779 case EBML_ID_EBMLVERSION:
780 case EBML_ID_DOCTYPEVERSION:
781 res = ebml_read_skip (matroska);
791 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
796 for (i = 0; i < matroska->num_tracks; i++)
797 if (matroska->tracks[i]->num == num)
805 * Put one packet in an application-supplied AVPacket struct.
806 * Returns 0 on success or -1 on failure.
810 matroska_deliver_packet (MatroskaDemuxContext *matroska,
813 if (matroska->num_packets > 0) {
814 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
815 av_free(matroska->packets[0]);
816 if (matroska->num_packets > 1) {
817 memmove(&matroska->packets[0], &matroska->packets[1],
818 (matroska->num_packets - 1) * sizeof(AVPacket *));
820 av_realloc(matroska->packets, (matroska->num_packets - 1) *
823 av_freep(&matroska->packets);
825 matroska->num_packets--;
833 * Put a packet into our internal queue. Will be delivered to the
834 * user/application during the next get_packet() call.
838 matroska_queue_packet (MatroskaDemuxContext *matroska,
842 av_realloc(matroska->packets, (matroska->num_packets + 1) *
844 matroska->packets[matroska->num_packets] = pkt;
845 matroska->num_packets++;
849 * Free all packets in our internal queue.
852 matroska_clear_queue (MatroskaDemuxContext *matroska)
854 if (matroska->packets) {
856 for (n = 0; n < matroska->num_packets; n++) {
857 av_free_packet(matroska->packets[n]);
858 av_free(matroska->packets[n]);
860 av_free(matroska->packets);
861 matroska->packets = NULL;
862 matroska->num_packets = 0;
872 matroska_probe (AVProbeData *p)
875 int len_mask = 0x80, size = 1, n = 1;
876 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
879 if (AV_RB32(p->buf) != EBML_ID_HEADER)
882 /* length of header */
884 while (size <= 8 && !(total & len_mask)) {
890 total &= (len_mask - 1);
892 total = (total << 8) | p->buf[4 + n++];
894 /* does the probe data contain the whole header? */
895 if (p->buf_size < 4 + size + total)
898 /* the header must contain the document type 'matroska'. For now,
899 * we don't parse the whole header but simply check for the
900 * availability of that array of characters inside the header.
901 * Not fully fool-proof, but good enough. */
902 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
903 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
904 return AVPROBE_SCORE_MAX;
910 * From here on, it's all XML-style DTD stuff... Needs no comments.
914 matroska_parse_info (MatroskaDemuxContext *matroska)
919 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
922 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
925 } else if (matroska->level_up) {
926 matroska->level_up--;
931 /* cluster timecode */
932 case MATROSKA_ID_TIMECODESCALE: {
934 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
936 matroska->time_scale = num;
940 case MATROSKA_ID_DURATION: {
942 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
944 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
948 case MATROSKA_ID_TITLE: {
950 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
952 strncpy(matroska->ctx->title, text,
953 sizeof(matroska->ctx->title)-1);
958 case MATROSKA_ID_WRITINGAPP: {
960 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
962 matroska->writing_app = text;
966 case MATROSKA_ID_MUXINGAPP: {
968 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
970 matroska->muxing_app = text;
974 case MATROSKA_ID_DATEUTC: {
976 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
978 matroska->created = time;
983 av_log(matroska->ctx, AV_LOG_INFO,
984 "Unknown entry 0x%x in info header\n", id);
988 res = ebml_read_skip(matroska);
992 if (matroska->level_up) {
993 matroska->level_up--;
1002 matroska_add_stream (MatroskaDemuxContext *matroska)
1006 MatroskaTrack *track;
1008 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1010 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1011 track = av_mallocz(MAX_TRACK_SIZE);
1012 matroska->num_tracks++;
1013 strcpy(track->language, "eng");
1015 /* start with the master */
1016 if ((res = ebml_read_master(matroska, &id)) < 0)
1019 /* try reading the trackentry headers */
1021 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1024 } else if (matroska->level_up > 0) {
1025 matroska->level_up--;
1030 /* track number (unique stream ID) */
1031 case MATROSKA_ID_TRACKNUMBER: {
1033 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1039 /* track UID (unique identifier) */
1040 case MATROSKA_ID_TRACKUID: {
1042 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1048 /* track type (video, audio, combined, subtitle, etc.) */
1049 case MATROSKA_ID_TRACKTYPE: {
1051 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1053 if (track->type && track->type != num) {
1054 av_log(matroska->ctx, AV_LOG_INFO,
1055 "More than one tracktype in an entry - skip\n");
1060 switch (track->type) {
1061 case MATROSKA_TRACK_TYPE_VIDEO:
1062 case MATROSKA_TRACK_TYPE_AUDIO:
1063 case MATROSKA_TRACK_TYPE_SUBTITLE:
1065 case MATROSKA_TRACK_TYPE_COMPLEX:
1066 case MATROSKA_TRACK_TYPE_LOGO:
1067 case MATROSKA_TRACK_TYPE_CONTROL:
1069 av_log(matroska->ctx, AV_LOG_INFO,
1070 "Unknown or unsupported track type 0x%x\n",
1075 matroska->tracks[matroska->num_tracks - 1] = track;
1079 /* tracktype specific stuff for video */
1080 case MATROSKA_ID_TRACKVIDEO: {
1081 MatroskaVideoTrack *videotrack;
1083 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1084 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1085 av_log(matroska->ctx, AV_LOG_INFO,
1086 "video data in non-video track - ignoring\n");
1087 res = AVERROR_INVALIDDATA;
1089 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1091 videotrack = (MatroskaVideoTrack *)track;
1094 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1097 } else if (matroska->level_up > 0) {
1098 matroska->level_up--;
1103 /* fixme, this should be one-up, but I get it here */
1104 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1106 if ((res = ebml_read_uint (matroska, &id,
1109 track->default_duration = num;
1113 /* video framerate */
1114 case MATROSKA_ID_VIDEOFRAMERATE: {
1116 if ((res = ebml_read_float(matroska, &id,
1119 if (!track->default_duration)
1120 track->default_duration = 1000000000/num;
1124 /* width of the size to display the video at */
1125 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1127 if ((res = ebml_read_uint(matroska, &id,
1130 videotrack->display_width = num;
1134 /* height of the size to display the video at */
1135 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1137 if ((res = ebml_read_uint(matroska, &id,
1140 videotrack->display_height = num;
1144 /* width of the video in the file */
1145 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1147 if ((res = ebml_read_uint(matroska, &id,
1150 videotrack->pixel_width = num;
1154 /* height of the video in the file */
1155 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1157 if ((res = ebml_read_uint(matroska, &id,
1160 videotrack->pixel_height = num;
1164 /* whether the video is interlaced */
1165 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1167 if ((res = ebml_read_uint(matroska, &id,
1172 MATROSKA_VIDEOTRACK_INTERLACED;
1175 ~MATROSKA_VIDEOTRACK_INTERLACED;
1179 /* stereo mode (whether the video has two streams,
1180 * where one is for the left eye and the other for
1181 * the right eye, which creates a 3D-like
1183 case MATROSKA_ID_VIDEOSTEREOMODE: {
1185 if ((res = ebml_read_uint(matroska, &id,
1188 if (num != MATROSKA_EYE_MODE_MONO &&
1189 num != MATROSKA_EYE_MODE_LEFT &&
1190 num != MATROSKA_EYE_MODE_RIGHT &&
1191 num != MATROSKA_EYE_MODE_BOTH) {
1192 av_log(matroska->ctx, AV_LOG_INFO,
1193 "Ignoring unknown eye mode 0x%x\n",
1197 videotrack->eye_mode = num;
1201 /* aspect ratio behaviour */
1202 case MATROSKA_ID_VIDEOASPECTRATIO: {
1204 if ((res = ebml_read_uint(matroska, &id,
1207 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1208 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1209 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1210 av_log(matroska->ctx, AV_LOG_INFO,
1211 "Ignoring unknown aspect ratio 0x%x\n",
1215 videotrack->ar_mode = num;
1219 /* colorspace (only matters for raw video)
1221 case MATROSKA_ID_VIDEOCOLORSPACE: {
1223 if ((res = ebml_read_uint(matroska, &id,
1226 videotrack->fourcc = num;
1231 av_log(matroska->ctx, AV_LOG_INFO,
1232 "Unknown video track header entry "
1233 "0x%x - ignoring\n", id);
1237 res = ebml_read_skip(matroska);
1241 if (matroska->level_up) {
1242 matroska->level_up--;
1249 /* tracktype specific stuff for audio */
1250 case MATROSKA_ID_TRACKAUDIO: {
1251 MatroskaAudioTrack *audiotrack;
1253 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1254 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1255 av_log(matroska->ctx, AV_LOG_INFO,
1256 "audio data in non-audio track - ignoring\n");
1257 res = AVERROR_INVALIDDATA;
1259 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1261 audiotrack = (MatroskaAudioTrack *)track;
1262 audiotrack->channels = 1;
1263 audiotrack->samplerate = 8000;
1266 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1269 } else if (matroska->level_up > 0) {
1270 matroska->level_up--;
1276 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1278 if ((res = ebml_read_float(matroska, &id,
1281 audiotrack->internal_samplerate =
1282 audiotrack->samplerate = num;
1286 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1288 if ((res = ebml_read_float(matroska, &id,
1291 audiotrack->samplerate = num;
1296 case MATROSKA_ID_AUDIOBITDEPTH: {
1298 if ((res = ebml_read_uint(matroska, &id,
1301 audiotrack->bitdepth = num;
1306 case MATROSKA_ID_AUDIOCHANNELS: {
1308 if ((res = ebml_read_uint(matroska, &id,
1311 audiotrack->channels = num;
1316 av_log(matroska->ctx, AV_LOG_INFO,
1317 "Unknown audio track header entry "
1318 "0x%x - ignoring\n", id);
1322 res = ebml_read_skip(matroska);
1326 if (matroska->level_up) {
1327 matroska->level_up--;
1334 /* codec identifier */
1335 case MATROSKA_ID_CODECID: {
1337 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1339 track->codec_id = text;
1343 /* codec private data */
1344 case MATROSKA_ID_CODECPRIVATE: {
1347 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1349 track->codec_priv = data;
1350 track->codec_priv_size = size;
1354 /* name of the codec */
1355 case MATROSKA_ID_CODECNAME: {
1357 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1359 track->codec_name = text;
1363 /* name of this track */
1364 case MATROSKA_ID_TRACKNAME: {
1366 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1372 /* language (matters for audio/subtitles, mostly) */
1373 case MATROSKA_ID_TRACKLANGUAGE: {
1375 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1377 if ((end = strchr(text, '-')))
1379 if (strlen(text) == 3)
1380 strcpy(track->language, text);
1385 /* whether this is actually used */
1386 case MATROSKA_ID_TRACKFLAGENABLED: {
1388 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1391 track->flags |= MATROSKA_TRACK_ENABLED;
1393 track->flags &= ~MATROSKA_TRACK_ENABLED;
1397 /* whether it's the default for this track type */
1398 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1400 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1403 track->flags |= MATROSKA_TRACK_DEFAULT;
1405 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1409 /* lacing (like MPEG, where blocks don't end/start on frame
1411 case MATROSKA_ID_TRACKFLAGLACING: {
1413 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1416 track->flags |= MATROSKA_TRACK_LACING;
1418 track->flags &= ~MATROSKA_TRACK_LACING;
1422 /* default length (in time) of one data block in this track */
1423 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1425 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1427 track->default_duration = num;
1432 av_log(matroska->ctx, AV_LOG_INFO,
1433 "Unknown track header entry 0x%x - ignoring\n", id);
1437 /* we ignore these because they're nothing useful. */
1438 case MATROSKA_ID_CODECINFOURL:
1439 case MATROSKA_ID_CODECDOWNLOADURL:
1440 case MATROSKA_ID_TRACKMINCACHE:
1441 case MATROSKA_ID_TRACKMAXCACHE:
1442 res = ebml_read_skip(matroska);
1446 if (matroska->level_up) {
1447 matroska->level_up--;
1456 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1461 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1464 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1467 } else if (matroska->level_up) {
1468 matroska->level_up--;
1473 /* one track within the "all-tracks" header */
1474 case MATROSKA_ID_TRACKENTRY:
1475 res = matroska_add_stream(matroska);
1479 av_log(matroska->ctx, AV_LOG_INFO,
1480 "Unknown entry 0x%x in track header\n", id);
1484 res = ebml_read_skip(matroska);
1488 if (matroska->level_up) {
1489 matroska->level_up--;
1498 matroska_parse_index (MatroskaDemuxContext *matroska)
1502 MatroskaDemuxIndex idx;
1504 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1507 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1510 } else if (matroska->level_up) {
1511 matroska->level_up--;
1516 /* one single index entry ('point') */
1517 case MATROSKA_ID_POINTENTRY:
1518 if ((res = ebml_read_master(matroska, &id)) < 0)
1521 /* in the end, we hope to fill one entry with a
1522 * timestamp, a file position and a tracknum */
1523 idx.pos = (uint64_t) -1;
1524 idx.time = (uint64_t) -1;
1525 idx.track = (uint16_t) -1;
1528 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1531 } else if (matroska->level_up) {
1532 matroska->level_up--;
1537 /* one single index entry ('point') */
1538 case MATROSKA_ID_CUETIME: {
1540 if ((res = ebml_read_uint(matroska, &id,
1543 idx.time = time * matroska->time_scale;
1547 /* position in the file + track to which it
1549 case MATROSKA_ID_CUETRACKPOSITION:
1550 if ((res = ebml_read_master(matroska, &id)) < 0)
1554 if (!(id = ebml_peek_id (matroska,
1555 &matroska->level_up))) {
1558 } else if (matroska->level_up) {
1559 matroska->level_up--;
1565 case MATROSKA_ID_CUETRACK: {
1567 if ((res = ebml_read_uint(matroska,
1574 /* position in file */
1575 case MATROSKA_ID_CUECLUSTERPOSITION: {
1577 if ((res = ebml_read_uint(matroska,
1580 idx.pos = num+matroska->segment_start;
1585 av_log(matroska->ctx, AV_LOG_INFO,
1586 "Unknown entry 0x%x in "
1587 "CuesTrackPositions\n", id);
1591 res = ebml_read_skip(matroska);
1595 if (matroska->level_up) {
1596 matroska->level_up--;
1604 av_log(matroska->ctx, AV_LOG_INFO,
1605 "Unknown entry 0x%x in cuespoint "
1610 res = ebml_read_skip(matroska);
1614 if (matroska->level_up) {
1615 matroska->level_up--;
1620 /* so let's see if we got what we wanted */
1621 if (idx.pos != (uint64_t) -1 &&
1622 idx.time != (uint64_t) -1 &&
1623 idx.track != (uint16_t) -1) {
1624 if (matroska->num_indexes % 32 == 0) {
1625 /* re-allocate bigger index */
1627 av_realloc(matroska->index,
1628 (matroska->num_indexes + 32) *
1629 sizeof(MatroskaDemuxIndex));
1631 matroska->index[matroska->num_indexes] = idx;
1632 matroska->num_indexes++;
1637 av_log(matroska->ctx, AV_LOG_INFO,
1638 "Unknown entry 0x%x in cues header\n", id);
1642 res = ebml_read_skip(matroska);
1646 if (matroska->level_up) {
1647 matroska->level_up--;
1656 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1662 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1665 } else if (matroska->level_up) {
1666 matroska->level_up--;
1671 /* Hm, this is unsupported... */
1673 av_log(matroska->ctx, AV_LOG_INFO,
1674 "Unknown entry 0x%x in metadata header\n", id);
1678 res = ebml_read_skip(matroska);
1682 if (matroska->level_up) {
1683 matroska->level_up--;
1692 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1697 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1700 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1703 } else if (matroska->level_up) {
1704 matroska->level_up--;
1709 case MATROSKA_ID_SEEKENTRY: {
1710 uint32_t seek_id = 0, peek_id_cache = 0;
1711 uint64_t seek_pos = (uint64_t) -1, t;
1713 if ((res = ebml_read_master(matroska, &id)) < 0)
1717 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1720 } else if (matroska->level_up) {
1721 matroska->level_up--;
1726 case MATROSKA_ID_SEEKID:
1727 res = ebml_read_uint(matroska, &id, &t);
1731 case MATROSKA_ID_SEEKPOSITION:
1732 res = ebml_read_uint(matroska, &id, &seek_pos);
1736 av_log(matroska->ctx, AV_LOG_INFO,
1737 "Unknown seekhead ID 0x%x\n", id);
1741 res = ebml_read_skip(matroska);
1745 if (matroska->level_up) {
1746 matroska->level_up--;
1751 if (!seek_id || seek_pos == (uint64_t) -1) {
1752 av_log(matroska->ctx, AV_LOG_INFO,
1753 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1759 case MATROSKA_ID_CUES:
1760 case MATROSKA_ID_TAGS: {
1761 uint32_t level_up = matroska->level_up;
1762 offset_t before_pos;
1764 MatroskaLevel level;
1766 /* remember the peeked ID and the current position */
1767 peek_id_cache = matroska->peek_id;
1768 before_pos = url_ftell(matroska->ctx->pb);
1771 if ((res = ebml_read_seek(matroska, seek_pos +
1772 matroska->segment_start)) < 0)
1775 /* we don't want to lose our seekhead level, so we add
1776 * a dummy. This is a crude hack. */
1777 if (matroska->num_levels == EBML_MAX_DEPTH) {
1778 av_log(matroska->ctx, AV_LOG_INFO,
1779 "Max EBML element depth (%d) reached, "
1780 "cannot parse further.\n", EBML_MAX_DEPTH);
1781 return AVERROR_UNKNOWN;
1785 level.length = (uint64_t)-1;
1786 matroska->levels[matroska->num_levels] = level;
1787 matroska->num_levels++;
1790 if (!(id = ebml_peek_id (matroska,
1791 &matroska->level_up)))
1793 if (id != seek_id) {
1794 av_log(matroska->ctx, AV_LOG_INFO,
1795 "We looked for ID=0x%x but got "
1796 "ID=0x%x (pos=%"PRIu64")",
1797 seek_id, id, seek_pos +
1798 matroska->segment_start);
1802 /* read master + parse */
1803 if ((res = ebml_read_master(matroska, &id)) < 0)
1806 case MATROSKA_ID_CUES:
1807 if (!(res = matroska_parse_index(matroska)) ||
1808 url_feof(matroska->ctx->pb)) {
1809 matroska->index_parsed = 1;
1813 case MATROSKA_ID_TAGS:
1814 if (!(res = matroska_parse_metadata(matroska)) ||
1815 url_feof(matroska->ctx->pb)) {
1816 matroska->metadata_parsed = 1;
1823 /* remove dummy level */
1824 while (matroska->num_levels) {
1825 matroska->num_levels--;
1827 matroska->levels[matroska->num_levels].length;
1828 if (length == (uint64_t)-1)
1833 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1835 matroska->peek_id = peek_id_cache;
1836 matroska->level_up = level_up;
1841 av_log(matroska->ctx, AV_LOG_INFO,
1842 "Ignoring seekhead entry for ID=0x%x\n",
1851 av_log(matroska->ctx, AV_LOG_INFO,
1852 "Unknown seekhead ID 0x%x\n", id);
1856 res = ebml_read_skip(matroska);
1860 if (matroska->level_up) {
1861 matroska->level_up--;
1870 matroska_parse_attachments(AVFormatContext *s)
1872 MatroskaDemuxContext *matroska = s->priv_data;
1876 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
1879 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1882 } else if (matroska->level_up) {
1883 matroska->level_up--;
1888 case MATROSKA_ID_ATTACHEDFILE: {
1891 uint8_t* data = NULL;
1892 int i, data_size = 0;
1895 if ((res = ebml_read_master(matroska, &id)) < 0)
1899 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1902 } else if (matroska->level_up) {
1903 matroska->level_up--;
1908 case MATROSKA_ID_FILENAME:
1909 res = ebml_read_utf8 (matroska, &id, &name);
1912 case MATROSKA_ID_FILEMIMETYPE:
1913 res = ebml_read_ascii (matroska, &id, &mime);
1916 case MATROSKA_ID_FILEDATA:
1917 res = ebml_read_binary(matroska, &id, &data, &data_size);
1921 av_log(matroska->ctx, AV_LOG_INFO,
1922 "Unknown attachedfile ID 0x%x\n", id);
1924 res = ebml_read_skip(matroska);
1928 if (matroska->level_up) {
1929 matroska->level_up--;
1934 if (!(name && mime && data && data_size > 0)) {
1935 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1939 st = av_new_stream(s, matroska->num_streams++);
1941 return AVERROR(ENOMEM);
1942 st->filename = av_strdup(name);
1943 st->codec->codec_id = CODEC_ID_NONE;
1944 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1945 st->codec->extradata = av_malloc(data_size);
1946 if(st->codec->extradata == NULL)
1947 return AVERROR(ENOMEM);
1948 st->codec->extradata_size = data_size;
1949 memcpy(st->codec->extradata, data, data_size);
1951 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1952 if (!strncmp(ff_mkv_mime_tags[i].str, mime,
1953 strlen(ff_mkv_mime_tags[i].str))) {
1954 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1959 av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
1964 av_log(matroska->ctx, AV_LOG_INFO,
1965 "Unknown attachments ID 0x%x\n", id);
1969 res = ebml_read_skip(matroska);
1973 if (matroska->level_up) {
1974 matroska->level_up--;
1982 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
1985 matroska_aac_profile (char *codec_id)
1987 static const char *aac_profiles[] = {
1992 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1993 if (strstr(codec_id, aac_profiles[profile]))
1999 matroska_aac_sri (int samplerate)
2003 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2004 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2010 matroska_read_header (AVFormatContext *s,
2011 AVFormatParameters *ap)
2013 MatroskaDemuxContext *matroska = s->priv_data;
2015 int version, last_level, res = 0;
2020 /* First read the EBML header. */
2022 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2024 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2025 av_log(matroska->ctx, AV_LOG_ERROR,
2026 "Wrong EBML doctype ('%s' != 'matroska').\n",
2027 doctype ? doctype : "(none)");
2030 return AVERROR_NOFMT;
2034 av_log(matroska->ctx, AV_LOG_ERROR,
2035 "Matroska demuxer version 2 too old for file version %d\n",
2037 return AVERROR_NOFMT;
2040 /* The next thing is a segment. */
2042 if (!(id = ebml_peek_id(matroska, &last_level)))
2043 return AVERROR(EIO);
2044 if (id == MATROSKA_ID_SEGMENT)
2048 av_log(matroska->ctx, AV_LOG_INFO,
2049 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2050 MATROSKA_ID_SEGMENT, id);
2051 if ((res = ebml_read_skip(matroska)) < 0)
2055 /* We now have a Matroska segment.
2056 * Seeks are from the beginning of the segment,
2057 * after the segment ID/length. */
2058 if ((res = ebml_read_master(matroska, &id)) < 0)
2060 matroska->segment_start = url_ftell(s->pb);
2062 matroska->time_scale = 1000000;
2063 /* we've found our segment, start reading the different contents in here */
2065 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2068 } else if (matroska->level_up) {
2069 matroska->level_up--;
2075 case MATROSKA_ID_INFO: {
2076 if ((res = ebml_read_master(matroska, &id)) < 0)
2078 res = matroska_parse_info(matroska);
2082 /* track info headers */
2083 case MATROSKA_ID_TRACKS: {
2084 if ((res = ebml_read_master(matroska, &id)) < 0)
2086 res = matroska_parse_tracks(matroska);
2091 case MATROSKA_ID_CUES: {
2092 if (!matroska->index_parsed) {
2093 if ((res = ebml_read_master(matroska, &id)) < 0)
2095 res = matroska_parse_index(matroska);
2097 res = ebml_read_skip(matroska);
2102 case MATROSKA_ID_TAGS: {
2103 if (!matroska->metadata_parsed) {
2104 if ((res = ebml_read_master(matroska, &id)) < 0)
2106 res = matroska_parse_metadata(matroska);
2108 res = ebml_read_skip(matroska);
2112 /* file index (if seekable, seek to Cues/Tags to parse it) */
2113 case MATROSKA_ID_SEEKHEAD: {
2114 if ((res = ebml_read_master(matroska, &id)) < 0)
2116 res = matroska_parse_seekhead(matroska);
2120 case MATROSKA_ID_ATTACHMENTS: {
2121 if ((res = ebml_read_master(matroska, &id)) < 0)
2123 res = matroska_parse_attachments(s);
2127 case MATROSKA_ID_CLUSTER: {
2128 /* Do not read the master - this will be done in the next
2129 * call to matroska_read_packet. */
2135 av_log(matroska->ctx, AV_LOG_INFO,
2136 "Unknown matroska file header ID 0x%x\n", id);
2140 res = ebml_read_skip(matroska);
2144 if (matroska->level_up) {
2145 matroska->level_up--;
2150 /* Have we found a cluster? */
2151 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2153 MatroskaTrack *track;
2156 for (i = 0; i < matroska->num_tracks; i++) {
2157 enum CodecID codec_id = CODEC_ID_NONE;
2158 uint8_t *extradata = NULL;
2159 int extradata_size = 0;
2160 int extradata_offset = 0;
2161 track = matroska->tracks[i];
2162 track->stream_index = -1;
2164 /* Apply some sanity checks. */
2165 if (track->codec_id == NULL)
2168 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2169 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2170 strlen(ff_mkv_codec_tags[j].str))){
2171 codec_id= ff_mkv_codec_tags[j].id;
2176 /* Set the FourCC from the CodecID. */
2177 /* This is the MS compatibility mode which stores a
2178 * BITMAPINFOHEADER in the CodecPrivate. */
2179 if (!strcmp(track->codec_id,
2180 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2181 (track->codec_priv_size >= 40) &&
2182 (track->codec_priv != NULL)) {
2183 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2185 /* Offset of biCompression. Stored in LE. */
2186 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2187 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2191 /* This is the MS compatibility mode which stores a
2192 * WAVEFORMATEX in the CodecPrivate. */
2193 else if (!strcmp(track->codec_id,
2194 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2195 (track->codec_priv_size >= 18) &&
2196 (track->codec_priv != NULL)) {
2199 /* Offset of wFormatTag. Stored in LE. */
2200 tag = AV_RL16(track->codec_priv);
2201 codec_id = codec_get_id(codec_wav_tags, tag);
2205 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2206 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2207 int profile = matroska_aac_profile(track->codec_id);
2208 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2209 extradata = av_malloc(5);
2210 if (extradata == NULL)
2211 return AVERROR(ENOMEM);
2212 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2213 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2214 if (strstr(track->codec_id, "SBR")) {
2215 sri = matroska_aac_sri(audiotrack->samplerate);
2216 extradata[2] = 0x56;
2217 extradata[3] = 0xE5;
2218 extradata[4] = 0x80 | (sri<<3);
2225 else if (codec_id == CODEC_ID_TTA) {
2226 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2228 extradata_size = 30;
2229 extradata = av_mallocz(extradata_size);
2230 if (extradata == NULL)
2231 return AVERROR(ENOMEM);
2232 init_put_byte(&b, extradata, extradata_size, 1,
2233 NULL, NULL, NULL, NULL);
2234 put_buffer(&b, "TTA1", 4);
2236 put_le16(&b, audiotrack->channels);
2237 put_le16(&b, audiotrack->bitdepth);
2238 put_le32(&b, audiotrack->samplerate);
2239 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2242 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2243 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2244 extradata_offset = 26;
2245 track->codec_priv_size -= extradata_offset;
2248 else if (codec_id == CODEC_ID_RA_144) {
2249 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2250 audiotrack->samplerate = 8000;
2251 audiotrack->channels = 1;
2254 else if (codec_id == CODEC_ID_RA_288 ||
2255 codec_id == CODEC_ID_COOK ||
2256 codec_id == CODEC_ID_ATRAC3) {
2257 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2260 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2261 NULL, NULL, NULL, NULL);
2263 audiotrack->coded_framesize = get_be32(&b);
2265 audiotrack->sub_packet_h = get_be16(&b);
2266 audiotrack->frame_size = get_be16(&b);
2267 audiotrack->sub_packet_size = get_be16(&b);
2268 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2269 if (codec_id == CODEC_ID_RA_288) {
2270 audiotrack->block_align = audiotrack->coded_framesize;
2271 track->codec_priv_size = 0;
2273 audiotrack->block_align = audiotrack->sub_packet_size;
2274 extradata_offset = 78;
2275 track->codec_priv_size -= extradata_offset;
2279 if (codec_id == CODEC_ID_NONE) {
2280 av_log(matroska->ctx, AV_LOG_INFO,
2281 "Unknown/unsupported CodecID %s.\n",
2285 track->stream_index = matroska->num_streams;
2287 matroska->num_streams++;
2288 st = av_new_stream(s, track->stream_index);
2290 return AVERROR(ENOMEM);
2291 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2293 st->codec->codec_id = codec_id;
2295 if (strcmp(track->language, "und"))
2296 strcpy(st->language, track->language);
2298 if (track->flags & MATROSKA_TRACK_DEFAULT)
2299 st->disposition |= AV_DISPOSITION_DEFAULT;
2301 if (track->default_duration)
2302 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2303 track->default_duration, 1000000000, 30000);
2306 st->codec->extradata = extradata;
2307 st->codec->extradata_size = extradata_size;
2308 } else if(track->codec_priv && track->codec_priv_size > 0){
2309 st->codec->extradata = av_malloc(track->codec_priv_size);
2310 if(st->codec->extradata == NULL)
2311 return AVERROR(ENOMEM);
2312 st->codec->extradata_size = track->codec_priv_size;
2313 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2314 track->codec_priv_size);
2317 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2318 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2320 st->codec->codec_type = CODEC_TYPE_VIDEO;
2321 st->codec->codec_tag = videotrack->fourcc;
2322 st->codec->width = videotrack->pixel_width;
2323 st->codec->height = videotrack->pixel_height;
2324 if (videotrack->display_width == 0)
2325 videotrack->display_width= videotrack->pixel_width;
2326 if (videotrack->display_height == 0)
2327 videotrack->display_height= videotrack->pixel_height;
2328 av_reduce(&st->codec->sample_aspect_ratio.num,
2329 &st->codec->sample_aspect_ratio.den,
2330 st->codec->height * videotrack->display_width,
2331 st->codec-> width * videotrack->display_height,
2333 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2334 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2335 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2337 st->codec->codec_type = CODEC_TYPE_AUDIO;
2338 st->codec->sample_rate = audiotrack->samplerate;
2339 st->codec->channels = audiotrack->channels;
2340 st->codec->block_align = audiotrack->block_align;
2341 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2342 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2345 /* What do we do with private data? E.g. for Vorbis. */
2350 if (matroska->index_parsed) {
2351 int i, track, stream;
2352 for (i=0; i<matroska->num_indexes; i++) {
2353 MatroskaDemuxIndex *idx = &matroska->index[i];
2354 track = matroska_find_track_by_num(matroska, idx->track);
2355 if (track < 0) continue;
2356 stream = matroska->tracks[track]->stream_index;
2357 if (stream >= 0 && stream < matroska->ctx->nb_streams)
2358 av_add_index_entry(matroska->ctx->streams[stream],
2359 idx->pos, idx->time/matroska->time_scale,
2360 0, 0, AVINDEX_KEYFRAME);
2368 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2369 int64_t pos, uint64_t cluster_time, uint64_t duration,
2370 int is_keyframe, int is_bframe)
2376 uint8_t *origdata = data;
2378 uint32_t *lace_size = NULL;
2379 int n, flags, laces = 0;
2383 /* first byte(s): tracknum */
2384 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2385 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2392 /* fetch track from num */
2393 track = matroska_find_track_by_num(matroska, num);
2394 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2395 av_log(matroska->ctx, AV_LOG_INFO,
2396 "Invalid stream %d or size %u\n", track, size);
2400 stream_index = matroska->tracks[track]->stream_index;
2401 if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2405 st = matroska->ctx->streams[stream_index];
2406 if (st->discard >= AVDISCARD_ALL) {
2410 if (duration == AV_NOPTS_VALUE)
2411 duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2413 /* block_time (relative to cluster time) */
2414 block_time = AV_RB16(data);
2418 if (is_keyframe == -1)
2419 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2421 if (matroska->skip_to_keyframe) {
2422 if (!is_keyframe || st != matroska->skip_to_stream) {
2426 matroska->skip_to_keyframe = 0;
2429 switch ((flags & 0x06) >> 1) {
2430 case 0x0: /* no lacing */
2432 lace_size = av_mallocz(sizeof(int));
2433 lace_size[0] = size;
2436 case 0x1: /* xiph lacing */
2437 case 0x2: /* fixed-size lacing */
2438 case 0x3: /* EBML lacing */
2443 laces = (*data) + 1;
2446 lace_size = av_mallocz(laces * sizeof(int));
2448 switch ((flags & 0x06) >> 1) {
2449 case 0x1: /* xiph lacing */ {
2452 for (n = 0; res == 0 && n < laces - 1; n++) {
2459 lace_size[n] += temp;
2465 total += lace_size[n];
2467 lace_size[n] = size - total;
2471 case 0x2: /* fixed-size lacing */
2472 for (n = 0; n < laces; n++)
2473 lace_size[n] = size / laces;
2476 case 0x3: /* EBML lacing */ {
2478 n = matroska_ebmlnum_uint(data, size, &num);
2480 av_log(matroska->ctx, AV_LOG_INFO,
2481 "EBML block data error\n");
2486 total = lace_size[0] = num;
2487 for (n = 1; res == 0 && n < laces - 1; n++) {
2490 r = matroska_ebmlnum_sint (data, size, &snum);
2492 av_log(matroska->ctx, AV_LOG_INFO,
2493 "EBML block data error\n");
2498 lace_size[n] = lace_size[n - 1] + snum;
2499 total += lace_size[n];
2501 lace_size[n] = size - total;
2509 uint64_t timecode = AV_NOPTS_VALUE;
2511 if (cluster_time != (uint64_t)-1
2512 && (block_time >= 0 || cluster_time >= -block_time))
2513 timecode = cluster_time + block_time;
2515 for (n = 0; n < laces; n++) {
2516 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2517 st->codec->codec_id == CODEC_ID_COOK ||
2518 st->codec->codec_id == CODEC_ID_ATRAC3) {
2519 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2520 int a = st->codec->block_align;
2521 int sps = audiotrack->sub_packet_size;
2522 int cfs = audiotrack->coded_framesize;
2523 int h = audiotrack->sub_packet_h;
2524 int y = audiotrack->sub_packet_cnt;
2525 int w = audiotrack->frame_size;
2528 if (!audiotrack->pkt_cnt) {
2529 if (st->codec->codec_id == CODEC_ID_RA_288)
2530 for (x=0; x<h/2; x++)
2531 memcpy(audiotrack->buf+x*2*w+y*cfs,
2534 for (x=0; x<w/sps; x++)
2535 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2537 if (++audiotrack->sub_packet_cnt >= h) {
2538 audiotrack->sub_packet_cnt = 0;
2539 audiotrack->pkt_cnt = h*w / a;
2542 while (audiotrack->pkt_cnt) {
2543 pkt = av_mallocz(sizeof(AVPacket));
2544 av_new_packet(pkt, a);
2545 memcpy(pkt->data, audiotrack->buf
2546 + a * (h*w / a - audiotrack->pkt_cnt--), a);
2548 pkt->stream_index = stream_index;
2549 matroska_queue_packet(matroska, pkt);
2554 pkt = av_mallocz(sizeof(AVPacket));
2555 /* XXX: prevent data copy... */
2556 if (av_new_packet(pkt, lace_size[n]-offset) < 0) {
2557 res = AVERROR(ENOMEM);
2561 memcpy (pkt->data, data+offset, lace_size[n]-offset);
2564 pkt->flags = is_keyframe;
2565 pkt->stream_index = stream_index;
2567 pkt->pts = timecode;
2569 pkt->duration = duration;
2571 matroska_queue_packet(matroska, pkt);
2574 if (timecode != AV_NOPTS_VALUE)
2575 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2576 data += lace_size[n];
2586 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2587 uint64_t cluster_time)
2592 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2593 uint64_t duration = AV_NOPTS_VALUE;
2598 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2601 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2604 } else if (matroska->level_up) {
2605 matroska->level_up--;
2610 /* one block inside the group. Note, block parsing is one
2611 * of the harder things, so this code is a bit complicated.
2612 * See http://www.matroska.org/ for documentation. */
2613 case MATROSKA_ID_BLOCK: {
2614 pos = url_ftell(matroska->ctx->pb);
2615 res = ebml_read_binary(matroska, &id, &data, &size);
2619 case MATROSKA_ID_BLOCKDURATION: {
2620 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2625 case MATROSKA_ID_BLOCKREFERENCE: {
2627 /* We've found a reference, so not even the first frame in
2628 * the lace is a key frame. */
2630 if (last_num_packets != matroska->num_packets)
2631 matroska->packets[last_num_packets]->flags = 0;
2632 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2640 av_log(matroska->ctx, AV_LOG_INFO,
2641 "Unknown entry 0x%x in blockgroup data\n", id);
2645 res = ebml_read_skip(matroska);
2649 if (matroska->level_up) {
2650 matroska->level_up--;
2659 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2660 duration, is_keyframe, is_bframe);
2666 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2670 uint64_t cluster_time = 0;
2675 av_log(matroska->ctx, AV_LOG_DEBUG,
2676 "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2679 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2682 } else if (matroska->level_up) {
2683 matroska->level_up--;
2688 /* cluster timecode */
2689 case MATROSKA_ID_CLUSTERTIMECODE: {
2691 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2697 /* a group of blocks inside a cluster */
2698 case MATROSKA_ID_BLOCKGROUP:
2699 if ((res = ebml_read_master(matroska, &id)) < 0)
2701 res = matroska_parse_blockgroup(matroska, cluster_time);
2704 case MATROSKA_ID_SIMPLEBLOCK:
2705 pos = url_ftell(matroska->ctx->pb);
2706 res = ebml_read_binary(matroska, &id, &data, &size);
2708 res = matroska_parse_block(matroska, data, size, pos,
2709 cluster_time, AV_NOPTS_VALUE,
2714 av_log(matroska->ctx, AV_LOG_INFO,
2715 "Unknown entry 0x%x in cluster data\n", id);
2719 res = ebml_read_skip(matroska);
2723 if (matroska->level_up) {
2724 matroska->level_up--;
2733 matroska_read_packet (AVFormatContext *s,
2736 MatroskaDemuxContext *matroska = s->priv_data;
2740 /* Read stream until we have a packet queued. */
2741 while (matroska_deliver_packet(matroska, pkt)) {
2743 /* Have we already reached the end? */
2745 return AVERROR(EIO);
2749 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2750 return AVERROR(EIO);
2751 } else if (matroska->level_up) {
2752 matroska->level_up--;
2757 case MATROSKA_ID_CLUSTER:
2758 if ((res = ebml_read_master(matroska, &id)) < 0)
2760 if ((res = matroska_parse_cluster(matroska)) == 0)
2761 res = 1; /* Parsed one cluster, let's get out. */
2766 res = ebml_read_skip(matroska);
2770 if (matroska->level_up) {
2771 matroska->level_up--;
2784 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2787 MatroskaDemuxContext *matroska = s->priv_data;
2788 AVStream *st = s->streams[stream_index];
2791 /* find index entry */
2792 index = av_index_search_timestamp(st, timestamp, flags);
2796 matroska_clear_queue(matroska);
2799 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2800 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2801 matroska->skip_to_stream = st;
2802 matroska->peek_id = 0;
2807 matroska_read_close (AVFormatContext *s)
2809 MatroskaDemuxContext *matroska = s->priv_data;
2812 av_free(matroska->writing_app);
2813 av_free(matroska->muxing_app);
2814 av_free(matroska->index);
2816 matroska_clear_queue(matroska);
2818 for (n = 0; n < matroska->num_tracks; n++) {
2819 MatroskaTrack *track = matroska->tracks[n];
2820 av_free(track->codec_id);
2821 av_free(track->codec_name);
2822 av_free(track->codec_priv);
2823 av_free(track->name);
2825 if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2826 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2827 av_free(audiotrack->buf);
2836 AVInputFormat matroska_demuxer = {
2838 "Matroska file format",
2839 sizeof(MatroskaDemuxContext),
2841 matroska_read_header,
2842 matroska_read_packet,
2843 matroska_read_close,