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/log.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
33 #include "avio_internal.h"
41 typedef struct WAVDemuxContext {
47 int smv_frames_per_jpeg;
56 #if CONFIG_WAV_DEMUXER
58 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
64 /* RIFF chunks are always on a even offset. */
65 static int64_t wav_seek_tag(AVIOContext *s, int64_t offset, int whence)
67 offset += offset < INT64_MAX && offset & 1;
69 return avio_seek(s, offset, whence);
72 /* return the size of the found tag */
73 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
81 size = next_tag(pb, &tag);
84 wav_seek_tag(pb, size, SEEK_CUR);
89 static int wav_probe(AVProbeData *p)
91 /* check file header */
92 if (p->buf_size <= 32)
94 if (!memcmp(p->buf + 8, "WAVE", 4)) {
95 if (!memcmp(p->buf, "RIFF", 4))
96 /* Since the ACT demuxer has a standard WAV header at the top of
97 * its own, the returned score is decreased to avoid a probe
98 * conflict between ACT and WAV. */
99 return AVPROBE_SCORE_MAX - 1;
100 else if (!memcmp(p->buf, "RF64", 4) &&
101 !memcmp(p->buf + 12, "ds64", 4))
102 return AVPROBE_SCORE_MAX;
107 static void handle_stream_probing(AVStream *st)
109 if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
110 st->request_probe = AVPROBE_SCORE_EXTENSION;
111 st->probe_packets = FFMIN(st->probe_packets, 4);
115 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
117 AVIOContext *pb = s->pb;
120 /* parse fmt header */
121 *st = avformat_new_stream(s, NULL);
123 return AVERROR(ENOMEM);
125 ret = ff_get_wav_header(pb, (*st)->codec, size);
128 handle_stream_probing(*st);
130 (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
132 avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
137 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
143 av_assert0(length <= sizeof(temp));
144 if ((ret = avio_read(s->pb, temp, length)) < 0)
150 return av_dict_set(&s->metadata, key, temp, 0);
155 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
157 char temp[131], *coding_history;
159 uint64_t time_reference;
160 int64_t umid_parts[8], umid_mask = 0;
162 if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
163 (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
164 (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
165 (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
166 (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
169 time_reference = avio_rl64(s->pb);
170 snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
171 if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
174 /* check if version is >= 1, in which case an UMID may be present */
175 if (avio_rl16(s->pb) >= 1) {
176 for (x = 0; x < 8; x++)
177 umid_mask |= umid_parts[x] = avio_rb64(s->pb);
180 /* the string formatting below is per SMPTE 330M-2004 Annex C */
181 if (umid_parts[4] == 0 && umid_parts[5] == 0 &&
182 umid_parts[6] == 0 && umid_parts[7] == 0) {
184 snprintf(temp, sizeof(temp),
185 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
186 umid_parts[0], umid_parts[1],
187 umid_parts[2], umid_parts[3]);
190 snprintf(temp, sizeof(temp),
191 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
192 "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
193 umid_parts[0], umid_parts[1],
194 umid_parts[2], umid_parts[3],
195 umid_parts[4], umid_parts[5],
196 umid_parts[6], umid_parts[7]);
199 if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
203 avio_skip(s->pb, 190);
205 avio_skip(s->pb, 254);
208 /* CodingHistory present */
211 if (!(coding_history = av_malloc(size + 1)))
212 return AVERROR(ENOMEM);
214 if ((ret = avio_read(s->pb, coding_history, size)) < 0)
217 coding_history[size] = 0;
218 if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
219 AV_DICT_DONT_STRDUP_VAL)) < 0)
226 static const AVMetadataConv wav_metadata_conv[] = {
227 { "description", "comment" },
228 { "originator", "encoded_by" },
229 { "origination_date", "date" },
230 { "origination_time", "creation_time" },
235 static int wav_read_header(AVFormatContext *s)
237 int64_t size, av_uninit(data_size);
238 int64_t sample_count = 0;
241 AVIOContext *pb = s->pb;
243 WAVDemuxContext *wav = s->priv_data;
244 int ret, got_fmt = 0;
245 int64_t next_tag_ofs, data_ofs = -1;
247 wav->smv_data_ofs = -1;
249 /* check RIFF header */
252 rf64 = tag == MKTAG('R', 'F', '6', '4');
253 if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
254 return AVERROR_INVALIDDATA;
255 avio_rl32(pb); /* file size */
257 if (tag != MKTAG('W', 'A', 'V', 'E'))
258 return AVERROR_INVALIDDATA;
261 if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
262 return AVERROR_INVALIDDATA;
263 size = avio_rl32(pb);
265 return AVERROR_INVALIDDATA;
266 avio_rl64(pb); /* RIFF size */
268 data_size = avio_rl64(pb);
269 sample_count = avio_rl64(pb);
271 if (data_size < 0 || sample_count < 0) {
272 av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
273 "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
274 data_size, sample_count);
275 return AVERROR_INVALIDDATA;
277 avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
283 size = next_tag(pb, &tag);
284 next_tag_ofs = avio_tell(pb) + size;
290 case MKTAG('f', 'm', 't', ' '):
291 /* only parse the first 'fmt ' tag found */
292 if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
295 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
299 case MKTAG('d', 'a', 't', 'a'):
301 av_log(s, AV_LOG_ERROR,
302 "found no 'fmt ' tag before the 'data' tag\n");
303 return AVERROR_INVALIDDATA;
307 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
310 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
313 data_ofs = avio_tell(pb);
315 /* don't look for footer metadata if we can't seek or if we don't
316 * know where the data tag ends
318 if (!pb->seekable || (!rf64 && !size))
321 case MKTAG('f', 'a', 'c', 't'):
323 sample_count = avio_rl32(pb);
325 case MKTAG('b', 'e', 'x', 't'):
326 if ((ret = wav_parse_bext_tag(s, size)) < 0)
329 case MKTAG('S','M','V','0'):
331 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
332 return AVERROR_INVALIDDATA;
334 // SMV file, a wav file with video appended.
335 if (size != MKTAG('0','2','0','0')) {
336 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
339 av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
340 vst = avformat_new_stream(s, NULL);
342 return AVERROR(ENOMEM);
345 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
346 vst->codec->codec_id = AV_CODEC_ID_MJPEG;
347 vst->codec->width = avio_rl24(pb);
348 vst->codec->height = avio_rl24(pb);
349 size = avio_rl24(pb);
350 wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
352 wav->smv_block_size = avio_rl24(pb);
353 avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
354 vst->duration = avio_rl24(pb);
357 wav->smv_frames_per_jpeg = avio_rl24(pb);
359 case MKTAG('L', 'I', 'S', 'T'):
361 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
362 return AVERROR_INVALIDDATA;
364 switch (avio_rl32(pb)) {
365 case MKTAG('I', 'N', 'F', 'O'):
366 ff_read_riff_info(s, size - 4);
371 /* seek to next tag unless we know that we'll run into EOF */
372 if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
373 wav_seek_tag(pb, next_tag_ofs, SEEK_SET) < 0) {
380 av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
381 return AVERROR_INVALIDDATA;
384 avio_seek(pb, data_ofs, SEEK_SET);
386 if (!sample_count && st->codec->channels &&
387 av_get_bits_per_sample(st->codec->codec_id) && wav->data_end <= avio_size(pb))
388 sample_count = (data_size << 3) /
389 (st->codec->channels *
390 (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
392 st->duration = sample_count;
394 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
395 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
401 * Find chunk with w64 GUID by skipping over other chunks.
402 * @return the size of the found chunk
404 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
409 while (!url_feof(pb)) {
410 avio_read(pb, guid, 16);
411 size = avio_rl64(pb);
413 return AVERROR_INVALIDDATA;
414 if (!memcmp(guid, guid1, 16))
416 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
421 #define MAX_SIZE 4096
423 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
428 WAVDemuxContext *wav = s->priv_data;
430 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
431 s->streams[0]->codec->codec_tag == 1) {
432 enum AVCodecID codec;
433 ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
435 if (ret > AVPROBE_SCORE_EXTENSION) {
436 s->streams[0]->codec->codec_id = codec;
442 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
443 return ff_spdif_read_packet(s, pkt);
445 if (wav->smv_data_ofs > 0) {
446 int64_t audio_dts, video_dts;
448 audio_dts = s->streams[0]->cur_dts;
449 video_dts = s->streams[1]->cur_dts;
450 if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
451 audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
452 video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
453 wav->smv_last_stream = video_dts >= audio_dts;
455 wav->smv_last_stream = !wav->smv_last_stream;
456 wav->smv_last_stream |= wav->audio_eof;
457 wav->smv_last_stream &= !wav->smv_eof;
458 if (wav->smv_last_stream) {
459 uint64_t old_pos = avio_tell(s->pb);
460 uint64_t new_pos = wav->smv_data_ofs +
461 wav->smv_block * wav->smv_block_size;
462 if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
466 size = avio_rl24(s->pb);
467 ret = av_get_packet(s->pb, pkt, size);
471 pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg;
473 pkt->stream_index = 1;
475 avio_seek(s->pb, old_pos, SEEK_SET);
476 if (ret == AVERROR_EOF) {
486 left = wav->data_end - avio_tell(s->pb);
487 if (wav->ignore_length)
490 if (CONFIG_W64_DEMUXER && wav->w64)
491 left = find_guid(s->pb, ff_w64_guid_data) - 24;
493 left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
496 if (wav->smv_data_ofs > 0 && !wav->smv_eof)
500 wav->data_end = avio_tell(s->pb) + left;
504 if (st->codec->block_align > 1) {
505 if (size < st->codec->block_align)
506 size = st->codec->block_align;
507 size = (size / st->codec->block_align) * st->codec->block_align;
509 size = FFMIN(size, left);
510 ret = av_get_packet(s->pb, pkt, size);
513 pkt->stream_index = 0;
518 static int wav_read_seek(AVFormatContext *s,
519 int stream_index, int64_t timestamp, int flags)
521 WAVDemuxContext *wav = s->priv_data;
525 if (wav->smv_data_ofs > 0) {
526 int64_t smv_timestamp = timestamp;
527 if (stream_index == 0)
528 smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
530 timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
531 wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
535 switch (st->codec->codec_id) {
536 case AV_CODEC_ID_MP2:
537 case AV_CODEC_ID_MP3:
538 case AV_CODEC_ID_AC3:
539 case AV_CODEC_ID_DTS:
540 /* use generic seeking with dynamically generated indexes */
545 return ff_pcm_read_seek(s, stream_index, timestamp, flags);
548 #define OFFSET(x) offsetof(WAVDemuxContext, x)
549 #define DEC AV_OPT_FLAG_DECODING_PARAM
550 static const AVOption demux_options[] = {
551 { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
555 static const AVClass wav_demuxer_class = {
556 .class_name = "WAV demuxer",
557 .item_name = av_default_item_name,
558 .option = demux_options,
559 .version = LIBAVUTIL_VERSION_INT,
561 AVInputFormat ff_wav_demuxer = {
563 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
564 .priv_data_size = sizeof(WAVDemuxContext),
565 .read_probe = wav_probe,
566 .read_header = wav_read_header,
567 .read_packet = wav_read_packet,
568 .read_seek = wav_read_seek,
569 .flags = AVFMT_GENERIC_INDEX,
570 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
571 .priv_class = &wav_demuxer_class,
573 #endif /* CONFIG_WAV_DEMUXER */
575 #if CONFIG_W64_DEMUXER
576 static int w64_probe(AVProbeData *p)
578 if (p->buf_size <= 40)
580 if (!memcmp(p->buf, ff_w64_guid_riff, 16) &&
581 !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
582 return AVPROBE_SCORE_MAX;
587 static int w64_read_header(AVFormatContext *s)
589 int64_t size, data_ofs = 0;
590 AVIOContext *pb = s->pb;
591 WAVDemuxContext *wav = s->priv_data;
596 avio_read(pb, guid, 16);
597 if (memcmp(guid, ff_w64_guid_riff, 16))
598 return AVERROR_INVALIDDATA;
600 /* riff + wave + fmt + sizes */
601 if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
602 return AVERROR_INVALIDDATA;
604 avio_read(pb, guid, 16);
605 if (memcmp(guid, ff_w64_guid_wave, 16)) {
606 av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
607 return AVERROR_INVALIDDATA;
612 st = avformat_new_stream(s, NULL);
614 return AVERROR(ENOMEM);
616 while (!url_feof(pb)) {
617 if (avio_read(pb, guid, 16) != 16)
619 size = avio_rl64(pb);
620 if (size <= 24 || INT64_MAX - size < avio_tell(pb))
621 return AVERROR_INVALIDDATA;
623 if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
624 /* subtract chunk header size - normal wav file doesn't count it */
625 ret = ff_get_wav_header(pb, st->codec, size - 24);
628 avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
630 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
631 } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
634 samples = avio_rl64(pb);
636 st->duration = samples;
637 } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
638 wav->data_end = avio_tell(pb) + size - 24;
640 data_ofs = avio_tell(pb);
644 avio_skip(pb, size - 24);
645 } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
646 int64_t start, end, cur;
647 uint32_t count, chunk_size, i;
649 start = avio_tell(pb);
651 count = avio_rl32(pb);
653 for (i = 0; i < count; i++) {
654 char chunk_key[5], *value;
656 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
660 avio_read(pb, chunk_key, 4);
661 chunk_size = avio_rl32(pb);
663 value = av_mallocz(chunk_size + 1);
665 return AVERROR(ENOMEM);
667 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
668 avio_skip(pb, chunk_size - ret);
670 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
673 avio_skip(pb, end - avio_tell(pb));
675 av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
676 avio_skip(pb, size - 24);
683 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
684 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
686 handle_stream_probing(st);
687 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
689 avio_seek(pb, data_ofs, SEEK_SET);
694 AVInputFormat ff_w64_demuxer = {
696 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
697 .priv_data_size = sizeof(WAVDemuxContext),
698 .read_probe = w64_probe,
699 .read_header = w64_read_header,
700 .read_packet = wav_read_packet,
701 .read_seek = wav_read_seek,
702 .flags = AVFMT_GENERIC_INDEX,
703 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
705 #endif /* CONFIG_W64_DEMUXER */