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 /* return the size of the found tag */
65 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
73 size = next_tag(pb, &tag);
76 avio_skip(pb, size + (size & 1));
81 static int wav_probe(AVProbeData *p)
83 /* check file header */
84 if (p->buf_size <= 32)
86 if (!memcmp(p->buf + 8, "WAVE", 4)) {
87 if (!memcmp(p->buf, "RIFF", 4))
88 /* Since the ACT demuxer has a standard WAV header at the top of
89 * its own, the returned score is decreased to avoid a probe
90 * conflict between ACT and WAV. */
91 return AVPROBE_SCORE_MAX - 1;
92 else if (!memcmp(p->buf, "RF64", 4) &&
93 !memcmp(p->buf + 12, "ds64", 4))
94 return AVPROBE_SCORE_MAX;
99 static void handle_stream_probing(AVStream *st)
101 if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
102 st->request_probe = AVPROBE_SCORE_MAX/2;
103 st->probe_packets = FFMIN(st->probe_packets, 4);
107 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
109 AVIOContext *pb = s->pb;
112 /* parse fmt header */
113 *st = avformat_new_stream(s, NULL);
115 return AVERROR(ENOMEM);
117 ret = ff_get_wav_header(pb, (*st)->codec, size);
120 handle_stream_probing(*st);
122 (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
124 avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
129 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
135 av_assert0(length <= sizeof(temp));
136 if ((ret = avio_read(s->pb, temp, length)) < 0)
142 return av_dict_set(&s->metadata, key, temp, 0);
147 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
149 char temp[131], *coding_history;
151 uint64_t time_reference;
152 int64_t umid_parts[8], umid_mask = 0;
154 if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
155 (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
156 (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
157 (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
158 (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
161 time_reference = avio_rl64(s->pb);
162 snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
163 if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
166 /* check if version is >= 1, in which case an UMID may be present */
167 if (avio_rl16(s->pb) >= 1) {
168 for (x = 0; x < 8; x++)
169 umid_mask |= umid_parts[x] = avio_rb64(s->pb);
172 /* the string formatting below is per SMPTE 330M-2004 Annex C */
173 if (umid_parts[4] == 0 && umid_parts[5] == 0 &&
174 umid_parts[6] == 0 && umid_parts[7] == 0) {
176 snprintf(temp, sizeof(temp),
177 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
178 umid_parts[0], umid_parts[1],
179 umid_parts[2], umid_parts[3]);
182 snprintf(temp, sizeof(temp),
183 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
184 "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
185 umid_parts[0], umid_parts[1],
186 umid_parts[2], umid_parts[3],
187 umid_parts[4], umid_parts[5],
188 umid_parts[6], umid_parts[7]);
191 if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
195 avio_skip(s->pb, 190);
197 avio_skip(s->pb, 254);
200 /* CodingHistory present */
203 if (!(coding_history = av_malloc(size + 1)))
204 return AVERROR(ENOMEM);
206 if ((ret = avio_read(s->pb, coding_history, size)) < 0)
209 coding_history[size] = 0;
210 if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
211 AV_DICT_DONT_STRDUP_VAL)) < 0)
218 static const AVMetadataConv wav_metadata_conv[] = {
219 { "description", "comment" },
220 { "originator", "encoded_by" },
221 { "origination_date", "date" },
222 { "origination_time", "creation_time" },
227 static int wav_read_header(AVFormatContext *s)
229 int64_t size, av_uninit(data_size);
230 int64_t sample_count = 0;
233 AVIOContext *pb = s->pb;
235 WAVDemuxContext *wav = s->priv_data;
236 int ret, got_fmt = 0;
237 int64_t next_tag_ofs, data_ofs = -1;
239 wav->smv_data_ofs = -1;
241 /* check RIFF header */
244 rf64 = tag == MKTAG('R', 'F', '6', '4');
245 if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
246 return AVERROR_INVALIDDATA;
247 avio_rl32(pb); /* file size */
249 if (tag != MKTAG('W', 'A', 'V', 'E'))
250 return AVERROR_INVALIDDATA;
253 if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
254 return AVERROR_INVALIDDATA;
255 size = avio_rl32(pb);
257 return AVERROR_INVALIDDATA;
258 avio_rl64(pb); /* RIFF size */
260 data_size = avio_rl64(pb);
261 sample_count = avio_rl64(pb);
263 if (data_size < 0 || sample_count < 0) {
264 av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
265 "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
266 data_size, sample_count);
267 return AVERROR_INVALIDDATA;
269 avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
275 size = next_tag(pb, &tag);
276 next_tag_ofs = avio_tell(pb) + size;
282 case MKTAG('f', 'm', 't', ' '):
283 /* only parse the first 'fmt ' tag found */
284 if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
287 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
291 case MKTAG('d', 'a', 't', 'a'):
293 av_log(s, AV_LOG_ERROR,
294 "found no 'fmt ' tag before the 'data' tag\n");
295 return AVERROR_INVALIDDATA;
299 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
302 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
305 data_ofs = avio_tell(pb);
307 /* don't look for footer metadata if we can't seek or if we don't
308 * know where the data tag ends
310 if (!pb->seekable || (!rf64 && !size))
313 case MKTAG('f', 'a', 'c', 't'):
315 sample_count = avio_rl32(pb);
317 case MKTAG('b', 'e', 'x', 't'):
318 if ((ret = wav_parse_bext_tag(s, size)) < 0)
321 case MKTAG('S','M','V','0'):
323 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
324 return AVERROR_INVALIDDATA;
326 // SMV file, a wav file with video appended.
327 if (size != MKTAG('0','2','0','0')) {
328 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
331 av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
332 vst = avformat_new_stream(s, NULL);
334 return AVERROR(ENOMEM);
337 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
338 vst->codec->codec_id = AV_CODEC_ID_MJPEG;
339 vst->codec->width = avio_rl24(pb);
340 vst->codec->height = avio_rl24(pb);
341 size = avio_rl24(pb);
342 wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
344 wav->smv_block_size = avio_rl24(pb);
345 avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
346 vst->duration = avio_rl24(pb);
349 wav->smv_frames_per_jpeg = avio_rl24(pb);
351 case MKTAG('L', 'I', 'S', 'T'):
353 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
354 return AVERROR_INVALIDDATA;
356 switch (avio_rl32(pb)) {
357 case MKTAG('I', 'N', 'F', 'O'):
358 ff_read_riff_info(s, size - 4);
363 /* skip padding byte */
364 next_tag_ofs += (next_tag_ofs < INT64_MAX && next_tag_ofs & 1);
366 /* seek to next tag unless we know that we'll run into EOF */
367 if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
368 avio_seek(pb, next_tag_ofs, SEEK_SET) < 0) {
375 av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
376 return AVERROR_INVALIDDATA;
379 avio_seek(pb, data_ofs, SEEK_SET);
381 if (!sample_count && st->codec->channels &&
382 av_get_bits_per_sample(st->codec->codec_id) && wav->data_end <= avio_size(pb))
383 sample_count = (data_size << 3) /
384 (st->codec->channels *
385 (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
387 st->duration = sample_count;
389 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
390 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
396 * Find chunk with w64 GUID by skipping over other chunks.
397 * @return the size of the found chunk
399 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
404 while (!url_feof(pb)) {
405 avio_read(pb, guid, 16);
406 size = avio_rl64(pb);
408 return AVERROR_INVALIDDATA;
409 if (!memcmp(guid, guid1, 16))
411 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
416 #define MAX_SIZE 4096
418 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
423 WAVDemuxContext *wav = s->priv_data;
425 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
426 s->streams[0]->codec->codec_tag == 1) {
427 enum AVCodecID codec;
428 ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
430 if (ret > AVPROBE_SCORE_MAX / 2) {
431 s->streams[0]->codec->codec_id = codec;
437 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
438 return ff_spdif_read_packet(s, pkt);
440 if (wav->smv_data_ofs > 0) {
441 int64_t audio_dts, video_dts;
443 audio_dts = s->streams[0]->cur_dts;
444 video_dts = s->streams[1]->cur_dts;
445 if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
446 audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
447 video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
448 wav->smv_last_stream = video_dts >= audio_dts;
450 wav->smv_last_stream = !wav->smv_last_stream;
451 wav->smv_last_stream |= wav->audio_eof;
452 wav->smv_last_stream &= !wav->smv_eof;
453 if (wav->smv_last_stream) {
454 uint64_t old_pos = avio_tell(s->pb);
455 uint64_t new_pos = wav->smv_data_ofs +
456 wav->smv_block * wav->smv_block_size;
457 if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
461 size = avio_rl24(s->pb);
462 ret = av_get_packet(s->pb, pkt, size);
466 pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg;
468 pkt->stream_index = 1;
470 avio_seek(s->pb, old_pos, SEEK_SET);
471 if (ret == AVERROR_EOF) {
481 left = wav->data_end - avio_tell(s->pb);
482 if (wav->ignore_length)
485 if (CONFIG_W64_DEMUXER && wav->w64)
486 left = find_guid(s->pb, ff_w64_guid_data) - 24;
488 left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
491 if (wav->smv_data_ofs > 0 && !wav->smv_eof)
495 wav->data_end = avio_tell(s->pb) + left;
499 if (st->codec->block_align > 1) {
500 if (size < st->codec->block_align)
501 size = st->codec->block_align;
502 size = (size / st->codec->block_align) * st->codec->block_align;
504 size = FFMIN(size, left);
505 ret = av_get_packet(s->pb, pkt, size);
508 pkt->stream_index = 0;
513 static int wav_read_seek(AVFormatContext *s,
514 int stream_index, int64_t timestamp, int flags)
516 WAVDemuxContext *wav = s->priv_data;
520 if (wav->smv_data_ofs > 0) {
521 int64_t smv_timestamp = timestamp;
522 if (stream_index == 0)
523 smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
525 timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
526 wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
530 switch (st->codec->codec_id) {
531 case AV_CODEC_ID_MP2:
532 case AV_CODEC_ID_MP3:
533 case AV_CODEC_ID_AC3:
534 case AV_CODEC_ID_DTS:
535 /* use generic seeking with dynamically generated indexes */
540 return ff_pcm_read_seek(s, stream_index, timestamp, flags);
543 #define OFFSET(x) offsetof(WAVDemuxContext, x)
544 #define DEC AV_OPT_FLAG_DECODING_PARAM
545 static const AVOption demux_options[] = {
546 { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
550 static const AVClass wav_demuxer_class = {
551 .class_name = "WAV demuxer",
552 .item_name = av_default_item_name,
553 .option = demux_options,
554 .version = LIBAVUTIL_VERSION_INT,
556 AVInputFormat ff_wav_demuxer = {
558 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
559 .priv_data_size = sizeof(WAVDemuxContext),
560 .read_probe = wav_probe,
561 .read_header = wav_read_header,
562 .read_packet = wav_read_packet,
563 .read_seek = wav_read_seek,
564 .flags = AVFMT_GENERIC_INDEX,
565 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
566 .priv_class = &wav_demuxer_class,
568 #endif /* CONFIG_WAV_DEMUXER */
570 #if CONFIG_W64_DEMUXER
571 static int w64_probe(AVProbeData *p)
573 if (p->buf_size <= 40)
575 if (!memcmp(p->buf, ff_w64_guid_riff, 16) &&
576 !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
577 return AVPROBE_SCORE_MAX;
582 static int w64_read_header(AVFormatContext *s)
584 int64_t size, data_ofs = 0;
585 AVIOContext *pb = s->pb;
586 WAVDemuxContext *wav = s->priv_data;
591 avio_read(pb, guid, 16);
592 if (memcmp(guid, ff_w64_guid_riff, 16))
593 return AVERROR_INVALIDDATA;
595 /* riff + wave + fmt + sizes */
596 if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
597 return AVERROR_INVALIDDATA;
599 avio_read(pb, guid, 16);
600 if (memcmp(guid, ff_w64_guid_wave, 16)) {
601 av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
602 return AVERROR_INVALIDDATA;
607 st = avformat_new_stream(s, NULL);
609 return AVERROR(ENOMEM);
611 while (!url_feof(pb)) {
612 if (avio_read(pb, guid, 16) != 16)
614 size = avio_rl64(pb);
615 if (size <= 24 || INT64_MAX - size < avio_tell(pb))
616 return AVERROR_INVALIDDATA;
618 if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
619 /* subtract chunk header size - normal wav file doesn't count it */
620 ret = ff_get_wav_header(pb, st->codec, size - 24);
623 avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
625 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
626 } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
629 samples = avio_rl64(pb);
631 st->duration = samples;
632 } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
633 wav->data_end = avio_tell(pb) + size - 24;
635 data_ofs = avio_tell(pb);
639 avio_skip(pb, size - 24);
640 } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
641 int64_t start, end, cur;
642 uint32_t count, chunk_size, i;
644 start = avio_tell(pb);
646 count = avio_rl32(pb);
648 for (i = 0; i < count; i++) {
649 char chunk_key[5], *value;
651 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
655 avio_read(pb, chunk_key, 4);
656 chunk_size = avio_rl32(pb);
658 value = av_mallocz(chunk_size + 1);
660 return AVERROR(ENOMEM);
662 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
663 avio_skip(pb, chunk_size - ret);
665 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
668 avio_skip(pb, end - avio_tell(pb));
670 av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
671 avio_skip(pb, size - 24);
678 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
679 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
681 handle_stream_probing(st);
682 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
684 avio_seek(pb, data_ofs, SEEK_SET);
689 AVInputFormat ff_w64_demuxer = {
691 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
692 .priv_data_size = sizeof(WAVDemuxContext),
693 .read_probe = w64_probe,
694 .read_header = w64_read_header,
695 .read_packet = wav_read_packet,
696 .read_seek = wav_read_seek,
697 .flags = AVFMT_GENERIC_INDEX,
698 .codec_tag = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
700 #endif /* CONFIG_W64_DEMUXER */