3 * Copyright (c) 2001, 2002 Fabrice Bellard
7 * Copyright (c) 2009 Daniel Verkamp
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/avassert.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/log.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
34 #include "avio_internal.h"
42 typedef struct WAVDemuxContext {
48 int smv_frames_per_jpeg;
59 #if CONFIG_WAV_DEMUXER
61 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
67 /* RIFF chunks are always on a even offset. */
68 static int64_t wav_seek_tag(AVIOContext *s, int64_t offset, int whence)
70 offset += offset < INT64_MAX && offset & 1;
72 return avio_seek(s, offset, whence);
75 /* return the size of the found tag */
76 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
84 size = next_tag(pb, &tag);
87 wav_seek_tag(pb, size, SEEK_CUR);
92 static int wav_probe(AVProbeData *p)
94 /* check file header */
95 if (p->buf_size <= 32)
97 if (!memcmp(p->buf + 8, "WAVE", 4)) {
98 if (!memcmp(p->buf, "RIFF", 4))
99 /* Since the ACT demuxer has a standard WAV header at the top of
100 * its own, the returned score is decreased to avoid a probe
101 * conflict between ACT and WAV. */
102 return AVPROBE_SCORE_MAX - 1;
103 else if (!memcmp(p->buf, "RF64", 4) &&
104 !memcmp(p->buf + 12, "ds64", 4))
105 return AVPROBE_SCORE_MAX;
110 static void handle_stream_probing(AVStream *st)
112 if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
113 st->request_probe = AVPROBE_SCORE_EXTENSION;
114 st->probe_packets = FFMIN(st->probe_packets, 4);
118 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
120 AVIOContext *pb = s->pb;
123 /* parse fmt header */
124 *st = avformat_new_stream(s, NULL);
126 return AVERROR(ENOMEM);
128 ret = ff_get_wav_header(pb, (*st)->codec, size);
131 handle_stream_probing(*st);
133 (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
135 avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
140 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
146 av_assert0(length <= sizeof(temp));
147 if ((ret = avio_read(s->pb, temp, length)) < 0)
153 return av_dict_set(&s->metadata, key, temp, 0);
158 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
160 char temp[131], *coding_history;
162 uint64_t time_reference;
163 int64_t umid_parts[8], umid_mask = 0;
165 if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
166 (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
167 (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
168 (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
169 (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
172 time_reference = avio_rl64(s->pb);
173 snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
174 if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
177 /* check if version is >= 1, in which case an UMID may be present */
178 if (avio_rl16(s->pb) >= 1) {
179 for (x = 0; x < 8; x++)
180 umid_mask |= umid_parts[x] = avio_rb64(s->pb);
183 /* the string formatting below is per SMPTE 330M-2004 Annex C */
184 if (umid_parts[4] == 0 && umid_parts[5] == 0 &&
185 umid_parts[6] == 0 && umid_parts[7] == 0) {
187 snprintf(temp, sizeof(temp),
188 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
189 umid_parts[0], umid_parts[1],
190 umid_parts[2], umid_parts[3]);
193 snprintf(temp, sizeof(temp),
194 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
195 "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
196 umid_parts[0], umid_parts[1],
197 umid_parts[2], umid_parts[3],
198 umid_parts[4], umid_parts[5],
199 umid_parts[6], umid_parts[7]);
202 if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
206 avio_skip(s->pb, 190);
208 avio_skip(s->pb, 254);
211 /* CodingHistory present */
214 if (!(coding_history = av_malloc(size + 1)))
215 return AVERROR(ENOMEM);
217 if ((ret = avio_read(s->pb, coding_history, size)) < 0)
220 coding_history[size] = 0;
221 if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
222 AV_DICT_DONT_STRDUP_VAL)) < 0)
229 static const AVMetadataConv wav_metadata_conv[] = {
230 { "description", "comment" },
231 { "originator", "encoded_by" },
232 { "origination_date", "date" },
233 { "origination_time", "creation_time" },
238 static int wav_read_header(AVFormatContext *s)
240 int64_t size, av_uninit(data_size);
241 int64_t sample_count = 0;
244 AVIOContext *pb = s->pb;
246 WAVDemuxContext *wav = s->priv_data;
247 int ret, got_fmt = 0;
248 int64_t next_tag_ofs, data_ofs = -1;
250 wav->smv_data_ofs = -1;
252 /* check RIFF header */
255 rf64 = tag == MKTAG('R', 'F', '6', '4');
256 if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
257 return AVERROR_INVALIDDATA;
258 avio_rl32(pb); /* file size */
260 if (tag != MKTAG('W', 'A', 'V', 'E'))
261 return AVERROR_INVALIDDATA;
264 if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
265 return AVERROR_INVALIDDATA;
266 size = avio_rl32(pb);
268 return AVERROR_INVALIDDATA;
269 avio_rl64(pb); /* RIFF size */
271 data_size = avio_rl64(pb);
272 sample_count = avio_rl64(pb);
274 if (data_size < 0 || sample_count < 0) {
275 av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
276 "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
277 data_size, sample_count);
278 return AVERROR_INVALIDDATA;
280 avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
286 size = next_tag(pb, &tag);
287 next_tag_ofs = avio_tell(pb) + size;
293 case MKTAG('f', 'm', 't', ' '):
294 /* only parse the first 'fmt ' tag found */
295 if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
298 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
302 case MKTAG('d', 'a', 't', 'a'):
304 av_log(s, AV_LOG_ERROR,
305 "found no 'fmt ' tag before the 'data' tag\n");
306 return AVERROR_INVALIDDATA;
310 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
313 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
316 data_ofs = avio_tell(pb);
318 /* don't look for footer metadata if we can't seek or if we don't
319 * know where the data tag ends
321 if (!pb->seekable || (!rf64 && !size))
324 case MKTAG('f', 'a', 'c', 't'):
326 sample_count = avio_rl32(pb);
328 case MKTAG('b', 'e', 'x', 't'):
329 if ((ret = wav_parse_bext_tag(s, size)) < 0)
332 case MKTAG('S','M','V','0'):
334 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
335 return AVERROR_INVALIDDATA;
337 // SMV file, a wav file with video appended.
338 if (size != MKTAG('0','2','0','0')) {
339 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
342 av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
343 wav->smv_given_first = 0;
344 vst = avformat_new_stream(s, NULL);
346 return AVERROR(ENOMEM);
349 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
350 vst->codec->codec_id = AV_CODEC_ID_SMVJPEG;
351 vst->codec->width = avio_rl24(pb);
352 vst->codec->height = avio_rl24(pb);
353 vst->codec->extradata_size = 4;
354 vst->codec->extradata = av_malloc(vst->codec->extradata_size +
355 FF_INPUT_BUFFER_PADDING_SIZE);
356 if (!vst->codec->extradata) {
357 av_log(s, AV_LOG_ERROR, "Could not allocate extradata.\n");
358 return AVERROR(ENOMEM);
360 size = avio_rl24(pb);
361 wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
363 wav->smv_block_size = avio_rl24(pb);
364 avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
365 vst->duration = avio_rl24(pb);
368 wav->smv_frames_per_jpeg = avio_rl24(pb);
369 AV_WL32(vst->codec->extradata, wav->smv_frames_per_jpeg);
372 case MKTAG('L', 'I', 'S', 'T'):
374 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
375 return AVERROR_INVALIDDATA;
377 switch (avio_rl32(pb)) {
378 case MKTAG('I', 'N', 'F', 'O'):
379 ff_read_riff_info(s, size - 4);
384 /* seek to next tag unless we know that we'll run into EOF */
385 if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
386 wav_seek_tag(pb, next_tag_ofs, SEEK_SET) < 0) {
393 av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
394 return AVERROR_INVALIDDATA;
397 avio_seek(pb, data_ofs, SEEK_SET);
399 if (!sample_count && st->codec->channels &&
400 av_get_bits_per_sample(st->codec->codec_id) && wav->data_end <= avio_size(pb))
401 sample_count = (data_size << 3) /
402 (st->codec->channels *
403 (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
405 st->duration = sample_count;
407 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
408 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
414 * Find chunk with w64 GUID by skipping over other chunks.
415 * @return the size of the found chunk
417 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
422 while (!url_feof(pb)) {
423 avio_read(pb, guid, 16);
424 size = avio_rl64(pb);
426 return AVERROR_INVALIDDATA;
427 if (!memcmp(guid, guid1, 16))
429 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
434 #define MAX_SIZE 4096
436 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
441 WAVDemuxContext *wav = s->priv_data;
443 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
444 s->streams[0]->codec->codec_tag == 1) {
445 enum AVCodecID codec;
446 ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
448 if (ret > AVPROBE_SCORE_EXTENSION) {
449 s->streams[0]->codec->codec_id = codec;
455 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
456 return ff_spdif_read_packet(s, pkt);
458 if (wav->smv_data_ofs > 0) {
459 int64_t audio_dts, video_dts;
461 audio_dts = s->streams[0]->cur_dts;
462 video_dts = s->streams[1]->cur_dts;
464 if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
465 audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
466 video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
467 /*We always return a video frame first to get the pixel format first*/
468 wav->smv_last_stream = wav->smv_given_first ? video_dts > audio_dts : 0;
469 wav->smv_given_first = 1;
471 wav->smv_last_stream = !wav->smv_last_stream;
472 wav->smv_last_stream |= wav->audio_eof;
473 wav->smv_last_stream &= !wav->smv_eof;
474 if (wav->smv_last_stream) {
475 uint64_t old_pos = avio_tell(s->pb);
476 uint64_t new_pos = wav->smv_data_ofs +
477 wav->smv_block * wav->smv_block_size;
478 if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
482 size = avio_rl24(s->pb);
483 ret = av_get_packet(s->pb, pkt, size);
487 pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt;
489 if (wav->smv_frames_per_jpeg > 0)
490 wav->smv_cur_pt %= wav->smv_frames_per_jpeg;
491 if (!wav->smv_cur_pt)
494 pkt->stream_index = 1;
496 avio_seek(s->pb, old_pos, SEEK_SET);
497 if (ret == AVERROR_EOF) {
507 left = wav->data_end - avio_tell(s->pb);
508 if (wav->ignore_length)
511 if (CONFIG_W64_DEMUXER && wav->w64)
512 left = find_guid(s->pb, ff_w64_guid_data) - 24;
514 left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
517 if (wav->smv_data_ofs > 0 && !wav->smv_eof)
521 wav->data_end = avio_tell(s->pb) + left;
525 if (st->codec->block_align > 1) {
526 if (size < st->codec->block_align)
527 size = st->codec->block_align;
528 size = (size / st->codec->block_align) * st->codec->block_align;
530 size = FFMIN(size, left);
531 ret = av_get_packet(s->pb, pkt, size);
534 pkt->stream_index = 0;
539 static int wav_read_seek(AVFormatContext *s,
540 int stream_index, int64_t timestamp, int flags)
542 WAVDemuxContext *wav = s->priv_data;
546 if (wav->smv_data_ofs > 0) {
547 int64_t smv_timestamp = timestamp;
548 if (stream_index == 0)
549 smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
551 timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
552 if (wav->smv_frames_per_jpeg > 0) {
553 wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
554 wav->smv_cur_pt = smv_timestamp % wav->smv_frames_per_jpeg;
559 switch (st->codec->codec_id) {
560 case AV_CODEC_ID_MP2:
561 case AV_CODEC_ID_MP3:
562 case AV_CODEC_ID_AC3:
563 case AV_CODEC_ID_DTS:
564 /* use generic seeking with dynamically generated indexes */
569 return ff_pcm_read_seek(s, stream_index, timestamp, flags);
572 #define OFFSET(x) offsetof(WAVDemuxContext, x)
573 #define DEC AV_OPT_FLAG_DECODING_PARAM
574 static const AVOption demux_options[] = {
575 { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
579 static const AVClass wav_demuxer_class = {
580 .class_name = "WAV demuxer",
581 .item_name = av_default_item_name,
582 .option = demux_options,
583 .version = LIBAVUTIL_VERSION_INT,
585 AVInputFormat ff_wav_demuxer = {
587 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
588 .priv_data_size = sizeof(WAVDemuxContext),
589 .read_probe = wav_probe,
590 .read_header = wav_read_header,
591 .read_packet = wav_read_packet,
592 .read_seek = wav_read_seek,
593 .flags = AVFMT_GENERIC_INDEX,
594 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
595 .priv_class = &wav_demuxer_class,
597 #endif /* CONFIG_WAV_DEMUXER */
599 #if CONFIG_W64_DEMUXER
600 static int w64_probe(AVProbeData *p)
602 if (p->buf_size <= 40)
604 if (!memcmp(p->buf, ff_w64_guid_riff, 16) &&
605 !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
606 return AVPROBE_SCORE_MAX;
611 static int w64_read_header(AVFormatContext *s)
613 int64_t size, data_ofs = 0;
614 AVIOContext *pb = s->pb;
615 WAVDemuxContext *wav = s->priv_data;
620 avio_read(pb, guid, 16);
621 if (memcmp(guid, ff_w64_guid_riff, 16))
622 return AVERROR_INVALIDDATA;
624 /* riff + wave + fmt + sizes */
625 if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
626 return AVERROR_INVALIDDATA;
628 avio_read(pb, guid, 16);
629 if (memcmp(guid, ff_w64_guid_wave, 16)) {
630 av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
631 return AVERROR_INVALIDDATA;
636 st = avformat_new_stream(s, NULL);
638 return AVERROR(ENOMEM);
640 while (!url_feof(pb)) {
641 if (avio_read(pb, guid, 16) != 16)
643 size = avio_rl64(pb);
644 if (size <= 24 || INT64_MAX - size < avio_tell(pb))
645 return AVERROR_INVALIDDATA;
647 if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
648 /* subtract chunk header size - normal wav file doesn't count it */
649 ret = ff_get_wav_header(pb, st->codec, size - 24);
652 avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
654 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
655 } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
658 samples = avio_rl64(pb);
660 st->duration = samples;
661 } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
662 wav->data_end = avio_tell(pb) + size - 24;
664 data_ofs = avio_tell(pb);
668 avio_skip(pb, size - 24);
669 } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
670 int64_t start, end, cur;
671 uint32_t count, chunk_size, i;
673 start = avio_tell(pb);
675 count = avio_rl32(pb);
677 for (i = 0; i < count; i++) {
678 char chunk_key[5], *value;
680 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
684 avio_read(pb, chunk_key, 4);
685 chunk_size = avio_rl32(pb);
687 value = av_mallocz(chunk_size + 1);
689 return AVERROR(ENOMEM);
691 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
692 avio_skip(pb, chunk_size - ret);
694 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
697 avio_skip(pb, end - avio_tell(pb));
699 av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
700 avio_skip(pb, size - 24);
707 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
708 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
710 handle_stream_probing(st);
711 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
713 avio_seek(pb, data_ofs, SEEK_SET);
718 AVInputFormat ff_w64_demuxer = {
720 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
721 .priv_data_size = sizeof(WAVDemuxContext),
722 .read_probe = w64_probe,
723 .read_header = w64_read_header,
724 .read_packet = wav_read_packet,
725 .read_seek = wav_read_seek,
726 .flags = AVFMT_GENERIC_INDEX,
727 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
729 #endif /* CONFIG_W64_DEMUXER */