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