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.

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