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