2 * WAV muxer and demuxer
3 * Copyright (c) 2001, 2002 Fabrice Bellard
7 * Copyright (c) 2009 Daniel Verkamp
9 * This file is part of Libav.
11 * Libav 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 * Libav 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 Libav; 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"
51 static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
53 AVDictionaryEntry *tag;
56 if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
57 len = strlen(tag->value);
58 len = FFMIN(len, maxlen);
59 avio_write(s->pb, tag->value, len);
62 ffio_fill(s->pb, 0, maxlen - len);
65 static void bwf_write_bext_chunk(AVFormatContext *s)
67 AVDictionaryEntry *tmp_tag;
68 uint64_t time_reference = 0;
69 int64_t bext = ff_start_tag(s->pb, "bext");
71 bwf_write_bext_string(s, "description", 256);
72 bwf_write_bext_string(s, "originator", 32);
73 bwf_write_bext_string(s, "originator_reference", 32);
74 bwf_write_bext_string(s, "origination_date", 10);
75 bwf_write_bext_string(s, "origination_time", 8);
77 if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
78 time_reference = strtoll(tmp_tag->value, NULL, 10);
79 avio_wl64(s->pb, time_reference);
80 avio_wl16(s->pb, 1); // set version to 1
82 if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {
83 unsigned char umidpart_str[17] = {0};
86 int len = strlen(tmp_tag->value+2);
88 for (i = 0; i < len/16; i++) {
89 memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
90 umidpart = strtoll(umidpart_str, NULL, 16);
91 avio_wb64(s->pb, umidpart);
93 ffio_fill(s->pb, 0, 64 - i*8);
95 ffio_fill(s->pb, 0, 64); // zero UMID
97 ffio_fill(s->pb, 0, 190); // Reserved
99 if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
100 avio_put_str(s->pb, tmp_tag->value);
102 ff_end_tag(s->pb, bext);
105 static int wav_write_header(AVFormatContext *s)
107 WAVContext *wav = s->priv_data;
108 AVIOContext *pb = s->pb;
111 ffio_wfourcc(pb, "RIFF");
112 avio_wl32(pb, 0); /* file length */
113 ffio_wfourcc(pb, "WAVE");
116 fmt = ff_start_tag(pb, "fmt ");
117 if (ff_put_wav_header(pb, s->streams[0]->codec) < 0) {
118 av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
119 s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
124 if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
125 && s->pb->seekable) {
126 fact = ff_start_tag(pb, "fact");
128 ff_end_tag(pb, fact);
132 bwf_write_bext_chunk(s);
134 avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
135 wav->maxpts = wav->last_duration = 0;
136 wav->minpts = INT64_MAX;
139 wav->data = ff_start_tag(pb, "data");
146 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
148 AVIOContext *pb = s->pb;
149 WAVContext *wav = s->priv_data;
150 avio_write(pb, pkt->data, pkt->size);
151 if(pkt->pts != AV_NOPTS_VALUE) {
152 wav->minpts = FFMIN(wav->minpts, pkt->pts);
153 wav->maxpts = FFMAX(wav->maxpts, pkt->pts);
154 wav->last_duration = pkt->duration;
156 av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
160 static int wav_write_trailer(AVFormatContext *s)
162 AVIOContext *pb = s->pb;
163 WAVContext *wav = s->priv_data;
168 if (s->pb->seekable) {
169 ff_end_tag(pb, wav->data);
171 /* update file size */
172 file_size = avio_tell(pb);
173 avio_seek(pb, 4, SEEK_SET);
174 avio_wl32(pb, (uint32_t)(file_size - 8));
175 avio_seek(pb, file_size, SEEK_SET);
179 if(s->streams[0]->codec->codec_tag != 0x01) {
180 /* Update num_samps in fact chunk */
181 int number_of_samples;
182 number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
183 s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
184 s->streams[0]->time_base.den);
185 avio_seek(pb, wav->data-12, SEEK_SET);
186 avio_wl32(pb, number_of_samples);
187 avio_seek(pb, file_size, SEEK_SET);
194 #define OFFSET(x) offsetof(WAVContext, x)
195 #define ENC AV_OPT_FLAG_ENCODING_PARAM
196 static const AVOption options[] = {
197 { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_INT, { 0 }, 0, 1, ENC },
201 static const AVClass wav_muxer_class = {
202 .class_name = "WAV muxer",
203 .item_name = av_default_item_name,
205 .version = LIBAVUTIL_VERSION_INT,
208 AVOutputFormat ff_wav_muxer = {
210 .long_name = NULL_IF_CONFIG_SMALL("WAV format"),
211 .mime_type = "audio/x-wav",
213 .priv_data_size = sizeof(WAVContext),
214 .audio_codec = CODEC_ID_PCM_S16LE,
215 .video_codec = CODEC_ID_NONE,
216 .write_header = wav_write_header,
217 .write_packet = wav_write_packet,
218 .write_trailer = wav_write_trailer,
219 .codec_tag= (const AVCodecTag* const []){ff_codec_wav_tags, 0},
220 .priv_class = &wav_muxer_class,
222 #endif /* CONFIG_WAV_MUXER */
225 #if CONFIG_WAV_DEMUXER
227 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
229 *tag = avio_rl32(pb);
230 return avio_rl32(pb);
233 /* return the size of the found tag */
234 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
242 size = next_tag(pb, &tag);
250 static int wav_probe(AVProbeData *p)
252 /* check file header */
253 if (p->buf_size <= 32)
255 if (!memcmp(p->buf + 8, "WAVE", 4)) {
256 if (!memcmp(p->buf, "RIFF", 4))
258 Since ACT demuxer has standard WAV header at top of it's own,
259 returning score is decreased to avoid probe conflict
262 return AVPROBE_SCORE_MAX - 1;
263 else if (!memcmp(p->buf, "RF64", 4) &&
264 !memcmp(p->buf + 12, "ds64", 4))
265 return AVPROBE_SCORE_MAX;
270 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
272 AVIOContext *pb = s->pb;
275 /* parse fmt header */
276 *st = avformat_new_stream(s, NULL);
278 return AVERROR(ENOMEM);
280 ret = ff_get_wav_header(pb, (*st)->codec, size);
283 (*st)->need_parsing = AVSTREAM_PARSE_FULL;
285 avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
290 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
296 av_assert0(length <= sizeof(temp));
297 if ((ret = avio_read(s->pb, temp, length)) < 0)
303 return av_dict_set(&s->metadata, key, temp, 0);
308 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
310 char temp[131], *coding_history;
312 uint64_t time_reference;
313 int64_t umid_parts[8], umid_mask = 0;
315 if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
316 (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
317 (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
318 (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
319 (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
322 time_reference = avio_rl64(s->pb);
323 snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
324 if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
327 /* check if version is >= 1, in which case an UMID may be present */
328 if (avio_rl16(s->pb) >= 1) {
329 for (x = 0; x < 8; x++)
330 umid_mask |= umid_parts[x] = avio_rb64(s->pb);
333 /* the string formatting below is per SMPTE 330M-2004 Annex C */
334 if (umid_parts[4] == 0 && umid_parts[5] == 0 && umid_parts[6] == 0 && umid_parts[7] == 0) {
336 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
337 umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3]);
340 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
341 "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
342 umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3],
343 umid_parts[4], umid_parts[5], umid_parts[6], umid_parts[7]);
346 if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
350 avio_skip(s->pb, 190);
352 avio_skip(s->pb, 254);
355 /* CodingHistory present */
358 if (!(coding_history = av_malloc(size+1)))
359 return AVERROR(ENOMEM);
361 if ((ret = avio_read(s->pb, coding_history, size)) < 0)
364 coding_history[size] = 0;
365 if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
366 AV_DICT_DONT_STRDUP_VAL)) < 0)
373 static const AVMetadataConv wav_metadata_conv[] = {
374 {"description", "comment" },
375 {"originator", "encoded_by" },
376 {"origination_date", "date" },
377 {"origination_time", "creation_time"},
382 static int wav_read_header(AVFormatContext *s)
384 int64_t size, av_uninit(data_size);
385 int64_t sample_count=0;
387 uint32_t tag, list_type;
388 AVIOContext *pb = s->pb;
390 WAVContext *wav = s->priv_data;
391 int ret, got_fmt = 0;
392 int64_t next_tag_ofs, data_ofs = -1;
394 /* check RIFF header */
397 rf64 = tag == MKTAG('R', 'F', '6', '4');
398 if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
400 avio_rl32(pb); /* file size */
402 if (tag != MKTAG('W', 'A', 'V', 'E'))
406 if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
408 size = avio_rl32(pb);
411 avio_rl64(pb); /* RIFF size */
412 data_size = avio_rl64(pb);
413 sample_count = avio_rl64(pb);
414 if (data_size < 0 || sample_count < 0) {
415 av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
416 "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
417 data_size, sample_count);
418 return AVERROR_INVALIDDATA;
420 avio_skip(pb, size - 16); /* skip rest of ds64 chunk */
424 size = next_tag(pb, &tag);
425 next_tag_ofs = avio_tell(pb) + size;
431 case MKTAG('f', 'm', 't', ' '):
432 /* only parse the first 'fmt ' tag found */
433 if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st) < 0)) {
436 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
440 case MKTAG('d', 'a', 't', 'a'):
442 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");
443 return AVERROR_INVALIDDATA;
447 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
450 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
453 data_ofs = avio_tell(pb);
455 /* don't look for footer metadata if we can't seek or if we don't
456 * know where the data tag ends
458 if (!pb->seekable || (!rf64 && !size))
461 case MKTAG('f','a','c','t'):
463 sample_count = avio_rl32(pb);
465 case MKTAG('b','e','x','t'):
466 if ((ret = wav_parse_bext_tag(s, size)) < 0)
469 case MKTAG('L', 'I', 'S', 'T'):
470 list_type = avio_rl32(pb);
472 av_log(s, AV_LOG_ERROR, "too short LIST");
473 return AVERROR_INVALIDDATA;
476 case MKTAG('I', 'N', 'F', 'O'):
477 if ((ret = ff_read_riff_info(s, size - 4)) < 0)
483 /* seek to next tag unless we know that we'll run into EOF */
484 if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
485 avio_seek(pb, next_tag_ofs, SEEK_SET) < 0) {
491 av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
492 return AVERROR_INVALIDDATA;
495 avio_seek(pb, data_ofs, SEEK_SET);
497 if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
498 sample_count = (data_size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
500 st->duration = sample_count;
502 ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
503 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
508 /** Find chunk with w64 GUID by skipping over other chunks
509 * @return the size of the found chunk
511 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
516 while (!pb->eof_reached) {
517 avio_read(pb, guid, 16);
518 size = avio_rl64(pb);
521 if (!memcmp(guid, guid1, 16))
523 avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
528 static const uint8_t guid_data[16] = { 'd', 'a', 't', 'a',
529 0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
531 #define MAX_SIZE 4096
533 static int wav_read_packet(AVFormatContext *s,
539 WAVContext *wav = s->priv_data;
543 left = wav->data_end - avio_tell(s->pb);
545 if (CONFIG_W64_DEMUXER && wav->w64)
546 left = find_guid(s->pb, guid_data) - 24;
548 left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
551 wav->data_end= avio_tell(s->pb) + left;
555 if (st->codec->block_align > 1) {
556 if (size < st->codec->block_align)
557 size = st->codec->block_align;
558 size = (size / st->codec->block_align) * st->codec->block_align;
560 size = FFMIN(size, left);
561 ret = av_get_packet(s->pb, pkt, size);
564 pkt->stream_index = 0;
569 static int wav_read_seek(AVFormatContext *s,
570 int stream_index, int64_t timestamp, int flags)
575 switch (st->codec->codec_id) {
580 /* use generic seeking with dynamically generated indexes */
585 return ff_pcm_read_seek(s, stream_index, timestamp, flags);
588 AVInputFormat ff_wav_demuxer = {
590 .long_name = NULL_IF_CONFIG_SMALL("WAV format"),
591 .priv_data_size = sizeof(WAVContext),
592 .read_probe = wav_probe,
593 .read_header = wav_read_header,
594 .read_packet = wav_read_packet,
595 .read_seek = wav_read_seek,
596 .flags= AVFMT_GENERIC_INDEX,
597 .codec_tag= (const AVCodecTag* const []){ff_codec_wav_tags, 0},
599 #endif /* CONFIG_WAV_DEMUXER */
602 #if CONFIG_W64_DEMUXER
603 static const uint8_t guid_riff[16] = { 'r', 'i', 'f', 'f',
604 0x2E, 0x91, 0xCF, 0x11, 0xA5, 0xD6, 0x28, 0xDB, 0x04, 0xC1, 0x00, 0x00 };
606 static const uint8_t guid_wave[16] = { 'w', 'a', 'v', 'e',
607 0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
609 static const uint8_t guid_fmt [16] = { 'f', 'm', 't', ' ',
610 0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
612 static int w64_probe(AVProbeData *p)
614 if (p->buf_size <= 40)
616 if (!memcmp(p->buf, guid_riff, 16) &&
617 !memcmp(p->buf + 24, guid_wave, 16))
618 return AVPROBE_SCORE_MAX;
623 static int w64_read_header(AVFormatContext *s)
626 AVIOContext *pb = s->pb;
627 WAVContext *wav = s->priv_data;
632 avio_read(pb, guid, 16);
633 if (memcmp(guid, guid_riff, 16))
636 if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
639 avio_read(pb, guid, 16);
640 if (memcmp(guid, guid_wave, 16)) {
641 av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
645 size = find_guid(pb, guid_fmt);
647 av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");
651 st = avformat_new_stream(s, NULL);
653 return AVERROR(ENOMEM);
655 /* subtract chunk header size - normal wav file doesn't count it */
656 ret = ff_get_wav_header(pb, st->codec, size - 24);
659 avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
661 st->need_parsing = AVSTREAM_PARSE_FULL;
663 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
665 size = find_guid(pb, guid_data);
667 av_log(s, AV_LOG_ERROR, "could not find data guid\n");
670 wav->data_end = avio_tell(pb) + size - 24;
676 AVInputFormat ff_w64_demuxer = {
678 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64 format"),
679 .priv_data_size = sizeof(WAVContext),
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 */