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.

559 lines
16KB

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