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 if (ff_alloc_extradata(vst->codec, 4)) {
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 if (wav->smv_frames_per_jpeg > 65536) {
370 av_log(s, AV_LOG_ERROR, "too many frames per jpeg\n");
371 return AVERROR_INVALIDDATA;
373 AV_WL32(vst->codec->extradata, wav->smv_frames_per_jpeg);
376 case MKTAG('L', 'I', 'S', 'T'):
378 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
379 return AVERROR_INVALIDDATA;
381 switch (avio_rl32(pb)) {
382 case MKTAG('I', 'N', 'F', 'O'):
383 ff_read_riff_info(s, size - 4);
388 /* seek to next tag unless we know that we'll run into EOF */
389 if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
390 wav_seek_tag(wav, pb, next_tag_ofs, SEEK_SET) < 0) {
397 av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
398 return AVERROR_INVALIDDATA;
401 avio_seek(pb, data_ofs, SEEK_SET);
403 if (!sample_count || av_get_exact_bits_per_sample(st->codec->codec_id) > 0)
404 if ( st->codec->channels
406 && av_get_bits_per_sample(st->codec->codec_id)
407 && wav->data_end <= avio_size(pb))
408 sample_count = (data_size << 3)
410 (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
413 st->duration = sample_count;
415 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
416 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
422 * Find chunk with w64 GUID by skipping over other chunks.
423 * @return the size of the found chunk
425 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
430 while (!url_feof(pb)) {
431 avio_read(pb, guid, 16);
432 size = avio_rl64(pb);
434 return AVERROR_INVALIDDATA;
435 if (!memcmp(guid, guid1, 16))
437 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
442 #define MAX_SIZE 4096
444 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
449 WAVDemuxContext *wav = s->priv_data;
451 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
452 s->streams[0]->codec->codec_tag == 1) {
453 enum AVCodecID codec;
454 ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
456 if (ret > AVPROBE_SCORE_EXTENSION) {
457 s->streams[0]->codec->codec_id = codec;
463 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
464 return ff_spdif_read_packet(s, pkt);
466 if (wav->smv_data_ofs > 0) {
467 int64_t audio_dts, video_dts;
469 audio_dts = (int32_t)s->streams[0]->cur_dts;
470 video_dts = (int32_t)s->streams[1]->cur_dts;
472 if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
473 /*We always return a video frame first to get the pixel format first*/
474 wav->smv_last_stream = wav->smv_given_first ?
475 av_compare_ts(video_dts, s->streams[1]->time_base,
476 audio_dts, s->streams[0]->time_base) > 0 : 0;
477 wav->smv_given_first = 1;
479 wav->smv_last_stream = !wav->smv_last_stream;
480 wav->smv_last_stream |= wav->audio_eof;
481 wav->smv_last_stream &= !wav->smv_eof;
482 if (wav->smv_last_stream) {
483 uint64_t old_pos = avio_tell(s->pb);
484 uint64_t new_pos = wav->smv_data_ofs +
485 wav->smv_block * wav->smv_block_size;
486 if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
490 size = avio_rl24(s->pb);
491 ret = av_get_packet(s->pb, pkt, size);
495 pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt;
497 if (wav->smv_frames_per_jpeg > 0)
498 wav->smv_cur_pt %= wav->smv_frames_per_jpeg;
499 if (!wav->smv_cur_pt)
502 pkt->stream_index = 1;
504 avio_seek(s->pb, old_pos, SEEK_SET);
505 if (ret == AVERROR_EOF) {
515 left = wav->data_end - avio_tell(s->pb);
516 if (wav->ignore_length)
519 if (CONFIG_W64_DEMUXER && wav->w64)
520 left = find_guid(s->pb, ff_w64_guid_data) - 24;
522 left = find_tag(wav, s->pb, MKTAG('d', 'a', 't', 'a'));
525 if (wav->smv_data_ofs > 0 && !wav->smv_eof)
529 wav->data_end = avio_tell(s->pb) + left;
533 if (st->codec->block_align > 1) {
534 if (size < st->codec->block_align)
535 size = st->codec->block_align;
536 size = (size / st->codec->block_align) * st->codec->block_align;
538 size = FFMIN(size, left);
539 ret = av_get_packet(s->pb, pkt, size);
542 pkt->stream_index = 0;
547 static int wav_read_seek(AVFormatContext *s,
548 int stream_index, int64_t timestamp, int flags)
550 WAVDemuxContext *wav = s->priv_data;
554 if (wav->smv_data_ofs > 0) {
555 int64_t smv_timestamp = timestamp;
556 if (stream_index == 0)
557 smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
559 timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
560 if (wav->smv_frames_per_jpeg > 0) {
561 wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
562 wav->smv_cur_pt = smv_timestamp % wav->smv_frames_per_jpeg;
567 switch (st->codec->codec_id) {
568 case AV_CODEC_ID_MP2:
569 case AV_CODEC_ID_MP3:
570 case AV_CODEC_ID_AC3:
571 case AV_CODEC_ID_DTS:
572 /* use generic seeking with dynamically generated indexes */
577 return ff_pcm_read_seek(s, stream_index, timestamp, flags);
580 #define OFFSET(x) offsetof(WAVDemuxContext, x)
581 #define DEC AV_OPT_FLAG_DECODING_PARAM
582 static const AVOption demux_options[] = {
583 { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
587 static const AVClass wav_demuxer_class = {
588 .class_name = "WAV demuxer",
589 .item_name = av_default_item_name,
590 .option = demux_options,
591 .version = LIBAVUTIL_VERSION_INT,
593 AVInputFormat ff_wav_demuxer = {
595 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
596 .priv_data_size = sizeof(WAVDemuxContext),
597 .read_probe = wav_probe,
598 .read_header = wav_read_header,
599 .read_packet = wav_read_packet,
600 .read_seek = wav_read_seek,
601 .flags = AVFMT_GENERIC_INDEX,
602 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
603 .priv_class = &wav_demuxer_class,
605 #endif /* CONFIG_WAV_DEMUXER */
607 #if CONFIG_W64_DEMUXER
608 static int w64_probe(AVProbeData *p)
610 if (p->buf_size <= 40)
612 if (!memcmp(p->buf, ff_w64_guid_riff, 16) &&
613 !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
614 return AVPROBE_SCORE_MAX;
619 static int w64_read_header(AVFormatContext *s)
621 int64_t size, data_ofs = 0;
622 AVIOContext *pb = s->pb;
623 WAVDemuxContext *wav = s->priv_data;
628 avio_read(pb, guid, 16);
629 if (memcmp(guid, ff_w64_guid_riff, 16))
630 return AVERROR_INVALIDDATA;
632 /* riff + wave + fmt + sizes */
633 if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
634 return AVERROR_INVALIDDATA;
636 avio_read(pb, guid, 16);
637 if (memcmp(guid, ff_w64_guid_wave, 16)) {
638 av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
639 return AVERROR_INVALIDDATA;
644 st = avformat_new_stream(s, NULL);
646 return AVERROR(ENOMEM);
648 while (!url_feof(pb)) {
649 if (avio_read(pb, guid, 16) != 16)
651 size = avio_rl64(pb);
652 if (size <= 24 || INT64_MAX - size < avio_tell(pb))
653 return AVERROR_INVALIDDATA;
655 if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
656 /* subtract chunk header size - normal wav file doesn't count it */
657 ret = ff_get_wav_header(pb, st->codec, size - 24);
660 avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
662 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
663 } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
666 samples = avio_rl64(pb);
668 st->duration = samples;
669 } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
670 wav->data_end = avio_tell(pb) + size - 24;
672 data_ofs = avio_tell(pb);
676 avio_skip(pb, size - 24);
677 } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
678 int64_t start, end, cur;
679 uint32_t count, chunk_size, i;
681 start = avio_tell(pb);
682 end = start + FFALIGN(size, INT64_C(8)) - 24;
683 count = avio_rl32(pb);
685 for (i = 0; i < count; i++) {
686 char chunk_key[5], *value;
688 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
692 avio_read(pb, chunk_key, 4);
693 chunk_size = avio_rl32(pb);
695 value = av_mallocz(chunk_size + 1);
697 return AVERROR(ENOMEM);
699 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
700 avio_skip(pb, chunk_size - ret);
702 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
705 avio_skip(pb, end - avio_tell(pb));
707 av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
708 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
715 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
716 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
718 handle_stream_probing(st);
719 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
721 avio_seek(pb, data_ofs, SEEK_SET);
726 AVInputFormat ff_w64_demuxer = {
728 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
729 .priv_data_size = sizeof(WAVDemuxContext),
730 .read_probe = w64_probe,
731 .read_header = w64_read_header,
732 .read_packet = wav_read_packet,
733 .read_seek = wav_read_seek,
734 .flags = AVFMT_GENERIC_INDEX,
735 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
737 #endif /* CONFIG_W64_DEMUXER */