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