]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_astats.c
avcodec/nvenc: Refactor timestamp generation logic
[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 typedef struct ChannelStats {
30     double last;
31     double sigma_x, sigma_x2;
32     double avg_sigma_x2, min_sigma_x2, max_sigma_x2;
33     double min, max;
34     double min_run, max_run;
35     double min_runs, max_runs;
36     double min_diff, max_diff;
37     double diff1_sum;
38     uint64_t mask;
39     uint64_t min_count, max_count;
40     uint64_t nb_samples;
41 } ChannelStats;
42
43 typedef struct {
44     const AVClass *class;
45     ChannelStats *chstats;
46     int nb_channels;
47     uint64_t tc_samples;
48     double time_constant;
49     double mult;
50     int metadata;
51     int reset_count;
52     int nb_frames;
53 } AudioStatsContext;
54
55 #define OFFSET(x) offsetof(AudioStatsContext, x)
56 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
57
58 static const AVOption astats_options[] = {
59     { "length", "set the window length", OFFSET(time_constant), AV_OPT_TYPE_DOUBLE, {.dbl=.05}, .01, 10, FLAGS },
60     { "metadata", "inject metadata in the filtergraph", OFFSET(metadata), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
61     { "reset", "recalculate stats after this many frames", OFFSET(reset_count), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS },
62     { NULL }
63 };
64
65 AVFILTER_DEFINE_CLASS(astats);
66
67 static int query_formats(AVFilterContext *ctx)
68 {
69     AVFilterFormats *formats;
70     AVFilterChannelLayouts *layouts;
71     static const enum AVSampleFormat sample_fmts[] = {
72         AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_DBLP,
73         AV_SAMPLE_FMT_NONE
74     };
75     int ret;
76
77     layouts = ff_all_channel_counts();
78     if (!layouts)
79         return AVERROR(ENOMEM);
80     ret = ff_set_common_channel_layouts(ctx, layouts);
81     if (ret < 0)
82         return ret;
83
84     formats = ff_make_format_list(sample_fmts);
85     if (!formats)
86         return AVERROR(ENOMEM);
87     ret = ff_set_common_formats(ctx, formats);
88     if (ret < 0)
89         return ret;
90
91     formats = ff_all_samplerates();
92     if (!formats)
93         return AVERROR(ENOMEM);
94     return ff_set_common_samplerates(ctx, formats);
95 }
96
97 static void reset_stats(AudioStatsContext *s)
98 {
99     int c;
100
101     for (c = 0; c < s->nb_channels; c++) {
102         ChannelStats *p = &s->chstats[c];
103
104         p->min = p->min_sigma_x2 = DBL_MAX;
105         p->max = p->max_sigma_x2 = DBL_MIN;
106         p->min_diff = DBL_MAX;
107         p->max_diff = DBL_MIN;
108         p->sigma_x = 0;
109         p->sigma_x2 = 0;
110         p->avg_sigma_x2 = 0;
111         p->min_sigma_x2 = 0;
112         p->max_sigma_x2 = 0;
113         p->min_run = 0;
114         p->max_run = 0;
115         p->min_runs = 0;
116         p->max_runs = 0;
117         p->diff1_sum = 0;
118         p->mask = 0;
119         p->min_count = 0;
120         p->max_count = 0;
121         p->nb_samples = 0;
122     }
123 }
124
125 static int config_output(AVFilterLink *outlink)
126 {
127     AudioStatsContext *s = outlink->src->priv;
128
129     s->chstats = av_calloc(sizeof(*s->chstats), outlink->channels);
130     if (!s->chstats)
131         return AVERROR(ENOMEM);
132     s->nb_channels = outlink->channels;
133     s->mult = exp((-1 / s->time_constant / outlink->sample_rate));
134     s->tc_samples = 5 * s->time_constant * outlink->sample_rate + .5;
135     s->nb_frames = 0;
136
137     reset_stats(s);
138
139     return 0;
140 }
141
142 static unsigned bit_depth(uint64_t mask)
143 {
144     unsigned result = 64;
145
146     for (; result && !(mask & 1); --result, mask >>= 1);
147
148     return result;
149 }
150
151 static inline void update_stat(AudioStatsContext *s, ChannelStats *p, double d)
152 {
153     if (d < p->min) {
154         p->min = d;
155         p->min_run = 1;
156         p->min_runs = 0;
157         p->min_count = 1;
158     } else if (d == p->min) {
159         p->min_count++;
160         p->min_run = d == p->last ? p->min_run + 1 : 1;
161     } else if (p->last == p->min) {
162         p->min_runs += p->min_run * p->min_run;
163     }
164
165     if (d > p->max) {
166         p->max = d;
167         p->max_run = 1;
168         p->max_runs = 0;
169         p->max_count = 1;
170     } else if (d == p->max) {
171         p->max_count++;
172         p->max_run = d == p->last ? p->max_run + 1 : 1;
173     } else if (p->last == p->max) {
174         p->max_runs += p->max_run * p->max_run;
175     }
176
177     p->sigma_x += d;
178     p->sigma_x2 += d * d;
179     p->avg_sigma_x2 = p->avg_sigma_x2 * s->mult + (1.0 - s->mult) * d * d;
180     p->min_diff = FFMIN(p->min_diff, fabs(d - p->last));
181     p->max_diff = FFMAX(p->max_diff, fabs(d - p->last));
182     p->diff1_sum += fabs(d - p->last);
183     p->last = d;
184     p->mask |= llrint(d * (UINT64_C(1) << 63));
185
186     if (p->nb_samples >= s->tc_samples) {
187         p->max_sigma_x2 = FFMAX(p->max_sigma_x2, p->avg_sigma_x2);
188         p->min_sigma_x2 = FFMIN(p->min_sigma_x2, p->avg_sigma_x2);
189     }
190     p->nb_samples++;
191 }
192
193 static void set_meta(AVDictionary **metadata, int chan, const char *key,
194                      const char *fmt, double val)
195 {
196     uint8_t value[128];
197     uint8_t key2[128];
198
199     snprintf(value, sizeof(value), fmt, val);
200     if (chan)
201         snprintf(key2, sizeof(key2), "lavfi.astats.%d.%s", chan, key);
202     else
203         snprintf(key2, sizeof(key2), "lavfi.astats.%s", key);
204     av_dict_set(metadata, key2, value, 0);
205 }
206
207 #define LINEAR_TO_DB(x) (log10(x) * 20)
208
209 static void set_metadata(AudioStatsContext *s, AVDictionary **metadata)
210 {
211     uint64_t mask = 0, min_count = 0, max_count = 0, nb_samples = 0;
212     double min_runs = 0, max_runs = 0,
213            min = DBL_MAX, max = DBL_MIN, min_diff = DBL_MAX, max_diff = 0,
214            max_sigma_x = 0,
215            diff1_sum = 0,
216            sigma_x = 0,
217            sigma_x2 = 0,
218            min_sigma_x2 = DBL_MAX,
219            max_sigma_x2 = DBL_MIN;
220     int c;
221
222     for (c = 0; c < s->nb_channels; c++) {
223         ChannelStats *p = &s->chstats[c];
224
225         if (p->nb_samples < s->tc_samples)
226             p->min_sigma_x2 = p->max_sigma_x2 = p->sigma_x2 / p->nb_samples;
227
228         min = FFMIN(min, p->min);
229         max = FFMAX(max, p->max);
230         min_diff = FFMIN(min_diff, p->min_diff);
231         max_diff = FFMAX(max_diff, p->max_diff);
232         diff1_sum += p->diff1_sum,
233         min_sigma_x2 = FFMIN(min_sigma_x2, p->min_sigma_x2);
234         max_sigma_x2 = FFMAX(max_sigma_x2, p->max_sigma_x2);
235         sigma_x += p->sigma_x;
236         sigma_x2 += p->sigma_x2;
237         min_count += p->min_count;
238         max_count += p->max_count;
239         min_runs += p->min_runs;
240         max_runs += p->max_runs;
241         mask |= p->mask;
242         nb_samples += p->nb_samples;
243         if (fabs(p->sigma_x) > fabs(max_sigma_x))
244             max_sigma_x = p->sigma_x;
245
246         set_meta(metadata, c + 1, "DC_offset", "%f", p->sigma_x / p->nb_samples);
247         set_meta(metadata, c + 1, "Min_level", "%f", p->min);
248         set_meta(metadata, c + 1, "Max_level", "%f", p->max);
249         set_meta(metadata, c + 1, "Min_difference", "%f", p->min_diff);
250         set_meta(metadata, c + 1, "Max_difference", "%f", p->max_diff);
251         set_meta(metadata, c + 1, "Mean_difference", "%f", p->diff1_sum / (p->nb_samples - 1));
252         set_meta(metadata, c + 1, "Peak_level", "%f", LINEAR_TO_DB(FFMAX(-p->min, p->max)));
253         set_meta(metadata, c + 1, "RMS_level", "%f", LINEAR_TO_DB(sqrt(p->sigma_x2 / p->nb_samples)));
254         set_meta(metadata, c + 1, "RMS_peak", "%f", LINEAR_TO_DB(sqrt(p->max_sigma_x2)));
255         set_meta(metadata, c + 1, "RMS_trough", "%f", LINEAR_TO_DB(sqrt(p->min_sigma_x2)));
256         set_meta(metadata, c + 1, "Crest_factor", "%f", p->sigma_x2 ? FFMAX(-p->min, p->max) / sqrt(p->sigma_x2 / p->nb_samples) : 1);
257         set_meta(metadata, c + 1, "Flat_factor", "%f", LINEAR_TO_DB((p->min_runs + p->max_runs) / (p->min_count + p->max_count)));
258         set_meta(metadata, c + 1, "Peak_count", "%f", (float)(p->min_count + p->max_count));
259         set_meta(metadata, c + 1, "Bit_depth", "%f", bit_depth(p->mask));
260     }
261
262     set_meta(metadata, 0, "Overall.DC_offset", "%f", max_sigma_x / (nb_samples / s->nb_channels));
263     set_meta(metadata, 0, "Overall.Min_level", "%f", min);
264     set_meta(metadata, 0, "Overall.Max_level", "%f", max);
265     set_meta(metadata, 0, "Overall.Min_difference", "%f", min_diff);
266     set_meta(metadata, 0, "Overall.Max_difference", "%f", max_diff);
267     set_meta(metadata, 0, "Overall.Mean_difference", "%f", diff1_sum / (nb_samples - s->nb_channels));
268     set_meta(metadata, 0, "Overall.Peak_level", "%f", LINEAR_TO_DB(FFMAX(-min, max)));
269     set_meta(metadata, 0, "Overall.RMS_level", "%f", LINEAR_TO_DB(sqrt(sigma_x2 / nb_samples)));
270     set_meta(metadata, 0, "Overall.RMS_peak", "%f", LINEAR_TO_DB(sqrt(max_sigma_x2)));
271     set_meta(metadata, 0, "Overall.RMS_trough", "%f", LINEAR_TO_DB(sqrt(min_sigma_x2)));
272     set_meta(metadata, 0, "Overall.Flat_factor", "%f", LINEAR_TO_DB((min_runs + max_runs) / (min_count + max_count)));
273     set_meta(metadata, 0, "Overall.Peak_count", "%f", (float)(min_count + max_count) / (double)s->nb_channels);
274     set_meta(metadata, 0, "Overall.Bit_depth", "%f", bit_depth(mask));
275     set_meta(metadata, 0, "Overall.Number_of_samples", "%f", nb_samples / s->nb_channels);
276 }
277
278 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
279 {
280     AudioStatsContext *s = inlink->dst->priv;
281     AVDictionary **metadata = avpriv_frame_get_metadatap(buf);
282     const int channels = s->nb_channels;
283     const double *src;
284     int i, c;
285
286     if (s->reset_count > 0) {
287         if (s->nb_frames >= s->reset_count) {
288             reset_stats(s);
289             s->nb_frames = 0;
290         }
291         s->nb_frames++;
292     }
293
294     switch (inlink->format) {
295     case AV_SAMPLE_FMT_DBLP:
296         for (c = 0; c < channels; c++) {
297             ChannelStats *p = &s->chstats[c];
298             src = (const double *)buf->extended_data[c];
299
300             for (i = 0; i < buf->nb_samples; i++, src++)
301                 update_stat(s, p, *src);
302         }
303         break;
304     case AV_SAMPLE_FMT_DBL:
305         src = (const double *)buf->extended_data[0];
306
307         for (i = 0; i < buf->nb_samples; i++) {
308             for (c = 0; c < channels; c++, src++)
309                 update_stat(s, &s->chstats[c], *src);
310         }
311         break;
312     }
313
314     if (s->metadata)
315         set_metadata(s, metadata);
316
317     return ff_filter_frame(inlink->dst->outputs[0], buf);
318 }
319
320 static void print_stats(AVFilterContext *ctx)
321 {
322     AudioStatsContext *s = ctx->priv;
323     uint64_t mask = 0, min_count = 0, max_count = 0, nb_samples = 0;
324     double min_runs = 0, max_runs = 0,
325            min = DBL_MAX, max = DBL_MIN, min_diff = DBL_MAX, max_diff = 0,
326            max_sigma_x = 0,
327            diff1_sum = 0,
328            sigma_x = 0,
329            sigma_x2 = 0,
330            min_sigma_x2 = DBL_MAX,
331            max_sigma_x2 = DBL_MIN;
332     int c;
333
334     for (c = 0; c < s->nb_channels; c++) {
335         ChannelStats *p = &s->chstats[c];
336
337         if (p->nb_samples < s->tc_samples)
338             p->min_sigma_x2 = p->max_sigma_x2 = p->sigma_x2 / p->nb_samples;
339
340         min = FFMIN(min, p->min);
341         max = FFMAX(max, p->max);
342         min_diff = FFMIN(min_diff, p->min_diff);
343         max_diff = FFMAX(max_diff, p->max_diff);
344         diff1_sum += p->diff1_sum,
345         min_sigma_x2 = FFMIN(min_sigma_x2, p->min_sigma_x2);
346         max_sigma_x2 = FFMAX(max_sigma_x2, p->max_sigma_x2);
347         sigma_x += p->sigma_x;
348         sigma_x2 += p->sigma_x2;
349         min_count += p->min_count;
350         max_count += p->max_count;
351         min_runs += p->min_runs;
352         max_runs += p->max_runs;
353         mask |= p->mask;
354         nb_samples += p->nb_samples;
355         if (fabs(p->sigma_x) > fabs(max_sigma_x))
356             max_sigma_x = p->sigma_x;
357
358         av_log(ctx, AV_LOG_INFO, "Channel: %d\n", c + 1);
359         av_log(ctx, AV_LOG_INFO, "DC offset: %f\n", p->sigma_x / p->nb_samples);
360         av_log(ctx, AV_LOG_INFO, "Min level: %f\n", p->min);
361         av_log(ctx, AV_LOG_INFO, "Max level: %f\n", p->max);
362         av_log(ctx, AV_LOG_INFO, "Min difference: %f\n", p->min_diff);
363         av_log(ctx, AV_LOG_INFO, "Max difference: %f\n", p->max_diff);
364         av_log(ctx, AV_LOG_INFO, "Mean difference: %f\n", p->diff1_sum / (p->nb_samples - 1));
365         av_log(ctx, AV_LOG_INFO, "Peak level dB: %f\n", LINEAR_TO_DB(FFMAX(-p->min, p->max)));
366         av_log(ctx, AV_LOG_INFO, "RMS level dB: %f\n", LINEAR_TO_DB(sqrt(p->sigma_x2 / p->nb_samples)));
367         av_log(ctx, AV_LOG_INFO, "RMS peak dB: %f\n", LINEAR_TO_DB(sqrt(p->max_sigma_x2)));
368         if (p->min_sigma_x2 != 1)
369             av_log(ctx, AV_LOG_INFO, "RMS trough dB: %f\n",LINEAR_TO_DB(sqrt(p->min_sigma_x2)));
370         av_log(ctx, AV_LOG_INFO, "Crest factor: %f\n", p->sigma_x2 ? FFMAX(-p->min, p->max) / sqrt(p->sigma_x2 / p->nb_samples) : 1);
371         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)));
372         av_log(ctx, AV_LOG_INFO, "Peak count: %"PRId64"\n", p->min_count + p->max_count);
373         av_log(ctx, AV_LOG_INFO, "Bit depth: %u\n", bit_depth(p->mask));
374     }
375
376     av_log(ctx, AV_LOG_INFO, "Overall\n");
377     av_log(ctx, AV_LOG_INFO, "DC offset: %f\n", max_sigma_x / (nb_samples / s->nb_channels));
378     av_log(ctx, AV_LOG_INFO, "Min level: %f\n", min);
379     av_log(ctx, AV_LOG_INFO, "Max level: %f\n", max);
380     av_log(ctx, AV_LOG_INFO, "Min difference: %f\n", min_diff);
381     av_log(ctx, AV_LOG_INFO, "Max difference: %f\n", max_diff);
382     av_log(ctx, AV_LOG_INFO, "Mean difference: %f\n", diff1_sum / (nb_samples - s->nb_channels));
383     av_log(ctx, AV_LOG_INFO, "Peak level dB: %f\n", LINEAR_TO_DB(FFMAX(-min, max)));
384     av_log(ctx, AV_LOG_INFO, "RMS level dB: %f\n", LINEAR_TO_DB(sqrt(sigma_x2 / nb_samples)));
385     av_log(ctx, AV_LOG_INFO, "RMS peak dB: %f\n", LINEAR_TO_DB(sqrt(max_sigma_x2)));
386     if (min_sigma_x2 != 1)
387         av_log(ctx, AV_LOG_INFO, "RMS trough dB: %f\n", LINEAR_TO_DB(sqrt(min_sigma_x2)));
388     av_log(ctx, AV_LOG_INFO, "Flat factor: %f\n", LINEAR_TO_DB((min_runs + max_runs) / (min_count + max_count)));
389     av_log(ctx, AV_LOG_INFO, "Peak count: %f\n", (min_count + max_count) / (double)s->nb_channels);
390     av_log(ctx, AV_LOG_INFO, "Bit depth: %u\n", bit_depth(mask));
391     av_log(ctx, AV_LOG_INFO, "Number of samples: %"PRId64"\n", nb_samples / s->nb_channels);
392 }
393
394 static av_cold void uninit(AVFilterContext *ctx)
395 {
396     AudioStatsContext *s = ctx->priv;
397
398     if (s->nb_channels)
399         print_stats(ctx);
400     av_freep(&s->chstats);
401 }
402
403 static const AVFilterPad astats_inputs[] = {
404     {
405         .name         = "default",
406         .type         = AVMEDIA_TYPE_AUDIO,
407         .filter_frame = filter_frame,
408     },
409     { NULL }
410 };
411
412 static const AVFilterPad astats_outputs[] = {
413     {
414         .name         = "default",
415         .type         = AVMEDIA_TYPE_AUDIO,
416         .config_props = config_output,
417     },
418     { NULL }
419 };
420
421 AVFilter ff_af_astats = {
422     .name          = "astats",
423     .description   = NULL_IF_CONFIG_SMALL("Show time domain statistics about audio frames."),
424     .query_formats = query_formats,
425     .priv_size     = sizeof(AudioStatsContext),
426     .priv_class    = &astats_class,
427     .uninit        = uninit,
428     .inputs        = astats_inputs,
429     .outputs       = astats_outputs,
430 };