f_ebur128.c 47 KB

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