]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_astats.c
avfilter/af_astats: extend bitdepth calculation
[ffmpeg] / libavfilter / af_astats.c
1 /*
2  * Copyright (c) 2009 Rob Sykes <robs@users.sourceforge.net>
3  * Copyright (c) 2013 Paul B Mahol
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <float.h>
23
24 #include "libavutil/opt.h"
25 #include "audio.h"
26 #include "avfilter.h"
27 #include "internal.h"
28
29 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, imask;
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->imask = 0xFFFFFFFFFFFFFFFF;
120         p->min_count = 0;
121         p->max_count = 0;
122         p->nb_samples = 0;
123     }
124 }
125
126 static int config_output(AVFilterLink *outlink)
127 {
128     AudioStatsContext *s = outlink->src->priv;
129
130     s->chstats = av_calloc(sizeof(*s->chstats), outlink->channels);
131     if (!s->chstats)
132         return AVERROR(ENOMEM);
133     s->nb_channels = outlink->channels;
134     s->mult = exp((-1 / s->time_constant / outlink->sample_rate));
135     s->tc_samples = 5 * s->time_constant * outlink->sample_rate + .5;
136     s->nb_frames = 0;
137
138     reset_stats(s);
139
140     return 0;
141 }
142
143 static void bit_depth(uint64_t mask, uint64_t imask, AVRational *depth)
144 {
145     unsigned result = 64;
146
147     mask = mask & (~imask);
148
149     for (; result && !(mask & 1); --result, mask >>= 1);
150
151     depth->den = result;
152     depth->num = 0;
153
154     for (; result; --result, mask >>= 1)
155         if (mask & 1)
156             depth->num++;
157 }
158
159 static inline void update_stat(AudioStatsContext *s, ChannelStats *p, double d)
160 {
161     if (d < p->min) {
162         p->min = d;
163         p->min_run = 1;
164         p->min_runs = 0;
165         p->min_count = 1;
166     } else if (d == p->min) {
167         p->min_count++;
168         p->min_run = d == p->last ? p->min_run + 1 : 1;
169     } else if (p->last == p->min) {
170         p->min_runs += p->min_run * p->min_run;
171     }
172
173     if (d > p->max) {
174         p->max = d;
175         p->max_run = 1;
176         p->max_runs = 0;
177         p->max_count = 1;
178     } else if (d == p->max) {
179         p->max_count++;
180         p->max_run = d == p->last ? p->max_run + 1 : 1;
181     } else if (p->last == p->max) {
182         p->max_runs += p->max_run * p->max_run;
183     }
184
185     p->sigma_x += d;
186     p->sigma_x2 += d * d;
187     p->avg_sigma_x2 = p->avg_sigma_x2 * s->mult + (1.0 - s->mult) * d * d;
188     p->min_diff = FFMIN(p->min_diff, fabs(d - p->last));
189     p->max_diff = FFMAX(p->max_diff, fabs(d - p->last));
190     p->diff1_sum += fabs(d - p->last);
191     p->last = d;
192     p->mask |= llrint(d * (UINT64_C(1) << 63));
193     p->imask &= llrint(d * (UINT64_C(1) << 63));
194
195     if (p->nb_samples >= s->tc_samples) {
196         p->max_sigma_x2 = FFMAX(p->max_sigma_x2, p->avg_sigma_x2);
197         p->min_sigma_x2 = FFMIN(p->min_sigma_x2, p->avg_sigma_x2);
198     }
199     p->nb_samples++;
200 }
201
202 static void set_meta(AVDictionary **metadata, int chan, const char *key,
203                      const char *fmt, double val)
204 {
205     uint8_t value[128];
206     uint8_t key2[128];
207
208     snprintf(value, sizeof(value), fmt, val);
209     if (chan)
210         snprintf(key2, sizeof(key2), "lavfi.astats.%d.%s", chan, key);
211     else
212         snprintf(key2, sizeof(key2), "lavfi.astats.%s", key);
213     av_dict_set(metadata, key2, value, 0);
214 }
215
216 #define LINEAR_TO_DB(x) (log10(x) * 20)
217
218 static void set_metadata(AudioStatsContext *s, AVDictionary **metadata)
219 {
220     uint64_t mask = 0, imask = 0xFFFFFFFFFFFFFFFF, min_count = 0, max_count = 0, nb_samples = 0;
221     double min_runs = 0, max_runs = 0,
222            min = DBL_MAX, max = DBL_MIN, min_diff = DBL_MAX, max_diff = 0,
223            max_sigma_x = 0,
224            diff1_sum = 0,
225            sigma_x = 0,
226            sigma_x2 = 0,
227            min_sigma_x2 = DBL_MAX,
228            max_sigma_x2 = DBL_MIN;
229     AVRational depth;
230     int c;
231
232     for (c = 0; c < s->nb_channels; c++) {
233         ChannelStats *p = &s->chstats[c];
234
235         if (p->nb_samples < s->tc_samples)
236             p->min_sigma_x2 = p->max_sigma_x2 = p->sigma_x2 / p->nb_samples;
237
238         min = FFMIN(min, p->min);
239         max = FFMAX(max, p->max);
240         min_diff = FFMIN(min_diff, p->min_diff);
241         max_diff = FFMAX(max_diff, p->max_diff);
242         diff1_sum += p->diff1_sum,
243         min_sigma_x2 = FFMIN(min_sigma_x2, p->min_sigma_x2);
244         max_sigma_x2 = FFMAX(max_sigma_x2, p->max_sigma_x2);
245         sigma_x += p->sigma_x;
246         sigma_x2 += p->sigma_x2;
247         min_count += p->min_count;
248         max_count += p->max_count;
249         min_runs += p->min_runs;
250         max_runs += p->max_runs;
251         mask |= p->mask;
252         imask &= p->imask;
253         nb_samples += p->nb_samples;
254         if (fabs(p->sigma_x) > fabs(max_sigma_x))
255             max_sigma_x = p->sigma_x;
256
257         set_meta(metadata, c + 1, "DC_offset", "%f", p->sigma_x / p->nb_samples);
258         set_meta(metadata, c + 1, "Min_level", "%f", p->min);
259         set_meta(metadata, c + 1, "Max_level", "%f", p->max);
260         set_meta(metadata, c + 1, "Min_difference", "%f", p->min_diff);
261         set_meta(metadata, c + 1, "Max_difference", "%f", p->max_diff);
262         set_meta(metadata, c + 1, "Mean_difference", "%f", p->diff1_sum / (p->nb_samples - 1));
263         set_meta(metadata, c + 1, "Peak_level", "%f", LINEAR_TO_DB(FFMAX(-p->min, p->max)));
264         set_meta(metadata, c + 1, "RMS_level", "%f", LINEAR_TO_DB(sqrt(p->sigma_x2 / p->nb_samples)));
265         set_meta(metadata, c + 1, "RMS_peak", "%f", LINEAR_TO_DB(sqrt(p->max_sigma_x2)));
266         set_meta(metadata, c + 1, "RMS_trough", "%f", LINEAR_TO_DB(sqrt(p->min_sigma_x2)));
267         set_meta(metadata, c + 1, "Crest_factor", "%f", p->sigma_x2 ? FFMAX(-p->min, p->max) / sqrt(p->sigma_x2 / p->nb_samples) : 1);
268         set_meta(metadata, c + 1, "Flat_factor", "%f", LINEAR_TO_DB((p->min_runs + p->max_runs) / (p->min_count + p->max_count)));
269         set_meta(metadata, c + 1, "Peak_count", "%f", (float)(p->min_count + p->max_count));
270         bit_depth(p->mask, p->imask, &depth);
271         set_meta(metadata, c + 1, "Bit_depth", "%f", depth.num);
272         set_meta(metadata, c + 1, "Bit_depth2", "%f", depth.den);
273     }
274
275     set_meta(metadata, 0, "Overall.DC_offset", "%f", max_sigma_x / (nb_samples / s->nb_channels));
276     set_meta(metadata, 0, "Overall.Min_level", "%f", min);
277     set_meta(metadata, 0, "Overall.Max_level", "%f", max);
278     set_meta(metadata, 0, "Overall.Min_difference", "%f", min_diff);
279     set_meta(metadata, 0, "Overall.Max_difference", "%f", max_diff);
280     set_meta(metadata, 0, "Overall.Mean_difference", "%f", diff1_sum / (nb_samples - s->nb_channels));
281     set_meta(metadata, 0, "Overall.Peak_level", "%f", LINEAR_TO_DB(FFMAX(-min, max)));
282     set_meta(metadata, 0, "Overall.RMS_level", "%f", LINEAR_TO_DB(sqrt(sigma_x2 / nb_samples)));
283     set_meta(metadata, 0, "Overall.RMS_peak", "%f", LINEAR_TO_DB(sqrt(max_sigma_x2)));
284     set_meta(metadata, 0, "Overall.RMS_trough", "%f", LINEAR_TO_DB(sqrt(min_sigma_x2)));
285     set_meta(metadata, 0, "Overall.Flat_factor", "%f", LINEAR_TO_DB((min_runs + max_runs) / (min_count + max_count)));
286     set_meta(metadata, 0, "Overall.Peak_count", "%f", (float)(min_count + max_count) / (double)s->nb_channels);
287     bit_depth(mask, imask, &depth);
288     set_meta(metadata, 0, "Overall.Bit_depth", "%f", depth.num);
289     set_meta(metadata, 0, "Overall.Bit_depth2", "%f", depth.den);
290     set_meta(metadata, 0, "Overall.Number_of_samples", "%f", nb_samples / s->nb_channels);
291 }
292
293 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
294 {
295     AudioStatsContext *s = inlink->dst->priv;
296     AVDictionary **metadata = avpriv_frame_get_metadatap(buf);
297     const int channels = s->nb_channels;
298     const double *src;
299     int i, c;
300
301     if (s->reset_count > 0) {
302         if (s->nb_frames >= s->reset_count) {
303             reset_stats(s);
304             s->nb_frames = 0;
305         }
306         s->nb_frames++;
307     }
308
309     switch (inlink->format) {
310     case AV_SAMPLE_FMT_DBLP:
311         for (c = 0; c < channels; c++) {
312             ChannelStats *p = &s->chstats[c];
313             src = (const double *)buf->extended_data[c];
314
315             for (i = 0; i < buf->nb_samples; i++, src++)
316                 update_stat(s, p, *src);
317         }
318         break;
319     case AV_SAMPLE_FMT_DBL:
320         src = (const double *)buf->extended_data[0];
321
322         for (i = 0; i < buf->nb_samples; i++) {
323             for (c = 0; c < channels; c++, src++)
324                 update_stat(s, &s->chstats[c], *src);
325         }
326         break;
327     }
328
329     if (s->metadata)
330         set_metadata(s, metadata);
331
332     return ff_filter_frame(inlink->dst->outputs[0], buf);
333 }
334
335 static void print_stats(AVFilterContext *ctx)
336 {
337     AudioStatsContext *s = ctx->priv;
338     uint64_t mask = 0, imask = 0xFFFFFFFFFFFFFFFF, min_count = 0, max_count = 0, nb_samples = 0;
339     double min_runs = 0, max_runs = 0,
340            min = DBL_MAX, max = DBL_MIN, min_diff = DBL_MAX, max_diff = 0,
341            max_sigma_x = 0,
342            diff1_sum = 0,
343            sigma_x = 0,
344            sigma_x2 = 0,
345            min_sigma_x2 = DBL_MAX,
346            max_sigma_x2 = DBL_MIN;
347     AVRational depth;
348     int c;
349
350     for (c = 0; c < s->nb_channels; c++) {
351         ChannelStats *p = &s->chstats[c];
352
353         if (p->nb_samples < s->tc_samples)
354             p->min_sigma_x2 = p->max_sigma_x2 = p->sigma_x2 / p->nb_samples;
355
356         min = FFMIN(min, p->min);
357         max = FFMAX(max, p->max);
358         min_diff = FFMIN(min_diff, p->min_diff);
359         max_diff = FFMAX(max_diff, p->max_diff);
360         diff1_sum += p->diff1_sum,
361         min_sigma_x2 = FFMIN(min_sigma_x2, p->min_sigma_x2);
362         max_sigma_x2 = FFMAX(max_sigma_x2, p->max_sigma_x2);
363         sigma_x += p->sigma_x;
364         sigma_x2 += p->sigma_x2;
365         min_count += p->min_count;
366         max_count += p->max_count;
367         min_runs += p->min_runs;
368         max_runs += p->max_runs;
369         mask |= p->mask;
370         imask &= p->imask;
371         nb_samples += p->nb_samples;
372         if (fabs(p->sigma_x) > fabs(max_sigma_x))
373             max_sigma_x = p->sigma_x;
374
375         av_log(ctx, AV_LOG_INFO, "Channel: %d\n", c + 1);
376         av_log(ctx, AV_LOG_INFO, "DC offset: %f\n", p->sigma_x / p->nb_samples);
377         av_log(ctx, AV_LOG_INFO, "Min level: %f\n", p->min);
378         av_log(ctx, AV_LOG_INFO, "Max level: %f\n", p->max);
379         av_log(ctx, AV_LOG_INFO, "Min difference: %f\n", p->min_diff);
380         av_log(ctx, AV_LOG_INFO, "Max difference: %f\n", p->max_diff);
381         av_log(ctx, AV_LOG_INFO, "Mean difference: %f\n", p->diff1_sum / (p->nb_samples - 1));
382         av_log(ctx, AV_LOG_INFO, "Peak level dB: %f\n", LINEAR_TO_DB(FFMAX(-p->min, p->max)));
383         av_log(ctx, AV_LOG_INFO, "RMS level dB: %f\n", LINEAR_TO_DB(sqrt(p->sigma_x2 / p->nb_samples)));
384         av_log(ctx, AV_LOG_INFO, "RMS peak dB: %f\n", LINEAR_TO_DB(sqrt(p->max_sigma_x2)));
385         if (p->min_sigma_x2 != 1)
386             av_log(ctx, AV_LOG_INFO, "RMS trough dB: %f\n",LINEAR_TO_DB(sqrt(p->min_sigma_x2)));
387         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);
388         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)));
389         av_log(ctx, AV_LOG_INFO, "Peak count: %"PRId64"\n", p->min_count + p->max_count);
390         bit_depth(p->mask, p->imask, &depth);
391         av_log(ctx, AV_LOG_INFO, "Bit depth: %u/%u\n", depth.num, depth.den);
392     }
393
394     av_log(ctx, AV_LOG_INFO, "Overall\n");
395     av_log(ctx, AV_LOG_INFO, "DC offset: %f\n", max_sigma_x / (nb_samples / s->nb_channels));
396     av_log(ctx, AV_LOG_INFO, "Min level: %f\n", min);
397     av_log(ctx, AV_LOG_INFO, "Max level: %f\n", max);
398     av_log(ctx, AV_LOG_INFO, "Min difference: %f\n", min_diff);
399     av_log(ctx, AV_LOG_INFO, "Max difference: %f\n", max_diff);
400     av_log(ctx, AV_LOG_INFO, "Mean difference: %f\n", diff1_sum / (nb_samples - s->nb_channels));
401     av_log(ctx, AV_LOG_INFO, "Peak level dB: %f\n", LINEAR_TO_DB(FFMAX(-min, max)));
402     av_log(ctx, AV_LOG_INFO, "RMS level dB: %f\n", LINEAR_TO_DB(sqrt(sigma_x2 / nb_samples)));
403     av_log(ctx, AV_LOG_INFO, "RMS peak dB: %f\n", LINEAR_TO_DB(sqrt(max_sigma_x2)));
404     if (min_sigma_x2 != 1)
405         av_log(ctx, AV_LOG_INFO, "RMS trough dB: %f\n", LINEAR_TO_DB(sqrt(min_sigma_x2)));
406     av_log(ctx, AV_LOG_INFO, "Flat factor: %f\n", LINEAR_TO_DB((min_runs + max_runs) / (min_count + max_count)));
407     av_log(ctx, AV_LOG_INFO, "Peak count: %f\n", (min_count + max_count) / (double)s->nb_channels);
408     bit_depth(mask, imask, &depth);
409     av_log(ctx, AV_LOG_INFO, "Bit depth: %u/%u\n", depth.num, depth.den);
410     av_log(ctx, AV_LOG_INFO, "Number of samples: %"PRId64"\n", nb_samples / s->nb_channels);
411 }
412
413 static av_cold void uninit(AVFilterContext *ctx)
414 {
415     AudioStatsContext *s = ctx->priv;
416
417     if (s->nb_channels)
418         print_stats(ctx);
419     av_freep(&s->chstats);
420 }
421
422 static const AVFilterPad astats_inputs[] = {
423     {
424         .name         = "default",
425         .type         = AVMEDIA_TYPE_AUDIO,
426         .filter_frame = filter_frame,
427     },
428     { NULL }
429 };
430
431 static const AVFilterPad astats_outputs[] = {
432     {
433         .name         = "default",
434         .type         = AVMEDIA_TYPE_AUDIO,
435         .config_props = config_output,
436     },
437     { NULL }
438 };
439
440 AVFilter ff_af_astats = {
441     .name          = "astats",
442     .description   = NULL_IF_CONFIG_SMALL("Show time domain statistics about audio frames."),
443     .query_formats = query_formats,
444     .priv_size     = sizeof(AudioStatsContext),
445     .priv_class    = &astats_class,
446     .uninit        = uninit,
447     .inputs        = astats_inputs,
448     .outputs       = astats_outputs,
449 };