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;
57 #if CONFIG_WAV_DEMUXER
59 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
65 /* return the size of the found tag */
66 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
74 size = next_tag(pb, &tag);
82 static int wav_probe(AVProbeData *p)
84 /* check file header */
85 if (p->buf_size <= 32)
87 if (!memcmp(p->buf + 8, "WAVE", 4)) {
88 if (!memcmp(p->buf, "RIFF", 4))
90 Since ACT demuxer has standard WAV header at top of it's own,
91 returning score is decreased to avoid probe conflict
94 return AVPROBE_SCORE_MAX - 1;
95 else if (!memcmp(p->buf, "RF64", 4) &&
96 !memcmp(p->buf + 12, "ds64", 4))
97 return AVPROBE_SCORE_MAX;
102 static void handle_stream_probing(AVStream *st)
104 if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
105 st->request_probe = AVPROBE_SCORE_MAX/2;
106 st->probe_packets = FFMIN(st->probe_packets, 4);
110 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
112 AVIOContext *pb = s->pb;
115 /* parse fmt header */
116 *st = avformat_new_stream(s, NULL);
118 return AVERROR(ENOMEM);
120 ret = ff_get_wav_header(pb, (*st)->codec, size);
123 handle_stream_probing(*st);
125 (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
127 avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
132 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
138 av_assert0(length <= sizeof(temp));
139 if ((ret = avio_read(s->pb, temp, length)) < 0)
145 return av_dict_set(&s->metadata, key, temp, 0);
150 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
152 char temp[131], *coding_history;
154 uint64_t time_reference;
155 int64_t umid_parts[8], umid_mask = 0;
157 if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
158 (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
159 (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
160 (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
161 (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
164 time_reference = avio_rl64(s->pb);
165 snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
166 if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
169 /* check if version is >= 1, in which case an UMID may be present */
170 if (avio_rl16(s->pb) >= 1) {
171 for (x = 0; x < 8; x++)
172 umid_mask |= umid_parts[x] = avio_rb64(s->pb);
175 /* the string formatting below is per SMPTE 330M-2004 Annex C */
176 if (umid_parts[4] == 0 && umid_parts[5] == 0 && umid_parts[6] == 0 && umid_parts[7] == 0) {
178 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
179 umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3]);
182 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
183 "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
184 umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3],
185 umid_parts[4], umid_parts[5], umid_parts[6], umid_parts[7]);
188 if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
192 avio_skip(s->pb, 190);
194 avio_skip(s->pb, 254);
197 /* CodingHistory present */
200 if (!(coding_history = av_malloc(size+1)))
201 return AVERROR(ENOMEM);
203 if ((ret = avio_read(s->pb, coding_history, size)) < 0)
206 coding_history[size] = 0;
207 if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
208 AV_DICT_DONT_STRDUP_VAL)) < 0)
215 static const AVMetadataConv wav_metadata_conv[] = {
216 {"description", "comment" },
217 {"originator", "encoded_by" },
218 {"origination_date", "date" },
219 {"origination_time", "creation_time"},
224 static int wav_read_header(AVFormatContext *s)
226 int64_t size, av_uninit(data_size);
227 int64_t sample_count=0;
230 AVIOContext *pb = s->pb;
232 WAVDemuxContext *wav = s->priv_data;
233 int ret, got_fmt = 0;
234 int64_t next_tag_ofs, data_ofs = -1;
236 wav->smv_data_ofs = -1;
238 /* check RIFF header */
241 rf64 = tag == MKTAG('R', 'F', '6', '4');
242 if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
244 avio_rl32(pb); /* file size */
246 if (tag != MKTAG('W', 'A', 'V', 'E'))
250 if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
252 size = avio_rl32(pb);
255 avio_rl64(pb); /* RIFF size */
256 data_size = avio_rl64(pb);
257 sample_count = avio_rl64(pb);
258 if (data_size < 0 || sample_count < 0) {
259 av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
260 "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
261 data_size, sample_count);
262 return AVERROR_INVALIDDATA;
264 avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
270 size = next_tag(pb, &tag);
271 next_tag_ofs = avio_tell(pb) + size;
277 case MKTAG('f', 'm', 't', ' '):
278 /* only parse the first 'fmt ' tag found */
279 if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
282 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
286 case MKTAG('d', 'a', 't', 'a'):
288 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");
289 return AVERROR_INVALIDDATA;
293 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
296 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
299 data_ofs = avio_tell(pb);
301 /* don't look for footer metadata if we can't seek or if we don't
302 * know where the data tag ends
304 if (!pb->seekable || (!rf64 && !size))
307 case MKTAG('f','a','c','t'):
309 sample_count = avio_rl32(pb);
311 case MKTAG('b','e','x','t'):
312 if ((ret = wav_parse_bext_tag(s, size)) < 0)
315 case MKTAG('S','M','V','0'):
317 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
318 return AVERROR_INVALIDDATA;
320 // SMV file, a wav file with video appended.
321 if (size != MKTAG('0','2','0','0')) {
322 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
325 av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
326 vst = avformat_new_stream(s, NULL);
328 return AVERROR(ENOMEM);
331 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
332 vst->codec->codec_id = AV_CODEC_ID_MJPEG;
333 vst->codec->width = avio_rl24(pb);
334 vst->codec->height = avio_rl24(pb);
335 size = avio_rl24(pb);
336 wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
338 wav->smv_block_size = avio_rl24(pb);
339 avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
340 vst->duration = avio_rl24(pb);
343 wav->smv_frames_per_jpeg = avio_rl24(pb);
345 case MKTAG('L', 'I', 'S', 'T'):
347 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
348 return AVERROR_INVALIDDATA;
350 switch (avio_rl32(pb)) {
351 case MKTAG('I', 'N', 'F', 'O'):
352 ff_read_riff_info(s, size - 4);
357 /* seek to next tag unless we know that we'll run into EOF */
358 if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
359 avio_seek(pb, next_tag_ofs, SEEK_SET) < 0) {
365 av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
366 return AVERROR_INVALIDDATA;
369 avio_seek(pb, data_ofs, SEEK_SET);
371 if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id) && wav->data_end <= avio_size(pb))
372 sample_count = (data_size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
374 st->duration = sample_count;
376 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
377 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
382 /** Find chunk with w64 GUID by skipping over other chunks
383 * @return the size of the found chunk
385 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
390 while (!url_feof(pb)) {
391 avio_read(pb, guid, 16);
392 size = avio_rl64(pb);
395 if (!memcmp(guid, guid1, 16))
397 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
402 #define MAX_SIZE 4096
404 static int wav_read_packet(AVFormatContext *s,
410 WAVDemuxContext *wav = s->priv_data;
412 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
413 s->streams[0]->codec->codec_tag == 1) {
414 enum AVCodecID codec;
415 ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
417 if (ret > AVPROBE_SCORE_MAX / 2) {
418 s->streams[0]->codec->codec_id = codec;
424 if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
425 return ff_spdif_read_packet(s, pkt);
427 if (wav->smv_data_ofs > 0) {
428 int64_t audio_dts, video_dts;
430 audio_dts = s->streams[0]->cur_dts;
431 video_dts = s->streams[1]->cur_dts;
432 if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
433 audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
434 video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
435 wav->smv_last_stream = video_dts >= audio_dts;
437 wav->smv_last_stream = !wav->smv_last_stream;
438 wav->smv_last_stream |= wav->audio_eof;
439 wav->smv_last_stream &= !wav->smv_eof;
440 if (wav->smv_last_stream) {
441 uint64_t old_pos = avio_tell(s->pb);
442 uint64_t new_pos = wav->smv_data_ofs +
443 wav->smv_block * wav->smv_block_size;
444 if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
448 size = avio_rl24(s->pb);
449 ret = av_get_packet(s->pb, pkt, size);
453 pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg;
455 pkt->stream_index = 1;
457 avio_seek(s->pb, old_pos, SEEK_SET);
458 if (ret == AVERROR_EOF) {
468 left = wav->data_end - avio_tell(s->pb);
469 if (wav->ignore_length)
472 if (CONFIG_W64_DEMUXER && wav->w64)
473 left = find_guid(s->pb, ff_w64_guid_data) - 24;
475 left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
478 if (wav->smv_data_ofs > 0 && !wav->smv_eof)
482 wav->data_end= avio_tell(s->pb) + left;
486 if (st->codec->block_align > 1) {
487 if (size < st->codec->block_align)
488 size = st->codec->block_align;
489 size = (size / st->codec->block_align) * st->codec->block_align;
491 size = FFMIN(size, left);
492 ret = av_get_packet(s->pb, pkt, size);
495 pkt->stream_index = 0;
500 static int wav_read_seek(AVFormatContext *s,
501 int stream_index, int64_t timestamp, int flags)
503 WAVDemuxContext *wav = s->priv_data;
507 if (wav->smv_data_ofs > 0) {
508 int64_t smv_timestamp = timestamp;
509 if (stream_index == 0)
510 smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
512 timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
513 wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
517 switch (st->codec->codec_id) {
518 case AV_CODEC_ID_MP2:
519 case AV_CODEC_ID_MP3:
520 case AV_CODEC_ID_AC3:
521 case AV_CODEC_ID_DTS:
522 /* use generic seeking with dynamically generated indexes */
527 return ff_pcm_read_seek(s, stream_index, timestamp, flags);
530 #define OFFSET(x) offsetof(WAVDemuxContext, x)
531 #define DEC AV_OPT_FLAG_DECODING_PARAM
532 static const AVOption demux_options[] = {
533 { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
537 static const AVClass wav_demuxer_class = {
538 .class_name = "WAV demuxer",
539 .item_name = av_default_item_name,
540 .option = demux_options,
541 .version = LIBAVUTIL_VERSION_INT,
543 AVInputFormat ff_wav_demuxer = {
545 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
546 .priv_data_size = sizeof(WAVDemuxContext),
547 .read_probe = wav_probe,
548 .read_header = wav_read_header,
549 .read_packet = wav_read_packet,
550 .read_seek = wav_read_seek,
551 .flags = AVFMT_GENERIC_INDEX,
552 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
553 .priv_class = &wav_demuxer_class,
555 #endif /* CONFIG_WAV_DEMUXER */
558 #if CONFIG_W64_DEMUXER
559 static int w64_probe(AVProbeData *p)
561 if (p->buf_size <= 40)
563 if (!memcmp(p->buf, ff_w64_guid_riff, 16) &&
564 !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
565 return AVPROBE_SCORE_MAX;
570 static int w64_read_header(AVFormatContext *s)
572 int64_t size, data_ofs = 0;
573 AVIOContext *pb = s->pb;
574 WAVDemuxContext *wav = s->priv_data;
579 avio_read(pb, guid, 16);
580 if (memcmp(guid, ff_w64_guid_riff, 16))
583 if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
586 avio_read(pb, guid, 16);
587 if (memcmp(guid, ff_w64_guid_wave, 16)) {
588 av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
594 st = avformat_new_stream(s, NULL);
596 return AVERROR(ENOMEM);
598 while (!url_feof(pb)) {
599 if (avio_read(pb, guid, 16) != 16)
601 size = avio_rl64(pb);
602 if (size <= 24 || INT64_MAX - size < avio_tell(pb))
603 return AVERROR_INVALIDDATA;
605 if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
606 /* subtract chunk header size - normal wav file doesn't count it */
607 ret = ff_get_wav_header(pb, st->codec, size - 24);
610 avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
612 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
613 } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
616 samples = avio_rl64(pb);
618 st->duration = samples;
619 } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
620 wav->data_end = avio_tell(pb) + size - 24;
622 data_ofs = avio_tell(pb);
626 avio_skip(pb, size - 24);
627 } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
628 int64_t start, end, cur;
629 uint32_t count, chunk_size, i;
631 start = avio_tell(pb);
633 count = avio_rl32(pb);
635 for (i = 0; i < count; i++) {
636 char chunk_key[5], *value;
638 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
642 avio_read(pb, chunk_key, 4);
643 chunk_size = avio_rl32(pb);
645 value = av_mallocz(chunk_size + 1);
647 return AVERROR(ENOMEM);
649 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
650 avio_skip(pb, chunk_size - ret);
652 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
655 avio_skip(pb, end - avio_tell(pb));
657 av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
658 avio_skip(pb, size - 24);
665 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
666 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
668 handle_stream_probing(st);
669 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
671 avio_seek(pb, data_ofs, SEEK_SET);
676 AVInputFormat ff_w64_demuxer = {
678 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
679 .priv_data_size = sizeof(WAVDemuxContext),
680 .read_probe = w64_probe,
681 .read_header = w64_read_header,
682 .read_packet = wav_read_packet,
683 .read_seek = wav_read_seek,
684 .flags = AVFMT_GENERIC_INDEX,
685 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
687 #endif /* CONFIG_W64_DEMUXER */