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.

1559 lines
45KB

  1. /*
  2. * Copyright (c) 2018 Gregor Richards
  3. * Copyright (c) 2017 Mozilla
  4. * Copyright (c) 2005-2009 Xiph.Org Foundation
  5. * Copyright (c) 2007-2008 CSIRO
  6. * Copyright (c) 2008-2011 Octasic Inc.
  7. * Copyright (c) Jean-Marc Valin
  8. * Copyright (c) 2019 Paul B Mahol
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions
  12. * are met:
  13. *
  14. * - Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. *
  17. * - Redistributions in binary form must reproduce the above copyright
  18. * notice, this list of conditions and the following disclaimer in the
  19. * documentation and/or other materials provided with the distribution.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
  25. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  26. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  27. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  28. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  29. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  30. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  31. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. */
  33. #include <float.h>
  34. #include "libavutil/avassert.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/float_dsp.h"
  37. #include "libavutil/opt.h"
  38. #include "libavutil/tx.h"
  39. #include "avfilter.h"
  40. #include "audio.h"
  41. #include "filters.h"
  42. #include "formats.h"
  43. #define FRAME_SIZE_SHIFT 2
  44. #define FRAME_SIZE (120<<FRAME_SIZE_SHIFT)
  45. #define WINDOW_SIZE (2*FRAME_SIZE)
  46. #define FREQ_SIZE (FRAME_SIZE + 1)
  47. #define PITCH_MIN_PERIOD 60
  48. #define PITCH_MAX_PERIOD 768
  49. #define PITCH_FRAME_SIZE 960
  50. #define PITCH_BUF_SIZE (PITCH_MAX_PERIOD+PITCH_FRAME_SIZE)
  51. #define SQUARE(x) ((x)*(x))
  52. #define NB_BANDS 22
  53. #define CEPS_MEM 8
  54. #define NB_DELTA_CEPS 6
  55. #define NB_FEATURES (NB_BANDS+3*NB_DELTA_CEPS+2)
  56. #define WEIGHTS_SCALE (1.f/256)
  57. #define MAX_NEURONS 128
  58. #define ACTIVATION_TANH 0
  59. #define ACTIVATION_SIGMOID 1
  60. #define ACTIVATION_RELU 2
  61. #define Q15ONE 1.0f
  62. typedef struct DenseLayer {
  63. const float *bias;
  64. const float *input_weights;
  65. int nb_inputs;
  66. int nb_neurons;
  67. int activation;
  68. } DenseLayer;
  69. typedef struct GRULayer {
  70. const float *bias;
  71. const float *input_weights;
  72. const float *recurrent_weights;
  73. int nb_inputs;
  74. int nb_neurons;
  75. int activation;
  76. } GRULayer;
  77. typedef struct RNNModel {
  78. int input_dense_size;
  79. const DenseLayer *input_dense;
  80. int vad_gru_size;
  81. const GRULayer *vad_gru;
  82. int noise_gru_size;
  83. const GRULayer *noise_gru;
  84. int denoise_gru_size;
  85. const GRULayer *denoise_gru;
  86. int denoise_output_size;
  87. const DenseLayer *denoise_output;
  88. int vad_output_size;
  89. const DenseLayer *vad_output;
  90. } RNNModel;
  91. typedef struct RNNState {
  92. float *vad_gru_state;
  93. float *noise_gru_state;
  94. float *denoise_gru_state;
  95. RNNModel *model;
  96. } RNNState;
  97. typedef struct DenoiseState {
  98. float analysis_mem[FRAME_SIZE];
  99. float cepstral_mem[CEPS_MEM][NB_BANDS];
  100. int memid;
  101. DECLARE_ALIGNED(32, float, synthesis_mem)[FRAME_SIZE];
  102. float pitch_buf[PITCH_BUF_SIZE];
  103. float pitch_enh_buf[PITCH_BUF_SIZE];
  104. float last_gain;
  105. int last_period;
  106. float mem_hp_x[2];
  107. float lastg[NB_BANDS];
  108. float history[FRAME_SIZE];
  109. RNNState rnn;
  110. AVTXContext *tx, *txi;
  111. av_tx_fn tx_fn, txi_fn;
  112. } DenoiseState;
  113. typedef struct AudioRNNContext {
  114. const AVClass *class;
  115. char *model_name;
  116. float mix;
  117. int channels;
  118. DenoiseState *st;
  119. DECLARE_ALIGNED(32, float, window)[WINDOW_SIZE];
  120. DECLARE_ALIGNED(32, float, dct_table)[FFALIGN(NB_BANDS, 4)][FFALIGN(NB_BANDS, 4)];
  121. RNNModel *model;
  122. AVFloatDSPContext *fdsp;
  123. } AudioRNNContext;
  124. #define F_ACTIVATION_TANH 0
  125. #define F_ACTIVATION_SIGMOID 1
  126. #define F_ACTIVATION_RELU 2
  127. static void rnnoise_model_free(RNNModel *model)
  128. {
  129. #define FREE_MAYBE(ptr) do { if (ptr) free(ptr); } while (0)
  130. #define FREE_DENSE(name) do { \
  131. if (model->name) { \
  132. av_free((void *) model->name->input_weights); \
  133. av_free((void *) model->name->bias); \
  134. av_free((void *) model->name); \
  135. } \
  136. } while (0)
  137. #define FREE_GRU(name) do { \
  138. if (model->name) { \
  139. av_free((void *) model->name->input_weights); \
  140. av_free((void *) model->name->recurrent_weights); \
  141. av_free((void *) model->name->bias); \
  142. av_free((void *) model->name); \
  143. } \
  144. } while (0)
  145. if (!model)
  146. return;
  147. FREE_DENSE(input_dense);
  148. FREE_GRU(vad_gru);
  149. FREE_GRU(noise_gru);
  150. FREE_GRU(denoise_gru);
  151. FREE_DENSE(denoise_output);
  152. FREE_DENSE(vad_output);
  153. av_free(model);
  154. }
  155. static RNNModel *rnnoise_model_from_file(FILE *f)
  156. {
  157. RNNModel *ret;
  158. DenseLayer *input_dense;
  159. GRULayer *vad_gru;
  160. GRULayer *noise_gru;
  161. GRULayer *denoise_gru;
  162. DenseLayer *denoise_output;
  163. DenseLayer *vad_output;
  164. int in;
  165. if (fscanf(f, "rnnoise-nu model file version %d\n", &in) != 1 || in != 1)
  166. return NULL;
  167. ret = av_calloc(1, sizeof(RNNModel));
  168. if (!ret)
  169. return NULL;
  170. #define ALLOC_LAYER(type, name) \
  171. name = av_calloc(1, sizeof(type)); \
  172. if (!name) { \
  173. rnnoise_model_free(ret); \
  174. return NULL; \
  175. } \
  176. ret->name = name
  177. ALLOC_LAYER(DenseLayer, input_dense);
  178. ALLOC_LAYER(GRULayer, vad_gru);
  179. ALLOC_LAYER(GRULayer, noise_gru);
  180. ALLOC_LAYER(GRULayer, denoise_gru);
  181. ALLOC_LAYER(DenseLayer, denoise_output);
  182. ALLOC_LAYER(DenseLayer, vad_output);
  183. #define INPUT_VAL(name) do { \
  184. if (fscanf(f, "%d", &in) != 1 || in < 0 || in > 128) { \
  185. rnnoise_model_free(ret); \
  186. return NULL; \
  187. } \
  188. name = in; \
  189. } while (0)
  190. #define INPUT_ACTIVATION(name) do { \
  191. int activation; \
  192. INPUT_VAL(activation); \
  193. switch (activation) { \
  194. case F_ACTIVATION_SIGMOID: \
  195. name = ACTIVATION_SIGMOID; \
  196. break; \
  197. case F_ACTIVATION_RELU: \
  198. name = ACTIVATION_RELU; \
  199. break; \
  200. default: \
  201. name = ACTIVATION_TANH; \
  202. } \
  203. } while (0)
  204. #define INPUT_ARRAY(name, len) do { \
  205. float *values = av_calloc((len), sizeof(float)); \
  206. if (!values) { \
  207. rnnoise_model_free(ret); \
  208. return NULL; \
  209. } \
  210. name = values; \
  211. for (int i = 0; i < (len); i++) { \
  212. if (fscanf(f, "%d", &in) != 1) { \
  213. rnnoise_model_free(ret); \
  214. return NULL; \
  215. } \
  216. values[i] = in; \
  217. } \
  218. } while (0)
  219. #define INPUT_ARRAY3(name, len0, len1, len2) do { \
  220. float *values = av_calloc(FFALIGN((len0), 4) * FFALIGN((len1), 4) * (len2), sizeof(float)); \
  221. if (!values) { \
  222. rnnoise_model_free(ret); \
  223. return NULL; \
  224. } \
  225. name = values; \
  226. for (int k = 0; k < (len0); k++) { \
  227. for (int i = 0; i < (len2); i++) { \
  228. for (int j = 0; j < (len1); j++) { \
  229. if (fscanf(f, "%d", &in) != 1) { \
  230. rnnoise_model_free(ret); \
  231. return NULL; \
  232. } \
  233. values[j * (len2) * FFALIGN((len0), 4) + i * FFALIGN((len0), 4) + k] = in; \
  234. } \
  235. } \
  236. } \
  237. } while (0)
  238. #define INPUT_DENSE(name) do { \
  239. INPUT_VAL(name->nb_inputs); \
  240. INPUT_VAL(name->nb_neurons); \
  241. ret->name ## _size = name->nb_neurons; \
  242. INPUT_ACTIVATION(name->activation); \
  243. INPUT_ARRAY(name->input_weights, name->nb_inputs * name->nb_neurons); \
  244. INPUT_ARRAY(name->bias, name->nb_neurons); \
  245. } while (0)
  246. #define INPUT_GRU(name) do { \
  247. INPUT_VAL(name->nb_inputs); \
  248. INPUT_VAL(name->nb_neurons); \
  249. ret->name ## _size = name->nb_neurons; \
  250. INPUT_ACTIVATION(name->activation); \
  251. INPUT_ARRAY3(name->input_weights, name->nb_inputs, name->nb_neurons, 3); \
  252. INPUT_ARRAY3(name->recurrent_weights, name->nb_neurons, name->nb_neurons, 3); \
  253. INPUT_ARRAY(name->bias, name->nb_neurons * 3); \
  254. } while (0)
  255. INPUT_DENSE(input_dense);
  256. INPUT_GRU(vad_gru);
  257. INPUT_GRU(noise_gru);
  258. INPUT_GRU(denoise_gru);
  259. INPUT_DENSE(denoise_output);
  260. INPUT_DENSE(vad_output);
  261. if (vad_output->nb_neurons != 1) {
  262. rnnoise_model_free(ret);
  263. return NULL;
  264. }
  265. return ret;
  266. }
  267. static int query_formats(AVFilterContext *ctx)
  268. {
  269. AVFilterFormats *formats = NULL;
  270. AVFilterChannelLayouts *layouts = NULL;
  271. static const enum AVSampleFormat sample_fmts[] = {
  272. AV_SAMPLE_FMT_FLTP,
  273. AV_SAMPLE_FMT_NONE
  274. };
  275. int ret, sample_rates[] = { 48000, -1 };
  276. formats = ff_make_format_list(sample_fmts);
  277. if (!formats)
  278. return AVERROR(ENOMEM);
  279. ret = ff_set_common_formats(ctx, formats);
  280. if (ret < 0)
  281. return ret;
  282. layouts = ff_all_channel_counts();
  283. if (!layouts)
  284. return AVERROR(ENOMEM);
  285. ret = ff_set_common_channel_layouts(ctx, layouts);
  286. if (ret < 0)
  287. return ret;
  288. formats = ff_make_format_list(sample_rates);
  289. if (!formats)
  290. return AVERROR(ENOMEM);
  291. return ff_set_common_samplerates(ctx, formats);
  292. }
  293. static int config_input(AVFilterLink *inlink)
  294. {
  295. AVFilterContext *ctx = inlink->dst;
  296. AudioRNNContext *s = ctx->priv;
  297. int ret;
  298. s->channels = inlink->channels;
  299. s->st = av_calloc(s->channels, sizeof(DenoiseState));
  300. if (!s->st)
  301. return AVERROR(ENOMEM);
  302. for (int i = 0; i < s->channels; i++) {
  303. DenoiseState *st = &s->st[i];
  304. st->rnn.model = s->model;
  305. st->rnn.vad_gru_state = av_calloc(sizeof(float), FFALIGN(s->model->vad_gru_size, 16));
  306. st->rnn.noise_gru_state = av_calloc(sizeof(float), FFALIGN(s->model->noise_gru_size, 16));
  307. st->rnn.denoise_gru_state = av_calloc(sizeof(float), FFALIGN(s->model->denoise_gru_size, 16));
  308. if (!st->rnn.vad_gru_state ||
  309. !st->rnn.noise_gru_state ||
  310. !st->rnn.denoise_gru_state)
  311. return AVERROR(ENOMEM);
  312. ret = av_tx_init(&st->tx, &st->tx_fn, AV_TX_FLOAT_FFT, 0, WINDOW_SIZE, NULL, 0);
  313. if (ret < 0)
  314. return ret;
  315. ret = av_tx_init(&st->txi, &st->txi_fn, AV_TX_FLOAT_FFT, 1, WINDOW_SIZE, NULL, 0);
  316. if (ret < 0)
  317. return ret;
  318. }
  319. return 0;
  320. }
  321. static void biquad(float *y, float mem[2], const float *x,
  322. const float *b, const float *a, int N)
  323. {
  324. for (int i = 0; i < N; i++) {
  325. float xi, yi;
  326. xi = x[i];
  327. yi = x[i] + mem[0];
  328. mem[0] = mem[1] + (b[0]*xi - a[0]*yi);
  329. mem[1] = (b[1]*xi - a[1]*yi);
  330. y[i] = yi;
  331. }
  332. }
  333. #define RNN_MOVE(dst, src, n) (memmove((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
  334. #define RNN_CLEAR(dst, n) (memset((dst), 0, (n)*sizeof(*(dst))))
  335. #define RNN_COPY(dst, src, n) (memcpy((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
  336. static void forward_transform(DenoiseState *st, AVComplexFloat *out, const float *in)
  337. {
  338. AVComplexFloat x[WINDOW_SIZE];
  339. AVComplexFloat y[WINDOW_SIZE];
  340. for (int i = 0; i < WINDOW_SIZE; i++) {
  341. x[i].re = in[i];
  342. x[i].im = 0;
  343. }
  344. st->tx_fn(st->tx, y, x, sizeof(float));
  345. RNN_COPY(out, y, FREQ_SIZE);
  346. }
  347. static void inverse_transform(DenoiseState *st, float *out, const AVComplexFloat *in)
  348. {
  349. AVComplexFloat x[WINDOW_SIZE];
  350. AVComplexFloat y[WINDOW_SIZE];
  351. RNN_COPY(x, in, FREQ_SIZE);
  352. for (int i = FREQ_SIZE; i < WINDOW_SIZE; i++) {
  353. x[i].re = x[WINDOW_SIZE - i].re;
  354. x[i].im = -x[WINDOW_SIZE - i].im;
  355. }
  356. st->txi_fn(st->txi, y, x, sizeof(float));
  357. for (int i = 0; i < WINDOW_SIZE; i++)
  358. out[i] = y[i].re / WINDOW_SIZE;
  359. }
  360. static const uint8_t eband5ms[] = {
  361. /*0 200 400 600 800 1k 1.2 1.4 1.6 2k 2.4 2.8 3.2 4k 4.8 5.6 6.8 8k 9.6 12k 15.6 20k*/
  362. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100
  363. };
  364. static void compute_band_energy(float *bandE, const AVComplexFloat *X)
  365. {
  366. float sum[NB_BANDS] = {0};
  367. for (int i = 0; i < NB_BANDS - 1; i++) {
  368. int band_size;
  369. band_size = (eband5ms[i + 1] - eband5ms[i]) << FRAME_SIZE_SHIFT;
  370. for (int j = 0; j < band_size; j++) {
  371. float tmp, frac = (float)j / band_size;
  372. tmp = SQUARE(X[(eband5ms[i] << FRAME_SIZE_SHIFT) + j].re);
  373. tmp += SQUARE(X[(eband5ms[i] << FRAME_SIZE_SHIFT) + j].im);
  374. sum[i] += (1.f - frac) * tmp;
  375. sum[i + 1] += frac * tmp;
  376. }
  377. }
  378. sum[0] *= 2;
  379. sum[NB_BANDS - 1] *= 2;
  380. for (int i = 0; i < NB_BANDS; i++)
  381. bandE[i] = sum[i];
  382. }
  383. static void compute_band_corr(float *bandE, const AVComplexFloat *X, const AVComplexFloat *P)
  384. {
  385. float sum[NB_BANDS] = { 0 };
  386. for (int i = 0; i < NB_BANDS - 1; i++) {
  387. int band_size;
  388. band_size = (eband5ms[i + 1] - eband5ms[i]) << FRAME_SIZE_SHIFT;
  389. for (int j = 0; j < band_size; j++) {
  390. float tmp, frac = (float)j / band_size;
  391. tmp = X[(eband5ms[i]<<FRAME_SIZE_SHIFT) + j].re * P[(eband5ms[i]<<FRAME_SIZE_SHIFT) + j].re;
  392. tmp += X[(eband5ms[i]<<FRAME_SIZE_SHIFT) + j].im * P[(eband5ms[i]<<FRAME_SIZE_SHIFT) + j].im;
  393. sum[i] += (1 - frac) * tmp;
  394. sum[i + 1] += frac * tmp;
  395. }
  396. }
  397. sum[0] *= 2;
  398. sum[NB_BANDS-1] *= 2;
  399. for (int i = 0; i < NB_BANDS; i++)
  400. bandE[i] = sum[i];
  401. }
  402. static void frame_analysis(AudioRNNContext *s, DenoiseState *st, AVComplexFloat *X, float *Ex, const float *in)
  403. {
  404. LOCAL_ALIGNED_32(float, x, [WINDOW_SIZE]);
  405. RNN_COPY(x, st->analysis_mem, FRAME_SIZE);
  406. RNN_COPY(x + FRAME_SIZE, in, FRAME_SIZE);
  407. RNN_COPY(st->analysis_mem, in, FRAME_SIZE);
  408. s->fdsp->vector_fmul(x, x, s->window, WINDOW_SIZE);
  409. forward_transform(st, X, x);
  410. compute_band_energy(Ex, X);
  411. }
  412. static void frame_synthesis(AudioRNNContext *s, DenoiseState *st, float *out, const AVComplexFloat *y)
  413. {
  414. LOCAL_ALIGNED_32(float, x, [WINDOW_SIZE]);
  415. const float *src = st->history;
  416. const float mix = s->mix;
  417. const float imix = 1.f - FFMAX(mix, 0.f);
  418. inverse_transform(st, x, y);
  419. s->fdsp->vector_fmul(x, x, s->window, WINDOW_SIZE);
  420. s->fdsp->vector_fmac_scalar(x, st->synthesis_mem, 1.f, FRAME_SIZE);
  421. RNN_COPY(out, x, FRAME_SIZE);
  422. RNN_COPY(st->synthesis_mem, &x[FRAME_SIZE], FRAME_SIZE);
  423. for (int n = 0; n < FRAME_SIZE; n++)
  424. out[n] = out[n] * mix + src[n] * imix;
  425. }
  426. static inline void xcorr_kernel(const float *x, const float *y, float sum[4], int len)
  427. {
  428. float y_0, y_1, y_2, y_3 = 0;
  429. int j;
  430. y_0 = *y++;
  431. y_1 = *y++;
  432. y_2 = *y++;
  433. for (j = 0; j < len - 3; j += 4) {
  434. float tmp;
  435. tmp = *x++;
  436. y_3 = *y++;
  437. sum[0] += tmp * y_0;
  438. sum[1] += tmp * y_1;
  439. sum[2] += tmp * y_2;
  440. sum[3] += tmp * y_3;
  441. tmp = *x++;
  442. y_0 = *y++;
  443. sum[0] += tmp * y_1;
  444. sum[1] += tmp * y_2;
  445. sum[2] += tmp * y_3;
  446. sum[3] += tmp * y_0;
  447. tmp = *x++;
  448. y_1 = *y++;
  449. sum[0] += tmp * y_2;
  450. sum[1] += tmp * y_3;
  451. sum[2] += tmp * y_0;
  452. sum[3] += tmp * y_1;
  453. tmp = *x++;
  454. y_2 = *y++;
  455. sum[0] += tmp * y_3;
  456. sum[1] += tmp * y_0;
  457. sum[2] += tmp * y_1;
  458. sum[3] += tmp * y_2;
  459. }
  460. if (j++ < len) {
  461. float tmp = *x++;
  462. y_3 = *y++;
  463. sum[0] += tmp * y_0;
  464. sum[1] += tmp * y_1;
  465. sum[2] += tmp * y_2;
  466. sum[3] += tmp * y_3;
  467. }
  468. if (j++ < len) {
  469. float tmp=*x++;
  470. y_0 = *y++;
  471. sum[0] += tmp * y_1;
  472. sum[1] += tmp * y_2;
  473. sum[2] += tmp * y_3;
  474. sum[3] += tmp * y_0;
  475. }
  476. if (j < len) {
  477. float tmp=*x++;
  478. y_1 = *y++;
  479. sum[0] += tmp * y_2;
  480. sum[1] += tmp * y_3;
  481. sum[2] += tmp * y_0;
  482. sum[3] += tmp * y_1;
  483. }
  484. }
  485. static inline float celt_inner_prod(const float *x,
  486. const float *y, int N)
  487. {
  488. float xy = 0.f;
  489. for (int i = 0; i < N; i++)
  490. xy += x[i] * y[i];
  491. return xy;
  492. }
  493. static void celt_pitch_xcorr(const float *x, const float *y,
  494. float *xcorr, int len, int max_pitch)
  495. {
  496. int i;
  497. for (i = 0; i < max_pitch - 3; i += 4) {
  498. float sum[4] = { 0, 0, 0, 0};
  499. xcorr_kernel(x, y + i, sum, len);
  500. xcorr[i] = sum[0];
  501. xcorr[i + 1] = sum[1];
  502. xcorr[i + 2] = sum[2];
  503. xcorr[i + 3] = sum[3];
  504. }
  505. /* In case max_pitch isn't a multiple of 4, do non-unrolled version. */
  506. for (; i < max_pitch; i++) {
  507. xcorr[i] = celt_inner_prod(x, y + i, len);
  508. }
  509. }
  510. static int celt_autocorr(const float *x, /* in: [0...n-1] samples x */
  511. float *ac, /* out: [0...lag-1] ac values */
  512. const float *window,
  513. int overlap,
  514. int lag,
  515. int n)
  516. {
  517. int fastN = n - lag;
  518. int shift;
  519. const float *xptr;
  520. float xx[PITCH_BUF_SIZE>>1];
  521. if (overlap == 0) {
  522. xptr = x;
  523. } else {
  524. for (int i = 0; i < n; i++)
  525. xx[i] = x[i];
  526. for (int i = 0; i < overlap; i++) {
  527. xx[i] = x[i] * window[i];
  528. xx[n-i-1] = x[n-i-1] * window[i];
  529. }
  530. xptr = xx;
  531. }
  532. shift = 0;
  533. celt_pitch_xcorr(xptr, xptr, ac, fastN, lag+1);
  534. for (int k = 0; k <= lag; k++) {
  535. float d = 0.f;
  536. for (int i = k + fastN; i < n; i++)
  537. d += xptr[i] * xptr[i-k];
  538. ac[k] += d;
  539. }
  540. return shift;
  541. }
  542. static void celt_lpc(float *lpc, /* out: [0...p-1] LPC coefficients */
  543. const float *ac, /* in: [0...p] autocorrelation values */
  544. int p)
  545. {
  546. float r, error = ac[0];
  547. RNN_CLEAR(lpc, p);
  548. if (ac[0] != 0) {
  549. for (int i = 0; i < p; i++) {
  550. /* Sum up this iteration's reflection coefficient */
  551. float rr = 0;
  552. for (int j = 0; j < i; j++)
  553. rr += (lpc[j] * ac[i - j]);
  554. rr += ac[i + 1];
  555. r = -rr/error;
  556. /* Update LPC coefficients and total error */
  557. lpc[i] = r;
  558. for (int j = 0; j < (i + 1) >> 1; j++) {
  559. float tmp1, tmp2;
  560. tmp1 = lpc[j];
  561. tmp2 = lpc[i-1-j];
  562. lpc[j] = tmp1 + (r*tmp2);
  563. lpc[i-1-j] = tmp2 + (r*tmp1);
  564. }
  565. error = error - (r * r *error);
  566. /* Bail out once we get 30 dB gain */
  567. if (error < .001f * ac[0])
  568. break;
  569. }
  570. }
  571. }
  572. static void celt_fir5(const float *x,
  573. const float *num,
  574. float *y,
  575. int N,
  576. float *mem)
  577. {
  578. float num0, num1, num2, num3, num4;
  579. float mem0, mem1, mem2, mem3, mem4;
  580. num0 = num[0];
  581. num1 = num[1];
  582. num2 = num[2];
  583. num3 = num[3];
  584. num4 = num[4];
  585. mem0 = mem[0];
  586. mem1 = mem[1];
  587. mem2 = mem[2];
  588. mem3 = mem[3];
  589. mem4 = mem[4];
  590. for (int i = 0; i < N; i++) {
  591. float sum = x[i];
  592. sum += (num0*mem0);
  593. sum += (num1*mem1);
  594. sum += (num2*mem2);
  595. sum += (num3*mem3);
  596. sum += (num4*mem4);
  597. mem4 = mem3;
  598. mem3 = mem2;
  599. mem2 = mem1;
  600. mem1 = mem0;
  601. mem0 = x[i];
  602. y[i] = sum;
  603. }
  604. mem[0] = mem0;
  605. mem[1] = mem1;
  606. mem[2] = mem2;
  607. mem[3] = mem3;
  608. mem[4] = mem4;
  609. }
  610. static void pitch_downsample(float *x[], float *x_lp,
  611. int len, int C)
  612. {
  613. float ac[5];
  614. float tmp=Q15ONE;
  615. float lpc[4], mem[5]={0,0,0,0,0};
  616. float lpc2[5];
  617. float c1 = .8f;
  618. for (int i = 1; i < len >> 1; i++)
  619. x_lp[i] = .5f * (.5f * (x[0][(2*i-1)]+x[0][(2*i+1)])+x[0][2*i]);
  620. x_lp[0] = .5f * (.5f * (x[0][1])+x[0][0]);
  621. if (C==2) {
  622. for (int i = 1; i < len >> 1; i++)
  623. x_lp[i] += (.5f * (.5f * (x[1][(2*i-1)]+x[1][(2*i+1)])+x[1][2*i]));
  624. x_lp[0] += .5f * (.5f * (x[1][1])+x[1][0]);
  625. }
  626. celt_autocorr(x_lp, ac, NULL, 0, 4, len>>1);
  627. /* Noise floor -40 dB */
  628. ac[0] *= 1.0001f;
  629. /* Lag windowing */
  630. for (int i = 1; i <= 4; i++) {
  631. /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
  632. ac[i] -= ac[i]*(.008f*i)*(.008f*i);
  633. }
  634. celt_lpc(lpc, ac, 4);
  635. for (int i = 0; i < 4; i++) {
  636. tmp = .9f * tmp;
  637. lpc[i] = (lpc[i] * tmp);
  638. }
  639. /* Add a zero */
  640. lpc2[0] = lpc[0] + .8f;
  641. lpc2[1] = lpc[1] + (c1 * lpc[0]);
  642. lpc2[2] = lpc[2] + (c1 * lpc[1]);
  643. lpc2[3] = lpc[3] + (c1 * lpc[2]);
  644. lpc2[4] = (c1 * lpc[3]);
  645. celt_fir5(x_lp, lpc2, x_lp, len>>1, mem);
  646. }
  647. static inline void dual_inner_prod(const float *x, const float *y01, const float *y02,
  648. int N, float *xy1, float *xy2)
  649. {
  650. float xy01 = 0, xy02 = 0;
  651. for (int i = 0; i < N; i++) {
  652. xy01 += (x[i] * y01[i]);
  653. xy02 += (x[i] * y02[i]);
  654. }
  655. *xy1 = xy01;
  656. *xy2 = xy02;
  657. }
  658. static float compute_pitch_gain(float xy, float xx, float yy)
  659. {
  660. return xy / sqrtf(1.f + xx * yy);
  661. }
  662. static const uint8_t second_check[16] = {0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2};
  663. static float remove_doubling(float *x, int maxperiod, int minperiod, int N,
  664. int *T0_, int prev_period, float prev_gain)
  665. {
  666. int k, i, T, T0;
  667. float g, g0;
  668. float pg;
  669. float xy,xx,yy,xy2;
  670. float xcorr[3];
  671. float best_xy, best_yy;
  672. int offset;
  673. int minperiod0;
  674. float yy_lookup[PITCH_MAX_PERIOD+1];
  675. minperiod0 = minperiod;
  676. maxperiod /= 2;
  677. minperiod /= 2;
  678. *T0_ /= 2;
  679. prev_period /= 2;
  680. N /= 2;
  681. x += maxperiod;
  682. if (*T0_>=maxperiod)
  683. *T0_=maxperiod-1;
  684. T = T0 = *T0_;
  685. dual_inner_prod(x, x, x-T0, N, &xx, &xy);
  686. yy_lookup[0] = xx;
  687. yy=xx;
  688. for (i = 1; i <= maxperiod; i++) {
  689. yy = yy+(x[-i] * x[-i])-(x[N-i] * x[N-i]);
  690. yy_lookup[i] = FFMAX(0, yy);
  691. }
  692. yy = yy_lookup[T0];
  693. best_xy = xy;
  694. best_yy = yy;
  695. g = g0 = compute_pitch_gain(xy, xx, yy);
  696. /* Look for any pitch at T/k */
  697. for (k = 2; k <= 15; k++) {
  698. int T1, T1b;
  699. float g1;
  700. float cont=0;
  701. float thresh;
  702. T1 = (2*T0+k)/(2*k);
  703. if (T1 < minperiod)
  704. break;
  705. /* Look for another strong correlation at T1b */
  706. if (k==2)
  707. {
  708. if (T1+T0>maxperiod)
  709. T1b = T0;
  710. else
  711. T1b = T0+T1;
  712. } else
  713. {
  714. T1b = (2*second_check[k]*T0+k)/(2*k);
  715. }
  716. dual_inner_prod(x, &x[-T1], &x[-T1b], N, &xy, &xy2);
  717. xy = .5f * (xy + xy2);
  718. yy = .5f * (yy_lookup[T1] + yy_lookup[T1b]);
  719. g1 = compute_pitch_gain(xy, xx, yy);
  720. if (FFABS(T1-prev_period)<=1)
  721. cont = prev_gain;
  722. else if (FFABS(T1-prev_period)<=2 && 5 * k * k < T0)
  723. cont = prev_gain * .5f;
  724. else
  725. cont = 0;
  726. thresh = FFMAX(.3f, (.7f * g0) - cont);
  727. /* Bias against very high pitch (very short period) to avoid false-positives
  728. due to short-term correlation */
  729. if (T1<3*minperiod)
  730. thresh = FFMAX(.4f, (.85f * g0) - cont);
  731. else if (T1<2*minperiod)
  732. thresh = FFMAX(.5f, (.9f * g0) - cont);
  733. if (g1 > thresh)
  734. {
  735. best_xy = xy;
  736. best_yy = yy;
  737. T = T1;
  738. g = g1;
  739. }
  740. }
  741. best_xy = FFMAX(0, best_xy);
  742. if (best_yy <= best_xy)
  743. pg = Q15ONE;
  744. else
  745. pg = best_xy/(best_yy + 1);
  746. for (k = 0; k < 3; k++)
  747. xcorr[k] = celt_inner_prod(x, x-(T+k-1), N);
  748. if ((xcorr[2]-xcorr[0]) > .7f * (xcorr[1]-xcorr[0]))
  749. offset = 1;
  750. else if ((xcorr[0]-xcorr[2]) > (.7f * (xcorr[1] - xcorr[2])))
  751. offset = -1;
  752. else
  753. offset = 0;
  754. if (pg > g)
  755. pg = g;
  756. *T0_ = 2*T+offset;
  757. if (*T0_<minperiod0)
  758. *T0_=minperiod0;
  759. return pg;
  760. }
  761. static void find_best_pitch(float *xcorr, float *y, int len,
  762. int max_pitch, int *best_pitch)
  763. {
  764. float best_num[2];
  765. float best_den[2];
  766. float Syy = 1.f;
  767. best_num[0] = -1;
  768. best_num[1] = -1;
  769. best_den[0] = 0;
  770. best_den[1] = 0;
  771. best_pitch[0] = 0;
  772. best_pitch[1] = 1;
  773. for (int j = 0; j < len; j++)
  774. Syy += y[j] * y[j];
  775. for (int i = 0; i < max_pitch; i++) {
  776. if (xcorr[i]>0) {
  777. float num;
  778. float xcorr16;
  779. xcorr16 = xcorr[i];
  780. /* Considering the range of xcorr16, this should avoid both underflows
  781. and overflows (inf) when squaring xcorr16 */
  782. xcorr16 *= 1e-12f;
  783. num = xcorr16 * xcorr16;
  784. if ((num * best_den[1]) > (best_num[1] * Syy)) {
  785. if ((num * best_den[0]) > (best_num[0] * Syy)) {
  786. best_num[1] = best_num[0];
  787. best_den[1] = best_den[0];
  788. best_pitch[1] = best_pitch[0];
  789. best_num[0] = num;
  790. best_den[0] = Syy;
  791. best_pitch[0] = i;
  792. } else {
  793. best_num[1] = num;
  794. best_den[1] = Syy;
  795. best_pitch[1] = i;
  796. }
  797. }
  798. }
  799. Syy += y[i+len]*y[i+len] - y[i] * y[i];
  800. Syy = FFMAX(1, Syy);
  801. }
  802. }
  803. static void pitch_search(const float *x_lp, float *y,
  804. int len, int max_pitch, int *pitch)
  805. {
  806. int lag;
  807. int best_pitch[2]={0,0};
  808. int offset;
  809. float x_lp4[WINDOW_SIZE];
  810. float y_lp4[WINDOW_SIZE];
  811. float xcorr[WINDOW_SIZE];
  812. lag = len+max_pitch;
  813. /* Downsample by 2 again */
  814. for (int j = 0; j < len >> 2; j++)
  815. x_lp4[j] = x_lp[2*j];
  816. for (int j = 0; j < lag >> 2; j++)
  817. y_lp4[j] = y[2*j];
  818. /* Coarse search with 4x decimation */
  819. celt_pitch_xcorr(x_lp4, y_lp4, xcorr, len>>2, max_pitch>>2);
  820. find_best_pitch(xcorr, y_lp4, len>>2, max_pitch>>2, best_pitch);
  821. /* Finer search with 2x decimation */
  822. for (int i = 0; i < max_pitch >> 1; i++) {
  823. float sum;
  824. xcorr[i] = 0;
  825. if (FFABS(i-2*best_pitch[0])>2 && FFABS(i-2*best_pitch[1])>2)
  826. continue;
  827. sum = celt_inner_prod(x_lp, y+i, len>>1);
  828. xcorr[i] = FFMAX(-1, sum);
  829. }
  830. find_best_pitch(xcorr, y, len>>1, max_pitch>>1, best_pitch);
  831. /* Refine by pseudo-interpolation */
  832. if (best_pitch[0] > 0 && best_pitch[0] < (max_pitch >> 1) - 1) {
  833. float a, b, c;
  834. a = xcorr[best_pitch[0] - 1];
  835. b = xcorr[best_pitch[0]];
  836. c = xcorr[best_pitch[0] + 1];
  837. if (c - a > .7f * (b - a))
  838. offset = 1;
  839. else if (a - c > .7f * (b-c))
  840. offset = -1;
  841. else
  842. offset = 0;
  843. } else {
  844. offset = 0;
  845. }
  846. *pitch = 2 * best_pitch[0] - offset;
  847. }
  848. static void dct(AudioRNNContext *s, float *out, const float *in)
  849. {
  850. for (int i = 0; i < NB_BANDS; i++) {
  851. float sum;
  852. sum = s->fdsp->scalarproduct_float(in, s->dct_table[i], FFALIGN(NB_BANDS, 4));
  853. out[i] = sum * sqrtf(2.f / 22);
  854. }
  855. }
  856. static int compute_frame_features(AudioRNNContext *s, DenoiseState *st, AVComplexFloat *X, AVComplexFloat *P,
  857. float *Ex, float *Ep, float *Exp, float *features, const float *in)
  858. {
  859. float E = 0;
  860. float *ceps_0, *ceps_1, *ceps_2;
  861. float spec_variability = 0;
  862. LOCAL_ALIGNED_32(float, Ly, [NB_BANDS]);
  863. LOCAL_ALIGNED_32(float, p, [WINDOW_SIZE]);
  864. float pitch_buf[PITCH_BUF_SIZE>>1];
  865. int pitch_index;
  866. float gain;
  867. float *(pre[1]);
  868. float tmp[NB_BANDS];
  869. float follow, logMax;
  870. frame_analysis(s, st, X, Ex, in);
  871. RNN_MOVE(st->pitch_buf, &st->pitch_buf[FRAME_SIZE], PITCH_BUF_SIZE-FRAME_SIZE);
  872. RNN_COPY(&st->pitch_buf[PITCH_BUF_SIZE-FRAME_SIZE], in, FRAME_SIZE);
  873. pre[0] = &st->pitch_buf[0];
  874. pitch_downsample(pre, pitch_buf, PITCH_BUF_SIZE, 1);
  875. pitch_search(pitch_buf+(PITCH_MAX_PERIOD>>1), pitch_buf, PITCH_FRAME_SIZE,
  876. PITCH_MAX_PERIOD-3*PITCH_MIN_PERIOD, &pitch_index);
  877. pitch_index = PITCH_MAX_PERIOD-pitch_index;
  878. gain = remove_doubling(pitch_buf, PITCH_MAX_PERIOD, PITCH_MIN_PERIOD,
  879. PITCH_FRAME_SIZE, &pitch_index, st->last_period, st->last_gain);
  880. st->last_period = pitch_index;
  881. st->last_gain = gain;
  882. for (int i = 0; i < WINDOW_SIZE; i++)
  883. p[i] = st->pitch_buf[PITCH_BUF_SIZE-WINDOW_SIZE-pitch_index+i];
  884. s->fdsp->vector_fmul(p, p, s->window, WINDOW_SIZE);
  885. forward_transform(st, P, p);
  886. compute_band_energy(Ep, P);
  887. compute_band_corr(Exp, X, P);
  888. for (int i = 0; i < NB_BANDS; i++)
  889. Exp[i] = Exp[i] / sqrtf(.001f+Ex[i]*Ep[i]);
  890. dct(s, tmp, Exp);
  891. for (int i = 0; i < NB_DELTA_CEPS; i++)
  892. features[NB_BANDS+2*NB_DELTA_CEPS+i] = tmp[i];
  893. features[NB_BANDS+2*NB_DELTA_CEPS] -= 1.3;
  894. features[NB_BANDS+2*NB_DELTA_CEPS+1] -= 0.9;
  895. features[NB_BANDS+3*NB_DELTA_CEPS] = .01*(pitch_index-300);
  896. logMax = -2;
  897. follow = -2;
  898. for (int i = 0; i < NB_BANDS; i++) {
  899. Ly[i] = log10f(1e-2f + Ex[i]);
  900. Ly[i] = FFMAX(logMax-7, FFMAX(follow-1.5, Ly[i]));
  901. logMax = FFMAX(logMax, Ly[i]);
  902. follow = FFMAX(follow-1.5, Ly[i]);
  903. E += Ex[i];
  904. }
  905. if (E < 0.04f) {
  906. /* If there's no audio, avoid messing up the state. */
  907. RNN_CLEAR(features, NB_FEATURES);
  908. return 1;
  909. }
  910. dct(s, features, Ly);
  911. features[0] -= 12;
  912. features[1] -= 4;
  913. ceps_0 = st->cepstral_mem[st->memid];
  914. ceps_1 = (st->memid < 1) ? st->cepstral_mem[CEPS_MEM+st->memid-1] : st->cepstral_mem[st->memid-1];
  915. ceps_2 = (st->memid < 2) ? st->cepstral_mem[CEPS_MEM+st->memid-2] : st->cepstral_mem[st->memid-2];
  916. for (int i = 0; i < NB_BANDS; i++)
  917. ceps_0[i] = features[i];
  918. st->memid++;
  919. for (int i = 0; i < NB_DELTA_CEPS; i++) {
  920. features[i] = ceps_0[i] + ceps_1[i] + ceps_2[i];
  921. features[NB_BANDS+i] = ceps_0[i] - ceps_2[i];
  922. features[NB_BANDS+NB_DELTA_CEPS+i] = ceps_0[i] - 2*ceps_1[i] + ceps_2[i];
  923. }
  924. /* Spectral variability features. */
  925. if (st->memid == CEPS_MEM)
  926. st->memid = 0;
  927. for (int i = 0; i < CEPS_MEM; i++) {
  928. float mindist = 1e15f;
  929. for (int j = 0; j < CEPS_MEM; j++) {
  930. float dist = 0.f;
  931. for (int k = 0; k < NB_BANDS; k++) {
  932. float tmp;
  933. tmp = st->cepstral_mem[i][k] - st->cepstral_mem[j][k];
  934. dist += tmp*tmp;
  935. }
  936. if (j != i)
  937. mindist = FFMIN(mindist, dist);
  938. }
  939. spec_variability += mindist;
  940. }
  941. features[NB_BANDS+3*NB_DELTA_CEPS+1] = spec_variability/CEPS_MEM-2.1;
  942. return 0;
  943. }
  944. static void interp_band_gain(float *g, const float *bandE)
  945. {
  946. memset(g, 0, sizeof(*g) * FREQ_SIZE);
  947. for (int i = 0; i < NB_BANDS - 1; i++) {
  948. const int band_size = (eband5ms[i + 1] - eband5ms[i]) << FRAME_SIZE_SHIFT;
  949. for (int j = 0; j < band_size; j++) {
  950. float frac = (float)j / band_size;
  951. g[(eband5ms[i] << FRAME_SIZE_SHIFT) + j] = (1.f - frac) * bandE[i] + frac * bandE[i + 1];
  952. }
  953. }
  954. }
  955. static void pitch_filter(AVComplexFloat *X, const AVComplexFloat *P, const float *Ex, const float *Ep,
  956. const float *Exp, const float *g)
  957. {
  958. float newE[NB_BANDS];
  959. float r[NB_BANDS];
  960. float norm[NB_BANDS];
  961. float rf[FREQ_SIZE] = {0};
  962. float normf[FREQ_SIZE]={0};
  963. for (int i = 0; i < NB_BANDS; i++) {
  964. if (Exp[i]>g[i]) r[i] = 1;
  965. else r[i] = SQUARE(Exp[i])*(1-SQUARE(g[i]))/(.001 + SQUARE(g[i])*(1-SQUARE(Exp[i])));
  966. r[i] = sqrtf(av_clipf(r[i], 0, 1));
  967. r[i] *= sqrtf(Ex[i]/(1e-8+Ep[i]));
  968. }
  969. interp_band_gain(rf, r);
  970. for (int i = 0; i < FREQ_SIZE; i++) {
  971. X[i].re += rf[i]*P[i].re;
  972. X[i].im += rf[i]*P[i].im;
  973. }
  974. compute_band_energy(newE, X);
  975. for (int i = 0; i < NB_BANDS; i++) {
  976. norm[i] = sqrtf(Ex[i] / (1e-8+newE[i]));
  977. }
  978. interp_band_gain(normf, norm);
  979. for (int i = 0; i < FREQ_SIZE; i++) {
  980. X[i].re *= normf[i];
  981. X[i].im *= normf[i];
  982. }
  983. }
  984. static const float tansig_table[201] = {
  985. 0.000000f, 0.039979f, 0.079830f, 0.119427f, 0.158649f,
  986. 0.197375f, 0.235496f, 0.272905f, 0.309507f, 0.345214f,
  987. 0.379949f, 0.413644f, 0.446244f, 0.477700f, 0.507977f,
  988. 0.537050f, 0.564900f, 0.591519f, 0.616909f, 0.641077f,
  989. 0.664037f, 0.685809f, 0.706419f, 0.725897f, 0.744277f,
  990. 0.761594f, 0.777888f, 0.793199f, 0.807569f, 0.821040f,
  991. 0.833655f, 0.845456f, 0.856485f, 0.866784f, 0.876393f,
  992. 0.885352f, 0.893698f, 0.901468f, 0.908698f, 0.915420f,
  993. 0.921669f, 0.927473f, 0.932862f, 0.937863f, 0.942503f,
  994. 0.946806f, 0.950795f, 0.954492f, 0.957917f, 0.961090f,
  995. 0.964028f, 0.966747f, 0.969265f, 0.971594f, 0.973749f,
  996. 0.975743f, 0.977587f, 0.979293f, 0.980869f, 0.982327f,
  997. 0.983675f, 0.984921f, 0.986072f, 0.987136f, 0.988119f,
  998. 0.989027f, 0.989867f, 0.990642f, 0.991359f, 0.992020f,
  999. 0.992631f, 0.993196f, 0.993718f, 0.994199f, 0.994644f,
  1000. 0.995055f, 0.995434f, 0.995784f, 0.996108f, 0.996407f,
  1001. 0.996682f, 0.996937f, 0.997172f, 0.997389f, 0.997590f,
  1002. 0.997775f, 0.997946f, 0.998104f, 0.998249f, 0.998384f,
  1003. 0.998508f, 0.998623f, 0.998728f, 0.998826f, 0.998916f,
  1004. 0.999000f, 0.999076f, 0.999147f, 0.999213f, 0.999273f,
  1005. 0.999329f, 0.999381f, 0.999428f, 0.999472f, 0.999513f,
  1006. 0.999550f, 0.999585f, 0.999617f, 0.999646f, 0.999673f,
  1007. 0.999699f, 0.999722f, 0.999743f, 0.999763f, 0.999781f,
  1008. 0.999798f, 0.999813f, 0.999828f, 0.999841f, 0.999853f,
  1009. 0.999865f, 0.999875f, 0.999885f, 0.999893f, 0.999902f,
  1010. 0.999909f, 0.999916f, 0.999923f, 0.999929f, 0.999934f,
  1011. 0.999939f, 0.999944f, 0.999948f, 0.999952f, 0.999956f,
  1012. 0.999959f, 0.999962f, 0.999965f, 0.999968f, 0.999970f,
  1013. 0.999973f, 0.999975f, 0.999977f, 0.999978f, 0.999980f,
  1014. 0.999982f, 0.999983f, 0.999984f, 0.999986f, 0.999987f,
  1015. 0.999988f, 0.999989f, 0.999990f, 0.999990f, 0.999991f,
  1016. 0.999992f, 0.999992f, 0.999993f, 0.999994f, 0.999994f,
  1017. 0.999994f, 0.999995f, 0.999995f, 0.999996f, 0.999996f,
  1018. 0.999996f, 0.999997f, 0.999997f, 0.999997f, 0.999997f,
  1019. 0.999997f, 0.999998f, 0.999998f, 0.999998f, 0.999998f,
  1020. 0.999998f, 0.999998f, 0.999999f, 0.999999f, 0.999999f,
  1021. 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f,
  1022. 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f,
  1023. 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f,
  1024. 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f,
  1025. 1.000000f,
  1026. };
  1027. static inline float tansig_approx(float x)
  1028. {
  1029. float y, dy;
  1030. float sign=1;
  1031. int i;
  1032. /* Tests are reversed to catch NaNs */
  1033. if (!(x<8))
  1034. return 1;
  1035. if (!(x>-8))
  1036. return -1;
  1037. /* Another check in case of -ffast-math */
  1038. if (isnan(x))
  1039. return 0;
  1040. if (x < 0) {
  1041. x=-x;
  1042. sign=-1;
  1043. }
  1044. i = (int)floor(.5f+25*x);
  1045. x -= .04f*i;
  1046. y = tansig_table[i];
  1047. dy = 1-y*y;
  1048. y = y + x*dy*(1 - y*x);
  1049. return sign*y;
  1050. }
  1051. static inline float sigmoid_approx(float x)
  1052. {
  1053. return .5f + .5f*tansig_approx(.5f*x);
  1054. }
  1055. static void compute_dense(const DenseLayer *layer, float *output, const float *input)
  1056. {
  1057. const int N = layer->nb_neurons, M = layer->nb_inputs, stride = N;
  1058. for (int i = 0; i < N; i++) {
  1059. /* Compute update gate. */
  1060. float sum = layer->bias[i];
  1061. for (int j = 0; j < M; j++)
  1062. sum += layer->input_weights[j * stride + i] * input[j];
  1063. output[i] = WEIGHTS_SCALE * sum;
  1064. }
  1065. if (layer->activation == ACTIVATION_SIGMOID) {
  1066. for (int i = 0; i < N; i++)
  1067. output[i] = sigmoid_approx(output[i]);
  1068. } else if (layer->activation == ACTIVATION_TANH) {
  1069. for (int i = 0; i < N; i++)
  1070. output[i] = tansig_approx(output[i]);
  1071. } else if (layer->activation == ACTIVATION_RELU) {
  1072. for (int i = 0; i < N; i++)
  1073. output[i] = FFMAX(0, output[i]);
  1074. } else {
  1075. av_assert0(0);
  1076. }
  1077. }
  1078. static void compute_gru(AudioRNNContext *s, const GRULayer *gru, float *state, const float *input)
  1079. {
  1080. LOCAL_ALIGNED_32(float, z, [MAX_NEURONS]);
  1081. LOCAL_ALIGNED_32(float, r, [MAX_NEURONS]);
  1082. LOCAL_ALIGNED_32(float, h, [MAX_NEURONS]);
  1083. const int M = gru->nb_inputs;
  1084. const int N = gru->nb_neurons;
  1085. const int AN = FFALIGN(N, 4);
  1086. const int AM = FFALIGN(M, 4);
  1087. const int stride = 3 * AN, istride = 3 * AM;
  1088. for (int i = 0; i < N; i++) {
  1089. /* Compute update gate. */
  1090. float sum = gru->bias[i];
  1091. sum += s->fdsp->scalarproduct_float(gru->input_weights + i * istride, input, AM);
  1092. sum += s->fdsp->scalarproduct_float(gru->recurrent_weights + i * stride, state, AN);
  1093. z[i] = sigmoid_approx(WEIGHTS_SCALE * sum);
  1094. }
  1095. for (int i = 0; i < N; i++) {
  1096. /* Compute reset gate. */
  1097. float sum = gru->bias[N + i];
  1098. sum += s->fdsp->scalarproduct_float(gru->input_weights + AM + i * istride, input, AM);
  1099. sum += s->fdsp->scalarproduct_float(gru->recurrent_weights + AN + i * stride, state, AN);
  1100. r[i] = sigmoid_approx(WEIGHTS_SCALE * sum);
  1101. }
  1102. for (int i = 0; i < N; i++) {
  1103. /* Compute output. */
  1104. float sum = gru->bias[2 * N + i];
  1105. sum += s->fdsp->scalarproduct_float(gru->input_weights + 2 * AM + i * istride, input, AM);
  1106. for (int j = 0; j < N; j++)
  1107. sum += gru->recurrent_weights[2 * AN + i * stride + j] * state[j] * r[j];
  1108. if (gru->activation == ACTIVATION_SIGMOID)
  1109. sum = sigmoid_approx(WEIGHTS_SCALE * sum);
  1110. else if (gru->activation == ACTIVATION_TANH)
  1111. sum = tansig_approx(WEIGHTS_SCALE * sum);
  1112. else if (gru->activation == ACTIVATION_RELU)
  1113. sum = FFMAX(0, WEIGHTS_SCALE * sum);
  1114. else
  1115. av_assert0(0);
  1116. h[i] = z[i] * state[i] + (1.f - z[i]) * sum;
  1117. }
  1118. RNN_COPY(state, h, N);
  1119. }
  1120. #define INPUT_SIZE 42
  1121. static void compute_rnn(AudioRNNContext *s, RNNState *rnn, float *gains, float *vad, const float *input)
  1122. {
  1123. LOCAL_ALIGNED_32(float, dense_out, [MAX_NEURONS]);
  1124. LOCAL_ALIGNED_32(float, noise_input, [MAX_NEURONS * 3]);
  1125. LOCAL_ALIGNED_32(float, denoise_input, [MAX_NEURONS * 3]);
  1126. compute_dense(rnn->model->input_dense, dense_out, input);
  1127. compute_gru(s, rnn->model->vad_gru, rnn->vad_gru_state, dense_out);
  1128. compute_dense(rnn->model->vad_output, vad, rnn->vad_gru_state);
  1129. memcpy(noise_input, dense_out, rnn->model->input_dense_size * sizeof(float));
  1130. memcpy(noise_input + rnn->model->input_dense_size,
  1131. rnn->vad_gru_state, rnn->model->vad_gru_size * sizeof(float));
  1132. memcpy(noise_input + rnn->model->input_dense_size + rnn->model->vad_gru_size,
  1133. input, INPUT_SIZE * sizeof(float));
  1134. compute_gru(s, rnn->model->noise_gru, rnn->noise_gru_state, noise_input);
  1135. memcpy(denoise_input, rnn->vad_gru_state, rnn->model->vad_gru_size * sizeof(float));
  1136. memcpy(denoise_input + rnn->model->vad_gru_size,
  1137. rnn->noise_gru_state, rnn->model->noise_gru_size * sizeof(float));
  1138. memcpy(denoise_input + rnn->model->vad_gru_size + rnn->model->noise_gru_size,
  1139. input, INPUT_SIZE * sizeof(float));
  1140. compute_gru(s, rnn->model->denoise_gru, rnn->denoise_gru_state, denoise_input);
  1141. compute_dense(rnn->model->denoise_output, gains, rnn->denoise_gru_state);
  1142. }
  1143. static float rnnoise_channel(AudioRNNContext *s, DenoiseState *st, float *out, const float *in,
  1144. int disabled)
  1145. {
  1146. AVComplexFloat X[FREQ_SIZE];
  1147. AVComplexFloat P[WINDOW_SIZE];
  1148. float x[FRAME_SIZE];
  1149. float Ex[NB_BANDS], Ep[NB_BANDS];
  1150. LOCAL_ALIGNED_32(float, Exp, [NB_BANDS]);
  1151. float features[NB_FEATURES];
  1152. float g[NB_BANDS];
  1153. float gf[FREQ_SIZE];
  1154. float vad_prob = 0;
  1155. float *history = st->history;
  1156. static const float a_hp[2] = {-1.99599, 0.99600};
  1157. static const float b_hp[2] = {-2, 1};
  1158. int silence;
  1159. biquad(x, st->mem_hp_x, in, b_hp, a_hp, FRAME_SIZE);
  1160. silence = compute_frame_features(s, st, X, P, Ex, Ep, Exp, features, x);
  1161. if (!silence && !disabled) {
  1162. compute_rnn(s, &st->rnn, g, &vad_prob, features);
  1163. pitch_filter(X, P, Ex, Ep, Exp, g);
  1164. for (int i = 0; i < NB_BANDS; i++) {
  1165. float alpha = .6f;
  1166. g[i] = FFMAX(g[i], alpha * st->lastg[i]);
  1167. st->lastg[i] = g[i];
  1168. }
  1169. interp_band_gain(gf, g);
  1170. for (int i = 0; i < FREQ_SIZE; i++) {
  1171. X[i].re *= gf[i];
  1172. X[i].im *= gf[i];
  1173. }
  1174. }
  1175. frame_synthesis(s, st, out, X);
  1176. memcpy(history, in, FRAME_SIZE * sizeof(*history));
  1177. return vad_prob;
  1178. }
  1179. typedef struct ThreadData {
  1180. AVFrame *in, *out;
  1181. } ThreadData;
  1182. static int rnnoise_channels(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  1183. {
  1184. AudioRNNContext *s = ctx->priv;
  1185. ThreadData *td = arg;
  1186. AVFrame *in = td->in;
  1187. AVFrame *out = td->out;
  1188. const int start = (out->channels * jobnr) / nb_jobs;
  1189. const int end = (out->channels * (jobnr+1)) / nb_jobs;
  1190. for (int ch = start; ch < end; ch++) {
  1191. rnnoise_channel(s, &s->st[ch],
  1192. (float *)out->extended_data[ch],
  1193. (const float *)in->extended_data[ch],
  1194. ctx->is_disabled);
  1195. }
  1196. return 0;
  1197. }
  1198. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  1199. {
  1200. AVFilterContext *ctx = inlink->dst;
  1201. AVFilterLink *outlink = ctx->outputs[0];
  1202. AVFrame *out = NULL;
  1203. ThreadData td;
  1204. out = ff_get_audio_buffer(outlink, FRAME_SIZE);
  1205. if (!out) {
  1206. av_frame_free(&in);
  1207. return AVERROR(ENOMEM);
  1208. }
  1209. out->pts = in->pts;
  1210. td.in = in; td.out = out;
  1211. ctx->internal->execute(ctx, rnnoise_channels, &td, NULL, FFMIN(outlink->channels,
  1212. ff_filter_get_nb_threads(ctx)));
  1213. av_frame_free(&in);
  1214. return ff_filter_frame(outlink, out);
  1215. }
  1216. static int activate(AVFilterContext *ctx)
  1217. {
  1218. AVFilterLink *inlink = ctx->inputs[0];
  1219. AVFilterLink *outlink = ctx->outputs[0];
  1220. AVFrame *in = NULL;
  1221. int ret;
  1222. FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
  1223. ret = ff_inlink_consume_samples(inlink, FRAME_SIZE, FRAME_SIZE, &in);
  1224. if (ret < 0)
  1225. return ret;
  1226. if (ret > 0)
  1227. return filter_frame(inlink, in);
  1228. FF_FILTER_FORWARD_STATUS(inlink, outlink);
  1229. FF_FILTER_FORWARD_WANTED(outlink, inlink);
  1230. return FFERROR_NOT_READY;
  1231. }
  1232. static av_cold int init(AVFilterContext *ctx)
  1233. {
  1234. AudioRNNContext *s = ctx->priv;
  1235. FILE *f;
  1236. s->fdsp = avpriv_float_dsp_alloc(0);
  1237. if (!s->fdsp)
  1238. return AVERROR(ENOMEM);
  1239. if (!s->model_name)
  1240. return AVERROR(EINVAL);
  1241. f = av_fopen_utf8(s->model_name, "r");
  1242. if (!f)
  1243. return AVERROR(EINVAL);
  1244. s->model = rnnoise_model_from_file(f);
  1245. fclose(f);
  1246. if (!s->model)
  1247. return AVERROR(EINVAL);
  1248. for (int i = 0; i < FRAME_SIZE; i++) {
  1249. s->window[i] = sin(.5*M_PI*sin(.5*M_PI*(i+.5)/FRAME_SIZE) * sin(.5*M_PI*(i+.5)/FRAME_SIZE));
  1250. s->window[WINDOW_SIZE - 1 - i] = s->window[i];
  1251. }
  1252. for (int i = 0; i < NB_BANDS; i++) {
  1253. for (int j = 0; j < NB_BANDS; j++) {
  1254. s->dct_table[j][i] = cosf((i + .5f) * j * M_PI / NB_BANDS);
  1255. if (j == 0)
  1256. s->dct_table[j][i] *= sqrtf(.5);
  1257. }
  1258. }
  1259. return 0;
  1260. }
  1261. static av_cold void uninit(AVFilterContext *ctx)
  1262. {
  1263. AudioRNNContext *s = ctx->priv;
  1264. av_freep(&s->fdsp);
  1265. rnnoise_model_free(s->model);
  1266. s->model = NULL;
  1267. if (s->st) {
  1268. for (int ch = 0; ch < s->channels; ch++) {
  1269. av_freep(&s->st[ch].rnn.vad_gru_state);
  1270. av_freep(&s->st[ch].rnn.noise_gru_state);
  1271. av_freep(&s->st[ch].rnn.denoise_gru_state);
  1272. av_tx_uninit(&s->st[ch].tx);
  1273. av_tx_uninit(&s->st[ch].txi);
  1274. }
  1275. }
  1276. av_freep(&s->st);
  1277. }
  1278. static const AVFilterPad inputs[] = {
  1279. {
  1280. .name = "default",
  1281. .type = AVMEDIA_TYPE_AUDIO,
  1282. .config_props = config_input,
  1283. },
  1284. { NULL }
  1285. };
  1286. static const AVFilterPad outputs[] = {
  1287. {
  1288. .name = "default",
  1289. .type = AVMEDIA_TYPE_AUDIO,
  1290. },
  1291. { NULL }
  1292. };
  1293. #define OFFSET(x) offsetof(AudioRNNContext, x)
  1294. #define AF AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  1295. static const AVOption arnndn_options[] = {
  1296. { "model", "set model name", OFFSET(model_name), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, AF },
  1297. { "m", "set model name", OFFSET(model_name), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, AF },
  1298. { "mix", "set output vs input mix", OFFSET(mix), AV_OPT_TYPE_FLOAT, {.dbl=1.0},-1, 1, AF },
  1299. { NULL }
  1300. };
  1301. AVFILTER_DEFINE_CLASS(arnndn);
  1302. AVFilter ff_af_arnndn = {
  1303. .name = "arnndn",
  1304. .description = NULL_IF_CONFIG_SMALL("Reduce noise from speech using Recurrent Neural Networks."),
  1305. .query_formats = query_formats,
  1306. .priv_size = sizeof(AudioRNNContext),
  1307. .priv_class = &arnndn_class,
  1308. .activate = activate,
  1309. .init = init,
  1310. .uninit = uninit,
  1311. .inputs = inputs,
  1312. .outputs = outputs,
  1313. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL |
  1314. AVFILTER_FLAG_SLICE_THREADS,
  1315. };