From 51c2341027a7676c3e044e511da82dceab5e816d Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 15:55:06 +0200 Subject: [PATCH 01/17] audio: webrtc_aec: tune the float AEC delay and reference level The float AEC trusts the reported sound card delay, and the hardcoded 20 ms was larger than the real reference to echo delay, so the echo arrived before the aligned reference. The filter update is also clamped per block, so a quiet reference made convergence take tens of seconds. Add Kconfig options for the reported delay, default 0 ms, and for a linear reference gain, default 16. The echo reference latency also varies by a few ms between stream starts, so add a microphone delay line, default 8 ms, that keeps the echo causal. This gives a stable delay estimate and about 6 - 13 dB ERLE with music. Add optional debug traces of the AEC delay estimate with a coarse energy envelope cross-correlation lag, the reference and microphone peak levels, and once per second the ERLE and levels over frames with an active reference. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/Kconfig | 73 ++++++- src/audio/webrtc_aec/README.md | 9 +- src/audio/webrtc_aec/webrtc_aec-aec.c | 274 +++++++++++++++++++++++++- 3 files changed, 336 insertions(+), 20 deletions(-) diff --git a/src/audio/webrtc_aec/Kconfig b/src/audio/webrtc_aec/Kconfig index a1b00b60ce0c..828e13fbb5c9 100644 --- a/src/audio/webrtc_aec/Kconfig +++ b/src/audio/webrtc_aec/Kconfig @@ -75,6 +75,70 @@ config WEBRTC_AEC_FILTER_LEN_MS reverb tails) at the cost of increased memory and CPU. Valid values: 32, 64, 128. +config WEBRTC_AEC_DELAY_MS + int "Nominal echo path / soundcard buffer delay in ms" + range 0 15 if WEBRTC_AEC_BACKEND_FLOAT + range 0 500 + default 0 if WEBRTC_AEC_BACKEND_FLOAT + default 20 + help + Nominal delay in milliseconds between echo reference playback and + microphone capture. Used by AECm/Float AEC (msInSndCardBuf) and by + AEC3 when WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST is enabled. + + For the Float AEC this is the delay from a reference sample + entering the AEC to its echo appearing in the microphone input of + the AEC, for the shortest (direct) acoustic path. The linear + filter covers this delay plus 48 ms, so a value larger than the + real delay makes the echo non-causal and prevents cancellation. + Use the "delay median" trace to tune it. + +config WEBRTC_AEC_REF_GAIN + int "Float AEC echo reference linear gain" + range 1 256 + default 16 + depends on WEBRTC_AEC_BACKEND_FLOAT + help + Linear gain applied to the echo reference in float before the + AEC. The filter update is clamped per block, so convergence time + grows with the echo-to-reference level ratio. A quiet reference + with loud echo converges in tens of seconds; raising the + reference level shortens that. No clipping risk, the AEC is float. + +config WEBRTC_AEC_MIC_DELAY_MS + int "Float AEC microphone delay in ms" + range 0 20 + default 8 + depends on WEBRTC_AEC_BACKEND_FLOAT + help + Delay the microphone signal before the AEC. The AEC cannot cancel + echo that arrives before the reference, so if the reference path + latency varies by a few ms between stream starts, a mic delay of + a few ms keeps the echo causal. Adds the same latency to the + capture. + +config WEBRTC_AEC_DELAY_DEBUG + bool "Float AEC echo delay estimation trace" + depends on WEBRTC_AEC_BACKEND_FLOAT + help + Run the AEC signal based delay estimator and trace every 5 s the + echo delay median, spread and the reference and microphone peak + levels. Use it to tune WEBRTC_AEC_DELAY_MS and WEBRTC_AEC_REF_GAIN. + Also traces a coarse delay from the reference and microphone + 10 ms energy envelopes in -200 .. +600 ms, to catch offsets + outside the AEC estimator range. + Costs a few MCPS. + +config WEBRTC_AEC_ERLE_TRACE + bool "Float AEC echo return loss enhancement trace" + depends on WEBRTC_AEC_BACKEND_FLOAT + help + Trace every 1 s the echo return loss enhancement (ERLE), the + microphone and reference levels and the share of frames with an + active reference. Only frames with the reference above -50 dBFS + are counted. Near-end speech in those frames lowers the reported + ERLE, so read it from far-end only periods. + config WEBRTC_AEC_SUPPRESSION_LEVEL int "AECm comfort-noise suppression level (0=off, 1=low, 2=medium)" range 0 2 @@ -96,15 +160,6 @@ config WEBRTC_AEC_SAMPLE_RATE_HZ recommended for best echo suppression quality. Valid values: 8000, 16000. -config WEBRTC_AEC_DELAY_MS - int "Nominal echo path / soundcard buffer delay in ms" - range 0 500 - default 20 - help - Nominal delay in milliseconds between echo reference playback and - microphone capture. Used by AECm/Float AEC (msInSndCardBuf) and by - AEC3 when WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST is enabled. - config WEBRTC_AEC_STEREO_DOWNMIX_REF bool "Downmix stereo echo reference to mono before AEC" default n diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index 76d1b1da7df2..c7bd18bd1876 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -90,6 +90,11 @@ CONFIG_COMP_WEBRTC_AEC_STUB=n CONFIG_WEBRTC_AEC_BACKEND_FLOAT=y ``` +The float backend outputs the linear filter error without residual echo +suppression, which keeps the near-end talker intact for wake on voice +and barge-in. The far-end buffers and delay search are sized for a +reference to echo delay of at most 15 ms. + ### 3. Classic Fixed-Point AECm (Mobile / Low-Power Integer) ```ini @@ -115,7 +120,9 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | `CONFIG_WEBRTC_AEC_FILTER_LEN_MS` | 64 | int (`32`, `64`, `128`) | AECm adaptive filter length in ms | | `CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL` | 1 | int (`0` - `2`) | AECm comfort-noise suppression level | | `CONFIG_WEBRTC_AEC_SAMPLE_RATE_HZ` | 16000 | int (`8000`, `16000`) | Native AEC processing rate (32/48 kHz resampled) | -| `CONFIG_WEBRTC_AEC_DELAY_MS` | 20 | int (`0` - `500`) | Nominal echo path / soundcard buffer delay in ms | +| `CONFIG_WEBRTC_AEC_DELAY_MS` | 0 (Float), 20 | int (`0` - `15` Float, `0` - `500`) | Nominal echo path / soundcard buffer delay in ms; for Float the reference to echo delay, must not exceed the real delay | +| `CONFIG_WEBRTC_AEC_REF_GAIN` | 16 | int (`1` - `256`) | Float AEC linear gain on the reference, speeds up convergence | +| `CONFIG_WEBRTC_AEC_DELAY_DEBUG` | n | bool | Float AEC delay estimate and level trace every 5 s | | `CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF` | n | bool | Downmix multi-channel reference to mono before AEC | | `CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT` | y | bool (AEC3) | Dynamic stereo vs. dual-mono content detector | | `CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST` | n | bool (AEC3) | Lock AEC3 to `WEBRTC_AEC_DELAY_MS` instead of matched filter | diff --git a/src/audio/webrtc_aec/webrtc_aec-aec.c b/src/audio/webrtc_aec/webrtc_aec-aec.c index f415cb721d55..e0b200113631 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec.c @@ -20,6 +20,7 @@ #include #include +#include #include "webrtc_aec.h" #include @@ -27,11 +28,50 @@ LOG_MODULE_DECLARE(webrtc_aec, CONFIG_SOF_LOG_LEVEL); +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE +/* 100 frames of 10 ms */ +#define WEBRTC_AEC_ERLE_FRAMES 100 +/* Far-end active when the reference frame is above -50 dBFS */ +#define WEBRTC_AEC_ERLE_REF_MIN (32768.0f * 32768.0f * 1e-5f) +#define WEBRTC_AEC_FS_ENERGY (32768.0f * 32768.0f) +#endif + +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG +/* 10 ms frame energy envelopes, lag search -200 .. +600 ms every 5 s */ +#define WEBRTC_AEC_XC_HIST 256 +#define WEBRTC_AEC_XC_WIN 170 +#define WEBRTC_AEC_XC_LAG_MIN -20 +#define WEBRTC_AEC_XC_LAG_MAX 60 +#define WEBRTC_AEC_XC_FRAMES 500 +#endif + struct webrtc_aec_float_data { void *aec[WEBRTC_AEC_CHANNELS_MAX]; int num_mic_channels; int num_ref_channels; int suppression; + int stats_frames; + int16_t ref_peak; + int16_t mic_peak; +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE + int erle_frames; + int erle_active; + float erle_mic_e; + float erle_out_e; + float erle_ref_e; +#endif +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG + int xc_pos; + int xc_count; + int xc_frames; + float xc_ref[WEBRTC_AEC_XC_HIST]; + float xc_mic[WEBRTC_AEC_XC_HIST]; +#endif +#if CONFIG_WEBRTC_AEC_MIC_DELAY_MS > 0 + int mic_dly_len; + int mic_dly_pos[WEBRTC_AEC_CHANNELS_MAX]; + float mic_dly[WEBRTC_AEC_CHANNELS_MAX][CONFIG_WEBRTC_AEC_MIC_DELAY_MS * 16]; +#endif int delay_ms; float ref_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; float mic_f[WEBRTC_AEC_FRAME_SAMPLES_16K]; @@ -71,7 +111,8 @@ static int webrtc_aec_float_apply_cfg(struct processing_module *mod, (rd->suppression == 0) ? kAecNlpConservative : kAecNlpModerate; config.skewMode = kAecFalse; config.metricsMode = kAecTrue; - config.delay_logging = kAecFalse; + config.delay_logging = IS_ENABLED(CONFIG_WEBRTC_AEC_DELAY_DEBUG) ? + kAecTrue : kAecFalse; ret = WebRtcAec_set_config(inst, config); if (ret) { @@ -123,9 +164,18 @@ static int webrtc_aec_float_configure(struct processing_module *mod, int sample_ } rd->num_mic_channels = num_mic_channels; - comp_info(mod->dev, "webrtc_aec: Float AEC rate=%d high_supp=%d mic_ch=%d ref_ch=%d delay=%dms", + rd->stats_frames = 0; + rd->ref_peak = 0; + rd->mic_peak = 0; +#if CONFIG_WEBRTC_AEC_MIC_DELAY_MS > 0 + rd->mic_dly_len = CONFIG_WEBRTC_AEC_MIC_DELAY_MS * sample_rate_hz / 1000; + memset(rd->mic_dly_pos, 0, sizeof(rd->mic_dly_pos)); + memset(rd->mic_dly, 0, sizeof(rd->mic_dly)); +#endif + comp_info(mod->dev, "webrtc_aec: Float AEC rate=%d high_supp=%d mic_ch=%d ref_ch=%d delay=%d ms ref_gain=%d mic_delay=%d ms", sample_rate_hz, cd->high_suppression, num_mic_channels, num_ref_channels, - rd->delay_ms); + rd->delay_ms, CONFIG_WEBRTC_AEC_REF_GAIN, + CONFIG_WEBRTC_AEC_MIC_DELAY_MS); return 0; err: @@ -151,7 +201,8 @@ static int webrtc_aec_float_set_suppression(struct processing_module *mod, bool config.nlpMode = high_suppression ? kAecNlpAggressive : kAecNlpModerate; config.skewMode = kAecFalse; config.metricsMode = kAecTrue; - config.delay_logging = kAecFalse; + config.delay_logging = IS_ENABLED(CONFIG_WEBRTC_AEC_DELAY_DEBUG) ? + kAecTrue : kAecFalse; for (c = 0; c < rd->num_mic_channels; c++) { if (!rd->aec[c]) @@ -168,6 +219,151 @@ static int webrtc_aec_float_set_suppression(struct processing_module *mod, bool return 0; } +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE +static int webrtc_aec_db_round(float db) +{ + return (int)(db + (db >= 0.0f ? 0.5f : -0.5f)); +} + +/* ERLE over far-end active frames, near-end speech in them lowers the value */ +static void webrtc_aec_float_erle(struct processing_module *mod, + struct webrtc_aec_float_data *rd, + const float *ref_f, int frame_samples) +{ + const float inv_gain = 1.0f / (float)CONFIG_WEBRTC_AEC_REF_GAIN; + float ref_e = 0.0f, mic_e = 0.0f, out_e = 0.0f; + float norm; + int i; + + for (i = 0; i < frame_samples; i++) { + float r = ref_f[i] * inv_gain; + + ref_e += r * r; + mic_e += rd->mic_f[i] * rd->mic_f[i]; + out_e += rd->out_f[i] * rd->out_f[i]; + } + + if (ref_e > WEBRTC_AEC_ERLE_REF_MIN * frame_samples) { + rd->erle_ref_e += ref_e; + rd->erle_mic_e += mic_e; + rd->erle_out_e += out_e; + rd->erle_active++; + } + + if (++rd->erle_frames < WEBRTC_AEC_ERLE_FRAMES) + return; + + if (rd->erle_active) { + float mic = rd->erle_mic_e > 1.0f ? rd->erle_mic_e : 1.0f; + float out = rd->erle_out_e > 1.0f ? rd->erle_out_e : 1.0f; + + norm = WEBRTC_AEC_FS_ENERGY * rd->erle_active * frame_samples; + comp_info(mod->dev, + "webrtc_aec: ERLE %d dB mic %d ref %d dBFS active %d%%", + webrtc_aec_db_round(10.0f * log10f(mic / out)), + webrtc_aec_db_round(10.0f * log10f(mic / norm)), + webrtc_aec_db_round(10.0f * log10f(rd->erle_ref_e / norm)), + rd->erle_active * 100 / WEBRTC_AEC_ERLE_FRAMES); + } + + rd->erle_frames = 0; + rd->erle_active = 0; + rd->erle_mic_e = 0.0f; + rd->erle_out_e = 0.0f; + rd->erle_ref_e = 0.0f; +} +#endif + +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG +static float webrtc_aec_frame_db(const int16_t *x, int frame_samples) +{ + float e = 1.0f; + int i; + + for (i = 0; i < frame_samples; i++) + e += (float)x[i] * (float)x[i]; + + return 10.0f * log10f(e); +} + +/* Same for the float reference with the REF_GAIN removed */ +static float webrtc_aec_frame_db_f(const float *x, int frame_samples) +{ + const float inv_gain = 1.0f / (float)CONFIG_WEBRTC_AEC_REF_GAIN; + float e = 1.0f; + int i; + + for (i = 0; i < frame_samples; i++) + e += x[i] * inv_gain * x[i] * inv_gain; + + return 10.0f * log10f(e); +} + +/* Coarse echo delay from energy envelopes, independent of the AEC estimator */ +static void webrtc_aec_float_xcorr(struct processing_module *mod, + struct webrtc_aec_float_data *rd, + const float *ref_f, const int16_t *mic, + int frame_samples) +{ + const int h = WEBRTC_AEC_XC_HIST; + float mean_m = 0.0f, mean_r, smm = 0.0f, smr, srr; + float best_corr = -2.0f; + int best_lag = 0; + int newest, start, lag, n, im, ir; + + rd->xc_ref[rd->xc_pos] = webrtc_aec_frame_db_f(ref_f, frame_samples); + rd->xc_mic[rd->xc_pos] = webrtc_aec_frame_db(mic, frame_samples); + newest = rd->xc_pos; + rd->xc_pos = (rd->xc_pos + 1) % h; + if (rd->xc_count < h) + rd->xc_count++; + + if (++rd->xc_frames < WEBRTC_AEC_XC_FRAMES || rd->xc_count < h) + return; + + rd->xc_frames = 0; + + /* Mic window ends -LAG_MIN frames back so negative lags fit in history */ + start = newest + WEBRTC_AEC_XC_LAG_MIN - WEBRTC_AEC_XC_WIN + 1 + h; + for (n = 0; n < WEBRTC_AEC_XC_WIN; n++) + mean_m += rd->xc_mic[(start + n) % h]; + mean_m /= WEBRTC_AEC_XC_WIN; + for (n = 0; n < WEBRTC_AEC_XC_WIN; n++) { + float d = rd->xc_mic[(start + n) % h] - mean_m; + + smm += d * d; + } + + for (lag = WEBRTC_AEC_XC_LAG_MIN; lag <= WEBRTC_AEC_XC_LAG_MAX; lag++) { + mean_r = 0.0f; + for (n = 0; n < WEBRTC_AEC_XC_WIN; n++) + mean_r += rd->xc_ref[(start + n - lag + h) % h]; + mean_r /= WEBRTC_AEC_XC_WIN; + + smr = 0.0f; + srr = 0.0f; + for (n = 0; n < WEBRTC_AEC_XC_WIN; n++) { + im = (start + n) % h; + ir = (start + n - lag + h) % h; + smr += (rd->xc_mic[im] - mean_m) * (rd->xc_ref[ir] - mean_r); + srr += (rd->xc_ref[ir] - mean_r) * (rd->xc_ref[ir] - mean_r); + } + + if (smm > 0.0f && srr > 0.0f) { + float c = smr / sqrtf(smm * srr); + + if (c > best_corr) { + best_corr = c; + best_lag = lag; + } + } + } + + comp_info(mod->dev, "webrtc_aec: xcorr lag %d ms corr %d%%", + best_lag * 10, (int)(best_corr * 100.0f)); +} +#endif + static int webrtc_aec_float_set_delay(struct processing_module *mod, int delay_ms) { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); @@ -223,8 +419,25 @@ static int webrtc_aec_float_run_ch(struct processing_module *mod, return ret; } - for (i = 0; i < frame_samples; i++) + for (i = 0; i < frame_samples; i++) { rd->mic_f[i] = (float)mic[i]; +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG + if (ch == 0 && mic[i] > rd->mic_peak) + rd->mic_peak = mic[i]; +#endif + } + +#if CONFIG_WEBRTC_AEC_MIC_DELAY_MS > 0 + for (i = 0; i < frame_samples; i++) { + float x = rd->mic_f[i]; + float *dly = rd->mic_dly[ch]; + + rd->mic_f[i] = dly[rd->mic_dly_pos[ch]]; + dly[rd->mic_dly_pos[ch]] = x; + if (++rd->mic_dly_pos[ch] >= rd->mic_dly_len) + rd->mic_dly_pos[ch] = 0; + } +#endif ret = WebRtcAec_Process(rd->aec[ch], nearend, 1, out_ptrs, (size_t)frame_samples, (int16_t)rd->delay_ms, 0); @@ -233,6 +446,31 @@ static int webrtc_aec_float_run_ch(struct processing_module *mod, return ret; } +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG + /* Median < 0 means echo arrives before the aligned reference (non-causal) */ + if (ch == 0 && ++rd->stats_frames >= 500) { + int median, std; + float poor; + + if (!WebRtcAec_GetDelayMetrics(rd->aec[0], &median, &std, &poor)) + comp_info(mod->dev, + "webrtc_aec: delay median %d std %d ms poor %d%% ref_pk %d mic_pk %d", + median, std, (int)(poor * 100.0f), rd->ref_peak, rd->mic_peak); + rd->stats_frames = 0; + rd->ref_peak = 0; + rd->mic_peak = 0; + } +#endif + +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE + if (ch == 0) + webrtc_aec_float_erle(mod, rd, ref_f, frame_samples); +#endif +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG + if (ch == 0) + webrtc_aec_float_xcorr(mod, rd, ref_f, mic, frame_samples); +#endif + /* Round and saturate float output back into signed 16-bit PCM range. */ for (i = 0; i < frame_samples; i++) { float val = rd->out_f[i]; @@ -256,6 +494,7 @@ static int webrtc_aec_float_process_frame(struct processing_module *mod, { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); struct webrtc_aec_float_data *rd = cd->backend_data; + const float gain = (float)CONFIG_WEBRTC_AEC_REF_GAIN; int i, c, ret; if (frame_samples <= 0 || frame_samples > WEBRTC_AEC_FRAME_SAMPLES_16K || @@ -263,20 +502,30 @@ static int webrtc_aec_float_process_frame(struct processing_module *mod, num_ref_channels <= 0 || num_ref_channels > WEBRTC_AEC_CHANNELS_MAX) return -EINVAL; +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG + for (c = 0; c < num_ref_channels; c++) { + for (i = 0; i < frame_samples; i++) { + if (ref[c][i] > rd->ref_peak) + rd->ref_peak = ref[c][i]; + } + } +#endif + /* * Convert reference to float once outside the mic loop: use per-channel ref * when ref and mic counts match, otherwise downmix multi-channel ref to mono. + * The reference gain is applied here, see WEBRTC_AEC_REF_GAIN. */ if (num_ref_channels == num_mic_channels) { for (c = 0; c < num_ref_channels; c++) { for (i = 0; i < frame_samples; i++) - rd->ref_f[c][i] = (float)ref[c][i]; + rd->ref_f[c][i] = (float)ref[c][i] * gain; } } else if (num_ref_channels == 1) { for (i = 0; i < frame_samples; i++) - rd->ref_f[0][i] = (float)ref[0][i]; + rd->ref_f[0][i] = (float)ref[0][i] * gain; } else { - float inv = 1.0f / (float)num_ref_channels; + float inv = gain / (float)num_ref_channels; for (i = 0; i < frame_samples; i++) { float acc = 0.0f; @@ -310,8 +559,13 @@ static int webrtc_aec_float_process_ch(struct processing_module *mod, if (frame_samples > WEBRTC_AEC_FRAME_SAMPLES_16K) return -EINVAL; - for (i = 0; i < frame_samples; i++) - rd->ref_f[0][i] = (float)ref[i]; + for (i = 0; i < frame_samples; i++) { + rd->ref_f[0][i] = (float)ref[i] * (float)CONFIG_WEBRTC_AEC_REF_GAIN; +#ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG + if (ref[i] > rd->ref_peak) + rd->ref_peak = ref[i]; +#endif + } return webrtc_aec_float_run_ch(mod, rd, mic, rd->ref_f[0], out, frame_samples, ch); } From 994c23f39af27a3b93cfba4f894fe6b353b8fa70 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Thu, 3 Dec 2026 12:58:32 +0200 Subject: [PATCH 02/17] audio: webrtc_aec: wrap new and delete for Zephyr minimal libcpp The Zephyr minimal C++ library, enabled with CONFIG_CPP e.g. for the microwakeword module, defines the global new and delete operators. The AEC3 shims define them too, so a firmware with both AEC3 and MWW fails to link with multiple definitions. Wrap the operators with the linker --wrap option when CONFIG_MINIMAL_LIBCPP is set. All new and delete calls in the image then use the webrtc_malloc() and webrtc_free() versions in the AEC3 shims instead of the small libc arena. Throwing new calls k_panic() on failure since exceptions are disabled. The __cxa_atexit() and __cxa_pure_virtual() shims are built only without CONFIG_CPP since the Zephyr C++ runtime provides them. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/CMakeLists.txt | 10 +++++ src/audio/webrtc_aec/webrtc_aec3_shims.cpp | 48 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/audio/webrtc_aec/CMakeLists.txt b/src/audio/webrtc_aec/CMakeLists.txt index d1104b89aef3..48f7d50251ea 100644 --- a/src/audio/webrtc_aec/CMakeLists.txt +++ b/src/audio/webrtc_aec/CMakeLists.txt @@ -75,6 +75,16 @@ else() webrtc_aec3_shims.cpp ) + # The Zephyr minimal C++ library (CONFIG_CPP, e.g. for MWW) also defines + # the global new and delete operators. Wrap them so that the AEC3 + # allocations use the module heap versions in webrtc_aec3_shims.cpp. + if(CONFIG_MINIMAL_LIBCPP) + foreach(_sym _Znwj _Znaj _ZnwjRKSt9nothrow_t _ZnajRKSt9nothrow_t + _ZdlPv _ZdaPv _ZdlPvj _ZdaPvj) + zephyr_link_libraries(-Wl,--wrap=${_sym}) + endforeach() + endif() + file(GLOB _aec3_srcs "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec3/*.cc" ) diff --git a/src/audio/webrtc_aec/webrtc_aec3_shims.cpp b/src/audio/webrtc_aec/webrtc_aec3_shims.cpp index 3243ccdac62f..2b080cbb34da 100644 --- a/src/audio/webrtc_aec/webrtc_aec3_shims.cpp +++ b/src/audio/webrtc_aec/webrtc_aec3_shims.cpp @@ -22,6 +22,50 @@ void webrtc_free(void *ptr); #define SOF_MEM_FLAG_USER (1 << 8) +#if defined(CONFIG_MINIMAL_LIBCPP) +/* + * The Zephyr minimal C++ library, needed by other C++ modules such as MWW, + * defines the global new and delete operators with malloc() from the small + * libc arena. The AEC3 allocations must come from the module heap, so the + * linker wraps these symbols (see CMakeLists.txt) and every reference in the + * image resolves to the versions below. The names are the Itanium C++ ABI + * manglings for a 32-bit size_t. + */ +static void *webrtc_aec3_new(std::size_t size) +{ + void *p = webrtc_malloc(size); + + if (!p) + k_panic(); + return p; +} + +extern "C" { +void *__wrap__Znwj(std::size_t size) { return webrtc_aec3_new(size); } +void *__wrap__Znaj(std::size_t size) { return webrtc_aec3_new(size); } +void *__wrap__ZnwjRKSt9nothrow_t(std::size_t size, const std::nothrow_t &) +{ + return webrtc_malloc(size); +} +void *__wrap__ZnajRKSt9nothrow_t(std::size_t size, const std::nothrow_t &) +{ + return webrtc_malloc(size); +} +void __wrap__ZdlPv(void *ptr) { webrtc_free(ptr); } +void __wrap__ZdaPv(void *ptr) { webrtc_free(ptr); } +void __wrap__ZdlPvj(void *ptr, std::size_t) { webrtc_free(ptr); } +void __wrap__ZdaPvj(void *ptr, std::size_t) { webrtc_free(ptr); } +} + +/* Not defined by Zephyr, so no wrapping is needed for these */ +void operator delete(void* ptr, const std::nothrow_t&) noexcept { + webrtc_free(ptr); +} + +void operator delete[](void* ptr, const std::nothrow_t&) noexcept { + webrtc_free(ptr); +} +#else void* operator new(std::size_t size) { void* p = webrtc_malloc(size); if (!p) @@ -69,11 +113,15 @@ void operator delete(void* ptr, const std::nothrow_t&) noexcept { void operator delete[](void* ptr, const std::nothrow_t&) noexcept { webrtc_free(ptr); } +#endif /* CONFIG_MINIMAL_LIBCPP */ extern "C" { void* __dso_handle = nullptr; +#if !defined(CONFIG_CPP) +/* With CONFIG_CPP the Zephyr C++ runtime provides these */ int __cxa_atexit(void (*)(void*), void*, void*) { return 0; } void __cxa_pure_virtual() { k_panic(); } +#endif } namespace std { From 2161e00c14256501001d8531ca52df6191d96519 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Thu, 3 Dec 2026 12:58:55 +0200 Subject: [PATCH 03/17] audio: webrtc_aec: downmix multi-channel microphone for mono output Make the output channel count follow the sink format. With a mono output and a multi-channel microphone the microphone channels are averaged to mono before the AEC. This allows e.g. a stereo DMIC with a stereo echo reference to feed a mono WoV KPB without a separate micsel downmix in front of the AEC. Both input pins then have the same format, which the kernel requires since it matches the stream parameters only against the pin 0 formats when the input formats differ. With AEC3 the processing runs as 2R x 1C. The source channel count is stored in the new mic_in_channels and mic_channels is the processed and output channel count. Without the downmix a sink channel count different from the microphone channel count is rejected in prepare(). Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/README.md | 1 + src/audio/webrtc_aec/webrtc_aec.c | 95 ++++++++++++++++++++++++++++--- src/audio/webrtc_aec/webrtc_aec.h | 4 +- 3 files changed, 92 insertions(+), 8 deletions(-) diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index c7bd18bd1876..5dbe19a428ed 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -14,6 +14,7 @@ Wraps WebRTC's Acoustic Echo Cancellation algorithms behind the SOF `module_inte - **Multi-Channel & Asymmetric Echo Cancellation ($R\text{R} \times C\text{C}$, up to $4 \times 4$)**: - Decoupled reference (`ref_channels`) and microphone (`mic_channels`) counts (`WEBRTC_AEC_CHANNELS_MAX = 4`), eliminating ch0 output cloning. - Supports $1\text{R} \times N\text{C}$, $2\text{R} \times 2\text{C}$, asymmetric $2\text{R} \times 1\text{C}$ / $2\text{R} \times 4\text{C}$, and optional multi-channel reference downmixing (`CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF`). + - **Microphone Downmix for Mono Output**: The output channel count follows the sink format. With a mono output and a multi-channel microphone the microphone channels are averaged before the AEC, e.g. 2R x 2-mic input to a mono WoV KPB. Both input pins can then use the same format, and AEC3 runs as 2R x 1C. - **Multi-Rate Pipeline Support**: Native 8 kHz / 16 kHz plus WebRTC SPL resampling for 32 kHz (`WebRtcSpl_DownsampleBy2` / `UpsampleBy2`) and 48 kHz (`WebRtcSpl_Resample48khzTo16khz` / `16khzTo48khz`). - **AEC3 Stereo Power Tracking & Suppression**: Full $R \times C$ `EchoCanceller3::CreateDefaultMultichannelConfig()` support with configurable filter length, coarse filter fallback, stereo content detector, and external/internal delay estimation. - **DSP Mathematical Accelerations**: diff --git a/src/audio/webrtc_aec/webrtc_aec.c b/src/audio/webrtc_aec/webrtc_aec.c index f0eec961fa3a..f6617cafdfca 100644 --- a/src/audio/webrtc_aec/webrtc_aec.c +++ b/src/audio/webrtc_aec/webrtc_aec.c @@ -117,6 +117,68 @@ static void src_to_s16(struct sof_source *src, int n, source_release_data(src, nbytes); } +/** + * src_to_s16_avg() - Copy frames from a source into mono S16 scratch. + * Averages all channels of each frame, for a mono output from a + * multi-channel microphone. Handles both S16 and S32 pipeline formats. + * @src: SOF source (provides source_get_data / source_release_data) + * @n: number of frames to consume + * @dst: S16 destination, only dst[0] is written + * @frame0: offset within dst at which to start writing + * @ch: number of source channels + * @is_s32: true if the pipeline format is S32_LE + */ +static void src_to_s16_avg(struct sof_source *src, int n, + int16_t dst[][WEBRTC_AEC_FIFO_FRAMES], + int frame0, int ch, bool is_s32) +{ + size_t sample_sz = is_s32 ? sizeof(int32_t) : sizeof(int16_t); + size_t frame_bytes = (size_t)ch * sample_sz; + size_t nbytes = (size_t)n * frame_bytes; + struct cir_buf_source source_buf; + size_t bufsz; + int remaining = n; + int cur_frame = frame0; + int err; + + err = source_get_data(src, nbytes, &source_buf.ptr, &source_buf.buf_start, &bufsz); + if (err) + return; /* shouldn't happen if caller checked availability */ + source_buf.buf_end = (const char *)source_buf.buf_start + bufsz; + + while (remaining > 0) { + size_t fmax = circ_buf_frames_without_wrap(source_buf.ptr, source_buf.buf_end, + sample_sz, (size_t)ch); + size_t chunk = MIN((size_t)remaining, fmax); + size_t i; + int c; + + for (i = 0; i < chunk; i++) { + int64_t acc = 0; + + for (c = 0; c < ch; c++) { + if (is_s32) { + acc += *(const int32_t *)source_buf.ptr; + source_buf.ptr = (const char *)source_buf.ptr + sizeof(int32_t); + } else { + acc += *(const int16_t *)source_buf.ptr; + source_buf.ptr = (const char *)source_buf.ptr + sizeof(int16_t); + } + } + + /* The average of in-range samples stays in range */ + acc /= ch; + dst[0][cur_frame + i] = is_s32 ? (int16_t)(acc >> 16) : (int16_t)acc; + } + + remaining -= (int)chunk; + cur_frame += (int)chunk; + source_buf.ptr = source_cir_buf_wrap(source_buf.ptr, source_buf.buf_start, source_buf.buf_end); + } + + source_release_data(src, nbytes); +} + /** * s16_to_sink() - Write per-channel S16 output to a SOF sink. * Upshifts to S32 if the pipeline format requires it, handling buffer wrapping. @@ -305,7 +367,7 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, mic_fmt = source_get_frm_fmt(sources[cd->mic_src]); mic_rate = source_get_rate(sources[cd->mic_src]); - cd->mic_channels = source_get_channels(sources[cd->mic_src]); + cd->mic_in_channels = source_get_channels(sources[cd->mic_src]); if (cd->ref_src >= 0) { /* Pin 1 may come from a separate render pipeline; apply its IPC4 pin format. */ @@ -328,9 +390,23 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, cd->ref_channels = 1; } - if (cd->mic_channels <= 0 || cd->mic_channels > WEBRTC_AEC_CHANNELS_MAX) { + if (cd->mic_in_channels <= 0 || cd->mic_in_channels > WEBRTC_AEC_CHANNELS_MAX) { comp_err(dev, "webrtc_aec: invalid mic_channels %d (max %d)", - cd->mic_channels, WEBRTC_AEC_CHANNELS_MAX); + cd->mic_in_channels, WEBRTC_AEC_CHANNELS_MAX); + return -EINVAL; + } + + /* + * The output channel count follows the sink format. A mono output from a + * multi-channel microphone averages the microphone channels before the AEC, + * e.g. for a mono WoV KPB with a stereo echo reference. Otherwise the + * output has one channel per microphone channel. + */ + cd->downmix_mic = cd->mic_in_channels > 1 && sink_get_channels(sinks[0]) == 1; + cd->mic_channels = cd->downmix_mic ? 1 : cd->mic_in_channels; + if (sink_get_channels(sinks[0]) != cd->mic_channels) { + comp_err(dev, "webrtc_aec: output channels %d do not match mic channels %d", + sink_get_channels(sinks[0]), cd->mic_in_channels); return -EINVAL; } if (cd->ref_channels <= 0 || cd->ref_channels > WEBRTC_AEC_CHANNELS_MAX) { @@ -388,9 +464,9 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, return -EINVAL; } - comp_info(dev, "webrtc_aec: mic_src=%d ref_src=%d rate=%d/%d mic_ch=%d ref_ch=%d (eff_ref=%d) frame=%d %s/%s->%s resamp=%d", + comp_info(dev, "webrtc_aec: mic_src=%d ref_src=%d rate=%d/%d mic_ch=%d (eff_mic=%d) ref_ch=%d (eff_ref=%d) frame=%d %s/%s->%s resamp=%d", cd->mic_src, cd->ref_src, cd->rate, cd->proc_rate, - cd->mic_channels, cd->ref_channels, cd->effective_ref_ch, + cd->mic_in_channels, cd->mic_channels, cd->ref_channels, cd->effective_ref_ch, cd->frame_samples, cd->mic_is_s32 ? "S32" : "S16", cd->ref_is_s32 ? "S32" : "S16", cd->out_is_s32 ? "S32" : "S16", cd->resamp_mode); @@ -643,8 +719,13 @@ static int webrtc_aec_process(struct processing_module *mod, return 0; } - /* Convert mic input to per-channel S16 */ - src_to_s16(mic, n, cd->mic_buf, cd->buffered_in_frames, cd->mic_channels, cd->mic_is_s32); + /* Convert mic input to per-channel S16, or to mono S16 for a mono output */ + if (cd->downmix_mic) + src_to_s16_avg(mic, n, cd->mic_buf, cd->buffered_in_frames, cd->mic_in_channels, + cd->mic_is_s32); + else + src_to_s16(mic, n, cd->mic_buf, cd->buffered_in_frames, cd->mic_channels, + cd->mic_is_s32); /* * Validate dynamically attached reference source format/channels and trim diff --git a/src/audio/webrtc_aec/webrtc_aec.h b/src/audio/webrtc_aec/webrtc_aec.h index bde87c5edf4f..f275399b0108 100644 --- a/src/audio/webrtc_aec/webrtc_aec.h +++ b/src/audio/webrtc_aec/webrtc_aec.h @@ -149,6 +149,7 @@ struct webrtc_aec_comp_data { bool high_suppression; /* suppression switch (WEBRTC_AEC_CTL_ID_HIGH_SUPPRESSION) */ int delay_ms; /* echo path / soundcard buffer delay (ms) */ bool downmix_ref; /* downmix multi-ch ref to mono before backend */ + bool downmix_mic; /* average multi-ch mic to mono for a mono output */ /* Source routing (resolved in prepare / process). */ int mic_src; /* index into sources[] for microphone */ @@ -157,7 +158,8 @@ struct webrtc_aec_comp_data { /* Negotiated format. */ int rate; /* pipeline sample rate (Hz) */ int proc_rate; /* AEC processing rate (8000 or 16000 Hz) */ - int mic_channels; /* microphone / output channel count */ + int mic_in_channels; /* microphone source channel count */ + int mic_channels; /* processed microphone / output channel count */ int ref_channels; /* playback reference channel count */ int effective_ref_ch; /* ref channels fed to backend (1 if downmixed) */ int mic_frame_bytes; /* bytes per pipeline frame on mic input */ From 3aee3d57eeba0f1aa36985dbcd457fb52bb9638d Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Thu, 3 Dec 2026 12:59:10 +0200 Subject: [PATCH 04/17] audio: webrtc_aec: report the backend memory usage Count the bytes allocated by the WebRTC library in webrtc_malloc() and webrtc_calloc() and print the total after the backend configure in prepare(). A failed allocation is logged with the requested size and the amount allocated before it. This helps to size the heap for the AEC3 backend, e.g. 2R x 1C AEC3 at 16 kHz allocates about 600 kB, and to see the reason when AEC3 panics on an out of memory new. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/webrtc_aec-shims.c | 51 +++++++++++++++++++++++-- src/audio/webrtc_aec/webrtc_aec.c | 3 ++ src/audio/webrtc_aec/webrtc_aec.h | 4 ++ 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/audio/webrtc_aec/webrtc_aec-shims.c b/src/audio/webrtc_aec/webrtc_aec-shims.c index a838db26f593..936a25e26960 100644 --- a/src/audio/webrtc_aec/webrtc_aec-shims.c +++ b/src/audio/webrtc_aec/webrtc_aec-shims.c @@ -15,10 +15,53 @@ #if !defined(LLEXT_MODULE) #include static APP_SYSUSER_BSS struct processing_module *active_aec_mod; +static APP_SYSUSER_BSS size_t webrtc_alloc_bytes; #else static struct processing_module *active_aec_mod; +static size_t webrtc_alloc_bytes; #endif +LOG_MODULE_DECLARE(webrtc_aec, CONFIG_SOF_LOG_LEVEL); + +/** + * \brief Get the bytes allocated by the WebRTC library since the last reset. + * + * Frees are not subtracted, so this is the allocated total, e.g. the + * footprint of a backend instance when read after its creation. + * + * \return Allocated bytes + */ +size_t webrtc_aec_get_alloc_bytes(void) +{ + return webrtc_alloc_bytes; +} + +/** + * \brief Reset the allocated bytes counter, see webrtc_aec_get_alloc_bytes(). + */ +void webrtc_aec_reset_alloc_bytes(void) +{ + webrtc_alloc_bytes = 0; +} + +/** + * \brief Account an allocation and report a failed one. + * + * \param[in] p Allocated memory, NULL if the allocation failed + * \param[in] size Requested size in bytes + * \return The p argument + */ +static void *webrtc_alloc_done(void *p, size_t size) +{ + if (p) + webrtc_alloc_bytes += size; + else if (active_aec_mod) + comp_err(active_aec_mod->dev, + "webrtc_aec: alloc of %zu bytes failed, %zu bytes allocated before", + size, webrtc_alloc_bytes); + return p; +} + void webrtc_aec_set_active_mod(struct processing_module *mod) { active_aec_mod = mod; @@ -35,8 +78,8 @@ void *webrtc_malloc(size_t size) return NULL; if (active_aec_mod) - return mod_alloc(active_aec_mod, size); - return rmalloc(SOF_MEM_FLAG_USER, size); + return webrtc_alloc_done(mod_alloc(active_aec_mod, size), size); + return webrtc_alloc_done(rmalloc(SOF_MEM_FLAG_USER, size), size); } void webrtc_free(void *ptr) @@ -59,8 +102,8 @@ void *webrtc_calloc(size_t nmemb, size_t size) return NULL; if (active_aec_mod) - return mod_zalloc(active_aec_mod, total); - return rzalloc(SOF_MEM_FLAG_USER, total); + return webrtc_alloc_done(mod_zalloc(active_aec_mod, total), total); + return webrtc_alloc_done(rzalloc(SOF_MEM_FLAG_USER, total), total); } void *webrtc_realloc(void *ptr, size_t size) diff --git a/src/audio/webrtc_aec/webrtc_aec.c b/src/audio/webrtc_aec/webrtc_aec.c index f6617cafdfca..f6e8c804159f 100644 --- a/src/audio/webrtc_aec/webrtc_aec.c +++ b/src/audio/webrtc_aec/webrtc_aec.c @@ -472,6 +472,7 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, cd->resamp_mode); if (cd->backend->configure) { + webrtc_aec_reset_alloc_bytes(); ret = cd->backend->configure(mod, cd->proc_rate, CONFIG_WEBRTC_AEC_FILTER_LEN_MS, CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL, @@ -480,6 +481,8 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, comp_err(dev, "webrtc_aec: backend configure failed %d", ret); return ret; } + comp_info(dev, "webrtc_aec: backend allocated %zu bytes", + webrtc_aec_get_alloc_bytes()); } if (cd->backend->set_delay) diff --git a/src/audio/webrtc_aec/webrtc_aec.h b/src/audio/webrtc_aec/webrtc_aec.h index f275399b0108..ea876660214f 100644 --- a/src/audio/webrtc_aec/webrtc_aec.h +++ b/src/audio/webrtc_aec/webrtc_aec.h @@ -209,9 +209,13 @@ extern const struct webrtc_aec_backend webrtc_aec_backend; #if !defined(CONFIG_COMP_WEBRTC_AEC_STUB) void webrtc_aec_set_active_mod(struct processing_module *mod); struct processing_module *webrtc_aec_get_active_mod(void); +size_t webrtc_aec_get_alloc_bytes(void); +void webrtc_aec_reset_alloc_bytes(void); #else static inline void webrtc_aec_set_active_mod(struct processing_module *mod) { (void)mod; } static inline struct processing_module *webrtc_aec_get_active_mod(void) { return NULL; } +static inline size_t webrtc_aec_get_alloc_bytes(void) { return 0; } +static inline void webrtc_aec_reset_alloc_bytes(void) {} #endif #endif /* __SOF_AUDIO_WEBRTC_AEC_H__ */ From 4bff56fad7f08664d1ed434265f9901ffe568042 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Thu, 3 Dec 2026 12:59:24 +0200 Subject: [PATCH 05/17] audio: webrtc_aec: add Kconfig to build AEC3 with the hardware FPU The webrtc_aec sources are compiled with the Clang target feature -fp, so all float operations are soft-float library calls. For AEC3 this is far too slow, 2R x 1C AEC3 at 16 kHz needs about 13.6 ms of DSP time per 10 ms frame on PTL, i.e. about 600 MCPS. Add CONFIG_WEBRTC_AEC_AEC3_HW_FPU to drop the flag from the AEC3 build. The ACE 3.0 core has the FPU in the HiFi4 audio engine coprocessor, and its state including the FCR and FSR registers is preserved with the HiFi register sharing. The default is n until the hardware FPU build has been tested. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/CMakeLists.txt | 4 ++++ src/audio/webrtc_aec/Kconfig | 11 +++++++++++ src/audio/webrtc_aec/README.md | 1 + 3 files changed, 16 insertions(+) diff --git a/src/audio/webrtc_aec/CMakeLists.txt b/src/audio/webrtc_aec/CMakeLists.txt index 48f7d50251ea..119dd8cd6164 100644 --- a/src/audio/webrtc_aec/CMakeLists.txt +++ b/src/audio/webrtc_aec/CMakeLists.txt @@ -35,6 +35,10 @@ else() endif() if(CONFIG_WEBRTC_AEC_BACKEND_AEC3) + if(CONFIG_WEBRTC_AEC_AEC3_HW_FPU) + set(_clang_fp_flags "") + endif() + if(DEFINED CONFIG_SOC_TOOLCHAIN_NAME) set(_xtensa_target "${CONFIG_SOC_TOOLCHAIN_NAME}") else() diff --git a/src/audio/webrtc_aec/Kconfig b/src/audio/webrtc_aec/Kconfig index 828e13fbb5c9..32607720ff8d 100644 --- a/src/audio/webrtc_aec/Kconfig +++ b/src/audio/webrtc_aec/Kconfig @@ -58,6 +58,17 @@ config COMP_WEBRTC_AEC_STUB that passes microphone audio through without modification. endchoice +config WEBRTC_AEC_AEC3_HW_FPU + bool "Use the hardware FPU for AEC3" + default n + depends on WEBRTC_AEC_BACKEND_AEC3 + help + Compile the AEC3 backend with the hardware floating point + instructions. By default the webrtc_aec sources are built with the + FPU disabled and the float operations are done with soft-float + library calls, which makes AEC3 too slow for real time 16 kHz + processing with a stereo echo reference. + config WEBRTC_AEC_PERF_TELEMETRY bool "Enable AEC3 cycle profiling telemetry via printk" default y diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index 5dbe19a428ed..68302985e97a 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -128,6 +128,7 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | `CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT` | y | bool (AEC3) | Dynamic stereo vs. dual-mono content detector | | `CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST` | n | bool (AEC3) | Lock AEC3 to `WEBRTC_AEC_DELAY_MS` instead of matched filter | | `CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS` | 12 | int (`1` - `30`, AEC3) | AEC3 refined/coarse adaptive filter length in 4 ms blocks | +| `CONFIG_WEBRTC_AEC_AEC3_HW_FPU` | n | bool (AEC3) | Build AEC3 with hardware FPU instructions instead of soft-float | | `CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER` | y | bool (AEC3) | Enable AEC3 coarse filter output fallback | | `CONFIG_WEBRTC_AEC_DELAY_AGNOSTIC` | n | bool (Float) | Enable signal-based delay estimation and extended filter | From b50625cb5f3c11e4f223edc5c92f74d2f4268a0d Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Thu, 3 Dec 2026 12:59:24 +0200 Subject: [PATCH 06/17] app: add a WebRTC AEC3 built-in overlay Add an overlay to build the WebRTC AEC3 backend into the base firmware for a stereo echo reference with a mono microphone (2R x 1C) at 16 kHz. The stereo content detector is disabled since it increases the peak AEC3 memory from about 600 kB to about 870 kB. AEC3 allocates from the system heap without CONFIG_USERSPACE, so the heap is increased to 1 MB. The hardware FPU is used since soft-float AEC3 is slower than real time. The tone component is enabled for the siggen in the echo reference pipeline. Signed-off-by: Seppo Ingalsuo --- app/webrtc_aec3_static_overlay.conf | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 app/webrtc_aec3_static_overlay.conf diff --git a/app/webrtc_aec3_static_overlay.conf b/app/webrtc_aec3_static_overlay.conf new file mode 100644 index 000000000000..9c34b70e34cc --- /dev/null +++ b/app/webrtc_aec3_static_overlay.conf @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# WebRTC AEC3 built into the base firmware. AEC3 supports a stereo echo +# reference with a mono microphone (2R x 1C). + +CONFIG_COMP_WEBRTC_AEC=y +CONFIG_WEBRTC_AEC_BACKEND_AEC3=y +CONFIG_WEBRTC_AEC_SAMPLE_RATE_HZ=16000 +# With the stereo content detector AEC3 starts with a mono render path and +# allocates the multichannel one when stereo content appears, peaking at about +# 870 kB for 2R x 1C. Without it the multichannel path is created at once and +# stays at about 600 kB. +CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT=n +# Soft-float AEC3 2R x 1C needs about 600 MCPS, more than real time. +CONFIG_WEBRTC_AEC_AEC3_HW_FPU=y + +# AEC3 is allocated from the system heap, the topology DP heap size is used +# only with CONFIG_USERSPACE. Make room for 2R x 1C AEC3. +CONFIG_SOF_ZEPHYR_HEAP_SIZE=0x100000 + +# siggen in the echo reference pipeline +CONFIG_COMP_TONE=y From ad6a2c60e72ed936c6cef609b7a9b3bce2d959ea Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 13:55:34 +0200 Subject: [PATCH 07/17] audio: webrtc_aec: free the old AEC3 instance before re-creating it Destroy the previous EchoCanceller3 instance and audio buffers before creating the new ones. The unique_ptr assignment frees the old object only after the new one is constructed, so a re-creation needed heap for two instances, e.g. about 1.2 MB for 2R x 1C at 16 kHz. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp b/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp index ea26158c4bd8..67b5d0a77eea 100644 --- a/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp +++ b/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp @@ -62,6 +62,9 @@ static webrtc::EchoCanceller3Config build_aec3_config(const webrtc_aec3_cfg& cfg } static void create_aec3_buffers(webrtc_aec3_inst* inst) { + /* Free the old buffers before allocating, as in create_aec3_engine() */ + inst->render_buf.reset(); + inst->capture_buf.reset(); inst->render_buf = std::make_unique( inst->cfg.sample_rate_hz, inst->cfg.num_render_channels, inst->cfg.sample_rate_hz, inst->cfg.num_render_channels, @@ -87,6 +90,12 @@ static void create_aec3_engine(webrtc_aec3_inst* inst) { inst->cfg.delay_ms = delay_ms; } + /* + * Destroy the previous instance first. The assignment below would free + * it only after the new one is constructed, needing heap for two + * instances, e.g. about 1.2 MB for 2R x 1C at 16 kHz. + */ + inst->aec3.reset(); inst->aec3 = std::make_unique( config, mc_config, inst->cfg.sample_rate_hz, inst->cfg.num_render_channels, inst->cfg.num_capture_channels); From 4e5da032c1be7ebe24c1f243d0a155b5bdfeeb89 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 13:56:27 +0200 Subject: [PATCH 08/17] audio: webrtc_aec: add AEC3 filter, adaptation, delay and linear output options Add Kconfig options to tune AEC3 for a real time stereo echo reference on the DSP: - WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS sets a shorter coarse filter. It is always adapted, also when its output is not used, so a short coarse filter saves MCPS. - WEBRTC_AEC_AEC3_ADAPT_RATE_PCT slows down the converged state adaptation, the coarse filter step and the refined filter leakage, for a more stable filter during double talk and music. - WEBRTC_AEC_MIC_DELAY_MS is used also with AEC3 as the fixed capture delay. AEC3 cancels nothing if the echo arrives less than about 3 ms after the reference, as happens on PTL. - WEBRTC_AEC_AEC3_LINEAR_OUTPUT outputs the linear filter result without the residual echo suppression and comfort noise, for a more linear signal to keyword and speech recognition. The suppressor is then not run, which saves MCPS. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/Kconfig | 43 +++++++++++++-- src/audio/webrtc_aec/README.md | 4 ++ src/audio/webrtc_aec/webrtc_aec-aec3.c | 12 +++-- src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp | 57 ++++++++++++++++++-- src/audio/webrtc_aec/webrtc_aec3_wrapper.h | 4 ++ 5 files changed, 109 insertions(+), 11 deletions(-) diff --git a/src/audio/webrtc_aec/Kconfig b/src/audio/webrtc_aec/Kconfig index 32607720ff8d..9d3922b513e2 100644 --- a/src/audio/webrtc_aec/Kconfig +++ b/src/audio/webrtc_aec/Kconfig @@ -117,16 +117,17 @@ config WEBRTC_AEC_REF_GAIN reference level shortens that. No clipping risk, the AEC is float. config WEBRTC_AEC_MIC_DELAY_MS - int "Float AEC microphone delay in ms" + int "AEC microphone delay in ms" range 0 20 default 8 - depends on WEBRTC_AEC_BACKEND_FLOAT + depends on WEBRTC_AEC_BACKEND_FLOAT || WEBRTC_AEC_BACKEND_AEC3 help Delay the microphone signal before the AEC. The AEC cannot cancel echo that arrives before the reference, so if the reference path latency varies by a few ms between stream starts, a mic delay of a few ms keeps the echo causal. Adds the same latency to the - capture. + capture. With AEC3 this sets the fixed capture delay in the + AEC3 delay configuration. config WEBRTC_AEC_DELAY_DEBUG bool "Float AEC echo delay estimation trace" @@ -216,6 +217,42 @@ config WEBRTC_AEC_AEC3_COARSE_FILTER Enable AEC3 coarse linear filter output selection when the refined filter temporarily diverges. +config WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS + int "AEC3 coarse adaptive filter length in 4 ms blocks" + range 0 30 + default 0 + depends on WEBRTC_AEC_BACKEND_AEC3 + help + Length of the AEC3 coarse filter, 0 for the same length as the + refined filter. The coarse filter is always adapted, also with + WEBRTC_AEC_AEC3_COARSE_FILTER disabled, so a shorter coarse filter + saves MCPS. A value larger than WEBRTC_AEC_AEC3_FILTER_BLOCKS is + limited to it. + +config WEBRTC_AEC_AEC3_LINEAR_OUTPUT + bool "Output the AEC3 linear filter result" + default n + depends on WEBRTC_AEC_BACKEND_AEC3 + help + Output the echo cancelled signal of the AEC3 linear adaptive filter, + without the residual echo suppression and comfort noise. This gives + a more linear signal for e.g. keyword recognition, with more + residual echo. Supported at 16 kHz processing rate only. The + residual echo suppressor is not run, which also saves MCPS. + +config WEBRTC_AEC_AEC3_ADAPT_RATE_PCT + int "AEC3 converged state adaptation speed in percent" + range 10 100 + default 100 + depends on WEBRTC_AEC_BACKEND_AEC3 + help + Scale the AEC3 coarse filter NLMS step and the refined filter + leakage, which limits how fast the refined filter step size can + grow, after the initial convergence. A smaller value gives a more + stable filter with less misadjustment during double talk and music, + but slower tracking of echo path changes. 100 keeps the WebRTC + defaults. + config WEBRTC_AEC_DELAY_AGNOSTIC bool "Enable delay-agnostic mode in Classic Float AEC" default n diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index 68302985e97a..c189aa7c99ed 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -122,6 +122,7 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | `CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL` | 1 | int (`0` - `2`) | AECm comfort-noise suppression level | | `CONFIG_WEBRTC_AEC_SAMPLE_RATE_HZ` | 16000 | int (`8000`, `16000`) | Native AEC processing rate (32/48 kHz resampled) | | `CONFIG_WEBRTC_AEC_DELAY_MS` | 0 (Float), 20 | int (`0` - `15` Float, `0` - `500`) | Nominal echo path / soundcard buffer delay in ms; for Float the reference to echo delay, must not exceed the real delay | +| `CONFIG_WEBRTC_AEC_MIC_DELAY_MS` | 8 | int (`0` - `20`, Float and AEC3) | Microphone delay to keep the echo after the reference, AEC3 fixed capture delay | | `CONFIG_WEBRTC_AEC_REF_GAIN` | 16 | int (`1` - `256`) | Float AEC linear gain on the reference, speeds up convergence | | `CONFIG_WEBRTC_AEC_DELAY_DEBUG` | n | bool | Float AEC delay estimate and level trace every 5 s | | `CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF` | n | bool | Downmix multi-channel reference to mono before AEC | @@ -130,6 +131,9 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | `CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS` | 12 | int (`1` - `30`, AEC3) | AEC3 refined/coarse adaptive filter length in 4 ms blocks | | `CONFIG_WEBRTC_AEC_AEC3_HW_FPU` | n | bool (AEC3) | Build AEC3 with hardware FPU instructions instead of soft-float | | `CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER` | y | bool (AEC3) | Enable AEC3 coarse filter output fallback | +| `CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS` | 0 | int (`0` - `30`, AEC3) | AEC3 coarse filter length in 4 ms blocks, 0 for the refined filter length | +| `CONFIG_WEBRTC_AEC_AEC3_LINEAR_OUTPUT` | n | bool (AEC3) | Output the linear filter result and skip the residual echo suppressor, 16 kHz only | +| `CONFIG_WEBRTC_AEC_AEC3_ADAPT_RATE_PCT` | 100 | int (`10` - `100`, AEC3) | Converged state coarse filter step and refined filter leakage in percent | | `CONFIG_WEBRTC_AEC_DELAY_AGNOSTIC` | n | bool (Float) | Enable signal-based delay estimation and extended filter | --- diff --git a/src/audio/webrtc_aec/webrtc_aec-aec3.c b/src/audio/webrtc_aec/webrtc_aec-aec3.c index 50f445de3bc9..efb1c70078ee 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec3.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec3.c @@ -65,6 +65,10 @@ static int webrtc_aec3_backend_configure(struct processing_module *mod, int samp #else .filter_length_blocks = 12, #endif + .coarse_filter_length_blocks = CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS, + .linear_output = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_LINEAR_OUTPUT), + .adapt_rate_pct = CONFIG_WEBRTC_AEC_AEC3_ADAPT_RATE_PCT, + .capture_delay_ms = CONFIG_WEBRTC_AEC_MIC_DELAY_MS, .use_external_delay_estimator = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST), .enable_coarse_filter = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER), .detect_stereo_content = IS_ENABLED(CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT), @@ -92,10 +96,12 @@ static int webrtc_aec3_backend_configure(struct processing_module *mod, int samp rd->num_mic_channels = cfg.num_capture_channels; rd->num_ref_channels = cfg.num_render_channels; - comp_info(mod->dev, "webrtc_aec: AEC3 configured rate=%d mic=%d ref=%d blocks=%d ext_delay=%d stereo_det=%d", + comp_info(mod->dev, "webrtc_aec: AEC3 configured rate=%d mic=%d ref=%d blocks=%d coarse=%d ext_delay=%d stereo_det=%d linear=%d adapt=%d%% mic_delay=%d ms", sample_rate_hz, rd->num_mic_channels, rd->num_ref_channels, - cfg.filter_length_blocks, cfg.use_external_delay_estimator, - cfg.detect_stereo_content); + cfg.filter_length_blocks, cfg.coarse_filter_length_blocks, + cfg.use_external_delay_estimator, cfg.detect_stereo_content, + cfg.linear_output && sample_rate_hz == 16000, cfg.adapt_rate_pct, + cfg.capture_delay_ms); return 0; } diff --git a/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp b/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp index 67b5d0a77eea..2984a5f23536 100644 --- a/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp +++ b/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp @@ -16,6 +16,7 @@ struct webrtc_aec3_inst { std::unique_ptr aec3; std::unique_ptr render_buf; std::unique_ptr capture_buf; + std::unique_ptr linear_buf; /* linear output, if enabled */ webrtc_aec3_cfg cfg; std::atomic pending_delay_ms{-1}; std::atomic high_suppression{false}; @@ -36,10 +37,38 @@ static webrtc::EchoCanceller3Config build_aec3_config(const webrtc_aec3_cfg& cfg size_t init_blocks = std::min(blocks, (size_t)12); config.filter.refined.length_blocks = blocks; config.filter.refined_initial.length_blocks = init_blocks; - config.filter.coarse.length_blocks = blocks; - config.filter.coarse_initial.length_blocks = init_blocks; + /* + * The coarse filter is always adapted, also when its output is not used. + * A shorter coarse filter saves MCPS, it only needs to cover the main + * part of the echo path to detect the refined filter divergence. + */ + size_t coarse_blocks = cfg.coarse_filter_length_blocks > 0 ? + std::min((size_t)cfg.coarse_filter_length_blocks, blocks) : blocks; + config.filter.coarse.length_blocks = coarse_blocks; + config.filter.coarse_initial.length_blocks = std::min(init_blocks, coarse_blocks); config.filter.enable_coarse_filter_output_usage = cfg.enable_coarse_filter; + /* + * Slow down the converged state adaptation for a more stable filter: the + * coarse filter NLMS step and the refined filter leakage, which limits how + * fast its step size can grow. The initial state is kept for convergence. + */ + if (cfg.adapt_rate_pct > 0 && cfg.adapt_rate_pct < 100) { + const float scale = cfg.adapt_rate_pct / 100.f; + + config.filter.coarse.rate *= scale; + config.filter.refined.leakage_converged *= scale; + config.filter.refined.leakage_diverged *= scale; + } + + /* Delay the capture to keep the echo after the reference */ + if (cfg.capture_delay_ms > 0) + config.delay.fixed_capture_delay_samples = + (size_t)cfg.capture_delay_ms * cfg.sample_rate_hz / 1000; + + /* Export the linear filter output, before the suppressor and comfort noise */ + config.filter.export_linear_aec_output = cfg.linear_output && cfg.sample_rate_hz == 16000; + /* Keep single-section ERLE and disable nonlinear reverb modeling to fit DSP MCPS. */ config.erle.num_sections = 1; config.echo_model.model_reverb_in_nonlinear_mode = false; @@ -65,6 +94,7 @@ static void create_aec3_buffers(webrtc_aec3_inst* inst) { /* Free the old buffers before allocating, as in create_aec3_engine() */ inst->render_buf.reset(); inst->capture_buf.reset(); + inst->linear_buf.reset(); inst->render_buf = std::make_unique( inst->cfg.sample_rate_hz, inst->cfg.num_render_channels, inst->cfg.sample_rate_hz, inst->cfg.num_render_channels, @@ -73,6 +103,11 @@ static void create_aec3_buffers(webrtc_aec3_inst* inst) { inst->cfg.sample_rate_hz, inst->cfg.num_capture_channels, inst->cfg.sample_rate_hz, inst->cfg.num_capture_channels, inst->cfg.sample_rate_hz, inst->cfg.num_capture_channels); + if (inst->cfg.linear_output && inst->cfg.sample_rate_hz == 16000) + inst->linear_buf = std::make_unique( + 16000, inst->cfg.num_capture_channels, + 16000, inst->cfg.num_capture_channels, + 16000, inst->cfg.num_capture_channels); } static void create_aec3_engine(webrtc_aec3_inst* inst) { @@ -100,7 +135,12 @@ static void create_aec3_engine(webrtc_aec3_inst* inst) { config, mc_config, inst->cfg.sample_rate_hz, inst->cfg.num_render_channels, inst->cfg.num_capture_channels); inst->aec3->SetAudioBufferDelay(inst->cfg.delay_ms); - inst->aec3->SetCaptureOutputUsage(true); + /* + * With the linear output the suppressed capture signal is not used. AEC3 + * then skips the residual echo estimation, suppression gain and filter. + */ + inst->aec3->SetCaptureOutputUsage(!(inst->cfg.linear_output && + inst->cfg.sample_rate_hz == 16000)); } extern "C" { @@ -174,10 +214,17 @@ int webrtc_aec3_process(webrtc_aec3_inst_t* inst, const float* const* mic, size_ std::memcpy(dst, mic[ch], num_samples * sizeof(float)); } - inst->aec3->ProcessCapture(inst->capture_buf.get(), false); + webrtc::AudioBuffer* result = inst->capture_buf.get(); + + if (inst->linear_buf) { + inst->aec3->ProcessCapture(inst->capture_buf.get(), inst->linear_buf.get(), false); + result = inst->linear_buf.get(); + } else { + inst->aec3->ProcessCapture(inst->capture_buf.get(), false); + } for (size_t ch = 0; ch < num_capture_channels; ++ch) { - const float* src = inst->capture_buf->split_bands(ch)[0]; + const float* src = result->split_bands(ch)[0]; std::memcpy(out[ch], src, num_samples * sizeof(float)); } return 0; diff --git a/src/audio/webrtc_aec/webrtc_aec3_wrapper.h b/src/audio/webrtc_aec/webrtc_aec3_wrapper.h index 11c34844f025..bfdee59932ca 100644 --- a/src/audio/webrtc_aec/webrtc_aec3_wrapper.h +++ b/src/audio/webrtc_aec/webrtc_aec3_wrapper.h @@ -22,10 +22,14 @@ struct webrtc_aec3_cfg { int num_capture_channels; int delay_ms; int filter_length_blocks; + int coarse_filter_length_blocks; /* 0 for the refined filter length */ bool use_external_delay_estimator; bool enable_coarse_filter; bool detect_stereo_content; bool high_suppression; + bool linear_output; /* output the linear filter result, 16 kHz only */ + int adapt_rate_pct; /* steady state adaptation speed in percent, 0 for 100 */ + int capture_delay_ms; /* fixed microphone delay to keep the echo causal */ }; webrtc_aec3_inst_t* webrtc_aec3_create_cfg(const struct webrtc_aec3_cfg* cfg); From 824134d977d8fc48c881a656156d2284913a14dc Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 13:56:27 +0200 Subject: [PATCH 09/17] audio: webrtc_aec: trace the AEC3 metrics and ERLE With WEBRTC_AEC_PERF_TELEMETRY trace every 1 s the AEC3 delay estimate, ERL, ERLE and the maximum frame load in the last second. Support WEBRTC_AEC_ERLE_TRACE also with AEC3, with the same measure and trace format as the Float AEC. The mean of the reference channels is used, and with the linear output it is the linear filter ERLE. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/Kconfig | 13 ++- src/audio/webrtc_aec/README.md | 3 +- src/audio/webrtc_aec/webrtc_aec-aec3.c | 111 +++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 5 deletions(-) diff --git a/src/audio/webrtc_aec/Kconfig b/src/audio/webrtc_aec/Kconfig index 9d3922b513e2..6528e8593503 100644 --- a/src/audio/webrtc_aec/Kconfig +++ b/src/audio/webrtc_aec/Kconfig @@ -75,7 +75,9 @@ config WEBRTC_AEC_PERF_TELEMETRY depends on WEBRTC_AEC_BACKEND_AEC3 help Periodically emits [AEC3_P1] and [AEC3_P2] cycle count breakdowns - every 200ms to monitor DSP cycle budgets. + every 200ms to monitor DSP cycle budgets. Every 1 s the AEC3 + delay estimate, ERL, ERLE and the maximum frame load in the + last second are traced too. config WEBRTC_AEC_FILTER_LEN_MS int "AECm adaptive filter length in ms (32, 64 or 128)" @@ -142,14 +144,17 @@ config WEBRTC_AEC_DELAY_DEBUG Costs a few MCPS. config WEBRTC_AEC_ERLE_TRACE - bool "Float AEC echo return loss enhancement trace" - depends on WEBRTC_AEC_BACKEND_FLOAT + bool "AEC echo return loss enhancement trace" + depends on WEBRTC_AEC_BACKEND_FLOAT || WEBRTC_AEC_BACKEND_AEC3 help Trace every 1 s the echo return loss enhancement (ERLE), the microphone and reference levels and the share of frames with an active reference. Only frames with the reference above -50 dBFS are counted. Near-end speech in those frames lowers the reported - ERLE, so read it from far-end only periods. + ERLE, so read it from far-end only periods. With AEC3 the mean + of the reference channels is used, and with the linear output the + value is the linear filter ERLE, so it is not comparable to the + Float AEC ERLE that includes the nonlinear processing. config WEBRTC_AEC_SUPPRESSION_LEVEL int "AECm comfort-noise suppression level (0=off, 1=low, 2=medium)" diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index c189aa7c99ed..357b65506388 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -21,7 +21,7 @@ Wraps WebRTC's Acoustic Echo Cancellation algorithms behind the SOF `module_inte - **Fast Ooura RDFT**: 128-point split-radix real discrete Fourier transform replacing generic recursive FFTs. - **Branchless Soft-Float**: Fast mantissa seed lookup + Newton-Raphson iterations (`FastFloatSqrt`, `FastFloatDiv`). - **Zero Heap Allocations**: All frame buffers and filter states pre-allocated in static DSP heap during initialization. -- **Cycle Telemetry**: Built-in microsecond cycle telemetry (`CONFIG_WEBRTC_AEC_PERF_TELEMETRY`) outputting real-time phase breakdowns (`[AEC3_P1]`, `[AEC3_P2]`). +- **Cycle Telemetry**: Built-in microsecond cycle telemetry (`CONFIG_WEBRTC_AEC_PERF_TELEMETRY`) outputting real-time phase breakdowns (`[AEC3_P1]`, `[AEC3_P2]`), and a 1 s AEC3 trace of the delay estimate, ERL, ERLE and maximum frame load. --- @@ -123,6 +123,7 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | `CONFIG_WEBRTC_AEC_SAMPLE_RATE_HZ` | 16000 | int (`8000`, `16000`) | Native AEC processing rate (32/48 kHz resampled) | | `CONFIG_WEBRTC_AEC_DELAY_MS` | 0 (Float), 20 | int (`0` - `15` Float, `0` - `500`) | Nominal echo path / soundcard buffer delay in ms; for Float the reference to echo delay, must not exceed the real delay | | `CONFIG_WEBRTC_AEC_MIC_DELAY_MS` | 8 | int (`0` - `20`, Float and AEC3) | Microphone delay to keep the echo after the reference, AEC3 fixed capture delay | +| `CONFIG_WEBRTC_AEC_ERLE_TRACE` | n | bool (Float and AEC3) | 1 s ERLE, mic and reference level trace over far-end active frames; AEC3 with linear output reports the linear filter ERLE | | `CONFIG_WEBRTC_AEC_REF_GAIN` | 16 | int (`1` - `256`) | Float AEC linear gain on the reference, speeds up convergence | | `CONFIG_WEBRTC_AEC_DELAY_DEBUG` | n | bool | Float AEC delay estimate and level trace every 5 s | | `CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF` | n | bool | Downmix multi-channel reference to mono before AEC | diff --git a/src/audio/webrtc_aec/webrtc_aec-aec3.c b/src/audio/webrtc_aec/webrtc_aec-aec3.c index efb1c70078ee..f5f1109754ca 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec3.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec3.c @@ -15,11 +15,20 @@ #include #include +#include #include "webrtc_aec.h" #include "webrtc_aec3_wrapper.h" LOG_MODULE_DECLARE(webrtc_aec, CONFIG_SOF_LOG_LEVEL); +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE +/* 100 frames of 10 ms */ +#define WEBRTC_AEC3_ERLE_FRAMES 100 +/* Far-end active when the mean reference channel is above -50 dBFS */ +#define WEBRTC_AEC3_ERLE_REF_MIN (32768.0f * 32768.0f * 1e-5f) +#define WEBRTC_AEC3_FS_ENERGY (32768.0f * 32768.0f) +#endif + struct webrtc_aec3_data { webrtc_aec3_inst_t *aec3; int num_mic_channels; @@ -28,6 +37,14 @@ struct webrtc_aec3_data { uint32_t aec3_frames; uint64_t aec3_ref_cyc; uint64_t aec3_mic_cyc; + uint32_t aec3_max_cyc; /* maximum frame cycles in the trace period */ +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE + int erle_frames; /* frames in the current trace period */ + int erle_active; /* frames with an active reference */ + float erle_mic_e; /* microphone energy in the active frames */ + float erle_out_e; /* output energy in the active frames */ + float erle_ref_e; /* mean reference channel energy in the active frames */ +#endif float ref_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; float mic_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; float out_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; @@ -86,6 +103,14 @@ static int webrtc_aec3_backend_configure(struct processing_module *mod, int samp rd->aec3_frames = 0; rd->aec3_ref_cyc = 0; rd->aec3_mic_cyc = 0; + rd->aec3_max_cyc = 0; +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE + rd->erle_frames = 0; + rd->erle_active = 0; + rd->erle_mic_e = 0.0f; + rd->erle_out_e = 0.0f; + rd->erle_ref_e = 0.0f; +#endif rd->aec3 = webrtc_aec3_create_cfg(&cfg); if (!rd->aec3) { @@ -141,6 +166,80 @@ static int webrtc_aec3_backend_get_metrics(struct processing_module *mod, return webrtc_aec3_get_metrics(rd->aec3, erl_db, erle_db, delay_ms); } +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE +/** + * webrtc_aec3_db_round() - Round a dB value to the nearest integer. + * @db: value in dB + * + * Return: rounded value + */ +static int webrtc_aec3_db_round(float db) +{ + return (int)(db + (db >= 0.0f ? 0.5f : -0.5f)); +} + +/** + * webrtc_aec3_erle() - Accumulate and trace the ERLE every 1 s. + * Same measure and trace format as the Float AEC: microphone energy versus + * output energy over the frames with an active reference. The microphone + * channel 0 is used, it is the downmix for a mono output. Near-end speech in + * the active frames lowers the value. With the linear output this is the + * linear filter ERLE, which is not comparable to the Float AEC ERLE with its + * nonlinear processing. + * @mod: processing module + * @rd: backend data with the float frame buffers + * @frame_samples: samples per channel in the frame + * @num_ref_channels: reference channel count + */ +static void webrtc_aec3_erle(struct processing_module *mod, + struct webrtc_aec3_data *rd, int frame_samples, + int num_ref_channels) +{ + float ref_e = 0.0f, mic_e = 0.0f, out_e = 0.0f; + float norm; + int i, ch; + + for (ch = 0; ch < num_ref_channels; ch++) + for (i = 0; i < frame_samples; i++) + ref_e += rd->ref_f[ch][i] * rd->ref_f[ch][i]; + ref_e /= num_ref_channels; + + for (i = 0; i < frame_samples; i++) { + mic_e += rd->mic_f[0][i] * rd->mic_f[0][i]; + out_e += rd->out_f[0][i] * rd->out_f[0][i]; + } + + if (ref_e > WEBRTC_AEC3_ERLE_REF_MIN * frame_samples) { + rd->erle_ref_e += ref_e; + rd->erle_mic_e += mic_e; + rd->erle_out_e += out_e; + rd->erle_active++; + } + + if (++rd->erle_frames < WEBRTC_AEC3_ERLE_FRAMES) + return; + + if (rd->erle_active) { + float mic = rd->erle_mic_e > 1.0f ? rd->erle_mic_e : 1.0f; + float out = rd->erle_out_e > 1.0f ? rd->erle_out_e : 1.0f; + + norm = WEBRTC_AEC3_FS_ENERGY * rd->erle_active * frame_samples; + comp_info(mod->dev, + "webrtc_aec: ERLE %d dB mic %d ref %d dBFS active %d%%", + webrtc_aec3_db_round(10.0f * log10f(mic / out)), + webrtc_aec3_db_round(10.0f * log10f(mic / norm)), + webrtc_aec3_db_round(10.0f * log10f(rd->erle_ref_e / norm)), + rd->erle_active * 100 / WEBRTC_AEC3_ERLE_FRAMES); + } + + rd->erle_frames = 0; + rd->erle_active = 0; + rd->erle_mic_e = 0.0f; + rd->erle_out_e = 0.0f; + rd->erle_ref_e = 0.0f; +} +#endif + static int webrtc_aec3_backend_process_frame(struct processing_module *mod, const int16_t *const *mic, const int16_t *const *ref, @@ -211,7 +310,16 @@ static int webrtc_aec3_backend_process_frame(struct processing_module *mod, #if IS_ENABLED(CONFIG_WEBRTC_AEC_PERF_TELEMETRY) rd->aec3_ref_cyc += (uint64_t)(t1 - t0); rd->aec3_mic_cyc += (uint64_t)(t2 - t1); + rd->aec3_max_cyc = MAX(rd->aec3_max_cyc, t2 - t0); rd->aec3_frames++; + if (rd->aec3_frames % 100 == 0) { + int erl = 0, erle = 0, delay = 0; + + webrtc_aec3_get_metrics(rd->aec3, &erl, &erle, &delay); + comp_info(mod->dev, "webrtc_aec3 metrics: delay=%d ms erl=%d dB erle=%d dB max=%u kcyc", + delay, erl, erle, rd->aec3_max_cyc / 1000); + rd->aec3_max_cyc = 0; + } if (rd->aec3_frames % 20 == 0) { comp_info(mod->dev, "webrtc_aec3 (%dx%d) perf: f=%u ref=%u kcyc mic=%u kcyc tot=%u kcyc", num_ref_channels, num_mic_channels, rd->aec3_frames, @@ -234,6 +342,9 @@ static int webrtc_aec3_backend_process_frame(struct processing_module *mod, } } +#ifdef CONFIG_WEBRTC_AEC_ERLE_TRACE + webrtc_aec3_erle(mod, rd, frame_samples, num_ref_channels); +#endif return 0; } From efd69511f4cd55ad2c8b0de4932862c1d845a9f6 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 13:58:02 +0200 Subject: [PATCH 10/17] audio: webrtc_aec: create the AEC3 instance into a memory arena Without C++ exceptions a failed allocation inside AEC3 panics the DSP. With WEBRTC_AEC_AEC3_ARENA_SIZE the backend allocates one block for the instance in prepare, which fails gracefully with -ENOMEM, and creates AEC3 into it. The arena memory is not freed one by one; the whole arena is rewound when the instance is re-created. On reset the instance is destroyed and created again from the start of the arena, so stopping a stream needs no more heap. Allocations that do not fit come from the heap, and the needed size is traced. The C++ new and delete operators are global and serve also the other C++ modules, so they use the arena only while it is open for the creating thread, and the system heap otherwise. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/Kconfig | 15 ++ src/audio/webrtc_aec/README.md | 1 + src/audio/webrtc_aec/webrtc_aec-aec3.c | 72 +++++++- src/audio/webrtc_aec/webrtc_aec-shims.c | 194 ++++++++++++++++++++- src/audio/webrtc_aec/webrtc_aec.h | 35 ++++ src/audio/webrtc_aec/webrtc_aec3_shims.cpp | 56 +++--- 6 files changed, 339 insertions(+), 34 deletions(-) diff --git a/src/audio/webrtc_aec/Kconfig b/src/audio/webrtc_aec/Kconfig index 6528e8593503..149ae5c91521 100644 --- a/src/audio/webrtc_aec/Kconfig +++ b/src/audio/webrtc_aec/Kconfig @@ -69,6 +69,21 @@ config WEBRTC_AEC_AEC3_HW_FPU library calls, which makes AEC3 too slow for real time 16 kHz processing with a stereo echo reference. +config WEBRTC_AEC_AEC3_ARENA_SIZE + int "AEC3 instance memory arena size in bytes" + default 0 + depends on WEBRTC_AEC_BACKEND_AEC3 + help + Without C++ exceptions a failed allocation inside AEC3 panics the + DSP. With a non-zero size the backend allocates this much memory as + one block in prepare, which fails gracefully with -ENOMEM, and + creates the AEC3 instance into it. The instance is re-created into + the same arena on reset, so stopping a stream does not need more + heap. The used size is printed after the creation. Allocations + that do not fit come from the heap, as without the arena. E.g. 2R x + 1C at 16 kHz with 12 filter blocks needs about 600 kB. Zero + allocates the instance directly from the heap. + config WEBRTC_AEC_PERF_TELEMETRY bool "Enable AEC3 cycle profiling telemetry via printk" default y diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index 357b65506388..2c4bc2449379 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -131,6 +131,7 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | `CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST` | n | bool (AEC3) | Lock AEC3 to `WEBRTC_AEC_DELAY_MS` instead of matched filter | | `CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS` | 12 | int (`1` - `30`, AEC3) | AEC3 refined/coarse adaptive filter length in 4 ms blocks | | `CONFIG_WEBRTC_AEC_AEC3_HW_FPU` | n | bool (AEC3) | Build AEC3 with hardware FPU instructions instead of soft-float | +| `CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE` | 0 | int (bytes, AEC3) | Create AEC3 into one block allocated in prepare, to fail with -ENOMEM instead of a DSP panic, 0 to allocate from the heap | | `CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER` | y | bool (AEC3) | Enable AEC3 coarse filter output fallback | | `CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS` | 0 | int (`0` - `30`, AEC3) | AEC3 coarse filter length in 4 ms blocks, 0 for the refined filter length | | `CONFIG_WEBRTC_AEC_AEC3_LINEAR_OUTPUT` | n | bool (AEC3) | Output the linear filter result and skip the residual echo suppressor, 16 kHz only | diff --git a/src/audio/webrtc_aec/webrtc_aec-aec3.c b/src/audio/webrtc_aec/webrtc_aec-aec3.c index f5f1109754ca..48a9490aabb0 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec3.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec3.c @@ -31,6 +31,7 @@ LOG_MODULE_DECLARE(webrtc_aec, CONFIG_SOF_LOG_LEVEL); struct webrtc_aec3_data { webrtc_aec3_inst_t *aec3; + struct webrtc_aec3_cfg cfg; /* configuration for re-creation in reset */ int num_mic_channels; int num_ref_channels; int suppression; @@ -64,6 +65,43 @@ static int webrtc_aec3_backend_init(struct processing_module *mod) return 0; } +/** + * webrtc_aec3_backend_create() - Create the AEC3 instance from rd->cfg. + * With CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE the instance is created into the + * arena, which is allocated first if needed. The previous instance must have + * been freed. + * @mod: processing module + * @rd: backend data + * + * Return: 0 on success, -ENOMEM if the arena or the instance cannot be + * allocated. + */ +static int webrtc_aec3_backend_create(struct processing_module *mod, + struct webrtc_aec3_data *rd) +{ +#if WEBRTC_AEC_HAVE_ARENA + int ret; + + ret = webrtc_aec_arena_alloc(mod, CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); + if (ret < 0) + return ret; + + webrtc_aec_arena_open(); + rd->aec3 = webrtc_aec3_create_cfg(&rd->cfg); + webrtc_aec_arena_close(); + if (webrtc_aec_arena_overflow()) + comp_warn(mod->dev, "webrtc_aec: AEC3 arena overflow, %zu bytes from heap, increase arena to %zu bytes", + webrtc_aec_arena_overflow(), + webrtc_aec_arena_used() + webrtc_aec_arena_overflow()); + else + comp_info(mod->dev, "webrtc_aec: AEC3 arena used %zu of %d bytes", + webrtc_aec_arena_used(), CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); +#else + rd->aec3 = webrtc_aec3_create_cfg(&rd->cfg); +#endif + return rd->aec3 ? 0 : -ENOMEM; +} + static int webrtc_aec3_backend_configure(struct processing_module *mod, int sample_rate_hz, int filter_len_ms, int suppression, int num_mic_channels, int num_ref_channels) @@ -92,6 +130,8 @@ static int webrtc_aec3_backend_configure(struct processing_module *mod, int samp .high_suppression = (cd->high_suppression || suppression > 1), }; + int ret; + if (rd->aec3) { webrtc_aec3_free(rd->aec3); rd->aec3 = NULL; @@ -111,12 +151,13 @@ static int webrtc_aec3_backend_configure(struct processing_module *mod, int samp rd->erle_out_e = 0.0f; rd->erle_ref_e = 0.0f; #endif + rd->cfg = cfg; - rd->aec3 = webrtc_aec3_create_cfg(&cfg); - if (!rd->aec3) { - comp_err(mod->dev, "webrtc_aec: webrtc_aec3_create_cfg() failed rate=%d mic=%d ref=%d", + ret = webrtc_aec3_backend_create(mod, rd); + if (ret < 0) { + comp_err(mod->dev, "webrtc_aec: AEC3 creation failed rate=%d mic=%d ref=%d", sample_rate_hz, cfg.num_capture_channels, cfg.num_render_channels); - return -ENOMEM; + return ret; } rd->num_mic_channels = cfg.num_capture_channels; @@ -138,6 +179,7 @@ static int webrtc_aec3_backend_set_suppression(struct processing_module *mod, bo if (!rd || !rd->aec3) return 0; + rd->cfg.high_suppression = high_suppression; webrtc_aec3_set_suppression(rd->aec3, high_suppression); comp_info(mod->dev, "webrtc_aec: updated AEC3 suppression high=%d", high_suppression); return 0; @@ -151,6 +193,8 @@ static int webrtc_aec3_backend_set_delay(struct processing_module *mod, int dela if (!rd || !rd->aec3) return 0; + if (delay_ms >= 0) + rd->cfg.delay_ms = delay_ms; return webrtc_aec3_set_delay(rd->aec3, delay_ms); } @@ -366,9 +410,22 @@ static int webrtc_aec3_backend_reset(struct processing_module *mod) struct webrtc_aec_comp_data *cd = module_get_private_data(mod); struct webrtc_aec3_data *rd = cd->backend_data; - if (rd && rd->aec3) - webrtc_aec3_init(rd->aec3, cd->proc_rate); + if (!rd || !rd->aec3) + return 0; + +#if WEBRTC_AEC_HAVE_ARENA + /* + * The instance cannot be rebuilt in place in the arena. Destroy it and + * create it again from the start of the arena, this needs no heap. + */ + webrtc_aec3_free(rd->aec3); + rd->aec3 = NULL; + rd->cfg.sample_rate_hz = cd->proc_rate; + return webrtc_aec3_backend_create(mod, rd); +#else + webrtc_aec3_init(rd->aec3, cd->proc_rate); return 0; +#endif } static int webrtc_aec3_backend_free(struct processing_module *mod) @@ -383,6 +440,9 @@ static int webrtc_aec3_backend_free(struct processing_module *mod) webrtc_aec3_free(rd->aec3); rd->aec3 = NULL; } +#if WEBRTC_AEC_HAVE_ARENA + webrtc_aec_arena_free(mod); +#endif mod_free(mod, rd); cd->backend_data = NULL; return 0; diff --git a/src/audio/webrtc_aec/webrtc_aec-shims.c b/src/audio/webrtc_aec/webrtc_aec-shims.c index 936a25e26960..09344c3ea3f0 100644 --- a/src/audio/webrtc_aec/webrtc_aec-shims.c +++ b/src/audio/webrtc_aec/webrtc_aec-shims.c @@ -6,12 +6,15 @@ // // Maps malloc/calloc/free to SOF's rmalloc/rzalloc/rfree on SOF_MEM_FLAG_USER heap. +#include #include #include #include #include +#include #include #include +#include "webrtc_aec.h" #if !defined(LLEXT_MODULE) #include static APP_SYSUSER_BSS struct processing_module *active_aec_mod; @@ -23,6 +26,36 @@ static size_t webrtc_alloc_bytes; LOG_MODULE_DECLARE(webrtc_aec, CONFIG_SOF_LOG_LEVEL); +#if WEBRTC_AEC_HAVE_ARENA +/** + * \brief Bump allocator arena for the AEC3 instance. + * + * The WebRTC C++ code cannot report an allocation failure without + * exceptions, so a failed new panics the DSP. To fail gracefully the AEC3 + * backend allocates the whole instance memory as one block in prepare, + * where a failure is returned as -ENOMEM, and builds the instance into it. + * Frees of arena memory are ignored, the arena is rewound when the + * instance is destroyed. Allocations are served from the arena only in the + * thread that opened it, and when the arena is full they fall back to the + * heap. + */ +struct webrtc_aec_arena { + char *base; /**< Arena start, NULL if not allocated */ + size_t size; /**< Arena size in bytes */ + size_t used; /**< Bytes used since the last rewind */ + size_t overflow; /**< Bytes that did not fit and came from the heap */ + k_tid_t owner; /**< Thread that may allocate, NULL if closed */ +}; + +#if !defined(LLEXT_MODULE) +static APP_SYSUSER_BSS struct webrtc_aec_arena webrtc_arena; +#else +static struct webrtc_aec_arena webrtc_arena; +#endif + +#define WEBRTC_AEC_ARENA_ALIGN 16 +#endif + /** * \brief Get the bytes allocated by the WebRTC library since the last reset. * @@ -72,19 +105,173 @@ struct processing_module *webrtc_aec_get_active_mod(void) return active_aec_mod; } +#if WEBRTC_AEC_HAVE_ARENA +int webrtc_aec_arena_alloc(struct processing_module *mod, size_t size) +{ + if (webrtc_arena.base && webrtc_arena.size == size) + return 0; + + webrtc_aec_arena_free(mod); + webrtc_arena.base = mod_alloc_align(mod, size, WEBRTC_AEC_ARENA_ALIGN); + if (!webrtc_arena.base) { + comp_err(mod->dev, "webrtc_aec: failed to allocate %zu bytes AEC3 arena", size); + return -ENOMEM; + } + + webrtc_arena.size = size; + webrtc_arena.used = 0; + webrtc_arena.overflow = 0; + webrtc_arena.owner = NULL; + return 0; +} + +void webrtc_aec_arena_free(struct processing_module *mod) +{ + if (webrtc_arena.base) + mod_free(mod, webrtc_arena.base); + + webrtc_arena.base = NULL; + webrtc_arena.size = 0; + webrtc_arena.owner = NULL; +} + +void webrtc_aec_arena_open(void) +{ + webrtc_arena.used = 0; + webrtc_arena.overflow = 0; + webrtc_arena.owner = webrtc_arena.base ? k_current_get() : NULL; +} + +void webrtc_aec_arena_close(void) +{ + webrtc_arena.owner = NULL; +} + +size_t webrtc_aec_arena_used(void) +{ + return webrtc_arena.used; +} + +size_t webrtc_aec_arena_overflow(void) +{ + return webrtc_arena.overflow; +} + +/** + * \brief Check if the arena is open for the current thread. + * + * \return True if the current thread is creating an instance in the arena + */ +static bool webrtc_arena_owner_is_me(void) +{ + return webrtc_arena.owner && webrtc_arena.owner == k_current_get(); +} + +/** + * \brief Allocate from the arena if it is open for the current thread. + * + * \param[in] size Requested size in bytes + * \return Arena memory, NULL to allocate from the heap instead + */ +static void *webrtc_arena_get(size_t size) +{ + size_t start = ALIGN_UP(webrtc_arena.used, WEBRTC_AEC_ARENA_ALIGN); + + if (!webrtc_arena_owner_is_me()) + return NULL; + + if (start > webrtc_arena.size || size > webrtc_arena.size - start) { + webrtc_arena.overflow += size; + return NULL; + } + + webrtc_arena.used = start + size; + webrtc_alloc_bytes += size; + return webrtc_arena.base + start; +} + +/** + * \brief Check if memory is in the arena. + * + * \param[in] ptr Memory to check + * \return True if ptr is in the arena + */ +static bool webrtc_arena_has(const void *ptr) +{ + const char *p = ptr; + + return webrtc_arena.base && p >= webrtc_arena.base && + p < webrtc_arena.base + webrtc_arena.size; +} +#else +static inline void *webrtc_arena_get(size_t size) { return NULL; } +static inline bool webrtc_arena_owner_is_me(void) { return false; } +static inline bool webrtc_arena_has(const void *ptr) { return false; } +#endif + void *webrtc_malloc(size_t size) { + void *p; + if (size == 0) return NULL; + p = webrtc_arena_get(size); + if (p) + return p; + if (active_aec_mod) return webrtc_alloc_done(mod_alloc(active_aec_mod, size), size); return webrtc_alloc_done(rmalloc(SOF_MEM_FLAG_USER, size), size); } +/** + * \brief Allocate memory for the C++ new operators. + * + * The new operators are global, so they serve also other C++ modules than + * the AEC, possibly on other cores. Use the AEC3 arena when it is open for + * the current thread, otherwise the system heap. The module allocator of the + * AEC is not used since the memory could then be freed with the AEC module. + * + * \param[in] size Requested size in bytes + * \return Allocated memory or NULL + */ +void *webrtc_cxx_malloc(size_t size) +{ + void *p; + + if (size == 0) + size = 1; + + p = webrtc_arena_get(size); + if (p) + return p; + + p = rmalloc(SOF_MEM_FLAG_USER, size); + if (!p) + LOG_ERR("webrtc_aec: new of %zu bytes failed", size); + else if (webrtc_arena_owner_is_me()) + webrtc_alloc_bytes += size; + return p; +} + +/** + * \brief Free memory from webrtc_cxx_malloc(). + * + * \param[in] ptr Memory to free, arena memory is ignored + */ +void webrtc_cxx_free(void *ptr) +{ + if (!ptr || webrtc_arena_has(ptr)) + return; + + rfree(ptr); +} + void webrtc_free(void *ptr) { - if (!ptr) + /* Arena memory is released by rewinding the whole arena */ + if (!ptr || webrtc_arena_has(ptr)) return; if (active_aec_mod) { @@ -97,10 +284,15 @@ void webrtc_free(void *ptr) void *webrtc_calloc(size_t nmemb, size_t size) { size_t total = nmemb * size; + void *p; if (total == 0) return NULL; + p = webrtc_arena_get(total); + if (p) + return memset(p, 0, total); + if (active_aec_mod) return webrtc_alloc_done(mod_zalloc(active_aec_mod, total), total); return webrtc_alloc_done(rzalloc(SOF_MEM_FLAG_USER, total), total); diff --git a/src/audio/webrtc_aec/webrtc_aec.h b/src/audio/webrtc_aec/webrtc_aec.h index ea876660214f..c9292dd65bab 100644 --- a/src/audio/webrtc_aec/webrtc_aec.h +++ b/src/audio/webrtc_aec/webrtc_aec.h @@ -206,6 +206,41 @@ struct webrtc_aec_comp_data { /* Backend instance exported from the selected translation unit. */ extern const struct webrtc_aec_backend webrtc_aec_backend; +#if defined(CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE) && CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE > 0 +#define WEBRTC_AEC_HAVE_ARENA 1 + +/** + * \brief Allocate the AEC3 arena, keeps an existing arena of the same size. + * \param[in] mod Module that owns the arena memory + * \param[in] size Arena size in bytes + * \return 0 on success, -ENOMEM if the heap has no room for the arena + */ +int webrtc_aec_arena_alloc(struct processing_module *mod, size_t size); + +/** + * \brief Free the AEC3 arena. Destroy the instance in it first. + * \param[in] mod Module that owns the arena memory + */ +void webrtc_aec_arena_free(struct processing_module *mod); + +/** + * \brief Rewind the arena and serve the current thread allocations from it. + * The previous instance in the arena must have been destroyed. + */ +void webrtc_aec_arena_open(void); + +/** \brief Stop serving allocations from the arena. */ +void webrtc_aec_arena_close(void); + +/** \return Arena bytes used since webrtc_aec_arena_open() */ +size_t webrtc_aec_arena_used(void); + +/** \return Bytes that did not fit to the arena and were taken from the heap */ +size_t webrtc_aec_arena_overflow(void); +#else +#define WEBRTC_AEC_HAVE_ARENA 0 +#endif + #if !defined(CONFIG_COMP_WEBRTC_AEC_STUB) void webrtc_aec_set_active_mod(struct processing_module *mod); struct processing_module *webrtc_aec_get_active_mod(void); diff --git a/src/audio/webrtc_aec/webrtc_aec3_shims.cpp b/src/audio/webrtc_aec/webrtc_aec3_shims.cpp index 2b080cbb34da..90f391a20ee2 100644 --- a/src/audio/webrtc_aec/webrtc_aec3_shims.cpp +++ b/src/audio/webrtc_aec/webrtc_aec3_shims.cpp @@ -16,8 +16,8 @@ extern "C" { void *rmalloc_align(uint32_t flags, size_t bytes, uint32_t alignment); void *rmalloc(uint32_t flags, size_t bytes); void rfree(void *ptr); -void *webrtc_malloc(size_t size); -void webrtc_free(void *ptr); +void *webrtc_cxx_malloc(size_t size); +void webrtc_cxx_free(void *ptr); } #define SOF_MEM_FLAG_USER (1 << 8) @@ -26,14 +26,16 @@ void webrtc_free(void *ptr); /* * The Zephyr minimal C++ library, needed by other C++ modules such as MWW, * defines the global new and delete operators with malloc() from the small - * libc arena. The AEC3 allocations must come from the module heap, so the - * linker wraps these symbols (see CMakeLists.txt) and every reference in the - * image resolves to the versions below. The names are the Itanium C++ ABI - * manglings for a 32-bit size_t. + * libc arena. That arena is too small for AEC3, so the linker wraps these + * symbols (see CMakeLists.txt) and every reference in the image resolves to + * the versions below. They serve also the other C++ modules, so they use the + * AEC3 arena only while it is open for the creating thread, and otherwise the + * system heap, never the allocator of the AEC module. The names are the + * Itanium C++ ABI manglings for a 32-bit size_t. */ static void *webrtc_aec3_new(std::size_t size) { - void *p = webrtc_malloc(size); + void *p = webrtc_cxx_malloc(size); if (!p) k_panic(); @@ -45,73 +47,73 @@ void *__wrap__Znwj(std::size_t size) { return webrtc_aec3_new(size); } void *__wrap__Znaj(std::size_t size) { return webrtc_aec3_new(size); } void *__wrap__ZnwjRKSt9nothrow_t(std::size_t size, const std::nothrow_t &) { - return webrtc_malloc(size); + return webrtc_cxx_malloc(size); } void *__wrap__ZnajRKSt9nothrow_t(std::size_t size, const std::nothrow_t &) { - return webrtc_malloc(size); + return webrtc_cxx_malloc(size); } -void __wrap__ZdlPv(void *ptr) { webrtc_free(ptr); } -void __wrap__ZdaPv(void *ptr) { webrtc_free(ptr); } -void __wrap__ZdlPvj(void *ptr, std::size_t) { webrtc_free(ptr); } -void __wrap__ZdaPvj(void *ptr, std::size_t) { webrtc_free(ptr); } +void __wrap__ZdlPv(void *ptr) { webrtc_cxx_free(ptr); } +void __wrap__ZdaPv(void *ptr) { webrtc_cxx_free(ptr); } +void __wrap__ZdlPvj(void *ptr, std::size_t) { webrtc_cxx_free(ptr); } +void __wrap__ZdaPvj(void *ptr, std::size_t) { webrtc_cxx_free(ptr); } } /* Not defined by Zephyr, so no wrapping is needed for these */ void operator delete(void* ptr, const std::nothrow_t&) noexcept { - webrtc_free(ptr); + webrtc_cxx_free(ptr); } void operator delete[](void* ptr, const std::nothrow_t&) noexcept { - webrtc_free(ptr); + webrtc_cxx_free(ptr); } #else void* operator new(std::size_t size) { - void* p = webrtc_malloc(size); + void* p = webrtc_cxx_malloc(size); if (!p) k_panic(); return p; } void* operator new[](std::size_t size) { - void* p = webrtc_malloc(size); + void* p = webrtc_cxx_malloc(size); if (!p) k_panic(); return p; } void* operator new(std::size_t size, const std::nothrow_t&) noexcept { - return webrtc_malloc(size); + return webrtc_cxx_malloc(size); } void* operator new[](std::size_t size, const std::nothrow_t&) noexcept { - return webrtc_malloc(size); + return webrtc_cxx_malloc(size); } void operator delete(void* ptr) noexcept { - webrtc_free(ptr); + webrtc_cxx_free(ptr); } void operator delete[](void* ptr) noexcept { - webrtc_free(ptr); + webrtc_cxx_free(ptr); } void operator delete(void* ptr, std::size_t size) noexcept { (void)size; - webrtc_free(ptr); + webrtc_cxx_free(ptr); } void operator delete[](void* ptr, std::size_t size) noexcept { (void)size; - webrtc_free(ptr); + webrtc_cxx_free(ptr); } void operator delete(void* ptr, const std::nothrow_t&) noexcept { - webrtc_free(ptr); + webrtc_cxx_free(ptr); } void operator delete[](void* ptr, const std::nothrow_t&) noexcept { - webrtc_free(ptr); + webrtc_cxx_free(ptr); } #endif /* CONFIG_MINIMAL_LIBCPP */ @@ -148,7 +150,7 @@ void* AlignedMalloc(size_t size, size_t alignment) { if (size == 0) return nullptr; if (alignment < sizeof(void*)) alignment = sizeof(void*); size_t total = size + alignment + sizeof(void*); - void* orig = webrtc_malloc(total); + void* orig = webrtc_cxx_malloc(total); if (!orig) k_panic(); uintptr_t raw = reinterpret_cast(orig) + sizeof(void*); @@ -160,7 +162,7 @@ void* AlignedMalloc(size_t size, size_t alignment) { void AlignedFree(void* mem_block) { if (!mem_block) return; void* orig = reinterpret_cast(mem_block)[-1]; - webrtc_free(orig); + webrtc_cxx_free(orig); } namespace field_trial { From cea747073c4d6d8b5d76a3bfb387e94af2da994c Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Thu, 3 Dec 2026 19:28:24 +0200 Subject: [PATCH 11/17] app: webrtc_aec3_static_overlay: settings for real time stereo AEC3 Enable the AEC3 arena, linear output without the suppressor, 8 block refined and 4 block coarse filters, half speed adaptation, fixed 8 ms external delay with an 8 ms microphone delay, and the ERLE trace. The AEC3 matched filter delay search takes about 160 of 205 MCPS, the fixed delay brings the load down to about 48 MCPS. With the 8 ms microphone delay AEC3 measured a 16 ms delay on PTL, a fixed delay of 4 - 18 ms cancels it. Signed-off-by: Seppo Ingalsuo --- app/webrtc_aec3_static_overlay.conf | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/app/webrtc_aec3_static_overlay.conf b/app/webrtc_aec3_static_overlay.conf index 9c34b70e34cc..feefeaaa2c5f 100644 --- a/app/webrtc_aec3_static_overlay.conf +++ b/app/webrtc_aec3_static_overlay.conf @@ -14,9 +14,34 @@ CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT=n # Soft-float AEC3 2R x 1C needs about 600 MCPS, more than real time. CONFIG_WEBRTC_AEC_AEC3_HW_FPU=y +# With a playing reference the adaptive filters dominate the load. A 32 ms +# refined filter and a 16 ms coarse filter, instead of 48 ms for both. +CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS=8 +CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS=4 + +# Feed the keyword recognizer the linear AEC output, without the residual +# echo suppressor artefacts. The suppressor is not run. +CONFIG_WEBRTC_AEC_AEC3_LINEAR_OUTPUT=y + +# Half speed converged state adaptation for a more stable filter +CONFIG_WEBRTC_AEC_AEC3_ADAPT_RATE_PCT=50 + +# The AEC3 matched filter delay search takes about 160 of 205 MCPS. Use a +# fixed delay instead. On PTL with the 8 ms mic delay AEC3 measured 16 ms, +# a fixed 4 - 18 ms cancels it, 8 ms leaves margin both ways. +CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST=y +CONFIG_WEBRTC_AEC_DELAY_MS=8 + +# Allocate the AEC3 instance as one 640 kB block in prepare, so that a lack +# of memory fails the stream start instead of panicking the DSP. +CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE=655360 + # AEC3 is allocated from the system heap, the topology DP heap size is used # only with CONFIG_USERSPACE. Make room for 2R x 1C AEC3. CONFIG_SOF_ZEPHYR_HEAP_SIZE=0x100000 # siggen in the echo reference pipeline CONFIG_COMP_TONE=y + +# 1 s ERLE trace, read by the WoV AEC stress test script +CONFIG_WEBRTC_AEC_ERLE_TRACE=y From 431d875a4f749ce42ada30fcfa6708451d5670e1 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 11:24:30 +0200 Subject: [PATCH 12/17] audio: webrtc_aec: allocate per instance memory in prepare Allocate the FIFOs, the 16 kHz buffers and the resampler states in prepare() as one block sized for the negotiated channel counts and rate instead of worst case arrays for four channels at 48 kHz in the module data. The 16 kHz buffers and resampler states exist only when resampling. The FIFOs hold two 10 ms frames at the pipeline rate. The backend data and instance are created in prepare() too, and reset() frees everything, so a stopped stream holds no AEC memory. The AEC3 float frame buffers are sized for the configured channels. Replace the global active module, allocation counter and AEC3 arena with a per instance memory context. The module enters the context around the backend calls and the WebRTC library allocations of that thread go to the module allocator of the instance. Each AEC3 instance has its own arena, a list of the arenas lets a C++ delete in any thread find arena memory. This allows several AEC instances, e.g. a mono Float AEC and a stereo reference AEC3, at the same time. The backend reset operation is removed since prepare() now creates the backend from scratch. The unit test prepares again after the reset. Signed-off-by: Seppo Ingalsuo --- src/audio/webrtc_aec/README.md | 3 +- src/audio/webrtc_aec/webrtc_aec-aec.c | 20 -- src/audio/webrtc_aec/webrtc_aec-aec3.c | 95 ++++--- src/audio/webrtc_aec/webrtc_aec-aecm.c | 20 -- src/audio/webrtc_aec/webrtc_aec-shims.c | 263 ++++++++++-------- src/audio/webrtc_aec/webrtc_aec-stub.c | 7 - src/audio/webrtc_aec/webrtc_aec.c | 242 +++++++++++----- src/audio/webrtc_aec/webrtc_aec.h | 193 +++++++++---- .../unit/audio/webrtc_aec/webrtc_aec_ztest.c | 22 +- 9 files changed, 536 insertions(+), 329 deletions(-) diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index 2c4bc2449379..fb67589b5d1e 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -20,7 +20,8 @@ Wraps WebRTC's Acoustic Echo Cancellation algorithms behind the SOF `module_inte - **DSP Mathematical Accelerations**: - **Fast Ooura RDFT**: 128-point split-radix real discrete Fourier transform replacing generic recursive FFTs. - **Branchless Soft-Float**: Fast mantissa seed lookup + Newton-Raphson iterations (`FastFloatSqrt`, `FastFloatDiv`). - - **Zero Heap Allocations**: All frame buffers and filter states pre-allocated in static DSP heap during initialization. +- **Memory Sized at Prepare**: `init()` allocates only a small module struct. `prepare()` allocates the FIFOs and resampler states for the negotiated channel counts and rate as one block, then creates the backend instance. `reset()` frees all of it, so a stopped stream holds no AEC memory and e.g. a mono Float AEC instance never pays for AEC3 sized buffers. +- **Per-Instance Memory Context**: The WebRTC C libraries call `malloc()` and `free()` without a context. The module enters the memory context of the instance (`webrtc_aec_mem_enter()`) around backend calls, so these allocations go to the module allocator of that instance and are counted per instance. Each AEC3 instance has its own arena (`CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE`), up to `WEBRTC_AEC_ARENAS_MAX` instances at the same time. - **Cycle Telemetry**: Built-in microsecond cycle telemetry (`CONFIG_WEBRTC_AEC_PERF_TELEMETRY`) outputting real-time phase breakdowns (`[AEC3_P1]`, `[AEC3_P2]`), and a 1 s AEC3 trace of the delay estimate, ERL, ERLE and maximum frame load. --- diff --git a/src/audio/webrtc_aec/webrtc_aec-aec.c b/src/audio/webrtc_aec/webrtc_aec-aec.c index e0b200113631..2901774b17f3 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec.c @@ -570,25 +570,6 @@ static int webrtc_aec_float_process_ch(struct processing_module *mod, return webrtc_aec_float_run_ch(mod, rd, mic, rd->ref_f[0], out, frame_samples, ch); } -static int webrtc_aec_float_reset(struct processing_module *mod) -{ - struct webrtc_aec_comp_data *cd = module_get_private_data(mod); - struct webrtc_aec_float_data *rd = cd->backend_data; - int c, ret; - - for (c = 0; c < rd->num_mic_channels; c++) { - if (!rd->aec[c]) - continue; - ret = WebRtcAec_Init(rd->aec[c], cd->proc_rate, cd->proc_rate); - if (ret) { - comp_warn(mod->dev, "webrtc_aec: reset ch%d failed %d", c, ret); - continue; - } - webrtc_aec_float_apply_cfg(mod, rd, rd->aec[c], c); - } - return 0; -} - static int webrtc_aec_float_free(struct processing_module *mod) { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); @@ -618,6 +599,5 @@ const struct webrtc_aec_backend webrtc_aec_backend = { .get_metrics = webrtc_aec_float_get_metrics, .process_ch = webrtc_aec_float_process_ch, .process_frame = webrtc_aec_float_process_frame, - .reset = webrtc_aec_float_reset, .free = webrtc_aec_float_free, }; diff --git a/src/audio/webrtc_aec/webrtc_aec-aec3.c b/src/audio/webrtc_aec/webrtc_aec-aec3.c index 48a9490aabb0..f081c34efdc5 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec3.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec3.c @@ -46,9 +46,10 @@ struct webrtc_aec3_data { float erle_out_e; /* output energy in the active frames */ float erle_ref_e; /* mean reference channel energy in the active frames */ #endif - float ref_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; - float mic_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; - float out_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; + float *bufs; /* one allocation for the frame buffers below */ + float *ref_f[WEBRTC_AEC_CHANNELS_MAX]; /* num_ref_channels */ + float *mic_f[WEBRTC_AEC_CHANNELS_MAX]; /* num_mic_channels */ + float *out_f[WEBRTC_AEC_CHANNELS_MAX]; /* num_mic_channels */ }; static int webrtc_aec3_backend_init(struct processing_module *mod) @@ -65,11 +66,46 @@ static int webrtc_aec3_backend_init(struct processing_module *mod) return 0; } +/** + * webrtc_aec3_bufs_alloc() - Allocate the float frame buffers. + * One 10 ms 16 kHz buffer per reference channel and two per microphone + * channel, for the input and the output. + * @mod: processing module + * @rd: backend data + * @num_mic_channels: microphone channel count + * @num_ref_channels: reference channel count + * + * Return: 0 on success, -ENOMEM if the allocation fails. + */ +static int webrtc_aec3_bufs_alloc(struct processing_module *mod, struct webrtc_aec3_data *rd, + int num_mic_channels, int num_ref_channels) +{ + const int len = WEBRTC_AEC_FRAME_SAMPLES_16K; + float *p; + int ch; + + if (rd->bufs) + mod_free(mod, rd->bufs); + + rd->bufs = mod_alloc(mod, sizeof(float) * len * (num_ref_channels + 2 * num_mic_channels)); + if (!rd->bufs) + return -ENOMEM; + + p = rd->bufs; + for (ch = 0; ch < num_ref_channels; ch++, p += len) + rd->ref_f[ch] = p; + for (ch = 0; ch < num_mic_channels; ch++, p += len) + rd->mic_f[ch] = p; + for (ch = 0; ch < num_mic_channels; ch++, p += len) + rd->out_f[ch] = p; + return 0; +} + /** * webrtc_aec3_backend_create() - Create the AEC3 instance from rd->cfg. * With CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE the instance is created into the - * arena, which is allocated first if needed. The previous instance must have - * been freed. + * arena of the instance, which is allocated first if needed. The previous + * AEC3 instance must have been freed. * @mod: processing module * @rd: backend data * @@ -80,22 +116,23 @@ static int webrtc_aec3_backend_create(struct processing_module *mod, struct webrtc_aec3_data *rd) { #if WEBRTC_AEC_HAVE_ARENA + struct webrtc_aec_comp_data *cd = module_get_private_data(mod); + struct webrtc_aec_arena *arena = &cd->mem.arena; int ret; - ret = webrtc_aec_arena_alloc(mod, CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); + ret = webrtc_aec_arena_alloc(&cd->mem, CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); if (ret < 0) return ret; - webrtc_aec_arena_open(); + webrtc_aec_arena_open(&cd->mem); rd->aec3 = webrtc_aec3_create_cfg(&rd->cfg); - webrtc_aec_arena_close(); - if (webrtc_aec_arena_overflow()) + webrtc_aec_arena_close(&cd->mem); + if (arena->overflow) comp_warn(mod->dev, "webrtc_aec: AEC3 arena overflow, %zu bytes from heap, increase arena to %zu bytes", - webrtc_aec_arena_overflow(), - webrtc_aec_arena_used() + webrtc_aec_arena_overflow()); + arena->overflow, arena->used + arena->overflow); else comp_info(mod->dev, "webrtc_aec: AEC3 arena used %zu of %d bytes", - webrtc_aec_arena_used(), CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); + arena->used, CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); #else rd->aec3 = webrtc_aec3_create_cfg(&rd->cfg); #endif @@ -153,6 +190,12 @@ static int webrtc_aec3_backend_configure(struct processing_module *mod, int samp #endif rd->cfg = cfg; + ret = webrtc_aec3_bufs_alloc(mod, rd, cfg.num_capture_channels, cfg.num_render_channels); + if (ret < 0) { + comp_err(mod->dev, "webrtc_aec: AEC3 frame buffer allocation failed"); + return ret; + } + ret = webrtc_aec3_backend_create(mod, rd); if (ret < 0) { comp_err(mod->dev, "webrtc_aec: AEC3 creation failed rate=%d mic=%d ref=%d", @@ -405,29 +448,6 @@ static int webrtc_aec3_backend_process_ch(struct processing_module *mod, frame_samples, 1, 1); } -static int webrtc_aec3_backend_reset(struct processing_module *mod) -{ - struct webrtc_aec_comp_data *cd = module_get_private_data(mod); - struct webrtc_aec3_data *rd = cd->backend_data; - - if (!rd || !rd->aec3) - return 0; - -#if WEBRTC_AEC_HAVE_ARENA - /* - * The instance cannot be rebuilt in place in the arena. Destroy it and - * create it again from the start of the arena, this needs no heap. - */ - webrtc_aec3_free(rd->aec3); - rd->aec3 = NULL; - rd->cfg.sample_rate_hz = cd->proc_rate; - return webrtc_aec3_backend_create(mod, rd); -#else - webrtc_aec3_init(rd->aec3, cd->proc_rate); - return 0; -#endif -} - static int webrtc_aec3_backend_free(struct processing_module *mod) { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); @@ -441,8 +461,10 @@ static int webrtc_aec3_backend_free(struct processing_module *mod) rd->aec3 = NULL; } #if WEBRTC_AEC_HAVE_ARENA - webrtc_aec_arena_free(mod); + webrtc_aec_arena_free(&cd->mem); #endif + if (rd->bufs) + mod_free(mod, rd->bufs); mod_free(mod, rd); cd->backend_data = NULL; return 0; @@ -457,6 +479,5 @@ const struct webrtc_aec_backend webrtc_aec_backend = { .get_metrics = webrtc_aec3_backend_get_metrics, .process_ch = webrtc_aec3_backend_process_ch, .process_frame = webrtc_aec3_backend_process_frame, - .reset = webrtc_aec3_backend_reset, .free = webrtc_aec3_backend_free, }; diff --git a/src/audio/webrtc_aec/webrtc_aec-aecm.c b/src/audio/webrtc_aec/webrtc_aec-aecm.c index 03f23a0283da..bea9c1a3e952 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aecm.c +++ b/src/audio/webrtc_aec/webrtc_aec-aecm.c @@ -197,25 +197,6 @@ static int webrtc_aec_real_process_ch(struct processing_module *mod, return 0; } -static int webrtc_aec_real_reset(struct processing_module *mod) -{ - struct webrtc_aec_comp_data *cd = module_get_private_data(mod); - struct webrtc_aec_real_data *rd = cd->backend_data; - int c, ret; - - for (c = 0; c < rd->num_channels; c++) { - if (!rd->aecm[c]) - continue; - ret = WebRtcAecm_Init(rd->aecm[c], cd->proc_rate); - if (ret) { - comp_warn(mod->dev, "webrtc_aec: reset ch%d failed %d", c, ret); - continue; - } - webrtc_aec_real_apply_cfg(mod, rd, rd->aecm[c], c); - } - return 0; -} - static int webrtc_aec_real_free(struct processing_module *mod) { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); @@ -243,6 +224,5 @@ const struct webrtc_aec_backend webrtc_aec_backend = { .set_suppression = webrtc_aec_real_set_suppression, .set_delay = webrtc_aec_real_set_delay, .process_ch = webrtc_aec_real_process_ch, - .reset = webrtc_aec_real_reset, .free = webrtc_aec_real_free, }; diff --git a/src/audio/webrtc_aec/webrtc_aec-shims.c b/src/audio/webrtc_aec/webrtc_aec-shims.c index 09344c3ea3f0..9d2f56c7187d 100644 --- a/src/audio/webrtc_aec/webrtc_aec-shims.c +++ b/src/audio/webrtc_aec/webrtc_aec-shims.c @@ -4,8 +4,11 @@ // // Memory allocator shims for WebRTC modules. // -// Maps malloc/calloc/free to SOF's rmalloc/rzalloc/rfree on SOF_MEM_FLAG_USER heap. +// Maps malloc/calloc/free to the module allocator of the webrtc_aec instance +// whose memory context the current thread has entered, otherwise to SOF's +// rmalloc/rzalloc/rfree on SOF_MEM_FLAG_USER heap. +#include #include #include #include @@ -17,154 +20,158 @@ #include "webrtc_aec.h" #if !defined(LLEXT_MODULE) #include -static APP_SYSUSER_BSS struct processing_module *active_aec_mod; -static APP_SYSUSER_BSS size_t webrtc_alloc_bytes; +#define WEBRTC_AEC_BSS APP_SYSUSER_BSS #else -static struct processing_module *active_aec_mod; -static size_t webrtc_alloc_bytes; +#define WEBRTC_AEC_BSS #endif LOG_MODULE_DECLARE(webrtc_aec, CONFIG_SOF_LOG_LEVEL); -#if WEBRTC_AEC_HAVE_ARENA -/** - * \brief Bump allocator arena for the AEC3 instance. - * - * The WebRTC C++ code cannot report an allocation failure without - * exceptions, so a failed new panics the DSP. To fail gracefully the AEC3 - * backend allocates the whole instance memory as one block in prepare, - * where a failure is returned as -ENOMEM, and builds the instance into it. - * Frees of arena memory are ignored, the arena is rewound when the - * instance is destroyed. Allocations are served from the arena only in the - * thread that opened it, and when the arena is full they fall back to the - * heap. - */ -struct webrtc_aec_arena { - char *base; /**< Arena start, NULL if not allocated */ - size_t size; /**< Arena size in bytes */ - size_t used; /**< Bytes used since the last rewind */ - size_t overflow; /**< Bytes that did not fit and came from the heap */ - k_tid_t owner; /**< Thread that may allocate, NULL if closed */ -}; +/* Memory context entered by webrtc_aec_mem_enter(), NULL if none */ +static WEBRTC_AEC_BSS struct webrtc_aec_mem *webrtc_mem_cur; -#if !defined(LLEXT_MODULE) -static APP_SYSUSER_BSS struct webrtc_aec_arena webrtc_arena; -#else -static struct webrtc_aec_arena webrtc_arena; -#endif +struct webrtc_aec_mem *webrtc_aec_mem_enter(struct webrtc_aec_mem *mem) +{ + struct webrtc_aec_mem *prev = webrtc_mem_cur; -#define WEBRTC_AEC_ARENA_ALIGN 16 -#endif + mem->thread = k_current_get(); + webrtc_mem_cur = mem; + return prev; +} -/** - * \brief Get the bytes allocated by the WebRTC library since the last reset. - * - * Frees are not subtracted, so this is the allocated total, e.g. the - * footprint of a backend instance when read after its creation. - * - * \return Allocated bytes - */ -size_t webrtc_aec_get_alloc_bytes(void) +void webrtc_aec_mem_exit(struct webrtc_aec_mem *prev) { - return webrtc_alloc_bytes; + webrtc_mem_cur = prev; } /** - * \brief Reset the allocated bytes counter, see webrtc_aec_get_alloc_bytes(). + * \brief Get the memory context entered by the current thread. + * + * \return Memory context, NULL if the current thread has not entered one */ -void webrtc_aec_reset_alloc_bytes(void) +static struct webrtc_aec_mem *webrtc_mem_get(void) { - webrtc_alloc_bytes = 0; + struct webrtc_aec_mem *mem = webrtc_mem_cur; + + return mem && mem->thread == k_current_get() ? mem : NULL; } /** * \brief Account an allocation and report a failed one. * + * \param[in] mem Memory context of the allocation * \param[in] p Allocated memory, NULL if the allocation failed * \param[in] size Requested size in bytes * \return The p argument */ -static void *webrtc_alloc_done(void *p, size_t size) +static void *webrtc_alloc_done(struct webrtc_aec_mem *mem, void *p, size_t size) { if (p) - webrtc_alloc_bytes += size; - else if (active_aec_mod) - comp_err(active_aec_mod->dev, + mem->alloc_bytes += size; + else + comp_err(mem->mod->dev, "webrtc_aec: alloc of %zu bytes failed, %zu bytes allocated before", - size, webrtc_alloc_bytes); + size, mem->alloc_bytes); return p; } -void webrtc_aec_set_active_mod(struct processing_module *mod) +#if WEBRTC_AEC_HAVE_ARENA +#define WEBRTC_AEC_ARENA_ALIGN 16 + +/* + * Arenas of all instances. C++ memory can be freed in any thread, e.g. in + * processing, so a free looks up all arenas. Changed only in IPC context. + */ +static WEBRTC_AEC_BSS struct webrtc_aec_arena *webrtc_arenas[WEBRTC_AEC_ARENAS_MAX]; + +/** + * \brief Add an arena to the arena list. + * + * \param[in] arena Arena with allocated memory + * \return 0 on success, -ENOMEM if the list is full + */ +static int webrtc_arena_register(struct webrtc_aec_arena *arena) { - active_aec_mod = mod; + int i; + + for (i = 0; i < WEBRTC_AEC_ARENAS_MAX; i++) { + if (!webrtc_arenas[i]) { + webrtc_arenas[i] = arena; + return 0; + } + } + + return -ENOMEM; } -struct processing_module *webrtc_aec_get_active_mod(void) +/** + * \brief Remove an arena from the arena list. + * + * \param[in] arena Arena to remove + */ +static void webrtc_arena_unregister(struct webrtc_aec_arena *arena) { - return active_aec_mod; + int i; + + for (i = 0; i < WEBRTC_AEC_ARENAS_MAX; i++) + if (webrtc_arenas[i] == arena) + webrtc_arenas[i] = NULL; } -#if WEBRTC_AEC_HAVE_ARENA -int webrtc_aec_arena_alloc(struct processing_module *mod, size_t size) +int webrtc_aec_arena_alloc(struct webrtc_aec_mem *mem, size_t size) { - if (webrtc_arena.base && webrtc_arena.size == size) + struct webrtc_aec_arena *arena = &mem->arena; + int ret; + + if (arena->base && arena->size == size) return 0; - webrtc_aec_arena_free(mod); - webrtc_arena.base = mod_alloc_align(mod, size, WEBRTC_AEC_ARENA_ALIGN); - if (!webrtc_arena.base) { - comp_err(mod->dev, "webrtc_aec: failed to allocate %zu bytes AEC3 arena", size); + webrtc_aec_arena_free(mem); + arena->base = mod_alloc_align(mem->mod, size, WEBRTC_AEC_ARENA_ALIGN); + if (!arena->base) { + comp_err(mem->mod->dev, "webrtc_aec: failed to allocate %zu bytes AEC3 arena", + size); return -ENOMEM; } - webrtc_arena.size = size; - webrtc_arena.used = 0; - webrtc_arena.overflow = 0; - webrtc_arena.owner = NULL; - return 0; -} - -void webrtc_aec_arena_free(struct processing_module *mod) -{ - if (webrtc_arena.base) - mod_free(mod, webrtc_arena.base); + arena->size = size; + arena->used = 0; + arena->overflow = 0; + arena->open = false; + ret = webrtc_arena_register(arena); + if (ret < 0) { + comp_err(mem->mod->dev, "webrtc_aec: more than %d AEC3 arenas", + WEBRTC_AEC_ARENAS_MAX); + webrtc_aec_arena_free(mem); + } - webrtc_arena.base = NULL; - webrtc_arena.size = 0; - webrtc_arena.owner = NULL; + return ret; } -void webrtc_aec_arena_open(void) +void webrtc_aec_arena_free(struct webrtc_aec_mem *mem) { - webrtc_arena.used = 0; - webrtc_arena.overflow = 0; - webrtc_arena.owner = webrtc_arena.base ? k_current_get() : NULL; -} + struct webrtc_aec_arena *arena = &mem->arena; -void webrtc_aec_arena_close(void) -{ - webrtc_arena.owner = NULL; -} + if (!arena->base) + return; -size_t webrtc_aec_arena_used(void) -{ - return webrtc_arena.used; + webrtc_arena_unregister(arena); + mod_free(mem->mod, arena->base); + arena->base = NULL; + arena->size = 0; + arena->open = false; } -size_t webrtc_aec_arena_overflow(void) +void webrtc_aec_arena_open(struct webrtc_aec_mem *mem) { - return webrtc_arena.overflow; + mem->arena.used = 0; + mem->arena.overflow = 0; + mem->arena.open = mem->arena.base != NULL; } -/** - * \brief Check if the arena is open for the current thread. - * - * \return True if the current thread is creating an instance in the arena - */ -static bool webrtc_arena_owner_is_me(void) +void webrtc_aec_arena_close(struct webrtc_aec_mem *mem) { - return webrtc_arena.owner && webrtc_arena.owner == k_current_get(); + mem->arena.open = false; } /** @@ -175,42 +182,54 @@ static bool webrtc_arena_owner_is_me(void) */ static void *webrtc_arena_get(size_t size) { - size_t start = ALIGN_UP(webrtc_arena.used, WEBRTC_AEC_ARENA_ALIGN); + struct webrtc_aec_mem *mem = webrtc_mem_get(); + struct webrtc_aec_arena *arena; + size_t start; - if (!webrtc_arena_owner_is_me()) + if (!mem || !mem->arena.open) return NULL; - if (start > webrtc_arena.size || size > webrtc_arena.size - start) { - webrtc_arena.overflow += size; + arena = &mem->arena; + start = ALIGN_UP(arena->used, WEBRTC_AEC_ARENA_ALIGN); + if (start > arena->size || size > arena->size - start) { + arena->overflow += size; return NULL; } - webrtc_arena.used = start + size; - webrtc_alloc_bytes += size; - return webrtc_arena.base + start; + arena->used = start + size; + mem->alloc_bytes += size; + return arena->base + start; } /** - * \brief Check if memory is in the arena. + * \brief Check if memory is in an arena. * * \param[in] ptr Memory to check - * \return True if ptr is in the arena + * \return True if ptr is in the arena of any instance */ static bool webrtc_arena_has(const void *ptr) { + const struct webrtc_aec_arena *arena; const char *p = ptr; + int i; - return webrtc_arena.base && p >= webrtc_arena.base && - p < webrtc_arena.base + webrtc_arena.size; + for (i = 0; i < WEBRTC_AEC_ARENAS_MAX; i++) { + arena = webrtc_arenas[i]; + if (arena && arena->base && p >= arena->base && + p < arena->base + arena->size) + return true; + } + + return false; } #else static inline void *webrtc_arena_get(size_t size) { return NULL; } -static inline bool webrtc_arena_owner_is_me(void) { return false; } static inline bool webrtc_arena_has(const void *ptr) { return false; } #endif void *webrtc_malloc(size_t size) { + struct webrtc_aec_mem *mem; void *p; if (size == 0) @@ -220,9 +239,10 @@ void *webrtc_malloc(size_t size) if (p) return p; - if (active_aec_mod) - return webrtc_alloc_done(mod_alloc(active_aec_mod, size), size); - return webrtc_alloc_done(rmalloc(SOF_MEM_FLAG_USER, size), size); + mem = webrtc_mem_get(); + if (mem) + return webrtc_alloc_done(mem, mod_alloc(mem->mod, size), size); + return rmalloc(SOF_MEM_FLAG_USER, size); } /** @@ -238,6 +258,7 @@ void *webrtc_malloc(size_t size) */ void *webrtc_cxx_malloc(size_t size) { + struct webrtc_aec_mem *mem; void *p; if (size == 0) @@ -248,10 +269,11 @@ void *webrtc_cxx_malloc(size_t size) return p; p = rmalloc(SOF_MEM_FLAG_USER, size); + mem = webrtc_mem_get(); if (!p) LOG_ERR("webrtc_aec: new of %zu bytes failed", size); - else if (webrtc_arena_owner_is_me()) - webrtc_alloc_bytes += size; + else if (mem) + mem->alloc_bytes += size; return p; } @@ -270,12 +292,15 @@ void webrtc_cxx_free(void *ptr) void webrtc_free(void *ptr) { + struct webrtc_aec_mem *mem; + /* Arena memory is released by rewinding the whole arena */ if (!ptr || webrtc_arena_has(ptr)) return; - if (active_aec_mod) { - mod_free(active_aec_mod, ptr); + mem = webrtc_mem_get(); + if (mem) { + mod_free(mem->mod, ptr); return; } rfree(ptr); @@ -283,6 +308,7 @@ void webrtc_free(void *ptr) void *webrtc_calloc(size_t nmemb, size_t size) { + struct webrtc_aec_mem *mem; size_t total = nmemb * size; void *p; @@ -293,9 +319,10 @@ void *webrtc_calloc(size_t nmemb, size_t size) if (p) return memset(p, 0, total); - if (active_aec_mod) - return webrtc_alloc_done(mod_zalloc(active_aec_mod, total), total); - return webrtc_alloc_done(rzalloc(SOF_MEM_FLAG_USER, total), total); + mem = webrtc_mem_get(); + if (mem) + return webrtc_alloc_done(mem, mod_zalloc(mem->mod, total), total); + return rzalloc(SOF_MEM_FLAG_USER, total); } void *webrtc_realloc(void *ptr, size_t size) diff --git a/src/audio/webrtc_aec/webrtc_aec-stub.c b/src/audio/webrtc_aec/webrtc_aec-stub.c index 26a765137af1..fa9216ca1346 100644 --- a/src/audio/webrtc_aec/webrtc_aec-stub.c +++ b/src/audio/webrtc_aec/webrtc_aec-stub.c @@ -52,12 +52,6 @@ static int webrtc_aec_stub_set_delay(struct processing_module *mod, int delay_ms return 0; } -static int webrtc_aec_stub_reset(struct processing_module *mod) -{ - (void)mod; - return 0; -} - static int webrtc_aec_stub_free(struct processing_module *mod) { (void)mod; @@ -71,6 +65,5 @@ const struct webrtc_aec_backend webrtc_aec_backend = { .set_suppression = webrtc_aec_stub_set_suppression, .set_delay = webrtc_aec_stub_set_delay, .process_ch = webrtc_aec_stub_process_ch, - .reset = webrtc_aec_stub_reset, .free = webrtc_aec_stub_free, }; diff --git a/src/audio/webrtc_aec/webrtc_aec.c b/src/audio/webrtc_aec/webrtc_aec.c index f6e8c804159f..b2aa31042653 100644 --- a/src/audio/webrtc_aec/webrtc_aec.c +++ b/src/audio/webrtc_aec/webrtc_aec.c @@ -71,7 +71,7 @@ LOG_MODULE_REGISTER(webrtc_aec, CONFIG_SOF_LOG_LEVEL); * @is_s32: true if the pipeline format is S32_LE */ static void src_to_s16(struct sof_source *src, int n, - int16_t dst[][WEBRTC_AEC_FIFO_FRAMES], + int16_t *const *dst, int frame0, int ch, bool is_s32) { size_t sample_sz = is_s32 ? sizeof(int32_t) : sizeof(int16_t); @@ -129,7 +129,7 @@ static void src_to_s16(struct sof_source *src, int n, * @is_s32: true if the pipeline format is S32_LE */ static void src_to_s16_avg(struct sof_source *src, int n, - int16_t dst[][WEBRTC_AEC_FIFO_FRAMES], + int16_t *const *dst, int frame0, int ch, bool is_s32) { size_t sample_sz = is_s32 ? sizeof(int32_t) : sizeof(int16_t); @@ -188,7 +188,7 @@ static void src_to_s16_avg(struct sof_source *src, int n, * @ch: number of channels * @is_s32: true if the pipeline format is S32_LE */ -static void s16_to_sink(struct sof_sink *dst, int16_t src[][WEBRTC_AEC_FIFO_FRAMES], +static void s16_to_sink(struct sof_sink *dst, int16_t *const *src, int n, int ch, bool is_s32) { size_t sample_sz = is_s32 ? sizeof(int32_t) : sizeof(int16_t); @@ -287,17 +287,17 @@ __cold static int webrtc_aec_init(struct processing_module *mod) struct module_data *md = &mod->priv; struct comp_dev *dev = mod->dev; struct webrtc_aec_comp_data *cd; - int ret; - webrtc_aec_set_active_mod(mod); assert_can_be_cold(); comp_info(dev, "webrtc_aec: init"); + /* Buffers and backend state are allocated in prepare() for the formats. */ cd = mod_zalloc(mod, sizeof(*cd)); if (!cd) return -ENOMEM; md->private = cd; + cd->mem.mod = mod; cd->backend = &webrtc_aec_backend; cd->enabled = false; cd->high_suppression = false; @@ -312,37 +312,129 @@ __cold static int webrtc_aec_init(struct processing_module *mod) mod->max_sources = 2; comp_info(dev, "webrtc_aec: backend '%s'", cd->backend->name); + return 0; +} - if (cd->backend->init) { - ret = cd->backend->init(mod); - if (ret) { - comp_err(dev, "webrtc_aec: backend init failed %d", ret); - mod_free(mod, cd); - return ret; - } +/** + * \brief Take a buffer from the prepare() allocation. + * + * \param[in] base Allocation start, NULL to only compute the size + * \param[in,out] off Offset of the next buffer in the allocation + * \param[in] size Buffer size in bytes + * \return Buffer, NULL if base is NULL + */ +static void *webrtc_aec_take(uint8_t *base, size_t *off, size_t size) +{ + void *p = base ? base + *off : NULL; + + *off += ALIGN_UP(size, WEBRTC_AEC_BUF_ALIGN); + return p; +} + +/** + * \brief Lay out the buffers for the negotiated channel counts and rate. + * + * \param[in] cd Module data with the formats set + * \param[in] base Allocation start to set the buffer pointers, NULL to only + * compute the size + * \return Allocation size in bytes + */ +static size_t webrtc_aec_bufs_layout(struct webrtc_aec_comp_data *cd, uint8_t *base) +{ + size_t fifo_bytes = (size_t)cd->fifo_frames * sizeof(int16_t); + size_t f16_bytes = WEBRTC_AEC_FRAME_SAMPLES_16K * sizeof(int16_t); + size_t off = 0; + int c; + + for (c = 0; c < cd->mic_channels; c++) { + cd->mic_buf[c] = webrtc_aec_take(base, &off, fifo_bytes); + cd->out_fifo[c] = webrtc_aec_take(base, &off, fifo_bytes); + } + for (c = 0; c < cd->ref_channels; c++) + cd->ref_buf[c] = webrtc_aec_take(base, &off, fifo_bytes); + + if (cd->resamp_mode == WEBRTC_AEC_RESAMP_NONE) + return off; + + for (c = 0; c < cd->mic_channels; c++) { + cd->mic16[c] = webrtc_aec_take(base, &off, f16_bytes); + cd->out16[c] = webrtc_aec_take(base, &off, f16_bytes); } + for (c = 0; c < cd->ref_channels; c++) + cd->ref16[c] = webrtc_aec_take(base, &off, f16_bytes); + cd->mic_down = webrtc_aec_take(base, &off, sizeof(*cd->mic_down) * cd->mic_channels); + cd->ref_down = webrtc_aec_take(base, &off, sizeof(*cd->ref_down) * cd->ref_channels); + cd->out_up = webrtc_aec_take(base, &off, sizeof(*cd->out_up) * cd->mic_channels); + if (cd->resamp_mode == WEBRTC_AEC_RESAMP_48_TO_16) + cd->resamp_tmpmem = webrtc_aec_take(base, &off, + sizeof(int32_t) * WEBRTC_AEC_RESAMP_TMP_LEN); + + return off; +} + +/** + * \brief Allocate the buffers for the negotiated channel counts and rate. + * + * \param[in] mod Processing module with the formats set in its data + * \return 0 on success, -ENOMEM if the allocation fails + */ +static int webrtc_aec_bufs_alloc(struct processing_module *mod) +{ + struct webrtc_aec_comp_data *cd = module_get_private_data(mod); + size_t size; + + cd->fifo_frames = WEBRTC_AEC_FIFO_BLOCKS * cd->frame_samples; + size = webrtc_aec_bufs_layout(cd, NULL); + cd->bufs = mod_zalloc(mod, size); + if (!cd->bufs) { + comp_err(mod->dev, "webrtc_aec: failed to allocate %zu bytes of buffers", size); + return -ENOMEM; + } + + webrtc_aec_bufs_layout(cd, cd->bufs); + comp_info(mod->dev, "webrtc_aec: allocated %zu bytes of buffers", size); return 0; } +/** + * \brief Free the buffers and the backend state allocated in prepare(). + * + * \param[in] mod Processing module + */ +static void webrtc_aec_release(struct processing_module *mod) +{ + struct webrtc_aec_comp_data *cd = module_get_private_data(mod); + struct webrtc_aec_mem *prev; + + cd->configured = false; + if (cd->backend->free) { + prev = webrtc_aec_mem_enter(&cd->mem); + cd->backend->free(mod); + webrtc_aec_mem_exit(prev); + } + + if (cd->bufs) { + mod_free(mod, cd->bufs); + cd->bufs = NULL; + } +} + static void webrtc_aec_reset_resamplers(struct webrtc_aec_comp_data *cd) { int c; if (cd->resamp_mode == WEBRTC_AEC_RESAMP_48_TO_16) { for (c = 0; c < cd->mic_channels; c++) { - WebRtcSpl_ResetResample48khzTo16khz((void *)&cd->mic_resamp[c]); - WebRtcSpl_ResetResample16khzTo48khz((void *)&cd->out_resamp[c]); + WebRtcSpl_ResetResample48khzTo16khz((void *)&cd->mic_down[c].s48); + WebRtcSpl_ResetResample16khzTo48khz((void *)&cd->out_up[c].s48); } for (c = 0; c < cd->ref_channels; c++) - WebRtcSpl_ResetResample48khzTo16khz((void *)&cd->ref_resamp[c]); + WebRtcSpl_ResetResample48khzTo16khz((void *)&cd->ref_down[c].s48); } else if (cd->resamp_mode == WEBRTC_AEC_RESAMP_32_TO_16) { - for (c = 0; c < cd->mic_channels; c++) { - memset(cd->mic_resamp32[c], 0, sizeof(cd->mic_resamp32[c])); - memset(cd->out_resamp32[c], 0, sizeof(cd->out_resamp32[c])); - } - for (c = 0; c < cd->ref_channels; c++) - memset(cd->ref_resamp32[c], 0, sizeof(cd->ref_resamp32[c])); + memset(cd->mic_down, 0, sizeof(*cd->mic_down) * cd->mic_channels); + memset(cd->out_up, 0, sizeof(*cd->out_up) * cd->mic_channels); + memset(cd->ref_down, 0, sizeof(*cd->ref_down) * cd->ref_channels); } } @@ -352,11 +444,14 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); struct comp_dev *dev = mod->dev; + struct webrtc_aec_mem *prev; int mic_fmt, ref_fmt, out_fmt, mic_rate, ref_rate, ret; - webrtc_aec_set_active_mod(mod); assert_can_be_cold(); + /* Free the state of a previous prepare() without reset() */ + webrtc_aec_release(mod); + if ((num_of_sources != 1 && num_of_sources != 2) || num_of_sinks != 1) { comp_err(dev, "webrtc_aec: need 1 or 2 sources and 1 sink (got %d/%d)", num_of_sources, num_of_sinks); @@ -439,7 +534,6 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, cd->rate); return -EINVAL; } - webrtc_aec_reset_resamplers(cd); out_fmt = sink_get_frm_fmt(sinks[0]); if ((mic_fmt != SOF_IPC_FRAME_S16_LE && mic_fmt != SOF_IPC_FRAME_S32_LE) || @@ -471,35 +565,53 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, cd->ref_is_s32 ? "S32" : "S16", cd->out_is_s32 ? "S32" : "S16", cd->resamp_mode); + ret = webrtc_aec_bufs_alloc(mod); + if (ret) + return ret; + + webrtc_aec_reset_resamplers(cd); + + prev = webrtc_aec_mem_enter(&cd->mem); + cd->mem.alloc_bytes = 0; + ret = cd->backend->init ? cd->backend->init(mod) : 0; + if (ret) { + comp_err(dev, "webrtc_aec: backend init failed %d", ret); + goto err; + } + if (cd->backend->configure) { - webrtc_aec_reset_alloc_bytes(); ret = cd->backend->configure(mod, cd->proc_rate, CONFIG_WEBRTC_AEC_FILTER_LEN_MS, CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL, cd->mic_channels, cd->effective_ref_ch); if (ret) { comp_err(dev, "webrtc_aec: backend configure failed %d", ret); - return ret; + goto err; } - comp_info(dev, "webrtc_aec: backend allocated %zu bytes", - webrtc_aec_get_alloc_bytes()); } if (cd->backend->set_delay) cd->backend->set_delay(mod, cd->delay_ms); + webrtc_aec_mem_exit(prev); + comp_info(dev, "webrtc_aec: backend allocated %zu bytes", cd->mem.alloc_bytes); + /* * Prime output FIFO with one zeroed 10 ms frame so asymmetric sub-10 ms * pipeline periods can drain symmetrically on the first scheduling cycles. + * The buffers are zeroed by the allocation. */ cd->buffered_in_frames = 0; - for (ret = 0; ret < cd->mic_channels; ret++) - memset(cd->out_fifo[ret], 0, sizeof(int16_t) * cd->frame_samples); cd->buffered_out_frames = cd->frame_samples; cd->last_ref_ok = true; cd->ref_mismatch_warned = false; cd->configured = true; return 0; + +err: + webrtc_aec_mem_exit(prev); + webrtc_aec_release(mod); + return ret; } static int webrtc_aec_ref_surplus(struct sof_source *mic, struct sof_source *ref, @@ -530,7 +642,7 @@ static int webrtc_aec_ref_surplus(struct sof_source *mic, struct sof_source *ref return fref - MAX(fmic, ref_min); } -static void webrtc_aec_downmix_ref_s16(int16_t dst[][WEBRTC_AEC_FIFO_FRAMES], +static void webrtc_aec_downmix_ref_s16(int16_t *const *dst, int ref_channels, int nsamp) { int i, c; @@ -573,11 +685,11 @@ static void webrtc_aec_run_block(struct processing_module *mod, for (c = 0; c < cd->mic_channels; c++) { if (cd->resamp_mode == WEBRTC_AEC_RESAMP_48_TO_16) WebRtcSpl_Resample48khzTo16khz(cd->mic_buf[c], cd->mic16[c], - (void *)&cd->mic_resamp[c], + (void *)&cd->mic_down[c].s48, cd->resamp_tmpmem); else WebRtcSpl_DownsampleBy2(cd->mic_buf[c], WEBRTC_AEC_FRAME_SAMPLES_32K, - cd->mic16[c], cd->mic_resamp32[c]); + cd->mic16[c], cd->mic_down[c].s32); mic_ptrs[c] = cd->mic16[c]; out_ptrs[c] = cd->out16[c]; } @@ -585,11 +697,11 @@ static void webrtc_aec_run_block(struct processing_module *mod, for (c = 0; c < cd->effective_ref_ch; c++) { if (cd->resamp_mode == WEBRTC_AEC_RESAMP_48_TO_16) WebRtcSpl_Resample48khzTo16khz(cd->ref_buf[c], cd->ref16[c], - (void *)&cd->ref_resamp[c], + (void *)&cd->ref_down[c].s48, cd->resamp_tmpmem); else WebRtcSpl_DownsampleBy2(cd->ref_buf[c], WEBRTC_AEC_FRAME_SAMPLES_32K, - cd->ref16[c], cd->ref_resamp32[c]); + cd->ref16[c], cd->ref_down[c].s32); ref_ptrs[c] = cd->ref16[c]; } @@ -603,7 +715,8 @@ static void webrtc_aec_run_block(struct processing_module *mod, cd->mic_channels, cd->effective_ref_ch); if (ret) { for (c = 0; c < cd->mic_channels; c++) - memcpy(cd->out16[c], cd->mic16[c], sizeof(cd->out16[c])); + memcpy(cd->out16[c], cd->mic16[c], + WEBRTC_AEC_FRAME_SAMPLES_16K * sizeof(int16_t)); } } else { /* Per-channel backends cannot map R != C directly, so average ref to mono. */ @@ -627,7 +740,8 @@ static void webrtc_aec_run_block(struct processing_module *mod, cd->out16[c], WEBRTC_AEC_FRAME_SAMPLES_16K, c); if (ret) - memcpy(cd->out16[c], cd->mic16[c], sizeof(cd->out16[c])); + memcpy(cd->out16[c], cd->mic16[c], + WEBRTC_AEC_FRAME_SAMPLES_16K * sizeof(int16_t)); } } @@ -636,12 +750,12 @@ static void webrtc_aec_run_block(struct processing_module *mod, if (cd->resamp_mode == WEBRTC_AEC_RESAMP_48_TO_16) WebRtcSpl_Resample16khzTo48khz(cd->out16[c], &cd->out_fifo[c][cd->buffered_out_frames], - (void *)&cd->out_resamp[c], + (void *)&cd->out_up[c].s48, cd->resamp_tmpmem); else WebRtcSpl_UpsampleBy2(cd->out16[c], WEBRTC_AEC_FRAME_SAMPLES_16K, &cd->out_fifo[c][cd->buffered_out_frames], - cd->out_resamp32[c]); + cd->out_up[c].s32); } return; } @@ -698,7 +812,7 @@ static int webrtc_aec_process(struct processing_module *mod, int fmic, fref, n, drain, c, ref_min, surplus; bool ref_s32; - if (num_of_sources < 1 || num_of_sinks < 1) + if (!cd->configured || num_of_sources < 1 || num_of_sinks < 1) return 0; webrtc_aec_resolve_sources(sources, num_of_sources, &mic_idx, &ref_idx); @@ -712,7 +826,7 @@ static int webrtc_aec_process(struct processing_module *mod, fref = ref ? (int)source_get_data_frames_available(ref) : 0; /* Cap copy size to mic availability, input FIFO capacity, and free sink frames. */ - n = MIN(fmic, WEBRTC_AEC_FIFO_FRAMES - cd->buffered_in_frames); + n = MIN(fmic, cd->fifo_frames - cd->buffered_in_frames); n = MIN(n, (int)sink_get_free_frames(out)); if (n <= 0) { /* Drain surplus reference data even when mic/sink stalls so render never blocks. */ @@ -776,7 +890,7 @@ static int webrtc_aec_process(struct processing_module *mod, /* Process complete 10 ms blocks into out_fifo */ while (cd->buffered_in_frames >= cd->frame_samples && - cd->buffered_out_frames + cd->frame_samples <= WEBRTC_AEC_FIFO_FRAMES) { + cd->buffered_out_frames + cd->frame_samples <= cd->fifo_frames) { int fs = cd->frame_samples; webrtc_aec_run_block(mod, cd, fs); @@ -812,23 +926,14 @@ static int webrtc_aec_process(struct processing_module *mod, return 0; } +/* + * The stream stopped, free everything prepare() allocated so an idle + * instance holds no AEC memory. The next prepare() starts from scratch. + */ static int webrtc_aec_reset(struct processing_module *mod) { - struct webrtc_aec_comp_data *cd = module_get_private_data(mod); - int c; - - webrtc_aec_set_active_mod(mod); comp_dbg(mod->dev, "webrtc_aec: reset"); - cd->buffered_in_frames = 0; - cd->ref_mismatch_warned = false; - for (c = 0; c < cd->mic_channels; c++) - memset(cd->out_fifo[c], 0, sizeof(int16_t) * cd->frame_samples); - cd->buffered_out_frames = cd->frame_samples; - webrtc_aec_reset_resamplers(cd); - - if (cd->backend->reset) - return cd->backend->reset(mod); - + webrtc_aec_release(mod); return 0; } @@ -836,17 +941,14 @@ __cold static int webrtc_aec_free(struct processing_module *mod) { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); - webrtc_aec_set_active_mod(mod); assert_can_be_cold(); comp_dbg(mod->dev, "webrtc_aec: free"); - if (cd && cd->backend && cd->backend->free) - cd->backend->free(mod); - - if (webrtc_aec_get_active_mod() == mod) - webrtc_aec_set_active_mod(NULL); + if (cd) { + webrtc_aec_release(mod); + mod_free(mod, cd); + } - mod_free(mod, cd); return 0; } @@ -861,12 +963,19 @@ static int webrtc_aec_apply_ctl(struct processing_module *mod, cd->enabled = (value != 0); comp_info(dev, "webrtc_aec: switch enable = %d", cd->enabled); return 0; - case WEBRTC_AEC_CTL_ID_HIGH_SUPPRESSION: + case WEBRTC_AEC_CTL_ID_HIGH_SUPPRESSION: { + struct webrtc_aec_mem *prev; + int ret = 0; + cd->high_suppression = (value != 0); comp_info(dev, "webrtc_aec: high suppression = %d", cd->high_suppression); - if (cd->backend && cd->backend->set_suppression) - return cd->backend->set_suppression(mod, cd->high_suppression); - return 0; + if (cd->backend && cd->backend->set_suppression) { + prev = webrtc_aec_mem_enter(&cd->mem); + ret = cd->backend->set_suppression(mod, cd->high_suppression); + webrtc_aec_mem_exit(prev); + } + return ret; + } default: comp_err(dev, "webrtc_aec: unknown control id %u", id); return -EINVAL; @@ -881,7 +990,6 @@ static int webrtc_aec_set_config(struct processing_module *mod, uint32_t param_i struct webrtc_aec_comp_data *cd = module_get_private_data(mod); struct comp_dev *dev = mod->dev; - webrtc_aec_set_active_mod(mod); if (param_id == SOF_IPC4_SWITCH_CONTROL_PARAM_ID) { const struct sof_ipc4_control_msg_payload *ctl = (const struct sof_ipc4_control_msg_payload *)fragment; diff --git a/src/audio/webrtc_aec/webrtc_aec.h b/src/audio/webrtc_aec/webrtc_aec.h index c9292dd65bab..f4c2d74e2866 100644 --- a/src/audio/webrtc_aec/webrtc_aec.h +++ b/src/audio/webrtc_aec/webrtc_aec.h @@ -20,6 +20,7 @@ #define __SOF_AUDIO_WEBRTC_AEC_H__ #include +#include #include #include @@ -32,7 +33,12 @@ #define WEBRTC_AEC_FRAME_SAMPLES_32K 320 #define WEBRTC_AEC_FRAME_SAMPLES_48K 480 #define WEBRTC_AEC_FRAME_SAMPLES_MAX WEBRTC_AEC_FRAME_SAMPLES_48K -#define WEBRTC_AEC_FIFO_FRAMES (WEBRTC_AEC_FRAME_SAMPLES_MAX * 2) + +/* Input and output FIFO capacity in 10 ms frames at the pipeline rate. */ +#define WEBRTC_AEC_FIFO_BLOCKS 2 + +/* Alignment of the buffers carved from the prepare() allocation. */ +#define WEBRTC_AEC_BUF_ALIGN 8 /* Maximum supported channel count per stream (mic or ref). */ #define WEBRTC_AEC_CHANNELS_MAX 4 @@ -70,17 +76,74 @@ struct webrtc_aec_state_16_to_48 { int32_t s_24_48[8]; }; +/** \brief Per-channel downsampler state, 48 or 32 kHz to 16 kHz. */ +union webrtc_aec_down_state { + struct webrtc_aec_state_48_to_16 s48; /**< WebRtcSpl_Resample48khzTo16khz() */ + int32_t s32[8]; /**< WebRtcSpl_DownsampleBy2() */ +}; + +/** \brief Per-channel upsampler state, 16 kHz to 48 or 32 kHz. */ +union webrtc_aec_up_state { + struct webrtc_aec_state_16_to_48 s48; /**< WebRtcSpl_Resample16khzTo48khz() */ + int32_t s32[8]; /**< WebRtcSpl_UpsampleBy2() */ +}; + +/* Temporary buffer length of WebRtcSpl_Resample48khzTo16khz() and back. */ +#define WEBRTC_AEC_RESAMP_TMP_LEN 512 + +#if defined(CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE) && CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE > 0 +#define WEBRTC_AEC_HAVE_ARENA 1 +#else +#define WEBRTC_AEC_HAVE_ARENA 0 +#endif + +/* Maximum number of AEC3 instances with an arena at the same time. */ +#define WEBRTC_AEC_ARENAS_MAX 4 + +/** + * \brief Bump allocator arena for one AEC3 instance. + * + * The WebRTC C++ code cannot report an allocation failure without + * exceptions, so a failed new panics the DSP. To fail gracefully the AEC3 + * backend allocates the whole instance memory as one block in prepare, where + * a failure is returned as -ENOMEM, and builds the instance into it. Frees of + * arena memory are ignored, the arena is rewound when the instance is + * destroyed. + */ +struct webrtc_aec_arena { + char *base; /**< Arena start, NULL if not allocated */ + size_t size; /**< Arena size in bytes */ + size_t used; /**< Bytes used since the last rewind */ + size_t overflow; /**< Bytes that did not fit and came from the heap */ + bool open; /**< Allocations of the instance thread are served */ +}; + +/** + * \brief Memory context of one webrtc_aec instance. + * + * The WebRTC libraries call malloc() and free() without a context, so the + * module enters its memory context around every backend call that may + * allocate or free, see webrtc_aec_mem_enter(). The C library allocations + * then go to the module allocator of this instance and are accounted here. + */ +struct webrtc_aec_mem { + struct processing_module *mod; /**< Module that owns the allocations */ + k_tid_t thread; /**< Thread that entered the context */ + size_t alloc_bytes; /**< Bytes allocated since the last reset */ + struct webrtc_aec_arena arena; /**< AEC3 arena, unused without one */ +}; + /** * struct webrtc_aec_backend - AEC backend operations. */ struct webrtc_aec_backend { const char *name; - /* One-time allocation, called from init(). */ + /* Allocate the backend data. Called from prepare(), before configure(). */ int (*init)(struct processing_module *mod); /** - * Open/configure AEC state. Called from prepare(). + * Open/configure AEC state. Called from prepare() after init(). * @sample_rate_hz: 8000 or 16000 * @filter_len_ms: adaptive filter length (32/64/128) * @suppression: CNG/NLP level 0..2 @@ -130,10 +193,10 @@ struct webrtc_aec_backend { int frame_samples, int num_mic_channels, int num_ref_channels); - /* Reset adaptive filters (keep configuration). Called from reset(). */ - int (*reset)(struct processing_module *mod); - - /* Tear down all state from configure(). */ + /* + * Tear down all state from init() and configure(). Called from reset() + * and free(), the next prepare() calls init() and configure() again. + */ int (*free)(struct processing_module *mod); }; @@ -177,24 +240,27 @@ struct webrtc_aec_comp_data { int buffered_in_frames; int buffered_out_frames; - /* Per-channel S16 scratch buffers. */ - int16_t mic_buf[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FIFO_FRAMES]; - int16_t ref_buf[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FIFO_FRAMES]; - int16_t out_fifo[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FIFO_FRAMES]; - int16_t mic16[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; - int16_t ref16[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; - int16_t out16[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; - - /* Resampler state for 48kHz <-> 16kHz */ - struct webrtc_aec_state_48_to_16 mic_resamp[WEBRTC_AEC_CHANNELS_MAX]; - struct webrtc_aec_state_48_to_16 ref_resamp[WEBRTC_AEC_CHANNELS_MAX]; - struct webrtc_aec_state_16_to_48 out_resamp[WEBRTC_AEC_CHANNELS_MAX]; - int32_t resamp_tmpmem[512]; - - /* Resampler state for 32kHz <-> 16kHz (WebRtcSpl_DownsampleBy2/UpsampleBy2) */ - int32_t mic_resamp32[WEBRTC_AEC_CHANNELS_MAX][8]; - int32_t ref_resamp32[WEBRTC_AEC_CHANNELS_MAX][8]; - int32_t out_resamp32[WEBRTC_AEC_CHANNELS_MAX][8]; + /* + * Buffers allocated in prepare() as one block for the negotiated channel + * counts and rate, freed in reset(). The FIFOs hold fifo_frames frames + * at the pipeline rate, the 16 kHz buffers and the resampler states + * exist only when resampling. + */ + void *bufs; /* the single allocation that holds all below */ + int fifo_frames; /* per-channel capacity of mic_buf, ref_buf, out_fifo */ + int16_t *mic_buf[WEBRTC_AEC_CHANNELS_MAX]; /* mic_channels */ + int16_t *ref_buf[WEBRTC_AEC_CHANNELS_MAX]; /* ref_channels */ + int16_t *out_fifo[WEBRTC_AEC_CHANNELS_MAX]; /* mic_channels */ + int16_t *mic16[WEBRTC_AEC_CHANNELS_MAX]; /* mic_channels */ + int16_t *ref16[WEBRTC_AEC_CHANNELS_MAX]; /* ref_channels */ + int16_t *out16[WEBRTC_AEC_CHANNELS_MAX]; /* mic_channels */ + union webrtc_aec_down_state *mic_down; /* mic_channels */ + union webrtc_aec_down_state *ref_down; /* ref_channels */ + union webrtc_aec_up_state *out_up; /* mic_channels */ + int32_t *resamp_tmpmem; /* WEBRTC_AEC_RESAMP_TMP_LEN, 48 kHz only */ + + /* Memory context for the backend allocations. */ + struct webrtc_aec_mem mem; /* Ref stream liveness. */ bool last_ref_ok; @@ -206,51 +272,64 @@ struct webrtc_aec_comp_data { /* Backend instance exported from the selected translation unit. */ extern const struct webrtc_aec_backend webrtc_aec_backend; -#if defined(CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE) && CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE > 0 -#define WEBRTC_AEC_HAVE_ARENA 1 +#if !defined(CONFIG_COMP_WEBRTC_AEC_STUB) +/** + * \brief Enter the memory context of an instance in the current thread. + * + * Until webrtc_aec_mem_exit(), the WebRTC library allocations of this + * thread go to the instance. The calls are serialized by IPC, the thread + * check keeps other threads, e.g. processing of other instances, from using + * the context. + * + * \param[in] mem Memory context of the instance + * \return The previous context, pass it to webrtc_aec_mem_exit() + */ +struct webrtc_aec_mem *webrtc_aec_mem_enter(struct webrtc_aec_mem *mem); +/** + * \brief Restore the memory context that was current before entering. + * \param[in] prev Return value of the matching webrtc_aec_mem_enter() + */ +void webrtc_aec_mem_exit(struct webrtc_aec_mem *prev); +#else +static inline struct webrtc_aec_mem *webrtc_aec_mem_enter(struct webrtc_aec_mem *mem) +{ + (void)mem; + return NULL; +} + +static inline void webrtc_aec_mem_exit(struct webrtc_aec_mem *prev) { (void)prev; } +#endif + +#if WEBRTC_AEC_HAVE_ARENA /** * \brief Allocate the AEC3 arena, keeps an existing arena of the same size. - * \param[in] mod Module that owns the arena memory + * \param[in] mem Memory context of the instance * \param[in] size Arena size in bytes - * \return 0 on success, -ENOMEM if the heap has no room for the arena + * \return 0 on success, -ENOMEM if the heap has no room for the arena or + * WEBRTC_AEC_ARENAS_MAX arenas exist already */ -int webrtc_aec_arena_alloc(struct processing_module *mod, size_t size); +int webrtc_aec_arena_alloc(struct webrtc_aec_mem *mem, size_t size); /** * \brief Free the AEC3 arena. Destroy the instance in it first. - * \param[in] mod Module that owns the arena memory + * \param[in] mem Memory context of the instance */ -void webrtc_aec_arena_free(struct processing_module *mod); +void webrtc_aec_arena_free(struct webrtc_aec_mem *mem); /** - * \brief Rewind the arena and serve the current thread allocations from it. - * The previous instance in the arena must have been destroyed. + * \brief Rewind the arena and serve the context allocations from it. + * The previous instance in the arena must have been destroyed. The context + * must have been entered. + * \param[in] mem Memory context of the instance */ -void webrtc_aec_arena_open(void); - -/** \brief Stop serving allocations from the arena. */ -void webrtc_aec_arena_close(void); - -/** \return Arena bytes used since webrtc_aec_arena_open() */ -size_t webrtc_aec_arena_used(void); - -/** \return Bytes that did not fit to the arena and were taken from the heap */ -size_t webrtc_aec_arena_overflow(void); -#else -#define WEBRTC_AEC_HAVE_ARENA 0 -#endif +void webrtc_aec_arena_open(struct webrtc_aec_mem *mem); -#if !defined(CONFIG_COMP_WEBRTC_AEC_STUB) -void webrtc_aec_set_active_mod(struct processing_module *mod); -struct processing_module *webrtc_aec_get_active_mod(void); -size_t webrtc_aec_get_alloc_bytes(void); -void webrtc_aec_reset_alloc_bytes(void); -#else -static inline void webrtc_aec_set_active_mod(struct processing_module *mod) { (void)mod; } -static inline struct processing_module *webrtc_aec_get_active_mod(void) { return NULL; } -static inline size_t webrtc_aec_get_alloc_bytes(void) { return 0; } -static inline void webrtc_aec_reset_alloc_bytes(void) {} +/** + * \brief Stop serving allocations from the arena. + * \param[in] mem Memory context of the instance + */ +void webrtc_aec_arena_close(struct webrtc_aec_mem *mem); #endif #endif /* __SOF_AUDIO_WEBRTC_AEC_H__ */ diff --git a/test/ztest/unit/audio/webrtc_aec/webrtc_aec_ztest.c b/test/ztest/unit/audio/webrtc_aec/webrtc_aec_ztest.c index b12dd9a56980..da3c9d1e00de 100644 --- a/test/ztest/unit/audio/webrtc_aec/webrtc_aec_ztest.c +++ b/test/ztest/unit/audio/webrtc_aec/webrtc_aec_ztest.c @@ -513,11 +513,29 @@ ZTEST(webrtc_aec_suite, test_bypass_48k_s32_and_controls) zassert_equal(ctl_val, 1); zassert_equal(get_switch_ctl(mod, WEBRTC_AEC_CTL_ID_HIGH_SUPPRESSION, &ctl_val), 0); zassert_equal(ctl_val, 0); - if (cd->backend && cd->backend->set_delay) - zassert_equal(cd->backend->set_delay(mod, 18), 0); zassert_true(cd->enabled); zassert_false(cd->high_suppression); + + /* Reset frees the prepare() allocations, the next prepare() allocates again. */ zassert_equal(mod->dev->drv->adapter_ops->reset(mod), 0); + zassert_false(cd->configured); + zassert_is_null(cd->bufs); + zassert_is_null(cd->backend_data); + { + struct sof_source *sources[2] = { + audio_buffer_get_source(&ctx->mic_buf->audio_buffer), + audio_buffer_get_source(&ctx->ref_buf->audio_buffer), + }; + struct sof_sink *sinks[1] = { + audio_buffer_get_sink(&ctx->out_buf->audio_buffer), + }; + + zassert_equal(module_prepare(mod, sources, 2, sinks, 1), 0); + } + zassert_true(cd->configured); + zassert_true(cd->enabled); + if (cd->backend && cd->backend->set_delay) + zassert_equal(cd->backend->set_delay(mod, 18), 0); for (int b = 0; b < 20; b++) { for (int i = 0; i < fs; i++) { From 4cd96b86d1f38f889229c704be98509115b54378 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 12:02:47 +0200 Subject: [PATCH 13/17] audio: webrtc_aec: build several backends and select one in prepare Make the Float AEC, AEC3 and AECm backend Kconfig options independent so that several backends can be built into the module, and select the backend of an instance in prepare(). The new WEBRTC_AEC_BACKEND_SELECT choice selects automatically by the echo reference channel count, AEC3 for a multi-channel reference and the Float AEC for a mono reference, or always one backend. This allows e.g. a stereo reference WoV capture with AEC3 and a mono reference VoIP capture with the Float AEC side by side. The linker removes a backend that the selection cannot pick. Each backend exports its own operations and default echo path delay. WEBRTC_AEC_DELAY_MS is now only for the Float AEC with its 0 - 15 ms range, AEC3 and AECm get WEBRTC_AEC_AEC3_DELAY_MS and WEBRTC_AEC_AECM_DELAY_MS. The AEC3 overlay is updated for this, and the unit test configuration uses a Float AEC delay inside its range. Signed-off-by: Seppo Ingalsuo --- app/webrtc_aec3_static_overlay.conf | 2 +- src/audio/webrtc_aec/CMakeLists.txt | 51 +++++------ src/audio/webrtc_aec/Kconfig | 101 ++++++++++++++++------ src/audio/webrtc_aec/README.md | 27 ++++-- src/audio/webrtc_aec/llext/CMakeLists.txt | 9 +- src/audio/webrtc_aec/webrtc_aec-aec.c | 3 +- src/audio/webrtc_aec/webrtc_aec-aec3.c | 3 +- src/audio/webrtc_aec/webrtc_aec-aecm.c | 3 +- src/audio/webrtc_aec/webrtc_aec-stub.c | 3 +- src/audio/webrtc_aec/webrtc_aec.c | 59 +++++++++++-- src/audio/webrtc_aec/webrtc_aec.cmake | 14 +-- src/audio/webrtc_aec/webrtc_aec.h | 15 +++- test/ztest/unit/audio/webrtc_aec/prj.conf | 2 +- 13 files changed, 202 insertions(+), 90 deletions(-) diff --git a/app/webrtc_aec3_static_overlay.conf b/app/webrtc_aec3_static_overlay.conf index feefeaaa2c5f..2b75ec31ab49 100644 --- a/app/webrtc_aec3_static_overlay.conf +++ b/app/webrtc_aec3_static_overlay.conf @@ -30,7 +30,7 @@ CONFIG_WEBRTC_AEC_AEC3_ADAPT_RATE_PCT=50 # fixed delay instead. On PTL with the 8 ms mic delay AEC3 measured 16 ms, # a fixed 4 - 18 ms cancels it, 8 ms leaves margin both ways. CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST=y -CONFIG_WEBRTC_AEC_DELAY_MS=8 +CONFIG_WEBRTC_AEC_AEC3_DELAY_MS=8 # Allocate the AEC3 instance as one 640 kB block in prepare, so that a lack # of memory fails the stream start instead of panicking the DSP. diff --git a/src/audio/webrtc_aec/CMakeLists.txt b/src/audio/webrtc_aec/CMakeLists.txt index 119dd8cd6164..0d60e6139865 100644 --- a/src/audio/webrtc_aec/CMakeLists.txt +++ b/src/audio/webrtc_aec/CMakeLists.txt @@ -73,8 +73,6 @@ else() # Minimal C++ runtime, new/delete, and exception stubs are provided in webrtc_aec3_shims.cpp. add_local_sources(sof - webrtc_aec-aec3.c - webrtc_aec-math.c webrtc_aec3_wrapper.cpp webrtc_aec3_shims.cpp ) @@ -117,22 +115,36 @@ else() TARGET_DIRECTORY modules_sof PROPERTIES COMPILE_OPTIONS "-std=c++17;-fno-exceptions;-fno-rtti;-O3;${_no_vectorize_flags};${_clang_fp_flags};-DWEBRTC_POSIX;-DWEBRTC_ARCH_GENERIC;-DWEBRTC_APM_DEBUG_DUMP=0;-DRTC_DISABLE_METRICS;-DNDEBUG;-Wno-macro-redefined;-Wno-unused-function;-Wno-double-promotion" ) - elseif(CONFIG_WEBRTC_AEC_BACKEND_FLOAT) - add_local_sources(sof webrtc_aec-aec.c webrtc_aec-math.c) - add_local_sources(sof + endif() + + # The C backends, all selected backends are built in. The module + # selects the backend of an instance in prepare(). + set(_backend_glue "") + set(_backend_apm_srcs "") + if(CONFIG_WEBRTC_AEC_BACKEND_AEC3) + list(APPEND _backend_glue ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-aec3.c) + endif() + if(CONFIG_WEBRTC_AEC_BACKEND_FLOAT) + list(APPEND _backend_glue ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-aec.c) + list(APPEND _backend_apm_srcs "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/echo_cancellation.c" "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/aec_core.c" "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/aec_rdft.c" "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/aec_resampler.c" ) - else() - add_local_sources(sof webrtc_aec-aecm.c) - add_local_sources(sof + endif() + if(CONFIG_WEBRTC_AEC_BACKEND_AEC3 OR CONFIG_WEBRTC_AEC_BACKEND_FLOAT) + list(APPEND _backend_glue ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-math.c) + endif() + if(CONFIG_WEBRTC_AEC_BACKEND_AECM) + list(APPEND _backend_glue ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-aecm.c) + list(APPEND _backend_apm_srcs "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aecm/echo_control_mobile.c" "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aecm/aecm_core.c" "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aecm/aecm_core_c.c" ) endif() + add_local_sources(sof ${_backend_glue} ${_backend_apm_srcs}) add_local_sources(sof webrtc_aec-shims.c) add_local_sources(sof @@ -188,28 +200,7 @@ else() ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-shims.c ) - if(CONFIG_WEBRTC_AEC_BACKEND_AEC3) - list(APPEND _webrtc_aec_srcs - ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-aec3.c - ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-math.c - ) - elseif(CONFIG_WEBRTC_AEC_BACKEND_FLOAT) - list(APPEND _webrtc_aec_srcs - ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-aec.c - ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-math.c - "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/echo_cancellation.c" - "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/aec_core.c" - "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/aec_rdft.c" - "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aec/aec_resampler.c" - ) - else() - list(APPEND _webrtc_aec_srcs - ${CMAKE_CURRENT_SOURCE_DIR}/webrtc_aec-aecm.c - "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aecm/echo_control_mobile.c" - "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aecm/aecm_core.c" - "${SOF_WEBRTC_APM_SRC_DIR}/webrtc/modules/audio_processing/aecm/aecm_core_c.c" - ) - endif() + list(APPEND _webrtc_aec_srcs ${_backend_glue} ${_backend_apm_srcs}) set_source_files_properties( ${_webrtc_aec_srcs} diff --git a/src/audio/webrtc_aec/Kconfig b/src/audio/webrtc_aec/Kconfig index 149ae5c91521..7416435e4692 100644 --- a/src/audio/webrtc_aec/Kconfig +++ b/src/audio/webrtc_aec/Kconfig @@ -25,37 +25,69 @@ config COMP_WEBRTC_AEC if COMP_WEBRTC_AEC -choice WEBRTC_AEC_BACKEND - prompt "WebRTC AEC processing backend" - default COMP_WEBRTC_AEC_STUB if COMP_STUBS - default WEBRTC_AEC_BACKEND_FLOAT if COMP_WEBRTC_AEC = y - default WEBRTC_AEC_BACKEND_AECM +config COMP_WEBRTC_AEC_STUB + bool "WebRTC AEC stub backend (no WebRTC source dependency)" + default y if COMP_STUBS + help + Build the webrtc_aec module against a dependency-free stub backend + that passes microphone audio through without modification. The + other backends are not built. config WEBRTC_AEC_BACKEND_FLOAT bool "Classic Float AEC (Multidelay Block Frequency Domain with hardware FPU)" + default y if COMP_WEBRTC_AEC = y + depends on !COMP_WEBRTC_AEC_STUB help Single-precision floating-point AEC using partitioned-block frequency domain adaptive filtering (MDF) accelerated by the - hardware FPU and HiFi4 VFPU. + hardware FPU and HiFi4 VFPU. One instance per microphone channel + with a mono echo reference, a multi-channel reference is + downmixed. config WEBRTC_AEC_BACKEND_AEC3 bool "Modern WebRTC AEC3 (State-of-the-art C++17 Echo Canceller)" - depends on COMP_WEBRTC_AEC = y + depends on COMP_WEBRTC_AEC = y && !COMP_WEBRTC_AEC_STUB help Modern WebRTC AEC3 with matched filter delay estimator, multi-partition linear adaptive filter, non-linear suppression, and full-band ERLE estimator. + Cancels a multi-channel echo reference jointly. config WEBRTC_AEC_BACKEND_AECM bool "AECm (Mobile fixed-point integer AEC)" + default y if COMP_WEBRTC_AEC = m && !WEBRTC_AEC_BACKEND_FLOAT + depends on !COMP_WEBRTC_AEC_STUB help Pure integer Q15 fixed-point echo cancellation. Low memory (~12 KB/ch) and low CPU (~1.5 MCPS). -config COMP_WEBRTC_AEC_STUB - bool "WebRTC AEC stub backend (no WebRTC source dependency)" +choice WEBRTC_AEC_BACKEND_SELECT + prompt "WebRTC AEC backend selection" + default WEBRTC_AEC_SELECT_AUTO + depends on !COMP_WEBRTC_AEC_STUB help - Build the webrtc_aec module against a dependency-free stub backend - that passes microphone audio through without modification. + Several backends can be built into the module. The backend of an + instance is selected in prepare from the negotiated formats. + +config WEBRTC_AEC_SELECT_AUTO + bool "By echo reference channel count" + help + With a multi-channel echo reference use AEC3, or the Float AEC + if AEC3 is not built. With a mono reference use the Float AEC, + or AECm if the Float AEC is not built, or AEC3 if it is the only + built backend. With WEBRTC_AEC_STEREO_DOWNMIX_REF the reference is + mono. + +config WEBRTC_AEC_SELECT_FLOAT + bool "Classic Float AEC" + depends on WEBRTC_AEC_BACKEND_FLOAT + +config WEBRTC_AEC_SELECT_AEC3 + bool "AEC3" + depends on WEBRTC_AEC_BACKEND_AEC3 + +config WEBRTC_AEC_SELECT_AECM + bool "AECm" + depends on WEBRTC_AEC_BACKEND_AECM endchoice config WEBRTC_AEC_AEC3_HW_FPU @@ -69,6 +101,9 @@ config WEBRTC_AEC_AEC3_HW_FPU library calls, which makes AEC3 too slow for real time 16 kHz processing with a stereo echo reference. + This applies to all webrtc_aec sources, so with several backends + built in also the Float AEC uses the hardware FPU. + config WEBRTC_AEC_AEC3_ARENA_SIZE int "AEC3 instance memory arena size in bytes" default 0 @@ -77,9 +112,9 @@ config WEBRTC_AEC_AEC3_ARENA_SIZE Without C++ exceptions a failed allocation inside AEC3 panics the DSP. With a non-zero size the backend allocates this much memory as one block in prepare, which fails gracefully with -ENOMEM, and - creates the AEC3 instance into it. The instance is re-created into - the same arena on reset, so stopping a stream does not need more - heap. The used size is printed after the creation. Allocations + creates the AEC3 instance into it. Each AEC3 instance has its own + arena, it is freed on reset. The used size is printed after the + creation. Allocations that do not fit come from the heap, as without the arena. E.g. 2R x 1C at 16 kHz with 12 filter blocks needs about 600 kB. Zero allocates the instance directly from the heap. @@ -104,22 +139,36 @@ config WEBRTC_AEC_FILTER_LEN_MS Valid values: 32, 64, 128. config WEBRTC_AEC_DELAY_MS - int "Nominal echo path / soundcard buffer delay in ms" - range 0 15 if WEBRTC_AEC_BACKEND_FLOAT + int "Float AEC echo path delay in ms" + range 0 15 + default 0 + depends on WEBRTC_AEC_BACKEND_FLOAT + help + Delay in milliseconds reported to the Float AEC (msInSndCardBuf), + from a reference sample entering the AEC to its echo appearing in + the microphone input of the AEC, for the shortest (direct) acoustic + path. The linear filter covers this delay plus 48 ms, so a value + larger than the real delay makes the echo non-causal and prevents + cancellation. Use the "delay median" trace to tune it. + +config WEBRTC_AEC_AEC3_DELAY_MS + int "AEC3 nominal echo path delay in ms" range 0 500 - default 0 if WEBRTC_AEC_BACKEND_FLOAT default 20 + depends on WEBRTC_AEC_BACKEND_AEC3 help Nominal delay in milliseconds between echo reference playback and - microphone capture. Used by AECm/Float AEC (msInSndCardBuf) and by - AEC3 when WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST is enabled. + microphone capture for AEC3. With WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST + AEC3 uses this delay instead of its matched filter estimate. - For the Float AEC this is the delay from a reference sample - entering the AEC to its echo appearing in the microphone input of - the AEC, for the shortest (direct) acoustic path. The linear - filter covers this delay plus 48 ms, so a value larger than the - real delay makes the echo non-causal and prevents cancellation. - Use the "delay median" trace to tune it. +config WEBRTC_AEC_AECM_DELAY_MS + int "AECm nominal echo path delay in ms" + range 0 500 + default 20 + depends on WEBRTC_AEC_BACKEND_AECM + help + Nominal delay in milliseconds between echo reference playback and + microphone capture, reported to AECm (msInSndCardBuf). config WEBRTC_AEC_REF_GAIN int "Float AEC echo reference linear gain" @@ -217,7 +266,7 @@ config WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST help When disabled (recommended), AEC3 uses its internal matched-filter delay estimator to align render and capture automatically. Enable - to lock AEC3 to WEBRTC_AEC_DELAY_MS for reduced cycle usage when + to lock AEC3 to WEBRTC_AEC_AEC3_DELAY_MS for reduced cycle usage when the hardware echo path delay is fixed and known. config WEBRTC_AEC_AEC3_FILTER_BLOCKS diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index fb67589b5d1e..cb101689c865 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -75,6 +75,13 @@ graph TD ## Build Configuration +Several backends can be built into the module, each `CONFIG_WEBRTC_AEC_BACKEND_*` +option adds one. The backend of an instance is selected in prepare by +`CONFIG_WEBRTC_AEC_BACKEND_SELECT`. With the default automatic selection a +multi-channel echo reference uses AEC3 and a mono reference uses the Float AEC, +so e.g. a stereo reference WoV capture and a mono reference VoIP capture can run +side by side. A backend that the selection cannot pick is removed by the linker. + ### 1. Modern WebRTC AEC3 (Panther Lake / ACE 3.0) ```ini @@ -84,6 +91,9 @@ CONFIG_WEBRTC_AEC_BACKEND_AEC3=y CONFIG_WEBRTC_AEC_PERF_TELEMETRY=y ``` +The Float AEC is enabled by default too, and is used for the instances with a +mono echo reference. + ### 2. Classic Float AEC (MDF) ```ini @@ -114,24 +124,27 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | Option | Default | Type / Range | Description | |---|---|---|---| | `CONFIG_COMP_WEBRTC_AEC` | n | tristate (`y`/`m`/`n`) | Enable WebRTC AEC module | -| `CONFIG_COMP_WEBRTC_AEC_STUB` | y | bool | Build pass-through stub | -| `CONFIG_WEBRTC_AEC_BACKEND_AEC3` | y | bool | Use modern WebRTC AEC3 (C++17) backend | -| `CONFIG_WEBRTC_AEC_BACKEND_FLOAT` | n | bool | Use classic floating-point MDF AEC backend | -| `CONFIG_WEBRTC_AEC_BACKEND_AECM` | n | bool | Use classic fixed-point integer AECm backend | +| `CONFIG_COMP_WEBRTC_AEC_STUB` | n | bool | Build only the pass-through stub | +| `CONFIG_WEBRTC_AEC_BACKEND_AEC3` | n | bool (`y` module only) | Build the modern WebRTC AEC3 (C++17) backend | +| `CONFIG_WEBRTC_AEC_BACKEND_FLOAT` | y (built-in module) | bool | Build the classic floating-point MDF AEC backend | +| `CONFIG_WEBRTC_AEC_BACKEND_AECM` | y (`m` module without Float) | bool | Build the classic fixed-point integer AECm backend | +| `CONFIG_WEBRTC_AEC_BACKEND_SELECT` | `WEBRTC_AEC_SELECT_AUTO` | choice | Select the backend by the echo reference channel count, or always one backend | | `CONFIG_WEBRTC_AEC_PERF_TELEMETRY` | y | bool | Enable real-time cycle profiling via printk | | `CONFIG_WEBRTC_AEC_FILTER_LEN_MS` | 64 | int (`32`, `64`, `128`) | AECm adaptive filter length in ms | | `CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL` | 1 | int (`0` - `2`) | AECm comfort-noise suppression level | | `CONFIG_WEBRTC_AEC_SAMPLE_RATE_HZ` | 16000 | int (`8000`, `16000`) | Native AEC processing rate (32/48 kHz resampled) | -| `CONFIG_WEBRTC_AEC_DELAY_MS` | 0 (Float), 20 | int (`0` - `15` Float, `0` - `500`) | Nominal echo path / soundcard buffer delay in ms; for Float the reference to echo delay, must not exceed the real delay | +| `CONFIG_WEBRTC_AEC_DELAY_MS` | 0 | int (`0` - `15`, Float) | Float AEC reference to echo delay in ms, must not exceed the real delay | +| `CONFIG_WEBRTC_AEC_AEC3_DELAY_MS` | 20 | int (`0` - `500`, AEC3) | AEC3 nominal echo path delay in ms, used with `WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST` | +| `CONFIG_WEBRTC_AEC_AECM_DELAY_MS` | 20 | int (`0` - `500`, AECm) | AECm nominal echo path / soundcard buffer delay in ms | | `CONFIG_WEBRTC_AEC_MIC_DELAY_MS` | 8 | int (`0` - `20`, Float and AEC3) | Microphone delay to keep the echo after the reference, AEC3 fixed capture delay | | `CONFIG_WEBRTC_AEC_ERLE_TRACE` | n | bool (Float and AEC3) | 1 s ERLE, mic and reference level trace over far-end active frames; AEC3 with linear output reports the linear filter ERLE | | `CONFIG_WEBRTC_AEC_REF_GAIN` | 16 | int (`1` - `256`) | Float AEC linear gain on the reference, speeds up convergence | | `CONFIG_WEBRTC_AEC_DELAY_DEBUG` | n | bool | Float AEC delay estimate and level trace every 5 s | | `CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF` | n | bool | Downmix multi-channel reference to mono before AEC | | `CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT` | y | bool (AEC3) | Dynamic stereo vs. dual-mono content detector | -| `CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST` | n | bool (AEC3) | Lock AEC3 to `WEBRTC_AEC_DELAY_MS` instead of matched filter | +| `CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST` | n | bool (AEC3) | Lock AEC3 to `WEBRTC_AEC_AEC3_DELAY_MS` instead of matched filter | | `CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS` | 12 | int (`1` - `30`, AEC3) | AEC3 refined/coarse adaptive filter length in 4 ms blocks | -| `CONFIG_WEBRTC_AEC_AEC3_HW_FPU` | n | bool (AEC3) | Build AEC3 with hardware FPU instructions instead of soft-float | +| `CONFIG_WEBRTC_AEC_AEC3_HW_FPU` | n | bool (AEC3) | Build the webrtc_aec sources, also the Float AEC if built in, with hardware FPU instructions instead of soft-float | | `CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE` | 0 | int (bytes, AEC3) | Create AEC3 into one block allocated in prepare, to fail with -ENOMEM instead of a DSP panic, 0 to allocate from the heap | | `CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER` | y | bool (AEC3) | Enable AEC3 coarse filter output fallback | | `CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS` | 0 | int (`0` - `30`, AEC3) | AEC3 coarse filter length in 4 ms blocks, 0 for the refined filter length | diff --git a/src/audio/webrtc_aec/llext/CMakeLists.txt b/src/audio/webrtc_aec/llext/CMakeLists.txt index 795a80f28ec4..0ed29dd4897a 100644 --- a/src/audio/webrtc_aec/llext/CMakeLists.txt +++ b/src/audio/webrtc_aec/llext/CMakeLists.txt @@ -9,10 +9,13 @@ if(CONFIG_COMP_WEBRTC_AEC_STUB) else() include(${CMAKE_CURRENT_LIST_DIR}/../webrtc_aec.cmake) + # AEC3 is not available as LLEXT, see WEBRTC_AEC_BACKEND_AEC3 + set(_aec_backend_glue "") if(CONFIG_WEBRTC_AEC_BACKEND_FLOAT) - set(_aec_backend_glue ../webrtc_aec-aec.c ../webrtc_aec-math.c) - else() - set(_aec_backend_glue ../webrtc_aec-aecm.c) + list(APPEND _aec_backend_glue ../webrtc_aec-aec.c ../webrtc_aec-math.c) + endif() + if(CONFIG_WEBRTC_AEC_BACKEND_AECM) + list(APPEND _aec_backend_glue ../webrtc_aec-aecm.c) endif() sof_llext_build("webrtc_aec" diff --git a/src/audio/webrtc_aec/webrtc_aec-aec.c b/src/audio/webrtc_aec/webrtc_aec-aec.c index 2901774b17f3..9cca3c218f24 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec.c @@ -590,8 +590,9 @@ static int webrtc_aec_float_free(struct processing_module *mod) return 0; } -const struct webrtc_aec_backend webrtc_aec_backend = { +const struct webrtc_aec_backend webrtc_aec_backend_float = { .name = "aec_float", + .default_delay_ms = CONFIG_WEBRTC_AEC_DELAY_MS, .init = webrtc_aec_float_init, .configure = webrtc_aec_float_configure, .set_suppression = webrtc_aec_float_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec-aec3.c b/src/audio/webrtc_aec/webrtc_aec-aec3.c index f081c34efdc5..59c1233b31be 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec3.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec3.c @@ -470,8 +470,9 @@ static int webrtc_aec3_backend_free(struct processing_module *mod) return 0; } -const struct webrtc_aec_backend webrtc_aec_backend = { +const struct webrtc_aec_backend webrtc_aec_backend_aec3 = { .name = "aec3", + .default_delay_ms = CONFIG_WEBRTC_AEC_AEC3_DELAY_MS, .init = webrtc_aec3_backend_init, .configure = webrtc_aec3_backend_configure, .set_suppression = webrtc_aec3_backend_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec-aecm.c b/src/audio/webrtc_aec/webrtc_aec-aecm.c index bea9c1a3e952..2a8d7883fa2a 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aecm.c +++ b/src/audio/webrtc_aec/webrtc_aec-aecm.c @@ -217,8 +217,9 @@ static int webrtc_aec_real_free(struct processing_module *mod) return 0; } -const struct webrtc_aec_backend webrtc_aec_backend = { +const struct webrtc_aec_backend webrtc_aec_backend_aecm = { .name = "aecm", + .default_delay_ms = CONFIG_WEBRTC_AEC_AECM_DELAY_MS, .init = webrtc_aec_real_init, .configure = webrtc_aec_real_configure, .set_suppression = webrtc_aec_real_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec-stub.c b/src/audio/webrtc_aec/webrtc_aec-stub.c index fa9216ca1346..9a1cbebdf9ea 100644 --- a/src/audio/webrtc_aec/webrtc_aec-stub.c +++ b/src/audio/webrtc_aec/webrtc_aec-stub.c @@ -58,8 +58,9 @@ static int webrtc_aec_stub_free(struct processing_module *mod) return 0; } -const struct webrtc_aec_backend webrtc_aec_backend = { +const struct webrtc_aec_backend webrtc_aec_backend_stub = { .name = "stub", + .default_delay_ms = 0, .init = webrtc_aec_stub_init, .configure = webrtc_aec_stub_configure, .set_suppression = webrtc_aec_stub_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec.c b/src/audio/webrtc_aec/webrtc_aec.c index b2aa31042653..d45c252163fe 100644 --- a/src/audio/webrtc_aec/webrtc_aec.c +++ b/src/audio/webrtc_aec/webrtc_aec.c @@ -52,6 +52,11 @@ static inline void WebRtcSpl_UpsampleBy2(const int16_t *in, size_t len, int16_t } #endif +#if !CONFIG_COMP_WEBRTC_AEC_STUB && !CONFIG_WEBRTC_AEC_BACKEND_FLOAT && \ + !CONFIG_WEBRTC_AEC_BACKEND_AEC3 && !CONFIG_WEBRTC_AEC_BACKEND_AECM +#error "webrtc_aec: select at least one backend" +#endif + SOF_DEFINE_REG_UUID(webrtc_aec); LOG_MODULE_REGISTER(webrtc_aec, CONFIG_SOF_LOG_LEVEL); @@ -298,23 +303,51 @@ __cold static int webrtc_aec_init(struct processing_module *mod) md->private = cd; cd->mem.mod = mod; - cd->backend = &webrtc_aec_backend; cd->enabled = false; cd->high_suppression = false; -#ifdef CONFIG_WEBRTC_AEC_DELAY_MS - cd->delay_ms = CONFIG_WEBRTC_AEC_DELAY_MS; -#else - cd->delay_ms = 20; -#endif cd->downmix_ref = IS_ENABLED(CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF); /* Two input pins: mic + echo reference. */ mod->max_sources = 2; - comp_info(dev, "webrtc_aec: backend '%s'", cd->backend->name); return 0; } +/** + * \brief Select the backend for the negotiated formats. + * + * See WEBRTC_AEC_BACKEND_SELECT in Kconfig for the selection rules. + * + * \param[in] cd Module data with effective_ref_ch set + * \return Backend + */ +static const struct webrtc_aec_backend * +webrtc_aec_select_backend(const struct webrtc_aec_comp_data *cd) +{ +#if CONFIG_COMP_WEBRTC_AEC_STUB + return &webrtc_aec_backend_stub; +#elif CONFIG_WEBRTC_AEC_SELECT_FLOAT + return &webrtc_aec_backend_float; +#elif CONFIG_WEBRTC_AEC_SELECT_AEC3 + return &webrtc_aec_backend_aec3; +#elif CONFIG_WEBRTC_AEC_SELECT_AECM + return &webrtc_aec_backend_aecm; +#else +#if CONFIG_WEBRTC_AEC_BACKEND_AEC3 + /* AEC3 cancels a multi-channel reference jointly */ + if (cd->effective_ref_ch > 1) + return &webrtc_aec_backend_aec3; +#endif +#if CONFIG_WEBRTC_AEC_BACKEND_FLOAT + return &webrtc_aec_backend_float; +#elif CONFIG_WEBRTC_AEC_BACKEND_AECM + return &webrtc_aec_backend_aecm; +#else + return &webrtc_aec_backend_aec3; +#endif +#endif +} + /** * \brief Take a buffer from the prepare() allocation. * @@ -408,11 +441,12 @@ static void webrtc_aec_release(struct processing_module *mod) struct webrtc_aec_mem *prev; cd->configured = false; - if (cd->backend->free) { + if (cd->backend && cd->backend->free) { prev = webrtc_aec_mem_enter(&cd->mem); cd->backend->free(mod); webrtc_aec_mem_exit(prev); } + cd->backend = NULL; if (cd->bufs) { mod_free(mod, cd->bufs); @@ -565,9 +599,16 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, cd->ref_is_s32 ? "S32" : "S16", cd->out_is_s32 ? "S32" : "S16", cd->resamp_mode); + cd->backend = webrtc_aec_select_backend(cd); + cd->delay_ms = cd->backend->default_delay_ms; + comp_info(dev, "webrtc_aec: backend '%s' for %d reference channels", + cd->backend->name, cd->effective_ref_ch); + ret = webrtc_aec_bufs_alloc(mod); - if (ret) + if (ret) { + cd->backend = NULL; return ret; + } webrtc_aec_reset_resamplers(cd); diff --git a/src/audio/webrtc_aec/webrtc_aec.cmake b/src/audio/webrtc_aec/webrtc_aec.cmake index 5425a1e56eb3..45f463b633b9 100644 --- a/src/audio/webrtc_aec/webrtc_aec.cmake +++ b/src/audio/webrtc_aec/webrtc_aec.cmake @@ -30,19 +30,23 @@ set(WEBRTC_AECM_INSTALL_DIR "${CMAKE_CURRENT_BINARY_DIR}/webrtc-aecm-install" set(_aecm_src "${SOF_WEBRTC_APM_SRC_DIR}/webrtc") +# All selected C backends go to the same library +set(_aec_backend_srcs "") +set(_aec_backend_hdr "") if(CONFIG_WEBRTC_AEC_BACKEND_FLOAT) - set(_aec_backend_srcs " + string(APPEND _aec_backend_srcs " $SRC/modules/audio_processing/aec/echo_cancellation.c $SRC/modules/audio_processing/aec/aec_core.c $SRC/modules/audio_processing/aec/aec_rdft.c $SRC/modules/audio_processing/aec/aec_resampler.c") - set(_aec_backend_hdr "$SRC/modules/audio_processing/aec/include/echo_cancellation.h") -else() - set(_aec_backend_srcs " + string(APPEND _aec_backend_hdr " $SRC/modules/audio_processing/aec/include/echo_cancellation.h") +endif() +if(CONFIG_WEBRTC_AEC_BACKEND_AECM) + string(APPEND _aec_backend_srcs " $SRC/modules/audio_processing/aecm/aecm_core.c $SRC/modules/audio_processing/aecm/aecm_core_c.c $SRC/modules/audio_processing/aecm/echo_control_mobile.c") - set(_aec_backend_hdr "$SRC/modules/audio_processing/aecm/include/echo_control_mobile.h") + string(APPEND _aec_backend_hdr " $SRC/modules/audio_processing/aecm/include/echo_control_mobile.h") endif() file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/webrtc-aecm-build.sh.tmp" diff --git a/src/audio/webrtc_aec/webrtc_aec.h b/src/audio/webrtc_aec/webrtc_aec.h index f4c2d74e2866..5f164826928f 100644 --- a/src/audio/webrtc_aec/webrtc_aec.h +++ b/src/audio/webrtc_aec/webrtc_aec.h @@ -10,7 +10,8 @@ * One output pin: * sinks[0] — echo-cancelled microphone * - * Processing is delegated to a pluggable backend selected at build time: + * Processing is delegated to a pluggable backend. Several backends can be + * built in, the backend of an instance is selected in prepare(): * - Modern C++17 WebRTC AEC3 (webrtc_aec-aec3.c + webrtc_aec3_wrapper.cpp) * - Classic Float MDF AEC (webrtc_aec-aec.c) * - Fixed-point AECm (webrtc_aec-aecm.c) @@ -139,6 +140,9 @@ struct webrtc_aec_mem { struct webrtc_aec_backend { const char *name; + /* Echo path delay in ms given to set_delay() after configure(). */ + int default_delay_ms; + /* Allocate the backend data. Called from prepare(), before configure(). */ int (*init)(struct processing_module *mod); @@ -210,7 +214,7 @@ struct webrtc_aec_comp_data { /* Runtime ALSA mixer controls */ bool enabled; /* master bypass switch (WEBRTC_AEC_CTL_ID_ENABLE) */ bool high_suppression; /* suppression switch (WEBRTC_AEC_CTL_ID_HIGH_SUPPRESSION) */ - int delay_ms; /* echo path / soundcard buffer delay (ms) */ + int delay_ms; /* echo path delay (ms), backend default in prepare */ bool downmix_ref; /* downmix multi-ch ref to mono before backend */ bool downmix_mic; /* average multi-ch mic to mono for a mono output */ @@ -269,8 +273,11 @@ struct webrtc_aec_comp_data { bool configured; }; -/* Backend instance exported from the selected translation unit. */ -extern const struct webrtc_aec_backend webrtc_aec_backend; +/* Backends exported by the built backend translation units. */ +extern const struct webrtc_aec_backend webrtc_aec_backend_float; +extern const struct webrtc_aec_backend webrtc_aec_backend_aec3; +extern const struct webrtc_aec_backend webrtc_aec_backend_aecm; +extern const struct webrtc_aec_backend webrtc_aec_backend_stub; #if !defined(CONFIG_COMP_WEBRTC_AEC_STUB) /** diff --git a/test/ztest/unit/audio/webrtc_aec/prj.conf b/test/ztest/unit/audio/webrtc_aec/prj.conf index 597a61ad7140..7484996dbec5 100644 --- a/test/ztest/unit/audio/webrtc_aec/prj.conf +++ b/test/ztest/unit/audio/webrtc_aec/prj.conf @@ -12,6 +12,6 @@ CONFIG_COMP_WEBRTC_AEC=y CONFIG_COMP_WEBRTC_AEC_STUB=n CONFIG_WEBRTC_AEC_BACKEND_FLOAT=y CONFIG_WEBRTC_AEC_DELAY_AGNOSTIC=n -CONFIG_WEBRTC_AEC_DELAY_MS=20 +CONFIG_WEBRTC_AEC_DELAY_MS=15 CONFIG_FORMAT_S16LE=y CONFIG_FORMAT_S32LE=y From 2d760df70a5bceb3da4b8ca924aaaf57c508c75f Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 12:34:33 +0200 Subject: [PATCH 14/17] west.yml: bump webrtc-apm to df7293e5dd71 Update webrtc-apm to df7293e5dd7113ddbad0a886cd8108801355e40f for the native float AEC3 and the runtime selection of the Float AEC linear only output and step size with WebRtcAec_enable_linear_only() and WebRtcAec_set_normal_mu(). The soft-float AEC3 optimizations are reverted, AEC3 is built with the hardware FPU. Signed-off-by: Seppo Ingalsuo --- west.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/west.yml b/west.yml index dc2952b891fb..cd5f134b9d24 100644 --- a/west.yml +++ b/west.yml @@ -51,7 +51,7 @@ manifest: - name: webrtc-apm repo-path: webrtc-audio-processing path: modules/audio/webrtc-apm - revision: 07232bb5e5252210da688796eac66538ca8d5939 + revision: df7293e5dd7113ddbad0a886cd8108801355e40f # rnnoise — xiph/rnnoise deep-learning noise suppressor (webrtc_ns2) - name: rnnoise From 3fda11acd91971a79ad577e2ad978ef4dd7a4b58 Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 12:34:47 +0200 Subject: [PATCH 15/17] audio: webrtc_aec: add a bytes control for the instance configuration Add struct webrtc_aec_config, set with a bytes control of IPC4 param_id 1, to configure each instance separately. It selects the backend, automatic by the echo reference channel count or a built backend, and sets the tuning that was so far only in Kconfig: the suppression level, microphone delay and reference downmix, the Float AEC delay, reference gain, linear output without residual echo suppression, step size and delay agnostic mode, the AEC3 delay, external delay estimation, filter lengths, linear output, adaptation rate, stereo content detector and arena size, and the AECm delay and filter length. The Kconfig options are now the defaults of an instance without a blob, and a blob shorter than the struct sets only its first fields. The blob is checked when received and used in the next prepare. The new WEBRTC_AEC_FLOAT_LINEAR_OUTPUT is the default of the Float AEC linear output. The Float AEC microphone delay line is allocated in prepare for the configured delay. The AEC3 arena is available whenever AEC3 is built, its size comes from the configuration and zero allocates AEC3 from the heap. Signed-off-by: Seppo Ingalsuo --- app/webrtc_aec3_static_overlay.conf | 4 + src/audio/webrtc_aec/Kconfig | 29 ++- src/audio/webrtc_aec/README.md | 35 +++- src/audio/webrtc_aec/webrtc_aec-aec.c | 86 +++++--- src/audio/webrtc_aec/webrtc_aec-aec3.c | 46 ++--- src/audio/webrtc_aec/webrtc_aec-aecm.c | 2 +- src/audio/webrtc_aec/webrtc_aec-stub.c | 2 +- src/audio/webrtc_aec/webrtc_aec.c | 267 ++++++++++++++++++++++++- src/audio/webrtc_aec/webrtc_aec.h | 57 +++++- 9 files changed, 444 insertions(+), 84 deletions(-) diff --git a/app/webrtc_aec3_static_overlay.conf b/app/webrtc_aec3_static_overlay.conf index 2b75ec31ab49..981e5ffac7e2 100644 --- a/app/webrtc_aec3_static_overlay.conf +++ b/app/webrtc_aec3_static_overlay.conf @@ -2,6 +2,10 @@ # # WebRTC AEC3 built into the base firmware. AEC3 supports a stereo echo # reference with a mono microphone (2R x 1C). +# +# The AEC3 tuning here is the default of an instance. The bytes control of +# the instance overrides it, e.g. the topology "wov" blob has the same +# settings, see src/audio/webrtc_aec/tune/sof_webrtc_aec_blobs.m. CONFIG_COMP_WEBRTC_AEC=y CONFIG_WEBRTC_AEC_BACKEND_AEC3=y diff --git a/src/audio/webrtc_aec/Kconfig b/src/audio/webrtc_aec/Kconfig index 7416435e4692..5e139be91bbc 100644 --- a/src/audio/webrtc_aec/Kconfig +++ b/src/audio/webrtc_aec/Kconfig @@ -9,6 +9,10 @@ config COMP_WEBRTC_AEC audio processing library. It requires no floating-point unit and is well suited to Xtensa HiFi3/HiFi4 class DSPs. + The tuning options below are the defaults of an instance. The + bytes control of the instance, struct webrtc_aec_config in + webrtc_aec.h, overrides them, e.g. from the topology. + The module accepts two input streams (2 input pins): Pin 0 — microphone capture (same pipeline as the output) Pin 1 — playback echo reference (from the render pipeline) @@ -66,7 +70,8 @@ choice WEBRTC_AEC_BACKEND_SELECT depends on !COMP_WEBRTC_AEC_STUB help Several backends can be built into the module. The backend of an - instance is selected in prepare from the negotiated formats. + instance is selected in prepare from the negotiated formats. This + is the default of the backend field of the bytes control. config WEBRTC_AEC_SELECT_AUTO bool "By echo reference channel count" @@ -110,14 +115,14 @@ config WEBRTC_AEC_AEC3_ARENA_SIZE depends on WEBRTC_AEC_BACKEND_AEC3 help Without C++ exceptions a failed allocation inside AEC3 panics the - DSP. With a non-zero size the backend allocates this much memory as - one block in prepare, which fails gracefully with -ENOMEM, and + DSP. With a non-zero size the backend allocates this much memory + as one block in prepare, which fails gracefully with -ENOMEM, and creates the AEC3 instance into it. Each AEC3 instance has its own arena, it is freed on reset. The used size is printed after the - creation. Allocations - that do not fit come from the heap, as without the arena. E.g. 2R x - 1C at 16 kHz with 12 filter blocks needs about 600 kB. Zero - allocates the instance directly from the heap. + creation. Allocations that do not fit come from the heap, as + without the arena. E.g. 2R x 1C at 16 kHz with 12 filter blocks + needs about 600 kB. Zero allocates the instance directly from the + heap. The bytes control default is this size rounded up to kB. config WEBRTC_AEC_PERF_TELEMETRY bool "Enable AEC3 cycle profiling telemetry via printk" @@ -170,6 +175,16 @@ config WEBRTC_AEC_AECM_DELAY_MS Nominal delay in milliseconds between echo reference playback and microphone capture, reported to AECm (msInSndCardBuf). +config WEBRTC_AEC_FLOAT_LINEAR_OUTPUT + bool "Float AEC outputs the linear filter error" + default y + depends on WEBRTC_AEC_BACKEND_FLOAT + help + Output the linear filter error of the Float AEC without the + residual echo suppression (NLP). This keeps the near-end talker + intact for wake on voice and barge-in. Disable for e.g. a VoIP + capture where the residual echo must be suppressed. + config WEBRTC_AEC_REF_GAIN int "Float AEC echo reference linear gain" range 1 256 diff --git a/src/audio/webrtc_aec/README.md b/src/audio/webrtc_aec/README.md index cb101689c865..54d721124c7f 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -80,7 +80,8 @@ option adds one. The backend of an instance is selected in prepare by `CONFIG_WEBRTC_AEC_BACKEND_SELECT`. With the default automatic selection a multi-channel echo reference uses AEC3 and a mono reference uses the Float AEC, so e.g. a stereo reference WoV capture and a mono reference VoIP capture can run -side by side. A backend that the selection cannot pick is removed by the linker. +side by side. The bytes control of an instance can also select the backend, see +[Bytes Control](#bytes-control). ### 1. Modern WebRTC AEC3 (Panther Lake / ACE 3.0) @@ -151,6 +152,38 @@ CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL=1 | `CONFIG_WEBRTC_AEC_AEC3_LINEAR_OUTPUT` | n | bool (AEC3) | Output the linear filter result and skip the residual echo suppressor, 16 kHz only | | `CONFIG_WEBRTC_AEC_AEC3_ADAPT_RATE_PCT` | 100 | int (`10` - `100`, AEC3) | Converged state coarse filter step and refined filter leakage in percent | | `CONFIG_WEBRTC_AEC_DELAY_AGNOSTIC` | n | bool (Float) | Enable signal-based delay estimation and extended filter | +| `CONFIG_WEBRTC_AEC_FLOAT_LINEAR_OUTPUT` | y | bool (Float) | Output the linear filter error without residual echo suppression (NLP) | + +The tuning options are the defaults of an instance, the bytes control below +overrides them. + +## Bytes Control + +Each instance has a bytes control, IPC4 param_id 1, with `struct webrtc_aec_config` +from `webrtc_aec.h`. It selects the backend (0 auto, 1 Float AEC, 2 AEC3, 3 AECm) +and sets the tuning of each backend, e.g. whether the Float AEC and AEC3 suppress +the residual echo, the echo path and microphone delays, the AEC3 filter lengths +and arena size. Without a blob the Kconfig defaults are used. A blob shorter +than the struct sets only its first fields. The blob is checked when it is +received, and it takes effect in the next prepare, i.e. at the next stream +start. + +The blobs are generated with `tune/sof_webrtc_aec_blobs.m`: + +| Blob | Use | +|---|---| +| `default` | The Kconfig defaults | +| `wov` | Wake on voice, the Float AEC outputs the linear filter error for a mono reference, AEC3 for a stereo reference with the linear output, a fixed 8 ms delay, 8 + 4 filter blocks and a 640 kB arena | +| `voip` | The defaults with residual echo suppression in the Float AEC and AEC3 | + +The topology blobs are in `tools/topology/topology2/include/components/webrtc-aec/`, +selected for the SoundWire topologies with `SDW_DMIC_WOV_AEC_PARAMS` (default +`wov`) and `SDW_SPK_AEC_PARAMS` (default `default`). The same blobs for `sof-ctl` +are in `tools/ctl/ipc4/webrtc_aec/`, e.g. + +```sh +sof-ctl -i 4 -c name='AEC config' -s tools/ctl/ipc4/webrtc_aec/voip.txt +``` --- diff --git a/src/audio/webrtc_aec/webrtc_aec-aec.c b/src/audio/webrtc_aec/webrtc_aec-aec.c index 9cca3c218f24..a021a787bf69 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec.c @@ -67,11 +67,10 @@ struct webrtc_aec_float_data { float xc_ref[WEBRTC_AEC_XC_HIST]; float xc_mic[WEBRTC_AEC_XC_HIST]; #endif -#if CONFIG_WEBRTC_AEC_MIC_DELAY_MS > 0 - int mic_dly_len; + int mic_dly_len; /* microphone delay in samples, 0 for none */ int mic_dly_pos[WEBRTC_AEC_CHANNELS_MAX]; - float mic_dly[WEBRTC_AEC_CHANNELS_MAX][CONFIG_WEBRTC_AEC_MIC_DELAY_MS * 16]; -#endif + float *mic_dly; /* mic_dly_len samples per microphone channel */ + float ref_gain; /* linear gain on the reference */ int delay_ms; float ref_f[WEBRTC_AEC_CHANNELS_MAX][WEBRTC_AEC_FRAME_SAMPLES_16K]; float mic_f[WEBRTC_AEC_FRAME_SAMPLES_16K]; @@ -102,9 +101,16 @@ static int webrtc_aec_float_apply_cfg(struct processing_module *mod, AecConfig config; int ret; - if (core && IS_ENABLED(CONFIG_WEBRTC_AEC_DELAY_AGNOSTIC)) { - WebRtcAec_enable_delay_agnostic(core, 1); - WebRtcAec_enable_extended_filter(core, 1); + if (core) { + if (cd->config.float_delay_agnostic) { + WebRtcAec_enable_delay_agnostic(core, 1); + WebRtcAec_enable_extended_filter(core, 1); + } + + /* After WebRtcAec_Init() that sets the library defaults */ + WebRtcAec_enable_linear_only(core, cd->config.float_linear_output); + if (cd->config.float_mu_permille) + WebRtcAec_set_normal_mu(core, cd->config.float_mu_permille / 1000.0f); } config.nlpMode = (cd->high_suppression || rd->suppression > 1) ? kAecNlpAggressive : @@ -138,10 +144,26 @@ static int webrtc_aec_float_configure(struct processing_module *mod, int sample_ rd->aec[c] = NULL; } } + if (rd->mic_dly) { + mod_free(mod, rd->mic_dly); + rd->mic_dly = NULL; + } rd->num_mic_channels = 0; rd->num_ref_channels = num_ref_channels; rd->suppression = suppression; rd->delay_ms = cd->delay_ms; + rd->ref_gain = (float)cd->config.float_ref_gain; + + /* The microphone delay line, zeroed for a silent start */ + rd->mic_dly_len = cd->config.mic_delay_ms * sample_rate_hz / 1000; + memset(rd->mic_dly_pos, 0, sizeof(rd->mic_dly_pos)); + if (rd->mic_dly_len) { + rd->mic_dly = mod_zalloc(mod, sizeof(float) * rd->mic_dly_len * num_mic_channels); + if (!rd->mic_dly) { + comp_err(mod->dev, "webrtc_aec: mic delay allocation failed"); + return -ENOMEM; + } + } /* Classic Float AEC is single-capture-channel per handle, so allocate one per mic. */ for (c = 0; c < num_mic_channels; c++) { @@ -167,15 +189,10 @@ static int webrtc_aec_float_configure(struct processing_module *mod, int sample_ rd->stats_frames = 0; rd->ref_peak = 0; rd->mic_peak = 0; -#if CONFIG_WEBRTC_AEC_MIC_DELAY_MS > 0 - rd->mic_dly_len = CONFIG_WEBRTC_AEC_MIC_DELAY_MS * sample_rate_hz / 1000; - memset(rd->mic_dly_pos, 0, sizeof(rd->mic_dly_pos)); - memset(rd->mic_dly, 0, sizeof(rd->mic_dly)); -#endif - comp_info(mod->dev, "webrtc_aec: Float AEC rate=%d high_supp=%d mic_ch=%d ref_ch=%d delay=%d ms ref_gain=%d mic_delay=%d ms", + comp_info(mod->dev, "webrtc_aec: Float AEC rate=%d high_supp=%d mic_ch=%d ref_ch=%d delay=%d ms ref_gain=%d mic_delay=%d ms linear=%d mu=%d", sample_rate_hz, cd->high_suppression, num_mic_channels, num_ref_channels, - rd->delay_ms, CONFIG_WEBRTC_AEC_REF_GAIN, - CONFIG_WEBRTC_AEC_MIC_DELAY_MS); + rd->delay_ms, cd->config.float_ref_gain, cd->config.mic_delay_ms, + cd->config.float_linear_output, cd->config.float_mu_permille); return 0; err: @@ -230,7 +247,7 @@ static void webrtc_aec_float_erle(struct processing_module *mod, struct webrtc_aec_float_data *rd, const float *ref_f, int frame_samples) { - const float inv_gain = 1.0f / (float)CONFIG_WEBRTC_AEC_REF_GAIN; + const float inv_gain = 1.0f / rd->ref_gain; float ref_e = 0.0f, mic_e = 0.0f, out_e = 0.0f; float norm; int i; @@ -286,10 +303,10 @@ static float webrtc_aec_frame_db(const int16_t *x, int frame_samples) return 10.0f * log10f(e); } -/* Same for the float reference with the REF_GAIN removed */ -static float webrtc_aec_frame_db_f(const float *x, int frame_samples) +/* Same for the float reference with the reference gain removed */ +static float webrtc_aec_frame_db_f(const float *x, int frame_samples, float ref_gain) { - const float inv_gain = 1.0f / (float)CONFIG_WEBRTC_AEC_REF_GAIN; + const float inv_gain = 1.0f / ref_gain; float e = 1.0f; int i; @@ -311,7 +328,7 @@ static void webrtc_aec_float_xcorr(struct processing_module *mod, int best_lag = 0; int newest, start, lag, n, im, ir; - rd->xc_ref[rd->xc_pos] = webrtc_aec_frame_db_f(ref_f, frame_samples); + rd->xc_ref[rd->xc_pos] = webrtc_aec_frame_db_f(ref_f, frame_samples, rd->ref_gain); rd->xc_mic[rd->xc_pos] = webrtc_aec_frame_db(mic, frame_samples); newest = rd->xc_pos; rd->xc_pos = (rd->xc_pos + 1) % h; @@ -427,17 +444,18 @@ static int webrtc_aec_float_run_ch(struct processing_module *mod, #endif } -#if CONFIG_WEBRTC_AEC_MIC_DELAY_MS > 0 - for (i = 0; i < frame_samples; i++) { - float x = rd->mic_f[i]; - float *dly = rd->mic_dly[ch]; + if (rd->mic_dly_len) { + float *dly = rd->mic_dly + ch * rd->mic_dly_len; - rd->mic_f[i] = dly[rd->mic_dly_pos[ch]]; - dly[rd->mic_dly_pos[ch]] = x; - if (++rd->mic_dly_pos[ch] >= rd->mic_dly_len) - rd->mic_dly_pos[ch] = 0; + for (i = 0; i < frame_samples; i++) { + float x = rd->mic_f[i]; + + rd->mic_f[i] = dly[rd->mic_dly_pos[ch]]; + dly[rd->mic_dly_pos[ch]] = x; + if (++rd->mic_dly_pos[ch] >= rd->mic_dly_len) + rd->mic_dly_pos[ch] = 0; + } } -#endif ret = WebRtcAec_Process(rd->aec[ch], nearend, 1, out_ptrs, (size_t)frame_samples, (int16_t)rd->delay_ms, 0); @@ -494,7 +512,7 @@ static int webrtc_aec_float_process_frame(struct processing_module *mod, { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); struct webrtc_aec_float_data *rd = cd->backend_data; - const float gain = (float)CONFIG_WEBRTC_AEC_REF_GAIN; + const float gain = rd->ref_gain; int i, c, ret; if (frame_samples <= 0 || frame_samples > WEBRTC_AEC_FRAME_SAMPLES_16K || @@ -514,7 +532,7 @@ static int webrtc_aec_float_process_frame(struct processing_module *mod, /* * Convert reference to float once outside the mic loop: use per-channel ref * when ref and mic counts match, otherwise downmix multi-channel ref to mono. - * The reference gain is applied here, see WEBRTC_AEC_REF_GAIN. + * The reference gain is applied here, see webrtc_aec_config.float_ref_gain. */ if (num_ref_channels == num_mic_channels) { for (c = 0; c < num_ref_channels; c++) { @@ -560,7 +578,7 @@ static int webrtc_aec_float_process_ch(struct processing_module *mod, return -EINVAL; for (i = 0; i < frame_samples; i++) { - rd->ref_f[0][i] = (float)ref[i] * (float)CONFIG_WEBRTC_AEC_REF_GAIN; + rd->ref_f[0][i] = (float)ref[i] * rd->ref_gain; #ifdef CONFIG_WEBRTC_AEC_DELAY_DEBUG if (ref[i] > rd->ref_peak) rd->ref_peak = ref[i]; @@ -585,6 +603,8 @@ static int webrtc_aec_float_free(struct processing_module *mod) rd->aec[c] = NULL; } } + if (rd->mic_dly) + mod_free(mod, rd->mic_dly); mod_free(mod, rd); cd->backend_data = NULL; return 0; @@ -592,7 +612,7 @@ static int webrtc_aec_float_free(struct processing_module *mod) const struct webrtc_aec_backend webrtc_aec_backend_float = { .name = "aec_float", - .default_delay_ms = CONFIG_WEBRTC_AEC_DELAY_MS, + .id = WEBRTC_AEC_ID_FLOAT, .init = webrtc_aec_float_init, .configure = webrtc_aec_float_configure, .set_suppression = webrtc_aec_float_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec-aec3.c b/src/audio/webrtc_aec/webrtc_aec-aec3.c index 59c1233b31be..55bf68b89e06 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec3.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec3.c @@ -103,9 +103,9 @@ static int webrtc_aec3_bufs_alloc(struct processing_module *mod, struct webrtc_a /** * webrtc_aec3_backend_create() - Create the AEC3 instance from rd->cfg. - * With CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE the instance is created into the - * arena of the instance, which is allocated first if needed. The previous - * AEC3 instance must have been freed. + * With a non-zero webrtc_aec_config.aec3_arena_kb the instance is created + * into the arena of the instance, which is allocated first if needed. The + * previous AEC3 instance must have been freed. * @mod: processing module * @rd: backend data * @@ -115,12 +115,17 @@ static int webrtc_aec3_bufs_alloc(struct processing_module *mod, struct webrtc_a static int webrtc_aec3_backend_create(struct processing_module *mod, struct webrtc_aec3_data *rd) { -#if WEBRTC_AEC_HAVE_ARENA struct webrtc_aec_comp_data *cd = module_get_private_data(mod); struct webrtc_aec_arena *arena = &cd->mem.arena; + size_t arena_size = (size_t)cd->config.aec3_arena_kb * 1024; int ret; - ret = webrtc_aec_arena_alloc(&cd->mem, CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); + if (!arena_size) { + rd->aec3 = webrtc_aec3_create_cfg(&rd->cfg); + return rd->aec3 ? 0 : -ENOMEM; + } + + ret = webrtc_aec_arena_alloc(&cd->mem, arena_size); if (ret < 0) return ret; @@ -131,11 +136,8 @@ static int webrtc_aec3_backend_create(struct processing_module *mod, comp_warn(mod->dev, "webrtc_aec: AEC3 arena overflow, %zu bytes from heap, increase arena to %zu bytes", arena->overflow, arena->used + arena->overflow); else - comp_info(mod->dev, "webrtc_aec: AEC3 arena used %zu of %d bytes", - arena->used, CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE); -#else - rd->aec3 = webrtc_aec3_create_cfg(&rd->cfg); -#endif + comp_info(mod->dev, "webrtc_aec: AEC3 arena used %zu of %zu bytes", + arena->used, arena_size); return rd->aec3 ? 0 : -ENOMEM; } @@ -152,18 +154,14 @@ static int webrtc_aec3_backend_configure(struct processing_module *mod, int samp .num_capture_channels = (num_mic_channels > WEBRTC_AEC_CHANNELS_MAX) ? WEBRTC_AEC_CHANNELS_MAX : num_mic_channels, .delay_ms = cd->delay_ms, -#ifdef CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS - .filter_length_blocks = CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS, -#else - .filter_length_blocks = 12, -#endif - .coarse_filter_length_blocks = CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS, - .linear_output = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_LINEAR_OUTPUT), - .adapt_rate_pct = CONFIG_WEBRTC_AEC_AEC3_ADAPT_RATE_PCT, - .capture_delay_ms = CONFIG_WEBRTC_AEC_MIC_DELAY_MS, - .use_external_delay_estimator = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST), - .enable_coarse_filter = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER), - .detect_stereo_content = IS_ENABLED(CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT), + .filter_length_blocks = cd->config.aec3_filter_blocks, + .coarse_filter_length_blocks = cd->config.aec3_coarse_filter_blocks, + .linear_output = cd->config.aec3_linear_output, + .adapt_rate_pct = cd->config.aec3_adapt_rate_pct, + .capture_delay_ms = cd->config.mic_delay_ms, + .use_external_delay_estimator = cd->config.aec3_external_delay_est, + .enable_coarse_filter = cd->config.aec3_coarse_filter, + .detect_stereo_content = cd->config.aec3_stereo_content_detect, .high_suppression = (cd->high_suppression || suppression > 1), }; @@ -460,9 +458,7 @@ static int webrtc_aec3_backend_free(struct processing_module *mod) webrtc_aec3_free(rd->aec3); rd->aec3 = NULL; } -#if WEBRTC_AEC_HAVE_ARENA webrtc_aec_arena_free(&cd->mem); -#endif if (rd->bufs) mod_free(mod, rd->bufs); mod_free(mod, rd); @@ -472,7 +468,7 @@ static int webrtc_aec3_backend_free(struct processing_module *mod) const struct webrtc_aec_backend webrtc_aec_backend_aec3 = { .name = "aec3", - .default_delay_ms = CONFIG_WEBRTC_AEC_AEC3_DELAY_MS, + .id = WEBRTC_AEC_ID_AEC3, .init = webrtc_aec3_backend_init, .configure = webrtc_aec3_backend_configure, .set_suppression = webrtc_aec3_backend_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec-aecm.c b/src/audio/webrtc_aec/webrtc_aec-aecm.c index 2a8d7883fa2a..9f832a8827fe 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aecm.c +++ b/src/audio/webrtc_aec/webrtc_aec-aecm.c @@ -219,7 +219,7 @@ static int webrtc_aec_real_free(struct processing_module *mod) const struct webrtc_aec_backend webrtc_aec_backend_aecm = { .name = "aecm", - .default_delay_ms = CONFIG_WEBRTC_AEC_AECM_DELAY_MS, + .id = WEBRTC_AEC_ID_AECM, .init = webrtc_aec_real_init, .configure = webrtc_aec_real_configure, .set_suppression = webrtc_aec_real_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec-stub.c b/src/audio/webrtc_aec/webrtc_aec-stub.c index 9a1cbebdf9ea..5bc546ef2f97 100644 --- a/src/audio/webrtc_aec/webrtc_aec-stub.c +++ b/src/audio/webrtc_aec/webrtc_aec-stub.c @@ -60,7 +60,7 @@ static int webrtc_aec_stub_free(struct processing_module *mod) const struct webrtc_aec_backend webrtc_aec_backend_stub = { .name = "stub", - .default_delay_ms = 0, + .id = WEBRTC_AEC_ID_STUB, .init = webrtc_aec_stub_init, .configure = webrtc_aec_stub_configure, .set_suppression = webrtc_aec_stub_set_suppression, diff --git a/src/audio/webrtc_aec/webrtc_aec.c b/src/audio/webrtc_aec/webrtc_aec.c index d45c252163fe..afc05b8440cc 100644 --- a/src/audio/webrtc_aec/webrtc_aec.c +++ b/src/audio/webrtc_aec/webrtc_aec.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include "webrtc_aec.h" @@ -283,6 +284,231 @@ static void webrtc_aec_resolve_sources(struct sof_source **sources, int num_of_s } } +/* ---------------------------------------------------------------- + * Configuration blob + * ---------------------------------------------------------------- */ + +/** + * \brief Set the configuration defaults from Kconfig. + * + * The options of a backend that is not built get the Kconfig defaults. + * + * \param[out] cfg Configuration to set + */ +static void webrtc_aec_config_defaults(struct webrtc_aec_config *cfg) +{ + memset(cfg, 0, sizeof(*cfg)); + if (IS_ENABLED(CONFIG_WEBRTC_AEC_SELECT_FLOAT)) + cfg->backend = WEBRTC_AEC_ID_FLOAT; + else if (IS_ENABLED(CONFIG_WEBRTC_AEC_SELECT_AEC3)) + cfg->backend = WEBRTC_AEC_ID_AEC3; + else if (IS_ENABLED(CONFIG_WEBRTC_AEC_SELECT_AECM)) + cfg->backend = WEBRTC_AEC_ID_AECM; + else + cfg->backend = WEBRTC_AEC_ID_AUTO; + + cfg->suppression = CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL; + cfg->downmix_ref = IS_ENABLED(CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF); +#ifdef CONFIG_WEBRTC_AEC_MIC_DELAY_MS + cfg->mic_delay_ms = CONFIG_WEBRTC_AEC_MIC_DELAY_MS; +#else + cfg->mic_delay_ms = 8; +#endif +#ifdef CONFIG_WEBRTC_AEC_DELAY_MS + cfg->float_delay_ms = CONFIG_WEBRTC_AEC_DELAY_MS; +#endif +#ifdef CONFIG_WEBRTC_AEC_REF_GAIN + cfg->float_ref_gain = CONFIG_WEBRTC_AEC_REF_GAIN; +#else + cfg->float_ref_gain = 16; +#endif + cfg->float_linear_output = IS_ENABLED(CONFIG_WEBRTC_AEC_FLOAT_LINEAR_OUTPUT); + cfg->float_delay_agnostic = IS_ENABLED(CONFIG_WEBRTC_AEC_DELAY_AGNOSTIC); +#ifdef CONFIG_WEBRTC_AEC_AEC3_DELAY_MS + cfg->aec3_delay_ms = CONFIG_WEBRTC_AEC_AEC3_DELAY_MS; +#else + cfg->aec3_delay_ms = 20; +#endif + cfg->aec3_external_delay_est = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST); +#ifdef CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS + cfg->aec3_filter_blocks = CONFIG_WEBRTC_AEC_AEC3_FILTER_BLOCKS; + cfg->aec3_coarse_filter_blocks = CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER_BLOCKS; + cfg->aec3_adapt_rate_pct = CONFIG_WEBRTC_AEC_AEC3_ADAPT_RATE_PCT; + cfg->aec3_arena_kb = DIV_ROUND_UP(CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE, 1024); +#else + cfg->aec3_filter_blocks = 12; + cfg->aec3_adapt_rate_pct = 100; +#endif + cfg->aec3_coarse_filter = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_COARSE_FILTER); + cfg->aec3_linear_output = IS_ENABLED(CONFIG_WEBRTC_AEC_AEC3_LINEAR_OUTPUT); + cfg->aec3_stereo_content_detect = IS_ENABLED(CONFIG_WEBRTC_AEC_STEREO_CONTENT_DETECT); +#ifdef CONFIG_WEBRTC_AEC_AECM_DELAY_MS + cfg->aecm_delay_ms = CONFIG_WEBRTC_AEC_AECM_DELAY_MS; +#else + cfg->aecm_delay_ms = 20; +#endif + cfg->aecm_filter_len_ms = CONFIG_WEBRTC_AEC_FILTER_LEN_MS; +} + +/** \brief Valid range of a configuration field. */ +struct webrtc_aec_config_range { + const char *name; /**< Field name for the error trace */ + size_t offset; /**< Field offset in struct webrtc_aec_config */ + int32_t min; /**< Minimum value */ + int32_t max; /**< Maximum value */ +}; + +#define WEBRTC_AEC_RANGE(field, lo, hi) \ + { #field, offsetof(struct webrtc_aec_config, field), lo, hi } + +static const struct webrtc_aec_config_range webrtc_aec_config_ranges[] = { + WEBRTC_AEC_RANGE(backend, WEBRTC_AEC_ID_AUTO, WEBRTC_AEC_ID_AECM), + WEBRTC_AEC_RANGE(suppression, 0, 2), + WEBRTC_AEC_RANGE(mic_delay_ms, 0, WEBRTC_AEC_MIC_DELAY_MAX_MS), + WEBRTC_AEC_RANGE(downmix_ref, 0, 1), + WEBRTC_AEC_RANGE(float_delay_ms, 0, 15), + WEBRTC_AEC_RANGE(float_ref_gain, 1, 256), + WEBRTC_AEC_RANGE(float_linear_output, 0, 1), + WEBRTC_AEC_RANGE(float_mu_permille, 0, 1000), + WEBRTC_AEC_RANGE(float_delay_agnostic, 0, 1), + WEBRTC_AEC_RANGE(aec3_delay_ms, 0, 500), + WEBRTC_AEC_RANGE(aec3_external_delay_est, 0, 1), + WEBRTC_AEC_RANGE(aec3_filter_blocks, 1, 30), + WEBRTC_AEC_RANGE(aec3_coarse_filter, 0, 1), + WEBRTC_AEC_RANGE(aec3_coarse_filter_blocks, 0, 30), + WEBRTC_AEC_RANGE(aec3_linear_output, 0, 1), + WEBRTC_AEC_RANGE(aec3_adapt_rate_pct, 10, 100), + WEBRTC_AEC_RANGE(aec3_stereo_content_detect, 0, 1), + WEBRTC_AEC_RANGE(aec3_arena_kb, 0, 4096), + WEBRTC_AEC_RANGE(aecm_delay_ms, 0, 500), + WEBRTC_AEC_RANGE(aecm_filter_len_ms, 32, 128), +}; + +/** + * \brief Get a built backend by its identifier. + * + * \param[in] id Backend identifier + * \return Backend, NULL if the backend is not built + */ +static const struct webrtc_aec_backend *webrtc_aec_backend_by_id(int32_t id) +{ + switch (id) { +#if CONFIG_WEBRTC_AEC_BACKEND_FLOAT + case WEBRTC_AEC_ID_FLOAT: + return &webrtc_aec_backend_float; +#endif +#if CONFIG_WEBRTC_AEC_BACKEND_AEC3 + case WEBRTC_AEC_ID_AEC3: + return &webrtc_aec_backend_aec3; +#endif +#if CONFIG_WEBRTC_AEC_BACKEND_AECM + case WEBRTC_AEC_ID_AECM: + return &webrtc_aec_backend_aecm; +#endif + default: + return NULL; + } +} + +/** + * \brief Check a configuration. + * + * \param[in] mod Processing module + * \param[in] cfg Configuration to check + * \return 0 if valid, -EINVAL otherwise + */ +static int webrtc_aec_config_check(struct processing_module *mod, + const struct webrtc_aec_config *cfg) +{ + const struct webrtc_aec_config_range *r; + int32_t val; + int i; + + for (i = 0; i < ARRAY_SIZE(webrtc_aec_config_ranges); i++) { + r = &webrtc_aec_config_ranges[i]; + val = *(const int32_t *)((const uint8_t *)cfg + r->offset); + if (val < r->min || val > r->max) { + comp_err(mod->dev, "webrtc_aec: config %s %d not in %d - %d", + r->name, val, r->min, r->max); + return -EINVAL; + } + } + + if (cfg->aecm_filter_len_ms != 32 && cfg->aecm_filter_len_ms != 64 && + cfg->aecm_filter_len_ms != 128) { + comp_err(mod->dev, "webrtc_aec: config aecm_filter_len_ms %d not 32, 64 or 128", + cfg->aecm_filter_len_ms); + return -EINVAL; + } + + if (!IS_ENABLED(CONFIG_COMP_WEBRTC_AEC_STUB) && cfg->backend != WEBRTC_AEC_ID_AUTO && + !webrtc_aec_backend_by_id(cfg->backend)) { + comp_err(mod->dev, "webrtc_aec: config backend %d is not built", + cfg->backend); + return -EINVAL; + } + + return 0; +} + +/** + * \brief Set the configuration from the bytes control payload. + * + * The fields that a short blob does not contain get the Kconfig defaults. + * + * \param[in] mod Processing module + * \param[in] data Payload, struct webrtc_aec_config or a beginning of it + * \param[in] size Payload size in bytes + * \return 0 on success, -EINVAL for an invalid blob + */ +static int webrtc_aec_config_set(struct processing_module *mod, const uint8_t *data, + size_t size) +{ + struct webrtc_aec_comp_data *cd = module_get_private_data(mod); + struct webrtc_aec_config cfg; + int ret; + + if (!size || size > sizeof(cfg) || size % sizeof(int32_t)) { + comp_err(mod->dev, "webrtc_aec: invalid config size %zu, max %zu", + size, sizeof(cfg)); + return -EINVAL; + } + + webrtc_aec_config_defaults(&cfg); + memcpy_s(&cfg, sizeof(cfg), data, size); + ret = webrtc_aec_config_check(mod, &cfg); + if (ret) + return ret; + + cd->config = cfg; + comp_info(mod->dev, "webrtc_aec: config backend %d supp %d mic_delay %d, %s", + cfg.backend, cfg.suppression, cfg.mic_delay_ms, + cd->configured ? "used at next stream start" : "updated"); + return 0; +} + +/** + * \brief Get the echo path delay of a backend from the configuration. + * + * \param[in] cfg Configuration + * \param[in] id Backend identifier + * \return Delay in ms + */ +static int webrtc_aec_config_delay(const struct webrtc_aec_config *cfg, + enum webrtc_aec_backend_id id) +{ + switch (id) { + case WEBRTC_AEC_ID_FLOAT: + return cfg->float_delay_ms; + case WEBRTC_AEC_ID_AEC3: + return cfg->aec3_delay_ms; + case WEBRTC_AEC_ID_AECM: + return cfg->aecm_delay_ms; + default: + return 0; + } +} + /* ---------------------------------------------------------------- * module_interface operations * ---------------------------------------------------------------- */ @@ -305,7 +531,7 @@ __cold static int webrtc_aec_init(struct processing_module *mod) cd->mem.mod = mod; cd->enabled = false; cd->high_suppression = false; - cd->downmix_ref = IS_ENABLED(CONFIG_WEBRTC_AEC_STEREO_DOWNMIX_REF); + webrtc_aec_config_defaults(&cd->config); /* Two input pins: mic + echo reference. */ mod->max_sources = 2; @@ -316,7 +542,8 @@ __cold static int webrtc_aec_init(struct processing_module *mod) /** * \brief Select the backend for the negotiated formats. * - * See WEBRTC_AEC_BACKEND_SELECT in Kconfig for the selection rules. + * The configured backend, or with WEBRTC_AEC_ID_AUTO the backend for the + * echo reference channel count, see WEBRTC_AEC_SELECT_AUTO in Kconfig. * * \param[in] cd Module data with effective_ref_ch set * \return Backend @@ -326,13 +553,11 @@ webrtc_aec_select_backend(const struct webrtc_aec_comp_data *cd) { #if CONFIG_COMP_WEBRTC_AEC_STUB return &webrtc_aec_backend_stub; -#elif CONFIG_WEBRTC_AEC_SELECT_FLOAT - return &webrtc_aec_backend_float; -#elif CONFIG_WEBRTC_AEC_SELECT_AEC3 - return &webrtc_aec_backend_aec3; -#elif CONFIG_WEBRTC_AEC_SELECT_AECM - return &webrtc_aec_backend_aecm; #else + /* webrtc_aec_config_check() allows only built backends */ + if (cd->config.backend != WEBRTC_AEC_ID_AUTO) + return webrtc_aec_backend_by_id(cd->config.backend); + #if CONFIG_WEBRTC_AEC_BACKEND_AEC3 /* AEC3 cancels a multi-channel reference jointly */ if (cd->effective_ref_ch > 1) @@ -485,6 +710,7 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, /* Free the state of a previous prepare() without reset() */ webrtc_aec_release(mod); + cd->downmix_ref = cd->config.downmix_ref; if ((num_of_sources != 1 && num_of_sources != 2) || num_of_sinks != 1) { comp_err(dev, "webrtc_aec: need 1 or 2 sources and 1 sink (got %d/%d)", @@ -600,7 +826,7 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, cd->resamp_mode); cd->backend = webrtc_aec_select_backend(cd); - cd->delay_ms = cd->backend->default_delay_ms; + cd->delay_ms = webrtc_aec_config_delay(&cd->config, cd->backend->id); comp_info(dev, "webrtc_aec: backend '%s' for %d reference channels", cd->backend->name, cd->effective_ref_ch); @@ -622,8 +848,8 @@ __cold static int webrtc_aec_prepare(struct processing_module *mod, if (cd->backend->configure) { ret = cd->backend->configure(mod, cd->proc_rate, - CONFIG_WEBRTC_AEC_FILTER_LEN_MS, - CONFIG_WEBRTC_AEC_SUPPRESSION_LEVEL, + cd->config.aecm_filter_len_ms, + cd->config.suppression, cd->mic_channels, cd->effective_ref_ch); if (ret) { comp_err(dev, "webrtc_aec: backend configure failed %d", ret); @@ -1031,6 +1257,16 @@ static int webrtc_aec_set_config(struct processing_module *mod, uint32_t param_i struct webrtc_aec_comp_data *cd = module_get_private_data(mod); struct comp_dev *dev = mod->dev; + if (param_id == WEBRTC_AEC_CONFIG_PARAM_ID) { + /* The blob is small, it comes in a single fragment */ + if (pos != MODULE_CFG_FRAGMENT_SINGLE) { + comp_err(dev, "webrtc_aec: fragmented config is not supported"); + return -EINVAL; + } + + return webrtc_aec_config_set(mod, fragment, fragment_size); + } + if (param_id == SOF_IPC4_SWITCH_CONTROL_PARAM_ID) { const struct sof_ipc4_control_msg_payload *ctl = (const struct sof_ipc4_control_msg_payload *)fragment; @@ -1060,6 +1296,15 @@ static int webrtc_aec_get_config(struct processing_module *mod, uint32_t config_ { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); + if (config_id == WEBRTC_AEC_CONFIG_PARAM_ID) { + if (fragment_size < sizeof(cd->config)) + return -EINVAL; + + memcpy_s(fragment, fragment_size, &cd->config, sizeof(cd->config)); + *data_offset_size = sizeof(cd->config); + return 0; + } + if (config_id == SOF_IPC4_SWITCH_CONTROL_PARAM_ID) { struct sof_ipc4_control_msg_payload *ctl = (struct sof_ipc4_control_msg_payload *)fragment; diff --git a/src/audio/webrtc_aec/webrtc_aec.h b/src/audio/webrtc_aec/webrtc_aec.h index 5f164826928f..8a56f2e0e5a5 100644 --- a/src/audio/webrtc_aec/webrtc_aec.h +++ b/src/audio/webrtc_aec/webrtc_aec.h @@ -58,6 +58,54 @@ #define WEBRTC_AEC_CTL_ID_HIGH_SUPPRESSION 1 #define WEBRTC_AEC_CTL_NUM_ELEMS 1 +/* Maximum microphone delay in webrtc_aec_config.mic_delay_ms */ +#define WEBRTC_AEC_MIC_DELAY_MAX_MS 20 + +/* IPC4 param_id of the bytes control with struct webrtc_aec_config */ +#define WEBRTC_AEC_CONFIG_PARAM_ID 1 + +/** \brief Backend identifiers, also the values of webrtc_aec_config.backend. */ +enum webrtc_aec_backend_id { + WEBRTC_AEC_ID_AUTO = 0, /**< Select by the echo reference channel count */ + WEBRTC_AEC_ID_FLOAT = 1, /**< Classic Float AEC */ + WEBRTC_AEC_ID_AEC3 = 2, /**< AEC3 */ + WEBRTC_AEC_ID_AECM = 3, /**< Fixed-point AECm */ + WEBRTC_AEC_ID_STUB = 4, /**< Pass-through stub, not selectable */ +}; + +/** + * \brief Configuration of an instance, the payload of the bytes control. + * + * All fields are 32-bit little endian integers. Without a blob the + * defaults come from Kconfig. A blob shorter than this struct sets only the + * fields it contains, the rest keep the Kconfig defaults. The settings take + * effect in the next prepare(), i.e. at the next stream start. Boolean + * fields are zero for false and one for true. See tune/sof_webrtc_aec_blobs.m + * for the blob generator. + */ +struct webrtc_aec_config { + int32_t backend; /**< enum webrtc_aec_backend_id */ + int32_t suppression; /**< 0 - 2, AECm comfort noise, Float NLP mode, 2 AEC3 high */ + int32_t mic_delay_ms; /**< 0 - 20, Float AEC and AEC3 microphone delay */ + int32_t downmix_ref; /**< Downmix a multi-channel reference to mono */ + int32_t float_delay_ms; /**< 0 - 15, Float AEC reference to echo delay */ + int32_t float_ref_gain; /**< 1 - 256, Float AEC linear reference gain */ + int32_t float_linear_output; /**< Float AEC without residual echo suppression */ + int32_t float_mu_permille; /**< 0 - 1000, Float AEC step size, 0 for the default */ + int32_t float_delay_agnostic; /**< Float AEC signal based delay estimation */ + int32_t aec3_delay_ms; /**< 0 - 500, AEC3 nominal echo path delay */ + int32_t aec3_external_delay_est; /**< AEC3 uses aec3_delay_ms, no delay search */ + int32_t aec3_filter_blocks; /**< 1 - 30, AEC3 refined filter length in 4 ms blocks */ + int32_t aec3_coarse_filter; /**< AEC3 coarse filter output fallback */ + int32_t aec3_coarse_filter_blocks; /**< 0 - 30, coarse filter length, 0 for refined */ + int32_t aec3_linear_output; /**< AEC3 without residual echo suppression */ + int32_t aec3_adapt_rate_pct; /**< 10 - 100, AEC3 converged state adaptation speed */ + int32_t aec3_stereo_content_detect; /**< AEC3 stereo vs. dual mono content detector */ + int32_t aec3_arena_kb; /**< 0 - 4096, AEC3 arena size in kB, 0 for the heap */ + int32_t aecm_delay_ms; /**< 0 - 500, AECm nominal echo path delay */ + int32_t aecm_filter_len_ms; /**< 32, 64 or 128, AECm filter length */ +}; + enum webrtc_aec_resamp_mode { WEBRTC_AEC_RESAMP_NONE = 0, WEBRTC_AEC_RESAMP_32_TO_16, @@ -92,7 +140,7 @@ union webrtc_aec_up_state { /* Temporary buffer length of WebRtcSpl_Resample48khzTo16khz() and back. */ #define WEBRTC_AEC_RESAMP_TMP_LEN 512 -#if defined(CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE) && CONFIG_WEBRTC_AEC_AEC3_ARENA_SIZE > 0 +#if CONFIG_WEBRTC_AEC_BACKEND_AEC3 #define WEBRTC_AEC_HAVE_ARENA 1 #else #define WEBRTC_AEC_HAVE_ARENA 0 @@ -139,9 +187,7 @@ struct webrtc_aec_mem { */ struct webrtc_aec_backend { const char *name; - - /* Echo path delay in ms given to set_delay() after configure(). */ - int default_delay_ms; + enum webrtc_aec_backend_id id; /* Allocate the backend data. Called from prepare(), before configure(). */ int (*init)(struct processing_module *mod); @@ -214,7 +260,8 @@ struct webrtc_aec_comp_data { /* Runtime ALSA mixer controls */ bool enabled; /* master bypass switch (WEBRTC_AEC_CTL_ID_ENABLE) */ bool high_suppression; /* suppression switch (WEBRTC_AEC_CTL_ID_HIGH_SUPPRESSION) */ - int delay_ms; /* echo path delay (ms), backend default in prepare */ + struct webrtc_aec_config config; /* bytes control, used in prepare() */ + int delay_ms; /* echo path delay (ms) of the backend, set in prepare */ bool downmix_ref; /* downmix multi-ch ref to mono before backend */ bool downmix_mic; /* average multi-ch mic to mono for a mono output */ From 284a78c489cf20c87671053db2090da875ff788c Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 13:59:00 +0200 Subject: [PATCH 16/17] topology2: webrtc-aec: add the configuration bytes control and blobs Add the bytes control of struct webrtc_aec_config to the webrtc-aec widget class and the script tune/sof_webrtc_aec_blobs.m that exports the blobs for the topology and for sof-ctl: default with the Kconfig defaults, wov with the Float AEC linear output and the AEC3 settings for a stereo echo reference, and voip with the residual echo suppression enabled. The SDW_SPK_AEC_CAPTURE_PCM AEC gets the default blob, selected with the new SDW_SPK_AEC_PARAMS. The control is named "AEC config". Signed-off-by: Seppo Ingalsuo --- .../webrtc_aec/tune/sof_webrtc_aec_blobs.m | 137 ++++++++++++++++++ tools/ctl/ipc4/webrtc_aec/default.txt | 1 + tools/ctl/ipc4/webrtc_aec/voip.txt | 1 + tools/ctl/ipc4/webrtc_aec/wov.txt | 1 + tools/topology/topology2/cavs-sdw.conf | 3 + .../include/components/webrtc-aec.conf | 9 ++ .../components/webrtc-aec/default.conf | 19 +++ .../include/components/webrtc-aec/voip.conf | 19 +++ .../include/components/webrtc-aec/wov.conf | 19 +++ .../topology2/platform/intel/sdw-amp-aec.conf | 8 + 10 files changed, 217 insertions(+) create mode 100644 src/audio/webrtc_aec/tune/sof_webrtc_aec_blobs.m create mode 100644 tools/ctl/ipc4/webrtc_aec/default.txt create mode 100644 tools/ctl/ipc4/webrtc_aec/voip.txt create mode 100644 tools/ctl/ipc4/webrtc_aec/wov.txt create mode 100644 tools/topology/topology2/include/components/webrtc-aec/default.conf create mode 100644 tools/topology/topology2/include/components/webrtc-aec/voip.conf create mode 100644 tools/topology/topology2/include/components/webrtc-aec/wov.conf diff --git a/src/audio/webrtc_aec/tune/sof_webrtc_aec_blobs.m b/src/audio/webrtc_aec/tune/sof_webrtc_aec_blobs.m new file mode 100644 index 000000000000..74595f0b803f --- /dev/null +++ b/src/audio/webrtc_aec/tune/sof_webrtc_aec_blobs.m @@ -0,0 +1,137 @@ +% Export configuration blobs for the WebRTC AEC +% +% This script creates the bytes control blobs of struct webrtc_aec_config +% in src/audio/webrtc_aec/webrtc_aec.h for the topology and for sof-ctl. +% Run the script interactively from Octave shell with just command: +% +% sof_webrtc_aec_blobs +% +% There are no arguments for the function. Or from SOF level directory +% with command: +% +% cd src/audio/webrtc_aec/tune; octave sof_webrtc_aec_blobs.m +% +% The blobs are +% default - the Kconfig defaults +% wov - wake on voice, the Float AEC outputs the linear filter error +% for a mono echo reference and AEC3 with the linear output, +% fixed delay and 640 kB arena is used for a stereo reference +% voip - residual echo suppression enabled in the Float AEC and AEC3 + +% SPDX-License-Identifier: BSD-3-Clause +% +% Copyright (c) 2026, Intel Corporation. + +function sof_webrtc_aec_blobs() + + sof_tools = '../../../../tools'; + sof_tplg = fullfile(sof_tools, 'topology/topology2'); + sof_tplg_aec = fullfile(sof_tplg, 'include/components/webrtc-aec'); + sof_ctl_aec = fullfile(sof_tools, 'ctl/ipc4/webrtc_aec'); + + sof_webrtc_aec_paths(true); + mkdir_if_missing(sof_tplg_aec); + mkdir_if_missing(sof_ctl_aec); + + % Defaults, as the Kconfig defaults + def = webrtc_aec_defaults(); + export_blob(def, 'default', sof_tplg_aec, sof_ctl_aec); + + % Wake on voice, the Float AEC keeps the near-end talker intact with the + % linear output. AEC3 for a stereo reference as in the + % app/webrtc_aec3_static_overlay.conf settings. + wov = def; + wov.aec3_delay_ms = 8; + wov.aec3_external_delay_est = 1; + wov.aec3_filter_blocks = 8; + wov.aec3_coarse_filter_blocks = 4; + wov.aec3_linear_output = 1; + wov.aec3_adapt_rate_pct = 50; + wov.aec3_stereo_content_detect = 0; + wov.aec3_arena_kb = 640; + export_blob(wov, 'wov', sof_tplg_aec, sof_ctl_aec); + + % VoIP, suppress also the residual echo + voip = def; + voip.float_linear_output = 0; + voip.aec3_linear_output = 0; + export_blob(voip, 'voip', sof_tplg_aec, sof_ctl_aec); + + sof_webrtc_aec_paths(false); +end + +% The fields in the order of struct webrtc_aec_config +function cfg = webrtc_aec_defaults() + cfg.backend = 0; % 0 auto, 1 Float AEC, 2 AEC3, 3 AECm + cfg.suppression = 1; % 0 - 2 + cfg.mic_delay_ms = 8; % 0 - 20 + cfg.downmix_ref = 0; + cfg.float_delay_ms = 0; % 0 - 15 + cfg.float_ref_gain = 16; % 1 - 256 + cfg.float_linear_output = 1; + cfg.float_mu_permille = 0; % 0 - 1000, 0 for the library default + cfg.float_delay_agnostic = 0; + cfg.aec3_delay_ms = 20; % 0 - 500 + cfg.aec3_external_delay_est = 0; + cfg.aec3_filter_blocks = 12; % 1 - 30 + cfg.aec3_coarse_filter = 1; + cfg.aec3_coarse_filter_blocks = 0; % 0 - 30, 0 for the refined length + cfg.aec3_linear_output = 0; + cfg.aec3_adapt_rate_pct = 100; % 10 - 100 + cfg.aec3_stereo_content_detect = 1; + cfg.aec3_arena_kb = 0; % 0 - 4096, 0 for the heap + cfg.aecm_delay_ms = 20; % 0 - 500 + cfg.aecm_filter_len_ms = 64; % 32, 64 or 128 +end + +function export_blob(cfg, name, tplg_dir, ctl_dir) + blob8 = sof_webrtc_aec_build_blob(cfg); + tplg2_fn = sprintf('%s/%s.conf', tplg_dir, name); + sof_tplg2_write(tplg2_fn, blob8, 'webrtc_aec_config', ... + 'Exported with script sof_webrtc_aec_blobs.m', ... + 'cd src/audio/webrtc_aec/tune; octave sof_webrtc_aec_blobs.m'); + ctl_fn = sprintf('%s/%s.txt', ctl_dir, name); + sof_alsactl_write(ctl_fn, blob8); +end + +function blob8 = sof_webrtc_aec_build_blob(cfg) + blob_type = 0; + blob_param_id = 1; % WEBRTC_AEC_CONFIG_PARAM_ID + values = cell2mat(struct2cell(cfg)); + data_length = length(values); + data_size = 4 * data_length; + ipc_ver = 4; + [abi_bytes, abi_size] = sof_get_abi(data_size, ipc_ver, blob_type, blob_param_id); + blob_size = data_size + abi_size; + blob8 = uint8(zeros(1, blob_size)); + blob8(1:abi_size) = abi_bytes; + j = abi_size + 1; + for i = 1:data_length + blob8(j:j+3) = word2byte(int32(values(i))); + j = j + 4; + end +end + +function mkdir_if_missing(d) + if ~exist(d, 'dir') + mkdir(d); + end +end + +function sof_webrtc_aec_paths(enable) + common = '../../../../tools/tune/common'; + if enable + addpath(common); + else + rmpath(common); + end +end + +function bytes = word2byte(word) + sh = [0 -8 -16 -24]; + w = typecast(int32(word), 'uint32'); + bytes = uint8(zeros(1, 4)); + for i = 1:4 + bytes(i) = bitand(bitshift(w, sh(i)), 255); + end +end diff --git a/tools/ctl/ipc4/webrtc_aec/default.txt b/tools/ctl/ipc4/webrtc_aec/default.txt new file mode 100644 index 000000000000..a08e36f6f0d3 --- /dev/null +++ b/tools/ctl/ipc4/webrtc_aec/default.txt @@ -0,0 +1 @@ +3,112,877023059,1,80,50450433,0,0,0,0,0,1,8,0,0,16,1,0,0,20,0,12,1,0,0,100,1,0,20,64 diff --git a/tools/ctl/ipc4/webrtc_aec/voip.txt b/tools/ctl/ipc4/webrtc_aec/voip.txt new file mode 100644 index 000000000000..9ae272384124 --- /dev/null +++ b/tools/ctl/ipc4/webrtc_aec/voip.txt @@ -0,0 +1 @@ +3,112,877023059,1,80,50450433,0,0,0,0,0,1,8,0,0,16,0,0,0,20,0,12,1,0,0,100,1,0,20,64 diff --git a/tools/ctl/ipc4/webrtc_aec/wov.txt b/tools/ctl/ipc4/webrtc_aec/wov.txt new file mode 100644 index 000000000000..8fab14ae2686 --- /dev/null +++ b/tools/ctl/ipc4/webrtc_aec/wov.txt @@ -0,0 +1 @@ +3,112,877023059,1,80,50450433,0,0,0,0,0,1,8,0,0,16,1,0,0,8,1,8,1,4,1,50,0,640,20,64 diff --git a/tools/topology/topology2/cavs-sdw.conf b/tools/topology/topology2/cavs-sdw.conf index a12e9deeb696..3e9aee543895 100644 --- a/tools/topology/topology2/cavs-sdw.conf +++ b/tools/topology/topology2/cavs-sdw.conf @@ -148,6 +148,9 @@ Define { SDW_JACK_PIPELINE_SRC "generic" SDW_ECHO_REF_DAI "false" SDW_SPK_AEC_CAPTURE_PCM "false" + # Bytes control blob of the SDW_SPK_AEC_CAPTURE_PCM AEC from + # include/components/webrtc-aec/ + SDW_SPK_AEC_PARAMS "default" } # override defaults with platform-specific config diff --git a/tools/topology/topology2/include/components/webrtc-aec.conf b/tools/topology/topology2/include/components/webrtc-aec.conf index 99c628a96e4f..8f2808f4fac0 100644 --- a/tools/topology/topology2/include/components/webrtc-aec.conf +++ b/tools/topology/topology2/include/components/webrtc-aec.conf @@ -23,6 +23,11 @@ # } # } # +# The bytes control "bytes.1" sets struct webrtc_aec_config of the +# firmware, e.g. the backend and its tuning. Set its name and include a +# blob from include/components/webrtc-aec/ in the widget object, without a +# blob the firmware uses the Kconfig defaults. +# # UUID: e5da7b5b-133a-ba46-b517651d6300bb83 # Topology byte order: # e5da7b5b → 5b:7b:da:e5 @@ -31,6 +36,7 @@ # b517651d6300bb83 (last 8 bytes, as-is) + Define { # AECm processes 10 ms frames (same as google-rtc-aec) @@ -99,6 +105,9 @@ Class.Widget."webrtc-aec" { } max 1 } + bytes."1" { + max 256 + } } # pin0 is the microphone and pin1 is the echo reference. The module has multiple diff --git a/tools/topology/topology2/include/components/webrtc-aec/default.conf b/tools/topology/topology2/include/components/webrtc-aec/default.conf new file mode 100644 index 000000000000..1975e2e0080c --- /dev/null +++ b/tools/topology/topology2/include/components/webrtc-aec/default.conf @@ -0,0 +1,19 @@ +# Exported with script sof_webrtc_aec_blobs.m 04-Dec-2026 +# cd src/audio/webrtc_aec/tune; octave sof_webrtc_aec_blobs.m +Object.Base.data."webrtc_aec_config" { + bytes " + 0x53,0x4f,0x46,0x34,0x01,0x00,0x00,0x00, + 0x50,0x00,0x00,0x00,0x01,0xd0,0x01,0x03, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x14,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x0c,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x64,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x14,0x00,0x00,0x00,0x40,0x00,0x00,0x00" +} diff --git a/tools/topology/topology2/include/components/webrtc-aec/voip.conf b/tools/topology/topology2/include/components/webrtc-aec/voip.conf new file mode 100644 index 000000000000..01f8c32ef0b5 --- /dev/null +++ b/tools/topology/topology2/include/components/webrtc-aec/voip.conf @@ -0,0 +1,19 @@ +# Exported with script sof_webrtc_aec_blobs.m 04-Dec-2026 +# cd src/audio/webrtc_aec/tune; octave sof_webrtc_aec_blobs.m +Object.Base.data."webrtc_aec_config" { + bytes " + 0x53,0x4f,0x46,0x34,0x01,0x00,0x00,0x00, + 0x50,0x00,0x00,0x00,0x01,0xd0,0x01,0x03, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x14,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x0c,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x64,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x14,0x00,0x00,0x00,0x40,0x00,0x00,0x00" +} diff --git a/tools/topology/topology2/include/components/webrtc-aec/wov.conf b/tools/topology/topology2/include/components/webrtc-aec/wov.conf new file mode 100644 index 000000000000..92d5abcefddd --- /dev/null +++ b/tools/topology/topology2/include/components/webrtc-aec/wov.conf @@ -0,0 +1,19 @@ +# Exported with script sof_webrtc_aec_blobs.m 04-Dec-2026 +# cd src/audio/webrtc_aec/tune; octave sof_webrtc_aec_blobs.m +Object.Base.data."webrtc_aec_config" { + bytes " + 0x53,0x4f,0x46,0x34,0x01,0x00,0x00,0x00, + 0x50,0x00,0x00,0x00,0x01,0xd0,0x01,0x03, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x32,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x80,0x02,0x00,0x00, + 0x14,0x00,0x00,0x00,0x40,0x00,0x00,0x00" +} diff --git a/tools/topology/topology2/platform/intel/sdw-amp-aec.conf b/tools/topology/topology2/platform/intel/sdw-amp-aec.conf index ec11b6cfc16b..59055d0bdbd7 100644 --- a/tools/topology/topology2/platform/intel/sdw-amp-aec.conf +++ b/tools/topology/topology2/platform/intel/sdw-amp-aec.conf @@ -233,6 +233,14 @@ Object.Widget.webrtc-aec.1 { mixer."2" { name "AEC high suppression switch" } + bytes."1" { + name "AEC config" + IncludeByKey.SDW_SPK_AEC_PARAMS { + "default" "include/components/webrtc-aec/default.conf" + "wov" "include/components/webrtc-aec/wov.conf" + "voip" "include/components/webrtc-aec/voip.conf" + } + } } Object.Base.input_pin_binding.1 { From c2d3c52caa3c0a5669405b5c1a1490022b9b04ee Mon Sep 17 00:00:00 2001 From: Seppo Ingalsuo Date: Fri, 4 Dec 2026 16:23:29 +0200 Subject: [PATCH 17/17] topology2: sdw-amp-aec: add stereo echo reference AEC version Add SDW_SPK_AEC_STEREO_REF to build the SoundWire speaker AEC capture topology for an AEC with a stereo echo reference, such as WebRTC AEC3. The default false keeps the current mono topologies unchanged. With true the microphone and the echo reference are not downmixed with micsel, the SRC outputs feed the AEC directly. Both AEC input pins are 16 kHz stereo since the kernel does not support different formats on the input pins. The AEC output is mono, the AEC averages the microphone channels. Add the target sof-ptl-rt713-l3-rt1320-l12-stereo-aec. It uses the wov configuration blob with the AEC3 settings for real time processing with a stereo echo reference. Signed-off-by: Seppo Ingalsuo --- tools/topology/topology2/cavs-sdw.conf | 4 + .../topology2/development/tplg-targets.cmake | 7 + .../topology2/platform/intel/sdw-amp-aec.conf | 170 +++++++++++++++++- 3 files changed, 173 insertions(+), 8 deletions(-) diff --git a/tools/topology/topology2/cavs-sdw.conf b/tools/topology/topology2/cavs-sdw.conf index 3e9aee543895..da26a52747a4 100644 --- a/tools/topology/topology2/cavs-sdw.conf +++ b/tools/topology/topology2/cavs-sdw.conf @@ -151,6 +151,10 @@ Define { # Bytes control blob of the SDW_SPK_AEC_CAPTURE_PCM AEC from # include/components/webrtc-aec/ SDW_SPK_AEC_PARAMS "default" + # With SDW_SPK_AEC_CAPTURE_PCM, feed the AEC a stereo microphone and + # speaker echo reference instead of mono downmixes. Needs a stereo + # reference capable AEC such as the WebRTC AEC3 backend. + SDW_SPK_AEC_STEREO_REF "false" } # override defaults with platform-specific config diff --git a/tools/topology/topology2/development/tplg-targets.cmake b/tools/topology/topology2/development/tplg-targets.cmake index 5947071982e2..3dfe37fb94fa 100644 --- a/tools/topology/topology2/development/tplg-targets.cmake +++ b/tools/topology/topology2/development/tplg-targets.cmake @@ -515,6 +515,13 @@ SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture- SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ SDW_SPK_ECHO_REF=true,SDW_ECHO_REF_DAI=true,SDW_SPK_AEC_CAPTURE_PCM=true" +# The same with a stereo speaker echo reference, for the WebRTC AEC3 backend +"cavs-sdw\;sof-ptl-rt713-l3-rt1320-l12-stereo-aec\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=2,\ +SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ +SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ +SDW_SPK_ECHO_REF=true,SDW_ECHO_REF_DAI=true,SDW_SPK_AEC_CAPTURE_PCM=true,\ +SDW_SPK_AEC_STEREO_REF=true,SDW_SPK_AEC_PARAMS=wov" + # RT721 eval board with PCH-DMIC, sof_sdw_quirk_table with SOC_SDW_PCH_DMIC # Enable echo reference capture from jack and speaker output # Enable SSP2 BT diff --git a/tools/topology/topology2/platform/intel/sdw-amp-aec.conf b/tools/topology/topology2/platform/intel/sdw-amp-aec.conf index 59055d0bdbd7..c7f4ba362b9e 100644 --- a/tools/topology/topology2/platform/intel/sdw-amp-aec.conf +++ b/tools/topology/topology2/platform/intel/sdw-amp-aec.conf @@ -8,6 +8,17 @@ # src.120.1 (48 -> 16 kHz) -> webrtc-aec.140.1 pin 1 # webrtc-aec.140.1 -> host-copier PCM "Microphone AEC Capture" (16 kHz mono) # +# With SDW_SPK_AEC_STEREO_REF neither the microphone nor the echo reference +# is downmixed by micsel: +# module-copier.41.0 (SDW DMIC, 48 kHz stereo) -> src.141.1 (48 -> 16 kHz +# stereo) -> webrtc-aec.140.1 pin 0 +# siggen.120.1 (48 kHz stereo) -> src.120.1 (48 -> 16 kHz stereo) -> +# webrtc-aec.140.1 pin 1 +# The AEC averages the microphone channels for its mono output and cancels +# the echo with the stereo reference. Both input pins have the same format. +# This needs an AEC that supports a stereo reference, such as the WebRTC +# AEC3 backend. +# # Included from sdw-amp-echo-ref.conf when SDW_SPK_AEC_CAPTURE_PCM is true. The echo # reference DAI (SDW_ECHO_REF_DAI) must be enabled. @@ -39,6 +50,8 @@ Define { SDW_AEC_MIC_PIPELINE_ID 141 } +IncludeByKey.SDW_SPK_AEC_STEREO_REF { +"false" { # Echo reference: siggen -> micsel stereo to mono -> SRC 48 kHz to 16 kHz Object.Pipeline."sdw-aec-capture" [ { @@ -118,7 +131,63 @@ Object.Pipeline."sdw-aec-capture" [ } } ] +} +"true" { +# Echo reference: siggen -> SRC 48 kHz to 16 kHz stereo +Object.Pipeline."sdw-aec-capture" [ + { + index $SDW_SPK_ECHO_REF_PIPELINE_ID + Object.Widget.siggen.1 { + num_input_pins 1 + num_output_pins 1 + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + + Object.Widget.src.1 { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate 48000 + in_channels 2 + in_ch_cfg $CHANNEL_CONFIG_STEREO + in_ch_map $CHANNEL_MAP_STEREO + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate 16000 + out_channels 2 + out_ch_cfg $CHANNEL_CONFIG_STEREO + out_ch_map $CHANNEL_MAP_STEREO + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + } +] +} +} + +IncludeByKey.SDW_SPK_AEC_STEREO_REF { +"false" { # Microphone: micsel stereo to mono -> SRC 48 kHz to 16 kHz Object.Pipeline."sdw-aec-capture" [ { @@ -179,6 +248,41 @@ Object.Pipeline."sdw-aec-capture" [ } } ] +} +"true" { +# Microphone: SRC 48 kHz to 16 kHz stereo +Object.Pipeline."sdw-aec-capture" [ + { + index $SDW_AEC_MIC_PIPELINE_ID + + Object.Widget.src.1 { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate 48000 + in_channels 2 + in_ch_cfg $CHANNEL_CONFIG_STEREO + in_ch_map $CHANNEL_MAP_STEREO + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate 16000 + out_channels 2 + out_ch_cfg $CHANNEL_CONFIG_STEREO + out_ch_map $CHANNEL_MAP_STEREO + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + } +] +} +} # AEC and host capture Object.Pipeline.host-gateway-capture [ @@ -250,6 +354,9 @@ Object.Widget.webrtc-aec.1 { input_pin_binding_name "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" } + # Both input pins are stereo with SDW_SPK_AEC_STEREO_REF + IncludeByKey.SDW_SPK_AEC_STEREO_REF { + "false" { Object.Base.input_audio_format [ { input_pin_index 0 @@ -272,6 +379,32 @@ Object.Widget.webrtc-aec.1 { ibs 640 } ] + } + "true" { + Object.Base.input_audio_format [ + { + input_pin_index 0 + in_rate 16000 + in_channels 2 + in_ch_cfg $CHANNEL_CONFIG_STEREO + in_ch_map $CHANNEL_MAP_STEREO + in_bit_depth 32 + in_valid_bit_depth 32 + ibs 1280 + } + { + input_pin_index 1 + in_rate 16000 + in_channels 2 + in_ch_cfg $CHANNEL_CONFIG_STEREO + in_ch_map $CHANNEL_MAP_STEREO + in_bit_depth 32 + in_valid_bit_depth 32 + ibs 1280 + } + ] + } + } Object.Base.output_audio_format [ { out_rate 16000 @@ -314,6 +447,25 @@ Object.Base.route [ source "module-copier.21.22" sink "siggen.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" } + { + source "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + sink "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" + } + { + source "src.$SDW_AEC_MIC_PIPELINE_ID.1" + sink "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" + } + { + source "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" + sink "host-copier.$SDW_AEC_PCM_ID.capture" + } +] + +# The microphone and the echo reference feed micsel for the mono AEC inputs +# or directly the SRC for the stereo AEC inputs. +IncludeByKey.SDW_SPK_AEC_STEREO_REF { +"false" { +Object.Base.route [ { source "siggen.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" sink "micsel.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" @@ -322,10 +474,6 @@ Object.Base.route [ source "micsel.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" sink "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" } - { - source "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" - sink "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" - } { source "module-copier.41.0" sink "micsel.$SDW_AEC_MIC_PIPELINE_ID.1" @@ -334,12 +482,18 @@ Object.Base.route [ source "micsel.$SDW_AEC_MIC_PIPELINE_ID.1" sink "src.$SDW_AEC_MIC_PIPELINE_ID.1" } +] +} +"true" { +Object.Base.route [ { - source "src.$SDW_AEC_MIC_PIPELINE_ID.1" - sink "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" + source "siggen.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + sink "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" } { - source "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" - sink "host-copier.$SDW_AEC_PCM_ID.capture" + source "module-copier.41.0" + sink "src.$SDW_AEC_MIC_PIPELINE_ID.1" } ] +} +}