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.

1550 lines
44KB

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