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.

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