dahdi_echocan_mg2.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. /*
  2. * ECHO_CAN_MG2
  3. *
  4. * by Michael Gernoth
  5. *
  6. * Based upon kb1ec.h and mec2.h
  7. *
  8. * Copyright (C) 2002-2012, 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 ABS(a) abs(a!=-32768?a:-32767)
  43. #define RESTORE_COEFFS {\
  44. int x;\
  45. memcpy(pvt->a_i, pvt->c_i, pvt->N_d*sizeof(int));\
  46. for (x = 0; x < pvt->N_d; x++) {\
  47. pvt->a_s[x] = pvt->a_i[x] >> 16;\
  48. }\
  49. pvt->backup = BACKUP;\
  50. }
  51. /* Uncomment to provide summary statistics for overall echo can performance every 4000 samples */
  52. /* #define MEC2_STATS 4000 */
  53. /* Uncomment to generate per-sample statistics - this will severely degrade system performance and audio quality */
  54. /* #define MEC2_STATS_DETAILED */
  55. /* Uncomment to generate per-call DC bias offset messages */
  56. /* #define MEC2_DCBIAS_MESSAGE */
  57. /* Get optimized routines for math */
  58. #include "arith.h"
  59. /*
  60. Important constants for tuning mg2 echo can
  61. */
  62. /* Convergence (aka. adaptation) speed -- higher means slower */
  63. #define DEFAULT_BETA1_I 2048
  64. /* Constants for various power computations */
  65. #define DEFAULT_SIGMA_LY_I 7
  66. #define DEFAULT_SIGMA_LU_I 7
  67. #define DEFAULT_ALPHA_ST_I 5 /* near-end speech detection sensitivity factor */
  68. #define DEFAULT_ALPHA_YT_I 5
  69. #define DEFAULT_CUTOFF_I 128
  70. /* Define the near-end speech hangover counter: if near-end speech
  71. * is declared, hcntr is set equal to hangt (see pg. 432)
  72. */
  73. #define DEFAULT_HANGT 600 /* in samples, so 600 samples = 75ms */
  74. /* define the residual error suppression threshold */
  75. #define DEFAULT_SUPPR_I 16 /* 16 = -24db */
  76. /* This is the minimum reference signal power estimate level
  77. * that will result in filter adaptation.
  78. * If this is too low then background noise will cause the filter
  79. * coefficients to constantly be updated.
  80. */
  81. #define MIN_UPDATE_THRESH_I 2048
  82. /* The number of samples used to update coefficients using the
  83. * the block update method (M). It should be related back to the
  84. * length of the echo can.
  85. * ie. it only updates coefficients when (sample number MOD default_m) = 0
  86. *
  87. * Getting this wrong may cause an oops. Consider yourself warned!
  88. */
  89. #define DEFAULT_M 16 /* every 16th sample */
  90. /* If AGGRESSIVE supression is enabled, then we start cancelling residual
  91. * echos again even while there is potentially the very end of a near-side
  92. * signal present.
  93. * This defines how many samples of DEFAULT_HANGT can remain before we
  94. * kick back in
  95. */
  96. #define AGGRESSIVE_HCNTR 160 /* in samples, so 160 samples = 20ms */
  97. /* Treat sample as error if it has a different sign as the
  98. * input signal and is this number larger in ABS() as
  99. * the input-signal */
  100. #define MAX_SIGN_ERROR 3000
  101. /* Number of coefficients really used for calculating the
  102. * simulated echo. The value specifies how many of the
  103. * biggest coefficients are used for calculating rs.
  104. * This helps on long echo-tails by artificially limiting
  105. * the number of coefficients for the calculation and
  106. * preventing overflows.
  107. * Comment this to deactivate the code */
  108. #define USED_COEFFS 64
  109. /* Backup coefficients every this number of samples */
  110. #define BACKUP 256
  111. /***************************************************************/
  112. /* The following knobs are not implemented in the current code */
  113. /* we need a dynamic level of suppression varying with the ratio of the
  114. power of the echo to the power of the reference signal this is
  115. done so that we have a smoother background.
  116. we have a higher suppression when the power ratio is closer to
  117. suppr_ceil and reduces logarithmically as we approach suppr_floor.
  118. */
  119. #define SUPPR_FLOOR -64
  120. #define SUPPR_CEIL -24
  121. /* in a second departure, we calculate the residual error suppression
  122. * as a percentage of the reference signal energy level. The threshold
  123. * is defined in terms of dB below the reference signal.
  124. */
  125. #define RES_SUPR_FACTOR -20
  126. #define DC_NORMALIZE
  127. #ifndef NULL
  128. #define NULL 0
  129. #endif
  130. #ifndef FALSE
  131. #define FALSE 0
  132. #endif
  133. #ifndef TRUE
  134. #define TRUE (!FALSE)
  135. #endif
  136. /* Generic circular buffer definition */
  137. typedef struct {
  138. /* Pointer to the relative 'start' of the buffer */
  139. int idx_d;
  140. /* The absolute size of the buffer */
  141. int size_d;
  142. /* The actual sample - twice as large as we need, however we do store values at idx_d and idx_d+size_d */
  143. short *buf_d;
  144. } echo_can_cb_s;
  145. static int echo_can_create(struct dahdi_chan *chan, struct dahdi_echocanparams *ecp,
  146. struct dahdi_echocanparam *p, struct dahdi_echocan_state **ec);
  147. static void echo_can_free(struct dahdi_chan *chan, struct dahdi_echocan_state *ec);
  148. static void echo_can_process(struct dahdi_echocan_state *ec, short *isig, const short *iref, u32 size);
  149. static int echo_can_traintap(struct dahdi_echocan_state *ec, int pos, short val);
  150. static void echocan_NLP_toggle(struct dahdi_echocan_state *ec, unsigned int enable);
  151. static const char *name = "MG2";
  152. static const char *ec_name(const struct dahdi_chan *chan) { return name; }
  153. static const struct dahdi_echocan_factory my_factory = {
  154. .get_name = ec_name,
  155. .owner = THIS_MODULE,
  156. .echocan_create = echo_can_create,
  157. };
  158. static const struct dahdi_echocan_features my_features = {
  159. .NLP_toggle = 1,
  160. };
  161. static const struct dahdi_echocan_ops my_ops = {
  162. .echocan_free = echo_can_free,
  163. .echocan_process = echo_can_process,
  164. .echocan_traintap = echo_can_traintap,
  165. .echocan_NLP_toggle = echocan_NLP_toggle,
  166. };
  167. struct ec_pvt {
  168. struct dahdi_echocan_state dahdi;
  169. /* an arbitrary ID for this echo can - this really should be settable from the calling channel... */
  170. int id;
  171. /* absolute time - aka. sample number index - essentially the number of samples since this can was init'ed */
  172. int i_d;
  173. /* Pre-computed constants */
  174. /* ---------------------- */
  175. /* Number of filter coefficents */
  176. int N_d;
  177. /* Rate of adaptation of filter */
  178. int beta2_i;
  179. /* Accumulators for power computations */
  180. /* ----------------------------------- */
  181. /* reference signal power estimate - aka. Average absolute value of y(k) */
  182. int Ly_i;
  183. /* ... */
  184. int Lu_i;
  185. /* Accumulators for signal detectors */
  186. /* --------------------------------- */
  187. /* Power estimate of the recent past of the near-end hybrid signal - aka. Short-time average of: 2 x |s(i)| */
  188. int s_tilde_i;
  189. /* Power estimate of the recent past of the far-end receive signal - aka. Short-time average of: |y(i)| */
  190. int y_tilde_i;
  191. /* Near end speech detection counter - stores Hangover counter time remaining, in samples */
  192. int HCNTR_d;
  193. /* Circular buffers and coefficients */
  194. /* --------------------------------- */
  195. /* ... */
  196. int *a_i;
  197. /* ... */
  198. short *a_s;
  199. /* Backups */
  200. int *b_i;
  201. int *c_i;
  202. /* Reference samples of far-end receive signal */
  203. echo_can_cb_s y_s;
  204. /* Reference samples of near-end signal */
  205. echo_can_cb_s s_s;
  206. /* Reference samples of near-end signal minus echo estimate */
  207. echo_can_cb_s u_s;
  208. /* Reference samples of far-end receive signal used to calculate short-time average */
  209. echo_can_cb_s y_tilde_s;
  210. /* Peak far-end receive signal */
  211. /* --------------------------- */
  212. /* Highest y_tilde value in the sample buffer */
  213. short max_y_tilde;
  214. /* Index of the sample containing the max_y_tilde value */
  215. int max_y_tilde_pos;
  216. #ifdef MEC2_STATS
  217. /* Storage for performance statistics */
  218. int cntr_nearend_speech_frames;
  219. int cntr_residualcorrected_frames;
  220. int cntr_residualcorrected_framesskipped;
  221. int cntr_coeff_updates;
  222. int cntr_coeff_missedupdates;
  223. int avg_Lu_i_toolow;
  224. int avg_Lu_i_ok;
  225. #endif
  226. unsigned int aggressive:1;
  227. short lastsig;
  228. int lastcount;
  229. int backup;
  230. #ifdef DC_NORMALIZE
  231. int dc_estimate;
  232. #endif
  233. int use_nlp;
  234. };
  235. #define dahdi_to_pvt(a) container_of(a, struct ec_pvt, dahdi)
  236. static inline void init_cb_s(echo_can_cb_s *cb, int len, void *where)
  237. {
  238. cb->buf_d = (short *)where;
  239. cb->idx_d = 0;
  240. cb->size_d = len;
  241. }
  242. static inline void add_cc_s(echo_can_cb_s *cb, short newval)
  243. {
  244. /* Can't use modulus because N+M isn't a power of two (generally) */
  245. cb->idx_d--;
  246. if (cb->idx_d < (int)0)
  247. /* Whoops - the pointer to the 'start' wrapped around so reset it to the top of the buffer */
  248. cb->idx_d += cb->size_d;
  249. /* Load two copies into memory */
  250. cb->buf_d[cb->idx_d] = newval;
  251. cb->buf_d[cb->idx_d + cb->size_d] = newval;
  252. }
  253. static inline short get_cc_s(echo_can_cb_s *cb, int pos)
  254. {
  255. /* Load two copies into memory */
  256. return cb->buf_d[cb->idx_d + pos];
  257. }
  258. static inline void init_cc(struct ec_pvt *pvt, int N, int maxy, int maxu)
  259. {
  260. char *ptr = (char *) pvt;
  261. unsigned long tmp;
  262. /* Double-word align past end of state */
  263. ptr += sizeof(*pvt);
  264. tmp = (unsigned long)ptr;
  265. tmp += 3;
  266. tmp &= ~3L;
  267. ptr = (void *)tmp;
  268. /* Reset parameters */
  269. pvt->N_d = N;
  270. pvt->beta2_i = DEFAULT_BETA1_I;
  271. /* Allocate coefficient memory */
  272. pvt->a_i = (int *) ptr;
  273. ptr += (sizeof(int) * pvt->N_d);
  274. pvt->a_s = (short *) ptr;
  275. ptr += (sizeof(short) * pvt->N_d);
  276. /* Allocate backup memory */
  277. pvt->b_i = (int *) ptr;
  278. ptr += (sizeof(int) * pvt->N_d);
  279. pvt->c_i = (int *) ptr;
  280. ptr += (sizeof(int) * pvt->N_d);
  281. /* Reset Y circular buffer (short version) */
  282. init_cb_s(&pvt->y_s, maxy, ptr);
  283. ptr += (sizeof(short) * (maxy) * 2);
  284. /* Reset Sigma circular buffer (short version for FIR filter) */
  285. init_cb_s(&pvt->s_s, (1 << DEFAULT_ALPHA_ST_I), ptr);
  286. ptr += (sizeof(short) * (1 << DEFAULT_ALPHA_ST_I) * 2);
  287. init_cb_s(&pvt->u_s, maxu, ptr);
  288. ptr += (sizeof(short) * maxu * 2);
  289. /* Allocate a buffer for the reference signal power computation */
  290. init_cb_s(&pvt->y_tilde_s, pvt->N_d, ptr);
  291. /* Reset the absolute time index */
  292. pvt->i_d = (int)0;
  293. /* Reset the power computations (for y and u) */
  294. pvt->Ly_i = DEFAULT_CUTOFF_I;
  295. pvt->Lu_i = DEFAULT_CUTOFF_I;
  296. #ifdef MEC2_STATS
  297. /* set the identity */
  298. pvt->id = (int)&ptr;
  299. /* Reset performance stats */
  300. pvt->cntr_nearend_speech_frames = (int)0;
  301. pvt->cntr_residualcorrected_frames = (int)0;
  302. pvt->cntr_residualcorrected_framesskipped = (int)0;
  303. pvt->cntr_coeff_updates = (int)0;
  304. pvt->cntr_coeff_missedupdates = (int)0;
  305. pvt->avg_Lu_i_toolow = (int)0;
  306. pvt->avg_Lu_i_ok = (int)0;
  307. #endif
  308. /* Reset the near-end speech detector */
  309. pvt->s_tilde_i = (int)0;
  310. pvt->y_tilde_i = (int)0;
  311. pvt->HCNTR_d = (int)0;
  312. }
  313. static void echo_can_free(struct dahdi_chan *chan, struct dahdi_echocan_state *ec)
  314. {
  315. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  316. #if defined(DC_NORMALIZE) && defined(MEC2_DCBIAS_MESSAGE)
  317. printk(KERN_INFO "EC: DC bias calculated: %d V\n", pvt->dc_estimate >> 15);
  318. #endif
  319. kfree(pvt);
  320. }
  321. #ifdef DC_NORMALIZE
  322. static inline short dc_removal(int *dc_estimate, short samp)
  323. {
  324. *dc_estimate += ((((int)samp << 15) - *dc_estimate) >> 9);
  325. return samp - (*dc_estimate >> 15);
  326. }
  327. #endif
  328. static inline short sample_update(struct ec_pvt *pvt, short iref, short isig)
  329. {
  330. /* Declare local variables that are used more than once */
  331. /* ... */
  332. int k;
  333. /* ... */
  334. int rs;
  335. /* ... */
  336. short u;
  337. /* ... */
  338. int Py_i;
  339. /* ... */
  340. int two_beta_i;
  341. #ifdef DC_NORMALIZE
  342. isig = dc_removal(&pvt->dc_estimate, isig);
  343. #endif
  344. /* flow A on pg. 428 */
  345. /* eq. (16): high-pass filter the input to generate the next value;
  346. * push the current value into the circular buffer
  347. *
  348. * sdc_im1_d = sdc_d;
  349. * sdc_d = sig;
  350. * s_i_d = sdc_d;
  351. * s_d = s_i_d;
  352. * s_i_d = (float)(1.0 - gamma_d) * s_i_d
  353. * + (float)(0.5 * (1.0 - gamma_d)) * (sdc_d - sdc_im1_d);
  354. */
  355. /* Update the Far-end receive signal circular buffers and accumulators */
  356. /* ------------------------------------------------------------------- */
  357. /* Delete the oldest sample from the power estimate accumulator */
  358. pvt->y_tilde_i -= abs(get_cc_s(&pvt->y_s, (1 << DEFAULT_ALPHA_YT_I) - 1)) >> DEFAULT_ALPHA_YT_I;
  359. /* Add the new sample to the power estimate accumulator */
  360. pvt->y_tilde_i += abs(iref) >> DEFAULT_ALPHA_ST_I;
  361. /* Push a copy of the new sample into its circular buffer */
  362. add_cc_s(&pvt->y_s, iref);
  363. /* eq. (2): compute r in fixed-point */
  364. rs = CONVOLVE2(pvt->a_s,
  365. pvt->y_s.buf_d + pvt->y_s.idx_d,
  366. pvt->N_d);
  367. rs >>= 15;
  368. if (pvt->lastsig == isig) {
  369. pvt->lastcount++;
  370. } else {
  371. pvt->lastcount = 0;
  372. pvt->lastsig = isig;
  373. }
  374. if (isig == 0) {
  375. u = 0;
  376. } else if (pvt->lastcount > 255) {
  377. /* We have seen the same input-signal more than 255 times,
  378. * we should pass it through uncancelled, as we are likely on hold */
  379. u = isig;
  380. } else {
  381. int sign_error;
  382. if (rs < -32768) {
  383. rs = -32768;
  384. pvt->HCNTR_d = DEFAULT_HANGT;
  385. RESTORE_COEFFS;
  386. } else if (rs > 32767) {
  387. rs = 32767;
  388. pvt->HCNTR_d = DEFAULT_HANGT;
  389. RESTORE_COEFFS;
  390. }
  391. sign_error = ABS(rs) - ABS(isig);
  392. if (ABS(sign_error) > MAX_SIGN_ERROR)
  393. {
  394. rs = 0;
  395. RESTORE_COEFFS;
  396. }
  397. /* eq. (3): compute the output value (see figure 3) and the error
  398. * note: the error is the same as the output signal when near-end
  399. * speech is not present
  400. */
  401. u = isig - rs;
  402. if (u / isig < 0)
  403. u = isig - (rs >> 1);
  404. }
  405. /* Push a copy of the output value sample into its circular buffer */
  406. add_cc_s(&pvt->u_s, u);
  407. if (!pvt->backup) {
  408. /* Backup coefficients periodically */
  409. pvt->backup = BACKUP;
  410. memcpy(pvt->c_i, pvt->b_i, pvt->N_d*sizeof(int));
  411. memcpy(pvt->b_i, pvt->a_i, pvt->N_d*sizeof(int));
  412. } else
  413. pvt->backup--;
  414. /* Update the Near-end hybrid signal circular buffers and accumulators */
  415. /* ------------------------------------------------------------------- */
  416. /* Delete the oldest sample from the power estimate accumulator */
  417. pvt->s_tilde_i -= abs(get_cc_s(&pvt->s_s, (1 << DEFAULT_ALPHA_ST_I) - 1));
  418. /* Add the new sample to the power estimate accumulator */
  419. pvt->s_tilde_i += abs(isig);
  420. /* Push a copy of the new sample into it's circular buffer */
  421. add_cc_s(&pvt->s_s, isig);
  422. /* Push a copy of the current short-time average of the far-end receive signal into it's circular buffer */
  423. add_cc_s(&pvt->y_tilde_s, pvt->y_tilde_i);
  424. /* flow B on pg. 428 */
  425. /* If the hangover timer isn't running then compute the new convergence factor, otherwise set Py_i to 32768 */
  426. if (!pvt->HCNTR_d) {
  427. Py_i = (pvt->Ly_i >> DEFAULT_SIGMA_LY_I) * (pvt->Ly_i >> DEFAULT_SIGMA_LY_I);
  428. Py_i >>= 15;
  429. } else {
  430. Py_i = (1 << 15);
  431. }
  432. #if 0
  433. /* Vary rate of adaptation depending on position in the file
  434. * Do not do this for the first (DEFAULT_UPDATE_TIME) secs after speech
  435. * has begun of the file to allow the echo cancellor to estimate the
  436. * channel accurately
  437. * Still needs conversion!
  438. */
  439. if (pvt->start_speech_d != 0) {
  440. if (pvt->i_d > (DEFAULT_T0 + pvt->start_speech_d)*(SAMPLE_FREQ)) {
  441. 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)));
  442. }
  443. } else {
  444. pvt->beta2_d = DEFAULT_BETA1;
  445. }
  446. #endif
  447. /* Fixed point, inverted */
  448. pvt->beta2_i = DEFAULT_BETA1_I;
  449. /* Fixed point version, inverted */
  450. two_beta_i = (pvt->beta2_i * Py_i) >> 15;
  451. if (!two_beta_i)
  452. two_beta_i++;
  453. /* Update the Suppressed signal power estimate accumulator */
  454. /* ------------------------------------------------------- */
  455. /* Delete the oldest sample from the power estimate accumulator */
  456. pvt->Lu_i -= abs(get_cc_s(&pvt->u_s, (1 << DEFAULT_SIGMA_LU_I) - 1));
  457. /* Add the new sample to the power estimate accumulator */
  458. pvt->Lu_i += abs(u);
  459. /* Update the Far-end reference signal power estimate accumulator */
  460. /* -------------------------------------------------------------- */
  461. /* eq. (10): update power estimate of the reference */
  462. /* Delete the oldest sample from the power estimate accumulator */
  463. pvt->Ly_i -= abs(get_cc_s(&pvt->y_s, (1 << DEFAULT_SIGMA_LY_I) - 1)) ;
  464. /* Add the new sample to the power estimate accumulator */
  465. pvt->Ly_i += abs(iref);
  466. if (pvt->Ly_i < DEFAULT_CUTOFF_I)
  467. pvt->Ly_i = DEFAULT_CUTOFF_I;
  468. /* Update the Peak far-end receive signal detected */
  469. /* ----------------------------------------------- */
  470. if (pvt->y_tilde_i > pvt->max_y_tilde) {
  471. /* New highest y_tilde with full life */
  472. pvt->max_y_tilde = pvt->y_tilde_i;
  473. pvt->max_y_tilde_pos = pvt->N_d - 1;
  474. } else if (--pvt->max_y_tilde_pos < 0) {
  475. /* Time to find new max y tilde... */
  476. 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);
  477. }
  478. /* Determine if near end speech was detected in this sample */
  479. /* -------------------------------------------------------- */
  480. if (((pvt->s_tilde_i >> (DEFAULT_ALPHA_ST_I - 1)) > pvt->max_y_tilde)
  481. && (pvt->max_y_tilde > 0)) {
  482. /* Then start the Hangover counter */
  483. pvt->HCNTR_d = DEFAULT_HANGT;
  484. RESTORE_COEFFS;
  485. #ifdef MEC2_STATS_DETAILED
  486. 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);
  487. #endif
  488. #ifdef MEC2_STATS
  489. ++pvt->cntr_nearend_speech_frames;
  490. #endif
  491. } else if (pvt->HCNTR_d > (int)0) {
  492. /* otherwise, if it's still non-zero, decrement the Hangover counter by one sample */
  493. #ifdef MEC2_STATS
  494. ++pvt->cntr_nearend_speech_frames;
  495. #endif
  496. pvt->HCNTR_d--;
  497. }
  498. /* Update coefficients if no near-end speech in this sample (ie. HCNTR_d = 0)
  499. * and we have enough signal to bother trying to update.
  500. * --------------------------------------------------------------------------
  501. */
  502. if (!pvt->HCNTR_d && /* no near-end speech present */
  503. !(pvt->i_d % DEFAULT_M)) { /* we only update on every DEFAULM_M'th sample from the stream */
  504. if (pvt->Lu_i > MIN_UPDATE_THRESH_I) { /* there is sufficient energy above the noise floor to contain meaningful data */
  505. /* so loop over all the filter coefficients */
  506. #ifdef USED_COEFFS
  507. int max_coeffs[USED_COEFFS];
  508. int *pos;
  509. if (pvt->N_d > USED_COEFFS)
  510. memset(max_coeffs, 0, USED_COEFFS*sizeof(int));
  511. #endif
  512. #ifdef MEC2_STATS_DETAILED
  513. printk(KERN_INFO "updating coefficients with: pvt->Lu_i %9d\n", pvt->Lu_i);
  514. #endif
  515. #ifdef MEC2_STATS
  516. pvt->avg_Lu_i_ok = pvt->avg_Lu_i_ok + pvt->Lu_i;
  517. ++pvt->cntr_coeff_updates;
  518. #endif
  519. for (k = 0; k < pvt->N_d; k++) {
  520. /* eq. (7): compute an expectation over M_d samples */
  521. int grad2;
  522. grad2 = CONVOLVE2(pvt->u_s.buf_d + pvt->u_s.idx_d,
  523. pvt->y_s.buf_d + pvt->y_s.idx_d + k,
  524. DEFAULT_M);
  525. /* eq. (7): update the coefficient */
  526. pvt->a_i[k] += grad2 / two_beta_i;
  527. pvt->a_s[k] = pvt->a_i[k] >> 16;
  528. #ifdef USED_COEFFS
  529. if (pvt->N_d > USED_COEFFS) {
  530. if (abs(pvt->a_i[k]) > max_coeffs[USED_COEFFS-1]) {
  531. /* More or less insertion-sort... */
  532. pos = max_coeffs;
  533. while (*pos > abs(pvt->a_i[k]))
  534. pos++;
  535. if (*pos > max_coeffs[USED_COEFFS-1])
  536. memmove(pos+1, pos, (USED_COEFFS-(pos-max_coeffs)-1)*sizeof(int));
  537. *pos = abs(pvt->a_i[k]);
  538. }
  539. }
  540. #endif
  541. }
  542. #ifdef USED_COEFFS
  543. /* Filter out irrelevant coefficients */
  544. if (pvt->N_d > USED_COEFFS)
  545. for (k = 0; k < pvt->N_d; k++)
  546. if (abs(pvt->a_i[k]) < max_coeffs[USED_COEFFS-1])
  547. pvt->a_i[k] = pvt->a_s[k] = 0;
  548. #endif
  549. } else {
  550. #ifdef MEC2_STATS_DETAILED
  551. printk(KERN_INFO "insufficient signal to update coefficients pvt->Lu_i %5d < %5d\n", pvt->Lu_i, MIN_UPDATE_THRESH_I);
  552. #endif
  553. #ifdef MEC2_STATS
  554. pvt->avg_Lu_i_toolow = pvt->avg_Lu_i_toolow + pvt->Lu_i;
  555. ++pvt->cntr_coeff_missedupdates;
  556. #endif
  557. }
  558. }
  559. /* paragraph below eq. (15): if no near-end speech in the sample and
  560. * the reference signal power estimate > cutoff threshold
  561. * then perform residual error suppression
  562. */
  563. #ifdef MEC2_STATS_DETAILED
  564. if (pvt->HCNTR_d == 0)
  565. 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)));
  566. #endif
  567. #ifndef NO_ECHO_SUPPRESSOR
  568. if (pvt->use_nlp) {
  569. if (pvt->aggressive) {
  570. if ((pvt->HCNTR_d < AGGRESSIVE_HCNTR) && (pvt->Ly_i > (pvt->Lu_i << 1))) {
  571. for (k = 0; k < 2; k++) {
  572. u = u * (pvt->Lu_i >> DEFAULT_SIGMA_LU_I) / ((pvt->Ly_i >> (DEFAULT_SIGMA_LY_I)) + 1);
  573. }
  574. #ifdef MEC2_STATS_DETAILED
  575. 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)));
  576. #endif
  577. #ifdef MEC2_STATS
  578. ++pvt->cntr_residualcorrected_frames;
  579. #endif
  580. }
  581. } else {
  582. if (pvt->HCNTR_d == 0) {
  583. if ((pvt->Ly_i/(pvt->Lu_i + 1)) > DEFAULT_SUPPR_I) {
  584. for (k = 0; k < 1; k++) {
  585. u = u * (pvt->Lu_i >> DEFAULT_SIGMA_LU_I) / ((pvt->Ly_i >> (DEFAULT_SIGMA_LY_I + 2)) + 1);
  586. }
  587. #ifdef MEC2_STATS_DETAILED
  588. 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)));
  589. #endif
  590. #ifdef MEC2_STATS
  591. ++pvt->cntr_residualcorrected_frames;
  592. #endif
  593. }
  594. #ifdef MEC2_STATS
  595. else {
  596. ++pvt->cntr_residualcorrected_framesskipped;
  597. }
  598. #endif
  599. }
  600. }
  601. }
  602. #endif
  603. #if 0
  604. /* This will generate a non-linear supression factor, once converted */
  605. if ((pvt->HCNTR_d == 0) &&
  606. ((pvt->Lu_d/pvt->Ly_d) < DEFAULT_SUPPR) &&
  607. (pvt->Lu_d/pvt->Ly_d > EC_MIN_DB_VALUE)) {
  608. suppr_factor = (10 / (float)(SUPPR_FLOOR - SUPPR_CEIL)) * log(pvt->Lu_d/pvt->Ly_d)
  609. - SUPPR_CEIL / (float)(SUPPR_FLOOR - SUPPR_CEIL);
  610. u_suppr = pow(10.0, (suppr_factor) * RES_SUPR_FACTOR / 10.0) * u_suppr;
  611. }
  612. #endif
  613. #ifdef MEC2_STATS
  614. /* Periodically dump performance stats */
  615. if ((pvt->i_d % MEC2_STATS) == 0) {
  616. /* make sure to avoid div0's! */
  617. if (pvt->cntr_coeff_missedupdates > 0)
  618. pvt->avg_Lu_i_toolow = (int)(pvt->avg_Lu_i_toolow / pvt->cntr_coeff_missedupdates);
  619. else
  620. pvt->avg_Lu_i_toolow = -1;
  621. if (pvt->cntr_coeff_updates > 0)
  622. pvt->avg_Lu_i_ok = (pvt->avg_Lu_i_ok / pvt->cntr_coeff_updates);
  623. else
  624. pvt->avg_Lu_i_ok = -1;
  625. 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",
  626. pvt->id,
  627. pvt->cntr_nearend_speech_frames,
  628. pvt->cntr_residualcorrected_frames, pvt->cntr_residualcorrected_framesskipped,
  629. pvt->cntr_coeff_updates, pvt->cntr_coeff_missedupdates,
  630. pvt->avg_Lu_i_ok, pvt->avg_Lu_i_toolow);
  631. pvt->cntr_nearend_speech_frames = 0;
  632. pvt->cntr_residualcorrected_frames = 0;
  633. pvt->cntr_residualcorrected_framesskipped = 0;
  634. pvt->cntr_coeff_updates = 0;
  635. pvt->cntr_coeff_missedupdates = 0;
  636. pvt->avg_Lu_i_ok = 0;
  637. pvt->avg_Lu_i_toolow = 0;
  638. }
  639. #endif
  640. /* Increment the sample index and return the corrected sample */
  641. pvt->i_d++;
  642. return u;
  643. }
  644. static void echo_can_process(struct dahdi_echocan_state *ec, short *isig, const short *iref, u32 size)
  645. {
  646. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  647. u32 x;
  648. short result;
  649. for (x = 0; x < size; x++) {
  650. result = sample_update(pvt, *iref, *isig);
  651. *isig++ = result;
  652. ++iref;
  653. }
  654. }
  655. static int echo_can_create(struct dahdi_chan *chan, struct dahdi_echocanparams *ecp,
  656. struct dahdi_echocanparam *p, struct dahdi_echocan_state **ec)
  657. {
  658. int maxy;
  659. int maxu;
  660. size_t size;
  661. unsigned int x;
  662. char *c;
  663. struct ec_pvt *pvt;
  664. maxy = ecp->tap_length + DEFAULT_M;
  665. maxu = DEFAULT_M;
  666. if (maxy < (1 << DEFAULT_ALPHA_YT_I))
  667. maxy = (1 << DEFAULT_ALPHA_YT_I);
  668. if (maxy < (1 << DEFAULT_SIGMA_LY_I))
  669. maxy = (1 << DEFAULT_SIGMA_LY_I);
  670. if (maxu < (1 << DEFAULT_SIGMA_LU_I))
  671. maxu = (1 << DEFAULT_SIGMA_LU_I);
  672. size = sizeof(**ec) +
  673. 4 + /* align */
  674. sizeof(int) * ecp->tap_length + /* a_i */
  675. sizeof(short) * ecp->tap_length + /* a_s */
  676. sizeof(int) * ecp->tap_length + /* b_i */
  677. sizeof(int) * ecp->tap_length + /* c_i */
  678. 2 * sizeof(short) * (maxy) + /* y_s */
  679. 2 * sizeof(short) * (1 << DEFAULT_ALPHA_ST_I) + /* s_s */
  680. 2 * sizeof(short) * (maxu) + /* u_s */
  681. 2 * sizeof(short) * ecp->tap_length; /* y_tilde_s */
  682. pvt = kzalloc(size, GFP_KERNEL);
  683. if (!pvt)
  684. return -ENOMEM;
  685. pvt->dahdi.ops = &my_ops;
  686. pvt->aggressive = aggressive;
  687. pvt->dahdi.features = my_features;
  688. for (x = 0; x < ecp->param_count; x++) {
  689. for (c = p[x].name; *c; c++)
  690. *c = tolower(*c);
  691. if (!strcmp(p[x].name, "aggressive")) {
  692. pvt->aggressive = p[x].value ? 1 : 0;
  693. } else {
  694. printk(KERN_WARNING "Unknown parameter supplied to MG2 echo canceler: '%s'\n", p[x].name);
  695. kfree(pvt);
  696. return -EINVAL;
  697. }
  698. }
  699. init_cc(pvt, ecp->tap_length, maxy, maxu);
  700. /* Non-linear processor - a fancy way to say "zap small signals, to avoid
  701. accumulating noise". */
  702. pvt->use_nlp = TRUE;
  703. *ec = &pvt->dahdi;
  704. return 0;
  705. }
  706. static int echo_can_traintap(struct dahdi_echocan_state *ec, int pos, short val)
  707. {
  708. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  709. /* Set the hangover counter to the length of the can to
  710. * avoid adjustments occuring immediately after initial forced training
  711. */
  712. pvt->HCNTR_d = pvt->N_d << 1;
  713. if (pos >= pvt->N_d) {
  714. memcpy(pvt->b_i, pvt->a_i, pvt->N_d*sizeof(int));
  715. memcpy(pvt->c_i, pvt->a_i, pvt->N_d*sizeof(int));
  716. return 1;
  717. }
  718. pvt->a_i[pos] = val << 17;
  719. pvt->a_s[pos] = val << 1;
  720. if (++pos >= pvt->N_d) {
  721. memcpy(pvt->b_i, pvt->a_i, pvt->N_d*sizeof(int));
  722. memcpy(pvt->c_i, pvt->a_i, pvt->N_d*sizeof(int));
  723. return 1;
  724. }
  725. return 0;
  726. }
  727. static void echocan_NLP_toggle(struct dahdi_echocan_state *ec, unsigned int enable)
  728. {
  729. struct ec_pvt *pvt = dahdi_to_pvt(ec);
  730. pvt->use_nlp = enable ? 1 : 0;
  731. }
  732. static int __init mod_init(void)
  733. {
  734. if (dahdi_register_echocan_factory(&my_factory)) {
  735. module_printk(KERN_ERR, "could not register with DAHDI core\n");
  736. return -EPERM;
  737. }
  738. module_printk(KERN_NOTICE, "Registered echo canceler '%s'\n",
  739. my_factory.get_name(NULL));
  740. return 0;
  741. }
  742. static void __exit mod_exit(void)
  743. {
  744. dahdi_unregister_echocan_factory(&my_factory);
  745. }
  746. module_param(debug, int, S_IRUGO | S_IWUSR);
  747. module_param(aggressive, int, S_IRUGO | S_IWUSR);
  748. MODULE_DESCRIPTION("DAHDI 'MG2' Echo Canceler");
  749. MODULE_AUTHOR("Michael Gernoth");
  750. MODULE_LICENSE("GPL v2");
  751. module_init(mod_init);
  752. module_exit(mod_exit);