af_compand.c 17 KB

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