f_ebur128.c 37 KB

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