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.

588 lines
17KB

  1. /*
  2. * Copyright (c) 1999 Chris Bagwell
  3. * Copyright (c) 1999 Nick Bailey
  4. * Copyright (c) 2007 Rob Sykes <robs@users.sourceforge.net>
  5. * Copyright (c) 2013 Paul B Mahol
  6. * Copyright (c) 2014 Andrew Kelley
  7. *
  8. * This file is part of libav.
  9. *
  10. * Libav is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * Libav is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with Libav; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. /**
  25. * @file
  26. * audio compand filter
  27. */
  28. #include <string.h>
  29. #include "libavutil/channel_layout.h"
  30. #include "libavutil/common.h"
  31. #include "libavutil/mathematics.h"
  32. #include "libavutil/mem.h"
  33. #include "libavutil/opt.h"
  34. #include "audio.h"
  35. #include "avfilter.h"
  36. #include "formats.h"
  37. #include "internal.h"
  38. typedef struct ChanParam {
  39. float attack;
  40. float decay;
  41. float volume;
  42. } ChanParam;
  43. typedef struct CompandSegment {
  44. float x, y;
  45. float a, b;
  46. } CompandSegment;
  47. typedef struct CompandContext {
  48. const AVClass *class;
  49. int nb_channels;
  50. int nb_segments;
  51. char *attacks, *decays, *points;
  52. CompandSegment *segments;
  53. ChanParam *channels;
  54. float in_min_lin;
  55. float out_min_lin;
  56. double curve_dB;
  57. double gain_dB;
  58. double initial_volume;
  59. double delay;
  60. AVFrame *delay_frame;
  61. int delay_samples;
  62. int delay_count;
  63. int delay_index;
  64. int64_t pts;
  65. int (*compand)(AVFilterContext *ctx, AVFrame *frame);
  66. } CompandContext;
  67. #define OFFSET(x) offsetof(CompandContext, x)
  68. #define A AV_OPT_FLAG_AUDIO_PARAM
  69. static const AVOption compand_options[] = {
  70. { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, { .str = "0.3" }, 0, 0, A },
  71. { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, { .str = "0.8" }, 0, 0, A },
  72. { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, { .str = "-70/-70|-60/-20" }, 0, 0, A },
  73. { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0.01 }, 0.01, 900, A },
  74. { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 900, A },
  75. { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -900, 0, A },
  76. { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, 20, A },
  77. { NULL }
  78. };
  79. static const AVClass compand_class = {
  80. .class_name = "compand filter",
  81. .item_name = av_default_item_name,
  82. .option = compand_options,
  83. .version = LIBAVUTIL_VERSION_INT,
  84. };
  85. static av_cold int init(AVFilterContext *ctx)
  86. {
  87. CompandContext *s = ctx->priv;
  88. s->pts = AV_NOPTS_VALUE;
  89. return 0;
  90. }
  91. static av_cold void uninit(AVFilterContext *ctx)
  92. {
  93. CompandContext *s = ctx->priv;
  94. av_freep(&s->channels);
  95. av_freep(&s->segments);
  96. av_frame_free(&s->delay_frame);
  97. }
  98. static int query_formats(AVFilterContext *ctx)
  99. {
  100. AVFilterChannelLayouts *layouts;
  101. AVFilterFormats *formats;
  102. static const enum AVSampleFormat sample_fmts[] = {
  103. AV_SAMPLE_FMT_FLTP,
  104. AV_SAMPLE_FMT_NONE
  105. };
  106. layouts = ff_all_channel_layouts();
  107. if (!layouts)
  108. return AVERROR(ENOMEM);
  109. ff_set_common_channel_layouts(ctx, layouts);
  110. formats = ff_make_format_list(sample_fmts);
  111. if (!formats)
  112. return AVERROR(ENOMEM);
  113. ff_set_common_formats(ctx, formats);
  114. formats = ff_all_samplerates();
  115. if (!formats)
  116. return AVERROR(ENOMEM);
  117. ff_set_common_samplerates(ctx, formats);
  118. return 0;
  119. }
  120. static void count_items(char *item_str, int *nb_items)
  121. {
  122. char *p;
  123. *nb_items = 1;
  124. for (p = item_str; *p; p++) {
  125. if (*p == '|')
  126. (*nb_items)++;
  127. }
  128. }
  129. static void update_volume(ChanParam *cp, float in)
  130. {
  131. float delta = in - cp->volume;
  132. if (delta > 0.0)
  133. cp->volume += delta * cp->attack;
  134. else
  135. cp->volume += delta * cp->decay;
  136. }
  137. static float get_volume(CompandContext *s, float in_lin)
  138. {
  139. CompandSegment *cs;
  140. float in_log, out_log;
  141. int i;
  142. if (in_lin < s->in_min_lin)
  143. return s->out_min_lin;
  144. in_log = logf(in_lin);
  145. for (i = 1; i < s->nb_segments; i++)
  146. if (in_log <= s->segments[i].x)
  147. break;
  148. cs = &s->segments[i - 1];
  149. in_log -= cs->x;
  150. out_log = cs->y + in_log * (cs->a * in_log + cs->b);
  151. return expf(out_log);
  152. }
  153. static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
  154. {
  155. CompandContext *s = ctx->priv;
  156. AVFilterLink *inlink = ctx->inputs[0];
  157. const int channels = s->nb_channels;
  158. const int nb_samples = frame->nb_samples;
  159. AVFrame *out_frame;
  160. int chan, i;
  161. int err;
  162. if (av_frame_is_writable(frame)) {
  163. out_frame = frame;
  164. } else {
  165. out_frame = ff_get_audio_buffer(inlink, nb_samples);
  166. if (!out_frame) {
  167. av_frame_free(&frame);
  168. return AVERROR(ENOMEM);
  169. }
  170. err = av_frame_copy_props(out_frame, frame);
  171. if (err < 0) {
  172. av_frame_free(&out_frame);
  173. av_frame_free(&frame);
  174. return err;
  175. }
  176. }
  177. for (chan = 0; chan < channels; chan++) {
  178. const float *src = (float *)frame->extended_data[chan];
  179. float *dst = (float *)out_frame->extended_data[chan];
  180. ChanParam *cp = &s->channels[chan];
  181. for (i = 0; i < nb_samples; i++) {
  182. update_volume(cp, fabs(src[i]));
  183. dst[i] = av_clipf(src[i] * get_volume(s, cp->volume), -1.0f, 1.0f);
  184. }
  185. }
  186. if (frame != out_frame)
  187. av_frame_free(&frame);
  188. return ff_filter_frame(ctx->outputs[0], out_frame);
  189. }
  190. #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
  191. static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
  192. {
  193. CompandContext *s = ctx->priv;
  194. AVFilterLink *inlink = ctx->inputs[0];
  195. const int channels = s->nb_channels;
  196. const int nb_samples = frame->nb_samples;
  197. int chan, i, dindex = 0, oindex, count = 0;
  198. AVFrame *out_frame = NULL;
  199. int err;
  200. if (s->pts == AV_NOPTS_VALUE) {
  201. s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
  202. }
  203. for (chan = 0; chan < channels; chan++) {
  204. AVFrame *delay_frame = s->delay_frame;
  205. const float *src = (float *)frame->extended_data[chan];
  206. float *dbuf = (float *)delay_frame->extended_data[chan];
  207. ChanParam *cp = &s->channels[chan];
  208. float *dst;
  209. count = s->delay_count;
  210. dindex = s->delay_index;
  211. for (i = 0, oindex = 0; i < nb_samples; i++) {
  212. const float in = src[i];
  213. update_volume(cp, fabs(in));
  214. if (count >= s->delay_samples) {
  215. if (!out_frame) {
  216. out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
  217. if (!out_frame) {
  218. av_frame_free(&frame);
  219. return AVERROR(ENOMEM);
  220. }
  221. err = av_frame_copy_props(out_frame, frame);
  222. if (err < 0) {
  223. av_frame_free(&out_frame);
  224. av_frame_free(&frame);
  225. return err;
  226. }
  227. out_frame->pts = s->pts;
  228. s->pts += av_rescale_q(nb_samples - i,
  229. (AVRational){ 1, inlink->sample_rate },
  230. inlink->time_base);
  231. }
  232. dst = (float *)out_frame->extended_data[chan];
  233. dst[oindex++] = av_clipf(dbuf[dindex] *
  234. get_volume(s, cp->volume), -1.0f, 1.0f);
  235. } else {
  236. count++;
  237. }
  238. dbuf[dindex] = in;
  239. dindex = MOD(dindex + 1, s->delay_samples);
  240. }
  241. }
  242. s->delay_count = count;
  243. s->delay_index = dindex;
  244. av_frame_free(&frame);
  245. return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
  246. }
  247. static int compand_drain(AVFilterLink *outlink)
  248. {
  249. AVFilterContext *ctx = outlink->src;
  250. CompandContext *s = ctx->priv;
  251. const int channels = s->nb_channels;
  252. AVFrame *frame = NULL;
  253. int chan, i, dindex;
  254. /* 2048 is to limit output frame size during drain */
  255. frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
  256. if (!frame)
  257. return AVERROR(ENOMEM);
  258. frame->pts = s->pts;
  259. s->pts += av_rescale_q(frame->nb_samples,
  260. (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
  261. for (chan = 0; chan < channels; chan++) {
  262. AVFrame *delay_frame = s->delay_frame;
  263. float *dbuf = (float *)delay_frame->extended_data[chan];
  264. float *dst = (float *)frame->extended_data[chan];
  265. ChanParam *cp = &s->channels[chan];
  266. dindex = s->delay_index;
  267. for (i = 0; i < frame->nb_samples; i++) {
  268. dst[i] = av_clipf(dbuf[dindex] * get_volume(s, cp->volume),
  269. -1.0f, 1.0f);
  270. dindex = MOD(dindex + 1, s->delay_samples);
  271. }
  272. }
  273. s->delay_count -= frame->nb_samples;
  274. s->delay_index = dindex;
  275. return ff_filter_frame(outlink, frame);
  276. }
  277. static int config_output(AVFilterLink *outlink)
  278. {
  279. AVFilterContext *ctx = outlink->src;
  280. CompandContext *s = ctx->priv;
  281. const int sample_rate = outlink->sample_rate;
  282. double radius = s->curve_dB * M_LN10 / 20.0;
  283. char *p, *saveptr = NULL;
  284. const int channels =
  285. av_get_channel_layout_nb_channels(outlink->channel_layout);
  286. int nb_attacks, nb_decays, nb_points;
  287. int new_nb_items, num;
  288. int i;
  289. int err;
  290. count_items(s->attacks, &nb_attacks);
  291. count_items(s->decays, &nb_decays);
  292. count_items(s->points, &nb_points);
  293. if (channels <= 0) {
  294. av_log(ctx, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels);
  295. return AVERROR(EINVAL);
  296. }
  297. if (nb_attacks > channels || nb_decays > channels) {
  298. av_log(ctx, AV_LOG_ERROR,
  299. "Number of attacks/decays bigger than number of channels.\n");
  300. return AVERROR(EINVAL);
  301. }
  302. uninit(ctx);
  303. s->nb_channels = channels;
  304. s->channels = av_mallocz_array(channels, sizeof(*s->channels));
  305. s->nb_segments = (nb_points + 4) * 2;
  306. s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
  307. if (!s->channels || !s->segments) {
  308. uninit(ctx);
  309. return AVERROR(ENOMEM);
  310. }
  311. p = s->attacks;
  312. for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
  313. char *tstr = strtok_r(p, "|", &saveptr);
  314. p = NULL;
  315. new_nb_items += sscanf(tstr, "%f", &s->channels[i].attack) == 1;
  316. if (s->channels[i].attack < 0) {
  317. uninit(ctx);
  318. return AVERROR(EINVAL);
  319. }
  320. }
  321. nb_attacks = new_nb_items;
  322. p = s->decays;
  323. for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
  324. char *tstr = strtok_r(p, "|", &saveptr);
  325. p = NULL;
  326. new_nb_items += sscanf(tstr, "%f", &s->channels[i].decay) == 1;
  327. if (s->channels[i].decay < 0) {
  328. uninit(ctx);
  329. return AVERROR(EINVAL);
  330. }
  331. }
  332. nb_decays = new_nb_items;
  333. if (nb_attacks != nb_decays) {
  334. av_log(ctx, AV_LOG_ERROR,
  335. "Number of attacks %d differs from number of decays %d.\n",
  336. nb_attacks, nb_decays);
  337. uninit(ctx);
  338. return AVERROR(EINVAL);
  339. }
  340. #define S(x) s->segments[2 * ((x) + 1)]
  341. p = s->points;
  342. for (i = 0, new_nb_items = 0; i < nb_points; i++) {
  343. char *tstr = strtok_r(p, "|", &saveptr);
  344. p = NULL;
  345. if (sscanf(tstr, "%f/%f", &S(i).x, &S(i).y) != 2) {
  346. av_log(ctx, AV_LOG_ERROR,
  347. "Invalid and/or missing input/output value.\n");
  348. uninit(ctx);
  349. return AVERROR(EINVAL);
  350. }
  351. if (i && S(i - 1).x > S(i).x) {
  352. av_log(ctx, AV_LOG_ERROR,
  353. "Transfer function input values must be increasing.\n");
  354. uninit(ctx);
  355. return AVERROR(EINVAL);
  356. }
  357. S(i).y -= S(i).x;
  358. av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
  359. new_nb_items++;
  360. }
  361. num = new_nb_items;
  362. /* Add 0,0 if necessary */
  363. if (num == 0 || S(num - 1).x)
  364. num++;
  365. #undef S
  366. #define S(x) s->segments[2 * (x)]
  367. /* Add a tail off segment at the start */
  368. S(0).x = S(1).x - 2 * s->curve_dB;
  369. S(0).y = S(1).y;
  370. num++;
  371. /* Join adjacent colinear segments */
  372. for (i = 2; i < num; i++) {
  373. double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
  374. double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
  375. int j;
  376. /* here we purposefully lose precision so that we can compare floats */
  377. if (fabs(g1 - g2))
  378. continue;
  379. num--;
  380. for (j = --i; j < num; j++)
  381. S(j) = S(j + 1);
  382. }
  383. for (i = 0; !i || s->segments[i - 2].x; i += 2) {
  384. s->segments[i].y += s->gain_dB;
  385. s->segments[i].x *= M_LN10 / 20;
  386. s->segments[i].y *= M_LN10 / 20;
  387. }
  388. #define L(x) s->segments[i - (x)]
  389. for (i = 4; s->segments[i - 2].x; i += 2) {
  390. double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
  391. L(4).a = 0;
  392. L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
  393. L(2).a = 0;
  394. L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
  395. theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
  396. len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
  397. r = FFMIN(radius, len);
  398. L(3).x = L(2).x - r * cos(theta);
  399. L(3).y = L(2).y - r * sin(theta);
  400. theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
  401. len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
  402. r = FFMIN(radius, len / 2);
  403. x = L(2).x + r * cos(theta);
  404. y = L(2).y + r * sin(theta);
  405. cx = (L(3).x + L(2).x + x) / 3;
  406. cy = (L(3).y + L(2).y + y) / 3;
  407. L(2).x = x;
  408. L(2).y = y;
  409. in1 = cx - L(3).x;
  410. out1 = cy - L(3).y;
  411. in2 = L(2).x - L(3).x;
  412. out2 = L(2).y - L(3).y;
  413. L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
  414. L(3).b = out1 / in1 - L(3).a * in1;
  415. }
  416. L(3).x = 0;
  417. L(3).y = L(2).y;
  418. s->in_min_lin = exp(s->segments[1].x);
  419. s->out_min_lin = exp(s->segments[1].y);
  420. for (i = 0; i < channels; i++) {
  421. ChanParam *cp = &s->channels[i];
  422. if (cp->attack > 1.0 / sample_rate)
  423. cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
  424. else
  425. cp->attack = 1.0;
  426. if (cp->decay > 1.0 / sample_rate)
  427. cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
  428. else
  429. cp->decay = 1.0;
  430. cp->volume = pow(10.0, s->initial_volume / 20);
  431. }
  432. s->delay_samples = s->delay * sample_rate;
  433. if (s->delay_samples <= 0) {
  434. s->compand = compand_nodelay;
  435. return 0;
  436. }
  437. s->delay_frame = av_frame_alloc();
  438. if (!s->delay_frame) {
  439. uninit(ctx);
  440. return AVERROR(ENOMEM);
  441. }
  442. s->delay_frame->format = outlink->format;
  443. s->delay_frame->nb_samples = s->delay_samples;
  444. s->delay_frame->channel_layout = outlink->channel_layout;
  445. err = av_frame_get_buffer(s->delay_frame, 32);
  446. if (err)
  447. return err;
  448. s->compand = compand_delay;
  449. return 0;
  450. }
  451. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  452. {
  453. AVFilterContext *ctx = inlink->dst;
  454. CompandContext *s = ctx->priv;
  455. return s->compand(ctx, frame);
  456. }
  457. static int request_frame(AVFilterLink *outlink)
  458. {
  459. AVFilterContext *ctx = outlink->src;
  460. CompandContext *s = ctx->priv;
  461. int ret;
  462. ret = ff_request_frame(ctx->inputs[0]);
  463. if (ret == AVERROR_EOF && s->delay_count)
  464. ret = compand_drain(outlink);
  465. return ret;
  466. }
  467. static const AVFilterPad compand_inputs[] = {
  468. {
  469. .name = "default",
  470. .type = AVMEDIA_TYPE_AUDIO,
  471. .filter_frame = filter_frame,
  472. },
  473. { NULL }
  474. };
  475. static const AVFilterPad compand_outputs[] = {
  476. {
  477. .name = "default",
  478. .request_frame = request_frame,
  479. .config_props = config_output,
  480. .type = AVMEDIA_TYPE_AUDIO,
  481. },
  482. { NULL }
  483. };
  484. AVFilter ff_af_compand = {
  485. .name = "compand",
  486. .description = NULL_IF_CONFIG_SMALL(
  487. "Compress or expand audio dynamic range."),
  488. .query_formats = query_formats,
  489. .priv_size = sizeof(CompandContext),
  490. .priv_class = &compand_class,
  491. .init = init,
  492. .uninit = uninit,
  493. .inputs = compand_inputs,
  494. .outputs = compand_outputs,
  495. };