1 /*
2 * Copyright (c) 2011 Stefano Sabatini
3 * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 /**
23 * @file
24 * audio volume filter
25 */
26
27 #include "libavutil/channel_layout.h"
28 #include "libavutil/common.h"
29 #include "libavutil/eval.h"
30 #include "libavutil/ffmath.h"
31 #include "libavutil/float_dsp.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/replaygain.h"
35
36 #include "audio.h"
37 #include "avfilter.h"
38 #include "formats.h"
39 #include "internal.h"
40 #include "af_volume.h"
41
42 static const char * const precision_str[] = {
43 "fixed", "float", "double"
44 };
45
46 static const char *const var_names[] = {
47 "n", ///< frame number (starting at zero)
48 "nb_channels", ///< number of channels
49 "nb_consumed_samples", ///< number of samples consumed by the filter
50 "nb_samples", ///< number of samples in the current frame
51 "pos", ///< position in the file of the frame
52 "pts", ///< frame presentation timestamp
53 "sample_rate", ///< sample rate
54 "startpts", ///< PTS at start of stream
55 "startt", ///< time at start of stream
56 "t", ///< time in the file of the frame
57 "tb", ///< timebase
58 "volume", ///< last set value
59 NULL
60 };
61
62 #define OFFSET(x) offsetof(VolumeContext, x)
63 #define A AV_OPT_FLAG_AUDIO_PARAM
64 #define F AV_OPT_FLAG_FILTERING_PARAM
65 #define T AV_OPT_FLAG_RUNTIME_PARAM
66
67 static const AVOption volume_options[] = {
68 { "volume", "set volume adjustment expression",
69 OFFSET(volume_expr), AV_OPT_TYPE_STRING, { .str = "1.0" }, .flags = A|F|T },
70 { "precision", "select mathematical precision",
71 OFFSET(precision), AV_OPT_TYPE_INT, { .i64 = PRECISION_FLOAT }, PRECISION_FIXED, PRECISION_DOUBLE, A|F, "precision" },
72 { "fixed", "select 8-bit fixed-point", 0, AV_OPT_TYPE_CONST, { .i64 = PRECISION_FIXED }, INT_MIN, INT_MAX, A|F, "precision" },
73 { "float", "select 32-bit floating-point", 0, AV_OPT_TYPE_CONST, { .i64 = PRECISION_FLOAT }, INT_MIN, INT_MAX, A|F, "precision" },
74 { "double", "select 64-bit floating-point", 0, AV_OPT_TYPE_CONST, { .i64 = PRECISION_DOUBLE }, INT_MIN, INT_MAX, A|F, "precision" },
75 { "eval", "specify when to evaluate expressions", OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_ONCE}, 0, EVAL_MODE_NB-1, .flags = A|F, "eval" },
76 { "once", "eval volume expression once", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_ONCE}, .flags = A|F, .unit = "eval" },
77 { "frame", "eval volume expression per-frame", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = A|F, .unit = "eval" },
78 { "replaygain", "Apply replaygain side data when present",
79 OFFSET(replaygain), AV_OPT_TYPE_INT, { .i64 = REPLAYGAIN_DROP }, REPLAYGAIN_DROP, REPLAYGAIN_ALBUM, A|F, "replaygain" },
80 { "drop", "replaygain side data is dropped", 0, AV_OPT_TYPE_CONST, { .i64 = REPLAYGAIN_DROP }, 0, 0, A|F, "replaygain" },
81 { "ignore", "replaygain side data is ignored", 0, AV_OPT_TYPE_CONST, { .i64 = REPLAYGAIN_IGNORE }, 0, 0, A|F, "replaygain" },
82 { "track", "track gain is preferred", 0, AV_OPT_TYPE_CONST, { .i64 = REPLAYGAIN_TRACK }, 0, 0, A|F, "replaygain" },
83 { "album", "album gain is preferred", 0, AV_OPT_TYPE_CONST, { .i64 = REPLAYGAIN_ALBUM }, 0, 0, A|F, "replaygain" },
84 { "replaygain_preamp", "Apply replaygain pre-amplification",
85 OFFSET(replaygain_preamp), AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, -15.0, 15.0, A|F },
86 { "replaygain_noclip", "Apply replaygain clipping prevention",
87 OFFSET(replaygain_noclip), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, A|F },
88 { NULL }
89 };
90
91 AVFILTER_DEFINE_CLASS(volume);
92
set_expr(AVExpr ** pexpr,const char * expr,void * log_ctx)93 static int set_expr(AVExpr **pexpr, const char *expr, void *log_ctx)
94 {
95 int ret;
96 AVExpr *old = NULL;
97
98 if (*pexpr)
99 old = *pexpr;
100 ret = av_expr_parse(pexpr, expr, var_names,
101 NULL, NULL, NULL, NULL, 0, log_ctx);
102 if (ret < 0) {
103 av_log(log_ctx, AV_LOG_ERROR,
104 "Error when evaluating the volume expression '%s'\n", expr);
105 *pexpr = old;
106 return ret;
107 }
108
109 av_expr_free(old);
110 return 0;
111 }
112
init(AVFilterContext * ctx)113 static av_cold int init(AVFilterContext *ctx)
114 {
115 VolumeContext *vol = ctx->priv;
116
117 vol->fdsp = avpriv_float_dsp_alloc(0);
118 if (!vol->fdsp)
119 return AVERROR(ENOMEM);
120
121 return set_expr(&vol->volume_pexpr, vol->volume_expr, ctx);
122 }
123
uninit(AVFilterContext * ctx)124 static av_cold void uninit(AVFilterContext *ctx)
125 {
126 VolumeContext *vol = ctx->priv;
127 av_expr_free(vol->volume_pexpr);
128 av_opt_free(vol);
129 av_freep(&vol->fdsp);
130 }
131
query_formats(AVFilterContext * ctx)132 static int query_formats(AVFilterContext *ctx)
133 {
134 VolumeContext *vol = ctx->priv;
135 static const enum AVSampleFormat sample_fmts[][7] = {
136 [PRECISION_FIXED] = {
137 AV_SAMPLE_FMT_U8,
138 AV_SAMPLE_FMT_U8P,
139 AV_SAMPLE_FMT_S16,
140 AV_SAMPLE_FMT_S16P,
141 AV_SAMPLE_FMT_S32,
142 AV_SAMPLE_FMT_S32P,
143 AV_SAMPLE_FMT_NONE
144 },
145 [PRECISION_FLOAT] = {
146 AV_SAMPLE_FMT_FLT,
147 AV_SAMPLE_FMT_FLTP,
148 AV_SAMPLE_FMT_NONE
149 },
150 [PRECISION_DOUBLE] = {
151 AV_SAMPLE_FMT_DBL,
152 AV_SAMPLE_FMT_DBLP,
153 AV_SAMPLE_FMT_NONE
154 }
155 };
156 int ret = ff_set_common_all_channel_counts(ctx);
157 if (ret < 0)
158 return ret;
159
160 ret = ff_set_common_formats_from_list(ctx, sample_fmts[vol->precision]);
161 if (ret < 0)
162 return ret;
163
164 return ff_set_common_all_samplerates(ctx);
165 }
166
scale_samples_u8(uint8_t * dst,const uint8_t * src,int nb_samples,int volume)167 static inline void scale_samples_u8(uint8_t *dst, const uint8_t *src,
168 int nb_samples, int volume)
169 {
170 int i;
171 for (i = 0; i < nb_samples; i++)
172 dst[i] = av_clip_uint8(((((int64_t)src[i] - 128) * volume + 128) >> 8) + 128);
173 }
174
scale_samples_u8_small(uint8_t * dst,const uint8_t * src,int nb_samples,int volume)175 static inline void scale_samples_u8_small(uint8_t *dst, const uint8_t *src,
176 int nb_samples, int volume)
177 {
178 int i;
179 for (i = 0; i < nb_samples; i++)
180 dst[i] = av_clip_uint8((((src[i] - 128) * volume + 128) >> 8) + 128);
181 }
182
scale_samples_s16(uint8_t * dst,const uint8_t * src,int nb_samples,int volume)183 static inline void scale_samples_s16(uint8_t *dst, const uint8_t *src,
184 int nb_samples, int volume)
185 {
186 int i;
187 int16_t *smp_dst = (int16_t *)dst;
188 const int16_t *smp_src = (const int16_t *)src;
189 for (i = 0; i < nb_samples; i++)
190 smp_dst[i] = av_clip_int16(((int64_t)smp_src[i] * volume + 128) >> 8);
191 }
192
scale_samples_s16_small(uint8_t * dst,const uint8_t * src,int nb_samples,int volume)193 static inline void scale_samples_s16_small(uint8_t *dst, const uint8_t *src,
194 int nb_samples, int volume)
195 {
196 int i;
197 int16_t *smp_dst = (int16_t *)dst;
198 const int16_t *smp_src = (const int16_t *)src;
199 for (i = 0; i < nb_samples; i++)
200 smp_dst[i] = av_clip_int16((smp_src[i] * volume + 128) >> 8);
201 }
202
scale_samples_s32(uint8_t * dst,const uint8_t * src,int nb_samples,int volume)203 static inline void scale_samples_s32(uint8_t *dst, const uint8_t *src,
204 int nb_samples, int volume)
205 {
206 int i;
207 int32_t *smp_dst = (int32_t *)dst;
208 const int32_t *smp_src = (const int32_t *)src;
209 for (i = 0; i < nb_samples; i++)
210 smp_dst[i] = av_clipl_int32((((int64_t)smp_src[i] * volume + 128) >> 8));
211 }
212
volume_init(VolumeContext * vol)213 static av_cold void volume_init(VolumeContext *vol)
214 {
215 vol->samples_align = 1;
216
217 switch (av_get_packed_sample_fmt(vol->sample_fmt)) {
218 case AV_SAMPLE_FMT_U8:
219 if (vol->volume_i < 0x1000000)
220 vol->scale_samples = scale_samples_u8_small;
221 else
222 vol->scale_samples = scale_samples_u8;
223 break;
224 case AV_SAMPLE_FMT_S16:
225 if (vol->volume_i < 0x10000)
226 vol->scale_samples = scale_samples_s16_small;
227 else
228 vol->scale_samples = scale_samples_s16;
229 break;
230 case AV_SAMPLE_FMT_S32:
231 vol->scale_samples = scale_samples_s32;
232 break;
233 case AV_SAMPLE_FMT_FLT:
234 vol->samples_align = 4;
235 break;
236 case AV_SAMPLE_FMT_DBL:
237 vol->samples_align = 8;
238 break;
239 }
240
241 #if ARCH_X86
242 ff_volume_init_x86(vol);
243 #endif
244 }
245
set_volume(AVFilterContext * ctx)246 static int set_volume(AVFilterContext *ctx)
247 {
248 VolumeContext *vol = ctx->priv;
249
250 vol->volume = av_expr_eval(vol->volume_pexpr, vol->var_values, NULL);
251 if (isnan(vol->volume)) {
252 if (vol->eval_mode == EVAL_MODE_ONCE) {
253 av_log(ctx, AV_LOG_ERROR, "Invalid value NaN for volume\n");
254 return AVERROR(EINVAL);
255 } else {
256 av_log(ctx, AV_LOG_WARNING, "Invalid value NaN for volume, setting to 0\n");
257 vol->volume = 0;
258 }
259 }
260 vol->var_values[VAR_VOLUME] = vol->volume;
261
262 av_log(ctx, AV_LOG_VERBOSE, "n:%f t:%f pts:%f precision:%s ",
263 vol->var_values[VAR_N], vol->var_values[VAR_T], vol->var_values[VAR_PTS],
264 precision_str[vol->precision]);
265
266 if (vol->precision == PRECISION_FIXED) {
267 vol->volume_i = (int)(vol->volume * 256 + 0.5);
268 vol->volume = vol->volume_i / 256.0;
269 av_log(ctx, AV_LOG_VERBOSE, "volume_i:%d/255 ", vol->volume_i);
270 }
271 av_log(ctx, AV_LOG_VERBOSE, "volume:%f volume_dB:%f\n",
272 vol->volume, 20.0*log10(vol->volume));
273
274 volume_init(vol);
275 return 0;
276 }
277
config_output(AVFilterLink * outlink)278 static int config_output(AVFilterLink *outlink)
279 {
280 AVFilterContext *ctx = outlink->src;
281 VolumeContext *vol = ctx->priv;
282 AVFilterLink *inlink = ctx->inputs[0];
283
284 vol->sample_fmt = inlink->format;
285 vol->channels = inlink->ch_layout.nb_channels;
286 vol->planes = av_sample_fmt_is_planar(inlink->format) ? vol->channels : 1;
287
288 vol->var_values[VAR_N] =
289 vol->var_values[VAR_NB_CONSUMED_SAMPLES] =
290 vol->var_values[VAR_NB_SAMPLES] =
291 vol->var_values[VAR_POS] =
292 vol->var_values[VAR_PTS] =
293 vol->var_values[VAR_STARTPTS] =
294 vol->var_values[VAR_STARTT] =
295 vol->var_values[VAR_T] =
296 vol->var_values[VAR_VOLUME] = NAN;
297
298 vol->var_values[VAR_NB_CHANNELS] = inlink->ch_layout.nb_channels;
299 vol->var_values[VAR_TB] = av_q2d(inlink->time_base);
300 vol->var_values[VAR_SAMPLE_RATE] = inlink->sample_rate;
301
302 av_log(inlink->src, AV_LOG_VERBOSE, "tb:%f sample_rate:%f nb_channels:%f\n",
303 vol->var_values[VAR_TB],
304 vol->var_values[VAR_SAMPLE_RATE],
305 vol->var_values[VAR_NB_CHANNELS]);
306
307 return set_volume(ctx);
308 }
309
process_command(AVFilterContext * ctx,const char * cmd,const char * args,char * res,int res_len,int flags)310 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
311 char *res, int res_len, int flags)
312 {
313 VolumeContext *vol = ctx->priv;
314 int ret = AVERROR(ENOSYS);
315
316 if (!strcmp(cmd, "volume")) {
317 if ((ret = set_expr(&vol->volume_pexpr, args, ctx)) < 0)
318 return ret;
319 if (vol->eval_mode == EVAL_MODE_ONCE)
320 set_volume(ctx);
321 }
322
323 return ret;
324 }
325
filter_frame(AVFilterLink * inlink,AVFrame * buf)326 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
327 {
328 AVFilterContext *ctx = inlink->dst;
329 VolumeContext *vol = inlink->dst->priv;
330 AVFilterLink *outlink = inlink->dst->outputs[0];
331 int nb_samples = buf->nb_samples;
332 AVFrame *out_buf;
333 int64_t pos;
334 AVFrameSideData *sd = av_frame_get_side_data(buf, AV_FRAME_DATA_REPLAYGAIN);
335 int ret;
336
337 if (sd && vol->replaygain != REPLAYGAIN_IGNORE) {
338 if (vol->replaygain != REPLAYGAIN_DROP) {
339 AVReplayGain *replaygain = (AVReplayGain*)sd->data;
340 int32_t gain = 100000;
341 uint32_t peak = 100000;
342 float g, p;
343
344 if (vol->replaygain == REPLAYGAIN_TRACK &&
345 replaygain->track_gain != INT32_MIN) {
346 gain = replaygain->track_gain;
347
348 if (replaygain->track_peak != 0)
349 peak = replaygain->track_peak;
350 } else if (replaygain->album_gain != INT32_MIN) {
351 gain = replaygain->album_gain;
352
353 if (replaygain->album_peak != 0)
354 peak = replaygain->album_peak;
355 } else {
356 av_log(inlink->dst, AV_LOG_WARNING, "Both ReplayGain gain "
357 "values are unknown.\n");
358 }
359 g = gain / 100000.0f;
360 p = peak / 100000.0f;
361
362 av_log(inlink->dst, AV_LOG_VERBOSE,
363 "Using gain %f dB from replaygain side data.\n", g);
364
365 vol->volume = ff_exp10((g + vol->replaygain_preamp) / 20);
366 if (vol->replaygain_noclip)
367 vol->volume = FFMIN(vol->volume, 1.0 / p);
368 vol->volume_i = (int)(vol->volume * 256 + 0.5);
369
370 volume_init(vol);
371 }
372 av_frame_remove_side_data(buf, AV_FRAME_DATA_REPLAYGAIN);
373 }
374
375 if (isnan(vol->var_values[VAR_STARTPTS])) {
376 vol->var_values[VAR_STARTPTS] = TS2D(buf->pts);
377 vol->var_values[VAR_STARTT ] = TS2T(buf->pts, inlink->time_base);
378 }
379 vol->var_values[VAR_PTS] = TS2D(buf->pts);
380 vol->var_values[VAR_T ] = TS2T(buf->pts, inlink->time_base);
381 vol->var_values[VAR_N ] = inlink->frame_count_out;
382
383 pos = buf->pkt_pos;
384 vol->var_values[VAR_POS] = pos == -1 ? NAN : pos;
385 if (vol->eval_mode == EVAL_MODE_FRAME)
386 set_volume(ctx);
387
388 if (vol->volume == 1.0 || vol->volume_i == 256) {
389 out_buf = buf;
390 goto end;
391 }
392
393 /* do volume scaling in-place if input buffer is writable */
394 if (av_frame_is_writable(buf)
395 && (vol->precision != PRECISION_FIXED || vol->volume_i > 0)) {
396 out_buf = buf;
397 } else {
398 out_buf = ff_get_audio_buffer(outlink, nb_samples);
399 if (!out_buf) {
400 av_frame_free(&buf);
401 return AVERROR(ENOMEM);
402 }
403 ret = av_frame_copy_props(out_buf, buf);
404 if (ret < 0) {
405 av_frame_free(&out_buf);
406 av_frame_free(&buf);
407 return ret;
408 }
409 }
410
411 if (vol->precision != PRECISION_FIXED || vol->volume_i > 0) {
412 int p, plane_samples;
413
414 if (av_sample_fmt_is_planar(buf->format))
415 plane_samples = FFALIGN(nb_samples, vol->samples_align);
416 else
417 plane_samples = FFALIGN(nb_samples * vol->channels, vol->samples_align);
418
419 if (vol->precision == PRECISION_FIXED) {
420 for (p = 0; p < vol->planes; p++) {
421 vol->scale_samples(out_buf->extended_data[p],
422 buf->extended_data[p], plane_samples,
423 vol->volume_i);
424 }
425 } else if (av_get_packed_sample_fmt(vol->sample_fmt) == AV_SAMPLE_FMT_FLT) {
426 for (p = 0; p < vol->planes; p++) {
427 vol->fdsp->vector_fmul_scalar((float *)out_buf->extended_data[p],
428 (const float *)buf->extended_data[p],
429 vol->volume, plane_samples);
430 }
431 } else {
432 for (p = 0; p < vol->planes; p++) {
433 vol->fdsp->vector_dmul_scalar((double *)out_buf->extended_data[p],
434 (const double *)buf->extended_data[p],
435 vol->volume, plane_samples);
436 }
437 }
438 }
439
440 emms_c();
441
442 if (buf != out_buf)
443 av_frame_free(&buf);
444
445 end:
446 vol->var_values[VAR_NB_CONSUMED_SAMPLES] += out_buf->nb_samples;
447 return ff_filter_frame(outlink, out_buf);
448 }
449
450 static const AVFilterPad avfilter_af_volume_inputs[] = {
451 {
452 .name = "default",
453 .type = AVMEDIA_TYPE_AUDIO,
454 .filter_frame = filter_frame,
455 },
456 };
457
458 static const AVFilterPad avfilter_af_volume_outputs[] = {
459 {
460 .name = "default",
461 .type = AVMEDIA_TYPE_AUDIO,
462 .config_props = config_output,
463 },
464 };
465
466 const AVFilter ff_af_volume = {
467 .name = "volume",
468 .description = NULL_IF_CONFIG_SMALL("Change input volume."),
469 .priv_size = sizeof(VolumeContext),
470 .priv_class = &volume_class,
471 .init = init,
472 .uninit = uninit,
473 FILTER_INPUTS(avfilter_af_volume_inputs),
474 FILTER_OUTPUTS(avfilter_af_volume_outputs),
475 FILTER_QUERY_FUNC(query_formats),
476 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
477 .process_command = process_command,
478 };
479