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