FFmpeg
Loading...
Searching...
No Matches
f_ebur128.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012 Clément Bœsch
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21/**
22 * @file
23 * EBU R.128 implementation
24 * @see http://tech.ebu.ch/loudness
25 * @see https://www.youtube.com/watch?v=iuEtQqC-Sqo "EBU R128 Introduction - Florian Camerer"
26 * @todo implement start/stop/reset through filter command injection
27 */
28
29#include <float.h>
30#include <math.h>
31
32#include "libavutil/avassert.h"
33#include "libavutil/bprint.h"
35#include "libavutil/dict.h"
36#include "libavutil/ffmath.h"
37#include "libavutil/mem.h"
39#include "libavutil/opt.h"
40#include "libavutil/timestamp.h"
42#include "avfilter.h"
43#include "filters.h"
44#include "formats.h"
45#include "video.h"
46
47#include "f_ebur128.h"
48
49#define ABS_THRES -70 ///< silence gate: we discard anything below this absolute (LUFS) threshold
50#define ABS_UP_THRES 10 ///< upper loud limit to consider (ABS_THRES being the minimum)
51#define HIST_GRAIN 100 ///< defines histogram precision
52#define HIST_SIZE ((ABS_UP_THRES - ABS_THRES) * HIST_GRAIN + 1)
53
54/**
55 * A histogram is an array of HIST_SIZE hist_entry storing all the energies
56 * recorded (with an accuracy of 1/HIST_GRAIN) of the loudnesses from ABS_THRES
57 * (at 0) to ABS_UP_THRES (at HIST_SIZE-1).
58 * This fixed-size system avoids the need of a list of energies growing
59 * infinitely over the time and is thus more scalable.
60 */
61struct hist_entry {
62 unsigned count; ///< how many times the corresponding value occurred
63 double energy; ///< E = 10^((L + 0.691) / 10)
64 double loudness; ///< L = -0.691 + 10 * log10(E)
65};
66
67struct integrator {
68 double *cache; ///< window of filtered samples (N ms)
69 int cache_pos; ///< focus on the last added bin in the cache array
71 double *sum; ///< sum of the last N ms filtered samples (cache content)
72 int filled; ///< 1 if the cache is completely filled, 0 otherwise
73 double rel_threshold; ///< relative threshold
74 double sum_kept_powers; ///< sum of the powers (weighted sums) above absolute threshold
75 int nb_kept_powers; ///< number of sum above absolute threshold
76 struct hist_entry *histogram; ///< histogram of the powers, used to compute LRA and I
77};
78
79struct rect { int x, y, w, h; };
80
81typedef struct EBUR128Context {
82 const AVClass *class; ///< AVClass context for log and options purpose
84
85 /* peak metering */
86 int peak_mode; ///< enabled peak modes
87 double true_peak; ///< global true peak
88 double *true_peaks; ///< true peaks per channel
89 double sample_peak; ///< global sample peak
90 double *sample_peaks; ///< sample peaks per channel
91 double *true_peaks_per_frame; ///< true peaks in a frame per channel
92#if CONFIG_SWRESAMPLE
93 SwrContext *swr_ctx; ///< over-sampling context for true peak metering
94 double *swr_buf; ///< resampled audio data for true peak metering
95 int swr_linesize;
96#endif
97
98 /* video */
99 int do_video; ///< 1 if video output enabled, 0 otherwise
100 int w, h; ///< size of the video output
101 struct rect text; ///< rectangle for the LU legend on the left
102 struct rect graph; ///< rectangle for the main graph in the center
103 struct rect gauge; ///< rectangle for the gauge on the right
104 AVFrame *outpicref; ///< output picture reference, updated regularly
105 int meter; ///< select a EBU mode between +9 and +18
106 int scale_range; ///< the range of LU values according to the meter
107 int y_zero_lu; ///< the y value (pixel position) for 0 LU
108 int y_opt_max; ///< the y value (pixel position) for 1 LU
109 int y_opt_min; ///< the y value (pixel position) for -1 LU
110 int *y_line_ref; ///< y reference values for drawing the LU lines in the graph and the gauge
111
112 /* audio */
113 int nb_channels; ///< number of channels in the input
114 double *ch_weighting; ///< channel weighting mapping
115 int sample_count; ///< sample count used for refresh frequency, reset at refresh
116 int nb_samples; ///< number of samples to consume per single input frame
117 int idx_insample; ///< current sample position of processed samples in single input frame
118 AVFrame *insamples; ///< input samples reference, updated regularly
119
120 struct integrator i400; ///< 400ms integrator, used for Momentary loudness (M), and Integrated loudness (I)
121 struct integrator i3000; ///< 3s integrator, used for Short term loudness (S), and Loudness Range (LRA)
122
123 /* I and LRA specific */
124 double integrated_loudness; ///< integrated loudness in LUFS (I)
125 double loudness_range; ///< loudness range in LU (LRA)
126 double lra_low, lra_high; ///< low and high LRA values
127
128 /* misc */
129 int loglevel; ///< log level for frame logging
130 int metadata; ///< whether or not to inject loudness results in frames
131 int dual_mono; ///< whether or not to treat single channel input files as dual-mono
132 double pan_law; ///< pan law value used to calculate dual-mono measurements
133 int target; ///< target level in LUFS used to set relative zero LU in visualization
134 int gauge_type; ///< whether gauge shows momentary or short
135 int scale; ///< display scale type of statistics
137
138enum {
142};
143
144enum {
147};
148
149enum {
152};
153
154#define OFFSET(x) offsetof(EBUR128Context, x)
155#define A AV_OPT_FLAG_AUDIO_PARAM
156#define V AV_OPT_FLAG_VIDEO_PARAM
157#define F AV_OPT_FLAG_FILTERING_PARAM
158#define X AV_OPT_FLAG_EXPORT
159#define R AV_OPT_FLAG_READONLY
160static const AVOption ebur128_options[] = {
161 { "video", "set video output", OFFSET(do_video), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, V|F },
162 { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, V|F },
163 { "meter", "set scale meter (+9 to +18)", OFFSET(meter), AV_OPT_TYPE_INT, {.i64 = 9}, 9, 18, V|F },
164 { "framelog", "force frame logging level", OFFSET(loglevel), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, A|V|F, .unit = "level" },
165 { "quiet", "logging disabled", 0, AV_OPT_TYPE_CONST, {.i64 = AV_LOG_QUIET}, INT_MIN, INT_MAX, A|V|F, .unit = "level" },
166 { "info", "information logging level", 0, AV_OPT_TYPE_CONST, {.i64 = AV_LOG_INFO}, INT_MIN, INT_MAX, A|V|F, .unit = "level" },
167 { "verbose", "verbose logging level", 0, AV_OPT_TYPE_CONST, {.i64 = AV_LOG_VERBOSE}, INT_MIN, INT_MAX, A|V|F, .unit = "level" },
168 { "metadata", "inject metadata in the filtergraph", OFFSET(metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, A|V|F },
169 { "peak", "set peak mode", OFFSET(peak_mode), AV_OPT_TYPE_FLAGS, {.i64 = PEAK_MODE_NONE}, 0, INT_MAX, A|F, .unit = "mode" },
170 { "none", "disable any peak mode", 0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_NONE}, INT_MIN, INT_MAX, A|F, .unit = "mode" },
171 { "sample", "enable peak-sample mode", 0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_SAMPLES_PEAKS}, INT_MIN, INT_MAX, A|F, .unit = "mode" },
172 { "true", "enable true-peak mode", 0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_TRUE_PEAKS}, INT_MIN, INT_MAX, A|F, .unit = "mode" },
173 { "dualmono", "treat mono input files as dual-mono", OFFSET(dual_mono), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, A|F },
174 { "panlaw", "set a specific pan law for dual-mono files", OFFSET(pan_law), AV_OPT_TYPE_DOUBLE, {.dbl = -3.01029995663978}, -10.0, 0.0, A|F },
175 { "target", "set a specific target level in LUFS (-23 to 0)", OFFSET(target), AV_OPT_TYPE_INT, {.i64 = -23}, -23, 0, V|F },
176 { "gauge", "set gauge display type", OFFSET(gauge_type), AV_OPT_TYPE_INT, {.i64 = 0 }, GAUGE_TYPE_MOMENTARY, GAUGE_TYPE_SHORTTERM, V|F, .unit = "gaugetype" },
177 { "momentary", "display momentary value", 0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_MOMENTARY}, INT_MIN, INT_MAX, V|F, .unit = "gaugetype" },
178 { "m", "display momentary value", 0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_MOMENTARY}, INT_MIN, INT_MAX, V|F, .unit = "gaugetype" },
179 { "shortterm", "display short-term value", 0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_SHORTTERM}, INT_MIN, INT_MAX, V|F, .unit = "gaugetype" },
180 { "s", "display short-term value", 0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_SHORTTERM}, INT_MIN, INT_MAX, V|F, .unit = "gaugetype" },
181 { "scale", "sets display method for the stats", OFFSET(scale), AV_OPT_TYPE_INT, {.i64 = 0}, SCALE_TYPE_ABSOLUTE, SCALE_TYPE_RELATIVE, V|F, .unit = "scaletype" },
182 { "absolute", "display absolute values (LUFS)", 0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_ABSOLUTE}, INT_MIN, INT_MAX, V|F, .unit = "scaletype" },
183 { "LUFS", "display absolute values (LUFS)", 0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_ABSOLUTE}, INT_MIN, INT_MAX, V|F, .unit = "scaletype" },
184 { "relative", "display values relative to target (LU)", 0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_RELATIVE}, INT_MIN, INT_MAX, V|F, .unit = "scaletype" },
185 { "LU", "display values relative to target (LU)", 0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_RELATIVE}, INT_MIN, INT_MAX, V|F, .unit = "scaletype" },
186 { "integrated", "integrated loudness (LUFS)", OFFSET(integrated_loudness), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, -DBL_MAX, DBL_MAX, A|F|X|R },
187 { "range", "loudness range (LU)", OFFSET(loudness_range), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, -DBL_MAX, DBL_MAX, A|F|X|R },
188 { "lra_low", "LRA low (LUFS)", OFFSET(lra_low), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, -DBL_MAX, DBL_MAX, A|F|X|R },
189 { "lra_high", "LRA high (LUFS)", OFFSET(lra_high), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, -DBL_MAX, DBL_MAX, A|F|X|R },
190 { "sample_peak", "sample peak (dBFS)", OFFSET(sample_peak), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, -DBL_MAX, DBL_MAX, A|F|X|R },
191 { "true_peak", "true peak (dBFS)", OFFSET(true_peak), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, -DBL_MAX, DBL_MAX, A|F|X|R },
192 { NULL },
193};
194
196
197static const uint8_t graph_colors[] = {
198 0xdd, 0x66, 0x66, // value above 1LU non reached below -1LU (impossible)
199 0x66, 0x66, 0xdd, // value below 1LU non reached below -1LU
200 0x96, 0x33, 0x33, // value above 1LU reached below -1LU (impossible)
201 0x33, 0x33, 0x96, // value below 1LU reached below -1LU
202 0xdd, 0x96, 0x96, // value above 1LU line non reached below -1LU (impossible)
203 0x96, 0x96, 0xdd, // value below 1LU line non reached below -1LU
204 0xdd, 0x33, 0x33, // value above 1LU line reached below -1LU (impossible)
205 0x33, 0x33, 0xdd, // value below 1LU line reached below -1LU
206 0xdd, 0x66, 0x66, // value above 1LU non reached above -1LU
207 0x66, 0xdd, 0x66, // value below 1LU non reached above -1LU
208 0x96, 0x33, 0x33, // value above 1LU reached above -1LU
209 0x33, 0x96, 0x33, // value below 1LU reached above -1LU
210 0xdd, 0x96, 0x96, // value above 1LU line non reached above -1LU
211 0x96, 0xdd, 0x96, // value below 1LU line non reached above -1LU
212 0xdd, 0x33, 0x33, // value above 1LU line reached above -1LU
213 0x33, 0xdd, 0x33, // value below 1LU line reached above -1LU
214};
215
216static const uint8_t *get_graph_color(const EBUR128Context *ebur128, int v, int y)
217{
218 const int above_opt_max = y > ebur128->y_opt_max;
219 const int below_opt_min = y < ebur128->y_opt_min;
220 const int reached = y >= v;
221 const int line = ebur128->y_line_ref[y] || y == ebur128->y_zero_lu;
222 const int colorid = 8*below_opt_min+ 4*line + 2*reached + above_opt_max;
223 return graph_colors + 3*colorid;
224}
225
226static inline int lu_to_y(const EBUR128Context *ebur128, double v)
227{
228 v += 2 * ebur128->meter; // make it in range [0;...]
229 v = av_clipf(v, 0, ebur128->scale_range); // make sure it's in the graph scale
230 v = ebur128->scale_range - v; // invert value (y=0 is on top)
231 return v * ebur128->graph.h / ebur128->scale_range; // rescale from scale range to px height
232}
233
234#define FONT8 0
235#define FONT16 1
236
237static const uint8_t font_colors[] = {
238 0xdd, 0xdd, 0x00,
239 0x00, 0x96, 0x96,
240};
241
242static void drawtext(AVFrame *pic, int x, int y, int ftid, const uint8_t *color, const char *fmt, ...)
243{
244 int i;
245 char buf[128] = {0};
246 const uint8_t *font;
247 int font_height;
248 va_list vl;
249
250 if (ftid == FONT16) font = avpriv_vga16_font_get(), font_height = 16;
251 else if (ftid == FONT8) font = avpriv_cga_font_get(), font_height = 8;
252 else return;
253
254 va_start(vl, fmt);
255 vsnprintf(buf, sizeof(buf), fmt, vl);
256 va_end(vl);
257
258 for (i = 0; buf[i]; i++) {
259 int char_y, mask;
260 uint8_t *p = pic->data[0] + y*pic->linesize[0] + (x + i*8)*3;
261
262 for (char_y = 0; char_y < font_height; char_y++) {
263 for (mask = 0x80; mask; mask >>= 1) {
264 if (font[buf[i] * font_height + char_y] & mask)
265 memcpy(p, color, 3);
266 else
267 memcpy(p, "\x00\x00\x00", 3);
268 p += 3;
269 }
270 p += pic->linesize[0] - 8*3;
271 }
272 }
273}
274
275static void drawline(AVFrame *pic, int x, int y, int len, int step)
276{
277 int i;
278 uint8_t *p = pic->data[0] + y*pic->linesize[0] + x*3;
279
280 for (i = 0; i < len; i++) {
281 memcpy(p, "\x00\xff\x00", 3);
282 p += step;
283 }
284}
285
287{
288 int i, x, y;
289 uint8_t *p;
290 FilterLink *l = ff_filter_link(outlink);
291 AVFilterContext *ctx = outlink->src;
292 EBUR128Context *ebur128 = ctx->priv;
293 AVFrame *outpicref;
294
295 /* check if there is enough space to represent everything decently */
296 if (ebur128->w < 640 || ebur128->h < 480) {
297 av_log(ctx, AV_LOG_ERROR, "Video size %dx%d is too small, "
298 "minimum size is 640x480\n", ebur128->w, ebur128->h);
299 return AVERROR(EINVAL);
300 }
301 outlink->w = ebur128->w;
302 outlink->h = ebur128->h;
303 outlink->sample_aspect_ratio = (AVRational){1,1};
304 l->frame_rate = av_make_q(10, 1);
305 outlink->time_base = av_inv_q(l->frame_rate);
306
307#define PAD 8
308
309 /* configure text area position and size */
310 ebur128->text.x = PAD;
311 ebur128->text.y = 40;
312 ebur128->text.w = 3 * 8; // 3 characters
313 ebur128->text.h = ebur128->h - PAD - ebur128->text.y;
314
315 /* configure gauge position and size */
316 ebur128->gauge.w = 20;
317 ebur128->gauge.h = ebur128->text.h;
318 ebur128->gauge.x = ebur128->w - PAD - ebur128->gauge.w;
319 ebur128->gauge.y = ebur128->text.y;
320
321 /* configure graph position and size */
322 ebur128->graph.x = ebur128->text.x + ebur128->text.w + PAD;
323 ebur128->graph.y = ebur128->gauge.y;
324 ebur128->graph.w = ebur128->gauge.x - ebur128->graph.x - PAD;
325 ebur128->graph.h = ebur128->gauge.h;
326
327 /* graph and gauge share the LU-to-pixel code */
328 av_assert0(ebur128->graph.h == ebur128->gauge.h);
329
330 /* prepare the initial picref buffer */
331 av_frame_free(&ebur128->outpicref);
332 ebur128->outpicref = outpicref =
333 ff_get_video_buffer(outlink, outlink->w, outlink->h);
334 if (!outpicref)
335 return AVERROR(ENOMEM);
336 outpicref->sample_aspect_ratio = (AVRational){1,1};
337
338 /* init y references values (to draw LU lines) */
339 ebur128->y_line_ref = av_calloc(ebur128->graph.h + 1, sizeof(*ebur128->y_line_ref));
340 if (!ebur128->y_line_ref)
341 return AVERROR(ENOMEM);
342
343 /* black background */
344 for (int y = 0; y < ebur128->h; y++)
345 memset(outpicref->data[0] + y * outpicref->linesize[0], 0, ebur128->w * 3);
346
347 /* draw LU legends */
348 drawtext(outpicref, PAD, PAD+16, FONT8, font_colors+3, " LU");
349 for (i = ebur128->meter; i >= -ebur128->meter * 2; i--) {
350 y = lu_to_y(ebur128, i);
351 x = PAD + (i < 10 && i > -10) * 8;
352 ebur128->y_line_ref[y] = i;
353 y -= 4; // -4 to center vertically
354 drawtext(outpicref, x, y + ebur128->graph.y, FONT8, font_colors+3,
355 "%c%d", i < 0 ? '-' : i > 0 ? '+' : ' ', FFABS(i));
356 }
357
358 /* draw graph */
359 ebur128->y_zero_lu = lu_to_y(ebur128, 0);
360 ebur128->y_opt_max = lu_to_y(ebur128, 1);
361 ebur128->y_opt_min = lu_to_y(ebur128, -1);
362 p = outpicref->data[0] + ebur128->graph.y * outpicref->linesize[0]
363 + ebur128->graph.x * 3;
364 for (y = 0; y < ebur128->graph.h; y++) {
365 const uint8_t *c = get_graph_color(ebur128, INT_MAX, y);
366
367 for (x = 0; x < ebur128->graph.w; x++)
368 memcpy(p + x*3, c, 3);
369 p += outpicref->linesize[0];
370 }
371
372 /* draw fancy rectangles around the graph and the gauge */
373#define DRAW_RECT(r) do { \
374 drawline(outpicref, r.x, r.y - 1, r.w, 3); \
375 drawline(outpicref, r.x, r.y + r.h, r.w, 3); \
376 drawline(outpicref, r.x - 1, r.y, r.h, outpicref->linesize[0]); \
377 drawline(outpicref, r.x + r.w, r.y, r.h, outpicref->linesize[0]); \
378} while (0)
379 DRAW_RECT(ebur128->graph);
380 DRAW_RECT(ebur128->gauge);
381
382 return 0;
383}
384
386{
387 AVFilterContext *ctx = inlink->dst;
388 EBUR128Context *ebur128 = ctx->priv;
389
390 /* Unofficial reversed parametrization of PRE
391 * and RLB from 48kHz */
392
393 double f0 = 1681.974450955533;
394 double G = 3.999843853973347;
395 double Q = 0.7071752369554196;
396
397 double K = tan(M_PI * f0 / (double)inlink->sample_rate);
398 double Vh = pow(10.0, G / 20.0);
399 double Vb = pow(Vh, 0.4996667741545416);
400
401 double a0 = 1.0 + K / Q + K * K;
402
403 ebur128->dsp.pre.b0 = (Vh + Vb * K / Q + K * K) / a0;
404 ebur128->dsp.pre.b1 = 2.0 * (K * K - Vh) / a0;
405 ebur128->dsp.pre.b2 = (Vh - Vb * K / Q + K * K) / a0;
406 ebur128->dsp.pre.a1 = 2.0 * (K * K - 1.0) / a0;
407 ebur128->dsp.pre.a2 = (1.0 - K / Q + K * K) / a0;
408
409 f0 = 38.13547087602444;
410 Q = 0.5003270373238773;
411 K = tan(M_PI * f0 / (double)inlink->sample_rate);
412
413 ebur128->dsp.rlb.b0 = 1.0;
414 ebur128->dsp.rlb.b1 = -2.0;
415 ebur128->dsp.rlb.b2 = 1.0;
416 ebur128->dsp.rlb.a1 = 2.0 * (K * K - 1.0) / (1.0 + K / Q + K * K);
417 ebur128->dsp.rlb.a2 = (1.0 - K / Q + K * K) / (1.0 + K / Q + K * K);
418
419 /* Force 100ms framing in case of metadata injection: the frames must have
420 * a granularity of the window overlap to be accurately exploited.
421 * As for the true peaks mode, it just simplifies the resampling buffer
422 * allocation and the lookup in it (since sample buffers differ in size, it
423 * can be more complex to integrate in the one-sample loop of
424 * filter_frame()). */
425 if (ebur128->metadata || (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS))
426 ebur128->nb_samples = FFMAX(inlink->sample_rate / 10, 1);
427 return 0;
428}
429
431{
432 int i;
433 AVFilterContext *ctx = outlink->src;
434 EBUR128Context *ebur128 = ctx->priv;
435 const int nb_channels = outlink->ch_layout.nb_channels;
436
437 /* Height channels always use a weight of 1.0 in ITU-R BS.1770. */
438#define WEIGHT_1_41_MASK (AV_CH_BACK_LEFT |AV_CH_BACK_CENTER | \
439 AV_CH_BACK_RIGHT |AV_CH_SIDE_LEFT | \
440 AV_CH_SIDE_RIGHT |AV_CH_SURROUND_DIRECT_LEFT | \
441 AV_CH_SURROUND_DIRECT_RIGHT)
442
443 ebur128->nb_channels = nb_channels;
444 ebur128->dsp.y = av_calloc(nb_channels, 3 * sizeof(*ebur128->dsp.y));
445 ebur128->dsp.z = av_calloc(nb_channels, 3 * sizeof(*ebur128->dsp.z));
446 ebur128->ch_weighting = av_calloc(nb_channels, sizeof(*ebur128->ch_weighting));
447 if (!ebur128->ch_weighting || !ebur128->dsp.y || !ebur128->dsp.z)
448 return AVERROR(ENOMEM);
449
450#define I400_BINS(x) ((x) * 2 / 5)
451#define I3000_BINS(x) ((x) * 3)
452
453 if (outlink->sample_rate > INT_MAX/3U || outlink->sample_rate < 3)
454 return AVERROR(EINVAL);
455
456 ebur128->i400.cache_size = I400_BINS(outlink->sample_rate);
457 ebur128->i3000.cache_size = I3000_BINS(outlink->sample_rate);
458 size_t i400_count, i3000_count;
459 if (av_size_mult(nb_channels, ebur128->i400.cache_size, &i400_count) < 0 || i400_count > INT_MAX ||
460 av_size_mult(nb_channels, ebur128->i3000.cache_size, &i3000_count) < 0 || i3000_count > INT_MAX)
461 return AVERROR(EINVAL);
462 ebur128->i400.sum = av_calloc(nb_channels, sizeof(*ebur128->i400.sum));
463 ebur128->i3000.sum = av_calloc(nb_channels, sizeof(*ebur128->i3000.sum));
464 ebur128->i400.cache = av_calloc(i400_count, sizeof(*ebur128->i400.cache));
465 ebur128->i3000.cache = av_calloc(i3000_count, sizeof(*ebur128->i3000.cache));
466 if (!ebur128->i400.sum || !ebur128->i3000.sum ||
467 !ebur128->i400.cache || !ebur128->i3000.cache)
468 return AVERROR(ENOMEM);
469
470 for (i = 0; i < nb_channels; i++) {
471 /* channel weighting */
472 const enum AVChannel chl = av_channel_layout_channel_from_index(&outlink->ch_layout, i);
473 if (chl == AV_CHAN_LOW_FREQUENCY || chl == AV_CHAN_LOW_FREQUENCY_2) {
474 ebur128->ch_weighting[i] = 0;
475 } else if (chl < 64 && (1ULL << chl) & WEIGHT_1_41_MASK) {
476 ebur128->ch_weighting[i] = 1.41;
477 } else {
478 ebur128->ch_weighting[i] = 1.0;
479 }
480 }
481
482#if CONFIG_SWRESAMPLE
483 if (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS) {
484 int ret;
485
486 ebur128->swr_buf = av_malloc_array(nb_channels, 19200 * sizeof(double));
487 ebur128->true_peaks = av_calloc(nb_channels, sizeof(*ebur128->true_peaks));
488 ebur128->true_peaks_per_frame = av_calloc(nb_channels, sizeof(*ebur128->true_peaks_per_frame));
489 ebur128->swr_ctx = swr_alloc();
490 if (!ebur128->swr_buf || !ebur128->true_peaks ||
491 !ebur128->true_peaks_per_frame || !ebur128->swr_ctx)
492 return AVERROR(ENOMEM);
493
494 av_opt_set_chlayout(ebur128->swr_ctx, "in_chlayout", &outlink->ch_layout, 0);
495 av_opt_set_int(ebur128->swr_ctx, "in_sample_rate", outlink->sample_rate, 0);
496 av_opt_set_sample_fmt(ebur128->swr_ctx, "in_sample_fmt", outlink->format, 0);
497
498 av_opt_set_chlayout(ebur128->swr_ctx, "out_chlayout", &outlink->ch_layout, 0);
499 av_opt_set_int(ebur128->swr_ctx, "out_sample_rate", 192000, 0);
500 av_opt_set_sample_fmt(ebur128->swr_ctx, "out_sample_fmt", outlink->format, 0);
501
502 ret = swr_init(ebur128->swr_ctx);
503 if (ret < 0)
504 return ret;
505 }
506#endif
507
508 if (ebur128->peak_mode & PEAK_MODE_SAMPLES_PEAKS) {
509 ebur128->sample_peaks = av_calloc(nb_channels, sizeof(*ebur128->sample_peaks));
510 if (!ebur128->sample_peaks)
511 return AVERROR(ENOMEM);
512 }
513
514#if ARCH_X86 && HAVE_X86ASM
515 ff_ebur128_init_x86(&ebur128->dsp, nb_channels);
516#endif
517 return 0;
518}
519
520#define ENERGY(loudness) (ff_exp10(((loudness) + 0.691) / 10.))
521#define LOUDNESS(energy) (-0.691 + 10 * log10(energy))
522#define DBFS(energy) (20 * log10(energy))
523
524static struct hist_entry *get_histogram(void)
525{
526 int i;
527 struct hist_entry *h = av_calloc(HIST_SIZE, sizeof(*h));
528
529 if (!h)
530 return NULL;
531 for (i = 0; i < HIST_SIZE; i++) {
532 h[i].loudness = i / (double)HIST_GRAIN + ABS_THRES;
533 h[i].energy = ENERGY(h[i].loudness);
534 }
535 return h;
536}
537
539{
540 EBUR128Context *ebur128 = ctx->priv;
541 AVFilterPad pad;
542 int ret;
543
544 if (ebur128->loglevel != AV_LOG_INFO &&
545 ebur128->loglevel != AV_LOG_QUIET &&
546 ebur128->loglevel != AV_LOG_VERBOSE) {
547 if (ebur128->do_video || ebur128->metadata)
548 ebur128->loglevel = AV_LOG_VERBOSE;
549 else
550 ebur128->loglevel = AV_LOG_INFO;
551 }
552
553 if (!CONFIG_SWRESAMPLE && (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS)) {
555 "True-peak mode requires libswresample to be performed\n");
556 return AVERROR(EINVAL);
557 }
558
559 // if meter is +9 scale, scale range is from -18 LU to +9 LU (or 3*9)
560 // if meter is +18 scale, scale range is from -36 LU to +18 LU (or 3*18)
561 ebur128->scale_range = 3 * ebur128->meter;
562
563 ebur128->i400.histogram = get_histogram();
564 ebur128->i3000.histogram = get_histogram();
565 if (!ebur128->i400.histogram || !ebur128->i3000.histogram)
566 return AVERROR(ENOMEM);
567
569 ebur128->loudness_range = 0;
570
571 /* insert output pads */
572 if (ebur128->do_video) {
573 pad = (AVFilterPad){
574 .name = "out0",
575 .type = AVMEDIA_TYPE_VIDEO,
576 .config_props = config_video_output,
577 };
578 ret = ff_append_outpad(ctx, &pad);
579 if (ret < 0)
580 return ret;
581 }
582 pad = (AVFilterPad){
583 .name = ebur128->do_video ? "out1" : "out0",
584 .type = AVMEDIA_TYPE_AUDIO,
585 .config_props = config_audio_output,
586 };
587 ret = ff_append_outpad(ctx, &pad);
588 if (ret < 0)
589 return ret;
590
591 /* summary */
592 av_log(ctx, AV_LOG_VERBOSE, "EBU +%d scale\n", ebur128->meter);
593
596 return 0;
597}
598
599#define HIST_POS(power) (int)(((power) - ABS_THRES) * HIST_GRAIN)
600
601/* loudness and power should be set such as loudness = -0.691 +
602 * 10*log10(power), we just avoid doing that calculus two times */
603static int gate_update(struct integrator *integ, double power,
604 double loudness, int gate_thres)
605{
606 int ipower;
607 double relative_threshold;
608 int gate_hist_pos;
609
610 /* update powers histograms by incrementing current power count */
611 ipower = av_clip(HIST_POS(loudness), 0, HIST_SIZE - 1);
612 integ->histogram[ipower].count++;
613
614 /* compute relative threshold and get its position in the histogram */
615 integ->sum_kept_powers += power;
616 integ->nb_kept_powers++;
617 relative_threshold = integ->sum_kept_powers / integ->nb_kept_powers;
618 if (!relative_threshold)
619 relative_threshold = 1e-12;
620 integ->rel_threshold = LOUDNESS(relative_threshold) + gate_thres;
621 gate_hist_pos = av_clip(HIST_POS(integ->rel_threshold), 0, HIST_SIZE - 1);
622
623 return gate_hist_pos;
624}
625
627 const double *restrict samples,
628 double *restrict cache_400,
629 double *restrict cache_3000,
630 double *restrict sum_400,
631 double *restrict sum_3000,
632 const int nb_channels)
633{
634 const EBUR128Biquad pre = dsp->pre;
635 const EBUR128Biquad rlb = dsp->rlb;
636
637 for (int ch = 0; ch < nb_channels; ch++) {
638 /* Y[i] = X[i]*b0 + X[i-1]*b1 + X[i-2]*b2 - Y[i-1]*a1 - Y[i-2]*a2 */
639#define FILTER(DST, SRC, FILT) do { \
640 const double tmp = DST[0] = FILT.b0 * SRC + DST[1]; \
641 DST[1] = FILT.b1 * SRC + DST[2] - FILT.a1 * tmp; \
642 DST[2] = FILT.b2 * SRC - FILT.a2 * tmp; \
643} while (0)
644
645 const double x = samples[ch];
646 double *restrict y = &dsp->y[3 * ch];
647 double *restrict z = &dsp->z[3 * ch];
648
649 // TODO: merge both filters in one?
650 FILTER(y, x, pre); // apply pre-filter
651 FILTER(z, *y, rlb); // apply RLB-filter
652
653 /* add the new value, and limit the sum to the cache size (400ms or 3s)
654 * by removing the oldest one */
655 const double bin = *z * *z;
656 sum_400 [ch] += bin - cache_400[ch];
657 sum_3000[ch] += bin - cache_3000[ch];
658 cache_400[ch] = cache_3000[ch] = bin;
659 }
660}
661
662double ff_ebur128_find_peak_c(double *restrict ch_peaks, const int nb_channels,
663 const double *samples, const int nb_samples)
664{
665 double maxpeak = 0.0;
666 for (int ch = 0; ch < nb_channels; ch++) {
667 double ch_peak = ch_peaks[ch];
668 for (int i = 0; i < nb_samples; i++) {
669 const double sample = fabs(samples[i * nb_channels + ch]);
670 ch_peak = FFMAX(ch_peak, sample);
671 }
672 maxpeak = FFMAX(maxpeak, ch_peak);
673 ch_peaks[ch] = ch_peak;
674 }
675
676 return maxpeak;
677}
678
679static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
680{
681 int ret;
682 AVFilterContext *ctx = inlink->dst;
683 EBUR128Context *ebur128 = ctx->priv;
684 const EBUR128DSPContext *dsp = &ebur128->dsp;
685 const int nb_channels = ebur128->nb_channels;
686 const int nb_samples = insamples->nb_samples;
687 const double *samples = (double *)insamples->data[0];
688 AVFrame *pic;
689
690#if CONFIG_SWRESAMPLE
691 if (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS && ebur128->idx_insample == 0) {
692 const double *swr_samples = ebur128->swr_buf;
693 int ret = swr_convert(ebur128->swr_ctx, (uint8_t**)&ebur128->swr_buf, 19200,
694 (const uint8_t **)insamples->data, nb_samples);
695 if (ret < 0)
696 return ret;
697
698 memset(ebur128->true_peaks_per_frame, 0,
699 nb_channels * sizeof(*ebur128->true_peaks_per_frame));
700
701 double peak = dsp->find_peak(ebur128->true_peaks_per_frame, nb_channels,
702 swr_samples, ret);
703
704 for (int ch = 0; ch < nb_channels; ch++) {
705 peak = FFMAX(peak, ebur128->true_peaks[ch]);
706 ebur128->true_peaks[ch] = FFMAX(ebur128->true_peaks[ch],
707 ebur128->true_peaks_per_frame[ch]);
708 }
709
710 ebur128->true_peak = DBFS(peak);
711 }
712#endif
713
714 if (ebur128->peak_mode & PEAK_MODE_SAMPLES_PEAKS) {
715 double peak = dsp->find_peak(ebur128->sample_peaks, nb_channels,
716 samples, nb_samples);
717 ebur128->sample_peak = DBFS(peak);
718 }
719
720 for (int idx_insample = ebur128->idx_insample; idx_insample < nb_samples; idx_insample++) {
721 const int bin_id_400 = ebur128->i400.cache_pos++;
722 const int bin_id_3000 = ebur128->i3000.cache_pos++;
723
724 if (ebur128->i400.cache_pos == ebur128->i400.cache_size) {
725 ebur128->i400.filled = 1;
726 ebur128->i400.cache_pos = 0;
727 }
728
729 if (ebur128->i3000.cache_pos == ebur128->i3000.cache_size) {
730 ebur128->i3000.filled = 1;
731 ebur128->i3000.cache_pos = 0;
732 }
733
734 dsp->filter_channels(dsp, &samples[idx_insample * nb_channels],
735 &ebur128->i400.cache[bin_id_400 * nb_channels],
736 &ebur128->i3000.cache[bin_id_3000 * nb_channels],
737 ebur128->i400.sum, ebur128->i3000.sum,
738 nb_channels);
739
740 /* For integrated loudness, gating blocks are 400ms long with 75%
741 * overlap (see BS.1770-2 p5), so a re-computation is needed each 100ms
742 * (4800 samples at 48kHz). */
743 if (++ebur128->sample_count == inlink->sample_rate / 10) {
744 double loudness_400, loudness_3000;
745 double power_400 = 1e-12, power_3000 = 1e-12;
746 AVFilterLink *outlink = ctx->outputs[0];
747 const int64_t pts = insamples->pts +
748 av_rescale_q(idx_insample, (AVRational){ 1, inlink->sample_rate },
749 ctx->outputs[ebur128->do_video]->time_base);
750
751 ebur128->sample_count = 0;
752
753#define COMPUTE_LOUDNESS(m, time) do { \
754 if (ebur128->i##time.filled) { \
755 /* weighting sum of the last <time> ms */ \
756 for (int ch = 0; ch < nb_channels; ch++) \
757 power_##time += ebur128->ch_weighting[ch] * ebur128->i##time.sum[ch]; \
758 power_##time /= I##time##_BINS(inlink->sample_rate); \
759 } \
760 loudness_##time = LOUDNESS(power_##time); \
761} while (0)
762
763 COMPUTE_LOUDNESS(M, 400);
764 COMPUTE_LOUDNESS(S, 3000);
765
766 /* Integrated loudness */
767#define I_GATE_THRES -10 // initially defined to -8 LU in the first EBU standard
768
769 if (loudness_400 >= ABS_THRES) {
770 double integrated_sum = 0.0;
771 uint64_t nb_integrated = 0;
772 int gate_hist_pos = gate_update(&ebur128->i400, power_400,
773 loudness_400, I_GATE_THRES);
774
775 /* compute integrated loudness by summing the histogram values
776 * above the relative threshold */
777 for (int i = gate_hist_pos; i < HIST_SIZE; i++) {
778 const unsigned nb_v = ebur128->i400.histogram[i].count;
779 nb_integrated += nb_v;
780 integrated_sum += nb_v * ebur128->i400.histogram[i].energy;
781 }
782 if (nb_integrated) {
783 ebur128->integrated_loudness = LOUDNESS(integrated_sum / nb_integrated);
784 /* dual-mono correction */
785 if (nb_channels == 1 && ebur128->dual_mono) {
786 ebur128->integrated_loudness -= ebur128->pan_law;
787 }
788 }
789 }
790
791 /* LRA */
792#define LRA_GATE_THRES -20
793#define LRA_LOWER_PRC 10
794#define LRA_HIGHER_PRC 95
795
796 /* XXX: example code in EBU 3342 is ">=" but formula in BS.1770
797 * specs is ">" */
798 if (loudness_3000 >= ABS_THRES) {
799 uint64_t nb_powers = 0;
800 int gate_hist_pos = gate_update(&ebur128->i3000, power_3000,
801 loudness_3000, LRA_GATE_THRES);
802
803 for (int i = gate_hist_pos; i < HIST_SIZE; i++)
804 nb_powers += ebur128->i3000.histogram[i].count;
805 if (nb_powers) {
806 uint64_t n, nb_pow;
807
808 /* get lower loudness to consider */
809 n = 0;
810 nb_pow = LRA_LOWER_PRC * nb_powers * 0.01 + 0.5;
811 for (int i = gate_hist_pos; i < HIST_SIZE; i++) {
812 n += ebur128->i3000.histogram[i].count;
813 if (n >= nb_pow) {
814 ebur128->lra_low = ebur128->i3000.histogram[i].loudness;
815 break;
816 }
817 }
818
819 /* get higher loudness to consider */
820 n = nb_powers;
821 nb_pow = LRA_HIGHER_PRC * nb_powers * 0.01 + 0.5;
822 for (int i = HIST_SIZE - 1; i >= 0; i--) {
823 n -= FFMIN(n, ebur128->i3000.histogram[i].count);
824 if (n < nb_pow) {
825 ebur128->lra_high = ebur128->i3000.histogram[i].loudness;
826 break;
827 }
828 }
829
830 // XXX: show low & high on the graph?
831 ebur128->loudness_range = ebur128->lra_high - ebur128->lra_low;
832 }
833 }
834
835 /* dual-mono correction */
836 if (nb_channels == 1 && ebur128->dual_mono) {
837 loudness_400 -= ebur128->pan_law;
838 loudness_3000 -= ebur128->pan_law;
839 }
840
841#define LOG_FMT "TARGET:%d LUFS M:%6.1f S:%6.1f I:%6.1f %s LRA:%6.1f LU"
842
843 /* push one video frame */
844 if (ebur128->do_video) {
845 AVFrame *clone;
846 int x, y;
847 uint8_t *p;
848 double gauge_value;
849 int y_loudness_lu_graph, y_loudness_lu_gauge;
850
851 if (ebur128->gauge_type == GAUGE_TYPE_MOMENTARY) {
852 gauge_value = loudness_400 - ebur128->target;
853 } else {
854 gauge_value = loudness_3000 - ebur128->target;
855 }
856
857 y_loudness_lu_graph = lu_to_y(ebur128, loudness_3000 - ebur128->target);
858 y_loudness_lu_gauge = lu_to_y(ebur128, gauge_value);
859
860 ret = ff_inlink_make_frame_writable(outlink, &ebur128->outpicref);
861 if (ret < 0) {
862 av_frame_free(&insamples);
863 ebur128->insamples = NULL;
864 return ret;
865 }
866 pic = ebur128->outpicref;
867 /* draw the graph using the short-term loudness */
868 p = pic->data[0] + ebur128->graph.y*pic->linesize[0] + ebur128->graph.x*3;
869 for (y = 0; y < ebur128->graph.h; y++) {
870 const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_graph, y);
871
872 memmove(p, p + 3, (ebur128->graph.w - 1) * 3);
873 memcpy(p + (ebur128->graph.w - 1) * 3, c, 3);
874 p += pic->linesize[0];
875 }
876
877 /* draw the gauge using either momentary or short-term loudness */
878 p = pic->data[0] + ebur128->gauge.y*pic->linesize[0] + ebur128->gauge.x*3;
879 for (y = 0; y < ebur128->gauge.h; y++) {
880 const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_gauge, y);
881
882 for (x = 0; x < ebur128->gauge.w; x++)
883 memcpy(p + x*3, c, 3);
884 p += pic->linesize[0];
885 }
886
887 /* draw textual info */
888 if (ebur128->scale == SCALE_TYPE_ABSOLUTE) {
889 drawtext(pic, PAD, PAD - PAD/2, FONT16, font_colors,
890 LOG_FMT " ", // padding to erase trailing characters
891 ebur128->target, loudness_400, loudness_3000,
892 ebur128->integrated_loudness, "LUFS", ebur128->loudness_range);
893 } else {
894 drawtext(pic, PAD, PAD - PAD/2, FONT16, font_colors,
895 LOG_FMT " ", // padding to erase trailing characters
896 ebur128->target, loudness_400-ebur128->target, loudness_3000-ebur128->target,
897 ebur128->integrated_loudness-ebur128->target, "LU", ebur128->loudness_range);
898 }
899
900 /* set pts and push frame */
901 pic->pts = av_rescale_q(pts, inlink->time_base, outlink->time_base);
902 pic->duration = 1;
903 clone = av_frame_clone(pic);
904 if (!clone)
905 return AVERROR(ENOMEM);
906 ebur128->idx_insample = idx_insample + 1;
908 return ff_filter_frame(outlink, clone);
909 }
910
911 if (ebur128->metadata) { /* happens only once per filter_frame call */
912 char metabuf[128];
913#define META_PREFIX "lavfi.r128."
914
915#define SET_META(name, var) do { \
916 snprintf(metabuf, sizeof(metabuf), "%.3f", var); \
917 av_dict_set(&insamples->metadata, name, metabuf, 0); \
918} while (0)
919
920#define SET_META_PEAK(name, ptype) do { \
921 if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) { \
922 double max_peak = 0.0; \
923 char key[64]; \
924 for (int ch = 0; ch < nb_channels; ch++) { \
925 snprintf(key, sizeof(key), \
926 META_PREFIX AV_STRINGIFY(name) "_peaks_ch%d", ch); \
927 max_peak = fmax(max_peak, ebur128->name##_peaks[ch]); \
928 SET_META(key, ebur128->name##_peaks[ch]); \
929 } \
930 snprintf(key, sizeof(key), \
931 META_PREFIX AV_STRINGIFY(name) "_peak"); \
932 SET_META(key, max_peak); \
933 } \
934} while (0)
935
936 SET_META(META_PREFIX "M", loudness_400);
937 SET_META(META_PREFIX "S", loudness_3000);
939 SET_META(META_PREFIX "LRA", ebur128->loudness_range);
940 SET_META(META_PREFIX "LRA.low", ebur128->lra_low);
941 SET_META(META_PREFIX "LRA.high", ebur128->lra_high);
942
944 SET_META_PEAK(true, TRUE);
945 }
946
947 if (ebur128->loglevel != AV_LOG_QUIET) {
948 AVBPrint bp;
949
951 if (ebur128->scale == SCALE_TYPE_ABSOLUTE) {
952 av_bprintf(&bp, "t: %-10s " LOG_FMT,
953 av_ts2timestr(pts, &outlink->time_base),
954 ebur128->target, loudness_400, loudness_3000,
955 ebur128->integrated_loudness, "LUFS", ebur128->loudness_range);
956 } else {
957 av_bprintf(&bp, "t: %-10s " LOG_FMT,
958 av_ts2timestr(pts, &outlink->time_base),
959 ebur128->target, loudness_400-ebur128->target, loudness_3000-ebur128->target,
960 ebur128->integrated_loudness-ebur128->target, "LU", ebur128->loudness_range);
961 }
962
963#define PRINT_PEAKS(str, sp, ptype) do { \
964 if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) { \
965 av_bprintf(&bp, " " str ":"); \
966 for (int ch = 0; ch < nb_channels; ch++) \
967 av_bprintf(&bp, " %5.1f", DBFS(sp[ch])); \
968 av_bprintf(&bp, " dBFS"); \
969 } \
970} while (0)
971
972 PRINT_PEAKS("SPK", ebur128->sample_peaks, SAMPLES);
973 PRINT_PEAKS("FTPK", ebur128->true_peaks_per_frame, TRUE);
974 PRINT_PEAKS("TPK", ebur128->true_peaks, TRUE);
975 ff_filter_log_lines(ctx, ebur128->loglevel, &bp);
977 }
978 }
979 }
980
981 ebur128->idx_insample = 0;
982 ebur128->insamples = NULL;
983
984 return ff_filter_frame(ctx->outputs[ebur128->do_video], insamples);
985}
986
988{
989 AVFilterLink *inlink = ctx->inputs[0];
990 EBUR128Context *ebur128 = ctx->priv;
991 AVFilterLink *voutlink = ctx->outputs[0];
992 AVFilterLink *outlink = ctx->outputs[ebur128->do_video];
993 int ret;
994
995 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
996 if (ebur128->do_video)
997 FF_FILTER_FORWARD_STATUS_BACK(voutlink, inlink);
998
999 if (!ebur128->insamples) {
1000 AVFrame *in;
1001
1002 if (ebur128->nb_samples > 0) {
1003 ret = ff_inlink_consume_samples(inlink, ebur128->nb_samples, ebur128->nb_samples, &in);
1004 } else {
1005 ret = ff_inlink_consume_frame(inlink, &in);
1006 }
1007 if (ret < 0)
1008 return ret;
1009 if (ret > 0)
1010 ebur128->insamples = in;
1011 }
1012
1013 if (ebur128->insamples)
1014 ret = filter_frame(inlink, ebur128->insamples);
1015
1017 FF_FILTER_FORWARD_WANTED(outlink, inlink);
1018 if (ebur128->do_video)
1019 FF_FILTER_FORWARD_WANTED(voutlink, inlink);
1020
1021 return ret;
1022}
1023
1025 AVFilterFormatsConfig **cfg_in,
1026 AVFilterFormatsConfig **cfg_out)
1027{
1028 const EBUR128Context *ebur128 = ctx->priv;
1030 int out_idx = 0;
1031 int ret;
1032
1034 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
1035
1036 /* set optional output video format */
1037 if (ebur128->do_video) {
1039 if ((ret = ff_formats_ref(formats, &cfg_out[0]->formats)) < 0)
1040 return ret;
1041 out_idx = 1;
1042 }
1043
1044 /* set input and output audio formats
1045 * Note: ff_set_common_* functions are not used because they affect all the
1046 * links, and thus break the video format negotiation */
1048 if ((ret = ff_formats_ref(formats, &cfg_in[0]->formats)) < 0 ||
1049 (ret = ff_formats_ref(formats, &cfg_out[out_idx]->formats)) < 0)
1050 return ret;
1051
1052 return 0;
1053}
1054
1056{
1057 EBUR128Context *ebur128 = ctx->priv;
1058
1059 /* dual-mono correction */
1060 if (ebur128->nb_channels == 1 && ebur128->dual_mono) {
1061 ebur128->i400.rel_threshold -= ebur128->pan_law;
1062 ebur128->i3000.rel_threshold -= ebur128->pan_law;
1063 ebur128->lra_low -= ebur128->pan_law;
1064 ebur128->lra_high -= ebur128->pan_law;
1065 }
1066
1067 if (ebur128->nb_channels > 0) {
1068 AVBPrint bp;
1069
1071 av_bprintf(&bp, "Summary:\n\n"
1072 " Integrated loudness:\n"
1073 " I: %5.1f LUFS\n"
1074 " Threshold: %5.1f LUFS\n\n"
1075 " Loudness range:\n"
1076 " LRA: %5.1f LU\n"
1077 " Threshold: %5.1f LUFS\n"
1078 " LRA low: %5.1f LUFS\n"
1079 " LRA high: %5.1f LUFS",
1080 ebur128->integrated_loudness, ebur128->i400.rel_threshold,
1081 ebur128->loudness_range, ebur128->i3000.rel_threshold,
1082 ebur128->lra_low, ebur128->lra_high);
1083
1084#define PRINT_PEAK_SUMMARY(str, value, ptype) do { \
1085 if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) { \
1086 av_bprintf(&bp, "\n\n " str " peak:\n" \
1087 " Peak: %5.1f dBFS", value); \
1088 } \
1089} while (0)
1090
1091 PRINT_PEAK_SUMMARY("Sample", ebur128->sample_peak, SAMPLES);
1092 PRINT_PEAK_SUMMARY("True", ebur128->true_peak, TRUE);
1093 av_log(ctx, AV_LOG_INFO, "%s\n", bp.str);
1095 }
1096
1097 av_freep(&ebur128->y_line_ref);
1098 av_freep(&ebur128->dsp.y);
1099 av_freep(&ebur128->dsp.z);
1100 av_freep(&ebur128->ch_weighting);
1101 av_freep(&ebur128->true_peaks);
1102 av_freep(&ebur128->sample_peaks);
1103 av_freep(&ebur128->true_peaks_per_frame);
1104 av_freep(&ebur128->i400.sum);
1105 av_freep(&ebur128->i3000.sum);
1106 av_freep(&ebur128->i400.histogram);
1107 av_freep(&ebur128->i3000.histogram);
1108 av_freep(&ebur128->i400.cache);
1109 av_freep(&ebur128->i3000.cache);
1110 av_frame_free(&ebur128->outpicref);
1111#if CONFIG_SWRESAMPLE
1112 av_freep(&ebur128->swr_buf);
1113 swr_free(&ebur128->swr_ctx);
1114#endif
1115}
1116
1117static const AVFilterPad ebur128_inputs[] = {
1118 {
1119 .name = "default",
1120 .type = AVMEDIA_TYPE_AUDIO,
1121 .config_props = config_audio_input,
1122 },
1123};
1124
1126 .p.name = "ebur128",
1127 .p.description = NULL_IF_CONFIG_SMALL("EBU R128 scanner."),
1128 .p.outputs = NULL,
1129 .p.priv_class = &ebur128_class,
1131 .priv_size = sizeof(EBUR128Context),
1132 .init = init,
1133 .uninit = uninit,
1134 .activate = activate,
1137};
static enum AVSampleFormat sample_fmts[]
Definition adpcmenc.c:933
static int query_formats(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out)
Definition aeval.c:246
const FFFilter ff_af_ebur128
Definition f_ebur128.c:1125
static AVFormatContext * ctx
#define A(x)
Definition vpx_arith.h:28
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
#define V
Definition avdct.c:32
static int config_video_output(AVFilterLink *outlink)
int ff_append_outpad(AVFilterContext *f, AVFilterPad *p)
Definition avfilter.c:138
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition avfilter.c:1112
void ff_filter_log_lines(void *ctx, int level, const AVBPrint *bp)
Definition avfilter.c:238
int ff_inlink_consume_samples(AVFilterLink *link, unsigned min, unsigned max, AVFrame **rframe)
Take samples from the link's FIFO and update the link's stats.
Definition avfilter.c:1580
void ff_filter_set_ready(AVFilterContext *filter, unsigned priority)
Mark a filter ready and schedule it for activation.
Definition avfilter.c:232
int ff_inlink_make_frame_writable(AVFilterLink *link, AVFrame **rframe)
Make sure a frame is writable.
Definition avfilter.c:1623
int ff_inlink_consume_frame(AVFilterLink *link, AVFrame **rframe)
Take a frame from the link's FIFO and update the link's stats.
Definition avfilter.c:1560
Main libavfilter public API header.
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:121
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:68
AVBPrint public header.
#define AV_BPRINT_SIZE_UNLIMITED
#define AV_BPRINT_SIZE_AUTOMATIC
static int FUNC metadata(CodedBitstreamContext *ctx, RWContext *rw, APVRawMetadata *current)
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
Public libavutil channel layout APIs header.
#define av_clip
Definition common.h:100
#define av_clipf
Definition common.h:145
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition common.h:74
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static __device__ float fabs(float a)
Public dictionary API.
#define F(x)
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
#define M(chr)
Definition exr.c:177
@ PEAK_MODE_NONE
Definition f_ebur128.c:139
@ PEAK_MODE_SAMPLES_PEAKS
Definition f_ebur128.c:140
@ PEAK_MODE_TRUE_PEAKS
Definition f_ebur128.c:141
#define META_PREFIX
static int gate_update(struct integrator *integ, double power, double loudness, int gate_thres)
Definition f_ebur128.c:603
void ff_ebur128_filter_channels_c(const EBUR128DSPContext *dsp, const double *restrict samples, double *restrict cache_400, double *restrict cache_3000, double *restrict sum_400, double *restrict sum_3000, const int nb_channels)
Definition f_ebur128.c:626
static void drawtext(AVFrame *pic, int x, int y, int ftid, const uint8_t *color, const char *fmt,...)
Definition f_ebur128.c:242
#define X
Definition f_ebur128.c:158
static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
Definition f_ebur128.c:679
static const uint8_t graph_colors[]
Definition f_ebur128.c:197
#define SET_META_PEAK(name, ptype)
static void drawline(AVFrame *pic, int x, int y, int len, int step)
Definition f_ebur128.c:275
static const uint8_t font_colors[]
Definition f_ebur128.c:237
static const AVFilterPad ebur128_inputs[]
Definition f_ebur128.c:1117
#define PAD
#define DRAW_RECT(r)
#define HIST_POS(power)
Definition f_ebur128.c:599
#define I_GATE_THRES
static int config_audio_output(AVFilterLink *outlink)
Definition f_ebur128.c:430
static struct hist_entry * get_histogram(void)
Definition f_ebur128.c:524
#define LRA_HIGHER_PRC
#define PRINT_PEAK_SUMMARY(str, value, ptype)
#define WEIGHT_1_41_MASK
#define FILTER(DST, SRC, FILT)
#define ENERGY(loudness)
Definition f_ebur128.c:520
#define HIST_SIZE
Definition f_ebur128.c:52
static const AVOption ebur128_options[]
Definition f_ebur128.c:160
static const uint8_t * get_graph_color(const EBUR128Context *ebur128, int v, int y)
Definition f_ebur128.c:216
#define COMPUTE_LOUDNESS(m, time)
#define SET_META(name, var)
#define FONT8
Definition f_ebur128.c:234
#define LOUDNESS(energy)
Definition f_ebur128.c:521
@ GAUGE_TYPE_SHORTTERM
Definition f_ebur128.c:146
@ GAUGE_TYPE_MOMENTARY
Definition f_ebur128.c:145
static int query_formats(const AVFilterContext *ctx, AVFilterFormatsConfig **cfg_in, AVFilterFormatsConfig **cfg_out)
Definition f_ebur128.c:1024
static int activate(AVFilterContext *ctx)
Definition f_ebur128.c:987
#define HIST_GRAIN
defines histogram precision
Definition f_ebur128.c:51
static av_cold void uninit(AVFilterContext *ctx)
Definition f_ebur128.c:1055
#define LRA_GATE_THRES
#define LOG_FMT
static int config_audio_input(AVFilterLink *inlink)
Definition f_ebur128.c:385
double ff_ebur128_find_peak_c(double *restrict ch_peaks, const int nb_channels, const double *samples, const int nb_samples)
Definition f_ebur128.c:662
#define DBFS(energy)
Definition f_ebur128.c:522
#define OFFSET(x)
Definition f_ebur128.c:154
#define ABS_THRES
silence gate: we discard anything below this absolute (LUFS) threshold
Definition f_ebur128.c:49
static int config_video_output(AVFilterLink *outlink)
Definition f_ebur128.c:286
#define I400_BINS(x)
static int lu_to_y(const EBUR128Context *ebur128, double v)
Definition f_ebur128.c:226
#define LRA_LOWER_PRC
#define I3000_BINS(x)
#define PRINT_PEAKS(str, sp, ptype)
#define FONT16
Definition f_ebur128.c:235
@ SCALE_TYPE_ABSOLUTE
Definition f_ebur128.c:150
@ SCALE_TYPE_RELATIVE
Definition f_ebur128.c:151
void ff_ebur128_init_x86(EBUR128DSPContext *dsp, int nb_channels)
internal math functions header
int ret
Definition ffplay.c:391
#define S(s, c, i)
#define sample
int ff_formats_ref(AVFilterFormats *f, AVFilterFormats **ref)
Add ref as a new reference to formats.
Definition formats.c:776
av_warn_unused_result AVFilterFormats * ff_make_sample_format_list(const enum AVSampleFormat *fmts)
Create a list of supported sample formats.
av_warn_unused_result AVFilterFormats * ff_make_pixel_format_list(const enum AVPixelFormat *fmts)
Create a list of supported pixel formats.
@ AV_OPT_TYPE_IMAGE_SIZE
Underlying C type is two consecutive integers.
Definition opt.h:302
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition opt.h:298
@ AV_OPT_TYPE_FLAGS
Underlying C type is unsigned int.
Definition opt.h:254
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_DOUBLE
Underlying C type is double.
Definition opt.h:266
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
#define AVFILTER_FLAG_DYNAMIC_OUTPUTS
The number of the filter outputs is not determined just by AVFilter.outputs.
Definition avfilter.h:167
enum AVChannel av_channel_layout_channel_from_index(const AVChannelLayout *channel_layout, unsigned int idx)
Get the channel with the given index in a channel layout.
AVChannel
@ AV_CHAN_LOW_FREQUENCY
@ AV_CHAN_LOW_FREQUENCY_2
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:234
#define AVERROR(e)
Definition error.h:45
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:65
AVFrame * av_frame_clone(const AVFrame *src)
Create a new frame that references the same data as src.
Definition frame.c:487
#define AV_LOG_QUIET
Print no output.
Definition log.h:192
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition rational.h:71
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition rational.h:159
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
int av_size_mult(size_t a, size_t b, size_t *r)
Multiply two size_t values checking for overflow.
Definition mem.c:671
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
AVSampleFormat
Audio sample formats.
Definition samplefmt.h:55
@ AV_SAMPLE_FMT_NONE
Definition samplefmt.h:56
@ AV_SAMPLE_FMT_DBL
double
Definition samplefmt.h:61
av_cold struct SwrContext * swr_alloc(void)
Allocate SwrContext.
Definition options.c:148
av_cold void swr_free(SwrContext **ss)
Free the given SwrContext and set the pointer to NULL.
Definition swresample.c:137
int attribute_align_arg swr_convert(struct SwrContext *s, uint8_t *const *out_arg, int out_count, const uint8_t *const *in_arg, int in_count)
Convert audio.
Definition swresample.c:776
av_cold int swr_init(struct SwrContext *s)
Initialize context after user parameters have been set.
Definition swresample.c:156
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition opt.c:992
int av_opt_set_chlayout(void *obj, const char *name, const AVChannelLayout *channel_layout, int search_flags)
Definition opt.c:1127
int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags)
Definition opt.c:1102
static av_always_inline void scale(vec_s32 res[4], vec_s16 res_packed[2], const int shift)
#define Q(q)
#define R
Definition huffyuv.h:44
#define G
Definition huffyuv.h:43
static av_cold void uninit(AVBitStreamFilterContext *ctx)
static int activate(AVBitStreamFilterContext *ctx)
#define FF_FILTER_FORWARD_STATUS_ALL(inlink, filter)
Acknowledge the status on an input link and forward it to an output link.
Definition filters.h:729
#define FILTER_INPUTS(array)
Definition filters.h:279
#define FF_FILTER_FORWARD_WANTED(outlink, inlink)
Forward the frame_wanted_out flag from an output link to an input link.
Definition filters.h:744
#define FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink)
Forward the status on an output link to an input link.
Definition filters.h:689
static FilterLink * ff_filter_link(AVFilterLink *link)
Definition filters.h:199
#define AVFILTER_DEFINE_CLASS(fname)
Definition filters.h:493
#define FILTER_QUERY_FUNC2(func)
Definition filters.h:256
#define av_cold
Definition attributes.h:117
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:98
static enum AVPixelFormat pix_fmts[]
Definition libkvazaar.c:296
uint8_t w
Definition llvidencdsp.c:39
static const uint16_t mask[17]
Definition lzw.c:38
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
#define M_PI
Definition mathematics.h:67
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
AVOptions.
#define K
Definition palette.c:25
AVPixelFormat
Pixel format.
Definition pixfmt.h:71
@ AV_PIX_FMT_NONE
Definition pixfmt.h:72
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition pixfmt.h:75
static float power(float r, float g, float b, float max)
formats
Definition signature.h:47
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
An instance of a filter.
Definition avfilter.h:279
Lists of formats / etc.
Definition avfilter.h:120
A list of supported formats for one end of a filter link.
Definition formats.h:64
A filter pad used for either input or output.
Definition filters.h:40
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
int nb_samples
number of audio samples (per channel) described by this frame
Definition frame.h:559
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition frame.h:581
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition frame.h:500
AVRational sample_aspect_ratio
Sample aspect ratio for the video frame, 0/1 if unknown/unspecified.
Definition frame.h:576
int linesize[AV_NUM_DATA_POINTERS]
For video, a positive or negative value, which is typically indicating the size in bytes of each pict...
Definition frame.h:524
int64_t duration
Duration of the frame, in the same units as pts.
Definition frame.h:830
AVOption.
Definition opt.h:428
Rational number (pair of numerator and denominator).
Definition rational.h:58
int gauge_type
whether gauge shows momentary or short
Definition f_ebur128.c:134
int y_opt_max
the y value (pixel position) for 1 LU
Definition f_ebur128.c:108
int idx_insample
current sample position of processed samples in single input frame
Definition f_ebur128.c:117
double sample_peak
global sample peak
Definition f_ebur128.c:89
double true_peak
global true peak
Definition f_ebur128.c:87
int peak_mode
enabled peak modes
Definition f_ebur128.c:86
AVFrame * outpicref
output picture reference, updated regularly
Definition f_ebur128.c:104
int meter
select a EBU mode between +9 and +18
Definition f_ebur128.c:105
int nb_samples
number of samples to consume per single input frame
Definition f_ebur128.c:116
int h
size of the video output
Definition f_ebur128.c:100
struct rect gauge
rectangle for the gauge on the right
Definition f_ebur128.c:103
double lra_high
low and high LRA values
Definition f_ebur128.c:126
double pan_law
pan law value used to calculate dual-mono measurements
Definition f_ebur128.c:132
struct integrator i3000
3s integrator, used for Short term loudness (S), and Loudness Range (LRA)
Definition f_ebur128.c:121
double integrated_loudness
integrated loudness in LUFS (I)
Definition f_ebur128.c:124
double * true_peaks_per_frame
true peaks in a frame per channel
Definition f_ebur128.c:91
int loglevel
log level for frame logging
Definition f_ebur128.c:129
EBUR128DSPContext dsp
Definition f_ebur128.c:83
int y_zero_lu
the y value (pixel position) for 0 LU
Definition f_ebur128.c:107
int metadata
whether or not to inject loudness results in frames
Definition f_ebur128.c:130
int scale_range
the range of LU values according to the meter
Definition f_ebur128.c:106
AVFrame * insamples
input samples reference, updated regularly
Definition f_ebur128.c:118
int do_video
1 if video output enabled, 0 otherwise
Definition f_ebur128.c:99
int nb_channels
number of channels in the input
Definition f_ebur128.c:113
double loudness_range
loudness range in LU (LRA)
Definition f_ebur128.c:125
int dual_mono
whether or not to treat single channel input files as dual-mono
Definition f_ebur128.c:131
int scale
display scale type of statistics
Definition f_ebur128.c:135
struct integrator i400
400ms integrator, used for Momentary loudness (M), and Integrated loudness (I)
Definition f_ebur128.c:120
int y_opt_min
the y value (pixel position) for -1 LU
Definition f_ebur128.c:109
double * ch_weighting
channel weighting mapping
Definition f_ebur128.c:114
double * true_peaks
true peaks per channel
Definition f_ebur128.c:88
struct rect text
rectangle for the LU legend on the left
Definition f_ebur128.c:101
int * y_line_ref
y reference values for drawing the LU lines in the graph and the gauge
Definition f_ebur128.c:110
int sample_count
sample count used for refresh frequency, reset at refresh
Definition f_ebur128.c:115
struct rect graph
rectangle for the main graph in the center
Definition f_ebur128.c:102
double * sample_peaks
sample peaks per channel
Definition f_ebur128.c:90
int target
target level in LUFS used to set relative zero LU in visualization
Definition f_ebur128.c:133
double(* find_peak)(double *ch_peaks, int nb_channels, const double *samples, int nb_samples)
Definition f_ebur128.h:50
void(* filter_channels)(const struct EBUR128DSPContext *dsp, const double *samples, double *cache_400, double *cache_3000, double *sum_400, double *sum_3000, int nb_channels)
Definition f_ebur128.h:43
EBUR128Biquad pre
Definition f_ebur128.h:35
EBUR128Biquad rlb
Definition f_ebur128.h:36
The libswresample context.
A histogram is an array of HIST_SIZE hist_entry storing all the energies recorded (with an accuracy o...
Definition f_ebur128.c:61
double energy
E = 10^((L + 0.691) / 10)
Definition f_ebur128.c:63
unsigned count
how many times the corresponding value occurred
Definition f_ebur128.c:62
double loudness
L = -0.691 + 10 * log10(E)
Definition f_ebur128.c:64
int cache_size
Definition f_ebur128.c:70
double rel_threshold
relative threshold
Definition f_ebur128.c:73
struct hist_entry * histogram
histogram of the powers, used to compute LRA and I
Definition f_ebur128.c:76
double * cache
window of filtered samples (N ms)
Definition f_ebur128.c:68
double * sum
sum of the last N ms filtered samples (cache content)
Definition f_ebur128.c:71
int nb_kept_powers
number of sum above absolute threshold
Definition f_ebur128.c:75
int filled
1 if the cache is completely filled, 0 otherwise
Definition f_ebur128.c:72
double sum_kept_powers
sum of the powers (weighted sums) above absolute threshold
Definition f_ebur128.c:74
int cache_pos
focus on the last added bin in the cache array
Definition f_ebur128.c:69
int w
Definition f_ebur128.c:79
int y
Definition f_ebur128.c:79
int h
Definition f_ebur128.c:79
int x
Definition f_ebur128.c:79
libswresample public header
#define av_malloc_array(a, b)
#define av_freep(p)
#define av_log(a,...)
#define SAMPLES
timestamp utils, mostly useful for debugging/logging purposes
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition timestamp.h:83
static int64_t pts
static double a0(void *priv, double x, double y)
Definition vf_xfade.c:2035
AVFrame * ff_get_video_buffer(AVFilterLink *link, int w, int h)
Request a picture buffer with a specific set of permissions.
Definition video.c:120
int len
static double c[64]
const uint8_t * avpriv_vga16_font_get(void)
const uint8_t * avpriv_cga_font_get(void)
CGA/EGA/VGA ROM font data.