]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_dynaudnorm.c
avfilter/af_dynaudnorm: implement threshold option
[ffmpeg] / libavfilter / af_dynaudnorm.c
1 /*
2  * Dynamic Audio Normalizer
3  * Copyright (c) 2015 LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Dynamic Audio Normalizer
25  */
26
27 #include <float.h>
28
29 #include "libavutil/avassert.h"
30 #include "libavutil/opt.h"
31
32 #define FF_BUFQUEUE_SIZE 302
33 #include "libavfilter/bufferqueue.h"
34
35 #include "audio.h"
36 #include "avfilter.h"
37 #include "filters.h"
38 #include "internal.h"
39
40 typedef struct local_gain {
41     double max_gain;
42     double threshold;
43 } local_gain;
44
45 typedef struct cqueue {
46     double *elements;
47     int size;
48     int nb_elements;
49     int first;
50 } cqueue;
51
52 typedef struct DynamicAudioNormalizerContext {
53     const AVClass *class;
54
55     struct FFBufQueue queue;
56
57     int frame_len;
58     int frame_len_msec;
59     int filter_size;
60     int dc_correction;
61     int channels_coupled;
62     int alt_boundary_mode;
63
64     double peak_value;
65     double max_amplification;
66     double target_rms;
67     double compress_factor;
68     double threshold;
69     double *prev_amplification_factor;
70     double *dc_correction_value;
71     double *compress_threshold;
72     double *fade_factors[2];
73     double *weights;
74
75     int channels;
76     int eof;
77     int64_t pts;
78
79     cqueue **gain_history_original;
80     cqueue **gain_history_minimum;
81     cqueue **gain_history_smoothed;
82     cqueue **threshold_history;
83
84     cqueue *is_enabled;
85 } DynamicAudioNormalizerContext;
86
87 #define OFFSET(x) offsetof(DynamicAudioNormalizerContext, x)
88 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
89
90 static const AVOption dynaudnorm_options[] = {
91     { "framelen",    "set the frame length in msec",     OFFSET(frame_len_msec),    AV_OPT_TYPE_INT,    {.i64 = 500},   10,  8000, FLAGS },
92     { "f",           "set the frame length in msec",     OFFSET(frame_len_msec),    AV_OPT_TYPE_INT,    {.i64 = 500},   10,  8000, FLAGS },
93     { "gausssize",   "set the filter size",              OFFSET(filter_size),       AV_OPT_TYPE_INT,    {.i64 = 31},     3,   301, FLAGS },
94     { "g",           "set the filter size",              OFFSET(filter_size),       AV_OPT_TYPE_INT,    {.i64 = 31},     3,   301, FLAGS },
95     { "peak",        "set the peak value",               OFFSET(peak_value),        AV_OPT_TYPE_DOUBLE, {.dbl = 0.95}, 0.0,   1.0, FLAGS },
96     { "p",           "set the peak value",               OFFSET(peak_value),        AV_OPT_TYPE_DOUBLE, {.dbl = 0.95}, 0.0,   1.0, FLAGS },
97     { "maxgain",     "set the max amplification",        OFFSET(max_amplification), AV_OPT_TYPE_DOUBLE, {.dbl = 10.0}, 1.0, 100.0, FLAGS },
98     { "m",           "set the max amplification",        OFFSET(max_amplification), AV_OPT_TYPE_DOUBLE, {.dbl = 10.0}, 1.0, 100.0, FLAGS },
99     { "targetrms",   "set the target RMS",               OFFSET(target_rms),        AV_OPT_TYPE_DOUBLE, {.dbl = 0.0},  0.0,   1.0, FLAGS },
100     { "r",           "set the target RMS",               OFFSET(target_rms),        AV_OPT_TYPE_DOUBLE, {.dbl = 0.0},  0.0,   1.0, FLAGS },
101     { "coupling",    "set channel coupling",             OFFSET(channels_coupled),  AV_OPT_TYPE_BOOL,   {.i64 = 1},      0,     1, FLAGS },
102     { "n",           "set channel coupling",             OFFSET(channels_coupled),  AV_OPT_TYPE_BOOL,   {.i64 = 1},      0,     1, FLAGS },
103     { "correctdc",   "set DC correction",                OFFSET(dc_correction),     AV_OPT_TYPE_BOOL,   {.i64 = 0},      0,     1, FLAGS },
104     { "c",           "set DC correction",                OFFSET(dc_correction),     AV_OPT_TYPE_BOOL,   {.i64 = 0},      0,     1, FLAGS },
105     { "altboundary", "set alternative boundary mode",    OFFSET(alt_boundary_mode), AV_OPT_TYPE_BOOL,   {.i64 = 0},      0,     1, FLAGS },
106     { "b",           "set alternative boundary mode",    OFFSET(alt_boundary_mode), AV_OPT_TYPE_BOOL,   {.i64 = 0},      0,     1, FLAGS },
107     { "compress",    "set the compress factor",          OFFSET(compress_factor),   AV_OPT_TYPE_DOUBLE, {.dbl = 0.0},  0.0,  30.0, FLAGS },
108     { "s",           "set the compress factor",          OFFSET(compress_factor),   AV_OPT_TYPE_DOUBLE, {.dbl = 0.0},  0.0,  30.0, FLAGS },
109     { "threshold",   "set the threshold value",          OFFSET(threshold),         AV_OPT_TYPE_DOUBLE, {.dbl = 0.0},  0.0,   1.0, FLAGS },
110     { "t",           "set the threshold value",          OFFSET(threshold),         AV_OPT_TYPE_DOUBLE, {.dbl = 0.0},  0.0,   1.0, FLAGS },
111     { NULL }
112 };
113
114 AVFILTER_DEFINE_CLASS(dynaudnorm);
115
116 static av_cold int init(AVFilterContext *ctx)
117 {
118     DynamicAudioNormalizerContext *s = ctx->priv;
119
120     if (!(s->filter_size & 1)) {
121         av_log(ctx, AV_LOG_WARNING, "filter size %d is invalid. Changing to an odd value.\n", s->filter_size);
122         s->filter_size |= 1;
123     }
124
125     return 0;
126 }
127
128 static int query_formats(AVFilterContext *ctx)
129 {
130     AVFilterFormats *formats;
131     AVFilterChannelLayouts *layouts;
132     static const enum AVSampleFormat sample_fmts[] = {
133         AV_SAMPLE_FMT_DBLP,
134         AV_SAMPLE_FMT_NONE
135     };
136     int ret;
137
138     layouts = ff_all_channel_counts();
139     if (!layouts)
140         return AVERROR(ENOMEM);
141     ret = ff_set_common_channel_layouts(ctx, layouts);
142     if (ret < 0)
143         return ret;
144
145     formats = ff_make_format_list(sample_fmts);
146     if (!formats)
147         return AVERROR(ENOMEM);
148     ret = ff_set_common_formats(ctx, formats);
149     if (ret < 0)
150         return ret;
151
152     formats = ff_all_samplerates();
153     if (!formats)
154         return AVERROR(ENOMEM);
155     return ff_set_common_samplerates(ctx, formats);
156 }
157
158 static inline int frame_size(int sample_rate, int frame_len_msec)
159 {
160     const int frame_size = lrint((double)sample_rate * (frame_len_msec / 1000.0));
161     return frame_size + (frame_size % 2);
162 }
163
164 static void precalculate_fade_factors(double *fade_factors[2], int frame_len)
165 {
166     const double step_size = 1.0 / frame_len;
167     int pos;
168
169     for (pos = 0; pos < frame_len; pos++) {
170         fade_factors[0][pos] = 1.0 - (step_size * (pos + 1.0));
171         fade_factors[1][pos] = 1.0 - fade_factors[0][pos];
172     }
173 }
174
175 static cqueue *cqueue_create(int size)
176 {
177     cqueue *q;
178
179     q = av_malloc(sizeof(cqueue));
180     if (!q)
181         return NULL;
182
183     q->size = size;
184     q->nb_elements = 0;
185     q->first = 0;
186
187     q->elements = av_malloc_array(size, sizeof(double));
188     if (!q->elements) {
189         av_free(q);
190         return NULL;
191     }
192
193     return q;
194 }
195
196 static void cqueue_free(cqueue *q)
197 {
198     if (q)
199         av_free(q->elements);
200     av_free(q);
201 }
202
203 static int cqueue_size(cqueue *q)
204 {
205     return q->nb_elements;
206 }
207
208 static int cqueue_empty(cqueue *q)
209 {
210     return !q->nb_elements;
211 }
212
213 static int cqueue_enqueue(cqueue *q, double element)
214 {
215     int i;
216
217     av_assert2(q->nb_elements != q->size);
218
219     i = (q->first + q->nb_elements) % q->size;
220     q->elements[i] = element;
221     q->nb_elements++;
222
223     return 0;
224 }
225
226 static double cqueue_peek(cqueue *q, int index)
227 {
228     av_assert2(index < q->nb_elements);
229     return q->elements[(q->first + index) % q->size];
230 }
231
232 static int cqueue_dequeue(cqueue *q, double *element)
233 {
234     av_assert2(!cqueue_empty(q));
235
236     *element = q->elements[q->first];
237     q->first = (q->first + 1) % q->size;
238     q->nb_elements--;
239
240     return 0;
241 }
242
243 static int cqueue_pop(cqueue *q)
244 {
245     av_assert2(!cqueue_empty(q));
246
247     q->first = (q->first + 1) % q->size;
248     q->nb_elements--;
249
250     return 0;
251 }
252
253 static void init_gaussian_filter(DynamicAudioNormalizerContext *s)
254 {
255     double total_weight = 0.0;
256     const double sigma = (((s->filter_size / 2.0) - 1.0) / 3.0) + (1.0 / 3.0);
257     double adjust;
258     int i;
259
260     // Pre-compute constants
261     const int offset = s->filter_size / 2;
262     const double c1 = 1.0 / (sigma * sqrt(2.0 * M_PI));
263     const double c2 = 2.0 * sigma * sigma;
264
265     // Compute weights
266     for (i = 0; i < s->filter_size; i++) {
267         const int x = i - offset;
268
269         s->weights[i] = c1 * exp(-x * x / c2);
270         total_weight += s->weights[i];
271     }
272
273     // Adjust weights
274     adjust = 1.0 / total_weight;
275     for (i = 0; i < s->filter_size; i++) {
276         s->weights[i] *= adjust;
277     }
278 }
279
280 static av_cold void uninit(AVFilterContext *ctx)
281 {
282     DynamicAudioNormalizerContext *s = ctx->priv;
283     int c;
284
285     av_freep(&s->prev_amplification_factor);
286     av_freep(&s->dc_correction_value);
287     av_freep(&s->compress_threshold);
288     av_freep(&s->fade_factors[0]);
289     av_freep(&s->fade_factors[1]);
290
291     for (c = 0; c < s->channels; c++) {
292         if (s->gain_history_original)
293             cqueue_free(s->gain_history_original[c]);
294         if (s->gain_history_minimum)
295             cqueue_free(s->gain_history_minimum[c]);
296         if (s->gain_history_smoothed)
297             cqueue_free(s->gain_history_smoothed[c]);
298         if (s->threshold_history)
299             cqueue_free(s->threshold_history[c]);
300     }
301
302     av_freep(&s->gain_history_original);
303     av_freep(&s->gain_history_minimum);
304     av_freep(&s->gain_history_smoothed);
305     av_freep(&s->threshold_history);
306
307     cqueue_free(s->is_enabled);
308     s->is_enabled = NULL;
309
310     av_freep(&s->weights);
311
312     ff_bufqueue_discard_all(&s->queue);
313 }
314
315 static int config_input(AVFilterLink *inlink)
316 {
317     AVFilterContext *ctx = inlink->dst;
318     DynamicAudioNormalizerContext *s = ctx->priv;
319     int c;
320
321     uninit(ctx);
322
323     s->frame_len = frame_size(inlink->sample_rate, s->frame_len_msec);
324     av_log(ctx, AV_LOG_DEBUG, "frame len %d\n", s->frame_len);
325
326     s->fade_factors[0] = av_malloc_array(s->frame_len, sizeof(*s->fade_factors[0]));
327     s->fade_factors[1] = av_malloc_array(s->frame_len, sizeof(*s->fade_factors[1]));
328
329     s->prev_amplification_factor = av_malloc_array(inlink->channels, sizeof(*s->prev_amplification_factor));
330     s->dc_correction_value = av_calloc(inlink->channels, sizeof(*s->dc_correction_value));
331     s->compress_threshold = av_calloc(inlink->channels, sizeof(*s->compress_threshold));
332     s->gain_history_original = av_calloc(inlink->channels, sizeof(*s->gain_history_original));
333     s->gain_history_minimum = av_calloc(inlink->channels, sizeof(*s->gain_history_minimum));
334     s->gain_history_smoothed = av_calloc(inlink->channels, sizeof(*s->gain_history_smoothed));
335     s->threshold_history = av_calloc(inlink->channels, sizeof(*s->threshold_history));
336     s->weights = av_malloc_array(s->filter_size, sizeof(*s->weights));
337     s->is_enabled = cqueue_create(s->filter_size);
338     if (!s->prev_amplification_factor || !s->dc_correction_value ||
339         !s->compress_threshold || !s->fade_factors[0] || !s->fade_factors[1] ||
340         !s->gain_history_original || !s->gain_history_minimum ||
341         !s->gain_history_smoothed || !s->threshold_history ||
342         !s->is_enabled || !s->weights)
343         return AVERROR(ENOMEM);
344
345     for (c = 0; c < inlink->channels; c++) {
346         s->prev_amplification_factor[c] = 1.0;
347
348         s->gain_history_original[c] = cqueue_create(s->filter_size);
349         s->gain_history_minimum[c]  = cqueue_create(s->filter_size);
350         s->gain_history_smoothed[c] = cqueue_create(s->filter_size);
351         s->threshold_history[c]     = cqueue_create(s->filter_size);
352
353         if (!s->gain_history_original[c] || !s->gain_history_minimum[c] ||
354             !s->gain_history_smoothed[c] || !s->threshold_history[c])
355             return AVERROR(ENOMEM);
356     }
357
358     precalculate_fade_factors(s->fade_factors, s->frame_len);
359     init_gaussian_filter(s);
360
361     s->channels = inlink->channels;
362
363     return 0;
364 }
365
366 static inline double fade(double prev, double next, int pos,
367                           double *fade_factors[2])
368 {
369     return fade_factors[0][pos] * prev + fade_factors[1][pos] * next;
370 }
371
372 static inline double pow_2(const double value)
373 {
374     return value * value;
375 }
376
377 static inline double bound(const double threshold, const double val)
378 {
379     const double CONST = 0.8862269254527580136490837416705725913987747280611935; //sqrt(PI) / 2.0
380     return erf(CONST * (val / threshold)) * threshold;
381 }
382
383 static double find_peak_magnitude(AVFrame *frame, int channel)
384 {
385     double max = DBL_EPSILON;
386     int c, i;
387
388     if (channel == -1) {
389         for (c = 0; c < frame->channels; c++) {
390             double *data_ptr = (double *)frame->extended_data[c];
391
392             for (i = 0; i < frame->nb_samples; i++)
393                 max = FFMAX(max, fabs(data_ptr[i]));
394         }
395     } else {
396         double *data_ptr = (double *)frame->extended_data[channel];
397
398         for (i = 0; i < frame->nb_samples; i++)
399             max = FFMAX(max, fabs(data_ptr[i]));
400     }
401
402     return max;
403 }
404
405 static double compute_frame_rms(AVFrame *frame, int channel)
406 {
407     double rms_value = 0.0;
408     int c, i;
409
410     if (channel == -1) {
411         for (c = 0; c < frame->channels; c++) {
412             const double *data_ptr = (double *)frame->extended_data[c];
413
414             for (i = 0; i < frame->nb_samples; i++) {
415                 rms_value += pow_2(data_ptr[i]);
416             }
417         }
418
419         rms_value /= frame->nb_samples * frame->channels;
420     } else {
421         const double *data_ptr = (double *)frame->extended_data[channel];
422         for (i = 0; i < frame->nb_samples; i++) {
423             rms_value += pow_2(data_ptr[i]);
424         }
425
426         rms_value /= frame->nb_samples;
427     }
428
429     return FFMAX(sqrt(rms_value), DBL_EPSILON);
430 }
431
432 static local_gain get_max_local_gain(DynamicAudioNormalizerContext *s, AVFrame *frame,
433                                      int channel)
434 {
435     const double peak_magnitude = find_peak_magnitude(frame, channel);
436     const double maximum_gain = s->peak_value / peak_magnitude;
437     const double rms_gain = s->target_rms > DBL_EPSILON ? (s->target_rms / compute_frame_rms(frame, channel)) : DBL_MAX;
438     local_gain gain;
439
440     gain.threshold = peak_magnitude > s->threshold;
441     gain.max_gain  = bound(s->max_amplification, FFMIN(maximum_gain, rms_gain));
442
443     return gain;
444 }
445
446 static double minimum_filter(cqueue *q)
447 {
448     double min = DBL_MAX;
449     int i;
450
451     for (i = 0; i < cqueue_size(q); i++) {
452         min = FFMIN(min, cqueue_peek(q, i));
453     }
454
455     return min;
456 }
457
458 static double gaussian_filter(DynamicAudioNormalizerContext *s, cqueue *q, cqueue *tq)
459 {
460     double result = 0.0, tsum = 0.0;
461     int i;
462
463     for (i = 0; i < cqueue_size(q); i++) {
464         tsum += cqueue_peek(tq, i) * s->weights[i];
465         result += cqueue_peek(q, i) * s->weights[i] * cqueue_peek(tq, i);
466     }
467
468     if (tsum == 0.0)
469         result = 1.0;
470
471     return result;
472 }
473
474 static void update_gain_history(DynamicAudioNormalizerContext *s, int channel,
475                                 local_gain gain)
476 {
477     if (cqueue_empty(s->gain_history_original[channel]) ||
478         cqueue_empty(s->gain_history_minimum[channel])) {
479         const int pre_fill_size = s->filter_size / 2;
480         const double initial_value = s->alt_boundary_mode ? gain.max_gain : 1.0;
481
482         s->prev_amplification_factor[channel] = initial_value;
483
484         while (cqueue_size(s->gain_history_original[channel]) < pre_fill_size) {
485             cqueue_enqueue(s->gain_history_original[channel], initial_value);
486             cqueue_enqueue(s->threshold_history[channel], gain.threshold);
487         }
488     }
489
490     cqueue_enqueue(s->gain_history_original[channel], gain.max_gain);
491     cqueue_enqueue(s->threshold_history[channel], gain.threshold);
492
493     while (cqueue_size(s->gain_history_original[channel]) >= s->filter_size) {
494         double minimum;
495         av_assert0(cqueue_size(s->gain_history_original[channel]) == s->filter_size);
496
497         if (cqueue_empty(s->gain_history_minimum[channel])) {
498             const int pre_fill_size = s->filter_size / 2;
499             double initial_value = s->alt_boundary_mode ? cqueue_peek(s->gain_history_original[channel], 0) : 1.0;
500             int input = pre_fill_size;
501
502             while (cqueue_size(s->gain_history_minimum[channel]) < pre_fill_size) {
503                 input++;
504                 initial_value = FFMIN(initial_value, cqueue_peek(s->gain_history_original[channel], input));
505                 cqueue_enqueue(s->gain_history_minimum[channel], initial_value);
506             }
507         }
508
509         minimum = minimum_filter(s->gain_history_original[channel]);
510
511         cqueue_enqueue(s->gain_history_minimum[channel], minimum);
512
513         cqueue_pop(s->gain_history_original[channel]);
514     }
515
516     while (cqueue_size(s->gain_history_minimum[channel]) >= s->filter_size) {
517         double smoothed;
518         av_assert0(cqueue_size(s->gain_history_minimum[channel]) == s->filter_size);
519         smoothed = gaussian_filter(s, s->gain_history_minimum[channel], s->threshold_history[channel]);
520         smoothed = FFMIN(smoothed, cqueue_peek(s->gain_history_minimum[channel], s->filter_size / 2));
521
522         cqueue_enqueue(s->gain_history_smoothed[channel], smoothed);
523
524         cqueue_pop(s->gain_history_minimum[channel]);
525         cqueue_pop(s->threshold_history[channel]);
526     }
527 }
528
529 static inline double update_value(double new, double old, double aggressiveness)
530 {
531     av_assert0((aggressiveness >= 0.0) && (aggressiveness <= 1.0));
532     return aggressiveness * new + (1.0 - aggressiveness) * old;
533 }
534
535 static void perform_dc_correction(DynamicAudioNormalizerContext *s, AVFrame *frame)
536 {
537     const double diff = 1.0 / frame->nb_samples;
538     int is_first_frame = cqueue_empty(s->gain_history_original[0]);
539     int c, i;
540
541     for (c = 0; c < s->channels; c++) {
542         double *dst_ptr = (double *)frame->extended_data[c];
543         double current_average_value = 0.0;
544         double prev_value;
545
546         for (i = 0; i < frame->nb_samples; i++)
547             current_average_value += dst_ptr[i] * diff;
548
549         prev_value = is_first_frame ? current_average_value : s->dc_correction_value[c];
550         s->dc_correction_value[c] = is_first_frame ? current_average_value : update_value(current_average_value, s->dc_correction_value[c], 0.1);
551
552         for (i = 0; i < frame->nb_samples; i++) {
553             dst_ptr[i] -= fade(prev_value, s->dc_correction_value[c], i, s->fade_factors);
554         }
555     }
556 }
557
558 static double setup_compress_thresh(double threshold)
559 {
560     if ((threshold > DBL_EPSILON) && (threshold < (1.0 - DBL_EPSILON))) {
561         double current_threshold = threshold;
562         double step_size = 1.0;
563
564         while (step_size > DBL_EPSILON) {
565             while ((llrint((current_threshold + step_size) * (UINT64_C(1) << 63)) >
566                     llrint(current_threshold * (UINT64_C(1) << 63))) &&
567                    (bound(current_threshold + step_size, 1.0) <= threshold)) {
568                 current_threshold += step_size;
569             }
570
571             step_size /= 2.0;
572         }
573
574         return current_threshold;
575     } else {
576         return threshold;
577     }
578 }
579
580 static double compute_frame_std_dev(DynamicAudioNormalizerContext *s,
581                                     AVFrame *frame, int channel)
582 {
583     double variance = 0.0;
584     int i, c;
585
586     if (channel == -1) {
587         for (c = 0; c < s->channels; c++) {
588             const double *data_ptr = (double *)frame->extended_data[c];
589
590             for (i = 0; i < frame->nb_samples; i++) {
591                 variance += pow_2(data_ptr[i]);  // Assume that MEAN is *zero*
592             }
593         }
594         variance /= (s->channels * frame->nb_samples) - 1;
595     } else {
596         const double *data_ptr = (double *)frame->extended_data[channel];
597
598         for (i = 0; i < frame->nb_samples; i++) {
599             variance += pow_2(data_ptr[i]);      // Assume that MEAN is *zero*
600         }
601         variance /= frame->nb_samples - 1;
602     }
603
604     return FFMAX(sqrt(variance), DBL_EPSILON);
605 }
606
607 static void perform_compression(DynamicAudioNormalizerContext *s, AVFrame *frame)
608 {
609     int is_first_frame = cqueue_empty(s->gain_history_original[0]);
610     int c, i;
611
612     if (s->channels_coupled) {
613         const double standard_deviation = compute_frame_std_dev(s, frame, -1);
614         const double current_threshold  = FFMIN(1.0, s->compress_factor * standard_deviation);
615
616         const double prev_value = is_first_frame ? current_threshold : s->compress_threshold[0];
617         double prev_actual_thresh, curr_actual_thresh;
618         s->compress_threshold[0] = is_first_frame ? current_threshold : update_value(current_threshold, s->compress_threshold[0], (1.0/3.0));
619
620         prev_actual_thresh = setup_compress_thresh(prev_value);
621         curr_actual_thresh = setup_compress_thresh(s->compress_threshold[0]);
622
623         for (c = 0; c < s->channels; c++) {
624             double *const dst_ptr = (double *)frame->extended_data[c];
625             for (i = 0; i < frame->nb_samples; i++) {
626                 const double localThresh = fade(prev_actual_thresh, curr_actual_thresh, i, s->fade_factors);
627                 dst_ptr[i] = copysign(bound(localThresh, fabs(dst_ptr[i])), dst_ptr[i]);
628             }
629         }
630     } else {
631         for (c = 0; c < s->channels; c++) {
632             const double standard_deviation = compute_frame_std_dev(s, frame, c);
633             const double current_threshold  = setup_compress_thresh(FFMIN(1.0, s->compress_factor * standard_deviation));
634
635             const double prev_value = is_first_frame ? current_threshold : s->compress_threshold[c];
636             double prev_actual_thresh, curr_actual_thresh;
637             double *dst_ptr;
638             s->compress_threshold[c] = is_first_frame ? current_threshold : update_value(current_threshold, s->compress_threshold[c], 1.0/3.0);
639
640             prev_actual_thresh = setup_compress_thresh(prev_value);
641             curr_actual_thresh = setup_compress_thresh(s->compress_threshold[c]);
642
643             dst_ptr = (double *)frame->extended_data[c];
644             for (i = 0; i < frame->nb_samples; i++) {
645                 const double localThresh = fade(prev_actual_thresh, curr_actual_thresh, i, s->fade_factors);
646                 dst_ptr[i] = copysign(bound(localThresh, fabs(dst_ptr[i])), dst_ptr[i]);
647             }
648         }
649     }
650 }
651
652 static void analyze_frame(DynamicAudioNormalizerContext *s, AVFrame *frame)
653 {
654     if (s->dc_correction) {
655         perform_dc_correction(s, frame);
656     }
657
658     if (s->compress_factor > DBL_EPSILON) {
659         perform_compression(s, frame);
660     }
661
662     if (s->channels_coupled) {
663         const local_gain gain = get_max_local_gain(s, frame, -1);
664         int c;
665
666         for (c = 0; c < s->channels; c++)
667             update_gain_history(s, c, gain);
668     } else {
669         int c;
670
671         for (c = 0; c < s->channels; c++)
672             update_gain_history(s, c, get_max_local_gain(s, frame, c));
673     }
674 }
675
676 static void amplify_frame(DynamicAudioNormalizerContext *s, AVFrame *frame, int enabled)
677 {
678     int c, i;
679
680     for (c = 0; c < s->channels; c++) {
681         double *dst_ptr = (double *)frame->extended_data[c];
682         double current_amplification_factor;
683
684         cqueue_dequeue(s->gain_history_smoothed[c], &current_amplification_factor);
685
686         for (i = 0; i < frame->nb_samples && enabled; i++) {
687             const double amplification_factor = fade(s->prev_amplification_factor[c],
688                                                      current_amplification_factor, i,
689                                                      s->fade_factors);
690
691             dst_ptr[i] *= amplification_factor;
692
693             if (fabs(dst_ptr[i]) > s->peak_value)
694                 dst_ptr[i] = copysign(s->peak_value, dst_ptr[i]);
695         }
696
697         s->prev_amplification_factor[c] = current_amplification_factor;
698     }
699 }
700
701 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
702 {
703     AVFilterContext *ctx = inlink->dst;
704     DynamicAudioNormalizerContext *s = ctx->priv;
705     AVFilterLink *outlink = inlink->dst->outputs[0];
706     int ret = 1;
707
708     if (!cqueue_empty(s->gain_history_smoothed[0])) {
709         double is_enabled;
710         AVFrame *out = ff_bufqueue_get(&s->queue);
711
712         cqueue_dequeue(s->is_enabled, &is_enabled);
713
714         amplify_frame(s, out, is_enabled > 0.);
715         ret = ff_filter_frame(outlink, out);
716     }
717
718     av_frame_make_writable(in);
719     if (!s->eof)
720         cqueue_enqueue(s->is_enabled, !ctx->is_disabled);
721     analyze_frame(s, in);
722     if (!s->eof)
723         ff_bufqueue_add(ctx, &s->queue, in);
724     else
725         av_frame_free(&in);
726
727     return ret;
728 }
729
730 static int flush_buffer(DynamicAudioNormalizerContext *s, AVFilterLink *inlink,
731                         AVFilterLink *outlink)
732 {
733     AVFrame *out = ff_get_audio_buffer(outlink, s->frame_len);
734     int c, i;
735
736     if (!out)
737         return AVERROR(ENOMEM);
738
739     for (c = 0; c < s->channels; c++) {
740         double *dst_ptr = (double *)out->extended_data[c];
741
742         for (i = 0; i < out->nb_samples; i++) {
743             dst_ptr[i] = s->alt_boundary_mode ? DBL_EPSILON : ((s->target_rms > DBL_EPSILON) ? FFMIN(s->peak_value, s->target_rms) : s->peak_value);
744             if (s->dc_correction) {
745                 dst_ptr[i] *= ((i % 2) == 1) ? -1 : 1;
746                 dst_ptr[i] += s->dc_correction_value[c];
747             }
748         }
749     }
750
751     return filter_frame(inlink, out);
752 }
753
754 static int flush(AVFilterLink *outlink)
755 {
756     AVFilterContext *ctx = outlink->src;
757     DynamicAudioNormalizerContext *s = ctx->priv;
758     int ret = 0;
759
760     if (!cqueue_empty(s->gain_history_smoothed[0])) {
761         ret = flush_buffer(s, ctx->inputs[0], outlink);
762     } else if (s->queue.available) {
763         AVFrame *out = ff_bufqueue_get(&s->queue);
764
765         s->pts = out->pts;
766         ret = ff_filter_frame(outlink, out);
767     }
768
769     return ret;
770 }
771
772 static int activate(AVFilterContext *ctx)
773 {
774     AVFilterLink *inlink = ctx->inputs[0];
775     AVFilterLink *outlink = ctx->outputs[0];
776     DynamicAudioNormalizerContext *s = ctx->priv;
777     AVFrame *in = NULL;
778     int ret = 0, status;
779     int64_t pts;
780
781     FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
782
783     if (!s->eof) {
784         ret = ff_inlink_consume_samples(inlink, s->frame_len, s->frame_len, &in);
785         if (ret < 0)
786             return ret;
787         if (ret > 0) {
788             ret = filter_frame(inlink, in);
789             if (ret <= 0)
790                 return ret;
791         }
792
793         if (ff_inlink_queued_samples(inlink) >= s->frame_len) {
794             ff_filter_set_ready(ctx, 10);
795             return 0;
796         }
797     }
798
799     if (!s->eof && ff_inlink_acknowledge_status(inlink, &status, &pts)) {
800         if (status == AVERROR_EOF)
801             s->eof = 1;
802     }
803
804     if (s->eof && s->queue.available)
805         return flush(outlink);
806
807     if (s->eof && !s->queue.available) {
808         ff_outlink_set_status(outlink, AVERROR_EOF, s->pts);
809         return 0;
810     }
811
812     if (!s->eof)
813         FF_FILTER_FORWARD_WANTED(outlink, inlink);
814
815     return FFERROR_NOT_READY;
816 }
817
818 static const AVFilterPad avfilter_af_dynaudnorm_inputs[] = {
819     {
820         .name           = "default",
821         .type           = AVMEDIA_TYPE_AUDIO,
822         .config_props   = config_input,
823     },
824     { NULL }
825 };
826
827 static const AVFilterPad avfilter_af_dynaudnorm_outputs[] = {
828     {
829         .name          = "default",
830         .type          = AVMEDIA_TYPE_AUDIO,
831     },
832     { NULL }
833 };
834
835 AVFilter ff_af_dynaudnorm = {
836     .name          = "dynaudnorm",
837     .description   = NULL_IF_CONFIG_SMALL("Dynamic Audio Normalizer."),
838     .query_formats = query_formats,
839     .priv_size     = sizeof(DynamicAudioNormalizerContext),
840     .init          = init,
841     .uninit        = uninit,
842     .activate      = activate,
843     .inputs        = avfilter_af_dynaudnorm_inputs,
844     .outputs       = avfilter_af_dynaudnorm_outputs,
845     .priv_class    = &dynaudnorm_class,
846     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL,
847 };