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.

590 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 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. int ret;
  98. layouts = ff_all_channel_counts();
  99. if (!layouts)
  100. return AVERROR(ENOMEM);
  101. ret = ff_set_common_channel_layouts(ctx, layouts);
  102. if (ret < 0)
  103. return ret;
  104. formats = ff_make_format_list(sample_fmts);
  105. if (!formats)
  106. return AVERROR(ENOMEM);
  107. ret = ff_set_common_formats(ctx, formats);
  108. if (ret < 0)
  109. return ret;
  110. formats = ff_all_samplerates();
  111. if (!formats)
  112. return AVERROR(ENOMEM);
  113. return ff_set_common_samplerates(ctx, formats);
  114. }
  115. static void count_items(char *item_str, int *nb_items)
  116. {
  117. char *p;
  118. *nb_items = 1;
  119. for (p = item_str; *p; p++) {
  120. if (*p == ' ' || *p == '|')
  121. (*nb_items)++;
  122. }
  123. }
  124. static void update_volume(ChanParam *cp, double in)
  125. {
  126. double delta = in - cp->volume;
  127. if (delta > 0.0)
  128. cp->volume += delta * cp->attack;
  129. else
  130. cp->volume += delta * cp->decay;
  131. }
  132. static double get_volume(CompandContext *s, double in_lin)
  133. {
  134. CompandSegment *cs;
  135. double in_log, out_log;
  136. int i;
  137. if (in_lin < s->in_min_lin)
  138. return s->out_min_lin;
  139. in_log = log(in_lin);
  140. for (i = 1; i < s->nb_segments; i++)
  141. if (in_log <= s->segments[i].x)
  142. break;
  143. cs = &s->segments[i - 1];
  144. in_log -= cs->x;
  145. out_log = cs->y + in_log * (cs->a * in_log + cs->b);
  146. return exp(out_log);
  147. }
  148. static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)
  149. {
  150. CompandContext *s = ctx->priv;
  151. AVFilterLink *inlink = ctx->inputs[0];
  152. const int channels = inlink->channels;
  153. const int nb_samples = frame->nb_samples;
  154. AVFrame *out_frame;
  155. int chan, i;
  156. int err;
  157. if (av_frame_is_writable(frame)) {
  158. out_frame = frame;
  159. } else {
  160. out_frame = ff_get_audio_buffer(inlink, nb_samples);
  161. if (!out_frame) {
  162. av_frame_free(&frame);
  163. return AVERROR(ENOMEM);
  164. }
  165. err = av_frame_copy_props(out_frame, frame);
  166. if (err < 0) {
  167. av_frame_free(&out_frame);
  168. av_frame_free(&frame);
  169. return err;
  170. }
  171. }
  172. for (chan = 0; chan < channels; chan++) {
  173. const double *src = (double *)frame->extended_data[chan];
  174. double *dst = (double *)out_frame->extended_data[chan];
  175. ChanParam *cp = &s->channels[chan];
  176. for (i = 0; i < nb_samples; i++) {
  177. update_volume(cp, fabs(src[i]));
  178. dst[i] = src[i] * get_volume(s, cp->volume);
  179. }
  180. }
  181. if (frame != out_frame)
  182. av_frame_free(&frame);
  183. return ff_filter_frame(ctx->outputs[0], out_frame);
  184. }
  185. #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
  186. static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
  187. {
  188. CompandContext *s = ctx->priv;
  189. AVFilterLink *inlink = ctx->inputs[0];
  190. const int channels = inlink->channels;
  191. const int nb_samples = frame->nb_samples;
  192. int chan, i, av_uninit(dindex), oindex, av_uninit(count);
  193. AVFrame *out_frame = NULL;
  194. int err;
  195. if (s->pts == AV_NOPTS_VALUE) {
  196. s->pts = (frame->pts == AV_NOPTS_VALUE) ? 0 : frame->pts;
  197. }
  198. av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
  199. for (chan = 0; chan < channels; chan++) {
  200. AVFrame *delay_frame = s->delay_frame;
  201. const double *src = (double *)frame->extended_data[chan];
  202. double *dbuf = (double *)delay_frame->extended_data[chan];
  203. ChanParam *cp = &s->channels[chan];
  204. double *dst;
  205. count = s->delay_count;
  206. dindex = s->delay_index;
  207. for (i = 0, oindex = 0; i < nb_samples; i++) {
  208. const double in = src[i];
  209. update_volume(cp, fabs(in));
  210. if (count >= s->delay_samples) {
  211. if (!out_frame) {
  212. out_frame = ff_get_audio_buffer(inlink, nb_samples - i);
  213. if (!out_frame) {
  214. av_frame_free(&frame);
  215. return AVERROR(ENOMEM);
  216. }
  217. err = av_frame_copy_props(out_frame, frame);
  218. if (err < 0) {
  219. av_frame_free(&out_frame);
  220. av_frame_free(&frame);
  221. return err;
  222. }
  223. out_frame->pts = s->pts;
  224. s->pts += av_rescale_q(nb_samples - i,
  225. (AVRational){ 1, inlink->sample_rate },
  226. inlink->time_base);
  227. }
  228. dst = (double *)out_frame->extended_data[chan];
  229. dst[oindex++] = dbuf[dindex] * get_volume(s, cp->volume);
  230. } else {
  231. count++;
  232. }
  233. dbuf[dindex] = in;
  234. dindex = MOD(dindex + 1, s->delay_samples);
  235. }
  236. }
  237. s->delay_count = count;
  238. s->delay_index = dindex;
  239. av_frame_free(&frame);
  240. if (out_frame) {
  241. err = ff_filter_frame(ctx->outputs[0], out_frame);
  242. return err;
  243. }
  244. return 0;
  245. }
  246. static int compand_drain(AVFilterLink *outlink)
  247. {
  248. AVFilterContext *ctx = outlink->src;
  249. CompandContext *s = ctx->priv;
  250. const int channels = outlink->channels;
  251. AVFrame *frame = NULL;
  252. int chan, i, dindex;
  253. /* 2048 is to limit output frame size during drain */
  254. frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
  255. if (!frame)
  256. return AVERROR(ENOMEM);
  257. frame->pts = s->pts;
  258. s->pts += av_rescale_q(frame->nb_samples,
  259. (AVRational){ 1, outlink->sample_rate }, outlink->time_base);
  260. av_assert0(channels > 0);
  261. for (chan = 0; chan < channels; chan++) {
  262. AVFrame *delay_frame = s->delay_frame;
  263. double *dbuf = (double *)delay_frame->extended_data[chan];
  264. double *dst = (double *)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] = dbuf[dindex] * get_volume(s, cp->volume);
  269. dindex = MOD(dindex + 1, s->delay_samples);
  270. }
  271. }
  272. s->delay_count -= frame->nb_samples;
  273. s->delay_index = dindex;
  274. return ff_filter_frame(outlink, frame);
  275. }
  276. static int config_output(AVFilterLink *outlink)
  277. {
  278. AVFilterContext *ctx = outlink->src;
  279. CompandContext *s = ctx->priv;
  280. const int sample_rate = outlink->sample_rate;
  281. double radius = s->curve_dB * M_LN10 / 20.0;
  282. char *p, *saveptr = NULL;
  283. const int channels = outlink->channels;
  284. int nb_attacks, nb_decays, nb_points;
  285. int new_nb_items, num;
  286. int i;
  287. int err;
  288. count_items(s->attacks, &nb_attacks);
  289. count_items(s->decays, &nb_decays);
  290. count_items(s->points, &nb_points);
  291. if (channels <= 0) {
  292. av_log(ctx, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels);
  293. return AVERROR(EINVAL);
  294. }
  295. if (nb_attacks > channels || nb_decays > channels) {
  296. av_log(ctx, AV_LOG_ERROR,
  297. "Number of attacks/decays bigger than number of channels.\n");
  298. return AVERROR(EINVAL);
  299. }
  300. uninit(ctx);
  301. s->channels = av_mallocz_array(channels, sizeof(*s->channels));
  302. s->nb_segments = (nb_points + 4) * 2;
  303. s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
  304. if (!s->channels || !s->segments) {
  305. uninit(ctx);
  306. return AVERROR(ENOMEM);
  307. }
  308. p = s->attacks;
  309. for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
  310. char *tstr = av_strtok(p, " |", &saveptr);
  311. p = NULL;
  312. new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
  313. if (s->channels[i].attack < 0) {
  314. uninit(ctx);
  315. return AVERROR(EINVAL);
  316. }
  317. }
  318. nb_attacks = new_nb_items;
  319. p = s->decays;
  320. for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
  321. char *tstr = av_strtok(p, " |", &saveptr);
  322. p = NULL;
  323. new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
  324. if (s->channels[i].decay < 0) {
  325. uninit(ctx);
  326. return AVERROR(EINVAL);
  327. }
  328. }
  329. nb_decays = new_nb_items;
  330. if (nb_attacks != nb_decays) {
  331. av_log(ctx, AV_LOG_ERROR,
  332. "Number of attacks %d differs from number of decays %d.\n",
  333. nb_attacks, nb_decays);
  334. uninit(ctx);
  335. return AVERROR(EINVAL);
  336. }
  337. for (i = nb_decays; i < channels; i++) {
  338. s->channels[i].attack = s->channels[nb_decays - 1].attack;
  339. s->channels[i].decay = s->channels[nb_decays - 1].decay;
  340. }
  341. #define S(x) s->segments[2 * ((x) + 1)]
  342. p = s->points;
  343. for (i = 0, new_nb_items = 0; i < nb_points; i++) {
  344. char *tstr = av_strtok(p, " |", &saveptr);
  345. p = NULL;
  346. if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
  347. av_log(ctx, AV_LOG_ERROR,
  348. "Invalid and/or missing input/output value.\n");
  349. uninit(ctx);
  350. return AVERROR(EINVAL);
  351. }
  352. if (i && S(i - 1).x > S(i).x) {
  353. av_log(ctx, AV_LOG_ERROR,
  354. "Transfer function input values must be increasing.\n");
  355. uninit(ctx);
  356. return AVERROR(EINVAL);
  357. }
  358. S(i).y -= S(i).x;
  359. av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
  360. new_nb_items++;
  361. }
  362. num = new_nb_items;
  363. /* Add 0,0 if necessary */
  364. if (num == 0 || S(num - 1).x)
  365. num++;
  366. #undef S
  367. #define S(x) s->segments[2 * (x)]
  368. /* Add a tail off segment at the start */
  369. S(0).x = S(1).x - 2 * s->curve_dB;
  370. S(0).y = S(1).y;
  371. num++;
  372. /* Join adjacent colinear segments */
  373. for (i = 2; i < num; i++) {
  374. double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
  375. double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
  376. int j;
  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->nb_segments; 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; i < s->nb_segments; 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 = hypot(L(2).x - L(4).x, L(2).y - L(4).y);
  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 = hypot(L(0).x - L(2).x, L(0).y - L(2).y);
  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 = ff_exp10(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 = 0;
  462. ret = ff_request_frame(ctx->inputs[0]);
  463. if (ret == AVERROR_EOF && !ctx->is_disabled && 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. };