]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_astats.c
avfilter/af_astats: add support for optimized min/max/peak calculation
[ffmpeg] / libavfilter / af_astats.c
1 /*
2  * Copyright (c) 2009 Rob Sykes <robs@users.sourceforge.net>
3  * Copyright (c) 2013 Paul B Mahol
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 #include <float.h>
23
24 #include "libavutil/opt.h"
25 #include "audio.h"
26 #include "avfilter.h"
27 #include "internal.h"
28
29 #define MEASURE_ALL                     UINT_MAX
30 #define MEASURE_NONE                           0
31
32 #define MEASURE_DC_OFFSET               (1 <<  0)
33 #define MEASURE_MIN_LEVEL               (1 <<  1)
34 #define MEASURE_MAX_LEVEL               (1 <<  2)
35 #define MEASURE_MIN_DIFFERENCE          (1 <<  3)
36 #define MEASURE_MAX_DIFFERENCE          (1 <<  4)
37 #define MEASURE_MEAN_DIFFERENCE         (1 <<  5)
38 #define MEASURE_RMS_DIFFERENCE          (1 <<  6)
39 #define MEASURE_PEAK_LEVEL              (1 <<  7)
40 #define MEASURE_RMS_LEVEL               (1 <<  8)
41 #define MEASURE_RMS_PEAK                (1 <<  9)
42 #define MEASURE_RMS_TROUGH              (1 << 10)
43 #define MEASURE_CREST_FACTOR            (1 << 11)
44 #define MEASURE_FLAT_FACTOR             (1 << 12)
45 #define MEASURE_PEAK_COUNT              (1 << 13)
46 #define MEASURE_BIT_DEPTH               (1 << 14)
47 #define MEASURE_DYNAMIC_RANGE           (1 << 15)
48 #define MEASURE_ZERO_CROSSINGS          (1 << 16)
49 #define MEASURE_ZERO_CROSSINGS_RATE     (1 << 17)
50 #define MEASURE_NUMBER_OF_SAMPLES       (1 << 18)
51
52 #define MEASURE_MINMAXPEAK              (MEASURE_MIN_LEVEL | MEASURE_MAX_LEVEL | MEASURE_PEAK_LEVEL)
53
54 typedef struct ChannelStats {
55     double last;
56     double last_non_zero;
57     double min_non_zero;
58     double sigma_x, sigma_x2;
59     double avg_sigma_x2, min_sigma_x2, max_sigma_x2;
60     double min, max;
61     double nmin, nmax;
62     double min_run, max_run;
63     double min_runs, max_runs;
64     double min_diff, max_diff;
65     double diff1_sum;
66     double diff1_sum_x2;
67     uint64_t mask, imask;
68     uint64_t min_count, max_count;
69     uint64_t zero_runs;
70     uint64_t nb_samples;
71 } ChannelStats;
72
73 typedef struct AudioStatsContext {
74     const AVClass *class;
75     ChannelStats *chstats;
76     int nb_channels;
77     uint64_t tc_samples;
78     double time_constant;
79     double mult;
80     int metadata;
81     int reset_count;
82     int nb_frames;
83     int maxbitdepth;
84     int measure_perchannel;
85     int measure_overall;
86 } AudioStatsContext;
87
88 #define OFFSET(x) offsetof(AudioStatsContext, x)
89 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
90
91 static const AVOption astats_options[] = {
92     { "length", "set the window length", OFFSET(time_constant), AV_OPT_TYPE_DOUBLE, {.dbl=.05}, .01, 10, FLAGS },
93     { "metadata", "inject metadata in the filtergraph", OFFSET(metadata), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
94     { "reset", "recalculate stats after this many frames", OFFSET(reset_count), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS },
95     { "measure_perchannel", "only measure_perchannel these per-channel statistics", OFFSET(measure_perchannel), AV_OPT_TYPE_FLAGS, {.i64=MEASURE_ALL}, 0, UINT_MAX, FLAGS, "measure" },
96       { "none"                      , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_NONE                }, 0, 0, FLAGS, "measure" },
97       { "all"                       , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_ALL                 }, 0, 0, FLAGS, "measure" },
98       { "DC_offset"                 , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_DC_OFFSET           }, 0, 0, FLAGS, "measure" },
99       { "Min_level"                 , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_MIN_LEVEL           }, 0, 0, FLAGS, "measure" },
100       { "Max_level"                 , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_MAX_LEVEL           }, 0, 0, FLAGS, "measure" },
101       { "Min_difference"            , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_MIN_DIFFERENCE      }, 0, 0, FLAGS, "measure" },
102       { "Max_difference"            , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_MAX_DIFFERENCE      }, 0, 0, FLAGS, "measure" },
103       { "Mean_difference"           , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_MEAN_DIFFERENCE     }, 0, 0, FLAGS, "measure" },
104       { "RMS_difference"            , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_RMS_DIFFERENCE      }, 0, 0, FLAGS, "measure" },
105       { "Peak_level"                , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_PEAK_LEVEL          }, 0, 0, FLAGS, "measure" },
106       { "RMS_level"                 , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_RMS_LEVEL           }, 0, 0, FLAGS, "measure" },
107       { "RMS_peak"                  , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_RMS_PEAK            }, 0, 0, FLAGS, "measure" },
108       { "RMS_trough"                , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_RMS_TROUGH          }, 0, 0, FLAGS, "measure" },
109       { "Crest_factor"              , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_CREST_FACTOR        }, 0, 0, FLAGS, "measure" },
110       { "Flat_factor"               , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_FLAT_FACTOR         }, 0, 0, FLAGS, "measure" },
111       { "Peak_count"                , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_PEAK_COUNT          }, 0, 0, FLAGS, "measure" },
112       { "Bit_depth"                 , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_BIT_DEPTH           }, 0, 0, FLAGS, "measure" },
113       { "Dynamic_range"             , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_DYNAMIC_RANGE       }, 0, 0, FLAGS, "measure" },
114       { "Zero_crossings"            , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_ZERO_CROSSINGS      }, 0, 0, FLAGS, "measure" },
115       { "Zero_crossings_rate"       , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_ZERO_CROSSINGS_RATE }, 0, 0, FLAGS, "measure" },
116       { "Number_of_samples"         , "", 0, AV_OPT_TYPE_CONST, {.i64=MEASURE_NUMBER_OF_SAMPLES   }, 0, 0, FLAGS, "measure" },
117     { "measure_overall", "only measure_perchannel these overall statistics", OFFSET(measure_overall), AV_OPT_TYPE_FLAGS, {.i64=MEASURE_ALL}, 0, UINT_MAX, FLAGS, "measure" },
118     { NULL }
119 };
120
121 AVFILTER_DEFINE_CLASS(astats);
122
123 static int query_formats(AVFilterContext *ctx)
124 {
125     AVFilterFormats *formats;
126     AVFilterChannelLayouts *layouts;
127     static const enum AVSampleFormat sample_fmts[] = {
128         AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16P,
129         AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S32P,
130         AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S64P,
131         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLTP,
132         AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_DBLP,
133         AV_SAMPLE_FMT_NONE
134     };
135     int ret;
136
137     layouts = ff_all_channel_counts();
138     if (!layouts)
139         return AVERROR(ENOMEM);
140     ret = ff_set_common_channel_layouts(ctx, layouts);
141     if (ret < 0)
142         return ret;
143
144     formats = ff_make_format_list(sample_fmts);
145     if (!formats)
146         return AVERROR(ENOMEM);
147     ret = ff_set_common_formats(ctx, formats);
148     if (ret < 0)
149         return ret;
150
151     formats = ff_all_samplerates();
152     if (!formats)
153         return AVERROR(ENOMEM);
154     return ff_set_common_samplerates(ctx, formats);
155 }
156
157 static void reset_stats(AudioStatsContext *s)
158 {
159     int c;
160
161     for (c = 0; c < s->nb_channels; c++) {
162         ChannelStats *p = &s->chstats[c];
163
164         p->min = p->nmin = p->min_sigma_x2 = DBL_MAX;
165         p->max = p->nmax = p->max_sigma_x2 = DBL_MIN;
166         p->min_non_zero = DBL_MAX;
167         p->min_diff = DBL_MAX;
168         p->max_diff = DBL_MIN;
169         p->sigma_x = 0;
170         p->sigma_x2 = 0;
171         p->avg_sigma_x2 = 0;
172         p->min_run = 0;
173         p->max_run = 0;
174         p->min_runs = 0;
175         p->max_runs = 0;
176         p->diff1_sum = 0;
177         p->diff1_sum_x2 = 0;
178         p->mask = 0;
179         p->imask = 0xFFFFFFFFFFFFFFFF;
180         p->min_count = 0;
181         p->max_count = 0;
182         p->zero_runs = 0;
183         p->nb_samples = 0;
184     }
185 }
186
187 static int config_output(AVFilterLink *outlink)
188 {
189     AudioStatsContext *s = outlink->src->priv;
190
191     s->chstats = av_calloc(sizeof(*s->chstats), outlink->channels);
192     if (!s->chstats)
193         return AVERROR(ENOMEM);
194     s->nb_channels = outlink->channels;
195     s->mult = exp((-1 / s->time_constant / outlink->sample_rate));
196     s->tc_samples = 5 * s->time_constant * outlink->sample_rate + .5;
197     s->nb_frames = 0;
198     s->maxbitdepth = av_get_bytes_per_sample(outlink->format) * 8;
199
200     reset_stats(s);
201
202     return 0;
203 }
204
205 static void bit_depth(AudioStatsContext *s, uint64_t mask, uint64_t imask, AVRational *depth)
206 {
207     unsigned result = s->maxbitdepth;
208
209     mask = mask & (~imask);
210
211     for (; result && !(mask & 1); --result, mask >>= 1);
212
213     depth->den = result;
214     depth->num = 0;
215
216     for (; result; --result, mask >>= 1)
217         if (mask & 1)
218             depth->num++;
219 }
220
221 static inline void update_minmax(AudioStatsContext *s, ChannelStats *p, double d)
222 {
223     if (d < p->min)
224         p->min = d;
225     if (d > p->max)
226         p->max = d;
227 }
228
229 static inline void update_stat(AudioStatsContext *s, ChannelStats *p, double d, double nd, int64_t i)
230 {
231     if (d < p->min) {
232         p->min = d;
233         p->nmin = nd;
234         p->min_run = 1;
235         p->min_runs = 0;
236         p->min_count = 1;
237     } else if (d == p->min) {
238         p->min_count++;
239         p->min_run = d == p->last ? p->min_run + 1 : 1;
240     } else if (p->last == p->min) {
241         p->min_runs += p->min_run * p->min_run;
242     }
243
244     if (d != 0 && FFABS(d) < p->min_non_zero)
245         p->min_non_zero = FFABS(d);
246
247     if (d > p->max) {
248         p->max = d;
249         p->nmax = nd;
250         p->max_run = 1;
251         p->max_runs = 0;
252         p->max_count = 1;
253     } else if (d == p->max) {
254         p->max_count++;
255         p->max_run = d == p->last ? p->max_run + 1 : 1;
256     } else if (p->last == p->max) {
257         p->max_runs += p->max_run * p->max_run;
258     }
259
260     if (d != 0) {
261         p->zero_runs += FFSIGN(d) != FFSIGN(p->last_non_zero);
262         p->last_non_zero = d;
263     }
264
265     p->sigma_x += nd;
266     p->sigma_x2 += nd * nd;
267     p->avg_sigma_x2 = p->avg_sigma_x2 * s->mult + (1.0 - s->mult) * nd * nd;
268     p->min_diff = FFMIN(p->min_diff, fabs(d - p->last));
269     p->max_diff = FFMAX(p->max_diff, fabs(d - p->last));
270     p->diff1_sum += fabs(d - p->last);
271     p->diff1_sum_x2 += (d - p->last) * (d - p->last);
272     p->last = d;
273     p->mask |= i;
274     p->imask &= i;
275
276     if (p->nb_samples >= s->tc_samples) {
277         p->max_sigma_x2 = FFMAX(p->max_sigma_x2, p->avg_sigma_x2);
278         p->min_sigma_x2 = FFMIN(p->min_sigma_x2, p->avg_sigma_x2);
279     }
280     p->nb_samples++;
281 }
282
283 static void set_meta(AVDictionary **metadata, int chan, const char *key,
284                      const char *fmt, double val)
285 {
286     uint8_t value[128];
287     uint8_t key2[128];
288
289     snprintf(value, sizeof(value), fmt, val);
290     if (chan)
291         snprintf(key2, sizeof(key2), "lavfi.astats.%d.%s", chan, key);
292     else
293         snprintf(key2, sizeof(key2), "lavfi.astats.%s", key);
294     av_dict_set(metadata, key2, value, 0);
295 }
296
297 #define LINEAR_TO_DB(x) (log10(x) * 20)
298
299 static void set_metadata(AudioStatsContext *s, AVDictionary **metadata)
300 {
301     uint64_t mask = 0, imask = 0xFFFFFFFFFFFFFFFF, min_count = 0, max_count = 0, nb_samples = 0;
302     double min_runs = 0, max_runs = 0,
303            min = DBL_MAX, max = DBL_MIN, min_diff = DBL_MAX, max_diff = 0,
304            nmin = DBL_MAX, nmax = DBL_MIN,
305            max_sigma_x = 0,
306            diff1_sum = 0,
307            diff1_sum_x2 = 0,
308            sigma_x = 0,
309            sigma_x2 = 0,
310            min_sigma_x2 = DBL_MAX,
311            max_sigma_x2 = DBL_MIN;
312     AVRational depth;
313     int c;
314
315     for (c = 0; c < s->nb_channels; c++) {
316         ChannelStats *p = &s->chstats[c];
317
318         if (p->nb_samples < s->tc_samples)
319             p->min_sigma_x2 = p->max_sigma_x2 = p->sigma_x2 / p->nb_samples;
320
321         min = FFMIN(min, p->min);
322         max = FFMAX(max, p->max);
323         nmin = FFMIN(nmin, p->nmin);
324         nmax = FFMAX(nmax, p->nmax);
325         min_diff = FFMIN(min_diff, p->min_diff);
326         max_diff = FFMAX(max_diff, p->max_diff);
327         diff1_sum += p->diff1_sum;
328         diff1_sum_x2 += p->diff1_sum_x2;
329         min_sigma_x2 = FFMIN(min_sigma_x2, p->min_sigma_x2);
330         max_sigma_x2 = FFMAX(max_sigma_x2, p->max_sigma_x2);
331         sigma_x += p->sigma_x;
332         sigma_x2 += p->sigma_x2;
333         min_count += p->min_count;
334         max_count += p->max_count;
335         min_runs += p->min_runs;
336         max_runs += p->max_runs;
337         mask |= p->mask;
338         imask &= p->imask;
339         nb_samples += p->nb_samples;
340         if (fabs(p->sigma_x) > fabs(max_sigma_x))
341             max_sigma_x = p->sigma_x;
342
343         if (s->measure_perchannel & MEASURE_DC_OFFSET)
344             set_meta(metadata, c + 1, "DC_offset", "%f", p->sigma_x / p->nb_samples);
345         if (s->measure_perchannel & MEASURE_MIN_LEVEL)
346             set_meta(metadata, c + 1, "Min_level", "%f", p->min);
347         if (s->measure_perchannel & MEASURE_MAX_LEVEL)
348             set_meta(metadata, c + 1, "Max_level", "%f", p->max);
349         if (s->measure_perchannel & MEASURE_MIN_DIFFERENCE)
350             set_meta(metadata, c + 1, "Min_difference", "%f", p->min_diff);
351         if (s->measure_perchannel & MEASURE_MAX_DIFFERENCE)
352             set_meta(metadata, c + 1, "Max_difference", "%f", p->max_diff);
353         if (s->measure_perchannel & MEASURE_MEAN_DIFFERENCE)
354             set_meta(metadata, c + 1, "Mean_difference", "%f", p->diff1_sum / (p->nb_samples - 1));
355         if (s->measure_perchannel & MEASURE_RMS_DIFFERENCE)
356             set_meta(metadata, c + 1, "RMS_difference", "%f", sqrt(p->diff1_sum_x2 / (p->nb_samples - 1)));
357         if (s->measure_perchannel & MEASURE_PEAK_LEVEL)
358             set_meta(metadata, c + 1, "Peak_level", "%f", LINEAR_TO_DB(FFMAX(-p->nmin, p->nmax)));
359         if (s->measure_perchannel & MEASURE_RMS_LEVEL)
360             set_meta(metadata, c + 1, "RMS_level", "%f", LINEAR_TO_DB(sqrt(p->sigma_x2 / p->nb_samples)));
361         if (s->measure_perchannel & MEASURE_RMS_PEAK)
362             set_meta(metadata, c + 1, "RMS_peak", "%f", LINEAR_TO_DB(sqrt(p->max_sigma_x2)));
363         if (s->measure_perchannel & MEASURE_RMS_TROUGH)
364             set_meta(metadata, c + 1, "RMS_trough", "%f", LINEAR_TO_DB(sqrt(p->min_sigma_x2)));
365         if (s->measure_perchannel & MEASURE_CREST_FACTOR)
366             set_meta(metadata, c + 1, "Crest_factor", "%f", p->sigma_x2 ? FFMAX(-p->min, p->max) / sqrt(p->sigma_x2 / p->nb_samples) : 1);
367         if (s->measure_perchannel & MEASURE_FLAT_FACTOR)
368             set_meta(metadata, c + 1, "Flat_factor", "%f", LINEAR_TO_DB((p->min_runs + p->max_runs) / (p->min_count + p->max_count)));
369         if (s->measure_perchannel & MEASURE_PEAK_COUNT)
370             set_meta(metadata, c + 1, "Peak_count", "%f", (float)(p->min_count + p->max_count));
371         if (s->measure_perchannel & MEASURE_BIT_DEPTH) {
372             bit_depth(s, p->mask, p->imask, &depth);
373             set_meta(metadata, c + 1, "Bit_depth", "%f", depth.num);
374             set_meta(metadata, c + 1, "Bit_depth2", "%f", depth.den);
375         }
376         if (s->measure_perchannel & MEASURE_DYNAMIC_RANGE)
377             set_meta(metadata, c + 1, "Dynamic_range", "%f", LINEAR_TO_DB(2 * FFMAX(FFABS(p->min), FFABS(p->max))/ p->min_non_zero));
378         if (s->measure_perchannel & MEASURE_ZERO_CROSSINGS)
379             set_meta(metadata, c + 1, "Zero_crossings", "%f", p->zero_runs);
380         if (s->measure_perchannel & MEASURE_ZERO_CROSSINGS_RATE)
381             set_meta(metadata, c + 1, "Zero_crossings_rate", "%f", p->zero_runs/(double)p->nb_samples);
382     }
383
384     if (s->measure_overall & MEASURE_DC_OFFSET)
385         set_meta(metadata, 0, "Overall.DC_offset", "%f", max_sigma_x / (nb_samples / s->nb_channels));
386     if (s->measure_overall & MEASURE_MIN_LEVEL)
387         set_meta(metadata, 0, "Overall.Min_level", "%f", min);
388     if (s->measure_overall & MEASURE_MAX_LEVEL)
389         set_meta(metadata, 0, "Overall.Max_level", "%f", max);
390     if (s->measure_overall & MEASURE_MIN_DIFFERENCE)
391         set_meta(metadata, 0, "Overall.Min_difference", "%f", min_diff);
392     if (s->measure_overall & MEASURE_MAX_DIFFERENCE)
393         set_meta(metadata, 0, "Overall.Max_difference", "%f", max_diff);
394     if (s->measure_overall & MEASURE_MEAN_DIFFERENCE)
395         set_meta(metadata, 0, "Overall.Mean_difference", "%f", diff1_sum / (nb_samples - s->nb_channels));
396     if (s->measure_overall & MEASURE_RMS_DIFFERENCE)
397         set_meta(metadata, 0, "Overall.RMS_difference", "%f", sqrt(diff1_sum_x2 / (nb_samples - s->nb_channels)));
398     if (s->measure_overall & MEASURE_PEAK_LEVEL)
399         set_meta(metadata, 0, "Overall.Peak_level", "%f", LINEAR_TO_DB(FFMAX(-nmin, nmax)));
400     if (s->measure_overall & MEASURE_RMS_LEVEL)
401         set_meta(metadata, 0, "Overall.RMS_level", "%f", LINEAR_TO_DB(sqrt(sigma_x2 / nb_samples)));
402     if (s->measure_overall & MEASURE_RMS_PEAK)
403         set_meta(metadata, 0, "Overall.RMS_peak", "%f", LINEAR_TO_DB(sqrt(max_sigma_x2)));
404     if (s->measure_overall & MEASURE_RMS_TROUGH)
405         set_meta(metadata, 0, "Overall.RMS_trough", "%f", LINEAR_TO_DB(sqrt(min_sigma_x2)));
406     if (s->measure_overall & MEASURE_FLAT_FACTOR)
407         set_meta(metadata, 0, "Overall.Flat_factor", "%f", LINEAR_TO_DB((min_runs + max_runs) / (min_count + max_count)));
408     if (s->measure_overall & MEASURE_PEAK_COUNT)
409         set_meta(metadata, 0, "Overall.Peak_count", "%f", (float)(min_count + max_count) / (double)s->nb_channels);
410     if (s->measure_overall & MEASURE_BIT_DEPTH) {
411         bit_depth(s, mask, imask, &depth);
412         set_meta(metadata, 0, "Overall.Bit_depth", "%f", depth.num);
413         set_meta(metadata, 0, "Overall.Bit_depth2", "%f", depth.den);
414     }
415     if (s->measure_overall & MEASURE_NUMBER_OF_SAMPLES)
416         set_meta(metadata, 0, "Overall.Number_of_samples", "%f", nb_samples / s->nb_channels);
417 }
418
419 #define UPDATE_STATS_P(type, update_func, channel_func)                         \
420     for (int c = 0; c < channels; c++) {                                        \
421         ChannelStats *p = &s->chstats[c];                                       \
422         const type *src = (const type *)data[c];                                \
423         const type * const srcend = src + samples;                              \
424         for (; src < srcend; src++)                                             \
425             update_func;                                                        \
426         channel_func;                                                           \
427     }
428
429 #define UPDATE_STATS_I(type, update_func, channel_func)                         \
430     for (int c = 0; c < channels; c++) {                                        \
431         ChannelStats *p = &s->chstats[c];                                       \
432         const type *src = (const type *)data[0];                                \
433         const type * const srcend = src + samples * channels;                   \
434         for (src += c; src < srcend; src += channels)                           \
435             update_func;                                                        \
436         channel_func;                                                           \
437     }
438
439 #define UPDATE_STATS(planar, type, sample, normalizer_suffix, int_sample) \
440     if ((s->measure_overall | s->measure_perchannel) & ~MEASURE_MINMAXPEAK) {                          \
441         UPDATE_STATS_##planar(type, update_stat(s, p, sample, sample normalizer_suffix, int_sample), );    \
442     } else {                                                                                           \
443         UPDATE_STATS_##planar(type, update_minmax(s, p, sample), p->nmin = p->min normalizer_suffix; p->nmax = p->max normalizer_suffix;); \
444     }
445
446 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
447 {
448     AudioStatsContext *s = inlink->dst->priv;
449     AVDictionary **metadata = &buf->metadata;
450     const int channels = s->nb_channels;
451     const int samples = buf->nb_samples;
452     const uint8_t * const * const data = (const uint8_t * const *)buf->extended_data;
453
454     if (s->reset_count > 0) {
455         if (s->nb_frames >= s->reset_count) {
456             reset_stats(s);
457             s->nb_frames = 0;
458         }
459         s->nb_frames++;
460     }
461
462     switch (inlink->format) {
463     case AV_SAMPLE_FMT_DBLP:
464         UPDATE_STATS(P, double, *src, , llrint(*src * (UINT64_C(1) << 63)));
465         break;
466     case AV_SAMPLE_FMT_DBL:
467         UPDATE_STATS(I, double, *src, , llrint(*src * (UINT64_C(1) << 63)));
468         break;
469     case AV_SAMPLE_FMT_FLTP:
470         UPDATE_STATS(P, float, *src, , llrint(*src * (UINT64_C(1) << 31)));
471         break;
472     case AV_SAMPLE_FMT_FLT:
473         UPDATE_STATS(I, float, *src, , llrint(*src * (UINT64_C(1) << 31)));
474         break;
475     case AV_SAMPLE_FMT_S64P:
476         UPDATE_STATS(P, int64_t, *src, / (double)INT64_MAX, *src);
477         break;
478     case AV_SAMPLE_FMT_S64:
479         UPDATE_STATS(I, int64_t, *src, / (double)INT64_MAX, *src);
480         break;
481     case AV_SAMPLE_FMT_S32P:
482         UPDATE_STATS(P, int32_t, *src, / (double)INT32_MAX, *src);
483         break;
484     case AV_SAMPLE_FMT_S32:
485         UPDATE_STATS(I, int32_t, *src, / (double)INT32_MAX, *src);
486         break;
487     case AV_SAMPLE_FMT_S16P:
488         UPDATE_STATS(P, int16_t, *src, / (double)INT16_MAX, *src);
489         break;
490     case AV_SAMPLE_FMT_S16:
491         UPDATE_STATS(I, int16_t, *src, / (double)INT16_MAX, *src);
492         break;
493     }
494
495     if (s->metadata)
496         set_metadata(s, metadata);
497
498     return ff_filter_frame(inlink->dst->outputs[0], buf);
499 }
500
501 static void print_stats(AVFilterContext *ctx)
502 {
503     AudioStatsContext *s = ctx->priv;
504     uint64_t mask = 0, imask = 0xFFFFFFFFFFFFFFFF, min_count = 0, max_count = 0, nb_samples = 0;
505     double min_runs = 0, max_runs = 0,
506            min = DBL_MAX, max = DBL_MIN, min_diff = DBL_MAX, max_diff = 0,
507            nmin = DBL_MAX, nmax = DBL_MIN,
508            max_sigma_x = 0,
509            diff1_sum_x2 = 0,
510            diff1_sum = 0,
511            sigma_x = 0,
512            sigma_x2 = 0,
513            min_sigma_x2 = DBL_MAX,
514            max_sigma_x2 = DBL_MIN;
515     AVRational depth;
516     int c;
517
518     for (c = 0; c < s->nb_channels; c++) {
519         ChannelStats *p = &s->chstats[c];
520
521         if (p->nb_samples < s->tc_samples)
522             p->min_sigma_x2 = p->max_sigma_x2 = p->sigma_x2 / p->nb_samples;
523
524         min = FFMIN(min, p->min);
525         max = FFMAX(max, p->max);
526         nmin = FFMIN(nmin, p->nmin);
527         nmax = FFMAX(nmax, p->nmax);
528         min_diff = FFMIN(min_diff, p->min_diff);
529         max_diff = FFMAX(max_diff, p->max_diff);
530         diff1_sum_x2 += p->diff1_sum_x2;
531         diff1_sum += p->diff1_sum;
532         min_sigma_x2 = FFMIN(min_sigma_x2, p->min_sigma_x2);
533         max_sigma_x2 = FFMAX(max_sigma_x2, p->max_sigma_x2);
534         sigma_x += p->sigma_x;
535         sigma_x2 += p->sigma_x2;
536         min_count += p->min_count;
537         max_count += p->max_count;
538         min_runs += p->min_runs;
539         max_runs += p->max_runs;
540         mask |= p->mask;
541         imask &= p->imask;
542         nb_samples += p->nb_samples;
543         if (fabs(p->sigma_x) > fabs(max_sigma_x))
544             max_sigma_x = p->sigma_x;
545
546         av_log(ctx, AV_LOG_INFO, "Channel: %d\n", c + 1);
547         if (s->measure_perchannel & MEASURE_DC_OFFSET)
548             av_log(ctx, AV_LOG_INFO, "DC offset: %f\n", p->sigma_x / p->nb_samples);
549         if (s->measure_perchannel & MEASURE_MIN_LEVEL)
550             av_log(ctx, AV_LOG_INFO, "Min level: %f\n", p->min);
551         if (s->measure_perchannel & MEASURE_MAX_LEVEL)
552             av_log(ctx, AV_LOG_INFO, "Max level: %f\n", p->max);
553         if (s->measure_perchannel & MEASURE_MIN_DIFFERENCE)
554             av_log(ctx, AV_LOG_INFO, "Min difference: %f\n", p->min_diff);
555         if (s->measure_perchannel & MEASURE_MAX_DIFFERENCE)
556             av_log(ctx, AV_LOG_INFO, "Max difference: %f\n", p->max_diff);
557         if (s->measure_perchannel & MEASURE_MEAN_DIFFERENCE)
558             av_log(ctx, AV_LOG_INFO, "Mean difference: %f\n", p->diff1_sum / (p->nb_samples - 1));
559         if (s->measure_perchannel & MEASURE_RMS_DIFFERENCE)
560             av_log(ctx, AV_LOG_INFO, "RMS difference: %f\n", sqrt(p->diff1_sum_x2 / (p->nb_samples - 1)));
561         if (s->measure_perchannel & MEASURE_PEAK_LEVEL)
562             av_log(ctx, AV_LOG_INFO, "Peak level dB: %f\n", LINEAR_TO_DB(FFMAX(-p->nmin, p->nmax)));
563         if (s->measure_perchannel & MEASURE_RMS_LEVEL)
564             av_log(ctx, AV_LOG_INFO, "RMS level dB: %f\n", LINEAR_TO_DB(sqrt(p->sigma_x2 / p->nb_samples)));
565         if (s->measure_perchannel & MEASURE_RMS_PEAK)
566             av_log(ctx, AV_LOG_INFO, "RMS peak dB: %f\n", LINEAR_TO_DB(sqrt(p->max_sigma_x2)));
567         if (s->measure_perchannel & MEASURE_RMS_TROUGH)
568             if (p->min_sigma_x2 != 1)
569                 av_log(ctx, AV_LOG_INFO, "RMS trough dB: %f\n",LINEAR_TO_DB(sqrt(p->min_sigma_x2)));
570         if (s->measure_perchannel & MEASURE_CREST_FACTOR)
571             av_log(ctx, AV_LOG_INFO, "Crest factor: %f\n", p->sigma_x2 ? FFMAX(-p->nmin, p->nmax) / sqrt(p->sigma_x2 / p->nb_samples) : 1);
572         if (s->measure_perchannel & MEASURE_FLAT_FACTOR)
573             av_log(ctx, AV_LOG_INFO, "Flat factor: %f\n", LINEAR_TO_DB((p->min_runs + p->max_runs) / (p->min_count + p->max_count)));
574         if (s->measure_perchannel & MEASURE_PEAK_COUNT)
575             av_log(ctx, AV_LOG_INFO, "Peak count: %"PRId64"\n", p->min_count + p->max_count);
576         if (s->measure_perchannel & MEASURE_BIT_DEPTH) {
577             bit_depth(s, p->mask, p->imask, &depth);
578             av_log(ctx, AV_LOG_INFO, "Bit depth: %u/%u\n", depth.num, depth.den);
579         }
580         if (s->measure_perchannel & MEASURE_DYNAMIC_RANGE)
581             av_log(ctx, AV_LOG_INFO, "Dynamic range: %f\n", LINEAR_TO_DB(2 * FFMAX(FFABS(p->min), FFABS(p->max))/ p->min_non_zero));
582         if (s->measure_perchannel & MEASURE_ZERO_CROSSINGS)
583             av_log(ctx, AV_LOG_INFO, "Zero crossings: %"PRId64"\n", p->zero_runs);
584         if (s->measure_perchannel & MEASURE_ZERO_CROSSINGS_RATE)
585             av_log(ctx, AV_LOG_INFO, "Zero crossings rate: %f\n", p->zero_runs/(double)p->nb_samples);
586     }
587
588     av_log(ctx, AV_LOG_INFO, "Overall\n");
589     if (s->measure_overall & MEASURE_DC_OFFSET)
590         av_log(ctx, AV_LOG_INFO, "DC offset: %f\n", max_sigma_x / (nb_samples / s->nb_channels));
591     if (s->measure_overall & MEASURE_MIN_LEVEL)
592         av_log(ctx, AV_LOG_INFO, "Min level: %f\n", min);
593     if (s->measure_overall & MEASURE_MAX_LEVEL)
594         av_log(ctx, AV_LOG_INFO, "Max level: %f\n", max);
595     if (s->measure_overall & MEASURE_MIN_DIFFERENCE)
596         av_log(ctx, AV_LOG_INFO, "Min difference: %f\n", min_diff);
597     if (s->measure_overall & MEASURE_MAX_DIFFERENCE)
598         av_log(ctx, AV_LOG_INFO, "Max difference: %f\n", max_diff);
599     if (s->measure_overall & MEASURE_MEAN_DIFFERENCE)
600         av_log(ctx, AV_LOG_INFO, "Mean difference: %f\n", diff1_sum / (nb_samples - s->nb_channels));
601     if (s->measure_overall & MEASURE_RMS_DIFFERENCE)
602         av_log(ctx, AV_LOG_INFO, "RMS difference: %f\n", sqrt(diff1_sum_x2 / (nb_samples - s->nb_channels)));
603     if (s->measure_overall & MEASURE_PEAK_LEVEL)
604         av_log(ctx, AV_LOG_INFO, "Peak level dB: %f\n", LINEAR_TO_DB(FFMAX(-nmin, nmax)));
605     if (s->measure_overall & MEASURE_RMS_LEVEL)
606         av_log(ctx, AV_LOG_INFO, "RMS level dB: %f\n", LINEAR_TO_DB(sqrt(sigma_x2 / nb_samples)));
607     if (s->measure_overall & MEASURE_RMS_PEAK)
608         av_log(ctx, AV_LOG_INFO, "RMS peak dB: %f\n", LINEAR_TO_DB(sqrt(max_sigma_x2)));
609     if (s->measure_overall & MEASURE_RMS_TROUGH)
610         if (min_sigma_x2 != 1)
611             av_log(ctx, AV_LOG_INFO, "RMS trough dB: %f\n", LINEAR_TO_DB(sqrt(min_sigma_x2)));
612     if (s->measure_overall & MEASURE_FLAT_FACTOR)
613         av_log(ctx, AV_LOG_INFO, "Flat factor: %f\n", LINEAR_TO_DB((min_runs + max_runs) / (min_count + max_count)));
614     if (s->measure_overall & MEASURE_PEAK_COUNT)
615         av_log(ctx, AV_LOG_INFO, "Peak count: %f\n", (min_count + max_count) / (double)s->nb_channels);
616     if (s->measure_overall & MEASURE_BIT_DEPTH) {
617         bit_depth(s, mask, imask, &depth);
618         av_log(ctx, AV_LOG_INFO, "Bit depth: %u/%u\n", depth.num, depth.den);
619     }
620     if (s->measure_overall & MEASURE_NUMBER_OF_SAMPLES)
621         av_log(ctx, AV_LOG_INFO, "Number of samples: %"PRId64"\n", nb_samples / s->nb_channels);
622 }
623
624 static av_cold void uninit(AVFilterContext *ctx)
625 {
626     AudioStatsContext *s = ctx->priv;
627
628     if (s->nb_channels)
629         print_stats(ctx);
630     av_freep(&s->chstats);
631 }
632
633 static const AVFilterPad astats_inputs[] = {
634     {
635         .name         = "default",
636         .type         = AVMEDIA_TYPE_AUDIO,
637         .filter_frame = filter_frame,
638     },
639     { NULL }
640 };
641
642 static const AVFilterPad astats_outputs[] = {
643     {
644         .name         = "default",
645         .type         = AVMEDIA_TYPE_AUDIO,
646         .config_props = config_output,
647     },
648     { NULL }
649 };
650
651 AVFilter ff_af_astats = {
652     .name          = "astats",
653     .description   = NULL_IF_CONFIG_SMALL("Show time domain statistics about audio frames."),
654     .query_formats = query_formats,
655     .priv_size     = sizeof(AudioStatsContext),
656     .priv_class    = &astats_class,
657     .uninit        = uninit,
658     .inputs        = astats_inputs,
659     .outputs       = astats_outputs,
660 };