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"
37 typedef struct Track {
38 MatroskaTrackType type;
40 /* Unique track number and track ID. stream_index is the index that
41 * the calling app uses for this track. */
44 uint32_t stream_index;
52 unsigned char *codec_priv;
55 uint64_t default_duration;
56 MatroskaTrackFlags flags;
59 typedef struct MatroskaVideoTrack {
69 MatroskaAspectRatioMode ar_mode;
70 MatroskaEyeMode eye_mode;
75 typedef struct MatroskaAudioTrack {
80 int internal_samplerate;
84 /* real audio header */
95 typedef struct MatroskaSubtitleTrack {
99 } MatroskaSubtitleTrack;
101 #define MAX_TRACK_SIZE (FFMAX(FFMAX(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_IO; /* 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 assert(level_up != NULL);
314 if (ebml_read_element_id(matroska, &id, level_up) < 0)
321 * Seek to a given offset.
322 * 0 is success, -1 is failure.
326 ebml_read_seek (MatroskaDemuxContext *matroska,
329 ByteIOContext *pb = &matroska->ctx->pb;
331 /* clear ID cache, if any */
332 matroska->peek_id = 0;
334 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
338 * Skip the next element.
339 * 0 is success, -1 is failure.
343 ebml_read_skip (MatroskaDemuxContext *matroska)
345 ByteIOContext *pb = &matroska->ctx->pb;
350 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
351 (res = ebml_read_element_length(matroska, &length)) < 0)
354 url_fskip(pb, length);
360 * Read the next element as an unsigned int.
361 * 0 is success, < 0 is failure.
365 ebml_read_uint (MatroskaDemuxContext *matroska,
369 ByteIOContext *pb = &matroska->ctx->pb;
370 int n = 0, size, res;
373 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
374 (res = ebml_read_element_length(matroska, &rlength)) < 0)
377 if (size < 1 || size > 8) {
378 offset_t pos = url_ftell(pb);
379 av_log(matroska->ctx, AV_LOG_ERROR,
380 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
382 return AVERROR_INVALIDDATA;
385 /* big-endian ordening; build up number */
388 *num = (*num << 8) | get_byte(pb);
394 * Read the next element as a signed int.
395 * 0 is success, < 0 is failure.
399 ebml_read_sint (MatroskaDemuxContext *matroska,
403 ByteIOContext *pb = &matroska->ctx->pb;
404 int size, n = 1, negative = 0, res;
407 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
408 (res = ebml_read_element_length(matroska, &rlength)) < 0)
411 if (size < 1 || size > 8) {
412 offset_t pos = url_ftell(pb);
413 av_log(matroska->ctx, AV_LOG_ERROR,
414 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
416 return AVERROR_INVALIDDATA;
418 if ((*num = get_byte(pb)) & 0x80) {
423 *num = (*num << 8) | get_byte(pb);
427 *num = *num - (1LL << ((8 * size) - 1));
433 * Read the next element as a float.
434 * 0 is success, < 0 is failure.
438 ebml_read_float (MatroskaDemuxContext *matroska,
442 ByteIOContext *pb = &matroska->ctx->pb;
446 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
447 (res = ebml_read_element_length(matroska, &rlength)) < 0)
452 *num= av_int2flt(get_be32(pb));
454 *num= av_int2dbl(get_be64(pb));
456 offset_t pos = url_ftell(pb);
457 av_log(matroska->ctx, AV_LOG_ERROR,
458 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
460 return AVERROR_INVALIDDATA;
467 * Read the next element as an ASCII string.
468 * 0 is success, < 0 is failure.
472 ebml_read_ascii (MatroskaDemuxContext *matroska,
476 ByteIOContext *pb = &matroska->ctx->pb;
480 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
481 (res = ebml_read_element_length(matroska, &rlength)) < 0)
485 /* ebml strings are usually not 0-terminated, so we allocate one
486 * byte more, read the string and NULL-terminate it ourselves. */
487 if (size < 0 || !(*str = av_malloc(size + 1))) {
488 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
489 return AVERROR_NOMEM;
491 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
492 offset_t pos = url_ftell(pb);
493 av_log(matroska->ctx, AV_LOG_ERROR,
494 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
503 * Read the next element as a UTF-8 string.
504 * 0 is success, < 0 is failure.
508 ebml_read_utf8 (MatroskaDemuxContext *matroska,
512 return ebml_read_ascii(matroska, id, str);
516 * Read the next element as a date (nanoseconds since 1/1/2000).
517 * 0 is success, < 0 is failure.
521 ebml_read_date (MatroskaDemuxContext *matroska,
525 return ebml_read_sint(matroska, id, date);
529 * Read the next element, but only the header. The contents
530 * are supposed to be sub-elements which can be read separately.
531 * 0 is success, < 0 is failure.
535 ebml_read_master (MatroskaDemuxContext *matroska,
538 ByteIOContext *pb = &matroska->ctx->pb;
540 MatroskaLevel *level;
543 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
544 (res = ebml_read_element_length(matroska, &length)) < 0)
547 /* protect... (Heaven forbids that the '>' is true) */
548 if (matroska->num_levels >= EBML_MAX_DEPTH) {
549 av_log(matroska->ctx, AV_LOG_ERROR,
550 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
551 return AVERROR_NOTSUPP;
555 level = &matroska->levels[matroska->num_levels++];
556 level->start = url_ftell(pb);
557 level->length = length;
563 * Read the next element as binary data.
564 * 0 is success, < 0 is failure.
568 ebml_read_binary (MatroskaDemuxContext *matroska,
573 ByteIOContext *pb = &matroska->ctx->pb;
577 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
578 (res = ebml_read_element_length(matroska, &rlength)) < 0)
582 if (!(*binary = av_malloc(*size))) {
583 av_log(matroska->ctx, AV_LOG_ERROR,
584 "Memory allocation error\n");
585 return AVERROR_NOMEM;
588 if (get_buffer(pb, *binary, *size) != *size) {
589 offset_t pos = url_ftell(pb);
590 av_log(matroska->ctx, AV_LOG_ERROR,
591 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
599 * Read signed/unsigned "EBML" numbers.
600 * Return: number of bytes processed, < 0 on error.
601 * XXX: use ebml_read_num().
605 matroska_ebmlnum_uint (uint8_t *data,
609 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
613 return AVERROR_INVALIDDATA;
616 while (read <= 8 && !(total & len_mask)) {
621 return AVERROR_INVALIDDATA;
623 if ((total &= (len_mask - 1)) == len_mask - 1)
626 return AVERROR_INVALIDDATA;
630 total = (total << 8) | data[n];
643 * Same as above, but signed.
647 matroska_ebmlnum_sint (uint8_t *data,
654 /* read as unsigned number first */
655 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
658 /* make signed (weird way) */
659 if (unum == (uint64_t)-1)
662 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
668 * Read an EBML header.
669 * 0 is success, < 0 is failure.
673 ebml_read_header (MatroskaDemuxContext *matroska,
678 int level_up, res = 0;
686 if (!(id = ebml_peek_id(matroska, &level_up)) ||
687 level_up != 0 || id != EBML_ID_HEADER) {
688 av_log(matroska->ctx, AV_LOG_ERROR,
689 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
690 return AVERROR_INVALIDDATA;
692 if ((res = ebml_read_master(matroska, &id)) < 0)
696 if (!(id = ebml_peek_id(matroska, &level_up)))
704 /* is our read version uptodate? */
705 case EBML_ID_EBMLREADVERSION: {
708 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
710 if (num > EBML_VERSION) {
711 av_log(matroska->ctx, AV_LOG_ERROR,
712 "EBML version %"PRIu64" (> %d) is not supported\n",
714 return AVERROR_INVALIDDATA;
719 /* we only handle 8 byte lengths at max */
720 case EBML_ID_EBMLMAXSIZELENGTH: {
723 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
725 if (num > sizeof(uint64_t)) {
726 av_log(matroska->ctx, AV_LOG_ERROR,
727 "Integers of size %"PRIu64" (> %zd) not supported\n",
728 num, sizeof(uint64_t));
729 return AVERROR_INVALIDDATA;
734 /* we handle 4 byte IDs at max */
735 case EBML_ID_EBMLMAXIDLENGTH: {
738 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
740 if (num > sizeof(uint32_t)) {
741 av_log(matroska->ctx, AV_LOG_ERROR,
742 "IDs of size %"PRIu64" (> %zu) not supported\n",
743 num, sizeof(uint32_t));
744 return AVERROR_INVALIDDATA;
749 case EBML_ID_DOCTYPE: {
752 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
763 case EBML_ID_DOCTYPEREADVERSION: {
766 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
774 av_log(matroska->ctx, AV_LOG_INFO,
775 "Unknown data type 0x%x in EBML header", id);
779 /* we ignore these two, as they don't tell us anything we
781 case EBML_ID_EBMLVERSION:
782 case EBML_ID_DOCTYPEVERSION:
783 res = ebml_read_skip (matroska);
793 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
798 for (i = 0; i < matroska->num_tracks; i++)
799 if (matroska->tracks[i]->num == num)
807 * Put one packet in an application-supplied AVPacket struct.
808 * Returns 0 on success or -1 on failure.
812 matroska_deliver_packet (MatroskaDemuxContext *matroska,
815 if (matroska->num_packets > 0) {
816 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
817 av_free(matroska->packets[0]);
818 if (matroska->num_packets > 1) {
819 memmove(&matroska->packets[0], &matroska->packets[1],
820 (matroska->num_packets - 1) * sizeof(AVPacket *));
822 av_realloc(matroska->packets, (matroska->num_packets - 1) *
825 av_freep(&matroska->packets);
827 matroska->num_packets--;
835 * Put a packet into our internal queue. Will be delivered to the
836 * user/application during the next get_packet() call.
840 matroska_queue_packet (MatroskaDemuxContext *matroska,
844 av_realloc(matroska->packets, (matroska->num_packets + 1) *
846 matroska->packets[matroska->num_packets] = pkt;
847 matroska->num_packets++;
856 matroska_probe (AVProbeData *p)
859 int len_mask = 0x80, size = 1, n = 1;
860 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
863 if ((p->buf[0] << 24 | p->buf[1] << 16 |
864 p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)
867 /* length of header */
869 while (size <= 8 && !(total & len_mask)) {
875 total &= (len_mask - 1);
877 total = (total << 8) | p->buf[4 + n++];
879 /* does the probe data contain the whole header? */
880 if (p->buf_size < 4 + size + total)
883 /* the header must contain the document type 'matroska'. For now,
884 * we don't parse the whole header but simply check for the
885 * availability of that array of characters inside the header.
886 * Not fully fool-proof, but good enough. */
887 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
888 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
889 return AVPROBE_SCORE_MAX;
895 * From here on, it's all XML-style DTD stuff... Needs no comments.
899 matroska_parse_info (MatroskaDemuxContext *matroska)
904 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
907 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
910 } else if (matroska->level_up) {
911 matroska->level_up--;
916 /* cluster timecode */
917 case MATROSKA_ID_TIMECODESCALE: {
919 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
921 matroska->time_scale = num;
925 case MATROSKA_ID_DURATION: {
927 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
929 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
933 case MATROSKA_ID_TITLE: {
935 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
937 strncpy(matroska->ctx->title, text,
938 sizeof(matroska->ctx->title)-1);
943 case MATROSKA_ID_WRITINGAPP: {
945 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
947 matroska->writing_app = text;
951 case MATROSKA_ID_MUXINGAPP: {
953 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
955 matroska->muxing_app = text;
959 case MATROSKA_ID_DATEUTC: {
961 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
963 matroska->created = time;
968 av_log(matroska->ctx, AV_LOG_INFO,
969 "Unknown entry 0x%x in info header\n", id);
973 res = ebml_read_skip(matroska);
977 if (matroska->level_up) {
978 matroska->level_up--;
987 matroska_add_stream (MatroskaDemuxContext *matroska)
991 MatroskaTrack *track;
993 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
995 /* Allocate a generic track. As soon as we know its type we'll realloc. */
996 track = av_mallocz(MAX_TRACK_SIZE);
997 matroska->num_tracks++;
999 /* start with the master */
1000 if ((res = ebml_read_master(matroska, &id)) < 0)
1003 /* try reading the trackentry headers */
1005 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1008 } else if (matroska->level_up > 0) {
1009 matroska->level_up--;
1014 /* track number (unique stream ID) */
1015 case MATROSKA_ID_TRACKNUMBER: {
1017 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1023 /* track UID (unique identifier) */
1024 case MATROSKA_ID_TRACKUID: {
1026 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1032 /* track type (video, audio, combined, subtitle, etc.) */
1033 case MATROSKA_ID_TRACKTYPE: {
1035 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1037 if (track->type && track->type != num) {
1038 av_log(matroska->ctx, AV_LOG_INFO,
1039 "More than one tracktype in an entry - skip\n");
1044 switch (track->type) {
1045 case MATROSKA_TRACK_TYPE_VIDEO:
1046 case MATROSKA_TRACK_TYPE_AUDIO:
1047 case MATROSKA_TRACK_TYPE_SUBTITLE:
1049 case MATROSKA_TRACK_TYPE_COMPLEX:
1050 case MATROSKA_TRACK_TYPE_LOGO:
1051 case MATROSKA_TRACK_TYPE_CONTROL:
1053 av_log(matroska->ctx, AV_LOG_INFO,
1054 "Unknown or unsupported track type 0x%x\n",
1059 matroska->tracks[matroska->num_tracks - 1] = track;
1063 /* tracktype specific stuff for video */
1064 case MATROSKA_ID_TRACKVIDEO: {
1065 MatroskaVideoTrack *videotrack;
1067 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1068 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1069 av_log(matroska->ctx, AV_LOG_INFO,
1070 "video data in non-video track - ignoring\n");
1071 res = AVERROR_INVALIDDATA;
1073 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1075 videotrack = (MatroskaVideoTrack *)track;
1078 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1081 } else if (matroska->level_up > 0) {
1082 matroska->level_up--;
1087 /* fixme, this should be one-up, but I get it here */
1088 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1090 if ((res = ebml_read_uint (matroska, &id,
1093 track->default_duration = num/matroska->time_scale;
1097 /* video framerate */
1098 case MATROSKA_ID_VIDEOFRAMERATE: {
1100 if ((res = ebml_read_float(matroska, &id,
1103 track->default_duration = 1000000000/(matroska->time_scale*num);
1107 /* width of the size to display the video at */
1108 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1110 if ((res = ebml_read_uint(matroska, &id,
1113 videotrack->display_width = num;
1117 /* height of the size to display the video at */
1118 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1120 if ((res = ebml_read_uint(matroska, &id,
1123 videotrack->display_height = num;
1127 /* width of the video in the file */
1128 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1130 if ((res = ebml_read_uint(matroska, &id,
1133 videotrack->pixel_width = num;
1137 /* height of the video in the file */
1138 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1140 if ((res = ebml_read_uint(matroska, &id,
1143 videotrack->pixel_height = num;
1147 /* whether the video is interlaced */
1148 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1150 if ((res = ebml_read_uint(matroska, &id,
1155 MATROSKA_VIDEOTRACK_INTERLACED;
1158 ~MATROSKA_VIDEOTRACK_INTERLACED;
1162 /* stereo mode (whether the video has two streams,
1163 * where one is for the left eye and the other for
1164 * the right eye, which creates a 3D-like
1166 case MATROSKA_ID_VIDEOSTEREOMODE: {
1168 if ((res = ebml_read_uint(matroska, &id,
1171 if (num != MATROSKA_EYE_MODE_MONO &&
1172 num != MATROSKA_EYE_MODE_LEFT &&
1173 num != MATROSKA_EYE_MODE_RIGHT &&
1174 num != MATROSKA_EYE_MODE_BOTH) {
1175 av_log(matroska->ctx, AV_LOG_INFO,
1176 "Ignoring unknown eye mode 0x%x\n",
1180 videotrack->eye_mode = num;
1184 /* aspect ratio behaviour */
1185 case MATROSKA_ID_VIDEOASPECTRATIO: {
1187 if ((res = ebml_read_uint(matroska, &id,
1190 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1191 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1192 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1193 av_log(matroska->ctx, AV_LOG_INFO,
1194 "Ignoring unknown aspect ratio 0x%x\n",
1198 videotrack->ar_mode = num;
1202 /* colourspace (only matters for raw video)
1204 case MATROSKA_ID_VIDEOCOLOURSPACE: {
1206 if ((res = ebml_read_uint(matroska, &id,
1209 videotrack->fourcc = num;
1214 av_log(matroska->ctx, AV_LOG_INFO,
1215 "Unknown video track header entry "
1216 "0x%x - ignoring\n", id);
1220 res = ebml_read_skip(matroska);
1224 if (matroska->level_up) {
1225 matroska->level_up--;
1232 /* tracktype specific stuff for audio */
1233 case MATROSKA_ID_TRACKAUDIO: {
1234 MatroskaAudioTrack *audiotrack;
1236 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1237 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1238 av_log(matroska->ctx, AV_LOG_INFO,
1239 "audio data in non-audio track - ignoring\n");
1240 res = AVERROR_INVALIDDATA;
1242 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1244 audiotrack = (MatroskaAudioTrack *)track;
1245 audiotrack->channels = 1;
1246 audiotrack->samplerate = 8000;
1249 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1252 } else if (matroska->level_up > 0) {
1253 matroska->level_up--;
1259 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1261 if ((res = ebml_read_float(matroska, &id,
1264 audiotrack->internal_samplerate =
1265 audiotrack->samplerate = num;
1269 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1271 if ((res = ebml_read_float(matroska, &id,
1274 audiotrack->samplerate = num;
1279 case MATROSKA_ID_AUDIOBITDEPTH: {
1281 if ((res = ebml_read_uint(matroska, &id,
1284 audiotrack->bitdepth = num;
1289 case MATROSKA_ID_AUDIOCHANNELS: {
1291 if ((res = ebml_read_uint(matroska, &id,
1294 audiotrack->channels = num;
1299 av_log(matroska->ctx, AV_LOG_INFO,
1300 "Unknown audio track header entry "
1301 "0x%x - ignoring\n", id);
1305 res = ebml_read_skip(matroska);
1309 if (matroska->level_up) {
1310 matroska->level_up--;
1317 /* codec identifier */
1318 case MATROSKA_ID_CODECID: {
1320 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1322 track->codec_id = text;
1326 /* codec private data */
1327 case MATROSKA_ID_CODECPRIVATE: {
1330 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1332 track->codec_priv = data;
1333 track->codec_priv_size = size;
1337 /* name of the codec */
1338 case MATROSKA_ID_CODECNAME: {
1340 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1342 track->codec_name = text;
1346 /* name of this track */
1347 case MATROSKA_ID_TRACKNAME: {
1349 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1355 /* language (matters for audio/subtitles, mostly) */
1356 case MATROSKA_ID_TRACKLANGUAGE: {
1358 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1360 track->language = text;
1364 /* whether this is actually used */
1365 case MATROSKA_ID_TRACKFLAGENABLED: {
1367 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1370 track->flags |= MATROSKA_TRACK_ENABLED;
1372 track->flags &= ~MATROSKA_TRACK_ENABLED;
1376 /* whether it's the default for this track type */
1377 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1379 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1382 track->flags |= MATROSKA_TRACK_DEFAULT;
1384 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1388 /* lacing (like MPEG, where blocks don't end/start on frame
1390 case MATROSKA_ID_TRACKFLAGLACING: {
1392 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1395 track->flags |= MATROSKA_TRACK_LACING;
1397 track->flags &= ~MATROSKA_TRACK_LACING;
1401 /* default length (in time) of one data block in this track */
1402 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1404 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1406 track->default_duration = num / matroska->time_scale;
1411 av_log(matroska->ctx, AV_LOG_INFO,
1412 "Unknown track header entry 0x%x - ignoring\n", id);
1416 /* we ignore these because they're nothing useful. */
1417 case MATROSKA_ID_CODECINFOURL:
1418 case MATROSKA_ID_CODECDOWNLOADURL:
1419 case MATROSKA_ID_TRACKMINCACHE:
1420 case MATROSKA_ID_TRACKMAXCACHE:
1421 res = ebml_read_skip(matroska);
1425 if (matroska->level_up) {
1426 matroska->level_up--;
1435 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1440 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1443 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1446 } else if (matroska->level_up) {
1447 matroska->level_up--;
1452 /* one track within the "all-tracks" header */
1453 case MATROSKA_ID_TRACKENTRY:
1454 res = matroska_add_stream(matroska);
1458 av_log(matroska->ctx, AV_LOG_INFO,
1459 "Unknown entry 0x%x in track header\n", id);
1463 res = ebml_read_skip(matroska);
1467 if (matroska->level_up) {
1468 matroska->level_up--;
1477 matroska_parse_index (MatroskaDemuxContext *matroska)
1481 MatroskaDemuxIndex idx;
1483 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1486 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1489 } else if (matroska->level_up) {
1490 matroska->level_up--;
1495 /* one single index entry ('point') */
1496 case MATROSKA_ID_POINTENTRY:
1497 if ((res = ebml_read_master(matroska, &id)) < 0)
1500 /* in the end, we hope to fill one entry with a
1501 * timestamp, a file position and a tracknum */
1502 idx.pos = (uint64_t) -1;
1503 idx.time = (uint64_t) -1;
1504 idx.track = (uint16_t) -1;
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_CUETIME: {
1519 if ((res = ebml_read_uint(matroska, &id,
1522 idx.time = time * matroska->time_scale;
1526 /* position in the file + track to which it
1528 case MATROSKA_ID_CUETRACKPOSITION:
1529 if ((res = ebml_read_master(matroska, &id)) < 0)
1533 if (!(id = ebml_peek_id (matroska,
1534 &matroska->level_up))) {
1537 } else if (matroska->level_up) {
1538 matroska->level_up--;
1544 case MATROSKA_ID_CUETRACK: {
1546 if ((res = ebml_read_uint(matroska,
1553 /* position in file */
1554 case MATROSKA_ID_CUECLUSTERPOSITION: {
1556 if ((res = ebml_read_uint(matroska,
1559 idx.pos = num+matroska->segment_start;
1564 av_log(matroska->ctx, AV_LOG_INFO,
1565 "Unknown entry 0x%x in "
1566 "CuesTrackPositions\n", id);
1570 res = ebml_read_skip(matroska);
1574 if (matroska->level_up) {
1575 matroska->level_up--;
1583 av_log(matroska->ctx, AV_LOG_INFO,
1584 "Unknown entry 0x%x in cuespoint "
1589 res = ebml_read_skip(matroska);
1593 if (matroska->level_up) {
1594 matroska->level_up--;
1599 /* so let's see if we got what we wanted */
1600 if (idx.pos != (uint64_t) -1 &&
1601 idx.time != (uint64_t) -1 &&
1602 idx.track != (uint16_t) -1) {
1603 if (matroska->num_indexes % 32 == 0) {
1604 /* re-allocate bigger index */
1606 av_realloc(matroska->index,
1607 (matroska->num_indexes + 32) *
1608 sizeof(MatroskaDemuxIndex));
1610 matroska->index[matroska->num_indexes] = idx;
1611 matroska->num_indexes++;
1616 av_log(matroska->ctx, AV_LOG_INFO,
1617 "Unknown entry 0x%x in cues header\n", id);
1621 res = ebml_read_skip(matroska);
1625 if (matroska->level_up) {
1626 matroska->level_up--;
1635 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1641 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1644 } else if (matroska->level_up) {
1645 matroska->level_up--;
1650 /* Hm, this is unsupported... */
1652 av_log(matroska->ctx, AV_LOG_INFO,
1653 "Unknown entry 0x%x in metadata header\n", id);
1657 res = ebml_read_skip(matroska);
1661 if (matroska->level_up) {
1662 matroska->level_up--;
1671 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1676 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1679 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1682 } else if (matroska->level_up) {
1683 matroska->level_up--;
1688 case MATROSKA_ID_SEEKENTRY: {
1689 uint32_t seek_id = 0, peek_id_cache = 0;
1690 uint64_t seek_pos = (uint64_t) -1, t;
1692 if ((res = ebml_read_master(matroska, &id)) < 0)
1696 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1699 } else if (matroska->level_up) {
1700 matroska->level_up--;
1705 case MATROSKA_ID_SEEKID:
1706 res = ebml_read_uint(matroska, &id, &t);
1710 case MATROSKA_ID_SEEKPOSITION:
1711 res = ebml_read_uint(matroska, &id, &seek_pos);
1715 av_log(matroska->ctx, AV_LOG_INFO,
1716 "Unknown seekhead ID 0x%x\n", id);
1720 res = ebml_read_skip(matroska);
1724 if (matroska->level_up) {
1725 matroska->level_up--;
1730 if (!seek_id || seek_pos == (uint64_t) -1) {
1731 av_log(matroska->ctx, AV_LOG_INFO,
1732 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1738 case MATROSKA_ID_CUES:
1739 case MATROSKA_ID_TAGS: {
1740 uint32_t level_up = matroska->level_up;
1741 offset_t before_pos;
1743 MatroskaLevel level;
1745 /* remember the peeked ID and the current position */
1746 peek_id_cache = matroska->peek_id;
1747 before_pos = url_ftell(&matroska->ctx->pb);
1750 if ((res = ebml_read_seek(matroska, seek_pos +
1751 matroska->segment_start)) < 0)
1754 /* we don't want to lose our seekhead level, so we add
1755 * a dummy. This is a crude hack. */
1756 if (matroska->num_levels == EBML_MAX_DEPTH) {
1757 av_log(matroska->ctx, AV_LOG_INFO,
1758 "Max EBML element depth (%d) reached, "
1759 "cannot parse further.\n", EBML_MAX_DEPTH);
1760 return AVERROR_UNKNOWN;
1764 level.length = (uint64_t)-1;
1765 matroska->levels[matroska->num_levels] = level;
1766 matroska->num_levels++;
1769 if (!(id = ebml_peek_id (matroska,
1770 &matroska->level_up)))
1772 if (id != seek_id) {
1773 av_log(matroska->ctx, AV_LOG_INFO,
1774 "We looked for ID=0x%x but got "
1775 "ID=0x%x (pos=%"PRIu64")",
1776 seek_id, id, seek_pos +
1777 matroska->segment_start);
1781 /* read master + parse */
1782 if ((res = ebml_read_master(matroska, &id)) < 0)
1785 case MATROSKA_ID_CUES:
1786 if (!(res = matroska_parse_index(matroska)) ||
1787 url_feof(&matroska->ctx->pb)) {
1788 matroska->index_parsed = 1;
1792 case MATROSKA_ID_TAGS:
1793 if (!(res = matroska_parse_metadata(matroska)) ||
1794 url_feof(&matroska->ctx->pb)) {
1795 matroska->metadata_parsed = 1;
1802 /* remove dummy level */
1803 while (matroska->num_levels) {
1804 matroska->num_levels--;
1806 matroska->levels[matroska->num_levels].length;
1807 if (length == (uint64_t)-1)
1812 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1814 matroska->peek_id = peek_id_cache;
1815 matroska->level_up = level_up;
1820 av_log(matroska->ctx, AV_LOG_INFO,
1821 "Ignoring seekhead entry for ID=0x%x\n",
1830 av_log(matroska->ctx, AV_LOG_INFO,
1831 "Unknown seekhead ID 0x%x\n", id);
1835 res = ebml_read_skip(matroska);
1839 if (matroska->level_up) {
1840 matroska->level_up--;
1848 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
1851 matroska_aac_profile (char *codec_id)
1853 static const char *aac_profiles[] = {
1858 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1859 if (strstr(codec_id, aac_profiles[profile]))
1865 matroska_aac_sri (int samplerate)
1867 static const int aac_sample_rates[] = {
1868 96000, 88200, 64000, 48000, 44100, 32000,
1869 24000, 22050, 16000, 12000, 11025, 8000,
1873 for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
1874 if (aac_sample_rates[sri] == samplerate)
1880 matroska_read_header (AVFormatContext *s,
1881 AVFormatParameters *ap)
1883 MatroskaDemuxContext *matroska = s->priv_data;
1885 int version, last_level, res = 0;
1890 /* First read the EBML header. */
1892 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
1894 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
1895 av_log(matroska->ctx, AV_LOG_ERROR,
1896 "Wrong EBML doctype ('%s' != 'matroska').\n",
1897 doctype ? doctype : "(none)");
1900 return AVERROR_NOFMT;
1904 av_log(matroska->ctx, AV_LOG_ERROR,
1905 "Matroska demuxer version 2 too old for file version %d\n",
1907 return AVERROR_NOFMT;
1910 /* The next thing is a segment. */
1912 if (!(id = ebml_peek_id(matroska, &last_level)))
1914 if (id == MATROSKA_ID_SEGMENT)
1918 av_log(matroska->ctx, AV_LOG_INFO,
1919 "Expected a Segment ID (0x%x), but received 0x%x!\n",
1920 MATROSKA_ID_SEGMENT, id);
1921 if ((res = ebml_read_skip(matroska)) < 0)
1925 /* We now have a Matroska segment.
1926 * Seeks are from the beginning of the segment,
1927 * after the segment ID/length. */
1928 if ((res = ebml_read_master(matroska, &id)) < 0)
1930 matroska->segment_start = url_ftell(&s->pb);
1932 matroska->time_scale = 1000000;
1933 /* we've found our segment, start reading the different contents in here */
1935 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1938 } else if (matroska->level_up) {
1939 matroska->level_up--;
1945 case MATROSKA_ID_INFO: {
1946 if ((res = ebml_read_master(matroska, &id)) < 0)
1948 res = matroska_parse_info(matroska);
1952 /* track info headers */
1953 case MATROSKA_ID_TRACKS: {
1954 if ((res = ebml_read_master(matroska, &id)) < 0)
1956 res = matroska_parse_tracks(matroska);
1961 case MATROSKA_ID_CUES: {
1962 if (!matroska->index_parsed) {
1963 if ((res = ebml_read_master(matroska, &id)) < 0)
1965 res = matroska_parse_index(matroska);
1967 res = ebml_read_skip(matroska);
1972 case MATROSKA_ID_TAGS: {
1973 if (!matroska->metadata_parsed) {
1974 if ((res = ebml_read_master(matroska, &id)) < 0)
1976 res = matroska_parse_metadata(matroska);
1978 res = ebml_read_skip(matroska);
1982 /* file index (if seekable, seek to Cues/Tags to parse it) */
1983 case MATROSKA_ID_SEEKHEAD: {
1984 if ((res = ebml_read_master(matroska, &id)) < 0)
1986 res = matroska_parse_seekhead(matroska);
1990 case MATROSKA_ID_CLUSTER: {
1991 /* Do not read the master - this will be done in the next
1992 * call to matroska_read_packet. */
1998 av_log(matroska->ctx, AV_LOG_INFO,
1999 "Unknown matroska file header ID 0x%x\n", id);
2003 res = ebml_read_skip(matroska);
2007 if (matroska->level_up) {
2008 matroska->level_up--;
2013 /* Have we found a cluster? */
2014 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2016 MatroskaTrack *track;
2019 for (i = 0; i < matroska->num_tracks; i++) {
2020 enum CodecID codec_id = CODEC_ID_NONE;
2021 uint8_t *extradata = NULL;
2022 int extradata_size = 0;
2023 int extradata_offset = 0;
2024 track = matroska->tracks[i];
2026 /* libavformat does not really support subtitles.
2027 * Also apply some sanity checks. */
2028 if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
2029 (track->codec_id == NULL))
2032 for(j=0; ff_mkv_codec_tags[j].str; j++){
2033 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2034 strlen(ff_mkv_codec_tags[j].str))){
2035 codec_id= ff_mkv_codec_tags[j].id;
2040 /* Set the FourCC from the CodecID. */
2041 /* This is the MS compatibility mode which stores a
2042 * BITMAPINFOHEADER in the CodecPrivate. */
2043 if (!strcmp(track->codec_id,
2044 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2045 (track->codec_priv_size >= 40) &&
2046 (track->codec_priv != NULL)) {
2049 /* Offset of biCompression. Stored in LE. */
2050 p = (unsigned char *)track->codec_priv + 16;
2051 ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
2052 (p[2] << 16) | (p[1] << 8) | p[0];
2053 codec_id = codec_get_id(codec_bmp_tags, ((MatroskaVideoTrack *)track)->fourcc);
2057 /* This is the MS compatibility mode which stores a
2058 * WAVEFORMATEX in the CodecPrivate. */
2059 else if (!strcmp(track->codec_id,
2060 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2061 (track->codec_priv_size >= 18) &&
2062 (track->codec_priv != NULL)) {
2066 /* Offset of wFormatTag. Stored in LE. */
2067 p = (unsigned char *)track->codec_priv;
2068 tag = (p[1] << 8) | p[0];
2069 codec_id = codec_get_id(codec_wav_tags, tag);
2073 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2074 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2075 int profile = matroska_aac_profile(track->codec_id);
2076 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2077 extradata = av_malloc(5);
2078 if (extradata == NULL)
2079 return AVERROR_NOMEM;
2080 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2081 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2082 if (strstr(track->codec_id, "SBR")) {
2083 sri = matroska_aac_sri(audiotrack->samplerate);
2084 extradata[2] = 0x56;
2085 extradata[3] = 0xE5;
2086 extradata[4] = 0x80 | (sri<<3);
2091 track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
2094 else if (codec_id == CODEC_ID_TTA) {
2095 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2097 extradata_size = 30;
2098 extradata = av_mallocz(extradata_size);
2099 if (extradata == NULL)
2100 return AVERROR_NOMEM;
2101 init_put_byte(&b, extradata, extradata_size, 1,
2102 NULL, NULL, NULL, NULL);
2103 put_buffer(&b, (uint8_t *) "TTA1", 4);
2105 put_le16(&b, audiotrack->channels);
2106 put_le16(&b, audiotrack->bitdepth);
2107 put_le32(&b, audiotrack->samplerate);
2108 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2111 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2112 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2113 extradata_offset = 26;
2114 track->codec_priv_size -= extradata_offset;
2115 track->flags |= MATROSKA_TRACK_REAL_V;
2118 else if (codec_id == CODEC_ID_RA_144) {
2119 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2120 audiotrack->samplerate = 8000;
2121 audiotrack->channels = 1;
2124 else if (codec_id == CODEC_ID_RA_288 ||
2125 codec_id == CODEC_ID_COOK ||
2126 codec_id == CODEC_ID_ATRAC3) {
2127 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2130 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2131 NULL, NULL, NULL, NULL);
2133 audiotrack->coded_framesize = get_be32(&b);
2135 audiotrack->sub_packet_h = get_be16(&b);
2136 audiotrack->frame_size = get_be16(&b);
2137 audiotrack->sub_packet_size = get_be16(&b);
2138 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2139 if (codec_id == CODEC_ID_RA_288) {
2140 audiotrack->block_align = audiotrack->coded_framesize;
2141 track->codec_priv_size = 0;
2143 audiotrack->block_align = audiotrack->sub_packet_size;
2144 extradata_offset = 78;
2145 track->codec_priv_size -= extradata_offset;
2149 if (codec_id == CODEC_ID_NONE) {
2150 av_log(matroska->ctx, AV_LOG_INFO,
2151 "Unknown/unsupported CodecID %s.\n",
2155 track->stream_index = matroska->num_streams;
2157 matroska->num_streams++;
2158 st = av_new_stream(s, track->stream_index);
2160 return AVERROR_NOMEM;
2161 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2163 st->codec->codec_id = codec_id;
2166 if (track->default_duration)
2167 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2168 track->default_duration, 1000, 30000);
2171 st->codec->extradata = extradata;
2172 st->codec->extradata_size = extradata_size;
2173 } else if(track->codec_priv && track->codec_priv_size > 0){
2174 st->codec->extradata = av_malloc(track->codec_priv_size);
2175 if(st->codec->extradata == NULL)
2176 return AVERROR_NOMEM;
2177 st->codec->extradata_size = track->codec_priv_size;
2178 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2179 track->codec_priv_size);
2182 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2183 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2185 st->codec->codec_type = CODEC_TYPE_VIDEO;
2186 st->codec->codec_tag = videotrack->fourcc;
2187 st->codec->width = videotrack->pixel_width;
2188 st->codec->height = videotrack->pixel_height;
2189 if (videotrack->display_width == 0)
2190 videotrack->display_width= videotrack->pixel_width;
2191 if (videotrack->display_height == 0)
2192 videotrack->display_height= videotrack->pixel_height;
2193 av_reduce(&st->codec->sample_aspect_ratio.num,
2194 &st->codec->sample_aspect_ratio.den,
2195 st->codec->height * videotrack->display_width,
2196 st->codec-> width * videotrack->display_height,
2198 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2199 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2200 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2202 st->codec->codec_type = CODEC_TYPE_AUDIO;
2203 st->codec->sample_rate = audiotrack->samplerate;
2204 st->codec->channels = audiotrack->channels;
2205 st->codec->block_align = audiotrack->block_align;
2206 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2207 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2210 /* What do we do with private data? E.g. for Vorbis. */
2215 if (matroska->index_parsed) {
2216 int i, track, stream;
2217 for (i=0; i<matroska->num_indexes; i++) {
2218 MatroskaDemuxIndex *idx = &matroska->index[i];
2219 track = matroska_find_track_by_num(matroska, idx->track);
2220 stream = matroska->tracks[track]->stream_index;
2221 av_add_index_entry(matroska->ctx->streams[stream],
2222 idx->pos, idx->time/matroska->time_scale,
2223 0, 0, AVINDEX_KEYFRAME);
2231 rv_offset(uint8_t *data, int slice, int slices)
2233 return AV_RL32(data+8*slice+4) + 8*slices;
2237 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2238 int64_t pos, uint64_t cluster_time, uint64_t duration,
2239 int is_keyframe, int is_bframe)
2245 uint8_t *origdata = data;
2247 uint32_t *lace_size = NULL;
2248 int n, flags, laces = 0;
2251 /* first byte(s): tracknum */
2252 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2253 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2260 /* fetch track from num */
2261 track = matroska_find_track_by_num(matroska, num);
2262 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2263 av_log(matroska->ctx, AV_LOG_INFO,
2264 "Invalid stream %d or size %u\n", track, size);
2268 st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2269 if (st->discard >= AVDISCARD_ALL) {
2273 if (duration == AV_NOPTS_VALUE)
2274 duration = matroska->tracks[track]->default_duration;
2276 /* block_time (relative to cluster time) */
2277 block_time = (data[0] << 8) | data[1];
2283 if (is_keyframe == -1)
2284 is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2286 if (matroska->skip_to_keyframe) {
2287 if (!is_keyframe || st != matroska->skip_to_stream)
2289 matroska->skip_to_keyframe = 0;
2292 switch ((flags & 0x06) >> 1) {
2293 case 0x0: /* no lacing */
2295 lace_size = av_mallocz(sizeof(int));
2296 lace_size[0] = size;
2299 case 0x1: /* xiph lacing */
2300 case 0x2: /* fixed-size lacing */
2301 case 0x3: /* EBML lacing */
2306 laces = (*data) + 1;
2309 lace_size = av_mallocz(laces * sizeof(int));
2311 switch ((flags & 0x06) >> 1) {
2312 case 0x1: /* xiph lacing */ {
2315 for (n = 0; res == 0 && n < laces - 1; n++) {
2322 lace_size[n] += temp;
2328 total += lace_size[n];
2330 lace_size[n] = size - total;
2334 case 0x2: /* fixed-size lacing */
2335 for (n = 0; n < laces; n++)
2336 lace_size[n] = size / laces;
2339 case 0x3: /* EBML lacing */ {
2341 n = matroska_ebmlnum_uint(data, size, &num);
2343 av_log(matroska->ctx, AV_LOG_INFO,
2344 "EBML block data error\n");
2349 total = lace_size[0] = num;
2350 for (n = 1; res == 0 && n < laces - 1; n++) {
2353 r = matroska_ebmlnum_sint (data, size, &snum);
2355 av_log(matroska->ctx, AV_LOG_INFO,
2356 "EBML block data error\n");
2361 lace_size[n] = lace_size[n - 1] + snum;
2362 total += lace_size[n];
2364 lace_size[n] = size - total;
2372 int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2373 uint64_t timecode = AV_NOPTS_VALUE;
2375 if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
2376 timecode = cluster_time + block_time;
2378 for (n = 0; n < laces; n++) {
2379 int slice, slices = 1;
2382 slices = *data++ + 1;
2386 for (slice=0; slice<slices; slice++) {
2387 int slice_size, slice_offset = 0;
2389 slice_offset = rv_offset(data, slice, slices);
2390 if (slice+1 == slices)
2391 slice_size = lace_size[n] - slice_offset;
2393 slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2395 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2396 st->codec->codec_id == CODEC_ID_COOK ||
2397 st->codec->codec_id == CODEC_ID_ATRAC3) {
2398 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2399 int a = st->codec->block_align;
2400 int sps = audiotrack->sub_packet_size;
2401 int cfs = audiotrack->coded_framesize;
2402 int h = audiotrack->sub_packet_h;
2403 int y = audiotrack->sub_packet_cnt;
2404 int w = audiotrack->frame_size;
2407 if (!audiotrack->pkt_cnt) {
2408 if (st->codec->codec_id == CODEC_ID_RA_288)
2409 for (x=0; x<h/2; x++)
2410 memcpy(audiotrack->buf+x*2*w+y*cfs,
2413 for (x=0; x<w/sps; x++)
2414 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2416 if (++audiotrack->sub_packet_cnt >= h) {
2417 audiotrack->sub_packet_cnt = 0;
2418 audiotrack->pkt_cnt = h*w / a;
2421 while (audiotrack->pkt_cnt) {
2422 pkt = av_mallocz(sizeof(AVPacket));
2423 av_new_packet(pkt, a);
2424 memcpy(pkt->data, audiotrack->buf
2425 + a * (h*w / a - audiotrack->pkt_cnt--), a);
2427 pkt->stream_index = matroska->tracks[track]->stream_index;
2428 matroska_queue_packet(matroska, pkt);
2431 pkt = av_mallocz(sizeof(AVPacket));
2432 /* XXX: prevent data copy... */
2433 if (av_new_packet(pkt, slice_size) < 0) {
2434 res = AVERROR_NOMEM;
2438 memcpy (pkt->data, data+slice_offset, slice_size);
2441 pkt->flags = is_keyframe;
2442 pkt->stream_index = matroska->tracks[track]->stream_index;
2444 pkt->pts = timecode;
2446 pkt->duration = duration;
2448 matroska_queue_packet(matroska, pkt);
2451 if (timecode != AV_NOPTS_VALUE)
2452 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2454 data += lace_size[n];
2464 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2465 uint64_t cluster_time)
2470 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2471 uint64_t duration = AV_NOPTS_VALUE;
2476 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2479 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2482 } else if (matroska->level_up) {
2483 matroska->level_up--;
2488 /* one block inside the group. Note, block parsing is one
2489 * of the harder things, so this code is a bit complicated.
2490 * See http://www.matroska.org/ for documentation. */
2491 case MATROSKA_ID_BLOCK: {
2492 pos = url_ftell(&matroska->ctx->pb);
2493 res = ebml_read_binary(matroska, &id, &data, &size);
2497 case MATROSKA_ID_BLOCKDURATION: {
2498 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2500 duration /= matroska->time_scale;
2504 case MATROSKA_ID_BLOCKREFERENCE: {
2506 /* We've found a reference, so not even the first frame in
2507 * the lace is a key frame. */
2509 if (last_num_packets != matroska->num_packets)
2510 matroska->packets[last_num_packets]->flags = 0;
2511 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2519 av_log(matroska->ctx, AV_LOG_INFO,
2520 "Unknown entry 0x%x in blockgroup data\n", id);
2524 res = ebml_read_skip(matroska);
2528 if (matroska->level_up) {
2529 matroska->level_up--;
2538 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2539 duration, is_keyframe, is_bframe);
2545 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2549 uint64_t cluster_time = 0;
2554 av_log(matroska->ctx, AV_LOG_DEBUG,
2555 "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2558 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2561 } else if (matroska->level_up) {
2562 matroska->level_up--;
2567 /* cluster timecode */
2568 case MATROSKA_ID_CLUSTERTIMECODE: {
2570 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2576 /* a group of blocks inside a cluster */
2577 case MATROSKA_ID_BLOCKGROUP:
2578 if ((res = ebml_read_master(matroska, &id)) < 0)
2580 res = matroska_parse_blockgroup(matroska, cluster_time);
2583 case MATROSKA_ID_SIMPLEBLOCK:
2584 pos = url_ftell(&matroska->ctx->pb);
2585 res = ebml_read_binary(matroska, &id, &data, &size);
2587 res = matroska_parse_block(matroska, data, size, pos,
2588 cluster_time, AV_NOPTS_VALUE,
2593 av_log(matroska->ctx, AV_LOG_INFO,
2594 "Unknown entry 0x%x in cluster data\n", id);
2598 res = ebml_read_skip(matroska);
2602 if (matroska->level_up) {
2603 matroska->level_up--;
2612 matroska_read_packet (AVFormatContext *s,
2615 MatroskaDemuxContext *matroska = s->priv_data;
2619 /* Read stream until we have a packet queued. */
2620 while (matroska_deliver_packet(matroska, pkt)) {
2622 /* Have we already reached the end? */
2628 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2630 } else if (matroska->level_up) {
2631 matroska->level_up--;
2636 case MATROSKA_ID_CLUSTER:
2637 if ((res = ebml_read_master(matroska, &id)) < 0)
2639 if ((res = matroska_parse_cluster(matroska)) == 0)
2640 res = 1; /* Parsed one cluster, let's get out. */
2645 res = ebml_read_skip(matroska);
2649 if (matroska->level_up) {
2650 matroska->level_up--;
2663 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2666 MatroskaDemuxContext *matroska = s->priv_data;
2667 AVStream *st = s->streams[stream_index];
2670 /* find index entry */
2671 index = av_index_search_timestamp(st, timestamp, flags);
2676 url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
2677 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2678 matroska->skip_to_stream = st;
2679 matroska->num_packets = 0;
2680 matroska->peek_id = 0;
2685 matroska_read_close (AVFormatContext *s)
2687 MatroskaDemuxContext *matroska = s->priv_data;
2690 av_free(matroska->writing_app);
2691 av_free(matroska->muxing_app);
2692 av_free(matroska->index);
2694 if (matroska->packets != NULL) {
2695 for (n = 0; n < matroska->num_packets; n++) {
2696 av_free_packet(matroska->packets[n]);
2697 av_free(matroska->packets[n]);
2699 av_free(matroska->packets);
2702 for (n = 0; n < matroska->num_tracks; n++) {
2703 MatroskaTrack *track = matroska->tracks[n];
2704 av_free(track->codec_id);
2705 av_free(track->codec_name);
2706 av_free(track->codec_priv);
2707 av_free(track->name);
2708 av_free(track->language);
2710 if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2711 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2712 av_free(audiotrack->buf);
2721 AVInputFormat matroska_demuxer = {
2723 "Matroska file format",
2724 sizeof(MatroskaDemuxContext),
2726 matroska_read_header,
2727 matroska_read_packet,
2728 matroska_read_close,