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