Staging: echo: fix up remaining checkpatch.pl issues
[linux/fpc-iii.git] / drivers / staging / echo / echo.c
blobd05642eec54b5f6c9f38e621f8f0f9d1ff397b00
1 /*
2 * SpanDSP - a series of DSP components for telephony
4 * echo.c - A line echo canceller. This code is being developed
5 * against and partially complies with G168.
7 * Written by Steve Underwood <steveu@coppice.org>
8 * and David Rowe <david_at_rowetel_dot_com>
10 * Copyright (C) 2001, 2003 Steve Underwood, 2007 David Rowe
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.
16 * All rights reserved.
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.
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.
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.
32 /*! \file */
34 /* Implementation Notes
35 David Rowe
36 April 2007
38 This code started life as Steve's NLMS algorithm with a tap
39 rotation algorithm to handle divergence during double talk. I
40 added a Geigel Double Talk Detector (DTD) [2] and performed some
41 G168 tests. However I had trouble meeting the G168 requirements,
42 especially for double talk - there were always cases where my DTD
43 failed, for example where near end speech was under the 6dB
44 threshold required for declaring double talk.
46 So I tried a two path algorithm [1], which has so far given better
47 results. The original tap rotation/Geigel algorithm is available
48 in SVN http://svn.rowetel.com/software/oslec/tags/before_16bit.
49 It's probably possible to make it work if some one wants to put some
50 serious work into it.
52 At present no special treatment is provided for tones, which
53 generally cause NLMS algorithms to diverge. Initial runs of a
54 subset of the G168 tests for tones (e.g ./echo_test 6) show the
55 current algorithm is passing OK, which is kind of surprising. The
56 full set of tests needs to be performed to confirm this result.
58 One other interesting change is that I have managed to get the NLMS
59 code to work with 16 bit coefficients, rather than the original 32
60 bit coefficents. This reduces the MIPs and storage required.
61 I evaulated the 16 bit port using g168_tests.sh and listening tests
62 on 4 real-world samples.
64 I also attempted the implementation of a block based NLMS update
65 [2] but although this passes g168_tests.sh it didn't converge well
66 on the real-world samples. I have no idea why, perhaps a scaling
67 problem. The block based code is also available in SVN
68 http://svn.rowetel.com/software/oslec/tags/before_16bit. If this
69 code can be debugged, it will lead to further reduction in MIPS, as
70 the block update code maps nicely onto DSP instruction sets (it's a
71 dot product) compared to the current sample-by-sample update.
73 Steve also has some nice notes on echo cancellers in echo.h
75 References:
77 [1] Ochiai, Areseki, and Ogihara, "Echo Canceller with Two Echo
78 Path Models", IEEE Transactions on communications, COM-25,
79 No. 6, June
80 1977.
81 http://www.rowetel.com/images/echo/dual_path_paper.pdf
83 [2] The classic, very useful paper that tells you how to
84 actually build a real world echo canceller:
85 Messerschmitt, Hedberg, Cole, Haoui, Winship, "Digital Voice
86 Echo Canceller with a TMS320020,
87 http://www.rowetel.com/images/echo/spra129.pdf
89 [3] I have written a series of blog posts on this work, here is
90 Part 1: http://www.rowetel.com/blog/?p=18
92 [4] The source code http://svn.rowetel.com/software/oslec/
94 [5] A nice reference on LMS filters:
95 http://en.wikipedia.org/wiki/Least_mean_squares_filter
97 Credits:
99 Thanks to Steve Underwood, Jean-Marc Valin, and Ramakrishnan
100 Muthukrishnan for their suggestions and email discussions. Thanks
101 also to those people who collected echo samples for me such as
102 Mark, Pawel, and Pavel.
105 #include <linux/kernel.h>
106 #include <linux/module.h>
107 #include <linux/slab.h>
109 #include "bit_operations.h"
110 #include "echo.h"
112 #define MIN_TX_POWER_FOR_ADAPTION 64
113 #define MIN_RX_POWER_FOR_ADAPTION 64
114 #define DTD_HANGOVER 600 /* 600 samples, or 75ms */
115 #define DC_LOG2BETA 3 /* log2() of DC filter Beta */
118 /* adapting coeffs using the traditional stochastic descent (N)LMS algorithm */
120 #ifdef __bfin__
121 static inline void lms_adapt_bg(struct oslec_state *ec, int clean,
122 int shift)
124 int i, j;
125 int offset1;
126 int offset2;
127 int factor;
128 int exp;
129 int16_t *phist;
130 int n;
132 if (shift > 0)
133 factor = clean << shift;
134 else
135 factor = clean >> -shift;
137 /* Update the FIR taps */
139 offset2 = ec->curr_pos;
140 offset1 = ec->taps - offset2;
141 phist = &ec->fir_state_bg.history[offset2];
143 /* st: and en: help us locate the assembler in echo.s */
145 /* asm("st:"); */
146 n = ec->taps;
147 for (i = 0, j = offset2; i < n; i++, j++) {
148 exp = *phist++ * factor;
149 ec->fir_taps16[1][i] += (int16_t) ((exp + (1 << 14)) >> 15);
151 /* asm("en:"); */
153 /* Note the asm for the inner loop above generated by Blackfin gcc
154 4.1.1 is pretty good (note even parallel instructions used):
156 R0 = W [P0++] (X);
157 R0 *= R2;
158 R0 = R0 + R3 (NS) ||
159 R1 = W [P1] (X) ||
160 nop;
161 R0 >>>= 15;
162 R0 = R0 + R1;
163 W [P1++] = R0;
165 A block based update algorithm would be much faster but the
166 above can't be improved on much. Every instruction saved in
167 the loop above is 2 MIPs/ch! The for loop above is where the
168 Blackfin spends most of it's time - about 17 MIPs/ch measured
169 with speedtest.c with 256 taps (32ms). Write-back and
170 Write-through cache gave about the same performance.
175 IDEAS for further optimisation of lms_adapt_bg():
177 1/ The rounding is quite costly. Could we keep as 32 bit coeffs
178 then make filter pluck the MS 16-bits of the coeffs when filtering?
179 However this would lower potential optimisation of filter, as I
180 think the dual-MAC architecture requires packed 16 bit coeffs.
182 2/ Block based update would be more efficient, as per comments above,
183 could use dual MAC architecture.
185 3/ Look for same sample Blackfin LMS code, see if we can get dual-MAC
186 packing.
188 4/ Execute the whole e/c in a block of say 20ms rather than sample
189 by sample. Processing a few samples every ms is inefficient.
192 #else
193 static inline void lms_adapt_bg(struct oslec_state *ec, int clean,
194 int shift)
196 int i;
198 int offset1;
199 int offset2;
200 int factor;
201 int exp;
203 if (shift > 0)
204 factor = clean << shift;
205 else
206 factor = clean >> -shift;
208 /* Update the FIR taps */
210 offset2 = ec->curr_pos;
211 offset1 = ec->taps - offset2;
213 for (i = ec->taps - 1; i >= offset1; i--) {
214 exp = (ec->fir_state_bg.history[i - offset1] * factor);
215 ec->fir_taps16[1][i] += (int16_t) ((exp + (1 << 14)) >> 15);
217 for (; i >= 0; i--) {
218 exp = (ec->fir_state_bg.history[i + offset2] * factor);
219 ec->fir_taps16[1][i] += (int16_t) ((exp + (1 << 14)) >> 15);
222 #endif
224 struct oslec_state *oslec_create(int len, int adaption_mode)
226 struct oslec_state *ec;
227 int i;
229 ec = kzalloc(sizeof(*ec), GFP_KERNEL);
230 if (!ec)
231 return NULL;
233 ec->taps = len;
234 ec->log2taps = top_bit(len);
235 ec->curr_pos = ec->taps - 1;
237 for (i = 0; i < 2; i++) {
238 ec->fir_taps16[i] =
239 kcalloc(ec->taps, sizeof(int16_t), GFP_KERNEL);
240 if (!ec->fir_taps16[i])
241 goto error_oom;
244 fir16_create(&ec->fir_state, ec->fir_taps16[0], ec->taps);
245 fir16_create(&ec->fir_state_bg, ec->fir_taps16[1], ec->taps);
247 for (i = 0; i < 5; i++)
248 ec->xvtx[i] = ec->yvtx[i] = ec->xvrx[i] = ec->yvrx[i] = 0;
250 ec->cng_level = 1000;
251 oslec_adaption_mode(ec, adaption_mode);
253 ec->snapshot = kcalloc(ec->taps, sizeof(int16_t), GFP_KERNEL);
254 if (!ec->snapshot)
255 goto error_oom;
257 ec->cond_met = 0;
258 ec->Pstates = 0;
259 ec->Ltxacc = ec->Lrxacc = ec->Lcleanacc = ec->Lclean_bgacc = 0;
260 ec->Ltx = ec->Lrx = ec->Lclean = ec->Lclean_bg = 0;
261 ec->tx_1 = ec->tx_2 = ec->rx_1 = ec->rx_2 = 0;
262 ec->Lbgn = ec->Lbgn_acc = 0;
263 ec->Lbgn_upper = 200;
264 ec->Lbgn_upper_acc = ec->Lbgn_upper << 13;
266 return ec;
268 error_oom:
269 for (i = 0; i < 2; i++)
270 kfree(ec->fir_taps16[i]);
272 kfree(ec);
273 return NULL;
275 EXPORT_SYMBOL_GPL(oslec_create);
277 void oslec_free(struct oslec_state *ec)
279 int i;
281 fir16_free(&ec->fir_state);
282 fir16_free(&ec->fir_state_bg);
283 for (i = 0; i < 2; i++)
284 kfree(ec->fir_taps16[i]);
285 kfree(ec->snapshot);
286 kfree(ec);
288 EXPORT_SYMBOL_GPL(oslec_free);
290 void oslec_adaption_mode(struct oslec_state *ec, int adaption_mode)
292 ec->adaption_mode = adaption_mode;
294 EXPORT_SYMBOL_GPL(oslec_adaption_mode);
296 void oslec_flush(struct oslec_state *ec)
298 int i;
300 ec->Ltxacc = ec->Lrxacc = ec->Lcleanacc = ec->Lclean_bgacc = 0;
301 ec->Ltx = ec->Lrx = ec->Lclean = ec->Lclean_bg = 0;
302 ec->tx_1 = ec->tx_2 = ec->rx_1 = ec->rx_2 = 0;
304 ec->Lbgn = ec->Lbgn_acc = 0;
305 ec->Lbgn_upper = 200;
306 ec->Lbgn_upper_acc = ec->Lbgn_upper << 13;
308 ec->nonupdate_dwell = 0;
310 fir16_flush(&ec->fir_state);
311 fir16_flush(&ec->fir_state_bg);
312 ec->fir_state.curr_pos = ec->taps - 1;
313 ec->fir_state_bg.curr_pos = ec->taps - 1;
314 for (i = 0; i < 2; i++)
315 memset(ec->fir_taps16[i], 0, ec->taps * sizeof(int16_t));
317 ec->curr_pos = ec->taps - 1;
318 ec->Pstates = 0;
320 EXPORT_SYMBOL_GPL(oslec_flush);
322 void oslec_snapshot(struct oslec_state *ec)
324 memcpy(ec->snapshot, ec->fir_taps16[0], ec->taps * sizeof(int16_t));
326 EXPORT_SYMBOL_GPL(oslec_snapshot);
328 /* Dual Path Echo Canceller */
330 int16_t oslec_update(struct oslec_state *ec, int16_t tx, int16_t rx)
332 int32_t echo_value;
333 int clean_bg;
334 int tmp, tmp1;
337 * Input scaling was found be required to prevent problems when tx
338 * starts clipping. Another possible way to handle this would be the
339 * filter coefficent scaling.
342 ec->tx = tx;
343 ec->rx = rx;
344 tx >>= 1;
345 rx >>= 1;
348 * Filter DC, 3dB point is 160Hz (I think), note 32 bit precision
349 * required otherwise values do not track down to 0. Zero at DC, Pole
350 * at (1-Beta) only real axis. Some chip sets (like Si labs) don't
351 * need this, but something like a $10 X100P card does. Any DC really
352 * slows down convergence.
354 * Note: removes some low frequency from the signal, this reduces the
355 * speech quality when listening to samples through headphones but may
356 * not be obvious through a telephone handset.
358 * Note that the 3dB frequency in radians is approx Beta, e.g. for Beta
359 * = 2^(-3) = 0.125, 3dB freq is 0.125 rads = 159Hz.
362 if (ec->adaption_mode & ECHO_CAN_USE_RX_HPF) {
363 tmp = rx << 15;
364 #if 1
366 * Make sure the gain of the HPF is 1.0. This can still
367 * saturate a little under impulse conditions, and it might
368 * roll to 32768 and need clipping on sustained peak level
369 * signals. However, the scale of such clipping is small, and
370 * the error due to any saturation should not markedly affect
371 * the downstream processing.
373 tmp -= (tmp >> 4);
374 #endif
375 ec->rx_1 += -(ec->rx_1 >> DC_LOG2BETA) + tmp - ec->rx_2;
378 * hard limit filter to prevent clipping. Note that at this
379 * stage rx should be limited to +/- 16383 due to right shift
380 * above
382 tmp1 = ec->rx_1 >> 15;
383 if (tmp1 > 16383)
384 tmp1 = 16383;
385 if (tmp1 < -16383)
386 tmp1 = -16383;
387 rx = tmp1;
388 ec->rx_2 = tmp;
391 /* Block average of power in the filter states. Used for
392 adaption power calculation. */
395 int new, old;
397 /* efficient "out with the old and in with the new" algorithm so
398 we don't have to recalculate over the whole block of
399 samples. */
400 new = (int)tx * (int)tx;
401 old = (int)ec->fir_state.history[ec->fir_state.curr_pos] *
402 (int)ec->fir_state.history[ec->fir_state.curr_pos];
403 ec->Pstates +=
404 ((new - old) + (1 << (ec->log2taps-1))) >> ec->log2taps;
405 if (ec->Pstates < 0)
406 ec->Pstates = 0;
409 /* Calculate short term average levels using simple single pole IIRs */
411 ec->Ltxacc += abs(tx) - ec->Ltx;
412 ec->Ltx = (ec->Ltxacc + (1 << 4)) >> 5;
413 ec->Lrxacc += abs(rx) - ec->Lrx;
414 ec->Lrx = (ec->Lrxacc + (1 << 4)) >> 5;
416 /* Foreground filter */
418 ec->fir_state.coeffs = ec->fir_taps16[0];
419 echo_value = fir16(&ec->fir_state, tx);
420 ec->clean = rx - echo_value;
421 ec->Lcleanacc += abs(ec->clean) - ec->Lclean;
422 ec->Lclean = (ec->Lcleanacc + (1 << 4)) >> 5;
424 /* Background filter */
426 echo_value = fir16(&ec->fir_state_bg, tx);
427 clean_bg = rx - echo_value;
428 ec->Lclean_bgacc += abs(clean_bg) - ec->Lclean_bg;
429 ec->Lclean_bg = (ec->Lclean_bgacc + (1 << 4)) >> 5;
431 /* Background Filter adaption */
433 /* Almost always adap bg filter, just simple DT and energy
434 detection to minimise adaption in cases of strong double talk.
435 However this is not critical for the dual path algorithm.
437 ec->factor = 0;
438 ec->shift = 0;
439 if ((ec->nonupdate_dwell == 0)) {
440 int P, logP, shift;
442 /* Determine:
444 f = Beta * clean_bg_rx/P ------ (1)
446 where P is the total power in the filter states.
448 The Boffins have shown that if we obey (1) we converge
449 quickly and avoid instability.
451 The correct factor f must be in Q30, as this is the fixed
452 point format required by the lms_adapt_bg() function,
453 therefore the scaled version of (1) is:
455 (2^30) * f = (2^30) * Beta * clean_bg_rx/P
456 factor = (2^30) * Beta * clean_bg_rx/P ----- (2)
458 We have chosen Beta = 0.25 by experiment, so:
460 factor = (2^30) * (2^-2) * clean_bg_rx/P
462 (30 - 2 - log2(P))
463 factor = clean_bg_rx 2 ----- (3)
465 To avoid a divide we approximate log2(P) as top_bit(P),
466 which returns the position of the highest non-zero bit in
467 P. This approximation introduces an error as large as a
468 factor of 2, but the algorithm seems to handle it OK.
470 Come to think of it a divide may not be a big deal on a
471 modern DSP, so its probably worth checking out the cycles
472 for a divide versus a top_bit() implementation.
475 P = MIN_TX_POWER_FOR_ADAPTION + ec->Pstates;
476 logP = top_bit(P) + ec->log2taps;
477 shift = 30 - 2 - logP;
478 ec->shift = shift;
480 lms_adapt_bg(ec, clean_bg, shift);
483 /* very simple DTD to make sure we dont try and adapt with strong
484 near end speech */
486 ec->adapt = 0;
487 if ((ec->Lrx > MIN_RX_POWER_FOR_ADAPTION) && (ec->Lrx > ec->Ltx))
488 ec->nonupdate_dwell = DTD_HANGOVER;
489 if (ec->nonupdate_dwell)
490 ec->nonupdate_dwell--;
492 /* Transfer logic */
494 /* These conditions are from the dual path paper [1], I messed with
495 them a bit to improve performance. */
497 if ((ec->adaption_mode & ECHO_CAN_USE_ADAPTION) &&
498 (ec->nonupdate_dwell == 0) &&
499 /* (ec->Lclean_bg < 0.875*ec->Lclean) */
500 (8 * ec->Lclean_bg < 7 * ec->Lclean) &&
501 /* (ec->Lclean_bg < 0.125*ec->Ltx) */
502 (8 * ec->Lclean_bg < ec->Ltx)) {
503 if (ec->cond_met == 6) {
505 * BG filter has had better results for 6 consecutive
506 * samples
508 ec->adapt = 1;
509 memcpy(ec->fir_taps16[0], ec->fir_taps16[1],
510 ec->taps * sizeof(int16_t));
511 } else
512 ec->cond_met++;
513 } else
514 ec->cond_met = 0;
516 /* Non-Linear Processing */
518 ec->clean_nlp = ec->clean;
519 if (ec->adaption_mode & ECHO_CAN_USE_NLP) {
521 * Non-linear processor - a fancy way to say "zap small
522 * signals, to avoid residual echo due to (uLaw/ALaw)
523 * non-linearity in the channel.".
526 if ((16 * ec->Lclean < ec->Ltx)) {
528 * Our e/c has improved echo by at least 24 dB (each
529 * factor of 2 is 6dB, so 2*2*2*2=16 is the same as
530 * 6+6+6+6=24dB)
532 if (ec->adaption_mode & ECHO_CAN_USE_CNG) {
533 ec->cng_level = ec->Lbgn;
536 * Very elementary comfort noise generation.
537 * Just random numbers rolled off very vaguely
538 * Hoth-like. DR: This noise doesn't sound
539 * quite right to me - I suspect there are some
540 * overlfow issues in the filtering as it's too
541 * "crackly".
542 * TODO: debug this, maybe just play noise at
543 * high level or look at spectrum.
546 ec->cng_rndnum =
547 1664525U * ec->cng_rndnum + 1013904223U;
548 ec->cng_filter =
549 ((ec->cng_rndnum & 0xFFFF) - 32768 +
550 5 * ec->cng_filter) >> 3;
551 ec->clean_nlp =
552 (ec->cng_filter * ec->cng_level * 8) >> 14;
554 } else if (ec->adaption_mode & ECHO_CAN_USE_CLIP) {
555 /* This sounds much better than CNG */
556 if (ec->clean_nlp > ec->Lbgn)
557 ec->clean_nlp = ec->Lbgn;
558 if (ec->clean_nlp < -ec->Lbgn)
559 ec->clean_nlp = -ec->Lbgn;
560 } else {
562 * just mute the residual, doesn't sound very
563 * good, used mainly in G168 tests
565 ec->clean_nlp = 0;
567 } else {
569 * Background noise estimator. I tried a few
570 * algorithms here without much luck. This very simple
571 * one seems to work best, we just average the level
572 * using a slow (1 sec time const) filter if the
573 * current level is less than a (experimentally
574 * derived) constant. This means we dont include high
575 * level signals like near end speech. When combined
576 * with CNG or especially CLIP seems to work OK.
578 if (ec->Lclean < 40) {
579 ec->Lbgn_acc += abs(ec->clean) - ec->Lbgn;
580 ec->Lbgn = (ec->Lbgn_acc + (1 << 11)) >> 12;
585 /* Roll around the taps buffer */
586 if (ec->curr_pos <= 0)
587 ec->curr_pos = ec->taps;
588 ec->curr_pos--;
590 if (ec->adaption_mode & ECHO_CAN_DISABLE)
591 ec->clean_nlp = rx;
593 /* Output scaled back up again to match input scaling */
595 return (int16_t) ec->clean_nlp << 1;
597 EXPORT_SYMBOL_GPL(oslec_update);
599 /* This function is seperated from the echo canceller is it is usually called
600 as part of the tx process. See rx HP (DC blocking) filter above, it's
601 the same design.
603 Some soft phones send speech signals with a lot of low frequency
604 energy, e.g. down to 20Hz. This can make the hybrid non-linear
605 which causes the echo canceller to fall over. This filter can help
606 by removing any low frequency before it gets to the tx port of the
607 hybrid.
609 It can also help by removing and DC in the tx signal. DC is bad
610 for LMS algorithms.
612 This is one of the classic DC removal filters, adjusted to provide
613 sufficient bass rolloff to meet the above requirement to protect hybrids
614 from things that upset them. The difference between successive samples
615 produces a lousy HPF, and then a suitably placed pole flattens things out.
616 The final result is a nicely rolled off bass end. The filtering is
617 implemented with extended fractional precision, which noise shapes things,
618 giving very clean DC removal.
621 int16_t oslec_hpf_tx(struct oslec_state *ec, int16_t tx)
623 int tmp, tmp1;
625 if (ec->adaption_mode & ECHO_CAN_USE_TX_HPF) {
626 tmp = tx << 15;
627 #if 1
629 * Make sure the gain of the HPF is 1.0. The first can still
630 * saturate a little under impulse conditions, and it might
631 * roll to 32768 and need clipping on sustained peak level
632 * signals. However, the scale of such clipping is small, and
633 * the error due to any saturation should not markedly affect
634 * the downstream processing.
636 tmp -= (tmp >> 4);
637 #endif
638 ec->tx_1 += -(ec->tx_1 >> DC_LOG2BETA) + tmp - ec->tx_2;
639 tmp1 = ec->tx_1 >> 15;
640 if (tmp1 > 32767)
641 tmp1 = 32767;
642 if (tmp1 < -32767)
643 tmp1 = -32767;
644 tx = tmp1;
645 ec->tx_2 = tmp;
648 return tx;
650 EXPORT_SYMBOL_GPL(oslec_hpf_tx);
652 MODULE_LICENSE("GPL");
653 MODULE_AUTHOR("David Rowe");
654 MODULE_DESCRIPTION("Open Source Line Echo Canceller");
655 MODULE_VERSION("0.3.0");