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)
53 #define PEAK_BUFFER_SIZE 1024
62 PEAK_FORMAT_UINT8 = 1,
66 typedef struct WAVMuxContext {
73 int16_t *peak_maxpos, *peak_maxneg;
74 uint32_t peak_num_frames;
75 uint32_t peak_outbuf_size;
76 uint32_t peak_outbuf_bytes;
90 static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
92 AVDictionaryEntry *tag;
95 if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
96 len = strlen(tag->value);
97 len = FFMIN(len, maxlen);
98 avio_write(s->pb, tag->value, len);
101 ffio_fill(s->pb, 0, maxlen - len);
104 static void bwf_write_bext_chunk(AVFormatContext *s)
106 AVDictionaryEntry *tmp_tag;
107 uint64_t time_reference = 0;
108 int64_t bext = ff_start_tag(s->pb, "bext");
110 bwf_write_bext_string(s, "description", 256);
111 bwf_write_bext_string(s, "originator", 32);
112 bwf_write_bext_string(s, "originator_reference", 32);
113 bwf_write_bext_string(s, "origination_date", 10);
114 bwf_write_bext_string(s, "origination_time", 8);
116 if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
117 time_reference = strtoll(tmp_tag->value, NULL, 10);
118 avio_wl64(s->pb, time_reference);
119 avio_wl16(s->pb, 1); // set version to 1
121 if ((tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) && strlen(tmp_tag->value) > 2) {
122 unsigned char umidpart_str[17] = {0};
125 size_t len = strlen(tmp_tag->value+2);
127 for (i = 0; i < len/16; i++) {
128 memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
129 umidpart = strtoll(umidpart_str, NULL, 16);
130 avio_wb64(s->pb, umidpart);
132 ffio_fill(s->pb, 0, 64 - i*8);
134 ffio_fill(s->pb, 0, 64); // zero UMID
136 ffio_fill(s->pb, 0, 190); // Reserved
138 if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
139 avio_put_str(s->pb, tmp_tag->value);
141 ff_end_tag(s->pb, bext);
144 static av_cold void wav_deinit(AVFormatContext *s)
146 WAVMuxContext *wav = s->priv_data;
148 av_freep(&wav->peak_maxpos);
149 av_freep(&wav->peak_maxneg);
150 av_freep(&wav->peak_output);
153 static av_cold int peak_init_writer(AVFormatContext *s)
155 WAVMuxContext *wav = s->priv_data;
156 AVCodecParameters *par = s->streams[0]->codecpar;
158 if (par->codec_id != AV_CODEC_ID_PCM_S8 &&
159 par->codec_id != AV_CODEC_ID_PCM_S16LE &&
160 par->codec_id != AV_CODEC_ID_PCM_U8 &&
161 par->codec_id != AV_CODEC_ID_PCM_U16LE) {
162 AVCodec *codec = avcodec_find_decoder(s->streams[0]->codecpar->codec_id);
163 av_log(s, AV_LOG_ERROR, "%s codec not supported for Peak Chunk\n",
164 codec ? codec->name : "NONE");
168 wav->peak_bps = av_get_bits_per_sample(par->codec_id) / 8;
170 if (wav->peak_bps == 1 && wav->peak_format == PEAK_FORMAT_UINT16) {
171 av_log(s, AV_LOG_ERROR,
172 "Writing 16 bit peak for 8 bit audio does not make sense\n");
173 return AVERROR(EINVAL);
176 wav->peak_maxpos = av_mallocz_array(par->channels, sizeof(*wav->peak_maxpos));
177 wav->peak_maxneg = av_mallocz_array(par->channels, sizeof(*wav->peak_maxneg));
178 wav->peak_output = av_malloc(PEAK_BUFFER_SIZE);
179 if (!wav->peak_maxpos || !wav->peak_maxneg || !wav->peak_output)
182 wav->peak_outbuf_size = PEAK_BUFFER_SIZE;
187 av_log(s, AV_LOG_ERROR, "Out of memory\n");
188 return AVERROR(ENOMEM);
191 static void peak_write_frame(AVFormatContext *s)
193 WAVMuxContext *wav = s->priv_data;
194 AVCodecParameters *par = s->streams[0]->codecpar;
197 if (!wav->peak_output)
200 for (c = 0; c < par->channels; c++) {
201 wav->peak_maxneg[c] = -wav->peak_maxneg[c];
203 if (wav->peak_bps == 2 && wav->peak_format == PEAK_FORMAT_UINT8) {
204 wav->peak_maxpos[c] = wav->peak_maxpos[c] / 256;
205 wav->peak_maxneg[c] = wav->peak_maxneg[c] / 256;
208 if (wav->peak_ppv == 1)
209 wav->peak_maxpos[c] =
210 FFMAX(wav->peak_maxpos[c], wav->peak_maxneg[c]);
212 if (wav->peak_outbuf_size - wav->peak_outbuf_bytes <
213 wav->peak_format * wav->peak_ppv) {
214 wav->peak_outbuf_size += PEAK_BUFFER_SIZE;
215 wav->peak_output = av_realloc(wav->peak_output,
216 wav->peak_outbuf_size);
217 if (!wav->peak_output) {
218 av_log(s, AV_LOG_ERROR, "No memory for peak data\n");
223 if (wav->peak_format == PEAK_FORMAT_UINT8) {
224 wav->peak_output[wav->peak_outbuf_bytes++] =
226 if (wav->peak_ppv == 2) {
227 wav->peak_output[wav->peak_outbuf_bytes++] =
231 AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
232 wav->peak_maxpos[c]);
233 wav->peak_outbuf_bytes += 2;
234 if (wav->peak_ppv == 2) {
235 AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
236 wav->peak_maxneg[c]);
237 wav->peak_outbuf_bytes += 2;
240 wav->peak_maxpos[c] = 0;
241 wav->peak_maxneg[c] = 0;
243 wav->peak_num_frames++;
246 static int peak_write_chunk(AVFormatContext *s)
248 WAVMuxContext *wav = s->priv_data;
249 AVIOContext *pb = s->pb;
250 AVCodecParameters *par = s->streams[0]->codecpar;
251 int64_t peak = ff_start_tag(s->pb, "levl");
256 /* Peak frame of incomplete block at end */
257 if (wav->peak_block_pos)
260 memset(timestamp, 0, sizeof(timestamp));
261 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
263 av_log(s, AV_LOG_INFO, "Writing local time and date to Peak Envelope Chunk\n");
265 now_secs = now0 / 1000000;
266 if (strftime(timestamp, sizeof(timestamp), "%Y:%m:%d:%H:%M:%S:", localtime_r(&now_secs, &tmpbuf))) {
267 av_strlcatf(timestamp, sizeof(timestamp), "%03d", (int)((now0 / 1000) % 1000));
269 av_log(s, AV_LOG_ERROR, "Failed to write timestamp\n");
274 avio_wl32(pb, 1); /* version */
275 avio_wl32(pb, wav->peak_format); /* 8 or 16 bit */
276 avio_wl32(pb, wav->peak_ppv); /* positive and negative */
277 avio_wl32(pb, wav->peak_block_size); /* frames per value */
278 avio_wl32(pb, par->channels); /* number of channels */
279 avio_wl32(pb, wav->peak_num_frames); /* number of peak frames */
280 avio_wl32(pb, -1); /* audio sample frame position (not implemented) */
281 avio_wl32(pb, 128); /* equal to size of header */
282 avio_write(pb, timestamp, 28); /* ASCII time stamp */
283 ffio_fill(pb, 0, 60);
285 avio_write(pb, wav->peak_output, wav->peak_outbuf_bytes);
287 ff_end_tag(pb, peak);
295 static int wav_write_header(AVFormatContext *s)
297 WAVMuxContext *wav = s->priv_data;
298 AVIOContext *pb = s->pb;
301 if (s->nb_streams != 1) {
302 av_log(s, AV_LOG_ERROR, "WAVE files have exactly one stream\n");
303 return AVERROR(EINVAL);
306 if (wav->rf64 == RF64_ALWAYS) {
307 ffio_wfourcc(pb, "RF64");
308 avio_wl32(pb, -1); /* RF64 chunk size: use size in ds64 */
310 ffio_wfourcc(pb, "RIFF");
311 avio_wl32(pb, -1); /* file length */
314 ffio_wfourcc(pb, "WAVE");
316 if (wav->rf64 != RF64_NEVER) {
317 /* write empty ds64 chunk or JUNK chunk to reserve space for ds64 */
318 ffio_wfourcc(pb, wav->rf64 == RF64_ALWAYS ? "ds64" : "JUNK");
319 avio_wl32(pb, 28); /* chunk size */
320 wav->ds64 = avio_tell(pb);
321 ffio_fill(pb, 0, 28);
324 if (wav->write_peak != PEAK_ONLY) {
326 fmt = ff_start_tag(pb, "fmt ");
327 if (ff_put_wav_header(s, pb, s->streams[0]->codecpar, 0) < 0) {
328 const AVCodecDescriptor *desc = avcodec_descriptor_get(s->streams[0]->codecpar->codec_id);
329 av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
330 desc ? desc->name : "unknown");
331 return AVERROR(ENOSYS);
336 if (s->streams[0]->codecpar->codec_tag != 0x01 /* hence for all other than PCM */
337 && (s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
338 wav->fact_pos = ff_start_tag(pb, "fact");
340 ff_end_tag(pb, wav->fact_pos);
344 bwf_write_bext_chunk(s);
346 if (wav->write_peak) {
348 if ((ret = peak_init_writer(s)) < 0)
352 avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codecpar->sample_rate);
353 wav->maxpts = wav->last_duration = 0;
354 wav->minpts = INT64_MAX;
356 if (wav->write_peak != PEAK_ONLY) {
358 ff_riff_write_info(s);
361 wav->data = ff_start_tag(pb, "data");
367 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
369 AVIOContext *pb = s->pb;
370 WAVMuxContext *wav = s->priv_data;
372 if (wav->write_peak != PEAK_ONLY)
373 avio_write(pb, pkt->data, pkt->size);
375 if (wav->write_peak) {
378 for (i = 0; i < pkt->size; i += wav->peak_bps) {
379 if (wav->peak_bps == 1) {
380 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], *(int8_t*)(pkt->data + i));
381 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], *(int8_t*)(pkt->data + i));
383 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], (int16_t)AV_RL16(pkt->data + i));
384 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], (int16_t)AV_RL16(pkt->data + i));
386 if (++c == s->streams[0]->codecpar->channels) {
388 if (++wav->peak_block_pos == wav->peak_block_size) {
390 wav->peak_block_pos = 0;
396 if(pkt->pts != AV_NOPTS_VALUE) {
397 wav->minpts = FFMIN(wav->minpts, pkt->pts);
398 wav->maxpts = FFMAX(wav->maxpts, pkt->pts);
399 wav->last_duration = pkt->duration;
401 av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
405 static int wav_write_trailer(AVFormatContext *s)
407 AVIOContext *pb = s->pb;
408 WAVMuxContext *wav = s->priv_data;
409 int64_t file_size, data_size;
410 int64_t number_of_samples = 0;
414 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
415 if (wav->write_peak != PEAK_ONLY && avio_tell(pb) - wav->data < UINT32_MAX) {
416 ff_end_tag(pb, wav->data);
419 if (wav->write_peak && wav->peak_output) {
420 ret = peak_write_chunk(s);
423 /* update file size */
424 file_size = avio_tell(pb);
425 data_size = file_size - wav->data;
426 if (wav->rf64 == RF64_ALWAYS || (wav->rf64 == RF64_AUTO && file_size - 8 > UINT32_MAX)) {
428 } else if (file_size - 8 <= UINT32_MAX) {
429 avio_seek(pb, 4, SEEK_SET);
430 avio_wl32(pb, (uint32_t)(file_size - 8));
431 avio_seek(pb, file_size, SEEK_SET);
433 av_log(s, AV_LOG_ERROR,
434 "Filesize %"PRId64" invalid for wav, output file will be broken\n",
438 number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
439 s->streams[0]->codecpar->sample_rate * (int64_t)s->streams[0]->time_base.num,
440 s->streams[0]->time_base.den);
442 if(s->streams[0]->codecpar->codec_tag != 0x01) {
443 /* Update num_samps in fact chunk */
444 avio_seek(pb, wav->fact_pos, SEEK_SET);
445 if (rf64 || (wav->rf64 == RF64_AUTO && number_of_samples > UINT32_MAX)) {
449 avio_wl32(pb, number_of_samples);
450 avio_seek(pb, file_size, SEEK_SET);
455 /* overwrite RIFF with RF64 */
456 avio_seek(pb, 0, SEEK_SET);
457 ffio_wfourcc(pb, "RF64");
460 /* write ds64 chunk (overwrite JUNK if rf64 == RF64_AUTO) */
461 avio_seek(pb, wav->ds64 - 8, SEEK_SET);
462 ffio_wfourcc(pb, "ds64");
463 avio_wl32(pb, 28); /* ds64 chunk size */
464 avio_wl64(pb, file_size - 8); /* RF64 chunk size */
465 avio_wl64(pb, data_size); /* data chunk size */
466 avio_wl64(pb, number_of_samples); /* fact chunk number of samples */
467 avio_wl32(pb, 0); /* number of table entries for non-'data' chunks */
469 /* write -1 in data chunk size */
470 avio_seek(pb, wav->data - 4, SEEK_SET);
473 avio_seek(pb, file_size, SEEK_SET);
480 #define OFFSET(x) offsetof(WAVMuxContext, x)
481 #define ENC AV_OPT_FLAG_ENCODING_PARAM
482 static const AVOption options[] = {
483 { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
484 { "write_peak", "Write Peak Envelope chunk.", OFFSET(write_peak), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, ENC, "peak" },
485 { "off", "Do not write peak chunk.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_OFF }, 0, 0, ENC, "peak" },
486 { "on", "Append peak chunk after wav data.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_ON }, 0, 0, ENC, "peak" },
487 { "only", "Write only peak chunk, omit wav data.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_ONLY }, 0, 0, ENC, "peak" },
488 { "rf64", "Use RF64 header rather than RIFF for large files.", OFFSET(rf64), AV_OPT_TYPE_INT, { .i64 = RF64_NEVER },-1, 1, ENC, "rf64" },
489 { "auto", "Write RF64 header if file grows large enough.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_AUTO }, 0, 0, ENC, "rf64" },
490 { "always", "Always write RF64 header regardless of file size.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_ALWAYS }, 0, 0, ENC, "rf64" },
491 { "never", "Never write RF64 header regardless of file size.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_NEVER }, 0, 0, ENC, "rf64" },
492 { "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 },
493 { "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 },
494 { "peak_ppv", "Number of peak points per peak value (1 or 2).", OFFSET(peak_ppv), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, 2, ENC },
498 static const AVClass wav_muxer_class = {
499 .class_name = "WAV muxer",
500 .item_name = av_default_item_name,
502 .version = LIBAVUTIL_VERSION_INT,
505 AVOutputFormat ff_wav_muxer = {
507 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
508 .mime_type = "audio/x-wav",
510 .priv_data_size = sizeof(WAVMuxContext),
511 .audio_codec = AV_CODEC_ID_PCM_S16LE,
512 .video_codec = AV_CODEC_ID_NONE,
513 .write_header = wav_write_header,
514 .write_packet = wav_write_packet,
515 .write_trailer = wav_write_trailer,
516 .deinit = wav_deinit,
517 .flags = AVFMT_TS_NONSTRICT,
518 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
519 .priv_class = &wav_muxer_class,
521 #endif /* CONFIG_WAV_MUXER */
526 static void start_guid(AVIOContext *pb, const uint8_t *guid, int64_t *pos)
528 *pos = avio_tell(pb);
530 avio_write(pb, guid, 16);
531 avio_wl64(pb, INT64_MAX);
534 static void end_guid(AVIOContext *pb, int64_t start)
536 int64_t end, pos = avio_tell(pb);
538 end = FFALIGN(pos, 8);
539 ffio_fill(pb, 0, end - pos);
540 avio_seek(pb, start + 16, SEEK_SET);
541 avio_wl64(pb, end - start);
542 avio_seek(pb, end, SEEK_SET);
545 static int w64_write_header(AVFormatContext *s)
547 WAVMuxContext *wav = s->priv_data;
548 AVIOContext *pb = s->pb;
552 avio_write(pb, ff_w64_guid_riff, sizeof(ff_w64_guid_riff));
554 avio_write(pb, ff_w64_guid_wave, sizeof(ff_w64_guid_wave));
555 start_guid(pb, ff_w64_guid_fmt, &start);
556 if ((ret = ff_put_wav_header(s, pb, s->streams[0]->codecpar, 0)) < 0) {
557 AVCodec *codec = avcodec_find_decoder(s->streams[0]->codecpar->codec_id);
558 av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
559 codec ? codec->name : "NONE");
564 if (s->streams[0]->codecpar->codec_tag != 0x01 /* hence for all other than PCM */
565 && (s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
566 start_guid(pb, ff_w64_guid_fact, &wav->fact_pos);
568 end_guid(pb, wav->fact_pos);
571 start_guid(pb, ff_w64_guid_data, &wav->data);
576 static int w64_write_trailer(AVFormatContext *s)
578 AVIOContext *pb = s->pb;
579 WAVMuxContext *wav = s->priv_data;
582 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
583 end_guid(pb, wav->data);
585 file_size = avio_tell(pb);
586 avio_seek(pb, 16, SEEK_SET);
587 avio_wl64(pb, file_size);
589 if (s->streams[0]->codecpar->codec_tag != 0x01) {
590 int64_t number_of_samples;
592 number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
593 s->streams[0]->codecpar->sample_rate * (int64_t)s->streams[0]->time_base.num,
594 s->streams[0]->time_base.den);
595 avio_seek(pb, wav->fact_pos + 24, SEEK_SET);
596 avio_wl64(pb, number_of_samples);
599 avio_seek(pb, file_size, SEEK_SET);
605 AVOutputFormat ff_w64_muxer = {
607 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
609 .priv_data_size = sizeof(WAVMuxContext),
610 .audio_codec = AV_CODEC_ID_PCM_S16LE,
611 .video_codec = AV_CODEC_ID_NONE,
612 .write_header = w64_write_header,
613 .write_packet = wav_write_packet,
614 .write_trailer = w64_write_trailer,
615 .flags = AVFMT_TS_NONSTRICT,
616 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
618 #endif /* CONFIG_W64_MUXER */