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