echo.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * SpanDSP - a series of DSP components for telephony
  4. *
  5. * echo.c - A line echo canceller. This code is being developed
  6. * against and partially complies with G168.
  7. *
  8. * Written by Steve Underwood <steveu@coppice.org>
  9. * and David Rowe <david_at_rowetel_dot_com>
  10. *
  11. * Copyright (C) 2001, 2003 Steve Underwood, 2007 David Rowe
  12. *
  13. * Based on a bit from here, a bit from there, eye of toad, ear of
  14. * bat, 15 years of failed attempts by David and a few fried brain
  15. * cells.
  16. *
  17. * All rights reserved.
  18. */
  19. /*! \file */
  20. /* Implementation Notes
  21. David Rowe
  22. April 2007
  23. This code started life as Steve's NLMS algorithm with a tap
  24. rotation algorithm to handle divergence during double talk. I
  25. added a Geigel Double Talk Detector (DTD) [2] and performed some
  26. G168 tests. However I had trouble meeting the G168 requirements,
  27. especially for double talk - there were always cases where my DTD
  28. failed, for example where near end speech was under the 6dB
  29. threshold required for declaring double talk.
  30. So I tried a two path algorithm [1], which has so far given better
  31. results. The original tap rotation/Geigel algorithm is available
  32. in SVN http://svn.rowetel.com/software/oslec/tags/before_16bit.
  33. It's probably possible to make it work if some one wants to put some
  34. serious work into it.
  35. At present no special treatment is provided for tones, which
  36. generally cause NLMS algorithms to diverge. Initial runs of a
  37. subset of the G168 tests for tones (e.g ./echo_test 6) show the
  38. current algorithm is passing OK, which is kind of surprising. The
  39. full set of tests needs to be performed to confirm this result.
  40. One other interesting change is that I have managed to get the NLMS
  41. code to work with 16 bit coefficients, rather than the original 32
  42. bit coefficents. This reduces the MIPs and storage required.
  43. I evaulated the 16 bit port using g168_tests.sh and listening tests
  44. on 4 real-world samples.
  45. I also attempted the implementation of a block based NLMS update
  46. [2] but although this passes g168_tests.sh it didn't converge well
  47. on the real-world samples. I have no idea why, perhaps a scaling
  48. problem. The block based code is also available in SVN
  49. http://svn.rowetel.com/software/oslec/tags/before_16bit. If this
  50. code can be debugged, it will lead to further reduction in MIPS, as
  51. the block update code maps nicely onto DSP instruction sets (it's a
  52. dot product) compared to the current sample-by-sample update.
  53. Steve also has some nice notes on echo cancellers in echo.h
  54. References:
  55. [1] Ochiai, Areseki, and Ogihara, "Echo Canceller with Two Echo
  56. Path Models", IEEE Transactions on communications, COM-25,
  57. No. 6, June
  58. 1977.
  59. https://www.rowetel.com/images/echo/dual_path_paper.pdf
  60. [2] The classic, very useful paper that tells you how to
  61. actually build a real world echo canceller:
  62. Messerschmitt, Hedberg, Cole, Haoui, Winship, "Digital Voice
  63. Echo Canceller with a TMS320020,
  64. https://www.rowetel.com/images/echo/spra129.pdf
  65. [3] I have written a series of blog posts on this work, here is
  66. Part 1: http://www.rowetel.com/blog/?p=18
  67. [4] The source code http://svn.rowetel.com/software/oslec/
  68. [5] A nice reference on LMS filters:
  69. https://en.wikipedia.org/wiki/Least_mean_squares_filter
  70. Credits:
  71. Thanks to Steve Underwood, Jean-Marc Valin, and Ramakrishnan
  72. Muthukrishnan for their suggestions and email discussions. Thanks
  73. also to those people who collected echo samples for me such as
  74. Mark, Pawel, and Pavel.
  75. */
  76. #include <linux/kernel.h>
  77. #include <linux/module.h>
  78. #include <linux/slab.h>
  79. #include "echo.h"
  80. #define MIN_TX_POWER_FOR_ADAPTION 64
  81. #define MIN_RX_POWER_FOR_ADAPTION 64
  82. #define DTD_HANGOVER 600 /* 600 samples, or 75ms */
  83. #define DC_LOG2BETA 3 /* log2() of DC filter Beta */
  84. /* adapting coeffs using the traditional stochastic descent (N)LMS algorithm */
  85. static inline void lms_adapt_bg(struct oslec_state *ec, int clean, int shift)
  86. {
  87. int i;
  88. int offset1;
  89. int offset2;
  90. int factor;
  91. int exp;
  92. if (shift > 0)
  93. factor = clean << shift;
  94. else
  95. factor = clean >> -shift;
  96. /* Update the FIR taps */
  97. offset2 = ec->curr_pos;
  98. offset1 = ec->taps - offset2;
  99. for (i = ec->taps - 1; i >= offset1; i--) {
  100. exp = (ec->fir_state_bg.history[i - offset1] * factor);
  101. ec->fir_taps16[1][i] += (int16_t) ((exp + (1 << 14)) >> 15);
  102. }
  103. for (; i >= 0; i--) {
  104. exp = (ec->fir_state_bg.history[i + offset2] * factor);
  105. ec->fir_taps16[1][i] += (int16_t) ((exp + (1 << 14)) >> 15);
  106. }
  107. }
  108. static inline int top_bit(unsigned int bits)
  109. {
  110. if (bits == 0)
  111. return -1;
  112. else
  113. return (int)fls((int32_t) bits) - 1;
  114. }
  115. struct oslec_state *oslec_create(int len, int adaption_mode)
  116. {
  117. struct oslec_state *ec;
  118. int i;
  119. const int16_t *history;
  120. ec = kzalloc(sizeof(*ec), GFP_KERNEL);
  121. if (!ec)
  122. return NULL;
  123. ec->taps = len;
  124. ec->log2taps = top_bit(len);
  125. ec->curr_pos = ec->taps - 1;
  126. ec->fir_taps16[0] =
  127. kcalloc(ec->taps, sizeof(int16_t), GFP_KERNEL);
  128. if (!ec->fir_taps16[0])
  129. goto error_oom_0;
  130. ec->fir_taps16[1] =
  131. kcalloc(ec->taps, sizeof(int16_t), GFP_KERNEL);
  132. if (!ec->fir_taps16[1])
  133. goto error_oom_1;
  134. history = fir16_create(&ec->fir_state, ec->fir_taps16[0], ec->taps);
  135. if (!history)
  136. goto error_state;
  137. history = fir16_create(&ec->fir_state_bg, ec->fir_taps16[1], ec->taps);
  138. if (!history)
  139. goto error_state_bg;
  140. for (i = 0; i < 5; i++)
  141. ec->xvtx[i] = ec->yvtx[i] = ec->xvrx[i] = ec->yvrx[i] = 0;
  142. ec->cng_level = 1000;
  143. oslec_adaption_mode(ec, adaption_mode);
  144. ec->snapshot = kcalloc(ec->taps, sizeof(int16_t), GFP_KERNEL);
  145. if (!ec->snapshot)
  146. goto error_snap;
  147. ec->cond_met = 0;
  148. ec->pstates = 0;
  149. ec->ltxacc = ec->lrxacc = ec->lcleanacc = ec->lclean_bgacc = 0;
  150. ec->ltx = ec->lrx = ec->lclean = ec->lclean_bg = 0;
  151. ec->tx_1 = ec->tx_2 = ec->rx_1 = ec->rx_2 = 0;
  152. ec->lbgn = ec->lbgn_acc = 0;
  153. ec->lbgn_upper = 200;
  154. ec->lbgn_upper_acc = ec->lbgn_upper << 13;
  155. return ec;
  156. error_snap:
  157. fir16_free(&ec->fir_state_bg);
  158. error_state_bg:
  159. fir16_free(&ec->fir_state);
  160. error_state:
  161. kfree(ec->fir_taps16[1]);
  162. error_oom_1:
  163. kfree(ec->fir_taps16[0]);
  164. error_oom_0:
  165. kfree(ec);
  166. return NULL;
  167. }
  168. EXPORT_SYMBOL_GPL(oslec_create);
  169. void oslec_free(struct oslec_state *ec)
  170. {
  171. int i;
  172. fir16_free(&ec->fir_state);
  173. fir16_free(&ec->fir_state_bg);
  174. for (i = 0; i < 2; i++)
  175. kfree(ec->fir_taps16[i]);
  176. kfree(ec->snapshot);
  177. kfree(ec);
  178. }
  179. EXPORT_SYMBOL_GPL(oslec_free);
  180. void oslec_adaption_mode(struct oslec_state *ec, int adaption_mode)
  181. {
  182. ec->adaption_mode = adaption_mode;
  183. }
  184. EXPORT_SYMBOL_GPL(oslec_adaption_mode);
  185. void oslec_flush(struct oslec_state *ec)
  186. {
  187. int i;
  188. ec->ltxacc = ec->lrxacc = ec->lcleanacc = ec->lclean_bgacc = 0;
  189. ec->ltx = ec->lrx = ec->lclean = ec->lclean_bg = 0;
  190. ec->tx_1 = ec->tx_2 = ec->rx_1 = ec->rx_2 = 0;
  191. ec->lbgn = ec->lbgn_acc = 0;
  192. ec->lbgn_upper = 200;
  193. ec->lbgn_upper_acc = ec->lbgn_upper << 13;
  194. ec->nonupdate_dwell = 0;
  195. fir16_flush(&ec->fir_state);
  196. fir16_flush(&ec->fir_state_bg);
  197. ec->fir_state.curr_pos = ec->taps - 1;
  198. ec->fir_state_bg.curr_pos = ec->taps - 1;
  199. for (i = 0; i < 2; i++)
  200. memset(ec->fir_taps16[i], 0, ec->taps * sizeof(int16_t));
  201. ec->curr_pos = ec->taps - 1;
  202. ec->pstates = 0;
  203. }
  204. EXPORT_SYMBOL_GPL(oslec_flush);
  205. void oslec_snapshot(struct oslec_state *ec)
  206. {
  207. memcpy(ec->snapshot, ec->fir_taps16[0], ec->taps * sizeof(int16_t));
  208. }
  209. EXPORT_SYMBOL_GPL(oslec_snapshot);
  210. /* Dual Path Echo Canceller */
  211. int16_t oslec_update(struct oslec_state *ec, int16_t tx, int16_t rx)
  212. {
  213. int32_t echo_value;
  214. int clean_bg;
  215. int tmp;
  216. int tmp1;
  217. /*
  218. * Input scaling was found be required to prevent problems when tx
  219. * starts clipping. Another possible way to handle this would be the
  220. * filter coefficent scaling.
  221. */
  222. ec->tx = tx;
  223. ec->rx = rx;
  224. tx >>= 1;
  225. rx >>= 1;
  226. /*
  227. * Filter DC, 3dB point is 160Hz (I think), note 32 bit precision
  228. * required otherwise values do not track down to 0. Zero at DC, Pole
  229. * at (1-Beta) on real axis. Some chip sets (like Si labs) don't
  230. * need this, but something like a $10 X100P card does. Any DC really
  231. * slows down convergence.
  232. *
  233. * Note: removes some low frequency from the signal, this reduces the
  234. * speech quality when listening to samples through headphones but may
  235. * not be obvious through a telephone handset.
  236. *
  237. * Note that the 3dB frequency in radians is approx Beta, e.g. for Beta
  238. * = 2^(-3) = 0.125, 3dB freq is 0.125 rads = 159Hz.
  239. */
  240. if (ec->adaption_mode & ECHO_CAN_USE_RX_HPF) {
  241. tmp = rx << 15;
  242. /*
  243. * Make sure the gain of the HPF is 1.0. This can still
  244. * saturate a little under impulse conditions, and it might
  245. * roll to 32768 and need clipping on sustained peak level
  246. * signals. However, the scale of such clipping is small, and
  247. * the error due to any saturation should not markedly affect
  248. * the downstream processing.
  249. */
  250. tmp -= (tmp >> 4);
  251. ec->rx_1 += -(ec->rx_1 >> DC_LOG2BETA) + tmp - ec->rx_2;
  252. /*
  253. * hard limit filter to prevent clipping. Note that at this
  254. * stage rx should be limited to +/- 16383 due to right shift
  255. * above
  256. */
  257. tmp1 = ec->rx_1 >> 15;
  258. if (tmp1 > 16383)
  259. tmp1 = 16383;
  260. if (tmp1 < -16383)
  261. tmp1 = -16383;
  262. rx = tmp1;
  263. ec->rx_2 = tmp;
  264. }
  265. /* Block average of power in the filter states. Used for
  266. adaption power calculation. */
  267. {
  268. int new, old;
  269. /* efficient "out with the old and in with the new" algorithm so
  270. we don't have to recalculate over the whole block of
  271. samples. */
  272. new = (int)tx * (int)tx;
  273. old = (int)ec->fir_state.history[ec->fir_state.curr_pos] *
  274. (int)ec->fir_state.history[ec->fir_state.curr_pos];
  275. ec->pstates +=
  276. ((new - old) + (1 << (ec->log2taps - 1))) >> ec->log2taps;
  277. if (ec->pstates < 0)
  278. ec->pstates = 0;
  279. }
  280. /* Calculate short term average levels using simple single pole IIRs */
  281. ec->ltxacc += abs(tx) - ec->ltx;
  282. ec->ltx = (ec->ltxacc + (1 << 4)) >> 5;
  283. ec->lrxacc += abs(rx) - ec->lrx;
  284. ec->lrx = (ec->lrxacc + (1 << 4)) >> 5;
  285. /* Foreground filter */
  286. ec->fir_state.coeffs = ec->fir_taps16[0];
  287. echo_value = fir16(&ec->fir_state, tx);
  288. ec->clean = rx - echo_value;
  289. ec->lcleanacc += abs(ec->clean) - ec->lclean;
  290. ec->lclean = (ec->lcleanacc + (1 << 4)) >> 5;
  291. /* Background filter */
  292. echo_value = fir16(&ec->fir_state_bg, tx);
  293. clean_bg = rx - echo_value;
  294. ec->lclean_bgacc += abs(clean_bg) - ec->lclean_bg;
  295. ec->lclean_bg = (ec->lclean_bgacc + (1 << 4)) >> 5;
  296. /* Background Filter adaption */
  297. /* Almost always adap bg filter, just simple DT and energy
  298. detection to minimise adaption in cases of strong double talk.
  299. However this is not critical for the dual path algorithm.
  300. */
  301. ec->factor = 0;
  302. ec->shift = 0;
  303. if (!ec->nonupdate_dwell) {
  304. int p, logp, shift;
  305. /* Determine:
  306. f = Beta * clean_bg_rx/P ------ (1)
  307. where P is the total power in the filter states.
  308. The Boffins have shown that if we obey (1) we converge
  309. quickly and avoid instability.
  310. The correct factor f must be in Q30, as this is the fixed
  311. point format required by the lms_adapt_bg() function,
  312. therefore the scaled version of (1) is:
  313. (2^30) * f = (2^30) * Beta * clean_bg_rx/P
  314. factor = (2^30) * Beta * clean_bg_rx/P ----- (2)
  315. We have chosen Beta = 0.25 by experiment, so:
  316. factor = (2^30) * (2^-2) * clean_bg_rx/P
  317. (30 - 2 - log2(P))
  318. factor = clean_bg_rx 2 ----- (3)
  319. To avoid a divide we approximate log2(P) as top_bit(P),
  320. which returns the position of the highest non-zero bit in
  321. P. This approximation introduces an error as large as a
  322. factor of 2, but the algorithm seems to handle it OK.
  323. Come to think of it a divide may not be a big deal on a
  324. modern DSP, so its probably worth checking out the cycles
  325. for a divide versus a top_bit() implementation.
  326. */
  327. p = MIN_TX_POWER_FOR_ADAPTION + ec->pstates;
  328. logp = top_bit(p) + ec->log2taps;
  329. shift = 30 - 2 - logp;
  330. ec->shift = shift;
  331. lms_adapt_bg(ec, clean_bg, shift);
  332. }
  333. /* very simple DTD to make sure we dont try and adapt with strong
  334. near end speech */
  335. ec->adapt = 0;
  336. if ((ec->lrx > MIN_RX_POWER_FOR_ADAPTION) && (ec->lrx > ec->ltx))
  337. ec->nonupdate_dwell = DTD_HANGOVER;
  338. if (ec->nonupdate_dwell)
  339. ec->nonupdate_dwell--;
  340. /* Transfer logic */
  341. /* These conditions are from the dual path paper [1], I messed with
  342. them a bit to improve performance. */
  343. if ((ec->adaption_mode & ECHO_CAN_USE_ADAPTION) &&
  344. (ec->nonupdate_dwell == 0) &&
  345. /* (ec->Lclean_bg < 0.875*ec->Lclean) */
  346. (8 * ec->lclean_bg < 7 * ec->lclean) &&
  347. /* (ec->Lclean_bg < 0.125*ec->Ltx) */
  348. (8 * ec->lclean_bg < ec->ltx)) {
  349. if (ec->cond_met == 6) {
  350. /*
  351. * BG filter has had better results for 6 consecutive
  352. * samples
  353. */
  354. ec->adapt = 1;
  355. memcpy(ec->fir_taps16[0], ec->fir_taps16[1],
  356. ec->taps * sizeof(int16_t));
  357. } else
  358. ec->cond_met++;
  359. } else
  360. ec->cond_met = 0;
  361. /* Non-Linear Processing */
  362. ec->clean_nlp = ec->clean;
  363. if (ec->adaption_mode & ECHO_CAN_USE_NLP) {
  364. /*
  365. * Non-linear processor - a fancy way to say "zap small
  366. * signals, to avoid residual echo due to (uLaw/ALaw)
  367. * non-linearity in the channel.".
  368. */
  369. if ((16 * ec->lclean < ec->ltx)) {
  370. /*
  371. * Our e/c has improved echo by at least 24 dB (each
  372. * factor of 2 is 6dB, so 2*2*2*2=16 is the same as
  373. * 6+6+6+6=24dB)
  374. */
  375. if (ec->adaption_mode & ECHO_CAN_USE_CNG) {
  376. ec->cng_level = ec->lbgn;
  377. /*
  378. * Very elementary comfort noise generation.
  379. * Just random numbers rolled off very vaguely
  380. * Hoth-like. DR: This noise doesn't sound
  381. * quite right to me - I suspect there are some
  382. * overflow issues in the filtering as it's too
  383. * "crackly".
  384. * TODO: debug this, maybe just play noise at
  385. * high level or look at spectrum.
  386. */
  387. ec->cng_rndnum =
  388. 1664525U * ec->cng_rndnum + 1013904223U;
  389. ec->cng_filter =
  390. ((ec->cng_rndnum & 0xFFFF) - 32768 +
  391. 5 * ec->cng_filter) >> 3;
  392. ec->clean_nlp =
  393. (ec->cng_filter * ec->cng_level * 8) >> 14;
  394. } else if (ec->adaption_mode & ECHO_CAN_USE_CLIP) {
  395. /* This sounds much better than CNG */
  396. if (ec->clean_nlp > ec->lbgn)
  397. ec->clean_nlp = ec->lbgn;
  398. if (ec->clean_nlp < -ec->lbgn)
  399. ec->clean_nlp = -ec->lbgn;
  400. } else {
  401. /*
  402. * just mute the residual, doesn't sound very
  403. * good, used mainly in G168 tests
  404. */
  405. ec->clean_nlp = 0;
  406. }
  407. } else {
  408. /*
  409. * Background noise estimator. I tried a few
  410. * algorithms here without much luck. This very simple
  411. * one seems to work best, we just average the level
  412. * using a slow (1 sec time const) filter if the
  413. * current level is less than a (experimentally
  414. * derived) constant. This means we dont include high
  415. * level signals like near end speech. When combined
  416. * with CNG or especially CLIP seems to work OK.
  417. */
  418. if (ec->lclean < 40) {
  419. ec->lbgn_acc += abs(ec->clean) - ec->lbgn;
  420. ec->lbgn = (ec->lbgn_acc + (1 << 11)) >> 12;
  421. }
  422. }
  423. }
  424. /* Roll around the taps buffer */
  425. if (ec->curr_pos <= 0)
  426. ec->curr_pos = ec->taps;
  427. ec->curr_pos--;
  428. if (ec->adaption_mode & ECHO_CAN_DISABLE)
  429. ec->clean_nlp = rx;
  430. /* Output scaled back up again to match input scaling */
  431. return (int16_t) ec->clean_nlp << 1;
  432. }
  433. EXPORT_SYMBOL_GPL(oslec_update);
  434. /* This function is separated from the echo canceller is it is usually called
  435. as part of the tx process. See rx HP (DC blocking) filter above, it's
  436. the same design.
  437. Some soft phones send speech signals with a lot of low frequency
  438. energy, e.g. down to 20Hz. This can make the hybrid non-linear
  439. which causes the echo canceller to fall over. This filter can help
  440. by removing any low frequency before it gets to the tx port of the
  441. hybrid.
  442. It can also help by removing and DC in the tx signal. DC is bad
  443. for LMS algorithms.
  444. This is one of the classic DC removal filters, adjusted to provide
  445. sufficient bass rolloff to meet the above requirement to protect hybrids
  446. from things that upset them. The difference between successive samples
  447. produces a lousy HPF, and then a suitably placed pole flattens things out.
  448. The final result is a nicely rolled off bass end. The filtering is
  449. implemented with extended fractional precision, which noise shapes things,
  450. giving very clean DC removal.
  451. */
  452. int16_t oslec_hpf_tx(struct oslec_state *ec, int16_t tx)
  453. {
  454. int tmp;
  455. int tmp1;
  456. if (ec->adaption_mode & ECHO_CAN_USE_TX_HPF) {
  457. tmp = tx << 15;
  458. /*
  459. * Make sure the gain of the HPF is 1.0. The first can still
  460. * saturate a little under impulse conditions, and it might
  461. * roll to 32768 and need clipping on sustained peak level
  462. * signals. However, the scale of such clipping is small, and
  463. * the error due to any saturation should not markedly affect
  464. * the downstream processing.
  465. */
  466. tmp -= (tmp >> 4);
  467. ec->tx_1 += -(ec->tx_1 >> DC_LOG2BETA) + tmp - ec->tx_2;
  468. tmp1 = ec->tx_1 >> 15;
  469. if (tmp1 > 32767)
  470. tmp1 = 32767;
  471. if (tmp1 < -32767)
  472. tmp1 = -32767;
  473. tx = tmp1;
  474. ec->tx_2 = tmp;
  475. }
  476. return tx;
  477. }
  478. EXPORT_SYMBOL_GPL(oslec_hpf_tx);
  479. MODULE_LICENSE("GPL");
  480. MODULE_AUTHOR("David Rowe");
  481. MODULE_DESCRIPTION("Open Source Line Echo Canceller");
  482. MODULE_VERSION("0.3.0");