]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_compand.c
Merge commit '48d1ed9c83ee0c388e8c2898e81ffb4add509ab9'
[ffmpeg] / libavfilter / af_compand.c
1 /*
2  * Copyright (c) 1999 Chris Bagwell
3  * Copyright (c) 1999 Nick Bailey
4  * Copyright (c) 2007 Rob Sykes <robs@users.sourceforge.net>
5  * Copyright (c) 2013 Paul B Mahol
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  */
24
25 #include "libavutil/avassert.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/samplefmt.h"
29 #include "avfilter.h"
30 #include "audio.h"
31 #include "internal.h"
32
33 typedef struct ChanParam {
34     double attack;
35     double decay;
36     double volume;
37 } ChanParam;
38
39 typedef struct CompandSegment {
40     double x, y;
41     double a, b;
42 } CompandSegment;
43
44 typedef struct CompandContext {
45     const AVClass *class;
46     char *attacks, *decays, *points;
47     CompandSegment *segments;
48     ChanParam *channels;
49     double in_min_lin;
50     double out_min_lin;
51     double curve_dB;
52     double gain_dB;
53     double initial_volume;
54     double delay;
55     uint8_t **delayptrs;
56     int delay_samples;
57     int delay_count;
58     int delay_index;
59     int64_t pts;
60
61     int (*compand)(AVFilterContext *ctx, AVFrame *frame);
62 } CompandContext;
63
64 #define OFFSET(x) offsetof(CompandContext, x)
65 #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
66
67 static const AVOption compand_options[] = {
68     { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
69     { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
70     { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
71     { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0.01}, 0.01, 900, A },
72     { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 900, A },
73     { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 0, A },
74     { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 20, A },
75     { NULL }
76 };
77
78 AVFILTER_DEFINE_CLASS(compand);
79
80 static av_cold int init(AVFilterContext *ctx)
81 {
82     CompandContext *s = ctx->priv;
83
84     if (!s->attacks || !s->decays || !s->points) {
85         av_log(ctx, AV_LOG_ERROR, "Missing attacks and/or decays and/or points.\n");
86         return AVERROR(EINVAL);
87     }
88
89     return 0;
90 }
91
92 static av_cold void uninit(AVFilterContext *ctx)
93 {
94     CompandContext *s = ctx->priv;
95
96     av_freep(&s->channels);
97     av_freep(&s->segments);
98     if (s->delayptrs)
99         av_freep(&s->delayptrs[0]);
100     av_freep(&s->delayptrs);
101 }
102
103 static int query_formats(AVFilterContext *ctx)
104 {
105     AVFilterChannelLayouts *layouts;
106     AVFilterFormats *formats;
107     static const enum AVSampleFormat sample_fmts[] = {
108         AV_SAMPLE_FMT_DBLP,
109         AV_SAMPLE_FMT_NONE
110     };
111
112     layouts = ff_all_channel_layouts();
113     if (!layouts)
114         return AVERROR(ENOMEM);
115     ff_set_common_channel_layouts(ctx, layouts);
116
117     formats = ff_make_format_list(sample_fmts);
118     if (!formats)
119         return AVERROR(ENOMEM);
120     ff_set_common_formats(ctx, formats);
121
122     formats = ff_all_samplerates();
123     if (!formats)
124         return AVERROR(ENOMEM);
125     ff_set_common_samplerates(ctx, formats);
126
127     return 0;
128 }
129
130 static void count_items(char *item_str, int *nb_items)
131 {
132     char *p;
133
134     *nb_items = 1;
135     for (p = item_str; *p; p++) {
136         if (*p == ' ')
137             (*nb_items)++;
138     }
139
140 }
141
142 static void update_volume(ChanParam *cp, double in)
143 {
144     double delta = in - cp->volume;
145
146     if (delta > 0.0)
147         cp->volume += delta * cp->attack;
148     else
149         cp->volume += delta * cp->decay;
150 }
151
152 static double get_volume(CompandContext *s, double in_lin)
153 {
154     CompandSegment *cs;
155     double in_log, out_log;
156     int i;
157
158     if (in_lin < s->in_min_lin)
159         return s->out_min_lin;
160
161     in_log = log(in_lin);
162
163     for (i = 1;; i++)
164         if (in_log <= s->segments[i + 1].x)
165             break;
166
167     cs = &s->segments[i];
168     in_log -= cs->x;
169     out_log = cs->y + in_log * (cs->a * in_log + cs->b);
170
171     return exp(out_log);
172 }
173
174 static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
175 {
176     CompandContext *s = ctx->priv;
177     AVFilterLink *inlink = ctx->inputs[0];
178     const int channels = inlink->channels;
179     const int nb_samples = frame->nb_samples;
180     AVFrame *out_frame;
181     int chan, i;
182
183     if (av_frame_is_writable(frame)) {
184         out_frame = frame;
185     } else {
186         out_frame = ff_get_audio_buffer(inlink, nb_samples);
187         if (!out_frame) {
188             av_frame_free(&frame);
189             return AVERROR(ENOMEM);
190         }
191         av_frame_copy_props(out_frame, frame);
192     }
193
194     for (chan = 0; chan < channels; chan++) {
195         const double *src = (double *)frame->extended_data[chan];
196         double *dst = (double *)out_frame->extended_data[chan];
197         ChanParam *cp = &s->channels[chan];
198
199         for (i = 0; i < nb_samples; i++) {
200             update_volume(cp, fabs(src[i]));
201
202             dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
203         }
204     }
205
206     if (frame != out_frame)
207         av_frame_free(&frame);
208
209     return ff_filter_frame(ctx->outputs[0], out_frame);
210 }
211
212 #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
213
214 static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
215 {
216     CompandContext *s = ctx->priv;
217     AVFilterLink *inlink = ctx->inputs[0];
218     const int channels = inlink->channels;
219     const int nb_samples = frame->nb_samples;
220     int chan, i, av_uninit(dindex), oindex, av_uninit(count);
221     AVFrame *out_frame = NULL;
222
223     av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
224
225     for (chan = 0; chan < channels; chan++) {
226         const double *src = (double *)frame->extended_data[chan];
227         double *dbuf = (double *)s->delayptrs[chan];
228         ChanParam *cp = &s->channels[chan];
229         double *dst;
230
231         count  = s->delay_count;
232         dindex = s->delay_index;
233         for (i = 0, oindex = 0; i < nb_samples; i++) {
234             const double in = src[i];
235             update_volume(cp, fabs(in));
236
237             if (count >= s->delay_samples) {
238                 if (!out_frame) {
239                     out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
240                     if (!out_frame) {
241                         av_frame_free(&frame);
242                         return AVERROR(ENOMEM);
243                     }
244                     av_frame_copy_props(out_frame, frame);
245                     out_frame->pts = s->pts;
246                     s->pts += av_rescale_q(nb_samples - i, (AVRational){1, inlink->sample_rate}, inlink->time_base);
247                 }
248
249                 dst = (double *)out_frame->extended_data[chan];
250                 dst[oindex++] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
251             } else {
252                 count++;
253             }
254
255             dbuf[dindex] = in;
256             dindex = MOD(dindex + 1, s->delay_samples);
257         }
258     }
259
260     s->delay_count = count;
261     s->delay_index = dindex;
262
263     av_frame_free(&frame);
264     return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
265 }
266
267 static int compand_drain(AVFilterLink *outlink)
268 {
269     AVFilterContext *ctx = outlink->src;
270     CompandContext *s = ctx->priv;
271     const int channels = outlink->channels;
272     int chan, i, dindex;
273     AVFrame *frame = NULL;
274
275     frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
276     if (!frame)
277         return AVERROR(ENOMEM);
278     frame->pts = s->pts;
279     s->pts += av_rescale_q(frame->nb_samples, (AVRational){1, outlink->sample_rate}, outlink->time_base);
280
281     for (chan = 0; chan < channels; chan++) {
282         double *dbuf = (double *)s->delayptrs[chan];
283         double *dst = (double *)frame->extended_data[chan];
284         ChanParam *cp = &s->channels[chan];
285
286         dindex = s->delay_index;
287         for (i = 0; i < frame->nb_samples; i++) {
288             dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
289             dindex = MOD(dindex + 1, s->delay_samples);
290         }
291     }
292     s->delay_count -= frame->nb_samples;
293     s->delay_index = dindex;
294
295     return ff_filter_frame(outlink, frame);
296 }
297
298 static int config_output(AVFilterLink *outlink)
299 {
300     AVFilterContext *ctx = outlink->src;
301     CompandContext *s = ctx->priv;
302     const int sample_rate = outlink->sample_rate;
303     double radius = s->curve_dB * M_LN10 / 20;
304     int nb_attacks, nb_decays, nb_points;
305     char *p, *saveptr = NULL;
306     int new_nb_items, num;
307     int i;
308
309     count_items(s->attacks, &nb_attacks);
310     count_items(s->decays, &nb_decays);
311     count_items(s->points, &nb_points);
312
313     if ((nb_attacks > outlink->channels) || (nb_decays > outlink->channels)) {
314         av_log(ctx, AV_LOG_ERROR, "Number of attacks/decays bigger than number of channels.\n");
315         return AVERROR(EINVAL);
316     }
317
318     uninit(ctx);
319
320     s->channels = av_mallocz_array(outlink->channels, sizeof(*s->channels));
321     s->segments = av_mallocz_array((nb_points + 4) * 2, sizeof(*s->segments));
322
323     if (!s->channels || !s->segments)
324         return AVERROR(ENOMEM);
325
326     p = s->attacks;
327     for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
328         char *tstr = av_strtok(p, " ", &saveptr);
329         p = NULL;
330         new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
331         if (s->channels[i].attack < 0)
332             return AVERROR(EINVAL);
333     }
334     nb_attacks = new_nb_items;
335
336     p = s->decays;
337     for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
338         char *tstr = av_strtok(p, " ", &saveptr);
339         p = NULL;
340         new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
341         if (s->channels[i].decay < 0)
342             return AVERROR(EINVAL);
343     }
344     nb_decays = new_nb_items;
345
346     if (nb_attacks != nb_decays) {
347         av_log(ctx, AV_LOG_ERROR, "Number of attacks %d differs from number of decays %d.\n", nb_attacks, nb_decays);
348         return AVERROR(EINVAL);
349     }
350
351 #define S(x) s->segments[2 * ((x) + 1)]
352     p = s->points;
353     for (i = 0, new_nb_items = 0; i < nb_points; i++) {
354         char *tstr = av_strtok(p, " ", &saveptr);
355         p = NULL;
356         if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
357             av_log(ctx, AV_LOG_ERROR, "Invalid and/or missing input/output value.\n");
358             return AVERROR(EINVAL);
359         }
360         if (i && S(i - 1).x > S(i).x) {
361             av_log(ctx, AV_LOG_ERROR, "Transfer function input values must be increasing.\n");
362             return AVERROR(EINVAL);
363         }
364         S(i).y -= S(i).x;
365         av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
366         new_nb_items++;
367     }
368     num = new_nb_items;
369
370     /* Add 0,0 if necessary */
371     if (num == 0 || S(num - 1).x)
372         num++;
373
374 #undef S
375 #define S(x) s->segments[2 * (x)]
376     /* Add a tail off segment at the start */
377     S(0).x = S(1).x - 2 * s->curve_dB;
378     S(0).y = S(1).y;
379     num++;
380
381     /* Join adjacent colinear segments */
382     for (i = 2; i < num; i++) {
383         double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
384         double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
385         int j;
386
387         if (fabs(g1 - g2))
388             continue;
389         num--;
390         for (j = --i; j < num; j++)
391             S(j) = S(j + 1);
392     }
393
394     for (i = 0; !i || s->segments[i - 2].x; i += 2) {
395         s->segments[i].y += s->gain_dB;
396         s->segments[i].x *= M_LN10 / 20;
397         s->segments[i].y *= M_LN10 / 20;
398     }
399
400 #define L(x) s->segments[i - (x)]
401     for (i = 4; s->segments[i - 2].x; i += 2) {
402         double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
403
404         L(4).a = 0;
405         L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
406
407         L(2).a = 0;
408         L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
409
410         theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
411         len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
412         r = FFMIN(radius, len);
413         L(3).x = L(2).x - r * cos(theta);
414         L(3).y = L(2).y - r * sin(theta);
415
416         theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
417         len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
418         r = FFMIN(radius, len / 2);
419         x = L(2).x + r * cos(theta);
420         y = L(2).y + r * sin(theta);
421
422         cx = (L(3).x + L(2).x + x) / 3;
423         cy = (L(3).y + L(2).y + y) / 3;
424
425         L(2).x = x;
426         L(2).y = y;
427
428         in1 = cx - L(3).x;
429         out1 = cy - L(3).y;
430         in2 = L(2).x - L(3).x;
431         out2 = L(2).y - L(3).y;
432         L(3).a = (out2 / in2 - out1 / in1) / (in2-in1);
433         L(3).b = out1 / in1 - L(3).a * in1;
434     }
435     L(3).x = 0;
436     L(3).y = L(2).y;
437
438     s->in_min_lin  = exp(s->segments[1].x);
439     s->out_min_lin = exp(s->segments[1].y);
440
441     for (i = 0; i < outlink->channels; i++) {
442         ChanParam *cp = &s->channels[i];
443
444         if (cp->attack > 1.0 / sample_rate)
445             cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
446         else
447             cp->attack = 1.0;
448         if (cp->decay > 1.0 / sample_rate)
449             cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
450         else
451             cp->decay = 1.0;
452         cp->volume = pow(10.0, s->initial_volume / 20);
453     }
454
455     s->delay_samples = s->delay * sample_rate;
456     if (s->delay_samples > 0) {
457         int ret;
458         if ((ret = av_samples_alloc_array_and_samples(&s->delayptrs, NULL,
459                                                       outlink->channels,
460                                                       s->delay_samples,
461                                                       outlink->format, 0)) < 0)
462             return ret;
463         s->compand = compand_delay;
464         outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
465     } else {
466         s->compand = compand_nodelay;
467     }
468     return 0;
469 }
470
471 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
472 {
473     AVFilterContext *ctx = inlink->dst;
474     CompandContext *s = ctx->priv;
475
476     return s->compand(ctx, frame);
477 }
478
479 static int request_frame(AVFilterLink *outlink)
480 {
481     AVFilterContext *ctx = outlink->src;
482     CompandContext *s = ctx->priv;
483     int ret;
484
485     ret = ff_request_frame(ctx->inputs[0]);
486
487     if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
488         ret = compand_drain(outlink);
489
490     return ret;
491 }
492
493 static const AVFilterPad compand_inputs[] = {
494     {
495         .name         = "default",
496         .type         = AVMEDIA_TYPE_AUDIO,
497         .filter_frame = filter_frame,
498     },
499     { NULL }
500 };
501
502 static const AVFilterPad compand_outputs[] = {
503     {
504         .name          = "default",
505         .request_frame = request_frame,
506         .config_props  = config_output,
507         .type          = AVMEDIA_TYPE_AUDIO,
508     },
509     { NULL }
510 };
511
512 AVFilter ff_af_compand = {
513     .name          = "compand",
514     .description   = NULL_IF_CONFIG_SMALL("Compress or expand audio dynamic range."),
515     .query_formats = query_formats,
516     .priv_size     = sizeof(CompandContext),
517     .priv_class    = &compand_class,
518     .init          = init,
519     .uninit        = uninit,
520     .inputs        = compand_inputs,
521     .outputs       = compand_outputs,
522 };