af_compand.c 17 KB

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