dahdi_echocan_kb1.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. /*
  2. * ECHO_CAN_KB1
  3. *
  4. * by Kris Boutilier
  5. *
  6. * Based upon mec2.h
  7. *
  8. * Copyright (C) 2002, Digium, Inc.
  9. *
  10. * Additional background on the techniques used in this code can be found in:
  11. *
  12. * Messerschmitt, David; Hedberg, David; Cole, Christopher; Haoui, Amine;
  13. * Winship, Peter; "Digital Voice Echo Canceller with a TMS32020,"
  14. * in Digital Signal Processing Applications with the TMS320 Family,
  15. * pp. 415-437, Texas Instruments, Inc., 1986.
  16. *
  17. * A pdf of which is available by searching on the document title at http://www.ti.com/
  18. *
  19. */
  20. /*
  21. * See http://www.asterisk.org for more information about
  22. * the Asterisk project. Please do not directly contact
  23. * any of the maintainers of this project for assistance;
  24. * the project provides a web site, mailing lists and IRC
  25. * channels for your use.
  26. *
  27. * This program is free software, distributed under the terms of
  28. * the GNU General Public License Version 2 as published by the
  29. * Free Software Foundation. See the LICENSE file included with
  30. * this program for more details.
  31. */
  32. #include <linux/kernel.h>
  33. #include <linux/slab.h>
  34. #include <linux/errno.h>
  35. #include <linux/module.h>
  36. #include <linux/init.h>
  37. #include <linux/ctype.h>
  38. #include <linux/moduleparam.h>
  39. #include <dahdi/kernel.h>
  40. static int debug;
  41. static int aggressive;
  42. #define module_printk(level, fmt, args...) printk(level "%s: " fmt, THIS_MODULE->name, ## args)
  43. #define debug_printk(level, fmt, args...) if (debug >= level) printk(KERN_DEBUG "%s (%s): " fmt, THIS_MODULE->name, __FUNCTION__, ## args)
  44. /* Uncomment to provide summary statistics for overall echo can performance every 4000 samples */
  45. /* #define MEC2_STATS 4000 */
  46. /* Uncomment to generate per-sample statistics - this will severely degrade system performance and audio quality */
  47. /* #define MEC2_STATS_DETAILED */
  48. /* Get optimized routines for math */
  49. #include "arith.h"
  50. /*
  51. Important constants for tuning kb1 echo can
  52. */
  53. /* Convergence (aka. adaptation) speed -- higher means slower */
  54. #define DEFAULT_BETA1_I 2048
  55. /* Constants for various power computations */
  56. #define DEFAULT_SIGMA_LY_I 7
  57. #define DEFAULT_SIGMA_LU_I 7
  58. #define DEFAULT_ALPHA_ST_I 5 /* near-end speech detection sensitivity factor */
  59. #define DEFAULT_ALPHA_YT_I 5
  60. #define DEFAULT_CUTOFF_I 128
  61. /* Define the near-end speech hangover counter: if near-end speech
  62. * is declared, hcntr is set equal to hangt (see pg. 432)
  63. */
  64. #define DEFAULT_HANGT 600 /* in samples, so 600 samples = 75ms */
  65. /* define the residual error suppression threshold */
  66. #define DEFAULT_SUPPR_I 16 /* 16 = -24db */
  67. /* This is the minimum reference signal power estimate level
  68. * that will result in filter adaptation.
  69. * If this is too low then background noise will cause the filter
  70. * coefficients to constantly be updated.
  71. */
  72. #define MIN_UPDATE_THRESH_I 4096
  73. /* The number of samples used to update coefficients using the
  74. * the block update method (M). It should be related back to the
  75. * length of the echo can.
  76. * ie. it only updates coefficients when (sample number MOD default_m) = 0
  77. *
  78. * Getting this wrong may cause an oops. Consider yourself warned!
  79. */
  80. #define DEFAULT_M 16 /* every 16th sample */
  81. /* If AGGRESSIVE supression is enabled, then we start cancelling residual
  82. * echos again even while there is potentially the very end of a near-side
  83. * signal present.
  84. * This defines how many samples of DEFAULT_HANGT can remain before we
  85. * kick back in
  86. */
  87. #define AGGRESSIVE_HCNTR 160 /* in samples, so 160 samples = 20ms */
  88. /***************************************************************/
  89. /* The following knobs are not implemented in the current code */
  90. /* we need a dynamic level of suppression varying with the ratio of the
  91. power of the echo to the power of the reference signal this is
  92. done so that we have a smoother background.
  93. we have a higher suppression when the power ratio is closer to
  94. suppr_ceil and reduces logarithmically as we approach suppr_floor.
  95. */
  96. #define SUPPR_FLOOR -64
  97. #define SUPPR_CEIL -24
  98. /* in a second departure, we calculate the residual error suppression
  99. * as a percentage of the reference signal energy level. The threshold
  100. * is defined in terms of dB below the reference signal.
  101. */
  102. #define RES_SUPR_FACTOR -20
  103. #ifndef NULL
  104. #define NULL 0
  105. #endif
  106. #ifndef FALSE
  107. #define FALSE 0
  108. #endif
  109. #ifndef TRUE
  110. #define TRUE (!FALSE)
  111. #endif
  112. /* Generic circular buffer definition */
  113. typedef struct {
  114. /* Pointer to the relative 'start' of the buffer */
  115. int idx_d;
  116. /* The absolute size of the buffer */
  117. int size_d;
  118. /* The actual sample - twice as large as we need, however we do store values at idx_d and idx_d+size_d */
  119. short *buf_d;
  120. } echo_can_cb_s;
  121. static int echo_can_create(struct dahdi_chan *chan, struct dahdi_echocanparams *ecp,
  122. struct dahdi_echocanparam *p, struct dahdi_echocan_state **ec);
  123. static void echo_can_free(struct dahdi_chan *chan, struct dahdi_echocan_state *ec);
  124. static void echo_can_process(struct dahdi_echocan_state *ec, short *isig, const short *iref, u32 size);
  125. static int echo_can_traintap(struct dahdi_echocan_state *ec, int pos, short val);
  126. static void echocan_NLP_toggle(struct dahdi_echocan_state *ec, unsigned int enable);
  127. static const struct dahdi_echocan_factory my_factory = {
  128. .name = "KB1",
  129. .owner = THIS_MODULE,
  130. .echocan_create = echo_can_create,
  131. };
  132. static const struct dahdi_echocan_features my_features = {
  133. .NLP_toggle = 1,
  134. };
  135. static const struct dahdi_echocan_ops my_ops = {
  136. .name = "KB1",
  137. .echocan_free = echo_can_free,
  138. .echocan_process = echo_can_process,
  139. .echocan_traintap = echo_can_traintap,
  140. .echocan_NLP_toggle = echocan_NLP_toggle,
  141. };
  142. struct ec_pvt {
  143. struct dahdi_echocan_state dahdi;
  144. /* an arbitrary ID for this echo can - this really should be settable from the calling channel... */
  145. int id;
  146. /* absolute time - aka. sample number index - essentially the number of samples since this can was init'ed */
  147. int i_d;
  148. /* Pre-computed constants */
  149. /* ---------------------- */
  150. /* Number of filter coefficents */
  151. int N_d;
  152. /* Rate of adaptation of filter */
  153. int beta2_i;
  154. /* Accumulators for power computations */
  155. /* ----------------------------------- */
  156. /* reference signal power estimate - aka. Average absolute value of y(k) */
  157. int Ly_i;
  158. /* ... */
  159. int Lu_i;
  160. /* Accumulators for signal detectors */
  161. /* --------------------------------- */
  162. /* Power estimate of the recent past of the near-end hybrid signal - aka. Short-time average of: 2 x |s(i)| */
  163. int s_tilde_i;
  164. /* Power estimate of the recent past of the far-end receive signal - aka. Short-time average of: |y(i)| */
  165. int y_tilde_i;
  166. /* Near end speech detection counter - stores Hangover counter time remaining, in samples */
  167. int HCNTR_d;
  168. /* Circular buffers and coefficients */
  169. /* --------------------------------- */
  170. /* ... */
  171. int *a_i;
  172. /* ... */
  173. short *a_s;
  174. /* Reference samples of far-end receive signal */
  175. echo_can_cb_s y_s;
  176. /* Reference samples of near-end signal */
  177. echo_can_cb_s s_s;
  178. /* Reference samples of near-end signal minus echo estimate */
  179. echo_can_cb_s u_s;
  180. /* Reference samples of far-end receive signal used to calculate short-time average */
  181. echo_can_cb_s y_tilde_s;
  182. /* Peak far-end receive signal */
  183. /* --------------------------- */
  184. /* Highest y_tilde value in the sample buffer */
  185. short max_y_tilde;
  186. /* Index of the sample containing the max_y_tilde value */
  187. int max_y_tilde_pos;
  188. #ifdef MEC2_STATS
  189. /* Storage for performance statistics */
  190. int cntr_nearend_speech_frames;
  191. int cntr_residualcorrected_frames;
  192. int cntr_residualcorrected_framesskipped;
  193. int cntr_coeff_updates;
  194. int cntr_coeff_missedupdates;
  195. int avg_Lu_i_toolow;
  196. int avg_Lu_i_ok;
  197. #endif
  198. unsigned int aggressive:1;
  199. int use_nlp;
  200. };
  201. #define dahdi_to_pvt(a) container_of(a, struct ec_pvt, dahdi)
  202. static inline void init_cb_s(echo_can_cb_s *cb, int len, void *where)
  203. {
  204. cb->buf_d = (short *)where;
  205. cb->idx_d = 0;
  206. cb->size_d = len;
  207. }
  208. static inline void add_cc_s(echo_can_cb_s *cb, short newval)
  209. {
  210. /* Can't use modulus because N+M isn't a power of two (generally) */
  211. cb->idx_d--;
  212. if (cb->idx_d < (int)0)
  213. /* Whoops - the pointer to the 'start' wrapped around so reset it to the top of the buffer */
  214. cb->idx_d += cb->size_d;
  215. /* Load two copies into memory */
  216. cb->buf_d[cb->idx_d] = newval;
  217. cb->buf_d[cb->idx_d + cb->size_d] = newval;
  218. }
  219. static inline short get_cc_s(echo_can_cb_s *cb, int pos)
  220. {
  221. /* Load two copies into memory */
  222. return cb->buf_d[cb->idx_d + pos];
  223. }
  224. static inline void init_cc(struct ec_pvt *pvt, int N, int maxy, int maxu)
  225. {
  226. char *ptr = (char *) pvt;
  227. unsigned long tmp;
  228. /* Double-word align past end of state */
  229. ptr += sizeof(*pvt);
  230. tmp = (unsigned long)ptr;
  231. tmp += 3;
  232. tmp &= ~3L;
  233. ptr = (void *)tmp;
  234. /* Reset parameters */
  235. pvt->N_d = N;
  236. pvt->beta2_i = DEFAULT_BETA1_I;
  237. /* Allocate coefficient memory */
  238. pvt->a_i = (int *) ptr;
  239. ptr += (sizeof(int) * pvt->N_d);
  240. pvt->a_s = (short *) ptr;
  241. ptr += (sizeof(short) * pvt->N_d);
  242. /* Reset Y circular buffer (short version) */
  243. init_cb_s(&pvt->y_s, maxy, ptr);
  244. ptr += (sizeof(short) * (maxy) * 2);
  245. /* Reset Sigma circular buffer (short version for FIR filter) */
  246. init_cb_s(&pvt->s_s, (1 << DEFAULT_ALPHA_ST_I), ptr);
  247. ptr += (sizeof(short) * (1 << DEFAULT_ALPHA_ST_I) * 2);
  248. init_cb_s(&pvt->u_s, maxu, ptr);
  249. ptr += (sizeof(short) * maxu * 2);
  250. /* Allocate a buffer for the reference signal power computation */
  251. init_cb_s(&pvt->y_tilde_s, pvt->N_d, ptr);
  252. /* Reset the absolute time index */
  253. pvt->i_d = (int)0;
  254. /* Reset the power computations (for y and u) */
  255. pvt->Ly_i = DEFAULT_CUTOFF_I;
  256. pvt->Lu_i = DEFAULT_CUTOFF_I;
  257. #ifdef MEC2_STATS
  258. /* set the identity */
  259. pvt->id = (int)&ptr;
  260. /* Reset performance stats */
  261. pvt->cntr_nearend_speech_frames = (int)0;
  262. pvt->cntr_residualcorrected_frames = (int)0;
  263. pvt->cntr_residualcorrected_framesskipped = (int)0;
  264. pvt->cntr_coeff_updates = (int)0;
  265. pvt->cntr_coeff_missedupdates = (int)0;
  266. pvt->avg_Lu_i_toolow = (int)0;
  267. pvt->avg_Lu_i_ok = (int)0;
  268. #endif
  269. /* Reset the near-end speech detector */
  270. pvt->s_tilde_i = (int)0;
  271. pvt->y_tilde_i = (int)0;
  272. pvt->HCNTR_d = (int)0;
  273. }
  274. static void echo_can_free(struct dahdi_chan *chan, struct dahdi_echocan_state *ec)
  275. {
  276. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  277. kfree(pvt);
  278. }
  279. static inline short sample_update(struct ec_pvt *pvt, short iref, short isig)
  280. {
  281. /* Declare local variables that are used more than once */
  282. /* ... */
  283. int k;
  284. /* ... */
  285. int rs;
  286. /* ... */
  287. short u;
  288. /* ... */
  289. int Py_i;
  290. /* ... */
  291. int two_beta_i;
  292. /* flow A on pg. 428 */
  293. /* eq. (16): high-pass filter the input to generate the next value;
  294. * push the current value into the circular buffer
  295. *
  296. * sdc_im1_d = sdc_d;
  297. * sdc_d = sig;
  298. * s_i_d = sdc_d;
  299. * s_d = s_i_d;
  300. * s_i_d = (float)(1.0 - gamma_d) * s_i_d
  301. * + (float)(0.5 * (1.0 - gamma_d)) * (sdc_d - sdc_im1_d);
  302. */
  303. /* Update the Far-end receive signal circular buffers and accumulators */
  304. /* ------------------------------------------------------------------- */
  305. /* Delete the oldest sample from the power estimate accumulator */
  306. pvt->y_tilde_i -= abs(get_cc_s(&pvt->y_s, (1 << DEFAULT_ALPHA_YT_I) - 1)) >> DEFAULT_ALPHA_YT_I;
  307. /* Add the new sample to the power estimate accumulator */
  308. pvt->y_tilde_i += abs(iref) >> DEFAULT_ALPHA_ST_I;
  309. /* Push a copy of the new sample into its circular buffer */
  310. add_cc_s(&pvt->y_s, iref);
  311. /* eq. (2): compute r in fixed-point */
  312. rs = CONVOLVE2(pvt->a_s,
  313. pvt->y_s.buf_d + pvt->y_s.idx_d,
  314. pvt->N_d);
  315. rs >>= 15;
  316. /* eq. (3): compute the output value (see figure 3) and the error
  317. * note: the error is the same as the output signal when near-end
  318. * speech is not present
  319. */
  320. u = isig - rs;
  321. /* Push a copy of the output value sample into its circular buffer */
  322. add_cc_s(&pvt->u_s, u);
  323. /* Update the Near-end hybrid signal circular buffers and accumulators */
  324. /* ------------------------------------------------------------------- */
  325. /* Delete the oldest sample from the power estimate accumulator */
  326. pvt->s_tilde_i -= abs(get_cc_s(&pvt->s_s, (1 << DEFAULT_ALPHA_ST_I) - 1));
  327. /* Add the new sample to the power estimate accumulator */
  328. pvt->s_tilde_i += abs(isig);
  329. /* Push a copy of the new sample into it's circular buffer */
  330. add_cc_s(&pvt->s_s, isig);
  331. /* Push a copy of the current short-time average of the far-end receive signal into it's circular buffer */
  332. add_cc_s(&pvt->y_tilde_s, pvt->y_tilde_i);
  333. /* flow B on pg. 428 */
  334. /* If the hangover timer isn't running then compute the new convergence factor, otherwise set Py_i to 32768 */
  335. if (!pvt->HCNTR_d) {
  336. Py_i = (pvt->Ly_i >> DEFAULT_SIGMA_LY_I) * (pvt->Ly_i >> DEFAULT_SIGMA_LY_I);
  337. Py_i >>= 15;
  338. } else {
  339. Py_i = (1 << 15);
  340. }
  341. #if 0
  342. /* Vary rate of adaptation depending on position in the file
  343. * Do not do this for the first (DEFAULT_UPDATE_TIME) secs after speech
  344. * has begun of the file to allow the echo cancellor to estimate the
  345. * channel accurately
  346. * Still needs conversion!
  347. */
  348. if (pvt->start_speech_d != 0) {
  349. if (pvt->i_d > (DEFAULT_T0 + pvt->start_speech_d)*(SAMPLE_FREQ)) {
  350. pvt->beta2_d = max_cc_float(MIN_BETA, DEFAULT_BETA1 * exp((-1/DEFAULT_TAU)*((pvt->i_d/(float)SAMPLE_FREQ) - DEFAULT_T0 - pvt->start_speech_d)));
  351. }
  352. } else {
  353. pvt->beta2_d = DEFAULT_BETA1;
  354. }
  355. #endif
  356. /* Fixed point, inverted */
  357. pvt->beta2_i = DEFAULT_BETA1_I;
  358. /* Fixed point version, inverted */
  359. two_beta_i = (pvt->beta2_i * Py_i) >> 15;
  360. if (!two_beta_i)
  361. two_beta_i++;
  362. /* Update the Suppressed signal power estimate accumulator */
  363. /* ------------------------------------------------------- */
  364. /* Delete the oldest sample from the power estimate accumulator */
  365. pvt->Lu_i -= abs(get_cc_s(&pvt->u_s, (1 << DEFAULT_SIGMA_LU_I) - 1));
  366. /* Add the new sample to the power estimate accumulator */
  367. pvt->Lu_i += abs(u);
  368. /* Update the Far-end reference signal power estimate accumulator */
  369. /* -------------------------------------------------------------- */
  370. /* eq. (10): update power estimate of the reference */
  371. /* Delete the oldest sample from the power estimate accumulator */
  372. pvt->Ly_i -= abs(get_cc_s(&pvt->y_s, (1 << DEFAULT_SIGMA_LY_I) - 1)) ;
  373. /* Add the new sample to the power estimate accumulator */
  374. pvt->Ly_i += abs(iref);
  375. if (pvt->Ly_i < DEFAULT_CUTOFF_I)
  376. pvt->Ly_i = DEFAULT_CUTOFF_I;
  377. /* Update the Peak far-end receive signal detected */
  378. /* ----------------------------------------------- */
  379. if (pvt->y_tilde_i > pvt->max_y_tilde) {
  380. /* New highest y_tilde with full life */
  381. pvt->max_y_tilde = pvt->y_tilde_i;
  382. pvt->max_y_tilde_pos = pvt->N_d - 1;
  383. } else if (--pvt->max_y_tilde_pos < 0) {
  384. /* Time to find new max y tilde... */
  385. pvt->max_y_tilde = MAX16(pvt->y_tilde_s.buf_d + pvt->y_tilde_s.idx_d, pvt->N_d, &pvt->max_y_tilde_pos);
  386. }
  387. /* Determine if near end speech was detected in this sample */
  388. /* -------------------------------------------------------- */
  389. if (((pvt->s_tilde_i >> (DEFAULT_ALPHA_ST_I - 1)) > pvt->max_y_tilde)
  390. && (pvt->max_y_tilde > 0)) {
  391. /* Then start the Hangover counter */
  392. pvt->HCNTR_d = DEFAULT_HANGT;
  393. #ifdef MEC2_STATS_DETAILED
  394. printk(KERN_INFO "Reset near end speech timer with: s_tilde_i %d, stmnt %d, max_y_tilde %d\n", pvt->s_tilde_i, (pvt->s_tilde_i >> (DEFAULT_ALPHA_ST_I - 1)), pvt->max_y_tilde);
  395. #endif
  396. #ifdef MEC2_STATS
  397. ++pvt->cntr_nearend_speech_frames;
  398. #endif
  399. } else if (pvt->HCNTR_d > (int)0) {
  400. /* otherwise, if it's still non-zero, decrement the Hangover counter by one sample */
  401. #ifdef MEC2_STATS
  402. ++pvt->cntr_nearend_speech_frames;
  403. #endif
  404. pvt->HCNTR_d--;
  405. }
  406. /* Update coefficients if no near-end speech in this sample (ie. HCNTR_d = 0)
  407. * and we have enough signal to bother trying to update.
  408. * --------------------------------------------------------------------------
  409. */
  410. if (!pvt->HCNTR_d && /* no near-end speech present */
  411. !(pvt->i_d % DEFAULT_M)) { /* we only update on every DEFAULM_M'th sample from the stream */
  412. if (pvt->Lu_i > MIN_UPDATE_THRESH_I) { /* there is sufficient energy above the noise floor to contain meaningful data */
  413. /* so loop over all the filter coefficients */
  414. #ifdef MEC2_STATS_DETAILED
  415. printk(KERN_INFO "updating coefficients with: pvt->Lu_i %9d\n", pvt->Lu_i);
  416. #endif
  417. #ifdef MEC2_STATS
  418. pvt->avg_Lu_i_ok = pvt->avg_Lu_i_ok + pvt->Lu_i;
  419. ++pvt->cntr_coeff_updates;
  420. #endif
  421. for (k = 0; k < pvt->N_d; k++) {
  422. /* eq. (7): compute an expectation over M_d samples */
  423. int grad2;
  424. grad2 = CONVOLVE2(pvt->u_s.buf_d + pvt->u_s.idx_d,
  425. pvt->y_s.buf_d + pvt->y_s.idx_d + k,
  426. DEFAULT_M);
  427. /* eq. (7): update the coefficient */
  428. pvt->a_i[k] += grad2 / two_beta_i;
  429. pvt->a_s[k] = pvt->a_i[k] >> 16;
  430. }
  431. } else {
  432. #ifdef MEC2_STATS_DETAILED
  433. printk(KERN_INFO "insufficient signal to update coefficients pvt->Lu_i %5d < %5d\n", pvt->Lu_i, MIN_UPDATE_THRESH_I);
  434. #endif
  435. #ifdef MEC2_STATS
  436. pvt->avg_Lu_i_toolow = pvt->avg_Lu_i_toolow + pvt->Lu_i;
  437. ++pvt->cntr_coeff_missedupdates;
  438. #endif
  439. }
  440. }
  441. /* paragraph below eq. (15): if no near-end speech in the sample and
  442. * the reference signal power estimate > cutoff threshold
  443. * then perform residual error suppression
  444. */
  445. #ifdef MEC2_STATS_DETAILED
  446. if (pvt->HCNTR_d == 0)
  447. printk(KERN_INFO "possibly correcting frame with pvt->Ly_i %9d pvt->Lu_i %9d and expression %d\n", pvt->Ly_i, pvt->Lu_i, (pvt->Ly_i/(pvt->Lu_i + 1)));
  448. #endif
  449. #ifndef NO_ECHO_SUPPRESSOR
  450. if (pvt->use_nlp) {
  451. if (pvt->aggressive) {
  452. if ((pvt->HCNTR_d < AGGRESSIVE_HCNTR) && (pvt->Ly_i > (pvt->Lu_i << 1))) {
  453. for (k = 0; k < 2; k++) {
  454. u = u * (pvt->Lu_i >> DEFAULT_SIGMA_LU_I) / ((pvt->Ly_i >> (DEFAULT_SIGMA_LY_I)) + 1);
  455. }
  456. #ifdef MEC2_STATS_DETAILED
  457. printk(KERN_INFO "aggresively correcting frame with pvt->Ly_i %9d pvt->Lu_i %9d expression %d\n", pvt->Ly_i, pvt->Lu_i, (pvt->Ly_i/(pvt->Lu_i + 1)));
  458. #endif
  459. #ifdef MEC2_STATS
  460. ++pvt->cntr_residualcorrected_frames;
  461. #endif
  462. }
  463. } else {
  464. if (pvt->HCNTR_d == 0) {
  465. if ((pvt->Ly_i/(pvt->Lu_i + 1)) > DEFAULT_SUPPR_I) {
  466. for (k = 0; k < 1; k++) {
  467. u = u * (pvt->Lu_i >> DEFAULT_SIGMA_LU_I) / ((pvt->Ly_i >> (DEFAULT_SIGMA_LY_I + 2)) + 1);
  468. }
  469. #ifdef MEC2_STATS_DETAILED
  470. printk(KERN_INFO "correcting frame with pvt->Ly_i %9d pvt->Lu_i %9d expression %d\n", pvt->Ly_i, pvt->Lu_i, (pvt->Ly_i/(pvt->Lu_i + 1)));
  471. #endif
  472. #ifdef MEC2_STATS
  473. ++pvt->cntr_residualcorrected_frames;
  474. #endif
  475. }
  476. #ifdef MEC2_STATS
  477. else {
  478. ++pvt->cntr_residualcorrected_framesskipped;
  479. }
  480. #endif
  481. }
  482. }
  483. }
  484. #endif
  485. #if 0
  486. /* This will generate a non-linear supression factor, once converted */
  487. if ((pvt->HCNTR_d == 0) &&
  488. ((pvt->Lu_d/pvt->Ly_d) < DEFAULT_SUPPR) &&
  489. (pvt->Lu_d/pvt->Ly_d > EC_MIN_DB_VALUE)) {
  490. suppr_factor = (10 / (float)(SUPPR_FLOOR - SUPPR_CEIL)) * log(pvt->Lu_d/pvt->Ly_d)
  491. - SUPPR_CEIL / (float)(SUPPR_FLOOR - SUPPR_CEIL);
  492. u_suppr = pow(10.0, (suppr_factor) * RES_SUPR_FACTOR / 10.0) * u_suppr;
  493. }
  494. #endif
  495. #ifdef MEC2_STATS
  496. /* Periodically dump performance stats */
  497. if ((pvt->i_d % MEC2_STATS) == 0) {
  498. /* make sure to avoid div0's! */
  499. if (pvt->cntr_coeff_missedupdates > 0)
  500. pvt->avg_Lu_i_toolow = (int)(pvt->avg_Lu_i_toolow / pvt->cntr_coeff_missedupdates);
  501. else
  502. pvt->avg_Lu_i_toolow = -1;
  503. if (pvt->cntr_coeff_updates > 0)
  504. pvt->avg_Lu_i_ok = (pvt->avg_Lu_i_ok / pvt->cntr_coeff_updates);
  505. else
  506. pvt->avg_Lu_i_ok = -1;
  507. printk( KERN_INFO "%d: Near end speech: %5d Residuals corrected/skipped: %5d/%5d Coefficients updated ok/low sig: %3d/%3d Lu_i avg ok/low sig %6d/%5d\n",
  508. pvt->id,
  509. pvt->cntr_nearend_speech_frames,
  510. pvt->cntr_residualcorrected_frames, pvt->cntr_residualcorrected_framesskipped,
  511. pvt->cntr_coeff_updates, pvt->cntr_coeff_missedupdates,
  512. pvt->avg_Lu_i_ok, pvt->avg_Lu_i_toolow);
  513. pvt->cntr_nearend_speech_frames = 0;
  514. pvt->cntr_residualcorrected_frames = 0;
  515. pvt->cntr_residualcorrected_framesskipped = 0;
  516. pvt->cntr_coeff_updates = 0;
  517. pvt->cntr_coeff_missedupdates = 0;
  518. pvt->avg_Lu_i_ok = 0;
  519. pvt->avg_Lu_i_toolow = 0;
  520. }
  521. #endif
  522. /* Increment the sample index and return the corrected sample */
  523. pvt->i_d++;
  524. return u;
  525. }
  526. static void echo_can_process(struct dahdi_echocan_state *ec, short *isig, const short *iref, u32 size)
  527. {
  528. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  529. u32 x;
  530. short result;
  531. for (x = 0; x < size; x++) {
  532. result = sample_update(pvt, *iref, *isig);
  533. *isig++ = result;
  534. ++iref;
  535. }
  536. }
  537. static int echo_can_create(struct dahdi_chan *chan, struct dahdi_echocanparams *ecp,
  538. struct dahdi_echocanparam *p, struct dahdi_echocan_state **ec)
  539. {
  540. int maxy;
  541. int maxu;
  542. size_t size;
  543. unsigned int x;
  544. char *c;
  545. struct ec_pvt *pvt;
  546. maxy = ecp->tap_length + DEFAULT_M;
  547. maxu = DEFAULT_M;
  548. if (maxy < (1 << DEFAULT_ALPHA_YT_I))
  549. maxy = (1 << DEFAULT_ALPHA_YT_I);
  550. if (maxy < (1 << DEFAULT_SIGMA_LY_I))
  551. maxy = (1 << DEFAULT_SIGMA_LY_I);
  552. if (maxu < (1 << DEFAULT_SIGMA_LU_I))
  553. maxu = (1 << DEFAULT_SIGMA_LU_I);
  554. size = sizeof(*ec) +
  555. 4 + /* align */
  556. sizeof(int) * ecp->tap_length + /* a_i */
  557. sizeof(short) * ecp->tap_length + /* a_s */
  558. 2 * sizeof(short) * (maxy) + /* y_s */
  559. 2 * sizeof(short) * (1 << DEFAULT_ALPHA_ST_I) + /* s_s */
  560. 2 * sizeof(short) * (maxu) + /* u_s */
  561. 2 * sizeof(short) * ecp->tap_length; /* y_tilde_s */
  562. pvt = kzalloc(size, GFP_KERNEL);
  563. if (!pvt)
  564. return -ENOMEM;
  565. pvt->dahdi.ops = &my_ops;
  566. pvt->aggressive = aggressive;
  567. pvt->dahdi.features = my_features;
  568. for (x = 0; x < ecp->param_count; x++) {
  569. for (c = p[x].name; *c; c++)
  570. *c = tolower(*c);
  571. if (!strcmp(p[x].name, "aggressive")) {
  572. pvt->aggressive = p[x].value ? 1 : 0;
  573. } else {
  574. printk(KERN_WARNING "Unknown parameter supplied to KB1 echo canceler: '%s'\n", p[x].name);
  575. kfree(pvt);
  576. return -EINVAL;
  577. }
  578. }
  579. init_cc(pvt, ecp->tap_length, maxy, maxu);
  580. /* Non-linear processor - a fancy way to say "zap small signals, to avoid
  581. accumulating noise". */
  582. pvt->use_nlp = TRUE;
  583. *ec = &pvt->dahdi;
  584. return 0;
  585. }
  586. static int echo_can_traintap(struct dahdi_echocan_state *ec, int pos, short val)
  587. {
  588. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  589. /* Set the hangover counter to the length of the can to
  590. * avoid adjustments occuring immediately after initial forced training
  591. */
  592. pvt->HCNTR_d = pvt->N_d << 1;
  593. if (pos >= pvt->N_d)
  594. return 1;
  595. pvt->a_i[pos] = val << 17;
  596. pvt->a_s[pos] = val << 1;
  597. if (++pos >= pvt->N_d)
  598. return 1;
  599. return 0;
  600. }
  601. static void echocan_NLP_toggle(struct dahdi_echocan_state *ec, unsigned int enable)
  602. {
  603. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  604. pvt->use_nlp = enable ? 1 : 0;
  605. }
  606. static int __init mod_init(void)
  607. {
  608. if (dahdi_register_echocan_factory(&my_factory)) {
  609. module_printk(KERN_ERR, "could not register with DAHDI core\n");
  610. return -EPERM;
  611. }
  612. module_printk(KERN_NOTICE, "Registered echo canceler '%s'\n", my_factory.name);
  613. return 0;
  614. }
  615. static void __exit mod_exit(void)
  616. {
  617. dahdi_unregister_echocan_factory(&my_factory);
  618. }
  619. module_param(debug, int, S_IRUGO | S_IWUSR);
  620. module_param(aggressive, int, S_IRUGO | S_IWUSR);
  621. MODULE_DESCRIPTION("DAHDI 'KB1' Echo Canceler");
  622. MODULE_AUTHOR("Kris Boutilier");
  623. MODULE_LICENSE("GPL v2");
  624. module_init(mod_init);
  625. module_exit(mod_exit);