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.

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