]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_dynaudnorm.c
Merge commit '7570c9e04f010c9b3bfdeb4338d330f2cdd25278'
[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     if (q)
177         av_free(q->elements);
178     av_free(q);
179 }
180
181 static int cqueue_size(cqueue *q)
182 {
183     return q->nb_elements;
184 }
185
186 static int cqueue_empty(cqueue *q)
187 {
188     return !q->nb_elements;
189 }
190
191 static int cqueue_enqueue(cqueue *q, double element)
192 {
193     int i;
194
195     av_assert2(q->nb_elements != q->size);
196
197     i = (q->first + q->nb_elements) % q->size;
198     q->elements[i] = element;
199     q->nb_elements++;
200
201     return 0;
202 }
203
204 static double cqueue_peek(cqueue *q, int index)
205 {
206     av_assert2(index < q->nb_elements);
207     return q->elements[(q->first + index) % q->size];
208 }
209
210 static int cqueue_dequeue(cqueue *q, double *element)
211 {
212     av_assert2(!cqueue_empty(q));
213
214     *element = q->elements[q->first];
215     q->first = (q->first + 1) % q->size;
216     q->nb_elements--;
217
218     return 0;
219 }
220
221 static int cqueue_pop(cqueue *q)
222 {
223     av_assert2(!cqueue_empty(q));
224
225     q->first = (q->first + 1) % q->size;
226     q->nb_elements--;
227
228     return 0;
229 }
230
231 static void init_gaussian_filter(DynamicAudioNormalizerContext *s)
232 {
233     double total_weight = 0.0;
234     const double sigma = (((s->filter_size / 2.0) - 1.0) / 3.0) + (1.0 / 3.0);
235     double adjust;
236     int i;
237
238     // Pre-compute constants
239     const int offset = s->filter_size / 2;
240     const double c1 = 1.0 / (sigma * sqrt(2.0 * M_PI));
241     const double c2 = 2.0 * sigma * sigma;
242
243     // Compute weights
244     for (i = 0; i < s->filter_size; i++) {
245         const int x = i - offset;
246
247         s->weights[i] = c1 * exp(-x * x / c2);
248         total_weight += s->weights[i];
249     }
250
251     // Adjust weights
252     adjust = 1.0 / total_weight;
253     for (i = 0; i < s->filter_size; i++) {
254         s->weights[i] *= adjust;
255     }
256 }
257
258 static int config_input(AVFilterLink *inlink)
259 {
260     AVFilterContext *ctx = inlink->dst;
261     DynamicAudioNormalizerContext *s = ctx->priv;
262     int c;
263
264     s->frame_len =
265     inlink->min_samples =
266     inlink->max_samples =
267     inlink->partial_buf_size = frame_size(inlink->sample_rate, s->frame_len_msec);
268     av_log(ctx, AV_LOG_DEBUG, "frame len %d\n", s->frame_len);
269
270     s->fade_factors[0] = av_malloc_array(s->frame_len, sizeof(*s->fade_factors[0]));
271     s->fade_factors[1] = av_malloc_array(s->frame_len, sizeof(*s->fade_factors[1]));
272
273     s->prev_amplification_factor = av_malloc_array(inlink->channels, sizeof(*s->prev_amplification_factor));
274     s->dc_correction_value = av_calloc(inlink->channels, sizeof(*s->dc_correction_value));
275     s->compress_threshold = av_calloc(inlink->channels, sizeof(*s->compress_threshold));
276     s->gain_history_original = av_calloc(inlink->channels, sizeof(*s->gain_history_original));
277     s->gain_history_minimum = av_calloc(inlink->channels, sizeof(*s->gain_history_minimum));
278     s->gain_history_smoothed = av_calloc(inlink->channels, sizeof(*s->gain_history_smoothed));
279     s->weights = av_malloc_array(s->filter_size, sizeof(*s->weights));
280     if (!s->prev_amplification_factor || !s->dc_correction_value ||
281         !s->compress_threshold || !s->fade_factors[0] || !s->fade_factors[1] ||
282         !s->gain_history_original || !s->gain_history_minimum ||
283         !s->gain_history_smoothed || !s->weights)
284         return AVERROR(ENOMEM);
285
286     for (c = 0; c < inlink->channels; c++) {
287         s->prev_amplification_factor[c] = 1.0;
288
289         s->gain_history_original[c] = cqueue_create(s->filter_size);
290         s->gain_history_minimum[c]  = cqueue_create(s->filter_size);
291         s->gain_history_smoothed[c] = cqueue_create(s->filter_size);
292
293         if (!s->gain_history_original[c] || !s->gain_history_minimum[c] ||
294             !s->gain_history_smoothed[c])
295             return AVERROR(ENOMEM);
296     }
297
298     precalculate_fade_factors(s->fade_factors, s->frame_len);
299     init_gaussian_filter(s);
300
301     s->channels = inlink->channels;
302     s->delay = s->filter_size;
303
304     return 0;
305 }
306
307 static inline double fade(double prev, double next, int pos,
308                           double *fade_factors[2])
309 {
310     return fade_factors[0][pos] * prev + fade_factors[1][pos] * next;
311 }
312
313 static inline double pow2(const double value)
314 {
315     return value * value;
316 }
317
318 static inline double bound(const double threshold, const double val)
319 {
320     const double CONST = 0.8862269254527580136490837416705725913987747280611935; //sqrt(PI) / 2.0
321     return erf(CONST * (val / threshold)) * threshold;
322 }
323
324 static double find_peak_magnitude(AVFrame *frame, int channel)
325 {
326     double max = DBL_EPSILON;
327     int c, i;
328
329     if (channel == -1) {
330         for (c = 0; c < av_frame_get_channels(frame); c++) {
331             double *data_ptr = (double *)frame->extended_data[c];
332
333             for (i = 0; i < frame->nb_samples; i++)
334                 max = FFMAX(max, fabs(data_ptr[i]));
335         }
336     } else {
337         double *data_ptr = (double *)frame->extended_data[channel];
338
339         for (i = 0; i < frame->nb_samples; i++)
340             max = FFMAX(max, fabs(data_ptr[i]));
341     }
342
343     return max;
344 }
345
346 static double compute_frame_rms(AVFrame *frame, int channel)
347 {
348     double rms_value = 0.0;
349     int c, i;
350
351     if (channel == -1) {
352         for (c = 0; c < av_frame_get_channels(frame); c++) {
353             const double *data_ptr = (double *)frame->extended_data[c];
354
355             for (i = 0; i < frame->nb_samples; i++) {
356                 rms_value += pow2(data_ptr[i]);
357             }
358         }
359
360         rms_value /= frame->nb_samples * av_frame_get_channels(frame);
361     } else {
362         const double *data_ptr = (double *)frame->extended_data[channel];
363         for (i = 0; i < frame->nb_samples; i++) {
364             rms_value += pow2(data_ptr[i]);
365         }
366
367         rms_value /= frame->nb_samples;
368     }
369
370     return FFMAX(sqrt(rms_value), DBL_EPSILON);
371 }
372
373 static double get_max_local_gain(DynamicAudioNormalizerContext *s, AVFrame *frame,
374                                  int channel)
375 {
376     const double maximum_gain = s->peak_value / find_peak_magnitude(frame, channel);
377     const double rms_gain = s->target_rms > DBL_EPSILON ? (s->target_rms / compute_frame_rms(frame, channel)) : DBL_MAX;
378     return bound(s->max_amplification, FFMIN(maximum_gain, rms_gain));
379 }
380
381 static double minimum_filter(cqueue *q)
382 {
383     double min = DBL_MAX;
384     int i;
385
386     for (i = 0; i < cqueue_size(q); i++) {
387         min = FFMIN(min, cqueue_peek(q, i));
388     }
389
390     return min;
391 }
392
393 static double gaussian_filter(DynamicAudioNormalizerContext *s, cqueue *q)
394 {
395     double result = 0.0;
396     int i;
397
398     for (i = 0; i < cqueue_size(q); i++) {
399         result += cqueue_peek(q, i) * s->weights[i];
400     }
401
402     return result;
403 }
404
405 static void update_gain_history(DynamicAudioNormalizerContext *s, int channel,
406                                 double current_gain_factor)
407 {
408     if (cqueue_empty(s->gain_history_original[channel]) ||
409         cqueue_empty(s->gain_history_minimum[channel])) {
410         const int pre_fill_size = s->filter_size / 2;
411
412         s->prev_amplification_factor[channel] = s->alt_boundary_mode ? current_gain_factor : 1.0;
413
414         while (cqueue_size(s->gain_history_original[channel]) < pre_fill_size) {
415             cqueue_enqueue(s->gain_history_original[channel], s->alt_boundary_mode ? current_gain_factor : 1.0);
416         }
417
418         while (cqueue_size(s->gain_history_minimum[channel]) < pre_fill_size) {
419             cqueue_enqueue(s->gain_history_minimum[channel], s->alt_boundary_mode ? current_gain_factor : 1.0);
420         }
421     }
422
423     cqueue_enqueue(s->gain_history_original[channel], current_gain_factor);
424
425     while (cqueue_size(s->gain_history_original[channel]) >= s->filter_size) {
426         double minimum;
427         av_assert0(cqueue_size(s->gain_history_original[channel]) == s->filter_size);
428         minimum = minimum_filter(s->gain_history_original[channel]);
429
430         cqueue_enqueue(s->gain_history_minimum[channel], minimum);
431
432         cqueue_pop(s->gain_history_original[channel]);
433     }
434
435     while (cqueue_size(s->gain_history_minimum[channel]) >= s->filter_size) {
436         double smoothed;
437         av_assert0(cqueue_size(s->gain_history_minimum[channel]) == s->filter_size);
438         smoothed = gaussian_filter(s, s->gain_history_minimum[channel]);
439
440         cqueue_enqueue(s->gain_history_smoothed[channel], smoothed);
441
442         cqueue_pop(s->gain_history_minimum[channel]);
443     }
444 }
445
446 static inline double update_value(double new, double old, double aggressiveness)
447 {
448     av_assert0((aggressiveness >= 0.0) && (aggressiveness <= 1.0));
449     return aggressiveness * new + (1.0 - aggressiveness) * old;
450 }
451
452 static void perform_dc_correction(DynamicAudioNormalizerContext *s, AVFrame *frame)
453 {
454     const double diff = 1.0 / frame->nb_samples;
455     int is_first_frame = cqueue_empty(s->gain_history_original[0]);
456     int c, i;
457
458     for (c = 0; c < s->channels; c++) {
459         double *dst_ptr = (double *)frame->extended_data[c];
460         double current_average_value = 0.0;
461         double prev_value;
462
463         for (i = 0; i < frame->nb_samples; i++)
464             current_average_value += dst_ptr[i] * diff;
465
466         prev_value = is_first_frame ? current_average_value : s->dc_correction_value[c];
467         s->dc_correction_value[c] = is_first_frame ? current_average_value : update_value(current_average_value, s->dc_correction_value[c], 0.1);
468
469         for (i = 0; i < frame->nb_samples; i++) {
470             dst_ptr[i] -= fade(prev_value, s->dc_correction_value[c], i, s->fade_factors);
471         }
472     }
473 }
474
475 static double setup_compress_thresh(double threshold)
476 {
477     if ((threshold > DBL_EPSILON) && (threshold < (1.0 - DBL_EPSILON))) {
478         double current_threshold = threshold;
479         double step_size = 1.0;
480
481         while (step_size > DBL_EPSILON) {
482             while ((current_threshold + step_size > current_threshold) &&
483                    (bound(current_threshold + step_size, 1.0) <= threshold)) {
484                 current_threshold += step_size;
485             }
486
487             step_size /= 2.0;
488         }
489
490         return current_threshold;
491     } else {
492         return threshold;
493     }
494 }
495
496 static double compute_frame_std_dev(DynamicAudioNormalizerContext *s,
497                                     AVFrame *frame, int channel)
498 {
499     double variance = 0.0;
500     int i, c;
501
502     if (channel == -1) {
503         for (c = 0; c < s->channels; c++) {
504             const double *data_ptr = (double *)frame->extended_data[c];
505
506             for (i = 0; i < frame->nb_samples; i++) {
507                 variance += pow2(data_ptr[i]);  // Assume that MEAN is *zero*
508             }
509         }
510         variance /= (s->channels * frame->nb_samples) - 1;
511     } else {
512         const double *data_ptr = (double *)frame->extended_data[channel];
513
514         for (i = 0; i < frame->nb_samples; i++) {
515             variance += pow2(data_ptr[i]);      // Assume that MEAN is *zero*
516         }
517         variance /= frame->nb_samples - 1;
518     }
519
520     return FFMAX(sqrt(variance), DBL_EPSILON);
521 }
522
523 static void perform_compression(DynamicAudioNormalizerContext *s, AVFrame *frame)
524 {
525     int is_first_frame = cqueue_empty(s->gain_history_original[0]);
526     int c, i;
527
528     if (s->channels_coupled) {
529         const double standard_deviation = compute_frame_std_dev(s, frame, -1);
530         const double current_threshold  = FFMIN(1.0, s->compress_factor * standard_deviation);
531
532         const double prev_value = is_first_frame ? current_threshold : s->compress_threshold[0];
533         double prev_actual_thresh, curr_actual_thresh;
534         s->compress_threshold[0] = is_first_frame ? current_threshold : update_value(current_threshold, s->compress_threshold[0], (1.0/3.0));
535
536         prev_actual_thresh = setup_compress_thresh(prev_value);
537         curr_actual_thresh = setup_compress_thresh(s->compress_threshold[0]);
538
539         for (c = 0; c < s->channels; c++) {
540             double *const dst_ptr = (double *)frame->extended_data[c];
541             for (i = 0; i < frame->nb_samples; i++) {
542                 const double localThresh = fade(prev_actual_thresh, curr_actual_thresh, i, s->fade_factors);
543                 dst_ptr[i] = copysign(bound(localThresh, fabs(dst_ptr[i])), dst_ptr[i]);
544             }
545         }
546     } else {
547         for (c = 0; c < s->channels; c++) {
548             const double standard_deviation = compute_frame_std_dev(s, frame, c);
549             const double current_threshold  = setup_compress_thresh(FFMIN(1.0, s->compress_factor * standard_deviation));
550
551             const double prev_value = is_first_frame ? current_threshold : s->compress_threshold[c];
552             double prev_actual_thresh, curr_actual_thresh;
553             double *dst_ptr;
554             s->compress_threshold[c] = is_first_frame ? current_threshold : update_value(current_threshold, s->compress_threshold[c], 1.0/3.0);
555
556             prev_actual_thresh = setup_compress_thresh(prev_value);
557             curr_actual_thresh = setup_compress_thresh(s->compress_threshold[c]);
558
559             dst_ptr = (double *)frame->extended_data[c];
560             for (i = 0; i < frame->nb_samples; i++) {
561                 const double localThresh = fade(prev_actual_thresh, curr_actual_thresh, i, s->fade_factors);
562                 dst_ptr[i] = copysign(bound(localThresh, fabs(dst_ptr[i])), dst_ptr[i]);
563             }
564         }
565     }
566 }
567
568 static void analyze_frame(DynamicAudioNormalizerContext *s, AVFrame *frame)
569 {
570     if (s->dc_correction) {
571         perform_dc_correction(s, frame);
572     }
573
574     if (s->compress_factor > DBL_EPSILON) {
575         perform_compression(s, frame);
576     }
577
578     if (s->channels_coupled) {
579         const double current_gain_factor = get_max_local_gain(s, frame, -1);
580         int c;
581
582         for (c = 0; c < s->channels; c++)
583             update_gain_history(s, c, current_gain_factor);
584     } else {
585         int c;
586
587         for (c = 0; c < s->channels; c++)
588             update_gain_history(s, c, get_max_local_gain(s, frame, c));
589     }
590 }
591
592 static void amplify_frame(DynamicAudioNormalizerContext *s, AVFrame *frame)
593 {
594     int c, i;
595
596     for (c = 0; c < s->channels; c++) {
597         double *dst_ptr = (double *)frame->extended_data[c];
598         double current_amplification_factor;
599
600         cqueue_dequeue(s->gain_history_smoothed[c], &current_amplification_factor);
601
602         for (i = 0; i < frame->nb_samples; i++) {
603             const double amplification_factor = fade(s->prev_amplification_factor[c],
604                                                      current_amplification_factor, i,
605                                                      s->fade_factors);
606
607             dst_ptr[i] *= amplification_factor;
608
609             if (fabs(dst_ptr[i]) > s->peak_value)
610                 dst_ptr[i] = copysign(s->peak_value, dst_ptr[i]);
611         }
612
613         s->prev_amplification_factor[c] = current_amplification_factor;
614     }
615 }
616
617 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
618 {
619     AVFilterContext *ctx = inlink->dst;
620     DynamicAudioNormalizerContext *s = ctx->priv;
621     AVFilterLink *outlink = inlink->dst->outputs[0];
622     int ret = 0;
623
624     if (!cqueue_empty(s->gain_history_smoothed[0])) {
625         AVFrame *out = ff_bufqueue_get(&s->queue);
626
627         amplify_frame(s, out);
628         ret = ff_filter_frame(outlink, out);
629     }
630
631     analyze_frame(s, in);
632     ff_bufqueue_add(ctx, &s->queue, in);
633
634     return ret;
635 }
636
637 static int flush_buffer(DynamicAudioNormalizerContext *s, AVFilterLink *inlink,
638                         AVFilterLink *outlink)
639 {
640     AVFrame *out = ff_get_audio_buffer(outlink, s->frame_len);
641     int c, i;
642
643     if (!out)
644         return AVERROR(ENOMEM);
645
646     for (c = 0; c < s->channels; c++) {
647         double *dst_ptr = (double *)out->extended_data[c];
648
649         for (i = 0; i < out->nb_samples; i++) {
650             dst_ptr[i] = s->alt_boundary_mode ? DBL_EPSILON : ((s->target_rms > DBL_EPSILON) ? FFMIN(s->peak_value, s->target_rms) : s->peak_value);
651             if (s->dc_correction) {
652                 dst_ptr[i] *= ((i % 2) == 1) ? -1 : 1;
653                 dst_ptr[i] += s->dc_correction_value[c];
654             }
655         }
656     }
657
658     s->delay--;
659     return filter_frame(inlink, out);
660 }
661
662 static int request_frame(AVFilterLink *outlink)
663 {
664     AVFilterContext *ctx = outlink->src;
665     DynamicAudioNormalizerContext *s = ctx->priv;
666     int ret = 0;
667
668     ret = ff_request_frame(ctx->inputs[0]);
669
670     if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay)
671         ret = flush_buffer(s, ctx->inputs[0], outlink);
672
673     return ret;
674 }
675
676 static av_cold void uninit(AVFilterContext *ctx)
677 {
678     DynamicAudioNormalizerContext *s = ctx->priv;
679     int c;
680
681     av_freep(&s->prev_amplification_factor);
682     av_freep(&s->dc_correction_value);
683     av_freep(&s->compress_threshold);
684     av_freep(&s->fade_factors[0]);
685     av_freep(&s->fade_factors[1]);
686
687     for (c = 0; c < s->channels; c++) {
688         if (s->gain_history_original)
689             cqueue_free(s->gain_history_original[c]);
690         if (s->gain_history_minimum)
691             cqueue_free(s->gain_history_minimum[c]);
692         if (s->gain_history_smoothed)
693             cqueue_free(s->gain_history_smoothed[c]);
694     }
695
696     av_freep(&s->gain_history_original);
697     av_freep(&s->gain_history_minimum);
698     av_freep(&s->gain_history_smoothed);
699
700     av_freep(&s->weights);
701
702     ff_bufqueue_discard_all(&s->queue);
703 }
704
705 static const AVFilterPad avfilter_af_dynaudnorm_inputs[] = {
706     {
707         .name           = "default",
708         .type           = AVMEDIA_TYPE_AUDIO,
709         .filter_frame   = filter_frame,
710         .config_props   = config_input,
711         .needs_writable = 1,
712     },
713     { NULL }
714 };
715
716 static const AVFilterPad avfilter_af_dynaudnorm_outputs[] = {
717     {
718         .name          = "default",
719         .type          = AVMEDIA_TYPE_AUDIO,
720         .request_frame = request_frame,
721     },
722     { NULL }
723 };
724
725 AVFilter ff_af_dynaudnorm = {
726     .name          = "dynaudnorm",
727     .description   = NULL_IF_CONFIG_SMALL("Dynamic Audio Normalizer."),
728     .query_formats = query_formats,
729     .priv_size     = sizeof(DynamicAudioNormalizerContext),
730     .init          = init,
731     .uninit        = uninit,
732     .inputs        = avfilter_af_dynaudnorm_inputs,
733     .outputs       = avfilter_af_dynaudnorm_outputs,
734     .priv_class    = &dynaudnorm_class,
735 };