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.

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