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;
77 uint32_t peak_pos_pop;
92 static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
94 AVDictionaryEntry *tag;
97 if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
98 len = strlen(tag->value);
99 len = FFMIN(len, maxlen);
100 avio_write(s->pb, tag->value, len);
103 ffio_fill(s->pb, 0, maxlen - len);
106 static void bwf_write_bext_chunk(AVFormatContext *s)
108 AVDictionaryEntry *tmp_tag;
109 uint64_t time_reference = 0;
110 int64_t bext = ff_start_tag(s->pb, "bext");
112 bwf_write_bext_string(s, "description", 256);
113 bwf_write_bext_string(s, "originator", 32);
114 bwf_write_bext_string(s, "originator_reference", 32);
115 bwf_write_bext_string(s, "origination_date", 10);
116 bwf_write_bext_string(s, "origination_time", 8);
118 if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
119 time_reference = strtoll(tmp_tag->value, NULL, 10);
120 avio_wl64(s->pb, time_reference);
121 avio_wl16(s->pb, 1); // set version to 1
123 if ((tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) && strlen(tmp_tag->value) > 2) {
124 unsigned char umidpart_str[17] = {0};
127 size_t len = strlen(tmp_tag->value+2);
129 for (i = 0; i < len/16; i++) {
130 memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
131 umidpart = strtoll(umidpart_str, NULL, 16);
132 avio_wb64(s->pb, umidpart);
134 ffio_fill(s->pb, 0, 64 - i*8);
136 ffio_fill(s->pb, 0, 64); // zero UMID
138 ffio_fill(s->pb, 0, 190); // Reserved
140 if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
141 avio_put_str(s->pb, tmp_tag->value);
143 ff_end_tag(s->pb, bext);
146 static av_cold void peak_free_buffers(AVFormatContext *s)
148 WAVMuxContext *wav = s->priv_data;
150 av_freep(&wav->peak_maxpos);
151 av_freep(&wav->peak_maxneg);
152 av_freep(&wav->peak_output);
155 static av_cold int peak_init_writer(AVFormatContext *s)
157 WAVMuxContext *wav = s->priv_data;
158 AVCodecContext *enc = s->streams[0]->codec;
160 if (enc->codec_id != AV_CODEC_ID_PCM_S8 &&
161 enc->codec_id != AV_CODEC_ID_PCM_S16LE &&
162 enc->codec_id != AV_CODEC_ID_PCM_U8 &&
163 enc->codec_id != AV_CODEC_ID_PCM_U16LE) {
164 av_log(s, AV_LOG_ERROR, "%s codec not supported for Peak Chunk\n",
165 s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
169 wav->peak_bps = av_get_bits_per_sample(enc->codec_id) / 8;
171 if (wav->peak_bps == 1 && wav->peak_format == PEAK_FORMAT_UINT16) {
172 av_log(s, AV_LOG_ERROR,
173 "Writing 16 bit peak for 8 bit audio does not make sense\n");
174 return AVERROR(EINVAL);
177 wav->peak_maxpos = av_mallocz_array(enc->channels, sizeof(*wav->peak_maxpos));
178 wav->peak_maxneg = av_mallocz_array(enc->channels, sizeof(*wav->peak_maxneg));
179 wav->peak_output = av_malloc(PEAK_BUFFER_SIZE);
180 if (!wav->peak_maxpos || !wav->peak_maxneg || !wav->peak_output)
183 wav->peak_outbuf_size = PEAK_BUFFER_SIZE;
188 av_log(s, AV_LOG_ERROR, "Out of memory\n");
189 peak_free_buffers(s);
190 return AVERROR(ENOMEM);
193 static void peak_write_frame(AVFormatContext *s)
195 WAVMuxContext *wav = s->priv_data;
196 AVCodecContext *enc = s->streams[0]->codec;
200 if (!wav->peak_output)
203 for (c = 0; c < enc->channels; c++) {
204 wav->peak_maxneg[c] = -wav->peak_maxneg[c];
206 if (wav->peak_bps == 2 && wav->peak_format == PEAK_FORMAT_UINT8) {
207 wav->peak_maxpos[c] = wav->peak_maxpos[c] / 256;
208 wav->peak_maxneg[c] = wav->peak_maxneg[c] / 256;
211 if (wav->peak_ppv == 1)
212 wav->peak_maxpos[c] =
213 FFMAX(wav->peak_maxpos[c], wav->peak_maxneg[c]);
215 peak_of_peaks = FFMAX3(wav->peak_maxpos[c], wav->peak_maxneg[c],
217 if (peak_of_peaks > wav->peak_pop)
218 wav->peak_pos_pop = wav->peak_num_frames;
219 wav->peak_pop = peak_of_peaks;
221 if (wav->peak_outbuf_size - wav->peak_outbuf_bytes <
222 wav->peak_format * wav->peak_ppv) {
223 wav->peak_outbuf_size += PEAK_BUFFER_SIZE;
224 wav->peak_output = av_realloc(wav->peak_output,
225 wav->peak_outbuf_size);
226 if (!wav->peak_output) {
227 av_log(s, AV_LOG_ERROR, "No memory for peak data\n");
232 if (wav->peak_format == PEAK_FORMAT_UINT8) {
233 wav->peak_output[wav->peak_outbuf_bytes++] =
235 if (wav->peak_ppv == 2) {
236 wav->peak_output[wav->peak_outbuf_bytes++] =
240 AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
241 wav->peak_maxpos[c]);
242 wav->peak_outbuf_bytes += 2;
243 if (wav->peak_ppv == 2) {
244 AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
245 wav->peak_maxneg[c]);
246 wav->peak_outbuf_bytes += 2;
249 wav->peak_maxpos[c] = 0;
250 wav->peak_maxneg[c] = 0;
252 wav->peak_num_frames++;
255 static int peak_write_chunk(AVFormatContext *s)
257 WAVMuxContext *wav = s->priv_data;
258 AVIOContext *pb = s->pb;
259 AVCodecContext *enc = s->streams[0]->codec;
260 int64_t peak = ff_start_tag(s->pb, "levl");
265 /* Peak frame of incomplete block at end */
266 if (wav->peak_block_pos)
269 memset(timestamp, 0, sizeof(timestamp));
270 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
272 av_log(s, AV_LOG_INFO, "Writing local time and date to Peak Envelope Chunk\n");
274 now_secs = now0 / 1000000;
275 if (strftime(timestamp, sizeof(timestamp), "%Y:%m:%d:%H:%M:%S:", localtime_r(&now_secs, &tmpbuf))) {
276 av_strlcatf(timestamp, sizeof(timestamp), "%03d", (int)((now0 / 1000) % 1000));
278 av_log(s, AV_LOG_ERROR, "Failed to write timestamp\n");
283 avio_wl32(pb, 1); /* version */
284 avio_wl32(pb, wav->peak_format); /* 8 or 16 bit */
285 avio_wl32(pb, wav->peak_ppv); /* positive and negative */
286 avio_wl32(pb, wav->peak_block_size); /* frames per value */
287 avio_wl32(pb, enc->channels); /* number of channels */
288 avio_wl32(pb, wav->peak_num_frames); /* number of peak frames */
289 avio_wl32(pb, wav->peak_pos_pop); /* audio sample frame index */
290 avio_wl32(pb, 128); /* equal to size of header */
291 avio_write(pb, timestamp, 28); /* ASCII time stamp */
292 ffio_fill(pb, 0, 60);
294 avio_write(pb, wav->peak_output, wav->peak_outbuf_bytes);
296 ff_end_tag(pb, peak);
304 static int wav_write_header(AVFormatContext *s)
306 WAVMuxContext *wav = s->priv_data;
307 AVIOContext *pb = s->pb;
310 if (s->nb_streams != 1) {
311 av_log(s, AV_LOG_ERROR, "WAVE files have exactly one stream\n");
312 return AVERROR(EINVAL);
315 if (wav->rf64 == RF64_ALWAYS) {
316 ffio_wfourcc(pb, "RF64");
317 avio_wl32(pb, -1); /* RF64 chunk size: use size in ds64 */
319 ffio_wfourcc(pb, "RIFF");
320 avio_wl32(pb, -1); /* file length */
323 ffio_wfourcc(pb, "WAVE");
325 if (wav->rf64 != RF64_NEVER) {
326 /* write empty ds64 chunk or JUNK chunk to reserve space for ds64 */
327 ffio_wfourcc(pb, wav->rf64 == RF64_ALWAYS ? "ds64" : "JUNK");
328 avio_wl32(pb, 28); /* chunk size */
329 wav->ds64 = avio_tell(pb);
330 ffio_fill(pb, 0, 28);
333 if (wav->write_peak != 2) {
335 fmt = ff_start_tag(pb, "fmt ");
336 if (ff_put_wav_header(pb, s->streams[0]->codec, 0) < 0) {
337 const AVCodecDescriptor *desc = avcodec_descriptor_get(s->streams[0]->codec->codec_id);
338 av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
339 desc ? desc->name : "unknown");
340 return AVERROR(ENOSYS);
345 if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
346 && s->pb->seekable) {
347 wav->fact_pos = ff_start_tag(pb, "fact");
349 ff_end_tag(pb, wav->fact_pos);
353 bwf_write_bext_chunk(s);
355 if (wav->write_peak) {
357 if ((ret = peak_init_writer(s)) < 0)
361 avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
362 wav->maxpts = wav->last_duration = 0;
363 wav->minpts = INT64_MAX;
365 if (wav->write_peak != 2) {
367 ff_riff_write_info(s);
370 wav->data = ff_start_tag(pb, "data");
378 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
380 AVIOContext *pb = s->pb;
381 WAVMuxContext *wav = s->priv_data;
383 if (wav->write_peak != 2)
384 avio_write(pb, pkt->data, pkt->size);
386 if (wav->write_peak) {
389 for (i = 0; i < pkt->size; i += wav->peak_bps) {
390 if (wav->peak_bps == 1) {
391 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], *(int8_t*)(pkt->data + i));
392 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], *(int8_t*)(pkt->data + i));
394 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], (int16_t)AV_RL16(pkt->data + i));
395 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], (int16_t)AV_RL16(pkt->data + i));
397 if (++c == s->streams[0]->codec->channels) {
399 if (++wav->peak_block_pos == wav->peak_block_size) {
401 wav->peak_block_pos = 0;
407 if(pkt->pts != AV_NOPTS_VALUE) {
408 wav->minpts = FFMIN(wav->minpts, pkt->pts);
409 wav->maxpts = FFMAX(wav->maxpts, pkt->pts);
410 wav->last_duration = pkt->duration;
412 av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
416 static int wav_write_trailer(AVFormatContext *s)
418 AVIOContext *pb = s->pb;
419 WAVMuxContext *wav = s->priv_data;
420 int64_t file_size, data_size;
421 int64_t number_of_samples = 0;
427 if (s->pb->seekable) {
428 if (wav->write_peak != 2 && avio_tell(pb) - wav->data < UINT32_MAX) {
429 ff_end_tag(pb, wav->data);
433 if (wav->write_peak && wav->peak_output) {
434 ret = peak_write_chunk(s);
438 /* update file size */
439 file_size = avio_tell(pb);
440 data_size = file_size - wav->data;
441 if (wav->rf64 == RF64_ALWAYS || (wav->rf64 == RF64_AUTO && file_size - 8 > UINT32_MAX)) {
443 } else if (file_size - 8 <= UINT32_MAX) {
444 avio_seek(pb, 4, SEEK_SET);
445 avio_wl32(pb, (uint32_t)(file_size - 8));
446 avio_seek(pb, file_size, SEEK_SET);
450 av_log(s, AV_LOG_ERROR,
451 "Filesize %"PRId64" invalid for wav, output file will be broken\n",
455 number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
456 s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
457 s->streams[0]->time_base.den);
459 if(s->streams[0]->codec->codec_tag != 0x01) {
460 /* Update num_samps in fact chunk */
461 avio_seek(pb, wav->fact_pos, SEEK_SET);
462 if (rf64 || (wav->rf64 == RF64_AUTO && number_of_samples > UINT32_MAX)) {
466 avio_wl32(pb, number_of_samples);
467 avio_seek(pb, file_size, SEEK_SET);
473 /* overwrite RIFF with RF64 */
474 avio_seek(pb, 0, SEEK_SET);
475 ffio_wfourcc(pb, "RF64");
478 /* write ds64 chunk (overwrite JUNK if rf64 == RF64_AUTO) */
479 avio_seek(pb, wav->ds64 - 8, SEEK_SET);
480 ffio_wfourcc(pb, "ds64");
481 avio_wl32(pb, 28); /* ds64 chunk size */
482 avio_wl64(pb, file_size - 8); /* RF64 chunk size */
483 avio_wl64(pb, data_size); /* data chunk size */
484 avio_wl64(pb, number_of_samples); /* fact chunk number of samples */
485 avio_wl32(pb, 0); /* number of table entries for non-'data' chunks */
487 /* write -1 in data chunk size */
488 avio_seek(pb, wav->data - 4, SEEK_SET);
491 avio_seek(pb, file_size, SEEK_SET);
497 peak_free_buffers(s);
502 #define OFFSET(x) offsetof(WAVMuxContext, x)
503 #define ENC AV_OPT_FLAG_ENCODING_PARAM
504 static const AVOption options[] = {
505 { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, ENC },
506 { "write_peak", "Write Peak Envelope chunk.", OFFSET(write_peak), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, ENC, "peak" },
507 { "off", "Do not write peak chunk.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_OFF }, 0, 0, ENC, "peak" },
508 { "on", "Append peak chunk after wav data.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_ON }, 0, 0, ENC, "peak" },
509 { "only", "Write only peak chunk, omit wav data.", 0, AV_OPT_TYPE_CONST, { .i64 = PEAK_ONLY }, 0, 0, ENC, "peak" },
510 { "rf64", "Use RF64 header rather than RIFF for large files.", OFFSET(rf64), AV_OPT_TYPE_INT, { .i64 = RF64_NEVER },-1, 1, ENC, "rf64" },
511 { "auto", "Write RF64 header if file grows large enough.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_AUTO }, 0, 0, ENC, "rf64" },
512 { "always", "Always write RF64 header regardless of file size.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_ALWAYS }, 0, 0, ENC, "rf64" },
513 { "never", "Never write RF64 header regardless of file size.", 0, AV_OPT_TYPE_CONST, { .i64 = RF64_NEVER }, 0, 0, ENC, "rf64" },
514 { "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 },
515 { "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 },
516 { "peak_ppv", "Number of peak points per peak value (1 or 2).", OFFSET(peak_ppv), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, 2, ENC },
520 static const AVClass wav_muxer_class = {
521 .class_name = "WAV muxer",
522 .item_name = av_default_item_name,
524 .version = LIBAVUTIL_VERSION_INT,
527 AVOutputFormat ff_wav_muxer = {
529 .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
530 .mime_type = "audio/x-wav",
532 .priv_data_size = sizeof(WAVMuxContext),
533 .audio_codec = AV_CODEC_ID_PCM_S16LE,
534 .video_codec = AV_CODEC_ID_NONE,
535 .write_header = wav_write_header,
536 .write_packet = wav_write_packet,
537 .write_trailer = wav_write_trailer,
538 .flags = AVFMT_TS_NONSTRICT,
539 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
540 .priv_class = &wav_muxer_class,
542 #endif /* CONFIG_WAV_MUXER */
547 static void start_guid(AVIOContext *pb, const uint8_t *guid, int64_t *pos)
549 *pos = avio_tell(pb);
551 avio_write(pb, guid, 16);
552 avio_wl64(pb, INT64_MAX);
555 static void end_guid(AVIOContext *pb, int64_t start)
557 int64_t end, pos = avio_tell(pb);
559 end = FFALIGN(pos, 8);
560 ffio_fill(pb, 0, end - pos);
561 avio_seek(pb, start + 16, SEEK_SET);
562 avio_wl64(pb, end - start);
563 avio_seek(pb, end, SEEK_SET);
566 static int w64_write_header(AVFormatContext *s)
568 WAVMuxContext *wav = s->priv_data;
569 AVIOContext *pb = s->pb;
573 avio_write(pb, ff_w64_guid_riff, sizeof(ff_w64_guid_riff));
575 avio_write(pb, ff_w64_guid_wave, sizeof(ff_w64_guid_wave));
576 start_guid(pb, ff_w64_guid_fmt, &start);
577 if ((ret = ff_put_wav_header(pb, s->streams[0]->codec, 0)) < 0) {
578 av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
579 s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
584 if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
585 && s->pb->seekable) {
586 start_guid(pb, ff_w64_guid_fact, &wav->fact_pos);
588 end_guid(pb, wav->fact_pos);
591 start_guid(pb, ff_w64_guid_data, &wav->data);
596 static int w64_write_trailer(AVFormatContext *s)
598 AVIOContext *pb = s->pb;
599 WAVMuxContext *wav = s->priv_data;
603 end_guid(pb, wav->data);
605 file_size = avio_tell(pb);
606 avio_seek(pb, 16, SEEK_SET);
607 avio_wl64(pb, file_size);
609 if (s->streams[0]->codec->codec_tag != 0x01) {
610 int64_t number_of_samples;
612 number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
613 s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
614 s->streams[0]->time_base.den);
615 avio_seek(pb, wav->fact_pos + 24, SEEK_SET);
616 avio_wl64(pb, number_of_samples);
619 avio_seek(pb, file_size, SEEK_SET);
626 AVOutputFormat ff_w64_muxer = {
628 .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
630 .priv_data_size = sizeof(WAVMuxContext),
631 .audio_codec = AV_CODEC_ID_PCM_S16LE,
632 .video_codec = AV_CODEC_ID_NONE,
633 .write_header = w64_write_header,
634 .write_packet = wav_write_packet,
635 .write_trailer = w64_write_trailer,
636 .flags = AVFMT_TS_NONSTRICT,
637 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
639 #endif /* CONFIG_W64_MUXER */