You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

949 lines
38KB

  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 modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (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
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
  18. * 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. * @todo support other frequencies to avoid resampling
  27. */
  28. #include <math.h>
  29. #include "libavutil/avassert.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/channel_layout.h"
  32. #include "libavutil/dict.h"
  33. #include "libavutil/xga_font_data.h"
  34. #include "libavutil/opt.h"
  35. #include "libavutil/timestamp.h"
  36. #include "libswresample/swresample.h"
  37. #include "audio.h"
  38. #include "avfilter.h"
  39. #include "formats.h"
  40. #include "internal.h"
  41. #define MAX_CHANNELS 63
  42. /* pre-filter coefficients */
  43. #define PRE_B0 1.53512485958697
  44. #define PRE_B1 -2.69169618940638
  45. #define PRE_B2 1.19839281085285
  46. #define PRE_A1 -1.69065929318241
  47. #define PRE_A2 0.73248077421585
  48. /* RLB-filter coefficients */
  49. #define RLB_B0 1.0
  50. #define RLB_B1 -2.0
  51. #define RLB_B2 1.0
  52. #define RLB_A1 -1.99004745483398
  53. #define RLB_A2 0.99007225036621
  54. #define ABS_THRES -70 ///< silence gate: we discard anything below this absolute (LUFS) threshold
  55. #define ABS_UP_THRES 10 ///< upper loud limit to consider (ABS_THRES being the minimum)
  56. #define HIST_GRAIN 100 ///< defines histogram precision
  57. #define HIST_SIZE ((ABS_UP_THRES - ABS_THRES) * HIST_GRAIN + 1)
  58. /**
  59. * A histogram is an array of HIST_SIZE hist_entry storing all the energies
  60. * recorded (with an accuracy of 1/HIST_GRAIN) of the loudnesses from ABS_THRES
  61. * (at 0) to ABS_UP_THRES (at HIST_SIZE-1).
  62. * This fixed-size system avoids the need of a list of energies growing
  63. * infinitely over the time and is thus more scalable.
  64. */
  65. struct hist_entry {
  66. int count; ///< how many times the corresponding value occurred
  67. double energy; ///< E = 10^((L + 0.691) / 10)
  68. double loudness; ///< L = -0.691 + 10 * log10(E)
  69. };
  70. struct integrator {
  71. double *cache[MAX_CHANNELS]; ///< window of filtered samples (N ms)
  72. int cache_pos; ///< focus on the last added bin in the cache array
  73. double sum[MAX_CHANNELS]; ///< sum of the last N ms filtered samples (cache content)
  74. int filled; ///< 1 if the cache is completely filled, 0 otherwise
  75. double rel_threshold; ///< relative threshold
  76. double sum_kept_powers; ///< sum of the powers (weighted sums) above absolute threshold
  77. int nb_kept_powers; ///< number of sum above absolute threshold
  78. struct hist_entry *histogram; ///< histogram of the powers, used to compute LRA and I
  79. };
  80. struct rect { int x, y, w, h; };
  81. typedef struct {
  82. const AVClass *class; ///< AVClass context for log and options purpose
  83. /* peak metering */
  84. int peak_mode; ///< enabled peak modes
  85. double *true_peaks; ///< true peaks per channel
  86. double *sample_peaks; ///< sample peaks per channel
  87. double *true_peaks_per_frame; ///< true peaks in a frame per channel
  88. #if CONFIG_SWRESAMPLE
  89. SwrContext *swr_ctx; ///< over-sampling context for true peak metering
  90. double *swr_buf; ///< resampled audio data for true peak metering
  91. int swr_linesize;
  92. #endif
  93. /* video */
  94. int do_video; ///< 1 if video output enabled, 0 otherwise
  95. int w, h; ///< size of the video output
  96. struct rect text; ///< rectangle for the LU legend on the left
  97. struct rect graph; ///< rectangle for the main graph in the center
  98. struct rect gauge; ///< rectangle for the gauge on the right
  99. AVFrame *outpicref; ///< output picture reference, updated regularly
  100. int meter; ///< select a EBU mode between +9 and +18
  101. int scale_range; ///< the range of LU values according to the meter
  102. int y_zero_lu; ///< the y value (pixel position) for 0 LU
  103. int *y_line_ref; ///< y reference values for drawing the LU lines in the graph and the gauge
  104. /* audio */
  105. int nb_channels; ///< number of channels in the input
  106. double *ch_weighting; ///< channel weighting mapping
  107. int sample_count; ///< sample count used for refresh frequency, reset at refresh
  108. /* Filter caches.
  109. * The mult by 3 in the following is for X[i], X[i-1] and X[i-2] */
  110. double x[MAX_CHANNELS * 3]; ///< 3 input samples cache for each channel
  111. double y[MAX_CHANNELS * 3]; ///< 3 pre-filter samples cache for each channel
  112. double z[MAX_CHANNELS * 3]; ///< 3 RLB-filter samples cache for each channel
  113. #define I400_BINS (48000 * 4 / 10)
  114. #define I3000_BINS (48000 * 3)
  115. struct integrator i400; ///< 400ms integrator, used for Momentary loudness (M), and Integrated loudness (I)
  116. struct integrator i3000; ///< 3s integrator, used for Short term loudness (S), and Loudness Range (LRA)
  117. /* I and LRA specific */
  118. double integrated_loudness; ///< integrated loudness in LUFS (I)
  119. double loudness_range; ///< loudness range in LU (LRA)
  120. double lra_low, lra_high; ///< low and high LRA values
  121. /* misc */
  122. int loglevel; ///< log level for frame logging
  123. int metadata; ///< whether or not to inject loudness results in frames
  124. int dual_mono; ///< whether or not to treat single channel input files as dual-mono
  125. double pan_law; ///< pan law value used to calulate dual-mono measurements
  126. } EBUR128Context;
  127. enum {
  128. PEAK_MODE_NONE = 0,
  129. PEAK_MODE_SAMPLES_PEAKS = 1<<1,
  130. PEAK_MODE_TRUE_PEAKS = 1<<2,
  131. };
  132. #define OFFSET(x) offsetof(EBUR128Context, x)
  133. #define A AV_OPT_FLAG_AUDIO_PARAM
  134. #define V AV_OPT_FLAG_VIDEO_PARAM
  135. #define F AV_OPT_FLAG_FILTERING_PARAM
  136. static const AVOption ebur128_options[] = {
  137. { "video", "set video output", OFFSET(do_video), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, V|F },
  138. { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, V|F },
  139. { "meter", "set scale meter (+9 to +18)", OFFSET(meter), AV_OPT_TYPE_INT, {.i64 = 9}, 9, 18, V|F },
  140. { "framelog", "force frame logging level", OFFSET(loglevel), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, A|V|F, "level" },
  141. { "info", "information logging level", 0, AV_OPT_TYPE_CONST, {.i64 = AV_LOG_INFO}, INT_MIN, INT_MAX, A|V|F, "level" },
  142. { "verbose", "verbose logging level", 0, AV_OPT_TYPE_CONST, {.i64 = AV_LOG_VERBOSE}, INT_MIN, INT_MAX, A|V|F, "level" },
  143. { "metadata", "inject metadata in the filtergraph", OFFSET(metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, A|V|F },
  144. { "peak", "set peak mode", OFFSET(peak_mode), AV_OPT_TYPE_FLAGS, {.i64 = PEAK_MODE_NONE}, 0, INT_MAX, A|F, "mode" },
  145. { "none", "disable any peak mode", 0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_NONE}, INT_MIN, INT_MAX, A|F, "mode" },
  146. { "sample", "enable peak-sample mode", 0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_SAMPLES_PEAKS}, INT_MIN, INT_MAX, A|F, "mode" },
  147. { "true", "enable true-peak mode", 0, AV_OPT_TYPE_CONST, {.i64 = PEAK_MODE_TRUE_PEAKS}, INT_MIN, INT_MAX, A|F, "mode" },
  148. { "dualmono", "treat mono input files as dual-mono", OFFSET(dual_mono), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, A|F },
  149. { "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 },
  150. { NULL },
  151. };
  152. AVFILTER_DEFINE_CLASS(ebur128);
  153. static const uint8_t graph_colors[] = {
  154. 0xdd, 0x66, 0x66, // value above 0LU non reached
  155. 0x66, 0x66, 0xdd, // value below 0LU non reached
  156. 0x96, 0x33, 0x33, // value above 0LU reached
  157. 0x33, 0x33, 0x96, // value below 0LU reached
  158. 0xdd, 0x96, 0x96, // value above 0LU line non reached
  159. 0x96, 0x96, 0xdd, // value below 0LU line non reached
  160. 0xdd, 0x33, 0x33, // value above 0LU line reached
  161. 0x33, 0x33, 0xdd, // value below 0LU line reached
  162. };
  163. static const uint8_t *get_graph_color(const EBUR128Context *ebur128, int v, int y)
  164. {
  165. const int below0 = y > ebur128->y_zero_lu;
  166. const int reached = y >= v;
  167. const int line = ebur128->y_line_ref[y] || y == ebur128->y_zero_lu;
  168. const int colorid = 4*line + 2*reached + below0;
  169. return graph_colors + 3*colorid;
  170. }
  171. static inline int lu_to_y(const EBUR128Context *ebur128, double v)
  172. {
  173. v += 2 * ebur128->meter; // make it in range [0;...]
  174. v = av_clipf(v, 0, ebur128->scale_range); // make sure it's in the graph scale
  175. v = ebur128->scale_range - v; // invert value (y=0 is on top)
  176. return v * ebur128->graph.h / ebur128->scale_range; // rescale from scale range to px height
  177. }
  178. #define FONT8 0
  179. #define FONT16 1
  180. static const uint8_t font_colors[] = {
  181. 0xdd, 0xdd, 0x00,
  182. 0x00, 0x96, 0x96,
  183. };
  184. static void drawtext(AVFrame *pic, int x, int y, int ftid, const uint8_t *color, const char *fmt, ...)
  185. {
  186. int i;
  187. char buf[128] = {0};
  188. const uint8_t *font;
  189. int font_height;
  190. va_list vl;
  191. if (ftid == FONT16) font = avpriv_vga16_font, font_height = 16;
  192. else if (ftid == FONT8) font = avpriv_cga_font, font_height = 8;
  193. else return;
  194. va_start(vl, fmt);
  195. vsnprintf(buf, sizeof(buf), fmt, vl);
  196. va_end(vl);
  197. for (i = 0; buf[i]; i++) {
  198. int char_y, mask;
  199. uint8_t *p = pic->data[0] + y*pic->linesize[0] + (x + i*8)*3;
  200. for (char_y = 0; char_y < font_height; char_y++) {
  201. for (mask = 0x80; mask; mask >>= 1) {
  202. if (font[buf[i] * font_height + char_y] & mask)
  203. memcpy(p, color, 3);
  204. else
  205. memcpy(p, "\x00\x00\x00", 3);
  206. p += 3;
  207. }
  208. p += pic->linesize[0] - 8*3;
  209. }
  210. }
  211. }
  212. static void drawline(AVFrame *pic, int x, int y, int len, int step)
  213. {
  214. int i;
  215. uint8_t *p = pic->data[0] + y*pic->linesize[0] + x*3;
  216. for (i = 0; i < len; i++) {
  217. memcpy(p, "\x00\xff\x00", 3);
  218. p += step;
  219. }
  220. }
  221. static int config_video_output(AVFilterLink *outlink)
  222. {
  223. int i, x, y;
  224. uint8_t *p;
  225. AVFilterContext *ctx = outlink->src;
  226. EBUR128Context *ebur128 = ctx->priv;
  227. AVFrame *outpicref;
  228. /* check if there is enough space to represent everything decently */
  229. if (ebur128->w < 640 || ebur128->h < 480) {
  230. av_log(ctx, AV_LOG_ERROR, "Video size %dx%d is too small, "
  231. "minimum size is 640x480\n", ebur128->w, ebur128->h);
  232. return AVERROR(EINVAL);
  233. }
  234. outlink->w = ebur128->w;
  235. outlink->h = ebur128->h;
  236. #define PAD 8
  237. /* configure text area position and size */
  238. ebur128->text.x = PAD;
  239. ebur128->text.y = 40;
  240. ebur128->text.w = 3 * 8; // 3 characters
  241. ebur128->text.h = ebur128->h - PAD - ebur128->text.y;
  242. /* configure gauge position and size */
  243. ebur128->gauge.w = 20;
  244. ebur128->gauge.h = ebur128->text.h;
  245. ebur128->gauge.x = ebur128->w - PAD - ebur128->gauge.w;
  246. ebur128->gauge.y = ebur128->text.y;
  247. /* configure graph position and size */
  248. ebur128->graph.x = ebur128->text.x + ebur128->text.w + PAD;
  249. ebur128->graph.y = ebur128->gauge.y;
  250. ebur128->graph.w = ebur128->gauge.x - ebur128->graph.x - PAD;
  251. ebur128->graph.h = ebur128->gauge.h;
  252. /* graph and gauge share the LU-to-pixel code */
  253. av_assert0(ebur128->graph.h == ebur128->gauge.h);
  254. /* prepare the initial picref buffer */
  255. av_frame_free(&ebur128->outpicref);
  256. ebur128->outpicref = outpicref =
  257. ff_get_video_buffer(outlink, outlink->w, outlink->h);
  258. if (!outpicref)
  259. return AVERROR(ENOMEM);
  260. outlink->sample_aspect_ratio = (AVRational){1,1};
  261. /* init y references values (to draw LU lines) */
  262. ebur128->y_line_ref = av_calloc(ebur128->graph.h + 1, sizeof(*ebur128->y_line_ref));
  263. if (!ebur128->y_line_ref)
  264. return AVERROR(ENOMEM);
  265. /* black background */
  266. memset(outpicref->data[0], 0, ebur128->h * outpicref->linesize[0]);
  267. /* draw LU legends */
  268. drawtext(outpicref, PAD, PAD+16, FONT8, font_colors+3, " LU");
  269. for (i = ebur128->meter; i >= -ebur128->meter * 2; i--) {
  270. y = lu_to_y(ebur128, i);
  271. x = PAD + (i < 10 && i > -10) * 8;
  272. ebur128->y_line_ref[y] = i;
  273. y -= 4; // -4 to center vertically
  274. drawtext(outpicref, x, y + ebur128->graph.y, FONT8, font_colors+3,
  275. "%c%d", i < 0 ? '-' : i > 0 ? '+' : ' ', FFABS(i));
  276. }
  277. /* draw graph */
  278. ebur128->y_zero_lu = lu_to_y(ebur128, 0);
  279. p = outpicref->data[0] + ebur128->graph.y * outpicref->linesize[0]
  280. + ebur128->graph.x * 3;
  281. for (y = 0; y < ebur128->graph.h; y++) {
  282. const uint8_t *c = get_graph_color(ebur128, INT_MAX, y);
  283. for (x = 0; x < ebur128->graph.w; x++)
  284. memcpy(p + x*3, c, 3);
  285. p += outpicref->linesize[0];
  286. }
  287. /* draw fancy rectangles around the graph and the gauge */
  288. #define DRAW_RECT(r) do { \
  289. drawline(outpicref, r.x, r.y - 1, r.w, 3); \
  290. drawline(outpicref, r.x, r.y + r.h, r.w, 3); \
  291. drawline(outpicref, r.x - 1, r.y, r.h, outpicref->linesize[0]); \
  292. drawline(outpicref, r.x + r.w, r.y, r.h, outpicref->linesize[0]); \
  293. } while (0)
  294. DRAW_RECT(ebur128->graph);
  295. DRAW_RECT(ebur128->gauge);
  296. return 0;
  297. }
  298. static int config_audio_input(AVFilterLink *inlink)
  299. {
  300. AVFilterContext *ctx = inlink->dst;
  301. EBUR128Context *ebur128 = ctx->priv;
  302. /* Force 100ms framing in case of metadata injection: the frames must have
  303. * a granularity of the window overlap to be accurately exploited.
  304. * As for the true peaks mode, it just simplifies the resampling buffer
  305. * allocation and the lookup in it (since sample buffers differ in size, it
  306. * can be more complex to integrate in the one-sample loop of
  307. * filter_frame()). */
  308. if (ebur128->metadata || (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS))
  309. inlink->min_samples =
  310. inlink->max_samples =
  311. inlink->partial_buf_size = inlink->sample_rate / 10;
  312. return 0;
  313. }
  314. static int config_audio_output(AVFilterLink *outlink)
  315. {
  316. int i;
  317. AVFilterContext *ctx = outlink->src;
  318. EBUR128Context *ebur128 = ctx->priv;
  319. const int nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
  320. #define BACK_MASK (AV_CH_BACK_LEFT |AV_CH_BACK_CENTER |AV_CH_BACK_RIGHT| \
  321. AV_CH_TOP_BACK_LEFT|AV_CH_TOP_BACK_CENTER|AV_CH_TOP_BACK_RIGHT| \
  322. AV_CH_SIDE_LEFT |AV_CH_SIDE_RIGHT| \
  323. AV_CH_SURROUND_DIRECT_LEFT |AV_CH_SURROUND_DIRECT_RIGHT)
  324. ebur128->nb_channels = nb_channels;
  325. ebur128->ch_weighting = av_calloc(nb_channels, sizeof(*ebur128->ch_weighting));
  326. if (!ebur128->ch_weighting)
  327. return AVERROR(ENOMEM);
  328. for (i = 0; i < nb_channels; i++) {
  329. /* channel weighting */
  330. const uint16_t chl = av_channel_layout_extract_channel(outlink->channel_layout, i);
  331. if (chl & (AV_CH_LOW_FREQUENCY|AV_CH_LOW_FREQUENCY_2)) {
  332. ebur128->ch_weighting[i] = 0;
  333. } else if (chl & BACK_MASK) {
  334. ebur128->ch_weighting[i] = 1.41;
  335. } else {
  336. ebur128->ch_weighting[i] = 1.0;
  337. }
  338. if (!ebur128->ch_weighting[i])
  339. continue;
  340. /* bins buffer for the two integration window (400ms and 3s) */
  341. ebur128->i400.cache[i] = av_calloc(I400_BINS, sizeof(*ebur128->i400.cache[0]));
  342. ebur128->i3000.cache[i] = av_calloc(I3000_BINS, sizeof(*ebur128->i3000.cache[0]));
  343. if (!ebur128->i400.cache[i] || !ebur128->i3000.cache[i])
  344. return AVERROR(ENOMEM);
  345. }
  346. #if CONFIG_SWRESAMPLE
  347. if (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS) {
  348. int ret;
  349. ebur128->swr_buf = av_malloc_array(nb_channels, 19200 * sizeof(double));
  350. ebur128->true_peaks = av_calloc(nb_channels, sizeof(*ebur128->true_peaks));
  351. ebur128->true_peaks_per_frame = av_calloc(nb_channels, sizeof(*ebur128->true_peaks_per_frame));
  352. ebur128->swr_ctx = swr_alloc();
  353. if (!ebur128->swr_buf || !ebur128->true_peaks ||
  354. !ebur128->true_peaks_per_frame || !ebur128->swr_ctx)
  355. return AVERROR(ENOMEM);
  356. av_opt_set_int(ebur128->swr_ctx, "in_channel_layout", outlink->channel_layout, 0);
  357. av_opt_set_int(ebur128->swr_ctx, "in_sample_rate", outlink->sample_rate, 0);
  358. av_opt_set_sample_fmt(ebur128->swr_ctx, "in_sample_fmt", outlink->format, 0);
  359. av_opt_set_int(ebur128->swr_ctx, "out_channel_layout", outlink->channel_layout, 0);
  360. av_opt_set_int(ebur128->swr_ctx, "out_sample_rate", 192000, 0);
  361. av_opt_set_sample_fmt(ebur128->swr_ctx, "out_sample_fmt", outlink->format, 0);
  362. ret = swr_init(ebur128->swr_ctx);
  363. if (ret < 0)
  364. return ret;
  365. }
  366. #endif
  367. if (ebur128->peak_mode & PEAK_MODE_SAMPLES_PEAKS) {
  368. ebur128->sample_peaks = av_calloc(nb_channels, sizeof(*ebur128->sample_peaks));
  369. if (!ebur128->sample_peaks)
  370. return AVERROR(ENOMEM);
  371. }
  372. return 0;
  373. }
  374. #define ENERGY(loudness) (pow(10, ((loudness) + 0.691) / 10.))
  375. #define LOUDNESS(energy) (-0.691 + 10 * log10(energy))
  376. #define DBFS(energy) (20 * log10(energy))
  377. static struct hist_entry *get_histogram(void)
  378. {
  379. int i;
  380. struct hist_entry *h = av_calloc(HIST_SIZE, sizeof(*h));
  381. if (!h)
  382. return NULL;
  383. for (i = 0; i < HIST_SIZE; i++) {
  384. h[i].loudness = i / (double)HIST_GRAIN + ABS_THRES;
  385. h[i].energy = ENERGY(h[i].loudness);
  386. }
  387. return h;
  388. }
  389. static av_cold int init(AVFilterContext *ctx)
  390. {
  391. EBUR128Context *ebur128 = ctx->priv;
  392. AVFilterPad pad;
  393. if (ebur128->loglevel != AV_LOG_INFO &&
  394. ebur128->loglevel != AV_LOG_VERBOSE) {
  395. if (ebur128->do_video || ebur128->metadata)
  396. ebur128->loglevel = AV_LOG_VERBOSE;
  397. else
  398. ebur128->loglevel = AV_LOG_INFO;
  399. }
  400. if (!CONFIG_SWRESAMPLE && (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS)) {
  401. av_log(ctx, AV_LOG_ERROR,
  402. "True-peak mode requires libswresample to be performed\n");
  403. return AVERROR(EINVAL);
  404. }
  405. // if meter is +9 scale, scale range is from -18 LU to +9 LU (or 3*9)
  406. // if meter is +18 scale, scale range is from -36 LU to +18 LU (or 3*18)
  407. ebur128->scale_range = 3 * ebur128->meter;
  408. ebur128->i400.histogram = get_histogram();
  409. ebur128->i3000.histogram = get_histogram();
  410. if (!ebur128->i400.histogram || !ebur128->i3000.histogram)
  411. return AVERROR(ENOMEM);
  412. ebur128->integrated_loudness = ABS_THRES;
  413. ebur128->loudness_range = 0;
  414. /* insert output pads */
  415. if (ebur128->do_video) {
  416. pad = (AVFilterPad){
  417. .name = av_strdup("out0"),
  418. .type = AVMEDIA_TYPE_VIDEO,
  419. .config_props = config_video_output,
  420. };
  421. if (!pad.name)
  422. return AVERROR(ENOMEM);
  423. ff_insert_outpad(ctx, 0, &pad);
  424. }
  425. pad = (AVFilterPad){
  426. .name = av_asprintf("out%d", ebur128->do_video),
  427. .type = AVMEDIA_TYPE_AUDIO,
  428. .config_props = config_audio_output,
  429. };
  430. if (!pad.name)
  431. return AVERROR(ENOMEM);
  432. ff_insert_outpad(ctx, ebur128->do_video, &pad);
  433. /* summary */
  434. av_log(ctx, AV_LOG_VERBOSE, "EBU +%d scale\n", ebur128->meter);
  435. return 0;
  436. }
  437. #define HIST_POS(power) (int)(((power) - ABS_THRES) * HIST_GRAIN)
  438. /* loudness and power should be set such as loudness = -0.691 +
  439. * 10*log10(power), we just avoid doing that calculus two times */
  440. static int gate_update(struct integrator *integ, double power,
  441. double loudness, int gate_thres)
  442. {
  443. int ipower;
  444. double relative_threshold;
  445. int gate_hist_pos;
  446. /* update powers histograms by incrementing current power count */
  447. ipower = av_clip(HIST_POS(loudness), 0, HIST_SIZE - 1);
  448. integ->histogram[ipower].count++;
  449. /* compute relative threshold and get its position in the histogram */
  450. integ->sum_kept_powers += power;
  451. integ->nb_kept_powers++;
  452. relative_threshold = integ->sum_kept_powers / integ->nb_kept_powers;
  453. if (!relative_threshold)
  454. relative_threshold = 1e-12;
  455. integ->rel_threshold = LOUDNESS(relative_threshold) + gate_thres;
  456. gate_hist_pos = av_clip(HIST_POS(integ->rel_threshold), 0, HIST_SIZE - 1);
  457. return gate_hist_pos;
  458. }
  459. static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
  460. {
  461. int i, ch, idx_insample;
  462. AVFilterContext *ctx = inlink->dst;
  463. EBUR128Context *ebur128 = ctx->priv;
  464. const int nb_channels = ebur128->nb_channels;
  465. const int nb_samples = insamples->nb_samples;
  466. const double *samples = (double *)insamples->data[0];
  467. AVFrame *pic = ebur128->outpicref;
  468. #if CONFIG_SWRESAMPLE
  469. if (ebur128->peak_mode & PEAK_MODE_TRUE_PEAKS) {
  470. const double *swr_samples = ebur128->swr_buf;
  471. int ret = swr_convert(ebur128->swr_ctx, (uint8_t**)&ebur128->swr_buf, 19200,
  472. (const uint8_t **)insamples->data, nb_samples);
  473. if (ret < 0)
  474. return ret;
  475. for (ch = 0; ch < nb_channels; ch++)
  476. ebur128->true_peaks_per_frame[ch] = 0.0;
  477. for (idx_insample = 0; idx_insample < ret; idx_insample++) {
  478. for (ch = 0; ch < nb_channels; ch++) {
  479. ebur128->true_peaks[ch] = FFMAX(ebur128->true_peaks[ch], fabs(*swr_samples));
  480. ebur128->true_peaks_per_frame[ch] = FFMAX(ebur128->true_peaks_per_frame[ch],
  481. fabs(*swr_samples));
  482. swr_samples++;
  483. }
  484. }
  485. }
  486. #endif
  487. for (idx_insample = 0; idx_insample < nb_samples; idx_insample++) {
  488. const int bin_id_400 = ebur128->i400.cache_pos;
  489. const int bin_id_3000 = ebur128->i3000.cache_pos;
  490. #define MOVE_TO_NEXT_CACHED_ENTRY(time) do { \
  491. ebur128->i##time.cache_pos++; \
  492. if (ebur128->i##time.cache_pos == I##time##_BINS) { \
  493. ebur128->i##time.filled = 1; \
  494. ebur128->i##time.cache_pos = 0; \
  495. } \
  496. } while (0)
  497. MOVE_TO_NEXT_CACHED_ENTRY(400);
  498. MOVE_TO_NEXT_CACHED_ENTRY(3000);
  499. for (ch = 0; ch < nb_channels; ch++) {
  500. double bin;
  501. if (ebur128->peak_mode & PEAK_MODE_SAMPLES_PEAKS)
  502. ebur128->sample_peaks[ch] = FFMAX(ebur128->sample_peaks[ch], fabs(*samples));
  503. ebur128->x[ch * 3] = *samples++; // set X[i]
  504. if (!ebur128->ch_weighting[ch])
  505. continue;
  506. /* Y[i] = X[i]*b0 + X[i-1]*b1 + X[i-2]*b2 - Y[i-1]*a1 - Y[i-2]*a2 */
  507. #define FILTER(Y, X, name) do { \
  508. double *dst = ebur128->Y + ch*3; \
  509. double *src = ebur128->X + ch*3; \
  510. dst[2] = dst[1]; \
  511. dst[1] = dst[0]; \
  512. dst[0] = src[0]*name##_B0 + src[1]*name##_B1 + src[2]*name##_B2 \
  513. - dst[1]*name##_A1 - dst[2]*name##_A2; \
  514. } while (0)
  515. // TODO: merge both filters in one?
  516. FILTER(y, x, PRE); // apply pre-filter
  517. ebur128->x[ch * 3 + 2] = ebur128->x[ch * 3 + 1];
  518. ebur128->x[ch * 3 + 1] = ebur128->x[ch * 3 ];
  519. FILTER(z, y, RLB); // apply RLB-filter
  520. bin = ebur128->z[ch * 3] * ebur128->z[ch * 3];
  521. /* add the new value, and limit the sum to the cache size (400ms or 3s)
  522. * by removing the oldest one */
  523. ebur128->i400.sum [ch] = ebur128->i400.sum [ch] + bin - ebur128->i400.cache [ch][bin_id_400];
  524. ebur128->i3000.sum[ch] = ebur128->i3000.sum[ch] + bin - ebur128->i3000.cache[ch][bin_id_3000];
  525. /* override old cache entry with the new value */
  526. ebur128->i400.cache [ch][bin_id_400 ] = bin;
  527. ebur128->i3000.cache[ch][bin_id_3000] = bin;
  528. }
  529. /* For integrated loudness, gating blocks are 400ms long with 75%
  530. * overlap (see BS.1770-2 p5), so a re-computation is needed each 100ms
  531. * (4800 samples at 48kHz). */
  532. if (++ebur128->sample_count == 4800) {
  533. double loudness_400, loudness_3000;
  534. double power_400 = 1e-12, power_3000 = 1e-12;
  535. AVFilterLink *outlink = ctx->outputs[0];
  536. const int64_t pts = insamples->pts +
  537. av_rescale_q(idx_insample, (AVRational){ 1, inlink->sample_rate },
  538. outlink->time_base);
  539. ebur128->sample_count = 0;
  540. #define COMPUTE_LOUDNESS(m, time) do { \
  541. if (ebur128->i##time.filled) { \
  542. /* weighting sum of the last <time> ms */ \
  543. for (ch = 0; ch < nb_channels; ch++) \
  544. power_##time += ebur128->ch_weighting[ch] * ebur128->i##time.sum[ch]; \
  545. power_##time /= I##time##_BINS; \
  546. } \
  547. loudness_##time = LOUDNESS(power_##time); \
  548. } while (0)
  549. COMPUTE_LOUDNESS(M, 400);
  550. COMPUTE_LOUDNESS(S, 3000);
  551. /* Integrated loudness */
  552. #define I_GATE_THRES -10 // initially defined to -8 LU in the first EBU standard
  553. if (loudness_400 >= ABS_THRES) {
  554. double integrated_sum = 0;
  555. int nb_integrated = 0;
  556. int gate_hist_pos = gate_update(&ebur128->i400, power_400,
  557. loudness_400, I_GATE_THRES);
  558. /* compute integrated loudness by summing the histogram values
  559. * above the relative threshold */
  560. for (i = gate_hist_pos; i < HIST_SIZE; i++) {
  561. const int nb_v = ebur128->i400.histogram[i].count;
  562. nb_integrated += nb_v;
  563. integrated_sum += nb_v * ebur128->i400.histogram[i].energy;
  564. }
  565. if (nb_integrated)
  566. ebur128->integrated_loudness = LOUDNESS(integrated_sum / nb_integrated);
  567. /* dual-mono correction */
  568. if (nb_channels == 1 && ebur128->dual_mono) {
  569. ebur128->integrated_loudness -= ebur128->pan_law;
  570. }
  571. }
  572. /* LRA */
  573. #define LRA_GATE_THRES -20
  574. #define LRA_LOWER_PRC 10
  575. #define LRA_HIGHER_PRC 95
  576. /* XXX: example code in EBU 3342 is ">=" but formula in BS.1770
  577. * specs is ">" */
  578. if (loudness_3000 >= ABS_THRES) {
  579. int nb_powers = 0;
  580. int gate_hist_pos = gate_update(&ebur128->i3000, power_3000,
  581. loudness_3000, LRA_GATE_THRES);
  582. for (i = gate_hist_pos; i < HIST_SIZE; i++)
  583. nb_powers += ebur128->i3000.histogram[i].count;
  584. if (nb_powers) {
  585. int n, nb_pow;
  586. /* get lower loudness to consider */
  587. n = 0;
  588. nb_pow = LRA_LOWER_PRC * nb_powers / 100. + 0.5;
  589. for (i = gate_hist_pos; i < HIST_SIZE; i++) {
  590. n += ebur128->i3000.histogram[i].count;
  591. if (n >= nb_pow) {
  592. ebur128->lra_low = ebur128->i3000.histogram[i].loudness;
  593. break;
  594. }
  595. }
  596. /* get higher loudness to consider */
  597. n = nb_powers;
  598. nb_pow = LRA_HIGHER_PRC * nb_powers / 100. + 0.5;
  599. for (i = HIST_SIZE - 1; i >= 0; i--) {
  600. n -= ebur128->i3000.histogram[i].count;
  601. if (n < nb_pow) {
  602. ebur128->lra_high = ebur128->i3000.histogram[i].loudness;
  603. break;
  604. }
  605. }
  606. // XXX: show low & high on the graph?
  607. ebur128->loudness_range = ebur128->lra_high - ebur128->lra_low;
  608. }
  609. }
  610. /* dual-mono correction */
  611. if (nb_channels == 1 && ebur128->dual_mono) {
  612. loudness_400 -= ebur128->pan_law;
  613. loudness_3000 -= ebur128->pan_law;
  614. }
  615. #define LOG_FMT "M:%6.1f S:%6.1f I:%6.1f LUFS LRA:%6.1f LU"
  616. /* push one video frame */
  617. if (ebur128->do_video) {
  618. int x, y, ret;
  619. uint8_t *p;
  620. const int y_loudness_lu_graph = lu_to_y(ebur128, loudness_3000 + 23);
  621. const int y_loudness_lu_gauge = lu_to_y(ebur128, loudness_400 + 23);
  622. /* draw the graph using the short-term loudness */
  623. p = pic->data[0] + ebur128->graph.y*pic->linesize[0] + ebur128->graph.x*3;
  624. for (y = 0; y < ebur128->graph.h; y++) {
  625. const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_graph, y);
  626. memmove(p, p + 3, (ebur128->graph.w - 1) * 3);
  627. memcpy(p + (ebur128->graph.w - 1) * 3, c, 3);
  628. p += pic->linesize[0];
  629. }
  630. /* draw the gauge using the momentary loudness */
  631. p = pic->data[0] + ebur128->gauge.y*pic->linesize[0] + ebur128->gauge.x*3;
  632. for (y = 0; y < ebur128->gauge.h; y++) {
  633. const uint8_t *c = get_graph_color(ebur128, y_loudness_lu_gauge, y);
  634. for (x = 0; x < ebur128->gauge.w; x++)
  635. memcpy(p + x*3, c, 3);
  636. p += pic->linesize[0];
  637. }
  638. /* draw textual info */
  639. drawtext(pic, PAD, PAD - PAD/2, FONT16, font_colors,
  640. LOG_FMT " ", // padding to erase trailing characters
  641. loudness_400, loudness_3000,
  642. ebur128->integrated_loudness, ebur128->loudness_range);
  643. /* set pts and push frame */
  644. pic->pts = pts;
  645. ret = ff_filter_frame(outlink, av_frame_clone(pic));
  646. if (ret < 0)
  647. return ret;
  648. }
  649. if (ebur128->metadata) { /* happens only once per filter_frame call */
  650. char metabuf[128];
  651. #define META_PREFIX "lavfi.r128."
  652. #define SET_META(name, var) do { \
  653. snprintf(metabuf, sizeof(metabuf), "%.3f", var); \
  654. av_dict_set(&insamples->metadata, name, metabuf, 0); \
  655. } while (0)
  656. #define SET_META_PEAK(name, ptype) do { \
  657. if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) { \
  658. char key[64]; \
  659. for (ch = 0; ch < nb_channels; ch++) { \
  660. snprintf(key, sizeof(key), \
  661. META_PREFIX AV_STRINGIFY(name) "_peaks_ch%d", ch); \
  662. SET_META(key, ebur128->name##_peaks[ch]); \
  663. } \
  664. } \
  665. } while (0)
  666. SET_META(META_PREFIX "M", loudness_400);
  667. SET_META(META_PREFIX "S", loudness_3000);
  668. SET_META(META_PREFIX "I", ebur128->integrated_loudness);
  669. SET_META(META_PREFIX "LRA", ebur128->loudness_range);
  670. SET_META(META_PREFIX "LRA.low", ebur128->lra_low);
  671. SET_META(META_PREFIX "LRA.high", ebur128->lra_high);
  672. SET_META_PEAK(sample, SAMPLES);
  673. SET_META_PEAK(true, TRUE);
  674. }
  675. av_log(ctx, ebur128->loglevel, "t: %-10s " LOG_FMT,
  676. av_ts2timestr(pts, &outlink->time_base),
  677. loudness_400, loudness_3000,
  678. ebur128->integrated_loudness, ebur128->loudness_range);
  679. #define PRINT_PEAKS(str, sp, ptype) do { \
  680. if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) { \
  681. av_log(ctx, ebur128->loglevel, " " str ":"); \
  682. for (ch = 0; ch < nb_channels; ch++) \
  683. av_log(ctx, ebur128->loglevel, " %5.1f", DBFS(sp[ch])); \
  684. av_log(ctx, ebur128->loglevel, " dBFS"); \
  685. } \
  686. } while (0)
  687. PRINT_PEAKS("SPK", ebur128->sample_peaks, SAMPLES);
  688. PRINT_PEAKS("FTPK", ebur128->true_peaks_per_frame, TRUE);
  689. PRINT_PEAKS("TPK", ebur128->true_peaks, TRUE);
  690. av_log(ctx, ebur128->loglevel, "\n");
  691. }
  692. }
  693. return ff_filter_frame(ctx->outputs[ebur128->do_video], insamples);
  694. }
  695. static int query_formats(AVFilterContext *ctx)
  696. {
  697. EBUR128Context *ebur128 = ctx->priv;
  698. AVFilterFormats *formats;
  699. AVFilterChannelLayouts *layouts;
  700. AVFilterLink *inlink = ctx->inputs[0];
  701. AVFilterLink *outlink = ctx->outputs[0];
  702. int ret;
  703. static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_NONE };
  704. static const int input_srate[] = {48000, -1}; // ITU-R BS.1770 provides coeff only for 48kHz
  705. static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
  706. /* set optional output video format */
  707. if (ebur128->do_video) {
  708. formats = ff_make_format_list(pix_fmts);
  709. if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
  710. return ret;
  711. outlink = ctx->outputs[1];
  712. }
  713. /* set input and output audio formats
  714. * Note: ff_set_common_* functions are not used because they affect all the
  715. * links, and thus break the video format negotiation */
  716. formats = ff_make_format_list(sample_fmts);
  717. if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0 ||
  718. (ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
  719. return ret;
  720. layouts = ff_all_channel_layouts();
  721. if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0 ||
  722. (ret = ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts)) < 0)
  723. return ret;
  724. formats = ff_make_format_list(input_srate);
  725. if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0 ||
  726. (ret = ff_formats_ref(formats, &outlink->in_samplerates)) < 0)
  727. return ret;
  728. return 0;
  729. }
  730. static av_cold void uninit(AVFilterContext *ctx)
  731. {
  732. int i;
  733. EBUR128Context *ebur128 = ctx->priv;
  734. /* dual-mono correction */
  735. if (ebur128->nb_channels == 1 && ebur128->dual_mono) {
  736. ebur128->i400.rel_threshold -= ebur128->pan_law;
  737. ebur128->i3000.rel_threshold -= ebur128->pan_law;
  738. ebur128->lra_low -= ebur128->pan_law;
  739. ebur128->lra_high -= ebur128->pan_law;
  740. }
  741. av_log(ctx, AV_LOG_INFO, "Summary:\n\n"
  742. " Integrated loudness:\n"
  743. " I: %5.1f LUFS\n"
  744. " Threshold: %5.1f LUFS\n\n"
  745. " Loudness range:\n"
  746. " LRA: %5.1f LU\n"
  747. " Threshold: %5.1f LUFS\n"
  748. " LRA low: %5.1f LUFS\n"
  749. " LRA high: %5.1f LUFS",
  750. ebur128->integrated_loudness, ebur128->i400.rel_threshold,
  751. ebur128->loudness_range, ebur128->i3000.rel_threshold,
  752. ebur128->lra_low, ebur128->lra_high);
  753. #define PRINT_PEAK_SUMMARY(str, sp, ptype) do { \
  754. int ch; \
  755. double maxpeak; \
  756. maxpeak = 0.0; \
  757. if (ebur128->peak_mode & PEAK_MODE_ ## ptype ## _PEAKS) { \
  758. for (ch = 0; ch < ebur128->nb_channels; ch++) \
  759. maxpeak = FFMAX(maxpeak, sp[ch]); \
  760. av_log(ctx, AV_LOG_INFO, "\n\n " str " peak:\n" \
  761. " Peak: %5.1f dBFS", \
  762. DBFS(maxpeak)); \
  763. } \
  764. } while (0)
  765. PRINT_PEAK_SUMMARY("Sample", ebur128->sample_peaks, SAMPLES);
  766. PRINT_PEAK_SUMMARY("True", ebur128->true_peaks, TRUE);
  767. av_log(ctx, AV_LOG_INFO, "\n");
  768. av_freep(&ebur128->y_line_ref);
  769. av_freep(&ebur128->ch_weighting);
  770. av_freep(&ebur128->true_peaks);
  771. av_freep(&ebur128->sample_peaks);
  772. av_freep(&ebur128->true_peaks_per_frame);
  773. av_freep(&ebur128->i400.histogram);
  774. av_freep(&ebur128->i3000.histogram);
  775. for (i = 0; i < ebur128->nb_channels; i++) {
  776. av_freep(&ebur128->i400.cache[i]);
  777. av_freep(&ebur128->i3000.cache[i]);
  778. }
  779. for (i = 0; i < ctx->nb_outputs; i++)
  780. av_freep(&ctx->output_pads[i].name);
  781. av_frame_free(&ebur128->outpicref);
  782. #if CONFIG_SWRESAMPLE
  783. av_freep(&ebur128->swr_buf);
  784. swr_free(&ebur128->swr_ctx);
  785. #endif
  786. }
  787. static const AVFilterPad ebur128_inputs[] = {
  788. {
  789. .name = "default",
  790. .type = AVMEDIA_TYPE_AUDIO,
  791. .filter_frame = filter_frame,
  792. .config_props = config_audio_input,
  793. },
  794. { NULL }
  795. };
  796. AVFilter ff_af_ebur128 = {
  797. .name = "ebur128",
  798. .description = NULL_IF_CONFIG_SMALL("EBU R128 scanner."),
  799. .priv_size = sizeof(EBUR128Context),
  800. .init = init,
  801. .uninit = uninit,
  802. .query_formats = query_formats,
  803. .inputs = ebur128_inputs,
  804. .outputs = NULL,
  805. .priv_class = &ebur128_class,
  806. .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
  807. };