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.

1286 lines
43KB

  1. /* Copyright (C) 2003-2008 Jean-Marc Valin
  2. File: mdf.c
  3. Echo canceller based on the MDF algorithm (see below)
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. 1. Redistributions of source code must retain the above copyright notice,
  8. this list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. 3. The name of the author may not be used to endorse or promote products
  13. derived from this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  15. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  16. OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
  18. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  21. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  22. STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  23. ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. /*
  27. The echo canceller is based on the MDF algorithm described in:
  28. J. S. Soo, K. K. Pang Multidelay block frequency adaptive filter,
  29. IEEE Trans. Acoust. Speech Signal Process., Vol. ASSP-38, No. 2,
  30. February 1990.
  31. We use the Alternatively Updated MDF (AUMDF) variant. Robustness to
  32. double-talk is achieved using a variable learning rate as described in:
  33. Valin, J.-M., On Adjusting the Learning Rate in Frequency Domain Echo
  34. Cancellation With Double-Talk. IEEE Transactions on Audio,
  35. Speech and Language Processing, Vol. 15, No. 3, pp. 1030-1034, 2007.
  36. http://people.xiph.org/~jm/papers/valin_taslp2006.pdf
  37. There is no explicit double-talk detection, but a continuous variation
  38. in the learning rate based on residual echo, double-talk and background
  39. noise.
  40. About the fixed-point version:
  41. All the signals are represented with 16-bit words. The filter weights
  42. are represented with 32-bit words, but only the top 16 bits are used
  43. in most cases. The lower 16 bits are completely unreliable (due to the
  44. fact that the update is done only on the top bits), but help in the
  45. adaptation -- probably by removing a "threshold effect" due to
  46. quantization (rounding going to zero) when the gradient is small.
  47. Another kludge that seems to work good: when performing the weight
  48. update, we only move half the way toward the "goal" this seems to
  49. reduce the effect of quantization noise in the update phase. This
  50. can be seen as applying a gradient descent on a "soft constraint"
  51. instead of having a hard constraint.
  52. */
  53. #ifdef HAVE_CONFIG_H
  54. #include "config.h"
  55. #endif
  56. #include "arch.h"
  57. #include "speex/speex_echo.h"
  58. #include "fftwrap.h"
  59. #include "pseudofloat.h"
  60. #include "math_approx.h"
  61. #include "os_support.h"
  62. #ifndef M_PI
  63. #define M_PI 3.14159265358979323846
  64. #endif
  65. #ifdef FIXED_POINT
  66. #define WEIGHT_SHIFT 11
  67. #define NORMALIZE_SCALEDOWN 5
  68. #define NORMALIZE_SCALEUP 3
  69. #else
  70. #define WEIGHT_SHIFT 0
  71. #endif
  72. #ifdef FIXED_POINT
  73. #define WORD2INT(x) ((x) < -32767 ? -32768 : ((x) > 32766 ? 32767 : (x)))
  74. #else
  75. #define WORD2INT(x) ((x) < -32767.5f ? -32768 : ((x) > 32766.5f ? 32767 : floor(.5+(x))))
  76. #endif
  77. /* If enabled, the AEC will use a foreground filter and a background filter to be more robust to double-talk
  78. and difficult signals in general. The cost is an extra FFT and a matrix-vector multiply */
  79. #define TWO_PATH
  80. #ifdef FIXED_POINT
  81. static const spx_float_t MIN_LEAK = {20972, -22};
  82. /* Constants for the two-path filter */
  83. static const spx_float_t VAR1_SMOOTH = {23593, -16};
  84. static const spx_float_t VAR2_SMOOTH = {23675, -15};
  85. static const spx_float_t VAR1_UPDATE = {16384, -15};
  86. static const spx_float_t VAR2_UPDATE = {16384, -16};
  87. static const spx_float_t VAR_BACKTRACK = {16384, -12};
  88. #define TOP16(x) ((x)>>16)
  89. #else
  90. static const spx_float_t MIN_LEAK = .005f;
  91. /* Constants for the two-path filter */
  92. static const spx_float_t VAR1_SMOOTH = .36f;
  93. static const spx_float_t VAR2_SMOOTH = .7225f;
  94. static const spx_float_t VAR1_UPDATE = .5f;
  95. static const spx_float_t VAR2_UPDATE = .25f;
  96. static const spx_float_t VAR_BACKTRACK = 4.f;
  97. #define TOP16(x) (x)
  98. #endif
  99. #define PLAYBACK_DELAY 2
  100. void speex_echo_get_residual(SpeexEchoState *st, spx_word32_t *Yout, int len);
  101. /** Speex echo cancellation state. */
  102. struct SpeexEchoState_ {
  103. int frame_size; /**< Number of samples processed each time */
  104. int window_size;
  105. int M;
  106. int cancel_count;
  107. int adapted;
  108. int saturated;
  109. int screwed_up;
  110. int C; /** Number of input channels (microphones) */
  111. int K; /** Number of output channels (loudspeakers) */
  112. spx_int32_t sampling_rate;
  113. spx_word16_t spec_average;
  114. spx_word16_t beta0;
  115. spx_word16_t beta_max;
  116. spx_word32_t sum_adapt;
  117. spx_word16_t leak_estimate;
  118. spx_word16_t *e; /* scratch */
  119. spx_word16_t *x; /* Far-end input buffer (2N) */
  120. spx_word16_t *X; /* Far-end buffer (M+1 frames) in frequency domain */
  121. spx_word16_t *input; /* scratch */
  122. spx_word16_t *y; /* scratch */
  123. spx_word16_t *last_y;
  124. spx_word16_t *Y; /* scratch */
  125. spx_word16_t *E;
  126. spx_word32_t *PHI; /* scratch */
  127. spx_word32_t *W; /* (Background) filter weights */
  128. #ifdef TWO_PATH
  129. spx_word16_t *foreground; /* Foreground filter weights */
  130. spx_word32_t Davg1; /* 1st recursive average of the residual power difference */
  131. spx_word32_t Davg2; /* 2nd recursive average of the residual power difference */
  132. spx_float_t Dvar1; /* Estimated variance of 1st estimator */
  133. spx_float_t Dvar2; /* Estimated variance of 2nd estimator */
  134. #endif
  135. spx_word32_t *power; /* Power of the far-end signal */
  136. spx_float_t *power_1;/* Inverse power of far-end */
  137. spx_word16_t *wtmp; /* scratch */
  138. #ifdef FIXED_POINT
  139. spx_word16_t *wtmp2; /* scratch */
  140. #endif
  141. spx_word32_t *Rf; /* scratch */
  142. spx_word32_t *Yf; /* scratch */
  143. spx_word32_t *Xf; /* scratch */
  144. spx_word32_t *Eh;
  145. spx_word32_t *Yh;
  146. spx_float_t Pey;
  147. spx_float_t Pyy;
  148. spx_word16_t *window;
  149. spx_word16_t *prop;
  150. void *fft_table;
  151. spx_word16_t *memX, *memD, *memE;
  152. spx_word16_t preemph;
  153. spx_word16_t notch_radius;
  154. spx_mem_t *notch_mem;
  155. /* NOTE: If you only use speex_echo_cancel() and want to save some memory, remove this */
  156. spx_int16_t *play_buf;
  157. int play_buf_pos;
  158. int play_buf_started;
  159. };
  160. static inline void filter_dc_notch16(const spx_int16_t *in, spx_word16_t radius, spx_word16_t *out, int len, spx_mem_t *mem, int stride)
  161. {
  162. int i;
  163. spx_word16_t den2;
  164. #ifdef FIXED_POINT
  165. den2 = MULT16_16_Q15(radius,radius) + MULT16_16_Q15(QCONST16(.7,15),MULT16_16_Q15(32767-radius,32767-radius));
  166. #else
  167. den2 = radius*radius + .7*(1-radius)*(1-radius);
  168. #endif
  169. /*printf ("%d %d %d %d %d %d\n", num[0], num[1], num[2], den[0], den[1], den[2]);*/
  170. for (i=0;i<len;i++)
  171. {
  172. spx_word16_t vin = in[i*stride];
  173. spx_word32_t vout = mem[0] + SHL32(EXTEND32(vin),15);
  174. #ifdef FIXED_POINT
  175. mem[0] = mem[1] + SHL32(SHL32(-EXTEND32(vin),15) + MULT16_32_Q15(radius,vout),1);
  176. #else
  177. mem[0] = mem[1] + 2*(-vin + radius*vout);
  178. #endif
  179. mem[1] = SHL32(EXTEND32(vin),15) - MULT16_32_Q15(den2,vout);
  180. out[i] = SATURATE32(PSHR32(MULT16_32_Q15(radius,vout),15),32767);
  181. }
  182. }
  183. /* This inner product is slightly different from the codec version because of fixed-point */
  184. static inline spx_word32_t mdf_inner_prod(const spx_word16_t *x, const spx_word16_t *y, int len)
  185. {
  186. spx_word32_t sum=0;
  187. len >>= 1;
  188. while(len--)
  189. {
  190. spx_word32_t part=0;
  191. part = MAC16_16(part,*x++,*y++);
  192. part = MAC16_16(part,*x++,*y++);
  193. /* HINT: If you had a 40-bit accumulator, you could shift only at the end */
  194. sum = ADD32(sum,SHR32(part,6));
  195. }
  196. return sum;
  197. }
  198. /** Compute power spectrum of a half-complex (packed) vector */
  199. static inline void power_spectrum(const spx_word16_t *X, spx_word32_t *ps, int N)
  200. {
  201. int i, j;
  202. ps[0]=MULT16_16(X[0],X[0]);
  203. for (i=1,j=1;i<N-1;i+=2,j++)
  204. {
  205. ps[j] = MULT16_16(X[i],X[i]) + MULT16_16(X[i+1],X[i+1]);
  206. }
  207. ps[j]=MULT16_16(X[i],X[i]);
  208. }
  209. /** Compute power spectrum of a half-complex (packed) vector and accumulate */
  210. static inline void power_spectrum_accum(const spx_word16_t *X, spx_word32_t *ps, int N)
  211. {
  212. int i, j;
  213. ps[0]+=MULT16_16(X[0],X[0]);
  214. for (i=1,j=1;i<N-1;i+=2,j++)
  215. {
  216. ps[j] += MULT16_16(X[i],X[i]) + MULT16_16(X[i+1],X[i+1]);
  217. }
  218. ps[j]+=MULT16_16(X[i],X[i]);
  219. }
  220. /** Compute cross-power spectrum of a half-complex (packed) vectors and add to acc */
  221. #ifdef FIXED_POINT
  222. static inline void spectral_mul_accum(const spx_word16_t *X, const spx_word32_t *Y, spx_word16_t *acc, int N, int M)
  223. {
  224. int i,j;
  225. spx_word32_t tmp1=0,tmp2=0;
  226. for (j=0;j<M;j++)
  227. {
  228. tmp1 = MAC16_16(tmp1, X[j*N],TOP16(Y[j*N]));
  229. }
  230. acc[0] = PSHR32(tmp1,WEIGHT_SHIFT);
  231. for (i=1;i<N-1;i+=2)
  232. {
  233. tmp1 = tmp2 = 0;
  234. for (j=0;j<M;j++)
  235. {
  236. tmp1 = SUB32(MAC16_16(tmp1, X[j*N+i],TOP16(Y[j*N+i])), MULT16_16(X[j*N+i+1],TOP16(Y[j*N+i+1])));
  237. tmp2 = MAC16_16(MAC16_16(tmp2, X[j*N+i+1],TOP16(Y[j*N+i])), X[j*N+i], TOP16(Y[j*N+i+1]));
  238. }
  239. acc[i] = PSHR32(tmp1,WEIGHT_SHIFT);
  240. acc[i+1] = PSHR32(tmp2,WEIGHT_SHIFT);
  241. }
  242. tmp1 = tmp2 = 0;
  243. for (j=0;j<M;j++)
  244. {
  245. tmp1 = MAC16_16(tmp1, X[(j+1)*N-1],TOP16(Y[(j+1)*N-1]));
  246. }
  247. acc[N-1] = PSHR32(tmp1,WEIGHT_SHIFT);
  248. }
  249. static inline void spectral_mul_accum16(const spx_word16_t *X, const spx_word16_t *Y, spx_word16_t *acc, int N, int M)
  250. {
  251. int i,j;
  252. spx_word32_t tmp1=0,tmp2=0;
  253. for (j=0;j<M;j++)
  254. {
  255. tmp1 = MAC16_16(tmp1, X[j*N],Y[j*N]);
  256. }
  257. acc[0] = PSHR32(tmp1,WEIGHT_SHIFT);
  258. for (i=1;i<N-1;i+=2)
  259. {
  260. tmp1 = tmp2 = 0;
  261. for (j=0;j<M;j++)
  262. {
  263. tmp1 = SUB32(MAC16_16(tmp1, X[j*N+i],Y[j*N+i]), MULT16_16(X[j*N+i+1],Y[j*N+i+1]));
  264. tmp2 = MAC16_16(MAC16_16(tmp2, X[j*N+i+1],Y[j*N+i]), X[j*N+i], Y[j*N+i+1]);
  265. }
  266. acc[i] = PSHR32(tmp1,WEIGHT_SHIFT);
  267. acc[i+1] = PSHR32(tmp2,WEIGHT_SHIFT);
  268. }
  269. tmp1 = tmp2 = 0;
  270. for (j=0;j<M;j++)
  271. {
  272. tmp1 = MAC16_16(tmp1, X[(j+1)*N-1],Y[(j+1)*N-1]);
  273. }
  274. acc[N-1] = PSHR32(tmp1,WEIGHT_SHIFT);
  275. }
  276. #else
  277. static inline void spectral_mul_accum(const spx_word16_t *X, const spx_word32_t *Y, spx_word16_t *acc, int N, int M)
  278. {
  279. int i,j;
  280. for (i=0;i<N;i++)
  281. acc[i] = 0;
  282. for (j=0;j<M;j++)
  283. {
  284. acc[0] += X[0]*Y[0];
  285. for (i=1;i<N-1;i+=2)
  286. {
  287. acc[i] += (X[i]*Y[i] - X[i+1]*Y[i+1]);
  288. acc[i+1] += (X[i+1]*Y[i] + X[i]*Y[i+1]);
  289. }
  290. acc[i] += X[i]*Y[i];
  291. X += N;
  292. Y += N;
  293. }
  294. }
  295. #define spectral_mul_accum16 spectral_mul_accum
  296. #endif
  297. /** Compute weighted cross-power spectrum of a half-complex (packed) vector with conjugate */
  298. static inline void weighted_spectral_mul_conj(const spx_float_t *w, const spx_float_t p, const spx_word16_t *X, const spx_word16_t *Y, spx_word32_t *prod, int N)
  299. {
  300. int i, j;
  301. spx_float_t W;
  302. W = FLOAT_AMULT(p, w[0]);
  303. prod[0] = FLOAT_MUL32(W,MULT16_16(X[0],Y[0]));
  304. for (i=1,j=1;i<N-1;i+=2,j++)
  305. {
  306. W = FLOAT_AMULT(p, w[j]);
  307. prod[i] = FLOAT_MUL32(W,MAC16_16(MULT16_16(X[i],Y[i]), X[i+1],Y[i+1]));
  308. prod[i+1] = FLOAT_MUL32(W,MAC16_16(MULT16_16(-X[i+1],Y[i]), X[i],Y[i+1]));
  309. }
  310. W = FLOAT_AMULT(p, w[j]);
  311. prod[i] = FLOAT_MUL32(W,MULT16_16(X[i],Y[i]));
  312. }
  313. static inline void mdf_adjust_prop(const spx_word32_t *W, int N, int M, int P, spx_word16_t *prop)
  314. {
  315. int i, j, p;
  316. spx_word16_t max_sum = 1;
  317. spx_word32_t prop_sum = 1;
  318. for (i=0;i<M;i++)
  319. {
  320. spx_word32_t tmp = 1;
  321. for (p=0;p<P;p++)
  322. for (j=0;j<N;j++)
  323. tmp += MULT16_16(EXTRACT16(SHR32(W[p*N*M + i*N+j],18)), EXTRACT16(SHR32(W[p*N*M + i*N+j],18)));
  324. #ifdef FIXED_POINT
  325. /* Just a security in case an overflow were to occur */
  326. tmp = MIN32(ABS32(tmp), 536870912);
  327. #endif
  328. prop[i] = spx_sqrt(tmp);
  329. if (prop[i] > max_sum)
  330. max_sum = prop[i];
  331. }
  332. for (i=0;i<M;i++)
  333. {
  334. prop[i] += MULT16_16_Q15(QCONST16(.1f,15),max_sum);
  335. prop_sum += EXTEND32(prop[i]);
  336. }
  337. for (i=0;i<M;i++)
  338. {
  339. prop[i] = DIV32(MULT16_16(QCONST16(.99f,15), prop[i]),prop_sum);
  340. /*printf ("%f ", prop[i]);*/
  341. }
  342. /*printf ("\n");*/
  343. }
  344. #ifdef DUMP_ECHO_CANCEL_DATA
  345. #include <stdio.h>
  346. static FILE *rFile=NULL, *pFile=NULL, *oFile=NULL;
  347. static void dump_audio(const spx_int16_t *rec, const spx_int16_t *play, const spx_int16_t *out, int len)
  348. {
  349. if (!(rFile && pFile && oFile))
  350. {
  351. speex_fatal("Dump files not open");
  352. }
  353. fwrite(rec, sizeof(spx_int16_t), len, rFile);
  354. fwrite(play, sizeof(spx_int16_t), len, pFile);
  355. fwrite(out, sizeof(spx_int16_t), len, oFile);
  356. }
  357. #endif
  358. /** Creates a new echo canceller state */
  359. EXPORT SpeexEchoState *speex_echo_state_init(int frame_size, int filter_length)
  360. {
  361. return speex_echo_state_init_mc(frame_size, filter_length, 1, 1);
  362. }
  363. EXPORT SpeexEchoState *speex_echo_state_init_mc(int frame_size, int filter_length, int nb_mic, int nb_speakers)
  364. {
  365. int i,N,M, C, K;
  366. SpeexEchoState *st = (SpeexEchoState *)speex_alloc(sizeof(SpeexEchoState));
  367. st->K = nb_speakers;
  368. st->C = nb_mic;
  369. C=st->C;
  370. K=st->K;
  371. #ifdef DUMP_ECHO_CANCEL_DATA
  372. if (rFile || pFile || oFile)
  373. speex_fatal("Opening dump files twice");
  374. rFile = fopen("aec_rec.sw", "wb");
  375. pFile = fopen("aec_play.sw", "wb");
  376. oFile = fopen("aec_out.sw", "wb");
  377. #endif
  378. st->frame_size = frame_size;
  379. st->window_size = 2*frame_size;
  380. N = st->window_size;
  381. M = st->M = (filter_length+st->frame_size-1)/frame_size;
  382. st->cancel_count=0;
  383. st->sum_adapt = 0;
  384. st->saturated = 0;
  385. st->screwed_up = 0;
  386. /* This is the default sampling rate */
  387. st->sampling_rate = 8000;
  388. st->spec_average = DIV32_16(SHL32(EXTEND32(st->frame_size), 15), st->sampling_rate);
  389. #ifdef FIXED_POINT
  390. st->beta0 = DIV32_16(SHL32(EXTEND32(st->frame_size), 16), st->sampling_rate);
  391. st->beta_max = DIV32_16(SHL32(EXTEND32(st->frame_size), 14), st->sampling_rate);
  392. #else
  393. st->beta0 = (2.0f*st->frame_size)/st->sampling_rate;
  394. st->beta_max = (.5f*st->frame_size)/st->sampling_rate;
  395. #endif
  396. st->leak_estimate = 0;
  397. st->fft_table = spx_fft_init(N);
  398. st->e = (spx_word16_t*)speex_alloc(C*N*sizeof(spx_word16_t));
  399. st->x = (spx_word16_t*)speex_alloc(K*N*sizeof(spx_word16_t));
  400. st->input = (spx_word16_t*)speex_alloc(C*st->frame_size*sizeof(spx_word16_t));
  401. st->y = (spx_word16_t*)speex_alloc(C*N*sizeof(spx_word16_t));
  402. st->last_y = (spx_word16_t*)speex_alloc(C*N*sizeof(spx_word16_t));
  403. st->Yf = (spx_word32_t*)speex_alloc((st->frame_size+1)*sizeof(spx_word32_t));
  404. st->Rf = (spx_word32_t*)speex_alloc((st->frame_size+1)*sizeof(spx_word32_t));
  405. st->Xf = (spx_word32_t*)speex_alloc((st->frame_size+1)*sizeof(spx_word32_t));
  406. st->Yh = (spx_word32_t*)speex_alloc((st->frame_size+1)*sizeof(spx_word32_t));
  407. st->Eh = (spx_word32_t*)speex_alloc((st->frame_size+1)*sizeof(spx_word32_t));
  408. st->X = (spx_word16_t*)speex_alloc(K*(M+1)*N*sizeof(spx_word16_t));
  409. st->Y = (spx_word16_t*)speex_alloc(C*N*sizeof(spx_word16_t));
  410. st->E = (spx_word16_t*)speex_alloc(C*N*sizeof(spx_word16_t));
  411. st->W = (spx_word32_t*)speex_alloc(C*K*M*N*sizeof(spx_word32_t));
  412. #ifdef TWO_PATH
  413. st->foreground = (spx_word16_t*)speex_alloc(M*N*C*K*sizeof(spx_word16_t));
  414. #endif
  415. st->PHI = (spx_word32_t*)speex_alloc(N*sizeof(spx_word32_t));
  416. st->power = (spx_word32_t*)speex_alloc((frame_size+1)*sizeof(spx_word32_t));
  417. st->power_1 = (spx_float_t*)speex_alloc((frame_size+1)*sizeof(spx_float_t));
  418. st->window = (spx_word16_t*)speex_alloc(N*sizeof(spx_word16_t));
  419. st->prop = (spx_word16_t*)speex_alloc(M*sizeof(spx_word16_t));
  420. st->wtmp = (spx_word16_t*)speex_alloc(N*sizeof(spx_word16_t));
  421. #ifdef FIXED_POINT
  422. st->wtmp2 = (spx_word16_t*)speex_alloc(N*sizeof(spx_word16_t));
  423. for (i=0;i<N>>1;i++)
  424. {
  425. st->window[i] = (16383-SHL16(spx_cos(DIV32_16(MULT16_16(25736,i<<1),N)),1));
  426. st->window[N-i-1] = st->window[i];
  427. }
  428. #else
  429. for (i=0;i<N;i++)
  430. st->window[i] = .5-.5*cos(2*M_PI*i/N);
  431. #endif
  432. for (i=0;i<=st->frame_size;i++)
  433. st->power_1[i] = FLOAT_ONE;
  434. for (i=0;i<N*M*K*C;i++)
  435. st->W[i] = 0;
  436. {
  437. spx_word32_t sum = 0;
  438. /* Ratio of ~10 between adaptation rate of first and last block */
  439. spx_word16_t decay = SHR32(spx_exp(NEG16(DIV32_16(QCONST16(2.4,11),M))),1);
  440. st->prop[0] = QCONST16(.7, 15);
  441. sum = EXTEND32(st->prop[0]);
  442. for (i=1;i<M;i++)
  443. {
  444. st->prop[i] = MULT16_16_Q15(st->prop[i-1], decay);
  445. sum = ADD32(sum, EXTEND32(st->prop[i]));
  446. }
  447. for (i=M-1;i>=0;i--)
  448. {
  449. st->prop[i] = DIV32(MULT16_16(QCONST16(.8f,15), st->prop[i]),sum);
  450. }
  451. }
  452. st->memX = (spx_word16_t*)speex_alloc(K*sizeof(spx_word16_t));
  453. st->memD = (spx_word16_t*)speex_alloc(C*sizeof(spx_word16_t));
  454. st->memE = (spx_word16_t*)speex_alloc(C*sizeof(spx_word16_t));
  455. st->preemph = QCONST16(.9,15);
  456. if (st->sampling_rate<12000)
  457. st->notch_radius = QCONST16(.9, 15);
  458. else if (st->sampling_rate<24000)
  459. st->notch_radius = QCONST16(.982, 15);
  460. else
  461. st->notch_radius = QCONST16(.992, 15);
  462. st->notch_mem = (spx_mem_t*)speex_alloc(2*C*sizeof(spx_mem_t));
  463. st->adapted = 0;
  464. st->Pey = st->Pyy = FLOAT_ONE;
  465. #ifdef TWO_PATH
  466. st->Davg1 = st->Davg2 = 0;
  467. st->Dvar1 = st->Dvar2 = FLOAT_ZERO;
  468. #endif
  469. st->play_buf = (spx_int16_t*)speex_alloc(K*(PLAYBACK_DELAY+1)*st->frame_size*sizeof(spx_int16_t));
  470. st->play_buf_pos = PLAYBACK_DELAY*st->frame_size;
  471. st->play_buf_started = 0;
  472. return st;
  473. }
  474. /** Resets echo canceller state */
  475. EXPORT void speex_echo_state_reset(SpeexEchoState *st)
  476. {
  477. int i, M, N, C, K;
  478. st->cancel_count=0;
  479. st->screwed_up = 0;
  480. N = st->window_size;
  481. M = st->M;
  482. C=st->C;
  483. K=st->K;
  484. for (i=0;i<N*M;i++)
  485. st->W[i] = 0;
  486. #ifdef TWO_PATH
  487. for (i=0;i<N*M;i++)
  488. st->foreground[i] = 0;
  489. #endif
  490. for (i=0;i<N*(M+1);i++)
  491. st->X[i] = 0;
  492. for (i=0;i<=st->frame_size;i++)
  493. {
  494. st->power[i] = 0;
  495. st->power_1[i] = FLOAT_ONE;
  496. st->Eh[i] = 0;
  497. st->Yh[i] = 0;
  498. }
  499. for (i=0;i<st->frame_size;i++)
  500. {
  501. st->last_y[i] = 0;
  502. }
  503. for (i=0;i<N*C;i++)
  504. {
  505. st->E[i] = 0;
  506. }
  507. for (i=0;i<N*K;i++)
  508. {
  509. st->x[i] = 0;
  510. }
  511. for (i=0;i<2*C;i++)
  512. st->notch_mem[i] = 0;
  513. for (i=0;i<C;i++)
  514. st->memD[i]=st->memE[i]=0;
  515. for (i=0;i<K;i++)
  516. st->memX[i]=0;
  517. st->saturated = 0;
  518. st->adapted = 0;
  519. st->sum_adapt = 0;
  520. st->Pey = st->Pyy = FLOAT_ONE;
  521. #ifdef TWO_PATH
  522. st->Davg1 = st->Davg2 = 0;
  523. st->Dvar1 = st->Dvar2 = FLOAT_ZERO;
  524. #endif
  525. for (i=0;i<3*st->frame_size;i++)
  526. st->play_buf[i] = 0;
  527. st->play_buf_pos = PLAYBACK_DELAY*st->frame_size;
  528. st->play_buf_started = 0;
  529. }
  530. /** Destroys an echo canceller state */
  531. EXPORT void speex_echo_state_destroy(SpeexEchoState *st)
  532. {
  533. spx_fft_destroy(st->fft_table);
  534. speex_free(st->e);
  535. speex_free(st->x);
  536. speex_free(st->input);
  537. speex_free(st->y);
  538. speex_free(st->last_y);
  539. speex_free(st->Yf);
  540. speex_free(st->Rf);
  541. speex_free(st->Xf);
  542. speex_free(st->Yh);
  543. speex_free(st->Eh);
  544. speex_free(st->X);
  545. speex_free(st->Y);
  546. speex_free(st->E);
  547. speex_free(st->W);
  548. #ifdef TWO_PATH
  549. speex_free(st->foreground);
  550. #endif
  551. speex_free(st->PHI);
  552. speex_free(st->power);
  553. speex_free(st->power_1);
  554. speex_free(st->window);
  555. speex_free(st->prop);
  556. speex_free(st->wtmp);
  557. #ifdef FIXED_POINT
  558. speex_free(st->wtmp2);
  559. #endif
  560. speex_free(st->memX);
  561. speex_free(st->memD);
  562. speex_free(st->memE);
  563. speex_free(st->notch_mem);
  564. speex_free(st->play_buf);
  565. speex_free(st);
  566. #ifdef DUMP_ECHO_CANCEL_DATA
  567. fclose(rFile);
  568. fclose(pFile);
  569. fclose(oFile);
  570. rFile = pFile = oFile = NULL;
  571. #endif
  572. }
  573. EXPORT void speex_echo_capture(SpeexEchoState *st, const spx_int16_t *rec, spx_int16_t *out)
  574. {
  575. int i;
  576. /*speex_warning_int("capture with fill level ", st->play_buf_pos/st->frame_size);*/
  577. st->play_buf_started = 1;
  578. if (st->play_buf_pos>=st->frame_size)
  579. {
  580. speex_echo_cancellation(st, rec, st->play_buf, out);
  581. st->play_buf_pos -= st->frame_size;
  582. for (i=0;i<st->play_buf_pos;i++)
  583. st->play_buf[i] = st->play_buf[i+st->frame_size];
  584. } else {
  585. speex_warning("No playback frame available (your application is buggy and/or got xruns)");
  586. if (st->play_buf_pos!=0)
  587. {
  588. speex_warning("internal playback buffer corruption?");
  589. st->play_buf_pos = 0;
  590. }
  591. for (i=0;i<st->frame_size;i++)
  592. out[i] = rec[i];
  593. }
  594. }
  595. EXPORT void speex_echo_playback(SpeexEchoState *st, const spx_int16_t *play)
  596. {
  597. /*speex_warning_int("playback with fill level ", st->play_buf_pos/st->frame_size);*/
  598. if (!st->play_buf_started)
  599. {
  600. speex_warning("discarded first playback frame");
  601. return;
  602. }
  603. if (st->play_buf_pos<=PLAYBACK_DELAY*st->frame_size)
  604. {
  605. int i;
  606. for (i=0;i<st->frame_size;i++)
  607. st->play_buf[st->play_buf_pos+i] = play[i];
  608. st->play_buf_pos += st->frame_size;
  609. if (st->play_buf_pos <= (PLAYBACK_DELAY-1)*st->frame_size)
  610. {
  611. speex_warning("Auto-filling the buffer (your application is buggy and/or got xruns)");
  612. for (i=0;i<st->frame_size;i++)
  613. st->play_buf[st->play_buf_pos+i] = play[i];
  614. st->play_buf_pos += st->frame_size;
  615. }
  616. } else {
  617. speex_warning("Had to discard a playback frame (your application is buggy and/or got xruns)");
  618. }
  619. }
  620. /** Performs echo cancellation on a frame (deprecated, last arg now ignored) */
  621. EXPORT void speex_echo_cancel(SpeexEchoState *st, const spx_int16_t *in, const spx_int16_t *far_end, spx_int16_t *out, spx_int32_t *Yout)
  622. {
  623. speex_echo_cancellation(st, in, far_end, out);
  624. }
  625. /** Performs echo cancellation on a frame */
  626. EXPORT void speex_echo_cancellation(SpeexEchoState *st, const spx_int16_t *in, const spx_int16_t *far_end, spx_int16_t *out)
  627. {
  628. int i,j, chan, speak;
  629. int N,M, C, K;
  630. spx_word32_t Syy,See,Sxx,Sdd, Sff;
  631. #ifdef TWO_PATH
  632. spx_word32_t Dbf;
  633. int update_foreground;
  634. #endif
  635. spx_word32_t Sey;
  636. spx_word16_t ss, ss_1;
  637. spx_float_t Pey = FLOAT_ONE, Pyy=FLOAT_ONE;
  638. spx_float_t alpha, alpha_1;
  639. spx_word16_t RER;
  640. spx_word32_t tmp32;
  641. N = st->window_size;
  642. M = st->M;
  643. C = st->C;
  644. K = st->K;
  645. st->cancel_count++;
  646. #ifdef FIXED_POINT
  647. ss=DIV32_16(11469,M);
  648. ss_1 = SUB16(32767,ss);
  649. #else
  650. ss=.35/M;
  651. ss_1 = 1-ss;
  652. #endif
  653. for (chan = 0; chan < C; chan++)
  654. {
  655. /* Apply a notch filter to make sure DC doesn't end up causing problems */
  656. filter_dc_notch16(in+chan, st->notch_radius, st->input+chan*st->frame_size, st->frame_size, st->notch_mem+2*chan, C);
  657. /* Copy input data to buffer and apply pre-emphasis */
  658. /* Copy input data to buffer */
  659. for (i=0;i<st->frame_size;i++)
  660. {
  661. spx_word32_t tmp32;
  662. /* FIXME: This core has changed a bit, need to merge properly */
  663. tmp32 = SUB32(EXTEND32(st->input[chan*st->frame_size+i]), EXTEND32(MULT16_16_P15(st->preemph, st->memD[chan])));
  664. #ifdef FIXED_POINT
  665. if (tmp32 > 32767)
  666. {
  667. tmp32 = 32767;
  668. if (st->saturated == 0)
  669. st->saturated = 1;
  670. }
  671. if (tmp32 < -32767)
  672. {
  673. tmp32 = -32767;
  674. if (st->saturated == 0)
  675. st->saturated = 1;
  676. }
  677. #endif
  678. st->memD[chan] = st->input[chan*st->frame_size+i];
  679. st->input[chan*st->frame_size+i] = EXTRACT16(tmp32);
  680. }
  681. }
  682. for (speak = 0; speak < K; speak++)
  683. {
  684. for (i=0;i<st->frame_size;i++)
  685. {
  686. spx_word32_t tmp32;
  687. st->x[speak*N+i] = st->x[speak*N+i+st->frame_size];
  688. tmp32 = SUB32(EXTEND32(far_end[i*K+speak]), EXTEND32(MULT16_16_P15(st->preemph, st->memX[speak])));
  689. #ifdef FIXED_POINT
  690. /*FIXME: If saturation occurs here, we need to freeze adaptation for M frames (not just one) */
  691. if (tmp32 > 32767)
  692. {
  693. tmp32 = 32767;
  694. st->saturated = M+1;
  695. }
  696. if (tmp32 < -32767)
  697. {
  698. tmp32 = -32767;
  699. st->saturated = M+1;
  700. }
  701. #endif
  702. st->x[speak*N+i+st->frame_size] = EXTRACT16(tmp32);
  703. st->memX[speak] = far_end[i*K+speak];
  704. }
  705. }
  706. for (speak = 0; speak < K; speak++)
  707. {
  708. /* Shift memory: this could be optimized eventually*/
  709. for (j=M-1;j>=0;j--)
  710. {
  711. for (i=0;i<N;i++)
  712. st->X[(j+1)*N*K+speak*N+i] = st->X[j*N*K+speak*N+i];
  713. }
  714. /* Convert x (echo input) to frequency domain */
  715. spx_fft(st->fft_table, st->x+speak*N, &st->X[speak*N]);
  716. }
  717. Sxx = 0;
  718. for (speak = 0; speak < K; speak++)
  719. {
  720. Sxx += mdf_inner_prod(st->x+speak*N+st->frame_size, st->x+speak*N+st->frame_size, st->frame_size);
  721. power_spectrum_accum(st->X+speak*N, st->Xf, N);
  722. }
  723. Sff = 0;
  724. for (chan = 0; chan < C; chan++)
  725. {
  726. #ifdef TWO_PATH
  727. /* Compute foreground filter */
  728. spectral_mul_accum16(st->X, st->foreground+chan*N*K*M, st->Y+chan*N, N, M*K);
  729. spx_ifft(st->fft_table, st->Y+chan*N, st->e+chan*N);
  730. for (i=0;i<st->frame_size;i++)
  731. st->e[chan*N+i] = SUB16(st->input[chan*st->frame_size+i], st->e[chan*N+i+st->frame_size]);
  732. Sff += mdf_inner_prod(st->e+chan*N, st->e+chan*N, st->frame_size);
  733. #endif
  734. }
  735. /* Adjust proportional adaption rate */
  736. /* FIXME: Adjust that for C, K*/
  737. if (st->adapted)
  738. mdf_adjust_prop (st->W, N, M, C*K, st->prop);
  739. /* Compute weight gradient */
  740. if (st->saturated == 0)
  741. {
  742. for (chan = 0; chan < C; chan++)
  743. {
  744. for (speak = 0; speak < K; speak++)
  745. {
  746. for (j=M-1;j>=0;j--)
  747. {
  748. weighted_spectral_mul_conj(st->power_1, FLOAT_SHL(PSEUDOFLOAT(st->prop[j]),-15), &st->X[(j+1)*N*K+speak*N], st->E+chan*N, st->PHI, N);
  749. for (i=0;i<N;i++)
  750. st->W[chan*N*K*M + j*N*K + speak*N + i] += st->PHI[i];
  751. }
  752. }
  753. }
  754. } else {
  755. st->saturated--;
  756. }
  757. /* FIXME: MC conversion required */
  758. /* Update weight to prevent circular convolution (MDF / AUMDF) */
  759. for (chan = 0; chan < C; chan++)
  760. {
  761. for (speak = 0; speak < K; speak++)
  762. {
  763. for (j=0;j<M;j++)
  764. {
  765. /* This is a variant of the Alternatively Updated MDF (AUMDF) */
  766. /* Remove the "if" to make this an MDF filter */
  767. if (j==0 || st->cancel_count%(M-1) == j-1)
  768. {
  769. #ifdef FIXED_POINT
  770. for (i=0;i<N;i++)
  771. st->wtmp2[i] = EXTRACT16(PSHR32(st->W[chan*N*K*M + j*N*K + speak*N + i],NORMALIZE_SCALEDOWN+16));
  772. spx_ifft(st->fft_table, st->wtmp2, st->wtmp);
  773. for (i=0;i<st->frame_size;i++)
  774. {
  775. st->wtmp[i]=0;
  776. }
  777. for (i=st->frame_size;i<N;i++)
  778. {
  779. st->wtmp[i]=SHL16(st->wtmp[i],NORMALIZE_SCALEUP);
  780. }
  781. spx_fft(st->fft_table, st->wtmp, st->wtmp2);
  782. /* The "-1" in the shift is a sort of kludge that trades less efficient update speed for decrease noise */
  783. for (i=0;i<N;i++)
  784. st->W[chan*N*K*M + j*N*K + speak*N + i] -= SHL32(EXTEND32(st->wtmp2[i]),16+NORMALIZE_SCALEDOWN-NORMALIZE_SCALEUP-1);
  785. #else
  786. spx_ifft(st->fft_table, &st->W[chan*N*K*M + j*N*K + speak*N], st->wtmp);
  787. for (i=st->frame_size;i<N;i++)
  788. {
  789. st->wtmp[i]=0;
  790. }
  791. spx_fft(st->fft_table, st->wtmp, &st->W[chan*N*K*M + j*N*K + speak*N]);
  792. #endif
  793. }
  794. }
  795. }
  796. }
  797. /* So we can use power_spectrum_accum */
  798. for (i=0;i<=st->frame_size;i++)
  799. st->Rf[i] = st->Yf[i] = st->Xf[i] = 0;
  800. Dbf = 0;
  801. See = 0;
  802. #ifdef TWO_PATH
  803. /* Difference in response, this is used to estimate the variance of our residual power estimate */
  804. for (chan = 0; chan < C; chan++)
  805. {
  806. spectral_mul_accum(st->X, st->W+chan*N*K*M, st->Y+chan*N, N, M*K);
  807. spx_ifft(st->fft_table, st->Y+chan*N, st->y+chan*N);
  808. for (i=0;i<st->frame_size;i++)
  809. st->e[chan*N+i] = SUB16(st->e[chan*N+i+st->frame_size], st->y[chan*N+i+st->frame_size]);
  810. Dbf += 10+mdf_inner_prod(st->e+chan*N, st->e+chan*N, st->frame_size);
  811. for (i=0;i<st->frame_size;i++)
  812. st->e[chan*N+i] = SUB16(st->input[chan*st->frame_size+i], st->y[chan*N+i+st->frame_size]);
  813. See += mdf_inner_prod(st->e+chan*N, st->e+chan*N, st->frame_size);
  814. }
  815. #endif
  816. #ifndef TWO_PATH
  817. Sff = See;
  818. #endif
  819. #ifdef TWO_PATH
  820. /* Logic for updating the foreground filter */
  821. /* For two time windows, compute the mean of the energy difference, as well as the variance */
  822. st->Davg1 = ADD32(MULT16_32_Q15(QCONST16(.6f,15),st->Davg1), MULT16_32_Q15(QCONST16(.4f,15),SUB32(Sff,See)));
  823. st->Davg2 = ADD32(MULT16_32_Q15(QCONST16(.85f,15),st->Davg2), MULT16_32_Q15(QCONST16(.15f,15),SUB32(Sff,See)));
  824. st->Dvar1 = FLOAT_ADD(FLOAT_MULT(VAR1_SMOOTH, st->Dvar1), FLOAT_MUL32U(MULT16_32_Q15(QCONST16(.4f,15),Sff), MULT16_32_Q15(QCONST16(.4f,15),Dbf)));
  825. st->Dvar2 = FLOAT_ADD(FLOAT_MULT(VAR2_SMOOTH, st->Dvar2), FLOAT_MUL32U(MULT16_32_Q15(QCONST16(.15f,15),Sff), MULT16_32_Q15(QCONST16(.15f,15),Dbf)));
  826. /* Equivalent float code:
  827. st->Davg1 = .6*st->Davg1 + .4*(Sff-See);
  828. st->Davg2 = .85*st->Davg2 + .15*(Sff-See);
  829. st->Dvar1 = .36*st->Dvar1 + .16*Sff*Dbf;
  830. st->Dvar2 = .7225*st->Dvar2 + .0225*Sff*Dbf;
  831. */
  832. update_foreground = 0;
  833. /* Check if we have a statistically significant reduction in the residual echo */
  834. /* Note that this is *not* Gaussian, so we need to be careful about the longer tail */
  835. if (FLOAT_GT(FLOAT_MUL32U(SUB32(Sff,See),ABS32(SUB32(Sff,See))), FLOAT_MUL32U(Sff,Dbf)))
  836. update_foreground = 1;
  837. else if (FLOAT_GT(FLOAT_MUL32U(st->Davg1, ABS32(st->Davg1)), FLOAT_MULT(VAR1_UPDATE,(st->Dvar1))))
  838. update_foreground = 1;
  839. else if (FLOAT_GT(FLOAT_MUL32U(st->Davg2, ABS32(st->Davg2)), FLOAT_MULT(VAR2_UPDATE,(st->Dvar2))))
  840. update_foreground = 1;
  841. /* Do we update? */
  842. if (update_foreground)
  843. {
  844. st->Davg1 = st->Davg2 = 0;
  845. st->Dvar1 = st->Dvar2 = FLOAT_ZERO;
  846. /* Copy background filter to foreground filter */
  847. for (i=0;i<N*M*C*K;i++)
  848. st->foreground[i] = EXTRACT16(PSHR32(st->W[i],16));
  849. /* Apply a smooth transition so as to not introduce blocking artifacts */
  850. for (chan = 0; chan < C; chan++)
  851. for (i=0;i<st->frame_size;i++)
  852. st->e[chan*N+i+st->frame_size] = MULT16_16_Q15(st->window[i+st->frame_size],st->e[chan*N+i+st->frame_size]) + MULT16_16_Q15(st->window[i],st->y[chan*N+i+st->frame_size]);
  853. } else {
  854. int reset_background=0;
  855. /* Otherwise, check if the background filter is significantly worse */
  856. if (FLOAT_GT(FLOAT_MUL32U(NEG32(SUB32(Sff,See)),ABS32(SUB32(Sff,See))), FLOAT_MULT(VAR_BACKTRACK,FLOAT_MUL32U(Sff,Dbf))))
  857. reset_background = 1;
  858. if (FLOAT_GT(FLOAT_MUL32U(NEG32(st->Davg1), ABS32(st->Davg1)), FLOAT_MULT(VAR_BACKTRACK,st->Dvar1)))
  859. reset_background = 1;
  860. if (FLOAT_GT(FLOAT_MUL32U(NEG32(st->Davg2), ABS32(st->Davg2)), FLOAT_MULT(VAR_BACKTRACK,st->Dvar2)))
  861. reset_background = 1;
  862. if (reset_background)
  863. {
  864. /* Copy foreground filter to background filter */
  865. for (i=0;i<N*M*C*K;i++)
  866. st->W[i] = SHL32(EXTEND32(st->foreground[i]),16);
  867. /* We also need to copy the output so as to get correct adaptation */
  868. for (chan = 0; chan < C; chan++)
  869. {
  870. for (i=0;i<st->frame_size;i++)
  871. st->y[chan*N+i+st->frame_size] = st->e[chan*N+i+st->frame_size];
  872. for (i=0;i<st->frame_size;i++)
  873. st->e[chan*N+i] = SUB16(st->input[chan*st->frame_size+i], st->y[chan*N+i+st->frame_size]);
  874. }
  875. See = Sff;
  876. st->Davg1 = st->Davg2 = 0;
  877. st->Dvar1 = st->Dvar2 = FLOAT_ZERO;
  878. }
  879. }
  880. #endif
  881. Sey = Syy = Sdd = 0;
  882. for (chan = 0; chan < C; chan++)
  883. {
  884. /* Compute error signal (for the output with de-emphasis) */
  885. for (i=0;i<st->frame_size;i++)
  886. {
  887. spx_word32_t tmp_out;
  888. #ifdef TWO_PATH
  889. tmp_out = SUB32(EXTEND32(st->input[chan*st->frame_size+i]), EXTEND32(st->e[chan*N+i+st->frame_size]));
  890. #else
  891. tmp_out = SUB32(EXTEND32(st->input[chan*st->frame_size+i]), EXTEND32(st->y[chan*N+i+st->frame_size]));
  892. #endif
  893. tmp_out = ADD32(tmp_out, EXTEND32(MULT16_16_P15(st->preemph, st->memE[chan])));
  894. /* This is an arbitrary test for saturation in the microphone signal */
  895. if (in[i*C+chan] <= -32000 || in[i*C+chan] >= 32000)
  896. {
  897. if (st->saturated == 0)
  898. st->saturated = 1;
  899. }
  900. out[i*C+chan] = WORD2INT(tmp_out);
  901. st->memE[chan] = tmp_out;
  902. }
  903. #ifdef DUMP_ECHO_CANCEL_DATA
  904. dump_audio(in, far_end, out, st->frame_size);
  905. #endif
  906. /* Compute error signal (filter update version) */
  907. for (i=0;i<st->frame_size;i++)
  908. {
  909. st->e[chan*N+i+st->frame_size] = st->e[chan*N+i];
  910. st->e[chan*N+i] = 0;
  911. }
  912. /* Compute a bunch of correlations */
  913. /* FIXME: bad merge */
  914. Sey += mdf_inner_prod(st->e+chan*N+st->frame_size, st->y+chan*N+st->frame_size, st->frame_size);
  915. Syy += mdf_inner_prod(st->y+chan*N+st->frame_size, st->y+chan*N+st->frame_size, st->frame_size);
  916. Sdd += mdf_inner_prod(st->input+chan*st->frame_size, st->input+chan*st->frame_size, st->frame_size);
  917. /* Convert error to frequency domain */
  918. spx_fft(st->fft_table, st->e+chan*N, st->E+chan*N);
  919. for (i=0;i<st->frame_size;i++)
  920. st->y[i+chan*N] = 0;
  921. spx_fft(st->fft_table, st->y+chan*N, st->Y+chan*N);
  922. /* Compute power spectrum of echo (X), error (E) and filter response (Y) */
  923. power_spectrum_accum(st->E+chan*N, st->Rf, N);
  924. power_spectrum_accum(st->Y+chan*N, st->Yf, N);
  925. }
  926. /*printf ("%f %f %f %f\n", Sff, See, Syy, Sdd, st->update_cond);*/
  927. /* Do some sanity check */
  928. if (!(Syy>=0 && Sxx>=0 && See >= 0)
  929. #ifndef FIXED_POINT
  930. || !(Sff < N*1e9 && Syy < N*1e9 && Sxx < N*1e9)
  931. #endif
  932. )
  933. {
  934. /* Things have gone really bad */
  935. st->screwed_up += 50;
  936. for (i=0;i<st->frame_size*C;i++)
  937. out[i] = 0;
  938. } else if (SHR32(Sff, 2) > ADD32(Sdd, SHR32(MULT16_16(N, 10000),6)))
  939. {
  940. /* AEC seems to add lots of echo instead of removing it, let's see if it will improve */
  941. st->screwed_up++;
  942. } else {
  943. /* Everything's fine */
  944. st->screwed_up=0;
  945. }
  946. if (st->screwed_up>=50)
  947. {
  948. speex_warning("The echo canceller started acting funny and got slapped (reset). It swears it will behave now.");
  949. speex_echo_state_reset(st);
  950. return;
  951. }
  952. /* Add a small noise floor to make sure not to have problems when dividing */
  953. See = MAX32(See, SHR32(MULT16_16(N, 100),6));
  954. for (speak = 0; speak < K; speak++)
  955. {
  956. Sxx += mdf_inner_prod(st->x+speak*N+st->frame_size, st->x+speak*N+st->frame_size, st->frame_size);
  957. power_spectrum_accum(st->X+speak*N, st->Xf, N);
  958. }
  959. /* Smooth far end energy estimate over time */
  960. for (j=0;j<=st->frame_size;j++)
  961. st->power[j] = MULT16_32_Q15(ss_1,st->power[j]) + 1 + MULT16_32_Q15(ss,st->Xf[j]);
  962. /* Compute filtered spectra and (cross-)correlations */
  963. for (j=st->frame_size;j>=0;j--)
  964. {
  965. spx_float_t Eh, Yh;
  966. Eh = PSEUDOFLOAT(st->Rf[j] - st->Eh[j]);
  967. Yh = PSEUDOFLOAT(st->Yf[j] - st->Yh[j]);
  968. Pey = FLOAT_ADD(Pey,FLOAT_MULT(Eh,Yh));
  969. Pyy = FLOAT_ADD(Pyy,FLOAT_MULT(Yh,Yh));
  970. #ifdef FIXED_POINT
  971. st->Eh[j] = MAC16_32_Q15(MULT16_32_Q15(SUB16(32767,st->spec_average),st->Eh[j]), st->spec_average, st->Rf[j]);
  972. st->Yh[j] = MAC16_32_Q15(MULT16_32_Q15(SUB16(32767,st->spec_average),st->Yh[j]), st->spec_average, st->Yf[j]);
  973. #else
  974. st->Eh[j] = (1-st->spec_average)*st->Eh[j] + st->spec_average*st->Rf[j];
  975. st->Yh[j] = (1-st->spec_average)*st->Yh[j] + st->spec_average*st->Yf[j];
  976. #endif
  977. }
  978. Pyy = FLOAT_SQRT(Pyy);
  979. Pey = FLOAT_DIVU(Pey,Pyy);
  980. /* Compute correlation updatete rate */
  981. tmp32 = MULT16_32_Q15(st->beta0,Syy);
  982. if (tmp32 > MULT16_32_Q15(st->beta_max,See))
  983. tmp32 = MULT16_32_Q15(st->beta_max,See);
  984. alpha = FLOAT_DIV32(tmp32, See);
  985. alpha_1 = FLOAT_SUB(FLOAT_ONE, alpha);
  986. /* Update correlations (recursive average) */
  987. st->Pey = FLOAT_ADD(FLOAT_MULT(alpha_1,st->Pey) , FLOAT_MULT(alpha,Pey));
  988. st->Pyy = FLOAT_ADD(FLOAT_MULT(alpha_1,st->Pyy) , FLOAT_MULT(alpha,Pyy));
  989. if (FLOAT_LT(st->Pyy, FLOAT_ONE))
  990. st->Pyy = FLOAT_ONE;
  991. /* We don't really hope to get better than 33 dB (MIN_LEAK-3dB) attenuation anyway */
  992. if (FLOAT_LT(st->Pey, FLOAT_MULT(MIN_LEAK,st->Pyy)))
  993. st->Pey = FLOAT_MULT(MIN_LEAK,st->Pyy);
  994. if (FLOAT_GT(st->Pey, st->Pyy))
  995. st->Pey = st->Pyy;
  996. /* leak_estimate is the linear regression result */
  997. st->leak_estimate = FLOAT_EXTRACT16(FLOAT_SHL(FLOAT_DIVU(st->Pey, st->Pyy),14));
  998. /* This looks like a stupid bug, but it's right (because we convert from Q14 to Q15) */
  999. if (st->leak_estimate > 16383)
  1000. st->leak_estimate = 32767;
  1001. else
  1002. st->leak_estimate = SHL16(st->leak_estimate,1);
  1003. /*printf ("%f\n", st->leak_estimate);*/
  1004. /* Compute Residual to Error Ratio */
  1005. #ifdef FIXED_POINT
  1006. tmp32 = MULT16_32_Q15(st->leak_estimate,Syy);
  1007. tmp32 = ADD32(SHR32(Sxx,13), ADD32(tmp32, SHL32(tmp32,1)));
  1008. /* Check for y in e (lower bound on RER) */
  1009. {
  1010. spx_float_t bound = PSEUDOFLOAT(Sey);
  1011. bound = FLOAT_DIVU(FLOAT_MULT(bound, bound), PSEUDOFLOAT(ADD32(1,Syy)));
  1012. if (FLOAT_GT(bound, PSEUDOFLOAT(See)))
  1013. tmp32 = See;
  1014. else if (tmp32 < FLOAT_EXTRACT32(bound))
  1015. tmp32 = FLOAT_EXTRACT32(bound);
  1016. }
  1017. if (tmp32 > SHR32(See,1))
  1018. tmp32 = SHR32(See,1);
  1019. RER = FLOAT_EXTRACT16(FLOAT_SHL(FLOAT_DIV32(tmp32,See),15));
  1020. #else
  1021. RER = (.0001*Sxx + 3.*MULT16_32_Q15(st->leak_estimate,Syy)) / See;
  1022. /* Check for y in e (lower bound on RER) */
  1023. if (RER < Sey*Sey/(1+See*Syy))
  1024. RER = Sey*Sey/(1+See*Syy);
  1025. if (RER > .5)
  1026. RER = .5;
  1027. #endif
  1028. /* We consider that the filter has had minimal adaptation if the following is true*/
  1029. if (!st->adapted && st->sum_adapt > SHL32(EXTEND32(M),15) && MULT16_32_Q15(st->leak_estimate,Syy) > MULT16_32_Q15(QCONST16(.03f,15),Syy))
  1030. {
  1031. st->adapted = 1;
  1032. }
  1033. if (st->adapted)
  1034. {
  1035. /* Normal learning rate calculation once we're past the minimal adaptation phase */
  1036. for (i=0;i<=st->frame_size;i++)
  1037. {
  1038. spx_word32_t r, e;
  1039. /* Compute frequency-domain adaptation mask */
  1040. r = MULT16_32_Q15(st->leak_estimate,SHL32(st->Yf[i],3));
  1041. e = SHL32(st->Rf[i],3)+1;
  1042. #ifdef FIXED_POINT
  1043. if (r>SHR32(e,1))
  1044. r = SHR32(e,1);
  1045. #else
  1046. if (r>.5*e)
  1047. r = .5*e;
  1048. #endif
  1049. r = MULT16_32_Q15(QCONST16(.7,15),r) + MULT16_32_Q15(QCONST16(.3,15),(spx_word32_t)(MULT16_32_Q15(RER,e)));
  1050. /*st->power_1[i] = adapt_rate*r/(e*(1+st->power[i]));*/
  1051. st->power_1[i] = FLOAT_SHL(FLOAT_DIV32_FLOAT(r,FLOAT_MUL32U(e,st->power[i]+10)),WEIGHT_SHIFT+16);
  1052. }
  1053. } else {
  1054. /* Temporary adaption rate if filter is not yet adapted enough */
  1055. spx_word16_t adapt_rate=0;
  1056. if (Sxx > SHR32(MULT16_16(N, 1000),6))
  1057. {
  1058. tmp32 = MULT16_32_Q15(QCONST16(.25f, 15), Sxx);
  1059. #ifdef FIXED_POINT
  1060. if (tmp32 > SHR32(See,2))
  1061. tmp32 = SHR32(See,2);
  1062. #else
  1063. if (tmp32 > .25*See)
  1064. tmp32 = .25*See;
  1065. #endif
  1066. adapt_rate = FLOAT_EXTRACT16(FLOAT_SHL(FLOAT_DIV32(tmp32, See),15));
  1067. }
  1068. for (i=0;i<=st->frame_size;i++)
  1069. st->power_1[i] = FLOAT_SHL(FLOAT_DIV32(EXTEND32(adapt_rate),ADD32(st->power[i],10)),WEIGHT_SHIFT+1);
  1070. /* How much have we adapted so far? */
  1071. st->sum_adapt = ADD32(st->sum_adapt,adapt_rate);
  1072. }
  1073. /* FIXME: MC conversion required */
  1074. for (i=0;i<st->frame_size;i++)
  1075. st->last_y[i] = st->last_y[st->frame_size+i];
  1076. if (st->adapted)
  1077. {
  1078. /* If the filter is adapted, take the filtered echo */
  1079. for (i=0;i<st->frame_size;i++)
  1080. st->last_y[st->frame_size+i] = in[i]-out[i];
  1081. } else {
  1082. /* If filter isn't adapted yet, all we can do is take the far end signal directly */
  1083. /* moved earlier: for (i=0;i<N;i++)
  1084. st->last_y[i] = st->x[i];*/
  1085. }
  1086. }
  1087. /* Compute spectrum of estimated echo for use in an echo post-filter */
  1088. void speex_echo_get_residual(SpeexEchoState *st, spx_word32_t *residual_echo, int len)
  1089. {
  1090. int i;
  1091. spx_word16_t leak2;
  1092. int N;
  1093. N = st->window_size;
  1094. /* Apply hanning window (should pre-compute it)*/
  1095. for (i=0;i<N;i++)
  1096. st->y[i] = MULT16_16_Q15(st->window[i],st->last_y[i]);
  1097. /* Compute power spectrum of the echo */
  1098. spx_fft(st->fft_table, st->y, st->Y);
  1099. power_spectrum(st->Y, residual_echo, N);
  1100. #ifdef FIXED_POINT
  1101. if (st->leak_estimate > 16383)
  1102. leak2 = 32767;
  1103. else
  1104. leak2 = SHL16(st->leak_estimate, 1);
  1105. #else
  1106. if (st->leak_estimate>.5)
  1107. leak2 = 1;
  1108. else
  1109. leak2 = 2*st->leak_estimate;
  1110. #endif
  1111. /* Estimate residual echo */
  1112. for (i=0;i<=st->frame_size;i++)
  1113. residual_echo[i] = (spx_int32_t)MULT16_32_Q15(leak2,residual_echo[i]);
  1114. }
  1115. EXPORT int speex_echo_ctl(SpeexEchoState *st, int request, void *ptr)
  1116. {
  1117. switch(request)
  1118. {
  1119. case SPEEX_ECHO_GET_FRAME_SIZE:
  1120. (*(int*)ptr) = st->frame_size;
  1121. break;
  1122. case SPEEX_ECHO_SET_SAMPLING_RATE:
  1123. st->sampling_rate = (*(int*)ptr);
  1124. st->spec_average = DIV32_16(SHL32(EXTEND32(st->frame_size), 15), st->sampling_rate);
  1125. #ifdef FIXED_POINT
  1126. st->beta0 = DIV32_16(SHL32(EXTEND32(st->frame_size), 16), st->sampling_rate);
  1127. st->beta_max = DIV32_16(SHL32(EXTEND32(st->frame_size), 14), st->sampling_rate);
  1128. #else
  1129. st->beta0 = (2.0f*st->frame_size)/st->sampling_rate;
  1130. st->beta_max = (.5f*st->frame_size)/st->sampling_rate;
  1131. #endif
  1132. if (st->sampling_rate<12000)
  1133. st->notch_radius = QCONST16(.9, 15);
  1134. else if (st->sampling_rate<24000)
  1135. st->notch_radius = QCONST16(.982, 15);
  1136. else
  1137. st->notch_radius = QCONST16(.992, 15);
  1138. break;
  1139. case SPEEX_ECHO_GET_SAMPLING_RATE:
  1140. (*(int*)ptr) = st->sampling_rate;
  1141. break;
  1142. case SPEEX_ECHO_GET_IMPULSE_RESPONSE_SIZE:
  1143. /*FIXME: Implement this for multiple channels */
  1144. *((spx_int32_t *)ptr) = st->M * st->frame_size;
  1145. break;
  1146. case SPEEX_ECHO_GET_IMPULSE_RESPONSE:
  1147. {
  1148. int M = st->M, N = st->window_size, n = st->frame_size, i, j;
  1149. spx_int32_t *filt = (spx_int32_t *) ptr;
  1150. for(j=0;j<M;j++)
  1151. {
  1152. /*FIXME: Implement this for multiple channels */
  1153. #ifdef FIXED_POINT
  1154. for (i=0;i<N;i++)
  1155. st->wtmp2[i] = EXTRACT16(PSHR32(st->W[j*N+i],16+NORMALIZE_SCALEDOWN));
  1156. spx_ifft(st->fft_table, st->wtmp2, st->wtmp);
  1157. #else
  1158. spx_ifft(st->fft_table, &st->W[j*N], st->wtmp);
  1159. #endif
  1160. for(i=0;i<n;i++)
  1161. filt[j*n+i] = PSHR32(MULT16_16(32767,st->wtmp[i]), WEIGHT_SHIFT-NORMALIZE_SCALEDOWN);
  1162. }
  1163. }
  1164. break;
  1165. default:
  1166. speex_warning_int("Unknown speex_echo_ctl request: ", request);
  1167. return -1;
  1168. }
  1169. return 0;
  1170. }