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