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