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