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.

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