echo.c 18 KB

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