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.

961 lines
39KB

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