• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <math.h>
30 
31 #include "libavutil/avassert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/dict.h"
35 #include "libavutil/ffmath.h"
36 #include "libavutil/xga_font_data.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/timestamp.h"
39 #include "libswresample/swresample.h"
40 #include "audio.h"
41 #include "avfilter.h"
42 #include "filters.h"
43 #include "formats.h"
44 #include "internal.h"
45 
46 #define ABS_THRES    -70            ///< silence gate: we discard anything below this absolute (LUFS) threshold
47 #define ABS_UP_THRES  10            ///< upper loud limit to consider (ABS_THRES being the minimum)
48 #define HIST_GRAIN   100            ///< defines histogram precision
49 #define HIST_SIZE  ((ABS_UP_THRES - ABS_THRES) * HIST_GRAIN + 1)
50 
51 /**
52  * A histogram is an array of HIST_SIZE hist_entry storing all the energies
53  * recorded (with an accuracy of 1/HIST_GRAIN) of the loudnesses from ABS_THRES
54  * (at 0) to ABS_UP_THRES (at HIST_SIZE-1).
55  * This fixed-size system avoids the need of a list of energies growing
56  * infinitely over the time and is thus more scalable.
57  */
58 struct hist_entry {
59     unsigned count;                 ///< how many times the corresponding value occurred
60     double energy;                  ///< E = 10^((L + 0.691) / 10)
61     double loudness;                ///< L = -0.691 + 10 * log10(E)
62 };
63 
64 struct integrator {
65     double **cache;                 ///< window of filtered samples (N ms)
66     int cache_pos;                  ///< focus on the last added bin in the cache array
67     int cache_size;
68     double *sum;                    ///< sum of the last N ms filtered samples (cache content)
69     int filled;                     ///< 1 if the cache is completely filled, 0 otherwise
70     double rel_threshold;           ///< relative threshold
71     double sum_kept_powers;         ///< sum of the powers (weighted sums) above absolute threshold
72     int nb_kept_powers;             ///< number of sum above absolute threshold
73     struct hist_entry *histogram;   ///< histogram of the powers, used to compute LRA and I
74 };
75 
76 struct rect { int x, y, w, h; };
77 
78 typedef struct EBUR128Context {
79     const AVClass *class;           ///< AVClass context for log and options purpose
80 
81     /* peak metering */
82     int peak_mode;                  ///< enabled peak modes
83     double *true_peaks;             ///< true peaks per channel
84     double *sample_peaks;           ///< sample peaks per channel
85     double *true_peaks_per_frame;   ///< true peaks in a frame per channel
86 #if CONFIG_SWRESAMPLE
87     SwrContext *swr_ctx;            ///< over-sampling context for true peak metering
88     double *swr_buf;                ///< resampled audio data for true peak metering
89     int swr_linesize;
90 #endif
91 
92     /* video  */
93     int do_video;                   ///< 1 if video output enabled, 0 otherwise
94     int w, h;                       ///< size of the video output
95     struct rect text;               ///< rectangle for the LU legend on the left
96     struct rect graph;              ///< rectangle for the main graph in the center
97     struct rect gauge;              ///< rectangle for the gauge on the right
98     AVFrame *outpicref;             ///< output picture reference, updated regularly
99     int meter;                      ///< select a EBU mode between +9 and +18
100     int scale_range;                ///< the range of LU values according to the meter
101     int y_zero_lu;                  ///< the y value (pixel position) for 0 LU
102     int y_opt_max;                  ///< the y value (pixel position) for 1 LU
103     int y_opt_min;                  ///< the y value (pixel position) for -1 LU
104     int *y_line_ref;                ///< y reference values for drawing the LU lines in the graph and the gauge
105 
106     /* audio */
107     int nb_channels;                ///< number of channels in the input
108     double *ch_weighting;           ///< channel weighting mapping
109     int sample_count;               ///< sample count used for refresh frequency, reset at refresh
110     int nb_samples;                 ///< number of samples to consume per single input frame
111     int idx_insample;               ///< current sample position of processed samples in single input frame
112     AVFrame *insamples;             ///< input samples reference, updated regularly
113 
114     /* Filter caches.
115      * The mult by 3 in the following is for X[i], X[i-1] and X[i-2] */
116     double *x;                      ///< 3 input samples cache for each channel
117     double *y;                      ///< 3 pre-filter samples cache for each channel
118     double *z;                      ///< 3 RLB-filter samples cache for each channel
119     double pre_b[3];                ///< pre-filter numerator coefficients
120     double pre_a[3];                ///< pre-filter denominator coefficients
121     double rlb_b[3];                ///< rlb-filter numerator coefficients
122     double rlb_a[3];                ///< rlb-filter denominator coefficients
123 
124     struct integrator i400;         ///< 400ms integrator, used for Momentary loudness  (M), and Integrated loudness (I)
125     struct integrator i3000;        ///<    3s integrator, used for Short term loudness (S), and Loudness Range      (LRA)
126 
127     /* I and LRA specific */
128     double integrated_loudness;     ///< integrated loudness in LUFS (I)
129     double loudness_range;          ///< loudness range in LU (LRA)
130     double lra_low, lra_high;       ///< low and high LRA values
131 
132     /* misc */
133     int loglevel;                   ///< log level for frame logging
134     int metadata;                   ///< whether or not to inject loudness results in frames
135     int dual_mono;                  ///< whether or not to treat single channel input files as dual-mono
136     double pan_law;                 ///< pan law value used to calculate dual-mono measurements
137     int target;                     ///< target level in LUFS used to set relative zero LU in visualization
138     int gauge_type;                 ///< whether gauge shows momentary or short
139     int scale;                      ///< display scale type of statistics
140 } EBUR128Context;
141 
142 enum {
143     PEAK_MODE_NONE          = 0,
144     PEAK_MODE_SAMPLES_PEAKS = 1<<1,
145     PEAK_MODE_TRUE_PEAKS    = 1<<2,
146 };
147 
148 enum {
149     GAUGE_TYPE_MOMENTARY = 0,
150     GAUGE_TYPE_SHORTTERM = 1,
151 };
152 
153 enum {
154     SCALE_TYPE_ABSOLUTE = 0,
155     SCALE_TYPE_RELATIVE = 1,
156 };
157 
158 #define OFFSET(x) offsetof(EBUR128Context, x)
159 #define A AV_OPT_FLAG_AUDIO_PARAM
160 #define V AV_OPT_FLAG_VIDEO_PARAM
161 #define F AV_OPT_FLAG_FILTERING_PARAM
162 static const AVOption ebur128_options[] = {
163     { "video", "set video output", OFFSET(do_video), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, V|F },
164     { "size",  "set video size",   OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, V|F },
165     { "meter", "set scale meter (+9 to +18)",  OFFSET(meter), AV_OPT_TYPE_INT, {.i64 = 9}, 9, 18, V|F },
166     { "framelog", "force frame logging level", OFFSET(loglevel), AV_OPT_TYPE_INT, {.i64 = -1},   INT_MIN, INT_MAX, A|V|F, "level" },
167         { "info",    "information logging level", 0, AV_OPT_TYPE_CONST, {.i64 = AV_LOG_INFO},    INT_MIN, INT_MAX, A|V|F, "level" },
168         { "verbose", "verbose logging level",     0, AV_OPT_TYPE_CONST, {.i64 = AV_LOG_VERBOSE}, INT_MIN, INT_MAX, A|V|F, "level" },
169     { "metadata", "inject metadata in the filtergraph", OFFSET(metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, A|V|F },
170     { "peak", "set peak mode", OFFSET(peak_mode), AV_OPT_TYPE_FLAGS, {.i64 = PEAK_MODE_NONE}, 0, INT_MAX, A|F, "mode" },
171         { "none",   "disable any peak mode",   0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_NONE},          INT_MIN, INT_MAX, A|F, "mode" },
172         { "sample", "enable peak-sample mode", 0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_SAMPLES_PEAKS}, INT_MIN, INT_MAX, A|F, "mode" },
173         { "true",   "enable true-peak mode",   0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_TRUE_PEAKS},    INT_MIN, INT_MAX, A|F, "mode" },
174     { "dualmono", "treat mono input files as dual-mono", OFFSET(dual_mono), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, A|F },
175     { "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 },
176     { "target", "set a specific target level in LUFS (-23 to 0)", OFFSET(target), AV_OPT_TYPE_INT, {.i64 = -23}, -23, 0, V|F },
177     { "gauge", "set gauge display type", OFFSET(gauge_type), AV_OPT_TYPE_INT, {.i64 = 0 }, GAUGE_TYPE_MOMENTARY, GAUGE_TYPE_SHORTTERM, V|F, "gaugetype" },
178         { "momentary",   "display momentary value",   0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_MOMENTARY}, INT_MIN, INT_MAX, V|F, "gaugetype" },
179         { "m",           "display momentary value",   0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_MOMENTARY}, INT_MIN, INT_MAX, V|F, "gaugetype" },
180         { "shortterm",   "display short-term value",  0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_SHORTTERM}, INT_MIN, INT_MAX, V|F, "gaugetype" },
181         { "s",           "display short-term value",  0, AV_OPT_TYPE_CONST, {.i64 = GAUGE_TYPE_SHORTTERM}, INT_MIN, INT_MAX, V|F, "gaugetype" },
182     { "scale", "sets display method for the stats", OFFSET(scale), AV_OPT_TYPE_INT, {.i64 = 0}, SCALE_TYPE_ABSOLUTE, SCALE_TYPE_RELATIVE, V|F, "scaletype" },
183         { "absolute",   "display absolute values (LUFS)",          0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_ABSOLUTE}, INT_MIN, INT_MAX, V|F, "scaletype" },
184         { "LUFS",       "display absolute values (LUFS)",          0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_ABSOLUTE}, INT_MIN, INT_MAX, V|F, "scaletype" },
185         { "relative",   "display values relative to target (LU)",  0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_RELATIVE}, INT_MIN, INT_MAX, V|F, "scaletype" },
186         { "LU",         "display values relative to target (LU)",  0, AV_OPT_TYPE_CONST, {.i64 = SCALE_TYPE_RELATIVE}, INT_MIN, INT_MAX, V|F, "scaletype" },
187     { NULL },
188 };
189 
190 AVFILTER_DEFINE_CLASS(ebur128);
191 
192 static const uint8_t graph_colors[] = {
193     0xdd, 0x66, 0x66,   // value above 1LU non reached below -1LU (impossible)
194     0x66, 0x66, 0xdd,   // value below 1LU non reached below -1LU
195     0x96, 0x33, 0x33,   // value above 1LU reached below -1LU (impossible)
196     0x33, 0x33, 0x96,   // value below 1LU reached below -1LU
197     0xdd, 0x96, 0x96,   // value above 1LU line non reached below -1LU (impossible)
198     0x96, 0x96, 0xdd,   // value below 1LU line non reached below -1LU
199     0xdd, 0x33, 0x33,   // value above 1LU line reached below -1LU (impossible)
200     0x33, 0x33, 0xdd,   // value below 1LU line reached below -1LU
201     0xdd, 0x66, 0x66,   // value above 1LU non reached above -1LU
202     0x66, 0xdd, 0x66,   // value below 1LU non reached above -1LU
203     0x96, 0x33, 0x33,   // value above 1LU reached above -1LU
204     0x33, 0x96, 0x33,   // value below 1LU reached above -1LU
205     0xdd, 0x96, 0x96,   // value above 1LU line non reached above -1LU
206     0x96, 0xdd, 0x96,   // value below 1LU line non reached above -1LU
207     0xdd, 0x33, 0x33,   // value above 1LU line reached above -1LU
208     0x33, 0xdd, 0x33,   // value below 1LU line reached above -1LU
209 };
210 
get_graph_color(const EBUR128Context * ebur128,int v,int y)211 static const uint8_t *get_graph_color(const EBUR128Context *ebur128, int v, int y)
212 {
213     const int above_opt_max = y > ebur128->y_opt_max;
214     const int below_opt_min = y < ebur128->y_opt_min;
215     const int reached = y >= v;
216     const int line    = ebur128->y_line_ref[y] || y == ebur128->y_zero_lu;
217     const int colorid = 8*below_opt_min+ 4*line + 2*reached + above_opt_max;
218     return graph_colors + 3*colorid;
219 }
220 
lu_to_y(const EBUR128Context * ebur128,double v)221 static inline int lu_to_y(const EBUR128Context *ebur128, double v)
222 {
223     v += 2 * ebur128->meter;                            // make it in range [0;...]
224     v  = av_clipf(v, 0, ebur128->scale_range);          // make sure it's in the graph scale
225     v  = ebur128->scale_range - v;                      // invert value (y=0 is on top)
226     return v * ebur128->graph.h / ebur128->scale_range; // rescale from scale range to px height
227 }
228 
229 #define FONT8   0
230 #define FONT16  1
231 
232 static const uint8_t font_colors[] = {
233     0xdd, 0xdd, 0x00,
234     0x00, 0x96, 0x96,
235 };
236 
drawtext(AVFrame * pic,int x,int y,int ftid,const uint8_t * color,const char * fmt,...)237 static void drawtext(AVFrame *pic, int x, int y, int ftid, const uint8_t *color, const char *fmt, ...)
238 {
239     int i;
240     char buf[128] = {0};
241     const uint8_t *font;
242     int font_height;
243     va_list vl;
244 
245     if      (ftid == FONT16) font = avpriv_vga16_font, font_height = 16;
246     else if (ftid == FONT8)  font = avpriv_cga_font,   font_height =  8;
247     else return;
248 
249     va_start(vl, fmt);
250     vsnprintf(buf, sizeof(buf), fmt, vl);
251     va_end(vl);
252 
253     for (i = 0; buf[i]; i++) {
254         int char_y, mask;
255         uint8_t *p = pic->data[0] + y*pic->linesize[0] + (x + i*8)*3;
256 
257         for (char_y = 0; char_y < font_height; char_y++) {
258             for (mask = 0x80; mask; mask >>= 1) {
259                 if (font[buf[i] * font_height + char_y] & mask)
260                     memcpy(p, color, 3);
261                 else
262                     memcpy(p, "\x00\x00\x00", 3);
263                 p += 3;
264             }
265             p += pic->linesize[0] - 8*3;
266         }
267     }
268 }
269 
drawline(AVFrame * pic,int x,int y,int len,int step)270 static void drawline(AVFrame *pic, int x, int y, int len, int step)
271 {
272     int i;
273     uint8_t *p = pic->data[0] + y*pic->linesize[0] + x*3;
274 
275     for (i = 0; i < len; i++) {
276         memcpy(p, "\x00\xff\x00", 3);
277         p += step;
278     }
279 }
280 
config_video_output(AVFilterLink * outlink)281 static int config_video_output(AVFilterLink *outlink)
282 {
283     int i, x, y;
284     uint8_t *p;
285     AVFilterContext *ctx = outlink->src;
286     AVFilterLink *inlink = ctx->inputs[0];
287     EBUR128Context *ebur128 = ctx->priv;
288     AVFrame *outpicref;
289 
290     /* check if there is enough space to represent everything decently */
291     if (ebur128->w < 640 || ebur128->h < 480) {
292         av_log(ctx, AV_LOG_ERROR, "Video size %dx%d is too small, "
293                "minimum size is 640x480\n", ebur128->w, ebur128->h);
294         return AVERROR(EINVAL);
295     }
296     outlink->w = ebur128->w;
297     outlink->h = ebur128->h;
298     outlink->sample_aspect_ratio = (AVRational){1,1};
299     outlink->time_base = inlink->time_base;
300     outlink->frame_rate = av_make_q(10, 1);
301 
302 #define PAD 8
303 
304     /* configure text area position and size */
305     ebur128->text.x  = PAD;
306     ebur128->text.y  = 40;
307     ebur128->text.w  = 3 * 8;   // 3 characters
308     ebur128->text.h  = ebur128->h - PAD - ebur128->text.y;
309 
310     /* configure gauge position and size */
311     ebur128->gauge.w = 20;
312     ebur128->gauge.h = ebur128->text.h;
313     ebur128->gauge.x = ebur128->w - PAD - ebur128->gauge.w;
314     ebur128->gauge.y = ebur128->text.y;
315 
316     /* configure graph position and size */
317     ebur128->graph.x = ebur128->text.x + ebur128->text.w + PAD;
318     ebur128->graph.y = ebur128->gauge.y;
319     ebur128->graph.w = ebur128->gauge.x - ebur128->graph.x - PAD;
320     ebur128->graph.h = ebur128->gauge.h;
321 
322     /* graph and gauge share the LU-to-pixel code */
323     av_assert0(ebur128->graph.h == ebur128->gauge.h);
324 
325     /* prepare the initial picref buffer */
326     av_frame_free(&ebur128->outpicref);
327     ebur128->outpicref = outpicref =
328         ff_get_video_buffer(outlink, outlink->w, outlink->h);
329     if (!outpicref)
330         return AVERROR(ENOMEM);
331     outpicref->sample_aspect_ratio = (AVRational){1,1};
332 
333     /* init y references values (to draw LU lines) */
334     ebur128->y_line_ref = av_calloc(ebur128->graph.h + 1, sizeof(*ebur128->y_line_ref));
335     if (!ebur128->y_line_ref)
336         return AVERROR(ENOMEM);
337 
338     /* black background */
339     memset(outpicref->data[0], 0, ebur128->h * outpicref->linesize[0]);
340 
341     /* draw LU legends */
342     drawtext(outpicref, PAD, PAD+16, FONT8, font_colors+3, " LU");
343     for (i = ebur128->meter; i >= -ebur128->meter * 2; i--) {
344         y = lu_to_y(ebur128, i);
345         x = PAD + (i < 10 && i > -10) * 8;
346         ebur128->y_line_ref[y] = i;
347         y -= 4; // -4 to center vertically
348         drawtext(outpicref, x, y + ebur128->graph.y, FONT8, font_colors+3,
349                  "%c%d", i < 0 ? '-' : i > 0 ? '+' : ' ', FFABS(i));
350     }
351 
352     /* draw graph */
353     ebur128->y_zero_lu = lu_to_y(ebur128, 0);
354     ebur128->y_opt_max = lu_to_y(ebur128, 1);
355     ebur128->y_opt_min = lu_to_y(ebur128, -1);
356     p = outpicref->data[0] + ebur128->graph.y * outpicref->linesize[0]
357                            + ebur128->graph.x * 3;
358     for (y = 0; y < ebur128->graph.h; y++) {
359         const uint8_t *c = get_graph_color(ebur128, INT_MAX, y);
360 
361         for (x = 0; x < ebur128->graph.w; x++)
362             memcpy(p + x*3, c, 3);
363         p += outpicref->linesize[0];
364     }
365 
366     /* draw fancy rectangles around the graph and the gauge */
367 #define DRAW_RECT(r) do { \
368     drawline(outpicref, r.x,       r.y - 1,   r.w, 3); \
369     drawline(outpicref, r.x,       r.y + r.h, r.w, 3); \
370     drawline(outpicref, r.x - 1,   r.y,       r.h, outpicref->linesize[0]); \
371     drawline(outpicref, r.x + r.w, r.y,       r.h, outpicref->linesize[0]); \
372 } while (0)
373     DRAW_RECT(ebur128->graph);
374     DRAW_RECT(ebur128->gauge);
375 
376     return 0;
377 }
378 
config_audio_input(AVFilterLink * inlink)379 static int config_audio_input(AVFilterLink *inlink)
380 {
381     AVFilterContext *ctx = inlink->dst;
382     EBUR128Context *ebur128 = ctx->priv;
383 
384     /* Unofficial reversed parametrization of PRE
385      * and RLB from 48kHz */
386 
387     double f0 = 1681.974450955533;
388     double G = 3.999843853973347;
389     double Q = 0.7071752369554196;
390 
391     double K = tan(M_PI * f0 / (double)inlink->sample_rate);
392     double Vh = pow(10.0, G / 20.0);
393     double Vb = pow(Vh, 0.4996667741545416);
394 
395     double a0 = 1.0 + K / Q + K * K;
396 
397     ebur128->pre_b[0] = (Vh + Vb * K / Q + K * K) / a0;
398     ebur128->pre_b[1] = 2.0 * (K * K - Vh) / a0;
399     ebur128->pre_b[2] = (Vh - Vb * K / Q + K * K) / a0;
400     ebur128->pre_a[1] = 2.0 * (K * K - 1.0) / a0;
401     ebur128->pre_a[2] = (1.0 - K / Q + K * K) / a0;
402 
403     f0 = 38.13547087602444;
404     Q = 0.5003270373238773;
405     K = tan(M_PI * f0 / (double)inlink->sample_rate);
406 
407     ebur128->rlb_b[0] = 1.0;
408     ebur128->rlb_b[1] = -2.0;
409     ebur128->rlb_b[2] = 1.0;
410     ebur128->rlb_a[1] = 2.0 * (K * K - 1.0) / (1.0 + K / Q + K * K);
411     ebur128->rlb_a[2] = (1.0 - K / Q + K * K) / (1.0 + K / Q + K * K);
412 
413     /* Force 100ms framing in case of metadata injection: the frames must have
414      * a granularity of the window overlap to be accurately exploited.
415      * As for the true peaks mode, it just simplifies the resampling buffer
416      * allocation and the lookup in it (since sample buffers differ in size, it
417      * can be more complex to integrate in the one-sample loop of
418      * filter_frame()). */
419     if (ebur128->metadata || (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS))
420         ebur128->nb_samples = inlink->sample_rate / 10;
421     return 0;
422 }
423 
config_audio_output(AVFilterLink * outlink)424 static int config_audio_output(AVFilterLink *outlink)
425 {
426     int i;
427     AVFilterContext *ctx = outlink->src;
428     EBUR128Context *ebur128 = ctx->priv;
429     const int nb_channels = outlink->ch_layout.nb_channels;
430 
431 #define BACK_MASK (AV_CH_BACK_LEFT    |AV_CH_BACK_CENTER    |AV_CH_BACK_RIGHT| \
432                    AV_CH_TOP_BACK_LEFT|AV_CH_TOP_BACK_CENTER|AV_CH_TOP_BACK_RIGHT| \
433                    AV_CH_SIDE_LEFT                          |AV_CH_SIDE_RIGHT| \
434                    AV_CH_SURROUND_DIRECT_LEFT               |AV_CH_SURROUND_DIRECT_RIGHT)
435 
436     ebur128->nb_channels  = nb_channels;
437     ebur128->x            = av_calloc(nb_channels, 3 * sizeof(*ebur128->x));
438     ebur128->y            = av_calloc(nb_channels, 3 * sizeof(*ebur128->y));
439     ebur128->z            = av_calloc(nb_channels, 3 * sizeof(*ebur128->z));
440     ebur128->ch_weighting = av_calloc(nb_channels, sizeof(*ebur128->ch_weighting));
441     if (!ebur128->ch_weighting || !ebur128->x || !ebur128->y || !ebur128->z)
442         return AVERROR(ENOMEM);
443 
444 #define I400_BINS(x)  ((x) * 4 / 10)
445 #define I3000_BINS(x) ((x) * 3)
446 
447     ebur128->i400.sum = av_calloc(nb_channels, sizeof(*ebur128->i400.sum));
448     ebur128->i3000.sum = av_calloc(nb_channels, sizeof(*ebur128->i3000.sum));
449     ebur128->i400.cache = av_calloc(nb_channels, sizeof(*ebur128->i400.cache));
450     ebur128->i3000.cache = av_calloc(nb_channels, sizeof(*ebur128->i3000.cache));
451     if (!ebur128->i400.sum || !ebur128->i3000.sum ||
452         !ebur128->i400.cache || !ebur128->i3000.cache)
453         return AVERROR(ENOMEM);
454 
455     for (i = 0; i < nb_channels; i++) {
456         /* channel weighting */
457         const enum AVChannel chl = av_channel_layout_channel_from_index(&outlink->ch_layout, i);
458         if (chl == AV_CHAN_LOW_FREQUENCY || chl == AV_CHAN_LOW_FREQUENCY_2) {
459             ebur128->ch_weighting[i] = 0;
460         } else if (chl < 64 && (1ULL << chl) & BACK_MASK) {
461             ebur128->ch_weighting[i] = 1.41;
462         } else {
463             ebur128->ch_weighting[i] = 1.0;
464         }
465 
466         if (!ebur128->ch_weighting[i])
467             continue;
468 
469         /* bins buffer for the two integration window (400ms and 3s) */
470         ebur128->i400.cache_size = I400_BINS(outlink->sample_rate);
471         ebur128->i3000.cache_size = I3000_BINS(outlink->sample_rate);
472         ebur128->i400.cache[i]  = av_calloc(ebur128->i400.cache_size,  sizeof(*ebur128->i400.cache[0]));
473         ebur128->i3000.cache[i] = av_calloc(ebur128->i3000.cache_size, sizeof(*ebur128->i3000.cache[0]));
474         if (!ebur128->i400.cache[i] || !ebur128->i3000.cache[i])
475             return AVERROR(ENOMEM);
476     }
477 
478 #if CONFIG_SWRESAMPLE
479     if (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS) {
480         int ret;
481 
482         ebur128->swr_buf    = av_malloc_array(nb_channels, 19200 * sizeof(double));
483         ebur128->true_peaks = av_calloc(nb_channels, sizeof(*ebur128->true_peaks));
484         ebur128->true_peaks_per_frame = av_calloc(nb_channels, sizeof(*ebur128->true_peaks_per_frame));
485         ebur128->swr_ctx    = swr_alloc();
486         if (!ebur128->swr_buf || !ebur128->true_peaks ||
487             !ebur128->true_peaks_per_frame || !ebur128->swr_ctx)
488             return AVERROR(ENOMEM);
489 
490         av_opt_set_chlayout(ebur128->swr_ctx, "in_chlayout",    &outlink->ch_layout, 0);
491         av_opt_set_int(ebur128->swr_ctx, "in_sample_rate",       outlink->sample_rate, 0);
492         av_opt_set_sample_fmt(ebur128->swr_ctx, "in_sample_fmt", outlink->format, 0);
493 
494         av_opt_set_chlayout(ebur128->swr_ctx, "out_chlayout",    &outlink->ch_layout, 0);
495         av_opt_set_int(ebur128->swr_ctx, "out_sample_rate",       192000, 0);
496         av_opt_set_sample_fmt(ebur128->swr_ctx, "out_sample_fmt", outlink->format, 0);
497 
498         ret = swr_init(ebur128->swr_ctx);
499         if (ret < 0)
500             return ret;
501     }
502 #endif
503 
504     if (ebur128->peak_mode & PEAK_MODE_SAMPLES_PEAKS) {
505         ebur128->sample_peaks = av_calloc(nb_channels, sizeof(*ebur128->sample_peaks));
506         if (!ebur128->sample_peaks)
507             return AVERROR(ENOMEM);
508     }
509 
510     return 0;
511 }
512 
513 #define ENERGY(loudness) (ff_exp10(((loudness) + 0.691) / 10.))
514 #define LOUDNESS(energy) (-0.691 + 10 * log10(energy))
515 #define DBFS(energy) (20 * log10(energy))
516 
get_histogram(void)517 static struct hist_entry *get_histogram(void)
518 {
519     int i;
520     struct hist_entry *h = av_calloc(HIST_SIZE, sizeof(*h));
521 
522     if (!h)
523         return NULL;
524     for (i = 0; i < HIST_SIZE; i++) {
525         h[i].loudness = i / (double)HIST_GRAIN + ABS_THRES;
526         h[i].energy   = ENERGY(h[i].loudness);
527     }
528     return h;
529 }
530 
init(AVFilterContext * ctx)531 static av_cold int init(AVFilterContext *ctx)
532 {
533     EBUR128Context *ebur128 = ctx->priv;
534     AVFilterPad pad;
535     int ret;
536 
537     if (ebur128->loglevel != AV_LOG_INFO &&
538         ebur128->loglevel != AV_LOG_VERBOSE) {
539         if (ebur128->do_video || ebur128->metadata)
540             ebur128->loglevel = AV_LOG_VERBOSE;
541         else
542             ebur128->loglevel = AV_LOG_INFO;
543     }
544 
545     if (!CONFIG_SWRESAMPLE && (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS)) {
546         av_log(ctx, AV_LOG_ERROR,
547                "True-peak mode requires libswresample to be performed\n");
548         return AVERROR(EINVAL);
549     }
550 
551     // if meter is  +9 scale, scale range is from -18 LU to  +9 LU (or 3*9)
552     // if meter is +18 scale, scale range is from -36 LU to +18 LU (or 3*18)
553     ebur128->scale_range = 3 * ebur128->meter;
554 
555     ebur128->i400.histogram  = get_histogram();
556     ebur128->i3000.histogram = get_histogram();
557     if (!ebur128->i400.histogram || !ebur128->i3000.histogram)
558         return AVERROR(ENOMEM);
559 
560     ebur128->integrated_loudness = ABS_THRES;
561     ebur128->loudness_range = 0;
562 
563     /* insert output pads */
564     if (ebur128->do_video) {
565         pad = (AVFilterPad){
566             .name         = "out0",
567             .type         = AVMEDIA_TYPE_VIDEO,
568             .config_props = config_video_output,
569         };
570         ret = ff_append_outpad(ctx, &pad);
571         if (ret < 0)
572             return ret;
573     }
574     pad = (AVFilterPad){
575         .name         = ebur128->do_video ? "out1" : "out0",
576         .type         = AVMEDIA_TYPE_AUDIO,
577         .config_props = config_audio_output,
578     };
579     ret = ff_append_outpad(ctx, &pad);
580     if (ret < 0)
581         return ret;
582 
583     /* summary */
584     av_log(ctx, AV_LOG_VERBOSE, "EBU +%d scale\n", ebur128->meter);
585 
586     return 0;
587 }
588 
589 #define HIST_POS(power) (int)(((power) - ABS_THRES) * HIST_GRAIN)
590 
591 /* loudness and power should be set such as loudness = -0.691 +
592  * 10*log10(power), we just avoid doing that calculus two times */
gate_update(struct integrator * integ,double power,double loudness,int gate_thres)593 static int gate_update(struct integrator *integ, double power,
594                        double loudness, int gate_thres)
595 {
596     int ipower;
597     double relative_threshold;
598     int gate_hist_pos;
599 
600     /* update powers histograms by incrementing current power count */
601     ipower = av_clip(HIST_POS(loudness), 0, HIST_SIZE - 1);
602     integ->histogram[ipower].count++;
603 
604     /* compute relative threshold and get its position in the histogram */
605     integ->sum_kept_powers += power;
606     integ->nb_kept_powers++;
607     relative_threshold = integ->sum_kept_powers / integ->nb_kept_powers;
608     if (!relative_threshold)
609         relative_threshold = 1e-12;
610     integ->rel_threshold = LOUDNESS(relative_threshold) + gate_thres;
611     gate_hist_pos = av_clip(HIST_POS(integ->rel_threshold), 0, HIST_SIZE - 1);
612 
613     return gate_hist_pos;
614 }
615 
filter_frame(AVFilterLink * inlink,AVFrame * insamples)616 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
617 {
618     int i, ch, idx_insample;
619     AVFilterContext *ctx = inlink->dst;
620     EBUR128Context *ebur128 = ctx->priv;
621     const int nb_channels = ebur128->nb_channels;
622     const int nb_samples  = insamples->nb_samples;
623     const double *samples = (double *)insamples->data[0];
624     AVFrame *pic = ebur128->outpicref;
625 
626 #if CONFIG_SWRESAMPLE
627     if (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS && ebur128->idx_insample == 0) {
628         const double *swr_samples = ebur128->swr_buf;
629         int ret = swr_convert(ebur128->swr_ctx, (uint8_t**)&ebur128->swr_buf, 19200,
630                               (const uint8_t **)insamples->data, nb_samples);
631         if (ret < 0)
632             return ret;
633         for (ch = 0; ch < nb_channels; ch++)
634             ebur128->true_peaks_per_frame[ch] = 0.0;
635         for (idx_insample = 0; idx_insample < ret; idx_insample++) {
636             for (ch = 0; ch < nb_channels; ch++) {
637                 ebur128->true_peaks[ch] = FFMAX(ebur128->true_peaks[ch], fabs(*swr_samples));
638                 ebur128->true_peaks_per_frame[ch] = FFMAX(ebur128->true_peaks_per_frame[ch],
639                                                           fabs(*swr_samples));
640                 swr_samples++;
641             }
642         }
643     }
644 #endif
645 
646     for (idx_insample = ebur128->idx_insample; idx_insample < nb_samples; idx_insample++) {
647         const int bin_id_400  = ebur128->i400.cache_pos;
648         const int bin_id_3000 = ebur128->i3000.cache_pos;
649 
650 #define MOVE_TO_NEXT_CACHED_ENTRY(time) do {                \
651     ebur128->i##time.cache_pos++;                           \
652     if (ebur128->i##time.cache_pos ==                       \
653         ebur128->i##time.cache_size) {                      \
654         ebur128->i##time.filled    = 1;                     \
655         ebur128->i##time.cache_pos = 0;                     \
656     }                                                       \
657 } while (0)
658 
659         MOVE_TO_NEXT_CACHED_ENTRY(400);
660         MOVE_TO_NEXT_CACHED_ENTRY(3000);
661 
662         for (ch = 0; ch < nb_channels; ch++) {
663             double bin;
664 
665             if (ebur128->peak_mode & PEAK_MODE_SAMPLES_PEAKS)
666                 ebur128->sample_peaks[ch] = FFMAX(ebur128->sample_peaks[ch], fabs(samples[idx_insample * nb_channels + ch]));
667 
668             ebur128->x[ch * 3] = samples[idx_insample * nb_channels + ch]; // set X[i]
669 
670             if (!ebur128->ch_weighting[ch])
671                 continue;
672 
673             /* Y[i] = X[i]*b0 + X[i-1]*b1 + X[i-2]*b2 - Y[i-1]*a1 - Y[i-2]*a2 */
674 #define FILTER(Y, X, NUM, DEN) do {                                             \
675             double *dst = ebur128->Y + ch*3;                                    \
676             double *src = ebur128->X + ch*3;                                    \
677             dst[2] = dst[1];                                                    \
678             dst[1] = dst[0];                                                    \
679             dst[0] = src[0]*NUM[0] + src[1]*NUM[1] + src[2]*NUM[2]              \
680                                    - dst[1]*DEN[1] - dst[2]*DEN[2];             \
681 } while (0)
682 
683             // TODO: merge both filters in one?
684             FILTER(y, x, ebur128->pre_b, ebur128->pre_a);  // apply pre-filter
685             ebur128->x[ch * 3 + 2] = ebur128->x[ch * 3 + 1];
686             ebur128->x[ch * 3 + 1] = ebur128->x[ch * 3    ];
687             FILTER(z, y, ebur128->rlb_b, ebur128->rlb_a);  // apply RLB-filter
688 
689             bin = ebur128->z[ch * 3] * ebur128->z[ch * 3];
690 
691             /* add the new value, and limit the sum to the cache size (400ms or 3s)
692              * by removing the oldest one */
693             ebur128->i400.sum [ch] = ebur128->i400.sum [ch] + bin - ebur128->i400.cache [ch][bin_id_400];
694             ebur128->i3000.sum[ch] = ebur128->i3000.sum[ch] + bin - ebur128->i3000.cache[ch][bin_id_3000];
695 
696             /* override old cache entry with the new value */
697             ebur128->i400.cache [ch][bin_id_400 ] = bin;
698             ebur128->i3000.cache[ch][bin_id_3000] = bin;
699         }
700 
701         /* For integrated loudness, gating blocks are 400ms long with 75%
702          * overlap (see BS.1770-2 p5), so a re-computation is needed each 100ms
703          * (4800 samples at 48kHz). */
704         if (++ebur128->sample_count == inlink->sample_rate / 10) {
705             double loudness_400, loudness_3000;
706             double power_400 = 1e-12, power_3000 = 1e-12;
707             AVFilterLink *outlink = ctx->outputs[0];
708             const int64_t pts = insamples->pts +
709                 av_rescale_q(idx_insample, (AVRational){ 1, inlink->sample_rate },
710                              outlink->time_base);
711 
712             ebur128->sample_count = 0;
713 
714 #define COMPUTE_LOUDNESS(m, time) do {                                              \
715     if (ebur128->i##time.filled) {                                                  \
716         /* weighting sum of the last <time> ms */                                   \
717         for (ch = 0; ch < nb_channels; ch++)                                        \
718             power_##time += ebur128->ch_weighting[ch] * ebur128->i##time.sum[ch];   \
719         power_##time /= I##time##_BINS(inlink->sample_rate);                        \
720     }                                                                               \
721     loudness_##time = LOUDNESS(power_##time);                                       \
722 } while (0)
723 
724             COMPUTE_LOUDNESS(M,  400);
725             COMPUTE_LOUDNESS(S, 3000);
726 
727             /* Integrated loudness */
728 #define I_GATE_THRES -10  // initially defined to -8 LU in the first EBU standard
729 
730             if (loudness_400 >= ABS_THRES) {
731                 double integrated_sum = 0.0;
732                 uint64_t nb_integrated = 0;
733                 int gate_hist_pos = gate_update(&ebur128->i400, power_400,
734                                                 loudness_400, I_GATE_THRES);
735 
736                 /* compute integrated loudness by summing the histogram values
737                  * above the relative threshold */
738                 for (i = gate_hist_pos; i < HIST_SIZE; i++) {
739                     const unsigned nb_v = ebur128->i400.histogram[i].count;
740                     nb_integrated  += nb_v;
741                     integrated_sum += nb_v * ebur128->i400.histogram[i].energy;
742                 }
743                 if (nb_integrated) {
744                     ebur128->integrated_loudness = LOUDNESS(integrated_sum / nb_integrated);
745                     /* dual-mono correction */
746                     if (nb_channels == 1 && ebur128->dual_mono) {
747                         ebur128->integrated_loudness -= ebur128->pan_law;
748                     }
749                 }
750             }
751 
752             /* LRA */
753 #define LRA_GATE_THRES -20
754 #define LRA_LOWER_PRC   10
755 #define LRA_HIGHER_PRC  95
756 
757             /* XXX: example code in EBU 3342 is ">=" but formula in BS.1770
758              * specs is ">" */
759             if (loudness_3000 >= ABS_THRES) {
760                 uint64_t nb_powers = 0;
761                 int gate_hist_pos = gate_update(&ebur128->i3000, power_3000,
762                                                 loudness_3000, LRA_GATE_THRES);
763 
764                 for (i = gate_hist_pos; i < HIST_SIZE; i++)
765                     nb_powers += ebur128->i3000.histogram[i].count;
766                 if (nb_powers) {
767                     uint64_t n, nb_pow;
768 
769                     /* get lower loudness to consider */
770                     n = 0;
771                     nb_pow = LRA_LOWER_PRC * nb_powers * 0.01 + 0.5;
772                     for (i = gate_hist_pos; i < HIST_SIZE; i++) {
773                         n += ebur128->i3000.histogram[i].count;
774                         if (n >= nb_pow) {
775                             ebur128->lra_low = ebur128->i3000.histogram[i].loudness;
776                             break;
777                         }
778                     }
779 
780                     /* get higher loudness to consider */
781                     n = nb_powers;
782                     nb_pow = LRA_HIGHER_PRC * nb_powers * 0.01 + 0.5;
783                     for (i = HIST_SIZE - 1; i >= 0; i--) {
784                         n -= FFMIN(n, ebur128->i3000.histogram[i].count);
785                         if (n < nb_pow) {
786                             ebur128->lra_high = ebur128->i3000.histogram[i].loudness;
787                             break;
788                         }
789                     }
790 
791                     // XXX: show low & high on the graph?
792                     ebur128->loudness_range = ebur128->lra_high - ebur128->lra_low;
793                 }
794             }
795 
796             /* dual-mono correction */
797             if (nb_channels == 1 && ebur128->dual_mono) {
798                 loudness_400 -= ebur128->pan_law;
799                 loudness_3000 -= ebur128->pan_law;
800             }
801 
802 #define LOG_FMT "TARGET:%d LUFS    M:%6.1f S:%6.1f     I:%6.1f %s       LRA:%6.1f LU"
803 
804             /* push one video frame */
805             if (ebur128->do_video) {
806                 AVFrame *clone;
807                 int x, y;
808                 uint8_t *p;
809                 double gauge_value;
810                 int y_loudness_lu_graph, y_loudness_lu_gauge;
811 
812                 if (ebur128->gauge_type == GAUGE_TYPE_MOMENTARY) {
813                     gauge_value = loudness_400 - ebur128->target;
814                 } else {
815                     gauge_value = loudness_3000 - ebur128->target;
816                 }
817 
818                 y_loudness_lu_graph = lu_to_y(ebur128, loudness_3000 - ebur128->target);
819                 y_loudness_lu_gauge = lu_to_y(ebur128, gauge_value);
820 
821                 av_frame_make_writable(pic);
822                 /* draw the graph using the short-term loudness */
823                 p = pic->data[0] + ebur128->graph.y*pic->linesize[0] + ebur128->graph.x*3;
824                 for (y = 0; y < ebur128->graph.h; y++) {
825                     const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_graph, y);
826 
827                     memmove(p, p + 3, (ebur128->graph.w - 1) * 3);
828                     memcpy(p + (ebur128->graph.w - 1) * 3, c, 3);
829                     p += pic->linesize[0];
830                 }
831 
832                 /* draw the gauge using either momentary or short-term loudness */
833                 p = pic->data[0] + ebur128->gauge.y*pic->linesize[0] + ebur128->gauge.x*3;
834                 for (y = 0; y < ebur128->gauge.h; y++) {
835                     const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_gauge, y);
836 
837                     for (x = 0; x < ebur128->gauge.w; x++)
838                         memcpy(p + x*3, c, 3);
839                     p += pic->linesize[0];
840                 }
841 
842                 /* draw textual info */
843                 if (ebur128->scale == SCALE_TYPE_ABSOLUTE) {
844                     drawtext(pic, PAD, PAD - PAD/2, FONT16, font_colors,
845                              LOG_FMT "     ", // padding to erase trailing characters
846                              ebur128->target, loudness_400, loudness_3000,
847                              ebur128->integrated_loudness, "LUFS", ebur128->loudness_range);
848                 } else {
849                     drawtext(pic, PAD, PAD - PAD/2, FONT16, font_colors,
850                              LOG_FMT "     ", // padding to erase trailing characters
851                              ebur128->target, loudness_400-ebur128->target, loudness_3000-ebur128->target,
852                              ebur128->integrated_loudness-ebur128->target, "LU", ebur128->loudness_range);
853                 }
854 
855                 /* set pts and push frame */
856                 pic->pts = pts;
857                 clone = av_frame_clone(pic);
858                 if (!clone)
859                     return AVERROR(ENOMEM);
860                 ebur128->idx_insample = idx_insample + 1;
861                 ff_filter_set_ready(ctx, 100);
862                 return ff_filter_frame(outlink, clone);
863             }
864 
865             if (ebur128->metadata) { /* happens only once per filter_frame call */
866                 char metabuf[128];
867 #define META_PREFIX "lavfi.r128."
868 
869 #define SET_META(name, var) do {                                            \
870     snprintf(metabuf, sizeof(metabuf), "%.3f", var);                        \
871     av_dict_set(&insamples->metadata, name, metabuf, 0);                    \
872 } while (0)
873 
874 #define SET_META_PEAK(name, ptype) do {                                     \
875     if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) {               \
876         double max_peak = 0.0;                                              \
877         char key[64];                                                       \
878         for (ch = 0; ch < nb_channels; ch++) {                              \
879             snprintf(key, sizeof(key),                                      \
880                      META_PREFIX AV_STRINGIFY(name) "_peaks_ch%d", ch);     \
881             max_peak = fmax(max_peak, ebur128->name##_peaks[ch]);           \
882             SET_META(key, ebur128->name##_peaks[ch]);                       \
883         }                                                                   \
884         snprintf(key, sizeof(key),                                          \
885                  META_PREFIX AV_STRINGIFY(name) "_peak");                   \
886         SET_META(key, max_peak);                                            \
887     }                                                                       \
888 } while (0)
889 
890                 SET_META(META_PREFIX "M",        loudness_400);
891                 SET_META(META_PREFIX "S",        loudness_3000);
892                 SET_META(META_PREFIX "I",        ebur128->integrated_loudness);
893                 SET_META(META_PREFIX "LRA",      ebur128->loudness_range);
894                 SET_META(META_PREFIX "LRA.low",  ebur128->lra_low);
895                 SET_META(META_PREFIX "LRA.high", ebur128->lra_high);
896 
897                 SET_META_PEAK(sample, SAMPLES);
898                 SET_META_PEAK(true,   TRUE);
899             }
900 
901             if (ebur128->scale == SCALE_TYPE_ABSOLUTE) {
902                 av_log(ctx, ebur128->loglevel, "t: %-10s " LOG_FMT,
903                        av_ts2timestr(pts, &outlink->time_base),
904                        ebur128->target, loudness_400, loudness_3000,
905                        ebur128->integrated_loudness, "LUFS", ebur128->loudness_range);
906             } else {
907                 av_log(ctx, ebur128->loglevel, "t: %-10s " LOG_FMT,
908                        av_ts2timestr(pts, &outlink->time_base),
909                        ebur128->target, loudness_400-ebur128->target, loudness_3000-ebur128->target,
910                        ebur128->integrated_loudness-ebur128->target, "LU", ebur128->loudness_range);
911             }
912 
913 #define PRINT_PEAKS(str, sp, ptype) do {                            \
914     if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) {       \
915         av_log(ctx, ebur128->loglevel, "  " str ":");               \
916         for (ch = 0; ch < nb_channels; ch++)                        \
917             av_log(ctx, ebur128->loglevel, " %5.1f", DBFS(sp[ch])); \
918         av_log(ctx, ebur128->loglevel, " dBFS");                    \
919     }                                                               \
920 } while (0)
921 
922             PRINT_PEAKS("SPK", ebur128->sample_peaks, SAMPLES);
923             PRINT_PEAKS("FTPK", ebur128->true_peaks_per_frame, TRUE);
924             PRINT_PEAKS("TPK", ebur128->true_peaks,   TRUE);
925             av_log(ctx, ebur128->loglevel, "\n");
926 
927         }
928     }
929 
930     ebur128->idx_insample = 0;
931     ebur128->insamples = NULL;
932 
933     return ff_filter_frame(ctx->outputs[ebur128->do_video], insamples);
934 }
935 
activate(AVFilterContext * ctx)936 static int activate(AVFilterContext *ctx)
937 {
938     AVFilterLink *inlink = ctx->inputs[0];
939     EBUR128Context *ebur128 = ctx->priv;
940     AVFilterLink *voutlink = ctx->outputs[0];
941     AVFilterLink *outlink = ctx->outputs[ebur128->do_video];
942     int ret;
943 
944     FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
945     if (ebur128->do_video)
946         FF_FILTER_FORWARD_STATUS_BACK(voutlink, inlink);
947 
948     if (!ebur128->insamples) {
949         AVFrame *in;
950 
951         if (ebur128->nb_samples > 0) {
952             ret = ff_inlink_consume_samples(inlink, ebur128->nb_samples, ebur128->nb_samples, &in);
953         } else {
954             ret = ff_inlink_consume_frame(inlink, &in);
955         }
956         if (ret < 0)
957             return ret;
958         if (ret > 0)
959             ebur128->insamples = in;
960     }
961 
962     if (ebur128->insamples)
963         ret = filter_frame(inlink, ebur128->insamples);
964 
965     FF_FILTER_FORWARD_STATUS_ALL(inlink, ctx);
966     FF_FILTER_FORWARD_WANTED(outlink, inlink);
967     if (ebur128->do_video)
968         FF_FILTER_FORWARD_WANTED(voutlink, inlink);
969 
970     return ret;
971 }
972 
query_formats(AVFilterContext * ctx)973 static int query_formats(AVFilterContext *ctx)
974 {
975     EBUR128Context *ebur128 = ctx->priv;
976     AVFilterFormats *formats;
977     AVFilterChannelLayouts *layouts;
978     AVFilterLink *inlink = ctx->inputs[0];
979     AVFilterLink *outlink = ctx->outputs[0];
980     int ret;
981 
982     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_NONE };
983     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
984 
985     /* set optional output video format */
986     if (ebur128->do_video) {
987         formats = ff_make_format_list(pix_fmts);
988         if ((ret = ff_formats_ref(formats, &outlink->incfg.formats)) < 0)
989             return ret;
990         outlink = ctx->outputs[1];
991     }
992 
993     /* set input and output audio formats
994      * Note: ff_set_common_* functions are not used because they affect all the
995      * links, and thus break the video format negotiation */
996     formats = ff_make_format_list(sample_fmts);
997     if ((ret = ff_formats_ref(formats, &inlink->outcfg.formats)) < 0 ||
998         (ret = ff_formats_ref(formats, &outlink->incfg.formats)) < 0)
999         return ret;
1000 
1001     layouts = ff_all_channel_layouts();
1002     if ((ret = ff_channel_layouts_ref(layouts, &inlink->outcfg.channel_layouts)) < 0 ||
1003         (ret = ff_channel_layouts_ref(layouts, &outlink->incfg.channel_layouts)) < 0)
1004         return ret;
1005 
1006     formats = ff_all_samplerates();
1007     if ((ret = ff_formats_ref(formats, &inlink->outcfg.samplerates)) < 0 ||
1008         (ret = ff_formats_ref(formats, &outlink->incfg.samplerates)) < 0)
1009         return ret;
1010 
1011     return 0;
1012 }
1013 
uninit(AVFilterContext * ctx)1014 static av_cold void uninit(AVFilterContext *ctx)
1015 {
1016     int i;
1017     EBUR128Context *ebur128 = ctx->priv;
1018 
1019     /* dual-mono correction */
1020     if (ebur128->nb_channels == 1 && ebur128->dual_mono) {
1021         ebur128->i400.rel_threshold -= ebur128->pan_law;
1022         ebur128->i3000.rel_threshold -= ebur128->pan_law;
1023         ebur128->lra_low -= ebur128->pan_law;
1024         ebur128->lra_high -= ebur128->pan_law;
1025     }
1026 
1027     av_log(ctx, AV_LOG_INFO, "Summary:\n\n"
1028            "  Integrated loudness:\n"
1029            "    I:         %5.1f LUFS\n"
1030            "    Threshold: %5.1f LUFS\n\n"
1031            "  Loudness range:\n"
1032            "    LRA:       %5.1f LU\n"
1033            "    Threshold: %5.1f LUFS\n"
1034            "    LRA low:   %5.1f LUFS\n"
1035            "    LRA high:  %5.1f LUFS",
1036            ebur128->integrated_loudness, ebur128->i400.rel_threshold,
1037            ebur128->loudness_range,      ebur128->i3000.rel_threshold,
1038            ebur128->lra_low, ebur128->lra_high);
1039 
1040 #define PRINT_PEAK_SUMMARY(str, sp, ptype) do {                  \
1041     int ch;                                                      \
1042     double maxpeak;                                              \
1043     maxpeak = 0.0;                                               \
1044     if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) {    \
1045         for (ch = 0; ch < ebur128->nb_channels; ch++)            \
1046             maxpeak = FFMAX(maxpeak, sp[ch]);                    \
1047         av_log(ctx, AV_LOG_INFO, "\n\n  " str " peak:\n"         \
1048                "    Peak:      %5.1f dBFS",                      \
1049                DBFS(maxpeak));                                   \
1050     }                                                            \
1051 } while (0)
1052 
1053     PRINT_PEAK_SUMMARY("Sample", ebur128->sample_peaks, SAMPLES);
1054     PRINT_PEAK_SUMMARY("True",   ebur128->true_peaks,   TRUE);
1055     av_log(ctx, AV_LOG_INFO, "\n");
1056 
1057     av_freep(&ebur128->y_line_ref);
1058     av_freep(&ebur128->x);
1059     av_freep(&ebur128->y);
1060     av_freep(&ebur128->z);
1061     av_freep(&ebur128->ch_weighting);
1062     av_freep(&ebur128->true_peaks);
1063     av_freep(&ebur128->sample_peaks);
1064     av_freep(&ebur128->true_peaks_per_frame);
1065     av_freep(&ebur128->i400.sum);
1066     av_freep(&ebur128->i3000.sum);
1067     av_freep(&ebur128->i400.histogram);
1068     av_freep(&ebur128->i3000.histogram);
1069     for (i = 0; i < ebur128->nb_channels; i++) {
1070         if (ebur128->i400.cache)
1071             av_freep(&ebur128->i400.cache[i]);
1072         if (ebur128->i3000.cache)
1073             av_freep(&ebur128->i3000.cache[i]);
1074     }
1075     av_freep(&ebur128->i400.cache);
1076     av_freep(&ebur128->i3000.cache);
1077     av_frame_free(&ebur128->outpicref);
1078 #if CONFIG_SWRESAMPLE
1079     av_freep(&ebur128->swr_buf);
1080     swr_free(&ebur128->swr_ctx);
1081 #endif
1082 }
1083 
1084 static const AVFilterPad ebur128_inputs[] = {
1085     {
1086         .name         = "default",
1087         .type         = AVMEDIA_TYPE_AUDIO,
1088         .config_props = config_audio_input,
1089     },
1090 };
1091 
1092 const AVFilter ff_af_ebur128 = {
1093     .name          = "ebur128",
1094     .description   = NULL_IF_CONFIG_SMALL("EBU R128 scanner."),
1095     .priv_size     = sizeof(EBUR128Context),
1096     .init          = init,
1097     .uninit        = uninit,
1098     .activate      = activate,
1099     FILTER_INPUTS(ebur128_inputs),
1100     .outputs       = NULL,
1101     FILTER_QUERY_FUNC(query_formats),
1102     .priv_class    = &ebur128_class,
1103     .flags         = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
1104 };
1105