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