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;
57 int unaligned; // e.g. if an odd number of bytes ID3 tag was prepended
60 #if CONFIG_WAV_DEMUXER
62 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
68 /* RIFF chunks are always at even offsets relative to where they start. */
69 static int64_t wav_seek_tag(WAVDemuxContext * wav, AVIOContext *s, int64_t offset, int whence)
71 offset += offset < INT64_MAX && offset + wav->unaligned & 1;
73 return avio_seek(s, offset, whence);
76 /* return the size of the found tag */
77 static int64_t find_tag(WAVDemuxContext * wav, AVIOContext *pb, uint32_t tag1)
85 size = next_tag(pb, &tag);
88 wav_seek_tag(wav, pb, size, SEEK_CUR);
93 static int wav_probe(AVProbeData *p)
95 /* check file header */
96 if (p->buf_size <= 32)
98 if (!memcmp(p->buf + 8, "WAVE", 4)) {
99 if (!memcmp(p->buf, "RIFF", 4))
100 /* Since the ACT demuxer has a standard WAV header at the top of
101 * its own, the returned score is decreased to avoid a probe
102 * conflict between ACT and WAV. */
103 return AVPROBE_SCORE_MAX - 1;
104 else if (!memcmp(p->buf, "RF64", 4) &&
105 !memcmp(p->buf + 12, "ds64", 4))
106 return AVPROBE_SCORE_MAX;
111 static void handle_stream_probing(AVStream *st)
113 if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
114 st->request_probe = AVPROBE_SCORE_EXTENSION;
115 st->probe_packets = FFMIN(st->probe_packets, 4);
119 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
121 AVIOContext *pb = s->pb;
124 /* parse fmt header */
125 *st = avformat_new_stream(s, NULL);
127 return AVERROR(ENOMEM);
129 ret = ff_get_wav_header(pb, (*st)->codec, size);
132 handle_stream_probing(*st);
134 (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
136 avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
141 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
147 av_assert0(length <= sizeof(temp));
148 if ((ret = avio_read(s->pb, temp, length)) < 0)
154 return av_dict_set(&s->metadata, key, temp, 0);
159 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
161 char temp[131], *coding_history;
163 uint64_t time_reference;
164 int64_t umid_parts[8], umid_mask = 0;
166 if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
167 (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
168 (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
169 (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
170 (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
173 time_reference = avio_rl64(s->pb);
174 snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
175 if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
178 /* check if version is >= 1, in which case an UMID may be present */
179 if (avio_rl16(s->pb) >= 1) {
180 for (x = 0; x < 8; x++)
181 umid_mask |= umid_parts[x] = avio_rb64(s->pb);
184 /* the string formatting below is per SMPTE 330M-2004 Annex C */
185 if (umid_parts[4] == 0 && umid_parts[5] == 0 &&
186 umid_parts[6] == 0 && umid_parts[7] == 0) {
188 snprintf(temp, sizeof(temp),
189 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
190 umid_parts[0], umid_parts[1],
191 umid_parts[2], umid_parts[3]);
194 snprintf(temp, sizeof(temp),
195 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
196 "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
197 umid_parts[0], umid_parts[1],
198 umid_parts[2], umid_parts[3],
199 umid_parts[4], umid_parts[5],
200 umid_parts[6], umid_parts[7]);
203 if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
207 avio_skip(s->pb, 190);
209 avio_skip(s->pb, 254);
212 /* CodingHistory present */
215 if (!(coding_history = av_malloc(size + 1)))
216 return AVERROR(ENOMEM);
218 if ((ret = avio_read(s->pb, coding_history, size)) < 0)
221 coding_history[size] = 0;
222 if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
223 AV_DICT_DONT_STRDUP_VAL)) < 0)
230 static const AVMetadataConv wav_metadata_conv[] = {
231 { "description", "comment" },
232 { "originator", "encoded_by" },
233 { "origination_date", "date" },
234 { "origination_time", "creation_time" },
239 static int wav_read_header(AVFormatContext *s)
241 int64_t size, av_uninit(data_size);
242 int64_t sample_count = 0;
245 AVIOContext *pb = s->pb;
247 WAVDemuxContext *wav = s->priv_data;
248 int ret, got_fmt = 0;
249 int64_t next_tag_ofs, data_ofs = -1;
251 wav->unaligned = avio_tell(s->pb) & 1;
253 wav->smv_data_ofs = -1;
255 /* check RIFF header */
258 rf64 = tag == MKTAG('R', 'F', '6', '4');
259 if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
260 return AVERROR_INVALIDDATA;
261 avio_rl32(pb); /* file size */
263 if (tag != MKTAG('W', 'A', 'V', 'E'))
264 return AVERROR_INVALIDDATA;
267 if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
268 return AVERROR_INVALIDDATA;
269 size = avio_rl32(pb);
271 return AVERROR_INVALIDDATA;
272 avio_rl64(pb); /* RIFF size */
274 data_size = avio_rl64(pb);
275 sample_count = avio_rl64(pb);
277 if (data_size < 0 || sample_count < 0) {
278 av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
279 "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
280 data_size, sample_count);
281 return AVERROR_INVALIDDATA;
283 avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
289 size = next_tag(pb, &tag);
290 next_tag_ofs = avio_tell(pb) + size;
296 case MKTAG('f', 'm', 't', ' '):
297 /* only parse the first 'fmt ' tag found */
298 if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
301 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
305 case MKTAG('d', 'a', 't', 'a'):
307 av_log(s, AV_LOG_ERROR,
308 "found no 'fmt ' tag before the 'data' tag\n");
309 return AVERROR_INVALIDDATA;
313 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
316 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
319 data_ofs = avio_tell(pb);
321 /* don't look for footer metadata if we can't seek or if we don't
322 * know where the data tag ends
324 if (!pb->seekable || (!rf64 && !size))
327 case MKTAG('f', 'a', 'c', 't'):
329 sample_count = avio_rl32(pb);
331 case MKTAG('b', 'e', 'x', 't'):
332 if ((ret = wav_parse_bext_tag(s, size)) < 0)
335 case MKTAG('S','M','V','0'):
337 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
338 return AVERROR_INVALIDDATA;
340 // SMV file, a wav file with video appended.
341 if (size != MKTAG('0','2','0','0')) {
342 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
345 av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
346 wav->smv_given_first = 0;
347 vst = avformat_new_stream(s, NULL);
349 return AVERROR(ENOMEM);
352 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
353 vst->codec->codec_id = AV_CODEC_ID_SMVJPEG;
354 vst->codec->width = avio_rl24(pb);
355 vst->codec->height = avio_rl24(pb);
356 vst->codec->extradata_size = 4;
357 vst->codec->extradata = av_malloc(vst->codec->extradata_size +
358 FF_INPUT_BUFFER_PADDING_SIZE);
359 if (!vst->codec->extradata) {
360 av_log(s, AV_LOG_ERROR, "Could not allocate extradata.\n");
361 return AVERROR(ENOMEM);
363 size = avio_rl24(pb);
364 wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
366 wav->smv_block_size = avio_rl24(pb);
367 avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
368 vst->duration = avio_rl24(pb);
371 wav->smv_frames_per_jpeg = avio_rl24(pb);
372 if (wav->smv_frames_per_jpeg > 65536) {
373 av_log(s, AV_LOG_ERROR, "too many frames per jpeg\n");
374 return AVERROR_INVALIDDATA;
376 AV_WL32(vst->codec->extradata, wav->smv_frames_per_jpeg);
379 case MKTAG('L', 'I', 'S', 'T'):
381 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
382 return AVERROR_INVALIDDATA;
384 switch (avio_rl32(pb)) {
385 case MKTAG('I', 'N', 'F', 'O'):
386 ff_read_riff_info(s, size - 4);
391 /* seek to next tag unless we know that we'll run into EOF */
392 if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
393 wav_seek_tag(wav, pb, next_tag_ofs, SEEK_SET) < 0) {
400 av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
401 return AVERROR_INVALIDDATA;
404 avio_seek(pb, data_ofs, SEEK_SET);
406 if (!sample_count || av_get_exact_bits_per_sample(st->codec->codec_id) > 0)
407 if ( st->codec->channels
409 && av_get_bits_per_sample(st->codec->codec_id)
410 && wav->data_end <= avio_size(pb))
411 sample_count = (data_size << 3)
413 (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
416 st->duration = sample_count;
418 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
419 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
425 * Find chunk with w64 GUID by skipping over other chunks.
426 * @return the size of the found chunk
428 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
433 while (!url_feof(pb)) {
434 avio_read(pb, guid, 16);
435 size = avio_rl64(pb);
437 return AVERROR_INVALIDDATA;
438 if (!memcmp(guid, guid1, 16))
440 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
445 #define MAX_SIZE 4096
447 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
452 WAVDemuxContext *wav = s->priv_data;
454 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
455 s->streams[0]->codec->codec_tag == 1) {
456 enum AVCodecID codec;
457 ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
459 if (ret > AVPROBE_SCORE_EXTENSION) {
460 s->streams[0]->codec->codec_id = codec;
466 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
467 return ff_spdif_read_packet(s, pkt);
469 if (wav->smv_data_ofs > 0) {
470 int64_t audio_dts, video_dts;
472 audio_dts = s->streams[0]->cur_dts;
473 video_dts = s->streams[1]->cur_dts;
475 if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
476 /*We always return a video frame first to get the pixel format first*/
477 wav->smv_last_stream = wav->smv_given_first ?
478 av_compare_ts(video_dts, s->streams[1]->time_base,
479 audio_dts, s->streams[0]->time_base) > 0 : 0;
480 wav->smv_given_first = 1;
482 wav->smv_last_stream = !wav->smv_last_stream;
483 wav->smv_last_stream |= wav->audio_eof;
484 wav->smv_last_stream &= !wav->smv_eof;
485 if (wav->smv_last_stream) {
486 uint64_t old_pos = avio_tell(s->pb);
487 uint64_t new_pos = wav->smv_data_ofs +
488 wav->smv_block * wav->smv_block_size;
489 if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
493 size = avio_rl24(s->pb);
494 ret = av_get_packet(s->pb, pkt, size);
498 pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt;
500 if (wav->smv_frames_per_jpeg > 0)
501 wav->smv_cur_pt %= wav->smv_frames_per_jpeg;
502 if (!wav->smv_cur_pt)
505 pkt->stream_index = 1;
507 avio_seek(s->pb, old_pos, SEEK_SET);
508 if (ret == AVERROR_EOF) {
518 left = wav->data_end - avio_tell(s->pb);
519 if (wav->ignore_length)
522 if (CONFIG_W64_DEMUXER && wav->w64)
523 left = find_guid(s->pb, ff_w64_guid_data) - 24;
525 left = find_tag(wav, s->pb, MKTAG('d', 'a', 't', 'a'));
528 if (wav->smv_data_ofs > 0 && !wav->smv_eof)
532 wav->data_end = avio_tell(s->pb) + left;
536 if (st->codec->block_align > 1) {
537 if (size < st->codec->block_align)
538 size = st->codec->block_align;
539 size = (size / st->codec->block_align) * st->codec->block_align;
541 size = FFMIN(size, left);
542 ret = av_get_packet(s->pb, pkt, size);
545 pkt->stream_index = 0;
550 static int wav_read_seek(AVFormatContext *s,
551 int stream_index, int64_t timestamp, int flags)
553 WAVDemuxContext *wav = s->priv_data;
557 if (wav->smv_data_ofs > 0) {
558 int64_t smv_timestamp = timestamp;
559 if (stream_index == 0)
560 smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
562 timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
563 if (wav->smv_frames_per_jpeg > 0) {
564 wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
565 wav->smv_cur_pt = smv_timestamp % wav->smv_frames_per_jpeg;
570 switch (st->codec->codec_id) {
571 case AV_CODEC_ID_MP2:
572 case AV_CODEC_ID_MP3:
573 case AV_CODEC_ID_AC3:
574 case AV_CODEC_ID_DTS:
575 /* use generic seeking with dynamically generated indexes */
580 return ff_pcm_read_seek(s, stream_index, timestamp, flags);
583 #define OFFSET(x) offsetof(WAVDemuxContext, x)
584 #define DEC AV_OPT_FLAG_DECODING_PARAM
585 static const AVOption demux_options[] = {
586 { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
590 static const AVClass wav_demuxer_class = {
591 .class_name = "WAV demuxer",
592 .item_name = av_default_item_name,
593 .option = demux_options,
594 .version = LIBAVUTIL_VERSION_INT,
596 AVInputFormat ff_wav_demuxer = {
598 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
599 .priv_data_size = sizeof(WAVDemuxContext),
600 .read_probe = wav_probe,
601 .read_header = wav_read_header,
602 .read_packet = wav_read_packet,
603 .read_seek = wav_read_seek,
604 .flags = AVFMT_GENERIC_INDEX,
605 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
606 .priv_class = &wav_demuxer_class,
608 #endif /* CONFIG_WAV_DEMUXER */
610 #if CONFIG_W64_DEMUXER
611 static int w64_probe(AVProbeData *p)
613 if (p->buf_size <= 40)
615 if (!memcmp(p->buf, ff_w64_guid_riff, 16) &&
616 !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
617 return AVPROBE_SCORE_MAX;
622 static int w64_read_header(AVFormatContext *s)
624 int64_t size, data_ofs = 0;
625 AVIOContext *pb = s->pb;
626 WAVDemuxContext *wav = s->priv_data;
631 avio_read(pb, guid, 16);
632 if (memcmp(guid, ff_w64_guid_riff, 16))
633 return AVERROR_INVALIDDATA;
635 /* riff + wave + fmt + sizes */
636 if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
637 return AVERROR_INVALIDDATA;
639 avio_read(pb, guid, 16);
640 if (memcmp(guid, ff_w64_guid_wave, 16)) {
641 av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
642 return AVERROR_INVALIDDATA;
647 st = avformat_new_stream(s, NULL);
649 return AVERROR(ENOMEM);
651 while (!url_feof(pb)) {
652 if (avio_read(pb, guid, 16) != 16)
654 size = avio_rl64(pb);
655 if (size <= 24 || INT64_MAX - size < avio_tell(pb))
656 return AVERROR_INVALIDDATA;
658 if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
659 /* subtract chunk header size - normal wav file doesn't count it */
660 ret = ff_get_wav_header(pb, st->codec, size - 24);
663 avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
665 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
666 } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
669 samples = avio_rl64(pb);
671 st->duration = samples;
672 } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
673 wav->data_end = avio_tell(pb) + size - 24;
675 data_ofs = avio_tell(pb);
679 avio_skip(pb, size - 24);
680 } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
681 int64_t start, end, cur;
682 uint32_t count, chunk_size, i;
684 start = avio_tell(pb);
685 end = start + FFALIGN(size, INT64_C(8)) - 24;
686 count = avio_rl32(pb);
688 for (i = 0; i < count; i++) {
689 char chunk_key[5], *value;
691 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
695 avio_read(pb, chunk_key, 4);
696 chunk_size = avio_rl32(pb);
698 value = av_mallocz(chunk_size + 1);
700 return AVERROR(ENOMEM);
702 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
703 avio_skip(pb, chunk_size - ret);
705 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
708 avio_skip(pb, end - avio_tell(pb));
710 av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
711 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
718 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
719 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
721 handle_stream_probing(st);
722 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
724 avio_seek(pb, data_ofs, SEEK_SET);
729 AVInputFormat ff_w64_demuxer = {
731 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
732 .priv_data_size = sizeof(WAVDemuxContext),
733 .read_probe = w64_probe,
734 .read_header = w64_read_header,
735 .read_packet = wav_read_packet,
736 .read_seek = wav_read_seek,
737 .flags = AVFMT_GENERIC_INDEX,
738 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
740 #endif /* CONFIG_W64_DEMUXER */