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