3 * Copyright (c) 2001, 2002 Fabrice Bellard
6 * Copyright (c) 2012 Paul B Mahol
8 * WAV muxer RF64 support
9 * Copyright (c) 2013 Daniel Verkamp <daniel@drv.nu>
11 * EBU Tech 3285 - Supplement 3 - Peak Envelope Chunk encoder
12 * Copyright (c) 2014 Georg Lippitsch <georg.lippitsch@gmx.at>
14 * This file is part of FFmpeg.
16 * FFmpeg is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU Lesser General Public
18 * License as published by the Free Software Foundation; either
19 * version 2.1 of the License, or (at your option) any later version.
21 * FFmpeg is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * Lesser General Public License for more details.
26 * You should have received a copy of the GNU Lesser General Public
27 * License along with FFmpeg; if not, write to the Free Software
28 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include "libavutil/avstring.h"
35 #include "libavutil/dict.h"
36 #include "libavutil/common.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/time.h"
41 #include "libavutil/time_internal.h"
45 #include "avio_internal.h"
49 #define RF64_AUTO (-1)
60 PEAK_FORMAT_UINT8 = 1,
64 typedef struct WAVMuxContext {
71 int16_t *peak_maxpos, *peak_maxneg;
72 uint32_t peak_num_frames;
73 unsigned peak_outbuf_size;
74 uint32_t peak_outbuf_bytes;
75 unsigned size_increment;
89 static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
91 AVDictionaryEntry *tag;
94 if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
95 len = strlen(tag->value);
96 len = FFMIN(len, maxlen);
97 avio_write(s->pb, tag->value, len);
100 ffio_fill(s->pb, 0, maxlen - len);
103 static void bwf_write_bext_chunk(AVFormatContext *s)
105 AVDictionaryEntry *tmp_tag;
106 uint64_t time_reference = 0;
107 int64_t bext = ff_start_tag(s->pb, "bext");
109 bwf_write_bext_string(s, "description", 256);
110 bwf_write_bext_string(s, "originator", 32);
111 bwf_write_bext_string(s, "originator_reference", 32);
112 bwf_write_bext_string(s, "origination_date", 10);
113 bwf_write_bext_string(s, "origination_time", 8);
115 if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
116 time_reference = strtoll(tmp_tag->value, NULL, 10);
117 avio_wl64(s->pb, time_reference);
118 avio_wl16(s->pb, 1); // set version to 1
120 if ((tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) && strlen(tmp_tag->value) > 2) {
121 unsigned char umidpart_str[17] = {0};
124 size_t len = strlen(tmp_tag->value+2);
126 for (i = 0; i < len/16; i++) {
127 memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
128 umidpart = strtoll(umidpart_str, NULL, 16);
129 avio_wb64(s->pb, umidpart);
131 ffio_fill(s->pb, 0, 64 - i*8);
133 ffio_fill(s->pb, 0, 64); // zero UMID
135 ffio_fill(s->pb, 0, 190); // Reserved
137 if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
138 avio_put_str(s->pb, tmp_tag->value);
140 ff_end_tag(s->pb, bext);
143 static av_cold void wav_deinit(AVFormatContext *s)
145 WAVMuxContext *wav = s->priv_data;
147 av_freep(&wav->peak_maxpos);
148 av_freep(&wav->peak_maxneg);
149 av_freep(&wav->peak_output);
152 static av_cold int peak_init_writer(AVFormatContext *s)
154 WAVMuxContext *wav = s->priv_data;
155 AVCodecParameters *par = s->streams[0]->codecpar;
157 if (par->codec_id != AV_CODEC_ID_PCM_S8 &&
158 par->codec_id != AV_CODEC_ID_PCM_S16LE &&
159 par->codec_id != AV_CODEC_ID_PCM_U8 &&
160 par->codec_id != AV_CODEC_ID_PCM_U16LE) {
161 av_log(s, AV_LOG_ERROR, "Codec %s not supported for Peak Chunk\n",
162 avcodec_get_name(par->codec_id));
166 wav->peak_bps = av_get_bits_per_sample(par->codec_id) / 8;
168 if (wav->peak_bps == 1 && wav->peak_format == PEAK_FORMAT_UINT16) {
169 av_log(s, AV_LOG_ERROR,
170 "Writing 16 bit peak for 8 bit audio does not make sense\n");
171 return AVERROR(EINVAL);
173 if (par->channels > INT_MAX / (wav->peak_bps * wav->peak_ppv))
174 return AVERROR(ERANGE);
175 wav->size_increment = par->channels * wav->peak_bps * wav->peak_ppv;
177 wav->peak_maxpos = av_mallocz_array(par->channels, sizeof(*wav->peak_maxpos));
178 wav->peak_maxneg = av_mallocz_array(par->channels, sizeof(*wav->peak_maxneg));
179 if (!wav->peak_maxpos || !wav->peak_maxneg)
185 av_log(s, AV_LOG_ERROR, "Out of memory\n");
186 return AVERROR(ENOMEM);
189 static int peak_write_frame(AVFormatContext *s)
191 WAVMuxContext *wav = s->priv_data;
192 AVCodecParameters *par = s->streams[0]->codecpar;
193 unsigned new_size = wav->peak_outbuf_bytes + wav->size_increment;
197 if (new_size > INT_MAX) {
198 wav->write_peak = PEAK_OFF;
199 return AVERROR(ERANGE);
201 tmp = av_fast_realloc(wav->peak_output, &wav->peak_outbuf_size, new_size);
203 wav->write_peak = PEAK_OFF;
204 return AVERROR(ENOMEM);
206 wav->peak_output = tmp;
208 for (c = 0; c < par->channels; c++) {
209 wav->peak_maxneg[c] = -wav->peak_maxneg[c];
211 if (wav->peak_bps == 2 && wav->peak_format == PEAK_FORMAT_UINT8) {
212 wav->peak_maxpos[c] = wav->peak_maxpos[c] / 256;
213 wav->peak_maxneg[c] = wav->peak_maxneg[c] / 256;
216 if (wav->peak_ppv == 1)
217 wav->peak_maxpos[c] =
218 FFMAX(wav->peak_maxpos[c], wav->peak_maxneg[c]);
220 if (wav->peak_format == PEAK_FORMAT_UINT8) {
221 wav->peak_output[wav->peak_outbuf_bytes++] =
223 if (wav->peak_ppv == 2) {
224 wav->peak_output[wav->peak_outbuf_bytes++] =
228 AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
229 wav->peak_maxpos[c]);
230 wav->peak_outbuf_bytes += 2;
231 if (wav->peak_ppv == 2) {
232 AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
233 wav->peak_maxneg[c]);
234 wav->peak_outbuf_bytes += 2;
237 wav->peak_maxpos[c] = 0;
238 wav->peak_maxneg[c] = 0;
240 wav->peak_num_frames++;
245 static int peak_write_chunk(AVFormatContext *s)
247 WAVMuxContext *wav = s->priv_data;
248 AVIOContext *pb = s->pb;
249 AVCodecParameters *par = s->streams[0]->codecpar;
250 int64_t peak = ff_start_tag(s->pb, "levl");
255 /* Peak frame of incomplete block at end */
256 if (wav->peak_block_pos) {
257 int ret = peak_write_frame(s);
262 memset(timestamp, 0, sizeof(timestamp));
263 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
265 av_log(s, AV_LOG_INFO, "Writing local time and date to Peak Envelope Chunk\n");
267 now_secs = now0 / 1000000;
268 if (strftime(timestamp, sizeof(timestamp), "%Y:%m:%d:%H:%M:%S:", localtime_r(&now_secs, &tmpbuf))) {
269 av_strlcatf(timestamp, sizeof(timestamp), "%03d", (int)((now0 / 1000) % 1000));
271 av_log(s, AV_LOG_ERROR, "Failed to write timestamp\n");
276 avio_wl32(pb, 1); /* version */
277 avio_wl32(pb, wav->peak_format); /* 8 or 16 bit */
278 avio_wl32(pb, wav->peak_ppv); /* positive and negative */
279 avio_wl32(pb, wav->peak_block_size); /* frames per value */
280 avio_wl32(pb, par->channels); /* number of channels */
281 avio_wl32(pb, wav->peak_num_frames); /* number of peak frames */
282 avio_wl32(pb, -1); /* audio sample frame position (not implemented) */
283 avio_wl32(pb, 128); /* equal to size of header */
284 avio_write(pb, timestamp, 28); /* ASCII time stamp */
285 ffio_fill(pb, 0, 60);
287 avio_write(pb, wav->peak_output, wav->peak_outbuf_bytes);
289 ff_end_tag(pb, peak);
297 static int wav_write_header(AVFormatContext *s)
299 WAVMuxContext *wav = s->priv_data;
300 AVIOContext *pb = s->pb;
303 if (s->nb_streams != 1) {
304 av_log(s, AV_LOG_ERROR, "WAVE files have exactly one stream\n");
305 return AVERROR(EINVAL);
308 if (wav->rf64 == RF64_ALWAYS) {
309 ffio_wfourcc(pb, "RF64");
310 avio_wl32(pb, -1); /* RF64 chunk size: use size in ds64 */
312 ffio_wfourcc(pb, "RIFF");
313 avio_wl32(pb, -1); /* file length */
316 ffio_wfourcc(pb, "WAVE");
318 if (wav->rf64 != RF64_NEVER) {
319 /* write empty ds64 chunk or JUNK chunk to reserve space for ds64 */
320 ffio_wfourcc(pb, wav->rf64 == RF64_ALWAYS ? "ds64" : "JUNK");
321 avio_wl32(pb, 28); /* chunk size */
322 wav->ds64 = avio_tell(pb);
323 ffio_fill(pb, 0, 28);
326 if (wav->write_peak != PEAK_ONLY) {
328 fmt = ff_start_tag(pb, "fmt ");
329 if (ff_put_wav_header(s, pb, s->streams[0]->codecpar, 0) < 0) {
330 av_log(s, AV_LOG_ERROR, "Codec %s not supported in WAVE format\n",
331 avcodec_get_name(s->streams[0]->codecpar->codec_id));
332 return AVERROR(ENOSYS);
337 if (s->streams[0]->codecpar->codec_tag != 0x01 /* hence for all other than PCM */
338 && (s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
339 wav->fact_pos = ff_start_tag(pb, "fact");
341 ff_end_tag(pb, wav->fact_pos);
345 bwf_write_bext_chunk(s);
347 if (wav->write_peak) {
349 if ((ret = peak_init_writer(s)) < 0)
353 avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codecpar->sample_rate);
354 wav->maxpts = wav->last_duration = 0;
355 wav->minpts = INT64_MAX;
357 if (wav->write_peak != PEAK_ONLY) {
359 ff_riff_write_info(s);
362 wav->data = ff_start_tag(pb, "data");
368 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
370 AVIOContext *pb = s->pb;
371 WAVMuxContext *wav = s->priv_data;
373 if (wav->write_peak != PEAK_ONLY)
374 avio_write(pb, pkt->data, pkt->size);
376 if (wav->write_peak) {
379 for (i = 0; i < pkt->size; i += wav->peak_bps) {
380 if (wav->peak_bps == 1) {
381 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], *(int8_t*)(pkt->data + i));
382 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], *(int8_t*)(pkt->data + i));
384 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], (int16_t)AV_RL16(pkt->data + i));
385 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], (int16_t)AV_RL16(pkt->data + i));
387 if (++c == s->streams[0]->codecpar->channels) {
389 if (++wav->peak_block_pos == wav->peak_block_size) {
390 int ret = peak_write_frame(s);
393 wav->peak_block_pos = 0;
399 if(pkt->pts != AV_NOPTS_VALUE) {
400 wav->minpts = FFMIN(wav->minpts, pkt->pts);
401 wav->maxpts = FFMAX(wav->maxpts, pkt->pts);
402 wav->last_duration = pkt->duration;
404 av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
408 static int wav_write_trailer(AVFormatContext *s)
410 AVIOContext *pb = s->pb;
411 WAVMuxContext *wav = s->priv_data;
412 int64_t file_size, data_size;
413 int64_t number_of_samples = 0;
417 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
418 if (wav->write_peak != PEAK_ONLY && avio_tell(pb) - wav->data < UINT32_MAX) {
419 ff_end_tag(pb, wav->data);
422 if (wav->write_peak && wav->peak_output) {
423 ret = peak_write_chunk(s);
426 /* update file size */
427 file_size = avio_tell(pb);
428 data_size = file_size - wav->data;
429 if (wav->rf64 == RF64_ALWAYS || (wav->rf64 == RF64_AUTO && file_size - 8 > UINT32_MAX)) {
431 } else if (file_size - 8 <= UINT32_MAX) {
432 avio_seek(pb, 4, SEEK_SET);
433 avio_wl32(pb, (uint32_t)(file_size - 8));
434 avio_seek(pb, file_size, SEEK_SET);
436 av_log(s, AV_LOG_ERROR,
437 "Filesize %"PRId64" invalid for wav, output file will be broken\n",
440 number_of_samples = av_rescale_q(wav->maxpts - wav->minpts + wav->last_duration,
441 s->streams[0]->time_base,
442 av_make_q(1, s->streams[0]->codecpar->sample_rate));
444 if(s->streams[0]->codecpar->codec_tag != 0x01) {
445 /* Update num_samps in fact chunk */
446 avio_seek(pb, wav->fact_pos, SEEK_SET);
447 if (rf64 || (wav->rf64 == RF64_AUTO && number_of_samples > UINT32_MAX)) {
451 avio_wl32(pb, number_of_samples);
452 avio_seek(pb, file_size, SEEK_SET);
457 /* overwrite RIFF with RF64 */
458 avio_seek(pb, 0, SEEK_SET);
459 ffio_wfourcc(pb, "RF64");
462 /* write ds64 chunk (overwrite JUNK if rf64 == RF64_AUTO) */
463 avio_seek(pb, wav->ds64 - 8, SEEK_SET);
464 ffio_wfourcc(pb, "ds64");
465 avio_wl32(pb, 28); /* ds64 chunk size */
466 avio_wl64(pb, file_size - 8); /* RF64 chunk size */
467 avio_wl64(pb, data_size); /* data chunk size */
468 avio_wl64(pb, number_of_samples); /* fact chunk number of samples */
469 avio_wl32(pb, 0); /* number of table entries for non-'data' chunks */
471 /* write -1 in data chunk size */
472 avio_seek(pb, wav->data - 4, SEEK_SET);
475 avio_seek(pb, file_size, SEEK_SET);
482 #define OFFSET(x) offsetof(WAVMuxContext, x)
483 #define ENC AV_OPT_FLAG_ENCODING_PARAM
484 static const AVOption options[] = {
485 { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
486 { "write_peak", "Write Peak Envelope chunk.", OFFSET(write_peak), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, ENC, "peak" },
487 { "off", "Do not write peak chunk.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_OFF }, 0, 0, ENC, "peak" },
488 { "on", "Append peak chunk after wav data.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_ON }, 0, 0, ENC, "peak" },
489 { "only", "Write only peak chunk, omit wav data.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_ONLY }, 0, 0, ENC, "peak" },
490 { "rf64", "Use RF64 header rather than RIFF for large files.", OFFSET(rf64), AV_OPT_TYPE_INT, { .i64 = RF64_NEVER },-1, 1, ENC, "rf64" },
491 { "auto", "Write RF64 header if file grows large enough.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_AUTO }, 0, 0, ENC, "rf64" },
492 { "always", "Always write RF64 header regardless of file size.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_ALWAYS }, 0, 0, ENC, "rf64" },
493 { "never", "Never write RF64 header regardless of file size.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_NEVER }, 0, 0, ENC, "rf64" },
494 { "peak_block_size", "Number of audio samples used to generate each peak frame.", OFFSET(peak_block_size), AV_OPT_TYPE_INT, { .i64 = 256 }, 0, 65536, ENC },
495 { "peak_format", "The format of the peak envelope data (1: uint8, 2: uint16).", OFFSET(peak_format), AV_OPT_TYPE_INT, { .i64 = PEAK_FORMAT_UINT16 }, PEAK_FORMAT_UINT8, PEAK_FORMAT_UINT16, ENC },
496 { "peak_ppv", "Number of peak points per peak value (1 or 2).", OFFSET(peak_ppv), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, 2, ENC },
500 static const AVClass wav_muxer_class = {
501 .class_name = "WAV muxer",
502 .item_name = av_default_item_name,
504 .version = LIBAVUTIL_VERSION_INT,
507 AVOutputFormat ff_wav_muxer = {
509 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
510 .mime_type = "audio/x-wav",
512 .priv_data_size = sizeof(WAVMuxContext),
513 .audio_codec = AV_CODEC_ID_PCM_S16LE,
514 .video_codec = AV_CODEC_ID_NONE,
515 .write_header = wav_write_header,
516 .write_packet = wav_write_packet,
517 .write_trailer = wav_write_trailer,
518 .deinit = wav_deinit,
519 .flags = AVFMT_TS_NONSTRICT,
520 .codec_tag = ff_wav_codec_tags_list,
521 .priv_class = &wav_muxer_class,
523 #endif /* CONFIG_WAV_MUXER */
528 static void start_guid(AVIOContext *pb, const uint8_t *guid, int64_t *pos)
530 *pos = avio_tell(pb);
532 avio_write(pb, guid, 16);
533 avio_wl64(pb, INT64_MAX);
536 static void end_guid(AVIOContext *pb, int64_t start)
538 int64_t end, pos = avio_tell(pb);
540 end = FFALIGN(pos, 8);
541 ffio_fill(pb, 0, end - pos);
542 avio_seek(pb, start + 16, SEEK_SET);
543 avio_wl64(pb, end - start);
544 avio_seek(pb, end, SEEK_SET);
547 static int w64_write_header(AVFormatContext *s)
549 WAVMuxContext *wav = s->priv_data;
550 AVIOContext *pb = s->pb;
554 avio_write(pb, ff_w64_guid_riff, sizeof(ff_w64_guid_riff));
556 avio_write(pb, ff_w64_guid_wave, sizeof(ff_w64_guid_wave));
557 start_guid(pb, ff_w64_guid_fmt, &start);
558 if ((ret = ff_put_wav_header(s, pb, s->streams[0]->codecpar, 0)) < 0) {
559 av_log(s, AV_LOG_ERROR, "Codec %s not supported\n",
560 avcodec_get_name(s->streams[0]->codecpar->codec_id));
565 if (s->streams[0]->codecpar->codec_tag != 0x01 /* hence for all other than PCM */
566 && (s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
567 start_guid(pb, ff_w64_guid_fact, &wav->fact_pos);
569 end_guid(pb, wav->fact_pos);
572 start_guid(pb, ff_w64_guid_data, &wav->data);
577 static int w64_write_trailer(AVFormatContext *s)
579 AVIOContext *pb = s->pb;
580 WAVMuxContext *wav = s->priv_data;
583 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
584 end_guid(pb, wav->data);
586 file_size = avio_tell(pb);
587 avio_seek(pb, 16, SEEK_SET);
588 avio_wl64(pb, file_size);
590 if (s->streams[0]->codecpar->codec_tag != 0x01) {
591 int64_t number_of_samples;
593 number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
594 s->streams[0]->codecpar->sample_rate * (int64_t)s->streams[0]->time_base.num,
595 s->streams[0]->time_base.den);
596 avio_seek(pb, wav->fact_pos + 24, SEEK_SET);
597 avio_wl64(pb, number_of_samples);
600 avio_seek(pb, file_size, SEEK_SET);
606 AVOutputFormat ff_w64_muxer = {
608 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
610 .priv_data_size = sizeof(WAVMuxContext),
611 .audio_codec = AV_CODEC_ID_PCM_S16LE,
612 .video_codec = AV_CODEC_ID_NONE,
613 .write_header = w64_write_header,
614 .write_packet = wav_write_packet,
615 .write_trailer = w64_write_trailer,
616 .flags = AVFMT_TS_NONSTRICT,
617 .codec_tag = ff_wav_codec_tags_list,
619 #endif /* CONFIG_W64_MUXER */