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