diff --git a/app/ultrasound.conf b/app/ultrasound.conf new file mode 100644 index 000000000000..6aa6a2b15bf6 --- /dev/null +++ b/app/ultrasound.conf @@ -0,0 +1,2 @@ +CONFIG_COMP_ULTRASOUND_TX=m +CONFIG_COMP_ULTRASOUND_RX=m diff --git a/src/audio/CMakeLists.txt b/src/audio/CMakeLists.txt index acaa0c2f708d..0b5401bbfe5d 100644 --- a/src/audio/CMakeLists.txt +++ b/src/audio/CMakeLists.txt @@ -182,3 +182,7 @@ endif() if(CONFIG_COMP_BT_CODEC) add_subdirectory(bt_codec) endif() + +if(CONFIG_COMP_ULTRASOUND_TX OR CONFIG_COMP_ULTRASOUND_RX) + add_subdirectory(ultrasound) +endif() diff --git a/src/audio/Kconfig b/src/audio/Kconfig index 2e567c1f1b04..d0152a5a8d2f 100644 --- a/src/audio/Kconfig +++ b/src/audio/Kconfig @@ -453,5 +453,6 @@ config DAI_VERBOSE_GLITCH_WARNINGS DAI DMA operation and issues with low-latency scheduling. rsource "bt_codec/Kconfig" +rsource "ultrasound/Kconfig" endmenu diff --git a/src/audio/ultrasound/CMakeLists.txt b/src/audio/ultrasound/CMakeLists.txt new file mode 100644 index 000000000000..6266f4ee7b4e --- /dev/null +++ b/src/audio/ultrasound/CMakeLists.txt @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: BSD-3-Clause + +if(CONFIG_COMP_ULTRASOUND_TX STREQUAL "m" AND DEFINED CONFIG_LLEXT) + add_subdirectory(llext_tx ${PROJECT_BINARY_DIR}/ultrasound_tx_llext) + add_dependencies(app ultrasound_tx) +elseif(CONFIG_COMP_ULTRASOUND_TX) + add_local_sources(sof ultrasound_tx.c) +endif() + +if(CONFIG_COMP_ULTRASOUND_RX STREQUAL "m" AND DEFINED CONFIG_LLEXT) + add_subdirectory(llext_rx ${PROJECT_BINARY_DIR}/ultrasound_rx_llext) + add_dependencies(app ultrasound_rx) +elseif(CONFIG_COMP_ULTRASOUND_RX) + add_local_sources(sof ultrasound_rx.c) +endif() diff --git a/src/audio/ultrasound/Kconfig b/src/audio/ultrasound/Kconfig new file mode 100644 index 000000000000..b3283c7289be --- /dev/null +++ b/src/audio/ultrasound/Kconfig @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: BSD-3-Clause + +config COMP_ULTRASOUND_TX + tristate "Ultrasonic carrier generator (TX) component" + default m if LIBRARY_DEFAULT_MODULAR + default y + help + Select for ultrasonic carrier generator component. Injects an inaudible + ultrasonic tone (>= 19 kHz) with smooth ramping onto an audio stream + for acoustic gesture and presence sensing. + +config COMP_ULTRASOUND_RX + tristate "Ultrasonic Doppler gesture and presence detector (RX) component" + default m if LIBRARY_DEFAULT_MODULAR + default y + help + Select for ultrasonic Doppler gesture and presence detector component. + Demodulates ultrasonic carrier sidebands, classifies push/pull/tap/swipe + gestures and user presence, and emits IPC4 module notifications. diff --git a/src/audio/ultrasound/llext_rx/CMakeLists.txt b/src/audio/ultrasound/llext_rx/CMakeLists.txt new file mode 100644 index 000000000000..d4ddcc720c52 --- /dev/null +++ b/src/audio/ultrasound/llext_rx/CMakeLists.txt @@ -0,0 +1,6 @@ +# Copyright (c) 2026 Intel Corporation. +# SPDX-License-Identifier: Apache-2.0 + +sof_llext_build("ultrasound_rx" + SOURCES ../ultrasound_rx.c +) diff --git a/src/audio/ultrasound/llext_rx/llext.toml.h b/src/audio/ultrasound/llext_rx/llext.toml.h new file mode 100644 index 000000000000..a693c1929f45 --- /dev/null +++ b/src/audio/ultrasound/llext_rx/llext.toml.h @@ -0,0 +1,6 @@ +#include +#define LOAD_TYPE "2" +#include "../ultrasound_rx.toml" + +[module] +count = __COUNTER__ diff --git a/src/audio/ultrasound/llext_tx/CMakeLists.txt b/src/audio/ultrasound/llext_tx/CMakeLists.txt new file mode 100644 index 000000000000..595b12fdd537 --- /dev/null +++ b/src/audio/ultrasound/llext_tx/CMakeLists.txt @@ -0,0 +1,6 @@ +# Copyright (c) 2026 Intel Corporation. +# SPDX-License-Identifier: Apache-2.0 + +sof_llext_build("ultrasound_tx" + SOURCES ../ultrasound_tx.c +) diff --git a/src/audio/ultrasound/llext_tx/llext.toml.h b/src/audio/ultrasound/llext_tx/llext.toml.h new file mode 100644 index 000000000000..0d4601e072fd --- /dev/null +++ b/src/audio/ultrasound/llext_tx/llext.toml.h @@ -0,0 +1,6 @@ +#include +#define LOAD_TYPE "2" +#include "../ultrasound_tx.toml" + +[module] +count = __COUNTER__ diff --git a/src/audio/ultrasound/ultrasound_dsp.h b/src/audio/ultrasound/ultrasound_dsp.h new file mode 100644 index 000000000000..bf40408f78d1 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_dsp.h @@ -0,0 +1,201 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Copyright(c) 2026 Intel Corporation. + * + * Fixed-point DSP primitives for SOF ultrasonic gesture/presence sensing. + */ + +#ifndef __SOF_AUDIO_ULTRASOUND_DSP_H__ +#define __SOF_AUDIO_ULTRASOUND_DSP_H__ + +#include + +#define US_FFT_SIZE 64 +#define US_FFT_LOG2 6 +#define US_BASEBAND_RATE_HZ 1000 +#define US_SPEED_OF_SOUND_M_S 343 + +/* 257-entry full-wave sine LUT in Q1.15 */ +static const int16_t us_sin_lut[257] = { + 0, 804, 1608, 2410, 3212, 4011, 4808, 5602, + 6393, 7179, 7962, 8739, 9512, 10278, 11039, 11793, + 12539, 13279, 14010, 14732, 15446, 16151, 16846, 17530, + 18204, 18868, 19519, 20159, 20787, 21403, 22005, 22594, + 23170, 23731, 24279, 24811, 25329, 25832, 26319, 26790, + 27245, 27683, 28105, 28510, 28898, 29268, 29621, 29956, + 30273, 30571, 30852, 31113, 31356, 31580, 31785, 31971, + 32137, 32285, 32412, 32521, 32609, 32678, 32728, 32757, + 32767, 32757, 32728, 32678, 32609, 32521, 32412, 32285, + 32137, 31971, 31785, 31580, 31356, 31113, 30852, 30571, + 30273, 29956, 29621, 29268, 28898, 28510, 28105, 27683, + 27245, 26790, 26319, 25832, 25329, 24811, 24279, 23731, + 23170, 22594, 22005, 21403, 20787, 20159, 19519, 18868, + 18204, 17530, 16846, 16151, 15446, 14732, 14010, 13279, + 12539, 11793, 11039, 10278, 9512, 8739, 7962, 7179, + 6393, 5602, 4808, 4011, 3212, 2410, 1608, 804, + 0, -804, -1608, -2410, -3212, -4011, -4808, -5602, + -6393, -7179, -7962, -8739, -9512, -10278, -11039, -11793, + -12539, -13279, -14010, -14732, -15446, -16151, -16846, -17530, + -18204, -18868, -19519, -20159, -20787, -21403, -22005, -22594, + -23170, -23731, -24279, -24811, -25329, -25832, -26319, -26790, + -27245, -27683, -28105, -28510, -28898, -29268, -29621, -29956, + -30273, -30571, -30852, -31113, -31356, -31580, -31785, -31971, + -32137, -32285, -32412, -32521, -32609, -32678, -32728, -32757, + -32767, -32757, -32728, -32678, -32609, -32521, -32412, -32285, + -32137, -31971, -31785, -31580, -31356, -31113, -30852, -30571, + -30273, -29956, -29621, -29268, -28898, -28510, -28105, -27683, + -27245, -26790, -26319, -25832, -25329, -24811, -24279, -23731, + -23170, -22594, -22005, -21403, -20787, -20159, -19519, -18868, + -18204, -17530, -16846, -16151, -15446, -14732, -14010, -13279, + -12539, -11793, -11039, -10278, -9512, -8739, -7962, -7179, + -6393, -5602, -4808, -4011, -3212, -2410, -1608, -804, + 0, +}; + +/* 64-point Hann window in Q1.15 */ +static const int16_t us_hann64[US_FFT_SIZE] = { + 0, 81, 325, 728, 1286, 1995, 2847, 3833, + 4944, 6169, 7495, 8909, 10398, 11946, 13539, 15159, + 16792, 18421, 20029, 21601, 23122, 24575, 25947, 27224, + 28393, 29443, 30363, 31145, 31779, 32260, 32584, 32747, + 32747, 32584, 32260, 31779, 31145, 30363, 29443, 28393, + 27224, 25947, 24575, 23122, 21601, 20029, 18421, 16792, + 15159, 13539, 11946, 10398, 8909, 7495, 6169, 4944, + 3833, 2847, 1995, 1286, 728, 325, 81, 0, +}; + +/* Linearly interpolated Q1.15 sine from 32-bit phase [0, 2*pi) */ +static inline int32_t us_sin_q15(uint32_t phase) +{ + uint32_t idx = phase >> 24; + int32_t frac = (int32_t)((phase >> 9) & 0x7FFFU); + int32_t y0 = us_sin_lut[idx]; + int32_t y1 = us_sin_lut[idx + 1]; + + return y0 + (((y1 - y0) * frac) >> 15); +} + +static inline int32_t us_cos_q15(uint32_t phase) +{ + return us_sin_q15(phase + 0x40000000U); +} + +static inline uint32_t us_phase_inc(uint32_t freq_hz, uint32_t sample_rate) +{ + if (!sample_rate) + return 0; + + return (uint32_t)((((uint64_t)freq_hz << 32) + (sample_rate >> 1)) / sample_rate); +} + +/* Exact 64-bit integer square root */ +static inline uint32_t us_isqrt64(uint64_t n) +{ + uint64_t x = n; + uint64_t y; + + if (n == 0) + return 0; + + y = (x + 1) >> 1; + while (y < x) { + x = y; + y = (x + n / x) >> 1; + } + + return (uint32_t)x; +} + +/* Q24.8 approximation of log2(x) for x >= 1 */ +static inline int32_t us_log2_q8(uint32_t x) +{ + int32_t msb; + uint32_t frac; + + if (x <= 1) + return 0; + + msb = 31 - __builtin_clz(x); + if (msb >= 8) + frac = (x >> (msb - 8)) & 0xFFU; + else + frac = (x << (8 - msb)) & 0xFFU; + + /* Small quadratic concavity correction for log2(1+f): +f*(1-f)*0.34 */ + frac += ((frac * (256U - frac)) * 87U) >> 16; + + return (msb << 8) + (int32_t)frac; +} + +/* 20 * log10(peak / floor) in Q24.8 dB: 20/ln(10)*ln(2) = 6.0206 = 1541 / 256 */ +static inline uint32_t us_snr_db_q8(uint32_t peak, uint32_t noise_floor) +{ + int32_t diff_log2; + + if (noise_floor < 1) + noise_floor = 1; + if (peak <= noise_floor) + return 0; + + diff_log2 = us_log2_q8(peak) - us_log2_q8(noise_floor); + if (diff_log2 <= 0) + return 0; + + return (uint32_t)(((int64_t)diff_log2 * 1541LL) >> 8); +} + +/* In-place 64-point radix-2 forward complex FFT (unscaled, int32_t safe up to |x|<=2^22) */ +static inline void us_fft64(int32_t *re, int32_t *im) +{ + int i, j, len, half; + + /* Bit-reversal permutation */ + for (i = 1, j = 0; i < US_FFT_SIZE; i++) { + int bit = US_FFT_SIZE >> 1; + + for (; j & bit; bit >>= 1) + j ^= bit; + j ^= bit; + + if (i < j) { + int32_t tr = re[i]; + int32_t ti = im[i]; + + re[i] = re[j]; + im[i] = im[j]; + re[j] = tr; + im[j] = ti; + } + } + + /* Cooley-Tukey stages: W_len^k = exp(-j * 2*pi * k / len) */ + for (len = 2; len <= US_FFT_SIZE; len <<= 1) { + uint32_t step = 0x100000000ULL / (uint32_t)len; + + half = len >> 1; + for (i = 0; i < US_FFT_SIZE; i += len) { + uint32_t angle = 0; + + for (j = 0; j < half; j++) { + int32_t wr = us_cos_q15(angle); + int32_t wi = -us_sin_q15(angle); + int idx1 = i + j; + int idx2 = idx1 + half; + int32_t tr = (int32_t)(((int64_t)re[idx2] * wr - + (int64_t)im[idx2] * wi) >> 15); + int32_t ti = (int32_t)(((int64_t)re[idx2] * wi + + (int64_t)im[idx2] * wr) >> 15); + + re[idx2] = re[idx1] - tr; + im[idx2] = im[idx1] - ti; + re[idx1] = re[idx1] + tr; + im[idx1] = im[idx1] + ti; + + angle += step; + } + } + } +} + +#endif /* __SOF_AUDIO_ULTRASOUND_DSP_H__ */ + diff --git a/src/audio/ultrasound/ultrasound_rx.c b/src/audio/ultrasound/ultrasound_rx.c new file mode 100644 index 000000000000..5e3fd647587f --- /dev/null +++ b/src/audio/ultrasound/ultrasound_rx.c @@ -0,0 +1,965 @@ +// SPDX-License-Identifier: BSD-3-Clause +// +// Copyright(c) 2026 Intel Corporation. +// +// Ultrasonic Doppler gesture & presence detector module (RX) for SOF. +// Supports both hostless terminal sink (1-in/0-out) and passthrough (1-in/1-out) +// modes with full 24-bit Q23 dynamic range for Intel PDM DMICs and Approach B +// in-DSP presence feedback to ultrasound_tx. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ultrasound_dsp.h" +#include "ultrasound_rx.h" + +SOF_DEFINE_REG_UUID(ultrasound_rx); + +LOG_MODULE_REGISTER(ultrasound_rx, CONFIG_SOF_LOG_LEVEL); + +static void ultrasound_rx_log_diag(struct comp_dev *dev, struct ultrasound_rx_data *cd, + const char *tag) +{ + uint32_t dc0, dc1; + + dc0 = us_isqrt64((uint64_t)((cd->ch[0].dc_i_q8 >> 8) * (cd->ch[0].dc_i_q8 >> 8) + + (cd->ch[0].dc_q_q8 >> 8) * (cd->ch[0].dc_q_q8 >> 8))); + dc1 = (cd->active_channels > 1) ? + us_isqrt64((uint64_t)((cd->ch[1].dc_i_q8 >> 8) * (cd->ch[1].dc_i_q8 >> 8) + + (cd->ch[1].dc_q_q8 >> 8) * (cd->ch[1].dc_q_q8 >> 8))) : 0; + + comp_info(dev, + "ultrasound_rx [%s]: carrier_dc=[%u,%u] nf=[%u,%u] present=%d seq=%u frames=%u", + tag, dc0, dc1, cd->ch[0].noise_floor, + cd->active_channels > 1 ? cd->ch[1].noise_floor : 0, + cd->present, cd->event_seq, (uint32_t)cd->total_frames); +} + +static void ultrasound_rx_reset_state(struct ultrasound_rx_data *cd) +{ + uint32_t ch; + + memset(cd->ch, 0, sizeof(cd->ch)); + cd->decim_count = 0; + cd->hop_count = 0; + cd->total_frames = 0; + cd->bb_ms = 0; + cd->warmup_logged = false; + cd->present = false; + cd->presence_consec = 0; + cd->last_activity_ms = 0; + cd->cooldown_until_ms = 0; + cd->stroke_dir = 0; + cd->stroke_hops = 0; + memset(&cd->pending_push, 0, sizeof(cd->pending_push)); + memset(&cd->pending_pull, 0, sizeof(cd->pending_pull)); + +#if CONFIG_IPC_MAJOR_4 + ultrasound_set_presence(false); +#endif + + if (cd->sample_rate >= US_BASEBAND_RATE_HZ) { + cd->decim_factor = cd->sample_rate / US_BASEBAND_RATE_HZ; + for (ch = 0; ch < SOF_ULTRASOUND_MAX_CHANNELS; ch++) + cd->ch[ch].phase_inc = us_phase_inc(cd->cfg.carrier_hz[ch], + cd->sample_rate); + } +} + +static void ultrasound_rx_emit_event(struct processing_module *mod, + struct ultrasound_rx_data *cd, + enum sof_ultrasound_event_type evt_type, + int32_t doppler_mhz, + uint32_t snr_db_q8, + uint32_t carrier_hz) +{ + struct sof_ultrasound_event ev; + uint32_t subtype; + uint32_t event_id; + uint32_t conf; + int32_t vel_mm_s = 0; + + if (carrier_hz) + vel_mm_s = (int32_t)(((int64_t)doppler_mhz * US_SPEED_OF_SOUND_M_S) / + (2LL * (int64_t)carrier_hz)); + + /* Map SNR margin above threshold (0..20 dB) into 500..1000 confidence */ + if (snr_db_q8 >= cd->cfg.snr_threshold_q8) { + uint32_t margin = snr_db_q8 - cd->cfg.snr_threshold_q8; + + conf = 500U + MIN(500U, (margin * 500U) / (20U << 8)); + } else { + conf = (snr_db_q8 * 500U) / MAX(1U, cd->cfg.snr_threshold_q8); + } + + ev.version = SOF_ULTRASOUND_ABI_VERSION; + ev.event_type = evt_type; + ev.doppler_mhz = doppler_mhz; + ev.velocity_mm_s = vel_mm_s; + ev.confidence = conf; + ev.snr_db_q8 = snr_db_q8; + ev.carrier_hz = carrier_hz; + ev.seq = ++cd->event_seq; + ev.dsp_timestamp_us = cd->sample_rate ? + (cd->total_frames * 1000000ULL) / cd->sample_rate : 0; + + subtype = (evt_type == SOF_US_EVT_PRESENCE_DETECTED || + evt_type == SOF_US_EVT_PRESENCE_LOST) ? + SOF_US_EVENT_SUBTYPE_PRESENCE : SOF_US_EVENT_SUBTYPE_GESTURE; + + comp_info(mod->dev, + "ultrasound evt=%u seq=%u doppler=%d mHz vel=%d mm/s snr=%u.%02u dB conf=%u", + evt_type, ev.seq, doppler_mhz, vel_mm_s, + snr_db_q8 >> 8, ((snr_db_q8 & 0xFFU) * 100U) >> 8, conf); + +#if CONFIG_IPC_MAJOR_4 + event_id = SOF_IPC4_NOTIFY_MODULE_EVENTID_GESTURE_MAGIC_VAL | subtype; + if (!send_module_notif_msg(cd->module_id, cd->instance_id, event_id, + &ev, sizeof(ev))) + comp_warn(mod->dev, "ultrasound_rx: failed to send IPC4 notification"); +#else + (void)event_id; + (void)subtype; +#endif +} + +static void ultrasound_rx_analyze_channel(struct ultrasound_rx_data *cd, uint32_t ch_idx) +{ + struct us_rx_channel *c = &cd->ch[ch_idx]; + int32_t re[US_FFT_SIZE]; + int32_t im[US_FFT_SIZE]; + uint32_t mag[US_FFT_SIZE]; + uint64_t nf_pos_sum = 0, nf_neg_sum = 0; + uint32_t nf_pos_cnt = 0, nf_neg_cnt = 0; + uint32_t cur_nf_pos, cur_nf_neg, eff_nf_pos, eff_nf_neg; + uint32_t pos_mag = 0, neg_mag = 0; + uint32_t pos_snr = 0, neg_snr = 0; + int pos_bin = 0, neg_bin = 0; + int k; + + /* Window oldest-to-newest 64 baseband samples with Hann window */ + for (k = 0; k < US_FFT_SIZE; k++) { + uint32_t idx = (c->ring_pos + (uint32_t)k) & (US_FFT_SIZE - 1); + int32_t w = us_hann64[k]; + + re[k] = (int32_t)(((int64_t)c->ring_i[idx] * w) >> 15); + im[k] = (int32_t)(((int64_t)c->ring_q[idx] * w) >> 15); + } + + us_fft64(re, im); + + for (k = 0; k < US_FFT_SIZE; k++) { + uint64_t m2 = (uint64_t)((int64_t)re[k] * re[k] + (int64_t)im[k] * im[k]); + + mag[k] = us_isqrt64(m2); + } + + /* Positive Doppler band: bins 2..16 (+31.25 Hz .. +250 Hz) */ + for (k = 2; k <= 16; k++) { + if (mag[k] > pos_mag) { + pos_mag = mag[k]; + pos_bin = k; + } + } + + /* Negative Doppler band: bins 48..62 (-250 Hz .. -31.25 Hz) */ + for (k = 48; k <= 62; k++) { + if (mag[k] > neg_mag) { + neg_mag = mag[k]; + neg_bin = k; + } + } + + /* + * Per-sideband local in-band noise floor (excluding +/-2 bins around each peak). + * Measuring noise right inside each Doppler band cancels both 2nd-order CIC + * passband droop (-5 dB at outer bins) and Intel PDM DMIC passband rolloff + * tilt above 20 kHz, preventing colored-noise PULL bias and false SNR inflation. + */ + for (k = 2; k <= 19; k++) { + if (pos_bin > 0 && k >= pos_bin - 2 && k <= pos_bin + 2) + continue; + nf_pos_sum += mag[k]; + nf_pos_cnt++; + } + for (k = 45; k <= 62; k++) { + if (neg_bin > 0 && k >= neg_bin - 2 && k <= neg_bin + 2) + continue; + nf_neg_sum += mag[k]; + nf_neg_cnt++; + } + + cur_nf_pos = nf_pos_cnt ? (uint32_t)(nf_pos_sum / nf_pos_cnt) : 1U; + cur_nf_neg = nf_neg_cnt ? (uint32_t)(nf_neg_sum / nf_neg_cnt) : 1U; + + if (c->noise_floor_pos == 0 || cd->bb_ms < US_RX_WARMUP_MS) { + c->noise_floor_pos = c->noise_floor_pos ? + ((3U * c->noise_floor_pos) + cur_nf_pos) >> 2 : cur_nf_pos; + c->noise_floor_neg = c->noise_floor_neg ? + ((3U * c->noise_floor_neg) + cur_nf_neg) >> 2 : cur_nf_neg; + } else { + c->noise_floor_pos = ((15U * c->noise_floor_pos) + cur_nf_pos) >> 4; + c->noise_floor_neg = ((15U * c->noise_floor_neg) + cur_nf_neg) >> 4; + } + c->noise_floor = (c->noise_floor_pos + c->noise_floor_neg) >> 1; + + /* Instantaneous floor guard rejects sudden broadband impulses & DMIC ramp jumps */ + eff_nf_pos = MAX(MAX(c->noise_floor_pos, cur_nf_pos), 1U); + eff_nf_neg = MAX(MAX(c->noise_floor_neg, cur_nf_neg), 1U); + + if (pos_bin > 0) + pos_snr = us_snr_db_q8(pos_mag, eff_nf_pos); + if (neg_bin > 0) + neg_snr = us_snr_db_q8(neg_mag, eff_nf_neg); + + c->hop_dir = 0; + c->hop_doppler_mhz = 0; + c->hop_snr_db_q8 = 0; + c->hop_peak_mag = 0; + + /* + * Require >= 3.0 dB normalized sideband SNR asymmetry (rejects symmetric broadband + * impulses/claps, Approach B TX burst AM envelopes, and DMIC passband tilt). + */ + if (pos_snr >= neg_snr && pos_bin > 0) { + if (pos_mag >= cd->cfg.min_peak_level && + pos_snr >= cd->cfg.snr_threshold_q8 && + pos_snr >= neg_snr + (3U << 8)) { + int64_t m_prev = mag[(pos_bin - 1) & (US_FFT_SIZE - 1)]; + int64_t m_cur = mag[pos_bin]; + int64_t m_next = mag[(pos_bin + 1) & (US_FFT_SIZE - 1)]; + int64_t denom = 2LL * (m_prev - 2LL * m_cur + m_next); + int64_t delta_q10 = 0; + + if (denom < 0) { + delta_q10 = ((m_prev - m_next) << 10) / denom; + if (delta_q10 > 512) + delta_q10 = 512; + else if (delta_q10 < -512) + delta_q10 = -512; + } + + c->hop_dir = 1; + c->hop_snr_db_q8 = pos_snr; + c->hop_peak_mag = pos_mag; + c->hop_doppler_mhz = (int32_t)((((int64_t)pos_bin << 10) + delta_q10) * + US_BASEBAND_RATE_HZ * 1000LL / + (US_FFT_SIZE * 1024LL)); + } + } else if (neg_snr > pos_snr && neg_bin > 0) { + if (neg_mag >= cd->cfg.min_peak_level && + neg_snr >= cd->cfg.snr_threshold_q8 && + neg_snr >= pos_snr + (3U << 8)) { + int64_t m_prev = mag[(neg_bin - 1) & (US_FFT_SIZE - 1)]; + int64_t m_cur = mag[neg_bin]; + int64_t m_next = mag[(neg_bin + 1) & (US_FFT_SIZE - 1)]; + int64_t denom = 2LL * (m_prev - 2LL * m_cur + m_next); + int64_t delta_q10 = 0; + int64_t signed_bin = (int64_t)neg_bin - US_FFT_SIZE; + + if (denom < 0) { + delta_q10 = ((m_prev - m_next) << 10) / denom; + if (delta_q10 > 512) + delta_q10 = 512; + else if (delta_q10 < -512) + delta_q10 = -512; + } + + c->hop_dir = -1; + c->hop_snr_db_q8 = neg_snr; + c->hop_peak_mag = neg_mag; + c->hop_doppler_mhz = (int32_t)(((signed_bin << 10) + delta_q10) * + US_BASEBAND_RATE_HZ * 1000LL / + (US_FFT_SIZE * 1024LL)); + } + } +} + +static void ultrasound_rx_clear_gestures(struct ultrasound_rx_data *cd) +{ + uint32_t ch; + + cd->stroke_dir = 0; + cd->stroke_hops = 0; + cd->pending_push.active = false; + cd->pending_pull.active = false; + + for (ch = 0; ch < SOF_ULTRASOUND_MAX_CHANNELS; ch++) { + cd->ch[ch].triggered = false; + cd->ch[ch].active_hops = 0; + } +} + +static void ultrasound_rx_run_hop(struct processing_module *mod, struct ultrasound_rx_data *cd) +{ + uint64_t now_ms = cd->bb_ms; + int8_t best_dir = 0; + int32_t best_doppler = 0; + uint32_t best_snr = 0; + uint32_t best_carrier = cd->cfg.carrier_hz[0]; + bool any_activity = false; + bool swipe_pending = false; + uint32_t ch; + + for (ch = 0; ch < cd->active_channels; ch++) { + ultrasound_rx_analyze_channel(cd, ch); + if (cd->ch[ch].hop_dir != 0) { + any_activity = true; + if (cd->ch[ch].hop_snr_db_q8 > best_snr) { + best_snr = cd->ch[ch].hop_snr_db_q8; + best_dir = cd->ch[ch].hop_dir; + best_doppler = cd->ch[ch].hop_doppler_mhz; + best_carrier = cd->cfg.carrier_hz[ch]; + } + } + } + + /* Allow CIC + DC blocker + noise floor to settle at stream startup */ + if (now_ms < US_RX_WARMUP_MS) + return; + + if (!cd->warmup_logged) { + cd->warmup_logged = true; + ultrasound_rx_log_diag(mod->dev, cd, "warmup"); + } + + /* 1. Presence tracking + Approach B TX auto-boost feedback (require coherent hops) */ + if (any_activity) { + int32_t df = best_doppler - cd->prev_best_doppler_mhz; + + if (df < 0) + df = -df; + if (cd->presence_consec == 0 || df <= US_RX_MAX_HOP_FREQ_JUMP_MHZ) + cd->presence_consec++; + else + cd->presence_consec = 1; + cd->prev_best_doppler_mhz = best_doppler; + + if (cd->presence_consec >= 2) + cd->last_activity_ms = now_ms; + + if (!cd->present && cd->presence_consec >= 3) { + cd->present = true; +#if CONFIG_IPC_MAJOR_4 + ultrasound_set_presence(true); +#endif + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PRESENCE_DETECTED, + best_doppler, best_snr, best_carrier); + } + } else { + cd->presence_consec = 0; + if (cd->present && (now_ms - cd->last_activity_ms) >= cd->cfg.presence_timeout_ms) { + cd->present = false; +#if CONFIG_IPC_MAJOR_4 + ultrasound_set_presence(false); +#endif + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PRESENCE_LOST, + 0, 0, cd->cfg.carrier_hz[0]); + } + } + + /* 2. Cooldown guard between gesture events */ + if (now_ms < cd->cooldown_until_ms) { + ultrasound_rx_clear_gestures(cd); + return; + } + + /* 3. Stereo inter-channel swipe detection (with hop-to-hop Doppler coherence) */ + if (cd->active_channels == 2) { + for (ch = 0; ch < 2; ch++) { + struct us_rx_channel *c = &cd->ch[ch]; + + if (c->hop_dir != 0) { + int32_t cdf = c->hop_doppler_mhz - c->prev_hop_doppler_mhz; + + if (cdf < 0) + cdf = -cdf; + if (c->active_hops > 0 && c->hop_dir == c->prev_hop_dir && + cdf <= US_RX_MAX_HOP_FREQ_JUMP_MHZ) + c->active_hops++; + else + c->active_hops = 1; + c->prev_hop_doppler_mhz = c->hop_doppler_mhz; + c->prev_hop_dir = c->hop_dir; + c->quiet_hops = 0; + if (!c->triggered && c->active_hops >= 3) { + c->triggered = true; + c->onset_ms = now_ms; + c->onset_doppler_mhz = c->hop_doppler_mhz; + c->onset_snr_db_q8 = c->hop_snr_db_q8; + } + } else { + c->active_hops = 0; + c->prev_hop_dir = 0; + c->quiet_hops++; + } + } + + if (cd->ch[0].triggered && cd->ch[1].triggered) { + int64_t lag = (int64_t)cd->ch[1].onset_ms - (int64_t)cd->ch[0].onset_ms; + int32_t avg_doppler = (cd->ch[0].onset_doppler_mhz + + cd->ch[1].onset_doppler_mhz) / 2; + uint32_t max_snr = MAX(cd->ch[0].onset_snr_db_q8, + cd->ch[1].onset_snr_db_q8); + + if (lag >= (int64_t)cd->cfg.swipe_min_lag_ms && + lag <= (int64_t)cd->cfg.swipe_max_lag_ms) { + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_SWIPE_RIGHT, + avg_doppler, max_snr, + cd->cfg.carrier_hz[0]); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + return; + } + if (-lag >= (int64_t)cd->cfg.swipe_min_lag_ms && + -lag <= (int64_t)cd->cfg.swipe_max_lag_ms) { + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_SWIPE_LEFT, + avg_doppler, max_snr, + cd->cfg.carrier_hz[1]); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + return; + } + } + + if (cd->ch[0].quiet_hops >= 5 && cd->ch[1].quiet_hops >= 5) { + cd->ch[0].triggered = false; + cd->ch[1].triggered = false; + } + + if (cd->ch[0].triggered != cd->ch[1].triggered) { + uint64_t first_ms = cd->ch[0].triggered ? + cd->ch[0].onset_ms : cd->ch[1].onset_ms; + + if ((now_ms - first_ms) < cd->cfg.swipe_max_lag_ms) + swipe_pending = true; + } + } + + /* 4. Push / Pull / Tap stroke classification (require coherent frequency trajectory) */ + if (best_dir != 0 && best_dir == cd->stroke_dir && cd->presence_consec >= 2) { + cd->stroke_hops++; + } else if (best_dir != 0) { + cd->stroke_dir = best_dir; + cd->stroke_hops = 1; + } else { + cd->stroke_dir = 0; + cd->stroke_hops = 0; + } + + if (cd->stroke_hops >= 3) { + if (cd->stroke_dir > 0) { + if (!cd->pending_push.active) { + cd->pending_push.active = true; + cd->pending_push.start_ms = now_ms; + cd->pending_push.peak_doppler_mhz = best_doppler; + cd->pending_push.peak_snr_db_q8 = best_snr; + cd->pending_push.carrier_hz = best_carrier; + cd->pending_pull.active = false; + } else if (best_snr > cd->pending_push.peak_snr_db_q8) { + cd->pending_push.peak_doppler_mhz = best_doppler; + cd->pending_push.peak_snr_db_q8 = best_snr; + cd->pending_push.carrier_hz = best_carrier; + } + } else { + if (cd->pending_push.active && !swipe_pending && + (now_ms - cd->pending_push.start_ms) <= cd->cfg.tap_window_ms) { + int32_t peak_d = cd->pending_push.peak_doppler_mhz; + uint32_t peak_s = MAX(cd->pending_push.peak_snr_db_q8, best_snr); + + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_TAP, + peak_d, peak_s, best_carrier); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + return; + } + + if (!cd->pending_pull.active) { + cd->pending_pull.active = true; + cd->pending_pull.start_ms = now_ms; + cd->pending_pull.peak_doppler_mhz = best_doppler; + cd->pending_pull.peak_snr_db_q8 = best_snr; + cd->pending_pull.carrier_hz = best_carrier; + } else if (best_snr > cd->pending_pull.peak_snr_db_q8) { + cd->pending_pull.peak_doppler_mhz = best_doppler; + cd->pending_pull.peak_snr_db_q8 = best_snr; + cd->pending_pull.carrier_hz = best_carrier; + } + } + } + + /* Deferred emission once tap/swipe disambiguation window elapses */ + if (cd->pending_push.active && !swipe_pending && + (now_ms - cd->pending_push.start_ms) >= cd->cfg.tap_window_ms) { + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PUSH, + cd->pending_push.peak_doppler_mhz, + cd->pending_push.peak_snr_db_q8, + cd->pending_push.carrier_hz); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + return; + } + + if (cd->pending_pull.active && !swipe_pending && + (now_ms - cd->pending_pull.start_ms) >= 96U) { + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PULL, + cd->pending_pull.peak_doppler_mhz, + cd->pending_pull.peak_snr_db_q8, + cd->pending_pull.carrier_hz); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + } +} + +/* Full 24-bit Q23 complex mixer to preserve low-level acoustic reflections without speech clipping */ +static inline void ultrasound_rx_feed_sample_q23(struct ultrasound_rx_data *cd, + uint32_t ch_idx, int32_t s_q23) +{ + struct us_rx_channel *c = &cd->ch[ch_idx]; + int32_t cos_v = us_cos_q15(c->phase); + int32_t sin_v = us_sin_q15(c->phase); + int64_t mix_i = ((int64_t)s_q23 * cos_v) >> 15; + int64_t mix_q = -((int64_t)s_q23 * sin_v) >> 15; + + c->phase += c->phase_inc; + + /* 2nd-order CIC integrators at input sample rate */ + c->int1_i += mix_i; + c->int2_i += c->int1_i; + c->int1_q += mix_q; + c->int2_q += c->int1_q; +} + +static void ultrasound_rx_finish_frame(struct processing_module *mod, + struct ultrasound_rx_data *cd) +{ + uint32_t shift_right; + + cd->total_frames++; + cd->decim_count++; + + if (cd->decim_count < cd->decim_factor) + return; + + cd->decim_count = 0; + cd->bb_ms++; + + /* + * 2nd-order CIC combs at 1000 Hz baseband. + * s_q23 -> /d2 gives Q23; shift right by (4 - gain_shift) maps: + * gain_shift=0 -> Q19 (same scale as legacy Q15<<4) + * gain_shift=2 -> Q21 (default: 4x extra sensitivity, 63x FFT headroom) + * gain_shift=4 -> Q23 (max sensitivity, 4x FFT headroom) + */ + shift_right = (cd->cfg.input_gain_shift >= 4) ? 0 : (4U - cd->cfg.input_gain_shift); + + int64_t d2 = (int64_t)cd->decim_factor * (int64_t)cd->decim_factor; + + for (uint32_t ch = 0; ch < cd->active_channels; ch++) { + struct us_rx_channel *c = &cd->ch[ch]; + int64_t c1_i = c->int2_i - c->comb1_i; + int64_t c2_i = c1_i - c->comb2_i; + int64_t c1_q = c->int2_q - c->comb1_q; + int64_t c2_q = c1_q - c->comb2_q; + int32_t raw_i, raw_q, bb_i, bb_q; + + c->comb1_i = c->int2_i; + c->comb2_i = c1_i; + c->comb1_q = c->int2_q; + c->comb2_q = c1_q; + + raw_i = (int32_t)((c2_i / d2) >> shift_right); + raw_q = (int32_t)((c2_q / d2) >> shift_right); + + if (!c->dc_initialized) { + c->dc_i_q8 = (int64_t)raw_i << 8; + c->dc_q_q8 = (int64_t)raw_q << 8; + c->dc_initialized = true; + } else { + c->dc_i_q8 += (((int64_t)raw_i << 8) - c->dc_i_q8) >> 4; + c->dc_q_q8 += (((int64_t)raw_q << 8) - c->dc_q_q8) >> 4; + } + + bb_i = raw_i - (int32_t)(c->dc_i_q8 >> 8); + bb_q = raw_q - (int32_t)(c->dc_q_q8 >> 8); + + c->ring_i[c->ring_pos] = bb_i; + c->ring_q[c->ring_pos] = bb_q; + c->ring_pos = (c->ring_pos + 1U) & (US_FFT_SIZE - 1); + } + + cd->hop_count++; + if (cd->hop_count >= US_RX_HOP_SAMPLES) { + cd->hop_count = 0; + ultrasound_rx_run_hop(mod, cd); + } +} + +static int ultrasound_rx_process_s16(struct processing_module *mod, + struct ultrasound_rx_data *cd, + struct sof_source *source, + struct sof_sink *sink, + uint32_t frames) +{ + const int16_t *x, *x_start, *x_end; + int16_t *y = NULL, *y_start = NULL, *y_end = NULL; + int x_size, y_size = 0; + uint32_t bytes = frames * cd->frame_bytes; + uint32_t remaining = frames * cd->channels; + uint32_t ch = 0; + int ret; + + ret = source_get_data_s16(source, bytes, &x, &x_start, &x_size); + if (ret) + return ret; + + if (sink) { + ret = sink_get_buffer_s16(sink, bytes, &y, &y_start, &y_size); + if (ret) + return ret; + y_end = y_start + y_size; + } + + x_end = x_start + x_size; + + while (remaining) { + uint32_t n = (uint32_t)(x_end - x); + + if (sink) + n = MIN(n, (uint32_t)(y_end - y)); + n = MIN(n, remaining); + + for (uint32_t i = 0; i < n; i++) { + int16_t sample = *x++; + + if (sink) + *y++ = sample; + if (ch < cd->active_channels) + ultrasound_rx_feed_sample_q23(cd, ch, (int32_t)sample << 8); + ch++; + if (ch == cd->channels) { + ch = 0; + ultrasound_rx_finish_frame(mod, cd); + } + } + + if (x >= x_end) + x -= x_size; + if (sink && y >= y_end) + y -= y_size; + remaining -= n; + } + + source_release_data(source, bytes); + if (sink) + sink_commit_buffer(sink, bytes); + return 0; +} + +static int ultrasound_rx_process_s32(struct processing_module *mod, + struct ultrasound_rx_data *cd, + struct sof_source *source, + struct sof_sink *sink, + uint32_t frames, + bool is_s24) +{ + const int32_t *x, *x_start, *x_end; + int32_t *y = NULL, *y_start = NULL, *y_end = NULL; + int x_size, y_size = 0; + uint32_t bytes = frames * cd->frame_bytes; + uint32_t remaining = frames * cd->channels; + uint32_t ch = 0; + int ret; + + ret = source_get_data_s32(source, bytes, &x, &x_start, &x_size); + if (ret) + return ret; + + if (sink) { + ret = sink_get_buffer_s32(sink, bytes, &y, &y_start, &y_size); + if (ret) + return ret; + y_end = y_start + y_size; + } + + x_end = x_start + x_size; + + while (remaining) { + uint32_t n = (uint32_t)(x_end - x); + + if (sink) + n = MIN(n, (uint32_t)(y_end - y)); + n = MIN(n, remaining); + + for (uint32_t i = 0; i < n; i++) { + int32_t sample = *x++; + + if (sink) + *y++ = sample; + if (ch < cd->active_channels) { + int32_t s_q23 = is_s24 ? ((sample << 8) >> 8) : (sample >> 8); + + ultrasound_rx_feed_sample_q23(cd, ch, s_q23); + } + ch++; + if (ch == cd->channels) { + ch = 0; + ultrasound_rx_finish_frame(mod, cd); + } + } + + if (x >= x_end) + x -= x_size; + if (sink && y >= y_end) + y -= y_size; + remaining -= n; + } + + source_release_data(source, bytes); + if (sink) + sink_commit_buffer(sink, bytes); + return 0; +} + +__cold static int ultrasound_rx_init(struct processing_module *mod) +{ + struct module_data *md = &mod->priv; + struct comp_dev *dev = mod->dev; + struct ultrasound_rx_data *cd; + + comp_info(dev, "ultrasound_rx_init (in_pins=%u out_pins=%u)", + mod->priv.cfg.nb_input_pins, mod->priv.cfg.nb_output_pins); + + cd = mod_zalloc(mod, sizeof(*cd)); + if (!cd) + return -ENOMEM; + + cd->cfg.version = SOF_ULTRASOUND_ABI_VERSION; + cd->cfg.enable = 1; + cd->cfg.carrier_hz[0] = US_RX_DEFAULT_CARRIER_HZ; + cd->cfg.carrier_hz[1] = US_RX_DEFAULT_CARRIER_HZ; + cd->cfg.snr_threshold_q8 = US_RX_DEFAULT_SNR_THRESH_Q8; + cd->cfg.min_peak_level = US_RX_DEFAULT_MIN_PEAK; + cd->cfg.cooldown_ms = US_RX_DEFAULT_COOLDOWN_MS; + cd->cfg.tap_window_ms = US_RX_DEFAULT_TAP_WINDOW_MS; + cd->cfg.swipe_min_lag_ms = US_RX_DEFAULT_SWIPE_MIN_LAG_MS; + cd->cfg.swipe_max_lag_ms = US_RX_DEFAULT_SWIPE_MAX_LAG_MS; + cd->cfg.presence_timeout_ms = US_RX_DEFAULT_PRESENCE_TO_MS; + cd->cfg.input_gain_shift = US_RX_DEFAULT_GAIN_SHIFT; + +#if CONFIG_IPC_MAJOR_4 + cd->module_id = IPC4_MOD_ID(dev->ipc_config.id); + cd->instance_id = IPC4_INST_ID(dev->ipc_config.id); + if (mod->priv.cfg.nb_output_pins == 0) { + dev->direction = SOF_IPC_STREAM_CAPTURE; + dev->direction_set = true; + cd->is_sink_only = true; + } +#endif + + md->private = cd; + return 0; +} + +static int ultrasound_rx_prepare(struct processing_module *mod, + struct sof_source **sources, int num_of_sources, + struct sof_sink **sinks, int num_of_sinks) +{ + struct ultrasound_rx_data *cd = module_get_private_data(mod); + struct comp_dev *dev = mod->dev; + + if (num_of_sources != 1 || (num_of_sinks != 0 && num_of_sinks != 1)) + return -EINVAL; + + cd->is_sink_only = (num_of_sinks == 0); + cd->sample_rate = source_get_rate(sources[0]); + cd->channels = source_get_channels(sources[0]); + cd->active_channels = MIN(cd->channels, (uint32_t)SOF_ULTRASOUND_MAX_CHANNELS); + cd->frame_bytes = source_get_frame_bytes(sources[0]); + cd->format = source_get_frm_fmt(sources[0]); + + if (cd->sample_rate < 44100 || (cd->sample_rate % US_BASEBAND_RATE_HZ) != 0) { + comp_err(dev, "Unsupported sample rate %u (need >=44.1k, multiple of 1kHz)", + cd->sample_rate); + return -EINVAL; + } + + if (cd->format != SOF_IPC_FRAME_S16_LE && + cd->format != SOF_IPC_FRAME_S24_4LE && + cd->format != SOF_IPC_FRAME_S32_LE) { + comp_err(dev, "Unsupported format %d", cd->format); + return -EINVAL; + } + + ultrasound_rx_reset_state(cd); + + comp_info(dev, + "ultrasound_rx prepare: sink_only=%d rate=%u ch=%u(act=%u) fmt=%d decim=%u f0=%u f1=%u mod=%u inst=%u", + cd->is_sink_only, cd->sample_rate, cd->channels, cd->active_channels, + cd->format, cd->decim_factor, cd->cfg.carrier_hz[0], cd->cfg.carrier_hz[1], + cd->module_id, cd->instance_id); + return 0; +} + +static int ultrasound_rx_process(struct processing_module *mod, + struct sof_source **sources, int num_of_sources, + struct sof_sink **sinks, int num_of_sinks) +{ + struct ultrasound_rx_data *cd = module_get_private_data(mod); + struct sof_source *source = sources[0]; + struct sof_sink *sink = (num_of_sinks > 0) ? sinks[0] : NULL; + uint32_t frames = source_get_data_frames_available(source); + + if (sink) + frames = MIN(frames, sink_get_free_frames(sink)); + frames = MIN(frames, mod->dev->frames); + if (!frames) + return 0; + + if (!cd->cfg.enable) { + if (sink) + source_to_sink_copy(source, sink, true, frames * cd->frame_bytes); + else + source_release_data(source, frames * cd->frame_bytes); + return 0; + } + + switch (cd->format) { + case SOF_IPC_FRAME_S16_LE: + return ultrasound_rx_process_s16(mod, cd, source, sink, frames); + case SOF_IPC_FRAME_S24_4LE: + return ultrasound_rx_process_s32(mod, cd, source, sink, frames, true); + case SOF_IPC_FRAME_S32_LE: + return ultrasound_rx_process_s32(mod, cd, source, sink, frames, false); + default: + return -EINVAL; + } +} + +__cold static int ultrasound_rx_set_config(struct processing_module *mod, + uint32_t param_id, + enum module_cfg_fragment_position pos, + uint32_t data_offset_size, + const uint8_t *fragment, + size_t fragment_size, + uint8_t *response, + size_t response_size) +{ + struct ultrasound_rx_data *cd = module_get_private_data(mod); + struct comp_dev *dev = mod->dev; + + assert_can_be_cold(); + +#if CONFIG_IPC_MAJOR_4 + 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; + + if (fragment_size < sizeof(*ctl) + sizeof(struct sof_ipc4_ctrl_value_chan)) + return -EINVAL; + + if (ctl->id == SOF_US_RX_CTL_DIAG_DUMP) { + ultrasound_rx_log_diag(dev, cd, "diag"); + return 0; + } + + cd->cfg.enable = ctl->chanv[0].value ? 0 : 1; + comp_info(dev, "ultrasound_rx bypass=%u enable=%u", + ctl->chanv[0].value, cd->cfg.enable); + return 0; + } +#endif + + if (param_id == SOF_US_RX_PARAM_CONFIG) { + if (fragment_size != sizeof(cd->cfg)) + return -EINVAL; + + memcpy_s(&cd->cfg, sizeof(cd->cfg), fragment, fragment_size); + ultrasound_rx_reset_state(cd); + comp_info(dev, "ultrasound_rx cfg updated: en=%u f0=%u f1=%u snr_q8=%u shift=%u", + cd->cfg.enable, cd->cfg.carrier_hz[0], cd->cfg.carrier_hz[1], + cd->cfg.snr_threshold_q8, cd->cfg.input_gain_shift); + return 0; + } + + return -EINVAL; +} + +__cold static int ultrasound_rx_get_config(struct processing_module *mod, + uint32_t param_id, + uint32_t *data_offset_size, + uint8_t *fragment, + size_t fragment_size) +{ + struct ultrasound_rx_data *cd = module_get_private_data(mod); + + assert_can_be_cold(); + + if (param_id == SOF_US_RX_PARAM_CONFIG) { + if (fragment_size < sizeof(cd->cfg)) + return -EINVAL; + memcpy_s(fragment, fragment_size, &cd->cfg, sizeof(cd->cfg)); + *data_offset_size = sizeof(cd->cfg); + return 0; + } + + return -EINVAL; +} + +static int ultrasound_rx_reset(struct processing_module *mod) +{ + struct ultrasound_rx_data *cd = module_get_private_data(mod); + + ultrasound_rx_reset_state(cd); + return 0; +} + +__cold static int ultrasound_rx_free(struct processing_module *mod) +{ + struct ultrasound_rx_data *cd = module_get_private_data(mod); + + assert_can_be_cold(); +#if CONFIG_IPC_MAJOR_4 + ultrasound_set_presence(false); +#endif + mod_free(mod, cd); + return 0; +} + +static const struct module_interface ultrasound_rx_interface = { + .init = ultrasound_rx_init, + .prepare = ultrasound_rx_prepare, + .process = ultrasound_rx_process, + .set_configuration = ultrasound_rx_set_config, + .get_configuration = ultrasound_rx_get_config, + .reset = ultrasound_rx_reset, + .free = ultrasound_rx_free, +}; + +#if CONFIG_COMP_ULTRASOUND_RX_MODULE + +#include +#include +#include + +static const struct sof_man_module_manifest mod_manifest __section(".module") __used = + SOF_LLEXT_MODULE_MANIFEST("USND_RX", &ultrasound_rx_interface, 1, + SOF_REG_UUID(ultrasound_rx), 8); + +SOF_LLEXT_BUILDINFO; + +#else + +DECLARE_TR_CTX(ultrasound_rx_tr, SOF_UUID(ultrasound_rx_uuid), LOG_LEVEL_INFO); +DECLARE_MODULE_ADAPTER(ultrasound_rx_interface, ultrasound_rx_uuid, ultrasound_rx_tr); +SOF_MODULE_INIT(ultrasound_rx, sys_comp_module_ultrasound_rx_interface_init); + +#endif diff --git a/src/audio/ultrasound/ultrasound_rx.h b/src/audio/ultrasound/ultrasound_rx.h new file mode 100644 index 000000000000..005f79b29b3c --- /dev/null +++ b/src/audio/ultrasound/ultrasound_rx.h @@ -0,0 +1,120 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Copyright(c) 2026 Intel Corporation. + */ + +#ifndef __SOF_AUDIO_ULTRASOUND_RX_H__ +#define __SOF_AUDIO_ULTRASOUND_RX_H__ + +#include +#include +#include +#include +#include "ultrasound_dsp.h" + +#define US_RX_HOP_SAMPLES 16 /* 16 ms hop at 1000 Hz baseband */ +#define US_RX_WARMUP_MS 600 /* Clear DMIC unmute ramp + in-band NF settle */ +#define US_RX_DEFAULT_CARRIER_HZ 20000 +#define US_RX_DEFAULT_SNR_THRESH_Q8 (13U << 8) /* 13.0 dB above local in-band noise floor */ +#define US_RX_DEFAULT_MIN_PEAK 800 /* Above live Intel DMIC ambient noise floor */ +#define US_RX_MAX_HOP_FREQ_JUMP_MHZ 65000 /* Max 65 Hz Doppler jump per 16 ms hop */ +#define US_RX_DEFAULT_COOLDOWN_MS 350 +#define US_RX_DEFAULT_TAP_WINDOW_MS 360 +#define US_RX_DEFAULT_SWIPE_MIN_LAG_MS 20 +#define US_RX_DEFAULT_SWIPE_MAX_LAG_MS 320 +#define US_RX_DEFAULT_PRESENCE_TO_MS 3000 +#define US_RX_DEFAULT_GAIN_SHIFT 2 /* Q21 baseband scale (full 24-bit dynamic range) */ + +struct us_rx_channel { + /* Carrier NCO */ + uint32_t phase; + uint32_t phase_inc; + + /* 2nd-order CIC decimator (Fs -> 1000 Hz complex baseband) */ + int64_t int1_i; + int64_t int2_i; + int64_t int1_q; + int64_t int2_q; + int64_t comb1_i; + int64_t comb2_i; + int64_t comb1_q; + int64_t comb2_q; + + /* 1-pole complex DC blocker (removes static carrier coupling) */ + int64_t dc_i_q8; + int64_t dc_q_q8; + bool dc_initialized; + + /* Baseband 64-sample ring buffer */ + int32_t ring_i[US_FFT_SIZE]; + int32_t ring_q[US_FFT_SIZE]; + uint32_t ring_pos; + + /* Adaptive per-sideband in-band noise floors (cancels CIC2 droop & DMIC rolloff tilt) */ + uint32_t noise_floor; + uint32_t noise_floor_pos; + uint32_t noise_floor_neg; + + /* Per-hop instantaneous detection */ + int8_t hop_dir; /* +1 approach, -1 recede, 0 none */ + int32_t hop_doppler_mhz; + int32_t prev_hop_doppler_mhz; + int8_t prev_hop_dir; + uint32_t hop_snr_db_q8; + uint32_t hop_peak_mag; + + /* Swipe onset tracking */ + uint32_t active_hops; + uint32_t quiet_hops; + bool triggered; + uint64_t onset_ms; + int32_t onset_doppler_mhz; + uint32_t onset_snr_db_q8; +}; + +struct us_rx_pending_stroke { + bool active; + uint64_t start_ms; + int32_t peak_doppler_mhz; + uint32_t peak_snr_db_q8; + uint32_t carrier_hz; +}; + +struct ultrasound_rx_data { + struct sof_ultrasound_rx_config cfg; + uint32_t sample_rate; + uint32_t channels; + uint32_t active_channels; + uint32_t frame_bytes; + enum sof_ipc_frame format; + bool is_sink_only; + + uint32_t decim_factor; + uint32_t decim_count; + uint32_t hop_count; + uint64_t total_frames; + uint64_t bb_ms; + bool warmup_logged; + + struct us_rx_channel ch[SOF_ULTRASOUND_MAX_CHANNELS]; + + /* Presence tracking */ + bool present; + uint32_t presence_consec; + uint64_t last_activity_ms; + + /* Gesture state machine */ + uint64_t cooldown_until_ms; + int8_t stroke_dir; + int32_t prev_best_doppler_mhz; + uint32_t stroke_hops; + struct us_rx_pending_stroke pending_push; + struct us_rx_pending_stroke pending_pull; + + /* IPC4 notification state */ + uint16_t module_id; + uint16_t instance_id; + uint32_t event_seq; +}; + +#endif /* __SOF_AUDIO_ULTRASOUND_RX_H__ */ diff --git a/src/audio/ultrasound/ultrasound_rx.toml b/src/audio/ultrasound/ultrasound_rx.toml new file mode 100644 index 000000000000..915b55cfbb36 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_rx.toml @@ -0,0 +1,21 @@ +#ifndef LOAD_TYPE +#define LOAD_TYPE "0" +#endif + + REM # Ultrasound RX Doppler gesture & presence detector module config + [[module.entry]] + name = "USND_RX" + uuid = UUIDREG_STR_ULTRASOUND_RX + affinity_mask = "0x1" + instance_count = "8" + domain_types = "0" + load_type = LOAD_TYPE + module_type = "9" + auto_start = "0" + sched_caps = [1, 0x00008000] + REM # pin = [dir, type, sample rate, size, container, channel-cfg] + pin = [0, 0, 0xfeef, 0xf, 0xf, 0x45ff, 1, 0, 0xfeef, 0xf, 0xf, 0x1ff] + REM # mod_cfg [PAR_0 PAR_1 PAR_2 PAR_3 IS_BYTES CPS IBS OBS MOD_FLAGS CPC OBLS] + mod_cfg = [0, 0, 0, 0, 8192, 2000000, 128, 128, 0, 0, 0] + + index = __COUNTER__ diff --git a/src/audio/ultrasound/ultrasound_tx.c b/src/audio/ultrasound/ultrasound_tx.c new file mode 100644 index 000000000000..66cff859eee1 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_tx.c @@ -0,0 +1,655 @@ +// SPDX-License-Identifier: BSD-3-Clause +// +// Copyright(c) 2026 Intel Corporation. +// +// Ultrasonic carrier generator module (hostless standalone source & additive TX) +// with Approach B click-free duty-cycled bursting and automatic presence boost. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ultrasound_dsp.h" +#include "ultrasound_tx.h" + +SOF_DEFINE_REG_UUID(ultrasound_tx); + +LOG_MODULE_REGISTER(ultrasound_tx, CONFIG_SOF_LOG_LEVEL); + +static inline int32_t sat_s16(int64_t v) +{ + if (v > INT16_MAX) + return INT16_MAX; + if (v < INT16_MIN) + return INT16_MIN; + return (int32_t)v; +} + +static inline int32_t sat_s24(int64_t v) +{ + if (v > 0x7FFFFF) + return 0x7FFFFF; + if (v < -0x800000) + return -0x800000; + return (int32_t)v; +} + +static inline int32_t sat_s32(int64_t v) +{ + if (v > INT32_MAX) + return INT32_MAX; + if (v < INT32_MIN) + return INT32_MIN; + return (int32_t)v; +} + +static void ultrasound_tx_update_params(struct ultrasound_tx_data *cd) +{ + uint32_t ramp_samples; + int ch; + + if (!cd->sample_rate) + return; + + for (ch = 0; ch < SOF_ULTRASOUND_MAX_CHANNELS; ch++) { + uint32_t freq = cd->cfg.carrier_hz[ch]; + + /* Clamp safely below Nyquist */ + if (freq >= (cd->sample_rate >> 1)) + freq = (cd->sample_rate >> 1) - 1000; + cd->phase_inc[ch] = us_phase_inc(freq, cd->sample_rate); + } + + cd->target_env_q31 = (cd->cfg.mode == SOF_US_TX_MODE_BYPASS) ? 0 : cd->cfg.amplitude_q31; + ramp_samples = (cd->cfg.ramp_ms * cd->sample_rate) / 1000; + if (ramp_samples < 1) + ramp_samples = 1; + cd->ramp_step_q31 = cd->cfg.amplitude_q31 / (int32_t)ramp_samples; + if (cd->ramp_step_q31 < 1) + cd->ramp_step_q31 = 1; + + if (cd->cfg.duty_period_ms > 0) { + uint32_t on_ms = cd->cfg.duty_on_ms; + + if (on_ms == 0 || on_ms > cd->cfg.duty_period_ms) + on_ms = cd->cfg.duty_period_ms; + cd->duty_period_samples = (cd->cfg.duty_period_ms * cd->sample_rate) / 1000; + cd->duty_on_samples = (on_ms * cd->sample_rate) / 1000; + if (cd->duty_sample_pos >= cd->duty_period_samples) + cd->duty_sample_pos = 0; + } else { + cd->duty_period_samples = 0; + cd->duty_on_samples = 0; + cd->duty_sample_pos = 0; + } +} + +static inline int32_t ultrasound_tx_step_env(struct ultrasound_tx_data *cd) +{ + int32_t desired = cd->target_env_q31; + + /* Approach B: click-free duty-cycled bursting with auto-boost on presence */ + if (desired > 0 && cd->duty_period_samples > 0) { + bool boosted = cd->cfg.auto_boost_on_presence && ultrasound_get_presence(); + + if (boosted) { + /* Stay continuously ON during active user/hand presence */ + cd->duty_sample_pos = 0; + } else { + if (cd->duty_sample_pos == 0) + cd->duty_bursts++; + if (cd->duty_sample_pos >= cd->duty_on_samples) + desired = 0; + cd->duty_sample_pos++; + if (cd->duty_sample_pos >= cd->duty_period_samples) + cd->duty_sample_pos = 0; + } + if (boosted != cd->last_boosted) { + cd->last_boosted = boosted; + cd->boost_logged = true; + } + } + cd->frames_generated++; + + if (cd->env_q31 < desired) { + cd->env_q31 += cd->ramp_step_q31; + if (cd->env_q31 > desired) + cd->env_q31 = desired; + } else if (cd->env_q31 > desired) { + cd->env_q31 -= cd->ramp_step_q31; + if (cd->env_q31 < desired) + cd->env_q31 = desired; + } + return cd->env_q31; +} + +static int ultrasound_tx_generate_s16(struct ultrasound_tx_data *cd, + struct sof_sink *sink, + uint32_t frames) +{ + int16_t *y, *y_start, *y_end; + int y_size; + uint32_t bytes = frames * cd->frame_bytes; + uint32_t remaining = frames * cd->channels; + uint32_t ch = 0; + int32_t env = cd->env_q31; + int ret; + + ret = sink_get_buffer_s16(sink, bytes, &y, &y_start, &y_size); + if (ret) + return ret; + + y_end = y_start + y_size; + + while (remaining) { + uint32_t n = MIN((uint32_t)(y_end - y), remaining); + + for (uint32_t i = 0; i < n; i++) { + if (ch == 0) + env = ultrasound_tx_step_env(cd); + + if (ch < SOF_ULTRASOUND_MAX_CHANNELS && env > 0) { + int32_t s_q15 = us_sin_q15(cd->phase[ch]); + int64_t tone = (((int64_t)s_q15 * env) >> 31); + + cd->phase[ch] += cd->phase_inc[ch]; + *y = (int16_t)sat_s16(tone); + } else { + *y = 0; + } + + y++; + ch++; + if (ch == cd->channels) + ch = 0; + } + + if (y >= y_end) + y -= y_size; + remaining -= n; + } + + sink_commit_buffer(sink, bytes); + return 0; +} + +static int ultrasound_tx_generate_s32(struct ultrasound_tx_data *cd, + struct sof_sink *sink, + uint32_t frames, + bool is_s24) +{ + int32_t *y, *y_start, *y_end; + int y_size; + uint32_t bytes = frames * cd->frame_bytes; + uint32_t remaining = frames * cd->channels; + uint32_t ch = 0; + int32_t env = cd->env_q31; + int ret; + + ret = sink_get_buffer_s32(sink, bytes, &y, &y_start, &y_size); + if (ret) + return ret; + + y_end = y_start + y_size; + + while (remaining) { + uint32_t n = MIN((uint32_t)(y_end - y), remaining); + + for (uint32_t i = 0; i < n; i++) { + if (ch == 0) + env = ultrasound_tx_step_env(cd); + + if (ch < SOF_ULTRASOUND_MAX_CHANNELS && env > 0) { + int32_t s_q15 = us_sin_q15(cd->phase[ch]); + int64_t tone31 = ((int64_t)s_q15 * env) >> 15; + + cd->phase[ch] += cd->phase_inc[ch]; + *y = is_s24 ? sat_s24(tone31 >> 8) : sat_s32(tone31); + } else { + *y = 0; + } + + y++; + ch++; + if (ch == cd->channels) + ch = 0; + } + + if (y >= y_end) + y -= y_size; + remaining -= n; + } + + sink_commit_buffer(sink, bytes); + return 0; +} + +static int ultrasound_tx_process_s16(struct ultrasound_tx_data *cd, + struct sof_source *source, + struct sof_sink *sink, + uint32_t frames) +{ + const int16_t *x, *x_start, *x_end; + int16_t *y, *y_start, *y_end; + int x_size, y_size; + uint32_t bytes = frames * cd->frame_bytes; + uint32_t remaining = frames * cd->channels; + uint32_t ch = 0; + int32_t env = cd->env_q31; + int ret; + + ret = source_get_data_s16(source, bytes, &x, &x_start, &x_size); + if (ret) + return ret; + + ret = sink_get_buffer_s16(sink, bytes, &y, &y_start, &y_size); + if (ret) + return ret; + + x_end = x_start + x_size; + y_end = y_start + y_size; + + while (remaining) { + uint32_t n = MIN((uint32_t)(x_end - x), (uint32_t)(y_end - y)); + + n = MIN(n, remaining); + for (uint32_t i = 0; i < n; i++) { + if (ch == 0) + env = ultrasound_tx_step_env(cd); + + if (ch < SOF_ULTRASOUND_MAX_CHANNELS && env > 0) { + int32_t s_q15 = us_sin_q15(cd->phase[ch]); + int64_t tone = (((int64_t)s_q15 * env) >> 31); + + cd->phase[ch] += cd->phase_inc[ch]; + if (cd->cfg.mode == SOF_US_TX_MODE_REPLACE) + *y = (int16_t)sat_s16(tone); + else + *y = (int16_t)sat_s16((int64_t)(*x) + tone); + } else { + *y = *x; + } + + x++; + y++; + ch++; + if (ch == cd->channels) + ch = 0; + } + + if (x >= x_end) + x -= x_size; + if (y >= y_end) + y -= y_size; + remaining -= n; + } + + source_release_data(source, bytes); + sink_commit_buffer(sink, bytes); + return 0; +} + +static int ultrasound_tx_process_s32(struct ultrasound_tx_data *cd, + struct sof_source *source, + struct sof_sink *sink, + uint32_t frames, + bool is_s24) +{ + const int32_t *x, *x_start, *x_end; + int32_t *y, *y_start, *y_end; + int x_size, y_size; + uint32_t bytes = frames * cd->frame_bytes; + uint32_t remaining = frames * cd->channels; + uint32_t ch = 0; + int32_t env = cd->env_q31; + int ret; + + ret = source_get_data_s32(source, bytes, &x, &x_start, &x_size); + if (ret) + return ret; + + ret = sink_get_buffer_s32(sink, bytes, &y, &y_start, &y_size); + if (ret) + return ret; + + x_end = x_start + x_size; + y_end = y_start + y_size; + + while (remaining) { + uint32_t n = MIN((uint32_t)(x_end - x), (uint32_t)(y_end - y)); + + n = MIN(n, remaining); + for (uint32_t i = 0; i < n; i++) { + if (ch == 0) + env = ultrasound_tx_step_env(cd); + + if (ch < SOF_ULTRASOUND_MAX_CHANNELS && env > 0) { + int32_t s_q15 = us_sin_q15(cd->phase[ch]); + int64_t tone31 = ((int64_t)s_q15 * env) >> 15; + + cd->phase[ch] += cd->phase_inc[ch]; + if (is_s24) { + int64_t in24 = (int64_t)((*x << 8) >> 8); + int64_t tone24 = tone31 >> 8; + + if (cd->cfg.mode == SOF_US_TX_MODE_REPLACE) + *y = sat_s24(tone24); + else + *y = sat_s24(in24 + tone24); + } else { + if (cd->cfg.mode == SOF_US_TX_MODE_REPLACE) + *y = sat_s32(tone31); + else + *y = sat_s32((int64_t)(*x) + tone31); + } + } else { + *y = *x; + } + + x++; + y++; + ch++; + if (ch == cd->channels) + ch = 0; + } + + if (x >= x_end) + x -= x_size; + if (y >= y_end) + y -= y_size; + remaining -= n; + } + + source_release_data(source, bytes); + sink_commit_buffer(sink, bytes); + return 0; +} + +__cold static int ultrasound_tx_init(struct processing_module *mod) +{ + struct module_data *md = &mod->priv; + struct comp_dev *dev = mod->dev; + struct ultrasound_tx_data *cd; + + comp_info(dev, "ultrasound_tx_init (in_pins=%u out_pins=%u)", + mod->priv.cfg.nb_input_pins, mod->priv.cfg.nb_output_pins); + + cd = mod_zalloc(mod, sizeof(*cd)); + if (!cd) + return -ENOMEM; + + cd->cfg.version = SOF_ULTRASOUND_ABI_VERSION; + cd->cfg.mode = SOF_US_TX_MODE_ADDITIVE; + cd->cfg.carrier_hz[0] = US_TX_DEFAULT_CARRIER_HZ; + cd->cfg.carrier_hz[1] = US_TX_DEFAULT_CARRIER_HZ; + cd->cfg.amplitude_q31 = US_TX_DEFAULT_AMPLITUDE_Q31; + cd->cfg.ramp_ms = US_TX_DEFAULT_RAMP_MS; + cd->cfg.duty_period_ms = 0; /* Approach A: continuous by default */ + cd->cfg.duty_on_ms = US_TX_LP_DUTY_ON_MS; + cd->cfg.auto_boost_on_presence = 1; + +#if CONFIG_IPC_MAJOR_4 + if (mod->priv.cfg.nb_input_pins == 0) { + dev->direction = SOF_IPC_STREAM_PLAYBACK; + dev->direction_set = true; + cd->is_standalone = true; + } +#endif + + md->private = cd; + return 0; +} + +static int ultrasound_tx_prepare(struct processing_module *mod, + struct sof_source **sources, int num_of_sources, + struct sof_sink **sinks, int num_of_sinks) +{ + struct ultrasound_tx_data *cd = module_get_private_data(mod); + struct comp_dev *dev = mod->dev; + + if ((num_of_sources != 0 && num_of_sources != 1) || num_of_sinks != 1) + return -EINVAL; + + cd->is_standalone = (num_of_sources == 0); + + if (cd->is_standalone) { +#if CONFIG_IPC_MAJOR_4 + ipc4_update_sink_format(sinks[0], &mod->priv.cfg.base_cfg.audio_fmt); +#endif + cd->sample_rate = sink_get_rate(sinks[0]); + cd->channels = sink_get_channels(sinks[0]); + cd->frame_bytes = sink_get_frame_bytes(sinks[0]); + cd->format = sink_get_frm_fmt(sinks[0]); + } else { + cd->sample_rate = source_get_rate(sources[0]); + cd->channels = source_get_channels(sources[0]); + cd->frame_bytes = source_get_frame_bytes(sources[0]); + cd->format = source_get_frm_fmt(sources[0]); + } + + if (cd->format != SOF_IPC_FRAME_S16_LE && + cd->format != SOF_IPC_FRAME_S24_4LE && + cd->format != SOF_IPC_FRAME_S32_LE) { + comp_err(dev, "Unsupported format %d", cd->format); + return -EINVAL; + } + + cd->phase[0] = 0; + cd->phase[1] = 0; + cd->env_q31 = 0; + cd->duty_sample_pos = 0; + cd->last_boosted = false; + ultrasound_tx_update_params(cd); + + comp_info(dev, "ultrasound_tx prepare: standalone=%d rate=%u ch=%u fmt=%d mode=%u f0=%u f1=%u duty=%u/%u ms", + cd->is_standalone, cd->sample_rate, cd->channels, cd->format, cd->cfg.mode, + cd->cfg.carrier_hz[0], cd->cfg.carrier_hz[1], + cd->cfg.duty_on_ms, cd->cfg.duty_period_ms); + return 0; +} + +static int ultrasound_tx_process(struct processing_module *mod, + struct sof_source **sources, int num_of_sources, + struct sof_sink **sinks, int num_of_sinks) +{ + struct ultrasound_tx_data *cd = module_get_private_data(mod); + struct sof_sink *sink = sinks[0]; + uint32_t frames; + + if (num_of_sources == 0) { + int ret; + + frames = MIN(sink_get_free_frames(sink), mod->dev->frames); + if (!frames) + return 0; + + switch (cd->format) { + case SOF_IPC_FRAME_S16_LE: + ret = ultrasound_tx_generate_s16(cd, sink, frames); + break; + case SOF_IPC_FRAME_S24_4LE: + ret = ultrasound_tx_generate_s32(cd, sink, frames, true); + break; + case SOF_IPC_FRAME_S32_LE: + ret = ultrasound_tx_generate_s32(cd, sink, frames, false); + break; + default: + return -EINVAL; + } + + if (cd->boost_logged) { + cd->boost_logged = false; + comp_info(mod->dev, + "ultrasound_tx: Approach B auto-boost -> %s (bursts=%u frames=%u)", + cd->last_boosted ? "CONTINUOUS (presence=1)" : + "PULSED (presence=0)", + cd->duty_bursts, (uint32_t)cd->frames_generated); + } + return ret; + } + + struct sof_source *source = sources[0]; + + frames = MIN(source_get_data_frames_available(source), + sink_get_free_frames(sink)); + frames = MIN(frames, mod->dev->frames); + if (!frames) + return 0; + + /* Pure fast-path copy when fully ramped down to bypass */ + if (cd->cfg.mode == SOF_US_TX_MODE_BYPASS && cd->env_q31 == 0) { + source_to_sink_copy(source, sink, true, frames * cd->frame_bytes); + return 0; + } + + switch (cd->format) { + case SOF_IPC_FRAME_S16_LE: + return ultrasound_tx_process_s16(cd, source, sink, frames); + case SOF_IPC_FRAME_S24_4LE: + return ultrasound_tx_process_s32(cd, source, sink, frames, true); + case SOF_IPC_FRAME_S32_LE: + return ultrasound_tx_process_s32(cd, source, sink, frames, false); + default: + return -EINVAL; + } +} + +__cold static int ultrasound_tx_set_config(struct processing_module *mod, + uint32_t param_id, + enum module_cfg_fragment_position pos, + uint32_t data_offset_size, + const uint8_t *fragment, + size_t fragment_size, + uint8_t *response, + size_t response_size) +{ + struct ultrasound_tx_data *cd = module_get_private_data(mod); + struct comp_dev *dev = mod->dev; + + assert_can_be_cold(); + +#if CONFIG_IPC_MAJOR_4 + 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; + + if (fragment_size < sizeof(*ctl) + sizeof(struct sof_ipc4_ctrl_value_chan)) + return -EINVAL; + + if (ctl->id == SOF_US_TX_CTL_LOW_POWER_DUTY) { + if (ctl->chanv[0].value) { + cd->cfg.duty_period_ms = US_TX_LP_DUTY_PERIOD_MS; + cd->cfg.duty_on_ms = US_TX_LP_DUTY_ON_MS; + cd->cfg.auto_boost_on_presence = 1; + } else { + cd->cfg.duty_period_ms = 0; + } + ultrasound_tx_update_params(cd); + comp_info(dev, "ultrasound_tx low_power_duty=%u (%u/%u ms, auto_boost=%u)", + ctl->chanv[0].value, cd->cfg.duty_on_ms, + cd->cfg.duty_period_ms, cd->cfg.auto_boost_on_presence); + return 0; + } + + cd->cfg.mode = ctl->chanv[0].value ? SOF_US_TX_MODE_BYPASS : + SOF_US_TX_MODE_ADDITIVE; + ultrasound_tx_update_params(cd); + comp_info(dev, "ultrasound_tx bypass=%u mode=%u", + ctl->chanv[0].value, cd->cfg.mode); + return 0; + } +#endif + + if (param_id == SOF_US_TX_PARAM_CONFIG) { + if (fragment_size != sizeof(cd->cfg)) + return -EINVAL; + + memcpy_s(&cd->cfg, sizeof(cd->cfg), fragment, fragment_size); + ultrasound_tx_update_params(cd); + comp_info(dev, "ultrasound_tx cfg updated: mode=%u f0=%u f1=%u amp=%d duty=%u/%u", + cd->cfg.mode, cd->cfg.carrier_hz[0], cd->cfg.carrier_hz[1], + cd->cfg.amplitude_q31, cd->cfg.duty_on_ms, cd->cfg.duty_period_ms); + return 0; + } + + return -EINVAL; +} + +__cold static int ultrasound_tx_get_config(struct processing_module *mod, + uint32_t param_id, + uint32_t *data_offset_size, + uint8_t *fragment, + size_t fragment_size) +{ + struct ultrasound_tx_data *cd = module_get_private_data(mod); + + assert_can_be_cold(); + + if (param_id == SOF_US_TX_PARAM_CONFIG) { + if (fragment_size < sizeof(cd->cfg)) + return -EINVAL; + memcpy_s(fragment, fragment_size, &cd->cfg, sizeof(cd->cfg)); + *data_offset_size = sizeof(cd->cfg); + return 0; + } + + return -EINVAL; +} + +static int ultrasound_tx_reset(struct processing_module *mod) +{ + struct ultrasound_tx_data *cd = module_get_private_data(mod); + + cd->phase[0] = 0; + cd->phase[1] = 0; + cd->env_q31 = 0; + cd->duty_sample_pos = 0; + cd->last_boosted = false; + return 0; +} + +__cold static int ultrasound_tx_free(struct processing_module *mod) +{ + struct ultrasound_tx_data *cd = module_get_private_data(mod); + + assert_can_be_cold(); + mod_free(mod, cd); + return 0; +} + +static const struct module_interface ultrasound_tx_interface = { + .init = ultrasound_tx_init, + .prepare = ultrasound_tx_prepare, + .process = ultrasound_tx_process, + .set_configuration = ultrasound_tx_set_config, + .get_configuration = ultrasound_tx_get_config, + .reset = ultrasound_tx_reset, + .free = ultrasound_tx_free, +}; + +#if CONFIG_COMP_ULTRASOUND_TX_MODULE + +#include +#include +#include + +static const struct sof_man_module_manifest mod_manifest __section(".module") __used = + SOF_LLEXT_MODULE_MANIFEST("USND_TX", &ultrasound_tx_interface, 1, + SOF_REG_UUID(ultrasound_tx), 8); + +SOF_LLEXT_BUILDINFO; + +#else + +DECLARE_TR_CTX(ultrasound_tx_tr, SOF_UUID(ultrasound_tx_uuid), LOG_LEVEL_INFO); +DECLARE_MODULE_ADAPTER(ultrasound_tx_interface, ultrasound_tx_uuid, ultrasound_tx_tr); +SOF_MODULE_INIT(ultrasound_tx, sys_comp_module_ultrasound_tx_interface_init); + +#endif diff --git a/src/audio/ultrasound/ultrasound_tx.h b/src/audio/ultrasound/ultrasound_tx.h new file mode 100644 index 000000000000..494307598e37 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_tx.h @@ -0,0 +1,47 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Copyright(c) 2026 Intel Corporation. + */ + +#ifndef __SOF_AUDIO_ULTRASOUND_TX_H__ +#define __SOF_AUDIO_ULTRASOUND_TX_H__ + +#include +#include +#include +#include + +/* Default -18 dBFS in Q1.31: round(10^(-18/20) * 2^31) — inaudible at 20 kHz, strong DMIC SNR */ +#define US_TX_DEFAULT_AMPLITUDE_Q31 270349788 +#define US_TX_DEFAULT_CARRIER_HZ 20000 +#define US_TX_DEFAULT_RAMP_MS 10 + +/* Approach B default low-power duty-cycling window (96 ms burst every 250 ms = 38.4% duty) */ +#define US_TX_LP_DUTY_PERIOD_MS 250 +#define US_TX_LP_DUTY_ON_MS 96 + +struct ultrasound_tx_data { + struct sof_ultrasound_tx_config cfg; + uint32_t sample_rate; + uint32_t channels; + uint32_t frame_bytes; + enum sof_ipc_frame format; + bool is_standalone; + + uint32_t phase[SOF_ULTRASOUND_MAX_CHANNELS]; + uint32_t phase_inc[SOF_ULTRASOUND_MAX_CHANNELS]; + int32_t env_q31; + int32_t target_env_q31; + int32_t ramp_step_q31; + + /* Approach B click-free duty-cycle burst generator */ + uint32_t duty_period_samples; + uint32_t duty_on_samples; + uint32_t duty_sample_pos; + uint32_t duty_bursts; + uint64_t frames_generated; + bool last_boosted; + bool boost_logged; +}; + +#endif /* __SOF_AUDIO_ULTRASOUND_TX_H__ */ diff --git a/src/audio/ultrasound/ultrasound_tx.toml b/src/audio/ultrasound/ultrasound_tx.toml new file mode 100644 index 000000000000..8251c31d3fa4 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_tx.toml @@ -0,0 +1,21 @@ +#ifndef LOAD_TYPE +#define LOAD_TYPE "0" +#endif + + REM # Ultrasound TX carrier generator module config + [[module.entry]] + name = "USND_TX" + uuid = UUIDREG_STR_ULTRASOUND_TX + affinity_mask = "0x1" + instance_count = "8" + domain_types = "0" + load_type = LOAD_TYPE + module_type = "9" + auto_start = "0" + sched_caps = [1, 0x00008000] + REM # pin = [dir, type, sample rate, size, container, channel-cfg] + pin = [0, 0, 0xfeef, 0xf, 0xf, 0x45ff, 1, 0, 0xfeef, 0xf, 0xf, 0x1ff] + REM # mod_cfg [PAR_0 PAR_1 PAR_2 PAR_3 IS_BYTES CPS IBS OBS MOD_FLAGS CPC OBLS] + mod_cfg = [0, 0, 0, 0, 4096, 1000000, 128, 128, 0, 0, 0] + + index = __COUNTER__ diff --git a/src/include/ipc4/header.h b/src/include/ipc4/header.h index 3f71a2e9cf4c..cfe135f46d02 100644 --- a/src/include/ipc4/header.h +++ b/src/include/ipc4/header.h @@ -208,6 +208,8 @@ struct ipc4_message_reply { #define SOF_IPC4_NOTIFY_MODULE_EVENTID_ALSA_MAGIC_VAL ((uint32_t)0xA15A << 16) /** Magic event ID prefix for compressed audio stream notifications (0xC0C00000). */ #define SOF_IPC4_NOTIFY_MODULE_EVENTID_COMPR_MAGIC_VAL ((uint32_t)0xC0C0 << 16) +/** Magic event ID prefix for ultrasonic gesture/presence notifications (0x6E570000). */ +#define SOF_IPC4_NOTIFY_MODULE_EVENTID_GESTURE_MAGIC_VAL ((uint32_t)0x6E57U << 16) /** * \brief Generic per-channel control value mapping. diff --git a/src/include/ipc4/notification.h b/src/include/ipc4/notification.h index c2a55dd32284..bcfd9bd16154 100644 --- a/src/include/ipc4/notification.h +++ b/src/include/ipc4/notification.h @@ -299,6 +299,33 @@ void send_mixer_underrun_notif_msg(uint32_t resource_id, uint32_t eos_flag, uint */ void ipc4_update_notification_mask(uint32_t ntfy_mask, uint32_t enabled_mask); +/** + * \brief Send generic IPC4 module notification message to host. + * \ingroup ipc4_notification_api + * \param module_id Originator module ID. + * \param instance_id Originator module instance ID. + * \param event_id Module-specific event identifier (including magic prefix). + * \param data Pointer to event payload bytes. + * \param data_size Size of event payload in bytes. + * \return True if dispatched, false if pool exhausted or payload too large. + */ +bool send_module_notif_msg(uint16_t module_id, uint16_t instance_id, + uint32_t event_id, const void *data, uint32_t data_size); + +/** + * \brief Update shared in-DSP ultrasonic presence state for TX duty-cycle boosting. + * \ingroup ipc4_notification_api + * \param present True when user/hand presence is active, false when lost. + */ +void ultrasound_set_presence(bool present); + +/** + * \brief Query shared in-DSP ultrasonic presence state. + * \ingroup ipc4_notification_api + * \return True if ultrasonic RX currently reports presence active. + */ +bool ultrasound_get_presence(void); + #if defined(__ZEPHYR__) && defined(CONFIG_SOF_FULL_ZEPHYR_APPLICATION) /** diff --git a/src/include/user/ultrasound.h b/src/include/user/ultrasound.h new file mode 100644 index 000000000000..4a5cbdaf1e6d --- /dev/null +++ b/src/include/user/ultrasound.h @@ -0,0 +1,94 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Copyright(c) 2026 Intel Corporation. + */ + +#ifndef __USER_ULTRASOUND_H__ +#define __USER_ULTRASOUND_H__ + +#include + +#define SOF_ULTRASOUND_ABI_VERSION 1 +#define SOF_ULTRASOUND_MAX_CHANNELS 2 + +/* Lower 16 bits of event_id (upper 16 bits = SOF_IPC4_NOTIFY_MODULE_EVENTID_GESTURE_MAGIC_VAL) */ +#define SOF_US_EVENT_SUBTYPE_GESTURE 1 +#define SOF_US_EVENT_SUBTYPE_PRESENCE 2 + +/* IPC4 LARGE_CONFIG parameter IDs */ +#define SOF_US_TX_PARAM_CONFIG 1 +#define SOF_US_RX_PARAM_CONFIG 1 + +/* ALSA switch control IDs */ +#define SOF_US_TX_CTL_BYPASS 0 +#define SOF_US_TX_CTL_LOW_POWER_DUTY 1 +#define SOF_US_RX_CTL_BYPASS 0 +#define SOF_US_RX_CTL_DIAG_DUMP 1 + +/* TX operating modes */ +#define SOF_US_TX_MODE_BYPASS 0 +#define SOF_US_TX_MODE_ADDITIVE 1 +#define SOF_US_TX_MODE_REPLACE 2 + +/** + * enum sof_ultrasound_event_type - Detected ultrasonic gesture / presence event + */ +enum sof_ultrasound_event_type { + SOF_US_EVT_NONE = 0, + SOF_US_EVT_PUSH = 1, + SOF_US_EVT_PULL = 2, + SOF_US_EVT_TAP = 3, + SOF_US_EVT_SWIPE_LEFT = 4, + SOF_US_EVT_SWIPE_RIGHT = 5, + SOF_US_EVT_PRESENCE_DETECTED = 6, + SOF_US_EVT_PRESENCE_LOST = 7, +}; + +/** + * struct sof_ultrasound_event - IPC4 notification payload carried in + * struct sof_ipc4_notify_module_data.event_data[] + */ +struct sof_ultrasound_event { + uint32_t version; /* SOF_ULTRASOUND_ABI_VERSION */ + uint32_t event_type; /* enum sof_ultrasound_event_type */ + int32_t doppler_mhz; /* signed peak Doppler shift in millihertz */ + int32_t velocity_mm_s; /* radial velocity in mm/s (+approach, -recede) */ + uint32_t confidence; /* 0..1000 (0.0% .. 100.0%) */ + uint32_t snr_db_q8; /* peak SNR above noise floor in Q24.8 dB */ + uint32_t carrier_hz; /* carrier frequency in Hz */ + uint32_t seq; /* monotonic sequence counter */ + uint64_t dsp_timestamp_us; /* monotonic DSP stream timestamp in us */ +} __attribute__((packed, aligned(4))); + +/** + * struct sof_ultrasound_tx_config - Runtime configuration for ultrasound_tx + */ +struct sof_ultrasound_tx_config { + uint32_t version; + uint32_t mode; /* SOF_US_TX_MODE_* */ + uint32_t carrier_hz[SOF_ULTRASOUND_MAX_CHANNELS]; /* Hz per channel (default 20000) */ + int32_t amplitude_q31; /* Q1.31 amplitude (default -18 dBFS) */ + uint32_t ramp_ms; /* fade-in/out duration in ms */ + uint32_t duty_period_ms; /* 0 = continuous, >0 = pulsed period ms */ + uint32_t duty_on_ms; /* active burst duration per period ms */ + uint32_t auto_boost_on_presence; /* 1 = force continuous on RX presence */ +} __attribute__((packed, aligned(4))); + +/** + * struct sof_ultrasound_rx_config - Runtime configuration for ultrasound_rx + */ +struct sof_ultrasound_rx_config { + uint32_t version; + uint32_t enable; /* 1 = active, 0 = bypass */ + uint32_t carrier_hz[SOF_ULTRASOUND_MAX_CHANNELS]; /* Hz per channel (default 20000) */ + uint32_t snr_threshold_q8; /* Q24.8 dB above noise floor (default 10 dB) */ + uint32_t min_peak_level; /* minimum FFT bin magnitude floor */ + uint32_t cooldown_ms; /* post-gesture debounce in ms */ + uint32_t tap_window_ms; /* max PUSH->PULL interval for TAP */ + uint32_t swipe_min_lag_ms; /* min stereo channel lag for swipe */ + uint32_t swipe_max_lag_ms; /* max stereo channel lag for swipe */ + uint32_t presence_timeout_ms; /* idle timeout before PRESENCE_LOST */ + uint32_t input_gain_shift; /* 0..4 extra post-CIC shift bits (default 2) */ +} __attribute__((packed, aligned(4))); + +#endif /* __USER_ULTRASOUND_H__ */ diff --git a/src/kernel/ipc/ipc4/notification.c b/src/kernel/ipc/ipc4/notification.c index 196771ecc0c4..168851184a70 100644 --- a/src/kernel/ipc/ipc4/notification.c +++ b/src/kernel/ipc/ipc4/notification.c @@ -9,8 +9,12 @@ #include #include #include +#include +#include #include #include +#include +#include #ifdef __ZEPHYR__ #include @@ -89,6 +93,53 @@ void ipc4_update_notification_mask(uint32_t ntfy_mask, uint32_t enabled_mask) notification_mask |= enabled_mask & ntfy_mask; } +bool send_module_notif_msg(uint16_t module_id, uint16_t instance_id, + uint32_t event_id, const void *data, uint32_t data_size) +{ + struct sof_ipc4_notify_module_data *mod_data; + union ipc4_notification_header header; + struct ipc_msg *msg; + size_t total_size = sizeof(*mod_data) + data_size; + + msg = ipc_notification_pool_get(total_size); + if (!msg) + return false; + + header.dat = 0; + header.r.notif_type = SOF_IPC4_MODULE_NOTIFICATION; + header.r.type = SOF_IPC4_GLB_NOTIFICATION; + header.r.rsp = SOF_IPC4_MESSAGE_DIR_MSG_REQUEST; + header.r.msg_tgt = SOF_IPC4_MESSAGE_TARGET_FW_GEN_MSG; + msg->header = header.dat; + msg->extension = 0; + + mod_data = msg->tx_data; + mod_data->instance_id = instance_id; + mod_data->module_id = module_id; + mod_data->event_id = event_id; + mod_data->event_data_size = data_size; + if (data && data_size) + memcpy_s(mod_data->event_data, data_size, data, data_size); + + ipc_msg_send(msg, msg->tx_data, false); + return true; +} +EXPORT_SYMBOL(send_module_notif_msg); + +static atomic_t g_ultrasound_presence; + +void ultrasound_set_presence(bool present) +{ + atomic_set(&g_ultrasound_presence, present ? 1 : 0); +} +EXPORT_SYMBOL(ultrasound_set_presence); + +bool ultrasound_get_presence(void) +{ + return atomic_read(&g_ultrasound_presence) != 0; +} +EXPORT_SYMBOL(ultrasound_get_presence); + #ifdef CONFIG_USERSPACE static inline bool z_vrfy_send_resource_notif(uint32_t resource_id, uint32_t event_type, uint32_t resource_type, void *data, diff --git a/src/kernel/ipc/notification_pool.c b/src/kernel/ipc/notification_pool.c index b3455bc601d4..d9dc18591c76 100644 --- a/src/kernel/ipc/notification_pool.c +++ b/src/kernel/ipc/notification_pool.c @@ -12,7 +12,7 @@ #include -#define NOTIFICATION_POOL_MAX_PAYLOAD_SIZE 40 /* IPC4 Resource Event needs 10dw */ +#define NOTIFICATION_POOL_MAX_PAYLOAD_SIZE 80 /* Covers IPC4 resource & module events */ #define NOTIFICATION_POOL_MAX_DEPTH 8 /* Maximum number of notifications * in the pool */ diff --git a/tools/rimage/config/ptl.toml.h b/tools/rimage/config/ptl.toml.h index cfa07c7c8806..d53f60a13267 100644 --- a/tools/rimage/config/ptl.toml.h +++ b/tools/rimage/config/ptl.toml.h @@ -209,5 +209,13 @@ index = __COUNTER__ #include