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.

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