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.

593 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_layouts();
  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] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
  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++] = av_clipd(dbuf[dindex] *
  230. get_volume(s, cp->volume), -1, 1);
  231. } else {
  232. count++;
  233. }
  234. dbuf[dindex] = in;
  235. dindex = MOD(dindex + 1, s->delay_samples);
  236. }
  237. }
  238. s->delay_count = count;
  239. s->delay_index = dindex;
  240. av_frame_free(&frame);
  241. if (out_frame) {
  242. err = ff_filter_frame(ctx->outputs[0], out_frame);
  243. return err;
  244. }
  245. return 0;
  246. }
  247. static int compand_drain(AVFilterLink *outlink)
  248. {
  249. AVFilterContext *ctx = outlink->src;
  250. CompandContext *s = ctx->priv;
  251. const int channels = outlink->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. av_assert0(channels > 0);
  262. for (chan = 0; chan < channels; chan++) {
  263. AVFrame *delay_frame = s->delay_frame;
  264. double *dbuf = (double *)delay_frame->extended_data[chan];
  265. double *dst = (double *)frame->extended_data[chan];
  266. ChanParam *cp = &s->channels[chan];
  267. dindex = s->delay_index;
  268. for (i = 0; i < frame->nb_samples; i++) {
  269. dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume),
  270. -1, 1);
  271. dindex = MOD(dindex + 1, s->delay_samples);
  272. }
  273. }
  274. s->delay_count -= frame->nb_samples;
  275. s->delay_index = dindex;
  276. return ff_filter_frame(outlink, frame);
  277. }
  278. static int config_output(AVFilterLink *outlink)
  279. {
  280. AVFilterContext *ctx = outlink->src;
  281. CompandContext *s = ctx->priv;
  282. const int sample_rate = outlink->sample_rate;
  283. double radius = s->curve_dB * M_LN10 / 20.0;
  284. char *p, *saveptr = NULL;
  285. const int channels = outlink->channels;
  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->channels = av_mallocz_array(channels, sizeof(*s->channels));
  304. s->nb_segments = (nb_points + 4) * 2;
  305. s->segments = av_mallocz_array(s->nb_segments, sizeof(*s->segments));
  306. if (!s->channels || !s->segments) {
  307. uninit(ctx);
  308. return AVERROR(ENOMEM);
  309. }
  310. p = s->attacks;
  311. for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
  312. char *tstr = av_strtok(p, " |", &saveptr);
  313. p = NULL;
  314. new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
  315. if (s->channels[i].attack < 0) {
  316. uninit(ctx);
  317. return AVERROR(EINVAL);
  318. }
  319. }
  320. nb_attacks = new_nb_items;
  321. p = s->decays;
  322. for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
  323. char *tstr = av_strtok(p, " |", &saveptr);
  324. p = NULL;
  325. new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
  326. if (s->channels[i].decay < 0) {
  327. uninit(ctx);
  328. return AVERROR(EINVAL);
  329. }
  330. }
  331. nb_decays = new_nb_items;
  332. if (nb_attacks != nb_decays) {
  333. av_log(ctx, AV_LOG_ERROR,
  334. "Number of attacks %d differs from number of decays %d.\n",
  335. nb_attacks, nb_decays);
  336. uninit(ctx);
  337. return AVERROR(EINVAL);
  338. }
  339. for (i = nb_decays; i < channels; i++) {
  340. s->channels[i].attack = s->channels[nb_decays - 1].attack;
  341. s->channels[i].decay = s->channels[nb_decays - 1].decay;
  342. }
  343. #define S(x) s->segments[2 * ((x) + 1)]
  344. p = s->points;
  345. for (i = 0, new_nb_items = 0; i < nb_points; i++) {
  346. char *tstr = av_strtok(p, " |", &saveptr);
  347. p = NULL;
  348. if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
  349. av_log(ctx, AV_LOG_ERROR,
  350. "Invalid and/or missing input/output value.\n");
  351. uninit(ctx);
  352. return AVERROR(EINVAL);
  353. }
  354. if (i && S(i - 1).x > S(i).x) {
  355. av_log(ctx, AV_LOG_ERROR,
  356. "Transfer function input values must be increasing.\n");
  357. uninit(ctx);
  358. return AVERROR(EINVAL);
  359. }
  360. S(i).y -= S(i).x;
  361. av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
  362. new_nb_items++;
  363. }
  364. num = new_nb_items;
  365. /* Add 0,0 if necessary */
  366. if (num == 0 || S(num - 1).x)
  367. num++;
  368. #undef S
  369. #define S(x) s->segments[2 * (x)]
  370. /* Add a tail off segment at the start */
  371. S(0).x = S(1).x - 2 * s->curve_dB;
  372. S(0).y = S(1).y;
  373. num++;
  374. /* Join adjacent colinear segments */
  375. for (i = 2; i < num; i++) {
  376. double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
  377. double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
  378. int j;
  379. if (fabs(g1 - g2))
  380. continue;
  381. num--;
  382. for (j = --i; j < num; j++)
  383. S(j) = S(j + 1);
  384. }
  385. for (i = 0; !i || s->segments[i - 2].x; i += 2) {
  386. s->segments[i].y += s->gain_dB;
  387. s->segments[i].x *= M_LN10 / 20;
  388. s->segments[i].y *= M_LN10 / 20;
  389. }
  390. #define L(x) s->segments[i - (x)]
  391. for (i = 4; s->segments[i - 2].x; i += 2) {
  392. double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
  393. L(4).a = 0;
  394. L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
  395. L(2).a = 0;
  396. L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
  397. theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
  398. len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
  399. r = FFMIN(radius, len);
  400. L(3).x = L(2).x - r * cos(theta);
  401. L(3).y = L(2).y - r * sin(theta);
  402. theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
  403. len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
  404. r = FFMIN(radius, len / 2);
  405. x = L(2).x + r * cos(theta);
  406. y = L(2).y + r * sin(theta);
  407. cx = (L(3).x + L(2).x + x) / 3;
  408. cy = (L(3).y + L(2).y + y) / 3;
  409. L(2).x = x;
  410. L(2).y = y;
  411. in1 = cx - L(3).x;
  412. out1 = cy - L(3).y;
  413. in2 = L(2).x - L(3).x;
  414. out2 = L(2).y - L(3).y;
  415. L(3).a = (out2 / in2 - out1 / in1) / (in2 - in1);
  416. L(3).b = out1 / in1 - L(3).a * in1;
  417. }
  418. L(3).x = 0;
  419. L(3).y = L(2).y;
  420. s->in_min_lin = exp(s->segments[1].x);
  421. s->out_min_lin = exp(s->segments[1].y);
  422. for (i = 0; i < channels; i++) {
  423. ChanParam *cp = &s->channels[i];
  424. if (cp->attack > 1.0 / sample_rate)
  425. cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
  426. else
  427. cp->attack = 1.0;
  428. if (cp->decay > 1.0 / sample_rate)
  429. cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
  430. else
  431. cp->decay = 1.0;
  432. cp->volume = pow(10.0, s->initial_volume / 20);
  433. }
  434. s->delay_samples = s->delay * sample_rate;
  435. if (s->delay_samples <= 0) {
  436. s->compand = compand_nodelay;
  437. return 0;
  438. }
  439. s->delay_frame = av_frame_alloc();
  440. if (!s->delay_frame) {
  441. uninit(ctx);
  442. return AVERROR(ENOMEM);
  443. }
  444. s->delay_frame->format = outlink->format;
  445. s->delay_frame->nb_samples = s->delay_samples;
  446. s->delay_frame->channel_layout = outlink->channel_layout;
  447. err = av_frame_get_buffer(s->delay_frame, 32);
  448. if (err)
  449. return err;
  450. outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
  451. s->compand = compand_delay;
  452. return 0;
  453. }
  454. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  455. {
  456. AVFilterContext *ctx = inlink->dst;
  457. CompandContext *s = ctx->priv;
  458. return s->compand(ctx, frame);
  459. }
  460. static int request_frame(AVFilterLink *outlink)
  461. {
  462. AVFilterContext *ctx = outlink->src;
  463. CompandContext *s = ctx->priv;
  464. int ret = 0;
  465. ret = ff_request_frame(ctx->inputs[0]);
  466. if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
  467. ret = compand_drain(outlink);
  468. return ret;
  469. }
  470. static const AVFilterPad compand_inputs[] = {
  471. {
  472. .name = "default",
  473. .type = AVMEDIA_TYPE_AUDIO,
  474. .filter_frame = filter_frame,
  475. },
  476. { NULL }
  477. };
  478. static const AVFilterPad compand_outputs[] = {
  479. {
  480. .name = "default",
  481. .request_frame = request_frame,
  482. .config_props = config_output,
  483. .type = AVMEDIA_TYPE_AUDIO,
  484. },
  485. { NULL }
  486. };
  487. AVFilter ff_af_compand = {
  488. .name = "compand",
  489. .description = NULL_IF_CONFIG_SMALL(
  490. "Compress or expand audio dynamic range."),
  491. .query_formats = query_formats,
  492. .priv_size = sizeof(CompandContext),
  493. .priv_class = &compand_class,
  494. .init = init,
  495. .uninit = uninit,
  496. .inputs = compand_inputs,
  497. .outputs = compand_outputs,
  498. };