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.

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