diff --git a/app/webrtc_aec3_static_overlay.conf b/app/webrtc_aec3_static_overlay.conf new file mode 100644 index 000000000000..981e5ffac7e2 --- /dev/null +++ b/app/webrtc_aec3_static_overlay.conf @@ -0,0 +1,51 @@ +# 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). +# +# 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 +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 + +# 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_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. +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 diff --git a/src/audio/webrtc_aec/CMakeLists.txt b/src/audio/webrtc_aec/CMakeLists.txt index d1104b89aef3..0d60e6139865 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() @@ -69,12 +73,20 @@ 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 ) + # 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" ) @@ -103,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 @@ -174,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 a1b00b60ce0c..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) @@ -25,46 +29,110 @@ 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. This + is the default of the backend field of the bytes control. + +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 + 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. + + 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 + 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. 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. The bytes control default is this size rounded up to kB. + config WEBRTC_AEC_PERF_TELEMETRY bool "Enable AEC3 cycle profiling telemetry via printk" default y 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)" @@ -75,6 +143,98 @@ 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 "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 20 + depends on WEBRTC_AEC_BACKEND_AEC3 + help + Nominal delay in milliseconds between echo reference playback and + microphone capture for AEC3. With WEBRTC_AEC_AEC3_EXTERNAL_DELAY_EST + AEC3 uses this delay instead of its matched filter estimate. + +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_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 + 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 "AEC microphone delay in ms" + range 0 20 + default 8 + 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. 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" + 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 "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. 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)" range 0 2 @@ -96,15 +256,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 @@ -130,7 +281,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 @@ -150,6 +301,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 76d1b1da7df2..54d721124c7f 100644 --- a/src/audio/webrtc_aec/README.md +++ b/src/audio/webrtc_aec/README.md @@ -14,13 +14,15 @@ 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**: - **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]`). +- **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. --- @@ -73,6 +75,14 @@ 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. 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) ```ini @@ -82,6 +92,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 @@ -90,6 +103,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 @@ -107,21 +125,65 @@ 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` | 20 | int (`0` - `500`) | Nominal echo path / soundcard buffer delay in ms | +| `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 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 | +| `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/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/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/src/audio/webrtc_aec/webrtc_aec-aec.c b/src/audio/webrtc_aec/webrtc_aec-aec.c index f415cb721d55..a021a787bf69 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,49 @@ 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 + int mic_dly_len; /* microphone delay in samples, 0 for none */ + int mic_dly_pos[WEBRTC_AEC_CHANNELS_MAX]; + 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]; @@ -62,16 +101,24 @@ 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 : (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) { @@ -97,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++) { @@ -123,9 +186,13 @@ 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; + 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); + 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: @@ -151,7 +218,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 +236,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 / rd->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 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 / 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->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; + 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 +436,26 @@ 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 (rd->mic_dly_len) { + float *dly = rd->mic_dly + ch * rd->mic_dly_len; + + 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; + } + } ret = WebRtcAec_Process(rd->aec[ch], nearend, 1, out_ptrs, (size_t)frame_samples, (int16_t)rd->delay_ms, 0); @@ -233,6 +464,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 +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 = rd->ref_gain; int i, c, ret; if (frame_samples <= 0 || frame_samples > WEBRTC_AEC_FRAME_SAMPLES_16K || @@ -263,20 +520,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_config.float_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,31 +577,17 @@ 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] * rd->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); } -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); @@ -350,13 +603,16 @@ 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; } -const struct webrtc_aec_backend webrtc_aec_backend = { +const struct webrtc_aec_backend webrtc_aec_backend_float = { .name = "aec_float", + .id = WEBRTC_AEC_ID_FLOAT, .init = webrtc_aec_float_init, .configure = webrtc_aec_float_configure, .set_suppression = webrtc_aec_float_set_suppression, @@ -364,6 +620,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 50f445de3bc9..55bf68b89e06 100644 --- a/src/audio/webrtc_aec/webrtc_aec-aec3.c +++ b/src/audio/webrtc_aec/webrtc_aec-aec3.c @@ -15,22 +15,41 @@ #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; + struct webrtc_aec3_cfg cfg; /* configuration for re-creation in reset */ int num_mic_channels; int num_ref_channels; int suppression; uint32_t aec3_frames; uint64_t aec3_ref_cyc; uint64_t aec3_mic_cyc; - 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]; + 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 *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) @@ -47,6 +66,81 @@ 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 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 + * + * 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) +{ + 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; + + 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; + + webrtc_aec_arena_open(&cd->mem); + rd->aec3 = webrtc_aec3_create_cfg(&rd->cfg); + 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", + arena->overflow, arena->used + arena->overflow); + else + comp_info(mod->dev, "webrtc_aec: AEC3 arena used %zu of %zu bytes", + arena->used, arena_size); + 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) @@ -60,17 +154,19 @@ 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 - .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), }; + int ret; + if (rd->aec3) { webrtc_aec3_free(rd->aec3); rd->aec3 = NULL; @@ -82,20 +178,37 @@ 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->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_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", sample_rate_hz, cfg.num_capture_channels, cfg.num_render_channels); - return -ENOMEM; + return ret; } 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; } @@ -107,6 +220,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; @@ -120,6 +234,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); } @@ -135,6 +251,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, @@ -205,7 +395,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, @@ -228,6 +427,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; } @@ -244,16 +446,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) - webrtc_aec3_init(rd->aec3, cd->proc_rate); - return 0; -} - static int webrtc_aec3_backend_free(struct processing_module *mod) { struct webrtc_aec_comp_data *cd = module_get_private_data(mod); @@ -266,13 +458,17 @@ static int webrtc_aec3_backend_free(struct processing_module *mod) webrtc_aec3_free(rd->aec3); rd->aec3 = NULL; } + webrtc_aec_arena_free(&cd->mem); + if (rd->bufs) + mod_free(mod, rd->bufs); mod_free(mod, rd); cd->backend_data = NULL; return 0; } -const struct webrtc_aec_backend webrtc_aec_backend = { +const struct webrtc_aec_backend webrtc_aec_backend_aec3 = { .name = "aec3", + .id = WEBRTC_AEC_ID_AEC3, .init = webrtc_aec3_backend_init, .configure = webrtc_aec3_backend_configure, .set_suppression = webrtc_aec3_backend_set_suppression, @@ -280,6 +476,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..9f832a8827fe 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); @@ -236,13 +217,13 @@ 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", + .id = WEBRTC_AEC_ID_AECM, .init = webrtc_aec_real_init, .configure = webrtc_aec_real_configure, .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 a838db26f593..9d2f56c7187d 100644 --- a/src/audio/webrtc_aec/webrtc_aec-shims.c +++ b/src/audio/webrtc_aec/webrtc_aec-shims.c @@ -4,48 +4,303 @@ // // 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 #include #include +#include #include #include +#include "webrtc_aec.h" #if !defined(LLEXT_MODULE) #include -static APP_SYSUSER_BSS struct processing_module *active_aec_mod; +#define WEBRTC_AEC_BSS APP_SYSUSER_BSS #else -static struct processing_module *active_aec_mod; +#define WEBRTC_AEC_BSS #endif -void webrtc_aec_set_active_mod(struct processing_module *mod) +LOG_MODULE_DECLARE(webrtc_aec, CONFIG_SOF_LOG_LEVEL); + +/* Memory context entered by webrtc_aec_mem_enter(), NULL if none */ +static WEBRTC_AEC_BSS struct webrtc_aec_mem *webrtc_mem_cur; + +struct webrtc_aec_mem *webrtc_aec_mem_enter(struct webrtc_aec_mem *mem) +{ + struct webrtc_aec_mem *prev = webrtc_mem_cur; + + mem->thread = k_current_get(); + webrtc_mem_cur = mem; + return prev; +} + +void webrtc_aec_mem_exit(struct webrtc_aec_mem *prev) +{ + webrtc_mem_cur = prev; +} + +/** + * \brief Get the memory context entered by the current thread. + * + * \return Memory context, NULL if the current thread has not entered one + */ +static struct webrtc_aec_mem *webrtc_mem_get(void) +{ + 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(struct webrtc_aec_mem *mem, void *p, size_t size) +{ + if (p) + mem->alloc_bytes += size; + else + comp_err(mem->mod->dev, + "webrtc_aec: alloc of %zu bytes failed, %zu bytes allocated before", + size, mem->alloc_bytes); + return p; +} + +#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) +{ + int i; + + for (i = 0; i < WEBRTC_AEC_ARENAS_MAX; i++) { + if (!webrtc_arenas[i]) { + webrtc_arenas[i] = arena; + return 0; + } + } + + return -ENOMEM; +} + +/** + * \brief Remove an arena from the arena list. + * + * \param[in] arena Arena to remove + */ +static void webrtc_arena_unregister(struct webrtc_aec_arena *arena) +{ + int i; + + for (i = 0; i < WEBRTC_AEC_ARENAS_MAX; i++) + if (webrtc_arenas[i] == arena) + webrtc_arenas[i] = NULL; +} + +int webrtc_aec_arena_alloc(struct webrtc_aec_mem *mem, size_t size) +{ + struct webrtc_aec_arena *arena = &mem->arena; + int ret; + + if (arena->base && arena->size == size) + return 0; + + 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; + } + + 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); + } + + return ret; +} + +void webrtc_aec_arena_free(struct webrtc_aec_mem *mem) +{ + struct webrtc_aec_arena *arena = &mem->arena; + + if (!arena->base) + return; + + webrtc_arena_unregister(arena); + mod_free(mem->mod, arena->base); + arena->base = NULL; + arena->size = 0; + arena->open = false; +} + +void webrtc_aec_arena_open(struct webrtc_aec_mem *mem) +{ + mem->arena.used = 0; + mem->arena.overflow = 0; + mem->arena.open = mem->arena.base != NULL; +} + +void webrtc_aec_arena_close(struct webrtc_aec_mem *mem) { - active_aec_mod = mod; + mem->arena.open = false; } -struct processing_module *webrtc_aec_get_active_mod(void) +/** + * \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) { - return active_aec_mod; + struct webrtc_aec_mem *mem = webrtc_mem_get(); + struct webrtc_aec_arena *arena; + size_t start; + + if (!mem || !mem->arena.open) + return NULL; + + 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; + } + + arena->used = start + size; + mem->alloc_bytes += size; + return arena->base + start; } +/** + * \brief Check if memory is in an arena. + * + * \param[in] ptr Memory to check + * \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; + + 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_has(const void *ptr) { return false; } +#endif + void *webrtc_malloc(size_t size) { + struct webrtc_aec_mem *mem; + void *p; + if (size == 0) return NULL; - if (active_aec_mod) - return mod_alloc(active_aec_mod, size); + p = webrtc_arena_get(size); + if (p) + return p; + + mem = webrtc_mem_get(); + if (mem) + return webrtc_alloc_done(mem, mod_alloc(mem->mod, size), size); return rmalloc(SOF_MEM_FLAG_USER, 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) +{ + struct webrtc_aec_mem *mem; + void *p; + + if (size == 0) + size = 1; + + p = webrtc_arena_get(size); + if (p) + 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 (mem) + mem->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) + 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); @@ -53,13 +308,20 @@ 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; if (total == 0) return NULL; - if (active_aec_mod) - return mod_zalloc(active_aec_mod, total); + p = webrtc_arena_get(total); + if (p) + return memset(p, 0, 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); } diff --git a/src/audio/webrtc_aec/webrtc_aec-stub.c b/src/audio/webrtc_aec/webrtc_aec-stub.c index 26a765137af1..5bc546ef2f97 100644 --- a/src/audio/webrtc_aec/webrtc_aec-stub.c +++ b/src/audio/webrtc_aec/webrtc_aec-stub.c @@ -52,25 +52,19 @@ 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; return 0; } -const struct webrtc_aec_backend webrtc_aec_backend = { +const struct webrtc_aec_backend webrtc_aec_backend_stub = { .name = "stub", + .id = WEBRTC_AEC_ID_STUB, .init = webrtc_aec_stub_init, .configure = webrtc_aec_stub_configure, .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 f0eec961fa3a..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" @@ -52,6 +53,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); @@ -71,7 +77,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); @@ -117,6 +123,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 *const *dst, + 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. @@ -126,7 +194,7 @@ static void src_to_s16(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); @@ -216,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 * ---------------------------------------------------------------- */ @@ -225,62 +518,182 @@ __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->backend = &webrtc_aec_backend; + cd->mem.mod = mod; 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); + webrtc_aec_config_defaults(&cd->config); /* Two input pins: mic + echo reference. */ 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 Select the backend for the negotiated formats. + * + * 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 + */ +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; +#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) + 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. + * + * \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 && 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); + 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); } } @@ -290,11 +703,15 @@ __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); + 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)", num_of_sources, num_of_sinks); @@ -305,7 +722,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 +745,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) { @@ -363,7 +794,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) || @@ -388,39 +818,67 @@ __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); + cd->backend = webrtc_aec_select_backend(cd); + 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); + + ret = webrtc_aec_bufs_alloc(mod); + if (ret) { + cd->backend = NULL; + 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) { 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); - return ret; + goto err; } } 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, @@ -451,7 +909,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; @@ -494,11 +952,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]; } @@ -506,11 +964,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]; } @@ -524,7 +982,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. */ @@ -548,7 +1007,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)); } } @@ -557,12 +1017,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; } @@ -619,7 +1079,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); @@ -633,7 +1093,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. */ @@ -643,8 +1103,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 @@ -692,7 +1157,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); @@ -728,23 +1193,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; } @@ -752,17 +1208,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; } @@ -777,12 +1230,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; @@ -797,7 +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; - webrtc_aec_set_active_mod(mod); + 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; @@ -827,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.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 bde87c5edf4f..8a56f2e0e5a5 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) @@ -20,6 +21,7 @@ #define __SOF_AUDIO_WEBRTC_AEC_H__ #include +#include #include #include @@ -32,7 +34,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 @@ -51,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, @@ -70,17 +125,75 @@ 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 CONFIG_WEBRTC_AEC_BACKEND_AEC3 +#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; + enum webrtc_aec_backend_id id; - /* 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 +243,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); }; @@ -147,8 +260,10 @@ 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) */ + 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 */ /* Source routing (resolved in prepare / process). */ int mic_src; /* index into sources[] for microphone */ @@ -157,7 +272,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 */ @@ -175,24 +291,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; @@ -201,15 +320,70 @@ 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) -void webrtc_aec_set_active_mod(struct processing_module *mod); -struct processing_module *webrtc_aec_get_active_mod(void); +/** + * \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 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 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] 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 or + * WEBRTC_AEC_ARENAS_MAX arenas exist already + */ +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] mem Memory context of the instance + */ +void webrtc_aec_arena_free(struct webrtc_aec_mem *mem); + +/** + * \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(struct webrtc_aec_mem *mem); + +/** + * \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/src/audio/webrtc_aec/webrtc_aec3_shims.cpp b/src/audio/webrtc_aec/webrtc_aec3_shims.cpp index 3243ccdac62f..90f391a20ee2 100644 --- a/src/audio/webrtc_aec/webrtc_aec3_shims.cpp +++ b/src/audio/webrtc_aec/webrtc_aec3_shims.cpp @@ -16,64 +16,114 @@ 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) +#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. 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_cxx_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_cxx_malloc(size); +} +void *__wrap__ZnajRKSt9nothrow_t(std::size_t size, const std::nothrow_t &) +{ + return webrtc_cxx_malloc(size); +} +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_cxx_free(ptr); +} + +void operator delete[](void* ptr, const std::nothrow_t&) noexcept { + 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 */ 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 { @@ -100,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*); @@ -112,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 { diff --git a/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp b/src/audio/webrtc_aec/webrtc_aec3_wrapper.cpp index ea26158c4bd8..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; @@ -62,6 +91,10 @@ 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->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, @@ -70,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) { @@ -87,11 +125,22 @@ 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); 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" { @@ -165,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); 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 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++) { 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..da26a52747a4 100644 --- a/tools/topology/topology2/cavs-sdw.conf +++ b/tools/topology/topology2/cavs-sdw.conf @@ -148,6 +148,13 @@ 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" + # 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/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..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 [ @@ -233,6 +337,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 { @@ -242,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 @@ -264,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 @@ -306,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" @@ -314,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" @@ -326,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" } ] +} +} 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