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