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.

523 lines
15KB

  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. double in_min_lin;
  46. double out_min_lin;
  47. double curve_dB;
  48. double gain_dB;
  49. double initial_volume;
  50. double delay;
  51. uint8_t **delayptrs;
  52. int delay_samples;
  53. int delay_count;
  54. int delay_index;
  55. int64_t pts;
  56. int (*compand)(AVFilterContext *ctx, AVFrame *frame);
  57. } CompandContext;
  58. #define OFFSET(x) offsetof(CompandContext, x)
  59. #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  60. static const AVOption compand_options[] = {
  61. { "attacks", "set time over which increase of volume is determined", OFFSET(attacks), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
  62. { "decays", "set time over which decrease of volume is determined", OFFSET(decays), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
  63. { "points", "set points of transfer function", OFFSET(points), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, A },
  64. { "soft-knee", "set soft-knee", OFFSET(curve_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0.01}, 0.01, 900, A },
  65. { "gain", "set output gain", OFFSET(gain_dB), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 900, A },
  66. { "volume", "set initial volume", OFFSET(initial_volume), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -900, 0, A },
  67. { "delay", "set delay for samples before sending them to volume adjuster", OFFSET(delay), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 20, A },
  68. { NULL }
  69. };
  70. AVFILTER_DEFINE_CLASS(compand);
  71. static av_cold int init(AVFilterContext *ctx)
  72. {
  73. CompandContext *s = ctx->priv;
  74. if (!s->attacks || !s->decays || !s->points) {
  75. av_log(ctx, AV_LOG_ERROR, "Missing attacks and/or decays and/or points.\n");
  76. return AVERROR(EINVAL);
  77. }
  78. return 0;
  79. }
  80. static av_cold void uninit(AVFilterContext *ctx)
  81. {
  82. CompandContext *s = ctx->priv;
  83. av_freep(&s->channels);
  84. av_freep(&s->segments);
  85. if (s->delayptrs)
  86. av_freep(&s->delayptrs[0]);
  87. av_freep(&s->delayptrs);
  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 == ' ')
  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++)
  137. if (in_log <= s->segments[i + 1].x)
  138. break;
  139. cs = &s->segments[i];
  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. if (av_frame_is_writable(frame)) {
  153. out_frame = frame;
  154. } else {
  155. out_frame = ff_get_audio_buffer(inlink, nb_samples);
  156. if (!out_frame) {
  157. av_frame_free(&frame);
  158. return AVERROR(ENOMEM);
  159. }
  160. av_frame_copy_props(out_frame, frame);
  161. }
  162. for (chan = 0; chan < channels; chan++) {
  163. const double *src = (double *)frame->extended_data[chan];
  164. double *dst = (double *)out_frame->extended_data[chan];
  165. ChanParam *cp = &s->channels[chan];
  166. for (i = 0; i < nb_samples; i++) {
  167. update_volume(cp, fabs(src[i]));
  168. dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);
  169. }
  170. }
  171. if (frame != out_frame)
  172. av_frame_free(&frame);
  173. return ff_filter_frame(ctx->outputs[0], out_frame);
  174. }
  175. #define MOD(a, b) (((a) >= (b)) ? (a) - (b) : (a))
  176. static int compand_delay(AVFilterContext *ctx, AVFrame *frame)
  177. {
  178. CompandContext *s = ctx->priv;
  179. AVFilterLink *inlink = ctx->inputs[0];
  180. const int channels = inlink->channels;
  181. const int nb_samples = frame->nb_samples;
  182. int chan, i, av_uninit(dindex), oindex, av_uninit(count);
  183. AVFrame *out_frame = NULL;
  184. av_assert1(channels > 0); /* would corrupt delay_count and delay_index */
  185. for (chan = 0; chan < channels; chan++) {
  186. const double *src = (double *)frame->extended_data[chan];
  187. double *dbuf = (double *)s->delayptrs[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, (AVRational){1, inlink->sample_rate}, inlink->time_base);
  205. }
  206. dst = (double *)out_frame->extended_data[chan];
  207. dst[oindex++] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
  208. } else {
  209. count++;
  210. }
  211. dbuf[dindex] = in;
  212. dindex = MOD(dindex + 1, s->delay_samples);
  213. }
  214. }
  215. s->delay_count = count;
  216. s->delay_index = dindex;
  217. av_frame_free(&frame);
  218. return out_frame ? ff_filter_frame(ctx->outputs[0], out_frame) : 0;
  219. }
  220. static int compand_drain(AVFilterLink *outlink)
  221. {
  222. AVFilterContext *ctx = outlink->src;
  223. CompandContext *s = ctx->priv;
  224. const int channels = outlink->channels;
  225. int chan, i, dindex;
  226. AVFrame *frame = NULL;
  227. frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));
  228. if (!frame)
  229. return AVERROR(ENOMEM);
  230. frame->pts = s->pts;
  231. s->pts += av_rescale_q(frame->nb_samples, (AVRational){1, outlink->sample_rate}, outlink->time_base);
  232. for (chan = 0; chan < channels; chan++) {
  233. double *dbuf = (double *)s->delayptrs[chan];
  234. double *dst = (double *)frame->extended_data[chan];
  235. ChanParam *cp = &s->channels[chan];
  236. dindex = s->delay_index;
  237. for (i = 0; i < frame->nb_samples; i++) {
  238. dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume), -1, 1);
  239. dindex = MOD(dindex + 1, s->delay_samples);
  240. }
  241. }
  242. s->delay_count -= frame->nb_samples;
  243. s->delay_index = dindex;
  244. return ff_filter_frame(outlink, frame);
  245. }
  246. static int config_output(AVFilterLink *outlink)
  247. {
  248. AVFilterContext *ctx = outlink->src;
  249. CompandContext *s = ctx->priv;
  250. const int sample_rate = outlink->sample_rate;
  251. double radius = s->curve_dB * M_LN10 / 20;
  252. int nb_attacks, nb_decays, nb_points;
  253. char *p, *saveptr = NULL;
  254. int new_nb_items, num;
  255. int i;
  256. count_items(s->attacks, &nb_attacks);
  257. count_items(s->decays, &nb_decays);
  258. count_items(s->points, &nb_points);
  259. if ((nb_attacks > outlink->channels) || (nb_decays > outlink->channels)) {
  260. av_log(ctx, AV_LOG_ERROR, "Number of attacks/decays bigger than number of channels.\n");
  261. return AVERROR(EINVAL);
  262. }
  263. uninit(ctx);
  264. s->channels = av_mallocz_array(outlink->channels, sizeof(*s->channels));
  265. s->segments = av_mallocz_array((nb_points + 4) * 2, sizeof(*s->segments));
  266. if (!s->channels || !s->segments)
  267. return AVERROR(ENOMEM);
  268. p = s->attacks;
  269. for (i = 0, new_nb_items = 0; i < nb_attacks; i++) {
  270. char *tstr = av_strtok(p, " ", &saveptr);
  271. p = NULL;
  272. new_nb_items += sscanf(tstr, "%lf", &s->channels[i].attack) == 1;
  273. if (s->channels[i].attack < 0)
  274. return AVERROR(EINVAL);
  275. }
  276. nb_attacks = new_nb_items;
  277. p = s->decays;
  278. for (i = 0, new_nb_items = 0; i < nb_decays; i++) {
  279. char *tstr = av_strtok(p, " ", &saveptr);
  280. p = NULL;
  281. new_nb_items += sscanf(tstr, "%lf", &s->channels[i].decay) == 1;
  282. if (s->channels[i].decay < 0)
  283. return AVERROR(EINVAL);
  284. }
  285. nb_decays = new_nb_items;
  286. if (nb_attacks != nb_decays) {
  287. av_log(ctx, AV_LOG_ERROR, "Number of attacks %d differs from number of decays %d.\n", nb_attacks, nb_decays);
  288. return AVERROR(EINVAL);
  289. }
  290. #define S(x) s->segments[2 * ((x) + 1)]
  291. p = s->points;
  292. for (i = 0, new_nb_items = 0; i < nb_points; i++) {
  293. char *tstr = av_strtok(p, " ", &saveptr);
  294. p = NULL;
  295. if (sscanf(tstr, "%lf/%lf", &S(i).x, &S(i).y) != 2) {
  296. av_log(ctx, AV_LOG_ERROR, "Invalid and/or missing input/output value.\n");
  297. return AVERROR(EINVAL);
  298. }
  299. if (i && S(i - 1).x > S(i).x) {
  300. av_log(ctx, AV_LOG_ERROR, "Transfer function input values must be increasing.\n");
  301. return AVERROR(EINVAL);
  302. }
  303. S(i).y -= S(i).x;
  304. av_log(ctx, AV_LOG_DEBUG, "%d: x=%f y=%f\n", i, S(i).x, S(i).y);
  305. new_nb_items++;
  306. }
  307. num = new_nb_items;
  308. /* Add 0,0 if necessary */
  309. if (num == 0 || S(num - 1).x)
  310. num++;
  311. #undef S
  312. #define S(x) s->segments[2 * (x)]
  313. /* Add a tail off segment at the start */
  314. S(0).x = S(1).x - 2 * s->curve_dB;
  315. S(0).y = S(1).y;
  316. num++;
  317. /* Join adjacent colinear segments */
  318. for (i = 2; i < num; i++) {
  319. double g1 = (S(i - 1).y - S(i - 2).y) * (S(i - 0).x - S(i - 1).x);
  320. double g2 = (S(i - 0).y - S(i - 1).y) * (S(i - 1).x - S(i - 2).x);
  321. int j;
  322. if (fabs(g1 - g2))
  323. continue;
  324. num--;
  325. for (j = --i; j < num; j++)
  326. S(j) = S(j + 1);
  327. }
  328. for (i = 0; !i || s->segments[i - 2].x; i += 2) {
  329. s->segments[i].y += s->gain_dB;
  330. s->segments[i].x *= M_LN10 / 20;
  331. s->segments[i].y *= M_LN10 / 20;
  332. }
  333. #define L(x) s->segments[i - (x)]
  334. for (i = 4; s->segments[i - 2].x; i += 2) {
  335. double x, y, cx, cy, in1, in2, out1, out2, theta, len, r;
  336. L(4).a = 0;
  337. L(4).b = (L(2).y - L(4).y) / (L(2).x - L(4).x);
  338. L(2).a = 0;
  339. L(2).b = (L(0).y - L(2).y) / (L(0).x - L(2).x);
  340. theta = atan2(L(2).y - L(4).y, L(2).x - L(4).x);
  341. len = sqrt(pow(L(2).x - L(4).x, 2.) + pow(L(2).y - L(4).y, 2.));
  342. r = FFMIN(radius, len);
  343. L(3).x = L(2).x - r * cos(theta);
  344. L(3).y = L(2).y - r * sin(theta);
  345. theta = atan2(L(0).y - L(2).y, L(0).x - L(2).x);
  346. len = sqrt(pow(L(0).x - L(2).x, 2.) + pow(L(0).y - L(2).y, 2.));
  347. r = FFMIN(radius, len / 2);
  348. x = L(2).x + r * cos(theta);
  349. y = L(2).y + r * sin(theta);
  350. cx = (L(3).x + L(2).x + x) / 3;
  351. cy = (L(3).y + L(2).y + y) / 3;
  352. L(2).x = x;
  353. L(2).y = y;
  354. in1 = cx - L(3).x;
  355. out1 = cy - L(3).y;
  356. in2 = L(2).x - L(3).x;
  357. out2 = L(2).y - L(3).y;
  358. L(3).a = (out2 / in2 - out1 / in1) / (in2-in1);
  359. L(3).b = out1 / in1 - L(3).a * in1;
  360. }
  361. L(3).x = 0;
  362. L(3).y = L(2).y;
  363. s->in_min_lin = exp(s->segments[1].x);
  364. s->out_min_lin = exp(s->segments[1].y);
  365. for (i = 0; i < outlink->channels; i++) {
  366. ChanParam *cp = &s->channels[i];
  367. if (cp->attack > 1.0 / sample_rate)
  368. cp->attack = 1.0 - exp(-1.0 / (sample_rate * cp->attack));
  369. else
  370. cp->attack = 1.0;
  371. if (cp->decay > 1.0 / sample_rate)
  372. cp->decay = 1.0 - exp(-1.0 / (sample_rate * cp->decay));
  373. else
  374. cp->decay = 1.0;
  375. cp->volume = pow(10.0, s->initial_volume / 20);
  376. }
  377. s->delay_samples = s->delay * sample_rate;
  378. if (s->delay_samples > 0) {
  379. int ret;
  380. if ((ret = av_samples_alloc_array_and_samples(&s->delayptrs, NULL,
  381. outlink->channels,
  382. s->delay_samples,
  383. outlink->format, 0)) < 0)
  384. return ret;
  385. s->compand = compand_delay;
  386. outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
  387. } else {
  388. s->compand = compand_nodelay;
  389. }
  390. return 0;
  391. }
  392. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  393. {
  394. AVFilterContext *ctx = inlink->dst;
  395. CompandContext *s = ctx->priv;
  396. return s->compand(ctx, frame);
  397. }
  398. static int request_frame(AVFilterLink *outlink)
  399. {
  400. AVFilterContext *ctx = outlink->src;
  401. CompandContext *s = ctx->priv;
  402. int ret;
  403. ret = ff_request_frame(ctx->inputs[0]);
  404. if (ret == AVERROR_EOF && !ctx->is_disabled && s->delay_count)
  405. ret = compand_drain(outlink);
  406. return ret;
  407. }
  408. static const AVFilterPad compand_inputs[] = {
  409. {
  410. .name = "default",
  411. .type = AVMEDIA_TYPE_AUDIO,
  412. .filter_frame = filter_frame,
  413. },
  414. { NULL }
  415. };
  416. static const AVFilterPad compand_outputs[] = {
  417. {
  418. .name = "default",
  419. .request_frame = request_frame,
  420. .config_props = config_output,
  421. .type = AVMEDIA_TYPE_AUDIO,
  422. },
  423. { NULL }
  424. };
  425. AVFilter ff_af_compand = {
  426. .name = "compand",
  427. .description = NULL_IF_CONFIG_SMALL("Compress or expand audio dynamic range."),
  428. .query_formats = query_formats,
  429. .priv_size = sizeof(CompandContext),
  430. .priv_class = &compand_class,
  431. .init = init,
  432. .uninit = uninit,
  433. .inputs = compand_inputs,
  434. .outputs = compand_outputs,
  435. };