diff --git a/app/ultrasound.conf b/app/ultrasound.conf new file mode 100644 index 000000000000..5c939a4ae831 --- /dev/null +++ b/app/ultrasound.conf @@ -0,0 +1,5 @@ +CONFIG_COMP_ULTRASOUND_TX=m +CONFIG_COMP_ULTRASOUND_RX=m + +# Ensure enough kernel heap for authenticating external LLEXTs alongside LL userspace +CONFIG_SOF_ZEPHYR_HEAP_SIZE=0x80000 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..bf98223c066d 100644 --- a/src/audio/Kconfig +++ b/src/audio/Kconfig @@ -234,6 +234,7 @@ rsource "tdfb/Kconfig" rsource "template/Kconfig" rsource "tensorflow/Kconfig" rsource "tone/Kconfig" +rsource "ultrasound/Kconfig" rsource "up_down_mixer/Kconfig" rsource "volume/Kconfig" rsource "webrtc_vad/Kconfig" 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..a63669123993 --- /dev/null +++ b/src/audio/ultrasound/Kconfig @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: BSD-3-Clause + +config COMP_ULTRASOUND_TX + tristate "Ultrasonic carrier generator (TX) component" + depends on COMP_MODULE_ADAPTER && IPC_MAJOR_4 + select MATH_LUT_SINE_FIXED + 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, and supports hostless + generator mode with low-power duty cycling. + +config COMP_ULTRASOUND_RX + tristate "Ultrasonic Doppler gesture and presence detector (RX) component" + depends on COMP_MODULE_ADAPTER && IPC_MAJOR_4 + select BINARY_LOGARITHM_FIXED + select MATH_32BIT_FFT + select MATH_DECIBELS + select MATH_FFT + select MATH_LUT_SINE_FIXED + select MATH_WINDOW + select NUMBERS_NORM + select SQRT_FIXED + 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 to the + host client driver. 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..d892e864fd8f --- /dev/null +++ b/src/audio/ultrasound/ultrasound_dsp.h @@ -0,0 +1,100 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Copyright(c) 2026 Intel Corporation. + * + * Fixed-point DSP helpers for SOF ultrasonic gesture/presence sensing, + * built on SOF's math library (LUT trig, sqrt, norm, base-2 log). + */ + +#ifndef __SOF_AUDIO_ULTRASOUND_DSP_H__ +#define __SOF_AUDIO_ULTRASOUND_DSP_H__ + +#include +#include +#include +#include +#include +#include +#include + +#define US_FFT_SIZE 64 +#define US_FFT_LOG2 6 +#define US_BASEBAND_RATE_HZ 1000 + +/* 20 * log10(2) in Q16.16: round(6.0205999133 * 65536) */ +#define US_20_LOG10_2_Q16 394566LL + +/* Q1.15 sine from 32-bit phase [0, 2*pi) via SOF quarter-wave LUT (Q4.28 rad) */ +static inline int32_t us_sin_q15(uint32_t phase) +{ + int32_t w_q28 = (int32_t)(((uint64_t)phase * PI_MUL2_Q4_28) >> 32); + + return sofm_lut_sin_fixed_16b(w_q28); +} + +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); +} + +/* Complex magnitude sqrt(re^2 + im^2) using SOF norm_int32() and sofm_sqrt_int32() */ +static inline uint32_t us_mag_u32(int32_t re, int32_t im) +{ + uint32_t are = (re < 0) ? (uint32_t)(-(int64_t)re) : (uint32_t)re; + uint32_t aim = (im < 0) ? (uint32_t)(-(int64_t)im) : (uint32_t)im; + uint32_t peak = (are >= aim) ? are : aim; + int32_t nr, ni, arg; + uint32_t m_q30; + int shift; + + if (!peak) + return 0; + + /* Scale (re, im) so max(|nr|, |ni|) is in [2^29, 2^30], keeping arg in [2^26, 2^29] */ + if (peak >= 0x40000000U) { + shift = -1; + nr = re >> 1; + ni = im >> 1; + } else { + shift = norm_int32((int32_t)peak) - 1; + nr = (int32_t)((uint32_t)re << shift); + ni = (int32_t)((uint32_t)im << shift); + } + + /* (nr^2 + ni^2) / 2^32 in Q2.30 -> sofm_sqrt_int32() returns sqrt(nr^2 + ni^2) / 2 */ + arg = (int32_t)(((int64_t)nr * nr + (int64_t)ni * ni) >> 32); + m_q30 = (uint32_t)sofm_sqrt_int32(arg); + + if (shift > 1) + return (m_q30 + (1U << (shift - 2))) >> (shift - 1); + if (shift == 1) + return m_q30; + return m_q30 << (1 - shift); +} + +/* 20 * log10(peak / noise_floor) in Q24.8 dB using SOF base2_logarithm() (Q16.16) */ +static inline uint32_t us_snr_db_q8(uint32_t peak, uint32_t noise_floor) +{ + int32_t diff_q16; + + if (noise_floor < 1) + noise_floor = 1; + if (peak <= noise_floor) + return 0; + + diff_q16 = base2_logarithm(peak) - base2_logarithm(noise_floor); + if (diff_q16 <= 0) + return 0; + + return (uint32_t)(((int64_t)diff_q16 * US_20_LOG10_2_Q16 + (1LL << 23)) >> 24); +} + +#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..c04a3a283e3d --- /dev/null +++ b/src/audio/ultrasound/ultrasound_rx.c @@ -0,0 +1,1552 @@ +// 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 + +#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_mag_u32((int32_t)(cd->ch[0].dc_i_q8 >> 8), + (int32_t)(cd->ch[0].dc_q_q8 >> 8)); + dc1 = (cd->active_channels > 1) ? + us_mag_u32((int32_t)(cd->ch[1].dc_i_q8 >> 8), + (int32_t)(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_detector(struct ultrasound_rx_data *cd, bool reset_timestamps) +{ + uint32_t ch; + + memset(cd->ch, 0, sizeof(cd->ch)); + cd->decim_count = 0; + cd->hop_count = 0; + if (reset_timestamps) { + cd->total_frames = 0; + cd->bb_ms = 0; + } + cd->warmup_until_ms = cd->bb_ms + US_RX_WARMUP_MS; + cd->warmup_logged = false; + cd->present = false; + cd->presence_consec = 0; + cd->presence_start_ms = 0; + cd->last_activity_ms = 0; + cd->cooldown_until_ms = 0; + cd->tail_suppress_dir = 0; + cd->tail_quiet_hops = 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)); + + ultrasound_set_presence(false); + + 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_reset_state(struct ultrasound_rx_data *cd) +{ + ultrasound_rx_reset_detector(cd, true); +} + +struct us_rx_evt_meta { + uint32_t duration_ms; + int32_t displacement_mm; + int16_t pos_x_permille; + int16_t zc_lag_ms_q2; + uint32_t peak_mag; +}; + +static inline int32_t ultrasound_rx_doppler_to_vel_mm_s(int32_t doppler_mhz, uint32_t carrier_hz) +{ + if (!carrier_hz) + return 0; + + return (int32_t)(((int64_t)doppler_mhz * SPEED_OF_SOUND) / + (2LL * (int64_t)carrier_hz)); +} + +static int16_t ultrasound_rx_calc_pos_x(const struct ultrasound_rx_data *cd, + uint64_t w0, uint64_t w1) +{ + int64_t sum, diff, val; + + if (cd->active_channels < 2) + return 0; + + sum = (int64_t)w0 + (int64_t)w1; + if (sum <= 0) + return 0; + + diff = (int64_t)w1 - (int64_t)w0; + if (cd->cfg.flags & SOF_US_RX_FLAG_SWAP_LR) + diff = -diff; + + val = (diff * 1000LL) / sum; + if (val > 1000) + val = 1000; + else if (val < -1000) + val = -1000; + + return (int16_t)val; +} + +static uint16_t ultrasound_rx_calc_proximity(const struct ultrasound_rx_data *cd, + uint32_t peak_mag) +{ + uint32_t db_q8, base; + + if (!peak_mag) + return 0; + + base = MAX(cd->cfg.min_peak_level, 1U); + if (peak_mag <= base) + return 0; + + db_q8 = us_snr_db_q8(peak_mag, base); + return (uint16_t)MIN(1000U, (db_q8 * 1000U) / (55U << 8)); +} + +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, + const struct us_rx_evt_meta *meta) +{ + struct sof_ultrasound_event ev; + uint32_t subtype; + uint32_t event_id; + uint32_t conf; + int32_t vel_mm_s = ultrasound_rx_doppler_to_vel_mm_s(doppler_mhz, carrier_hz); + uint16_t prox = meta ? ultrasound_rx_calc_proximity(cd, meta->peak_mag) : 0; + + /* 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_EVENT_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; + ev.duration_ms = meta ? meta->duration_ms : 0; + ev.displacement_mm = meta ? meta->displacement_mm : 0; + ev.pos_x_permille = meta ? meta->pos_x_permille : 0; + ev.zc_lag_ms_q2 = meta ? meta->zc_lag_ms_q2 : 0; + ev.proximity = prox; + ev.reserved = 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 dur=%u ms disp=%d mm pos_x=%d prox=%u", + evt_type, ev.seq, doppler_mhz, vel_mm_s, + snr_db_q8 >> 8, ((snr_db_q8 & 0xFFU) * 100U) >> 8, conf, + ev.duration_ms, ev.displacement_mm, ev.pos_x_permille, ev.proximity); + + 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"); +} + +static void ultrasound_rx_analyze_channel(struct ultrasound_rx_data *cd, uint32_t ch_idx) +{ + struct us_rx_channel *c = &cd->ch[ch_idx]; + 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; + uint32_t max_abs = 0; + int pos_bin = 0, neg_bin = 0; + int k; + + /* Window oldest-to-newest 64 baseband samples with SOF 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 = cd->hann_win[k]; + int32_t r = (int32_t)(((int64_t)c->ring_i[idx] * w) >> 15); + int32_t im = (int32_t)(((int64_t)c->ring_q[idx] * w) >> 15); + uint32_t ar = (r < 0) ? (uint32_t)(-(int64_t)r) : (uint32_t)r; + uint32_t ai = (im < 0) ? (uint32_t)(-(int64_t)im) : (uint32_t)im; + + cd->fft_in[k].real = r; + cd->fft_in[k].imag = im; + if (ar > max_abs) + max_abs = ar; + if (ai > max_abs) + max_abs = ai; + } + + if (!max_abs) { + memset(mag, 0, sizeof(mag)); + } else { + /* + * Block-normalize into Q1.31 before SOF's 32-bit FFT (which scales + * input by 1/N internally) and undo net_shift = bshift - log2(N) to + * recover unscaled DFT magnitudes for min_peak_level comparison. + */ + int bshift = (max_abs >= 0x40000000U) ? 0 : norm_int32((int32_t)max_abs); + int net_shift = bshift - US_FFT_LOG2; + + if (bshift > 0) { + for (k = 0; k < US_FFT_SIZE; k++) { + struct icomplex32 *in = &cd->fft_in[k]; + + in->real = (int32_t)((uint32_t)in->real << bshift); + in->imag = (int32_t)((uint32_t)in->imag << bshift); + } + } + + fft_execute_32(cd->fft_plan, false); + + for (k = 0; k < US_FFT_SIZE; k++) { + uint32_t m = us_mag_u32(cd->fft_out[k].real, cd->fft_out[k].imag); + + if (net_shift > 0) { + mag[k] = (uint32_t)(((uint64_t)m + + (1ULL << (net_shift - 1))) >> net_shift); + } else if (net_shift < 0) { + uint64_t scaled = (uint64_t)m << (-net_shift); + + mag[k] = (scaled > UINT32_MAX) ? UINT32_MAX : (uint32_t)scaled; + } else { + mag[k] = m; + } + } + } + + /* + * Positive Doppler band: bins 2..16 (+31.25 Hz .. +250 Hz). + * Score each bin by excess ratio above both broadband floor and slow per-bin + * stationary background so steady narrowband clutter (cooling fans, board AM + * spurs) cannot mask transient hand reflections or trigger false gestures. + */ + uint64_t best_pos_ratio = 0; + uint64_t best_neg_ratio = 0; + + for (k = 2; k <= 16; k++) { + uint32_t floor_k = MAX(MAX(c->noise_floor_pos, c->bin_bg_q8[k] >> 8), 1U); + uint64_t ratio_q16 = ((uint64_t)mag[k] << 16) / floor_k; + + if (ratio_q16 > best_pos_ratio) { + best_pos_ratio = ratio_q16; + pos_mag = mag[k]; + pos_bin = k; + } + } + + /* Negative Doppler band: bins 48..62 (-250 Hz .. -31.25 Hz) */ + for (k = 48; k <= 62; k++) { + uint32_t floor_k = MAX(MAX(c->noise_floor_neg, c->bin_bg_q8[k] >> 8), 1U); + uint64_t ratio_q16 = ((uint64_t)mag[k] << 16) / floor_k; + + if (ratio_q16 > best_neg_ratio) { + best_neg_ratio = ratio_q16; + 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; + + /* + * Track steady-state per-sideband noise floor with slew-limited upward growth + * so wide-band Doppler smear from strong hand gestures cannot inflate one + * sideband's steady floor above the other or blind subsequent hops, while + * eff_nf = MAX(steady_nf, cur_nf) still provides instant broadband clap gating. + */ + if (c->noise_floor_pos == 0 || cd->bb_ms < cd->warmup_until_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 { + if (cur_nf_pos <= c->noise_floor_pos) { + c->noise_floor_pos -= (c->noise_floor_pos - cur_nf_pos) >> 4; + } else { + uint32_t step = (cur_nf_pos - c->noise_floor_pos) >> 4; + uint32_t cap = MAX(c->noise_floor_pos >> 5, 4U); + + c->noise_floor_pos += MIN(step, cap); + } + if (cur_nf_neg <= c->noise_floor_neg) { + c->noise_floor_neg -= (c->noise_floor_neg - cur_nf_neg) >> 4; + } else { + uint32_t step = (cur_nf_neg - c->noise_floor_neg) >> 4; + uint32_t cap = MAX(c->noise_floor_neg >> 5, 4U); + + c->noise_floor_neg += MIN(step, cap); + } + } + 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); + + uint32_t pos_bg = (pos_bin > 0) ? (c->bin_bg_q8[pos_bin] >> 8) : 1U; + uint32_t neg_bg = (neg_bin > 0) ? (c->bin_bg_q8[neg_bin] >> 8) : 1U; + uint32_t pos_floor = MAX(eff_nf_pos, pos_bg); + uint32_t neg_floor = MAX(eff_nf_neg, neg_bg); + uint32_t pos_rel_floor = MAX(MAX(c->noise_floor_pos, pos_bg), 1U); + uint32_t neg_rel_floor = MAX(MAX(c->noise_floor_neg, neg_bg), 1U); + uint32_t pos_rel_snr = 0, neg_rel_snr = 0; + + if (pos_bin > 0) { + pos_snr = us_snr_db_q8(pos_mag, pos_floor); + pos_rel_snr = us_snr_db_q8(pos_mag, pos_rel_floor); + } + if (neg_bin > 0) { + neg_snr = us_snr_db_q8(neg_mag, neg_floor); + neg_rel_snr = us_snr_db_q8(neg_mag, neg_rel_floor); + } + + { + uint32_t pe = (pos_mag > pos_floor) ? (pos_mag - pos_floor) : 0U; + uint32_t ne = (neg_mag > neg_floor) ? (neg_mag - neg_floor) : 0U; + + c->hop_excess_mag = MAX(pe, ne); + } + + /* + * Update per-bin stationary background tracker after scoring the current hop: + * - Warmup: fast convergence (~128 ms tau) to learn steady fans/board spurs. + * - Steady state: fast downward recovery (~0.5 s tau) and strictly slew-limited + * upward tracking (~steady_nf/32 per hop) so strong transient hand gestures + * never inflate bin_bg and blind subsequent gestures, while continuous + * narrowband fans/spurs are still notched out cleanly. + */ + { + bool in_warmup = (cd->bb_ms < cd->warmup_until_ms); + uint32_t max_up_pos_q8 = MAX(c->noise_floor_pos << 3, 1024U); + uint32_t max_up_neg_q8 = MAX(c->noise_floor_neg << 3, 1024U); + + for (k = 2; k <= 16; k++) { + uint64_t m_q8 = (uint64_t)mag[k] << 8; + uint32_t clamped = (m_q8 > UINT32_MAX) ? UINT32_MAX : (uint32_t)m_q8; + uint32_t cur = c->bin_bg_q8[k]; + + if (cur == 0) { + c->bin_bg_q8[k] = clamped; + } else if (in_warmup) { + c->bin_bg_q8[k] = (uint32_t)((int64_t)cur + + (((int64_t)clamped - (int64_t)cur) >> 3)); + } else if (clamped <= cur) { + c->bin_bg_q8[k] = cur - ((cur - clamped) >> 5); + } else { + uint32_t step = (clamped - cur) >> 7; + + if (step > max_up_pos_q8) + step = max_up_pos_q8; + c->bin_bg_q8[k] = (cur > UINT32_MAX - step) ? + UINT32_MAX : (cur + step); + } + } + for (k = 48; k <= 62; k++) { + uint64_t m_q8 = (uint64_t)mag[k] << 8; + uint32_t clamped = (m_q8 > UINT32_MAX) ? UINT32_MAX : (uint32_t)m_q8; + uint32_t cur = c->bin_bg_q8[k]; + + if (cur == 0) { + c->bin_bg_q8[k] = clamped; + } else if (in_warmup) { + c->bin_bg_q8[k] = (uint32_t)((int64_t)cur + + (((int64_t)clamped - (int64_t)cur) >> 3)); + } else if (clamped <= cur) { + c->bin_bg_q8[k] = cur - ((cur - clamped) >> 5); + } else { + uint32_t step = (clamped - cur) >> 7; + + if (step > max_up_neg_q8) + step = max_up_neg_q8; + c->bin_bg_q8[k] = (cur > UINT32_MAX - step) ? + UINT32_MAX : (cur + step); + } + } + } + + c->hop_dir = 0; + c->hop_doppler_mhz = 0; + c->hop_snr_db_q8 = 0; + c->hop_peak_mag = 0; + + /* + * Compare sidebands using steady-floor normalized SNR (pos_rel_snr vs neg_rel_snr) + * so wide-band Doppler spread on the active sideband cannot let a weak opposite-side + * artifact invert hop_dir, while still requiring >= snr_threshold_q8 against the + * instantaneous broadband floor (eff_nf) and >= 3.0 dB sideband asymmetry. + */ + if (pos_rel_snr >= neg_rel_snr && pos_bin > 0) { + if (pos_mag >= cd->cfg.min_peak_level && + pos_snr >= cd->cfg.snr_threshold_q8 && + pos_rel_snr >= neg_rel_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_rel_snr > pos_rel_snr && neg_bin > 0) { + if (neg_mag >= cd->cfg.min_peak_level && + neg_snr >= cd->cfg.snr_threshold_q8 && + neg_rel_snr >= pos_rel_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].pos_hops = 0; + cd->ch[ch].neg_hops = 0; + cd->ch[ch].had_pos = false; + cd->ch[ch].zc_valid = false; + } +} + +static inline bool ultrasound_rx_push_qualified(const struct ultrasound_rx_data *cd) +{ + return cd->pending_push.active && + cd->pending_push.active_hops >= 6U && + cd->pending_push.peak_doppler_mhz >= 25000 && + (cd->active_channels < 2 || cd->pending_push.both_ch_hops >= 3U); +} + +static void ultrasound_rx_emit_pending_push(struct processing_module *mod, + struct ultrasound_rx_data *cd, + uint64_t now_ms, + int8_t tail_dir) +{ + struct us_rx_evt_meta meta = { + .duration_ms = (uint32_t)(cd->pending_push.last_active_ms - + cd->pending_push.start_ms + US_RX_HOP_SAMPLES), + .displacement_mm = (int32_t)(cd->pending_push.disp_um / 1000LL), + .pos_x_permille = ultrasound_rx_calc_pos_x( + cd, cd->pending_push.ch_ex_sum[0], + cd->pending_push.ch_ex_sum[1]), + .peak_mag = cd->pending_push.peak_mag, + }; + + 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, &meta); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + cd->tail_suppress_dir = tail_dir; + cd->tail_quiet_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_peak_mag = 0; + uint32_t best_carrier = cd->cfg.carrier_hz[0]; + bool any_activity = false; + bool coherent_activity = false; + bool zc_pending = false; + uint32_t push_quiet_ms; + 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_peak_mag = cd->ch[ch].hop_peak_mag; + best_carrier = cd->cfg.carrier_hz[ch]; + } + } + } + + /* Allow CIC + DC blocker + noise floor to settle at stream startup or re-enable */ + if (now_ms < cd->warmup_until_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) { + coherent_activity = true; + cd->last_activity_ms = now_ms; + } + + if (!cd->present && cd->presence_consec >= 3) { + struct us_rx_evt_meta meta = { + .pos_x_permille = ultrasound_rx_calc_pos_x( + cd, cd->ch[0].hop_excess_mag, + cd->active_channels > 1 ? cd->ch[1].hop_excess_mag : 0), + .peak_mag = best_peak_mag, + }; + + cd->present = true; + cd->presence_start_ms = now_ms; + ultrasound_set_presence(true); + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PRESENCE_DETECTED, + best_doppler, best_snr, best_carrier, &meta); + } + } else { + cd->presence_consec = 0; + } + + if (cd->present && !coherent_activity && + (now_ms - cd->last_activity_ms) >= cd->cfg.presence_timeout_ms) { + struct us_rx_evt_meta meta = { + .duration_ms = (cd->presence_start_ms && now_ms >= cd->presence_start_ms) ? + (uint32_t)(now_ms - cd->presence_start_ms) : 0U, + }; + + cd->present = false; + cd->presence_start_ms = 0; + ultrasound_set_presence(false); + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PRESENCE_LOST, + 0, 0, cd->cfg.carrier_hz[0], &meta); + } + + /* + * Track continuous trailing motion after emitting a gesture so a single long + * pull or swipe exit tail cannot re-fire duplicate PULL events once cooldown + * elapses; re-arms after 4 hops (64 ms) without that trailing direction. + */ + if (cd->tail_suppress_dir != 0) { + if (best_dir == cd->tail_suppress_dir) { + cd->tail_quiet_hops = 0; + } else { + cd->tail_quiet_hops++; + if (cd->tail_quiet_hops >= 4) { + cd->tail_suppress_dir = 0; + cd->tail_quiet_hops = 0; + } + } + } + + /* 2. Cooldown guard & continuous-stroke tail suppression */ + if (now_ms < cd->cooldown_until_ms || + (cd->tail_suppress_dir != 0 && best_dir == cd->tail_suppress_dir)) { + ultrasound_rx_clear_gestures(cd); + return; + } + + /* + * 3. Stereo (+ -> -) Doppler zero-crossing swipe & tap classifier. + * As a hand swipes laterally past mic 0 then mic 1, the ellipsoidal path length + * (tx -> hand -> mic_i) reaches its minimum (Doppler crosses + -> -) at mic 0 + * before mic 1 (zc_lag = t_zc1 - t_zc0 > 0 for L->R, < 0 for R->L), whereas a + * radial Tap crosses simultaneously on both mics (|zc_lag| <= 6 ms). + * Unlike onset/envelope lag, Doppler zero-crossing time is invariant to acoustic + * standing-wave amplitude fringes and never misfires on pure Push/Pull strokes. + */ + if (cd->active_channels == 2) { + for (ch = 0; ch < 2; ch++) { + struct us_rx_channel *c = &cd->ch[ch]; + + if (c->hop_dir > 0) { + int64_t hop_disp = (int64_t)ultrasound_rx_doppler_to_vel_mm_s( + c->hop_doppler_mhz, cd->cfg.carrier_hz[ch]) * + US_RX_HOP_SAMPLES; + + c->pos_hops++; + c->neg_hops = 0; + if (c->pos_hops >= 2 || (c->had_pos && !c->zc_valid)) { + if (!c->had_pos || c->zc_valid) { + c->first_pos_ms = (now_ms >= US_RX_HOP_SAMPLES) ? + (now_ms - US_RX_HOP_SAMPLES) : 0; + c->last_pos_snr = c->hop_snr_db_q8; + c->peak_pos_mhz = c->hop_doppler_mhz; + c->pos_peak_mag = c->hop_peak_mag; + c->pos_ex_sum = c->hop_excess_mag; + c->pos_disp_um = 2LL * hop_disp; + } else { + c->last_pos_snr = MAX(c->last_pos_snr, + c->hop_snr_db_q8); + if (c->hop_doppler_mhz > c->peak_pos_mhz) + c->peak_pos_mhz = c->hop_doppler_mhz; + if (c->hop_peak_mag > c->pos_peak_mag) + c->pos_peak_mag = c->hop_peak_mag; + c->pos_ex_sum += c->hop_excess_mag; + c->pos_disp_um += hop_disp; + } + c->had_pos = true; + c->last_pos_ms = now_ms; + c->last_pos_mhz = c->hop_doppler_mhz; + c->zc_valid = false; + } + } else if (c->hop_dir < 0) { + int32_t neg_abs = -c->hop_doppler_mhz; + + c->pos_hops = 0; + c->neg_hops++; + if (c->neg_hops == 1) { + c->first_neg_ms = now_ms; + c->first_neg_mhz = c->hop_doppler_mhz; + c->peak_neg_mhz = neg_abs; + } else if (neg_abs > c->peak_neg_mhz) { + c->peak_neg_mhz = neg_abs; + } + if (c->had_pos && !c->zc_valid && c->neg_hops >= 2) { + uint64_t gap = c->first_neg_ms - c->last_pos_ms; + uint32_t max_gap = MIN(cd->cfg.tap_window_ms, 160U); + + if (gap > 0 && gap <= max_gap) { + uint64_t fp = (uint64_t)MAX(c->last_pos_mhz, 1); + uint64_t fn = (uint64_t)MAX(-c->first_neg_mhz, 1); + + c->zc_ms_q2 = (c->last_pos_ms << 2) + + ((gap << 2) * fp) / (fp + fn); + c->zc_valid = true; + c->zc_confirm_ms = now_ms; + c->zc_gap_ms = (uint32_t)gap; + c->zc_snr_db_q8 = MAX(c->last_pos_snr, + c->hop_snr_db_q8); + c->zc_peak_mag = MAX(c->pos_peak_mag, + c->hop_peak_mag); + } + } + } else { + c->pos_hops = 0; + c->neg_hops = 0; + } + + if (c->had_pos && !c->zc_valid && + (now_ms - c->last_pos_ms) > cd->cfg.tap_window_ms) + c->had_pos = false; + } + + if (cd->ch[0].zc_valid && cd->ch[1].zc_valid) { + int64_t lag_q2 = (int64_t)cd->ch[1].zc_ms_q2 - (int64_t)cd->ch[0].zc_ms_q2; + int64_t abs_lag_q2 = (lag_q2 < 0) ? -lag_q2 : lag_q2; + int64_t min_lag_q2 = (int64_t)cd->cfg.swipe_min_lag_ms << 2; + int64_t max_lag_q2 = (int64_t)cd->cfg.swipe_max_lag_ms << 2; + int64_t tap_max_lag_q2 = (int64_t)MIN(cd->cfg.swipe_min_lag_ms, 6U) << 2; + int32_t avg_doppler = (cd->ch[0].peak_pos_mhz + + cd->ch[1].peak_pos_mhz) / 2; + uint32_t max_snr = MAX(cd->ch[0].zc_snr_db_q8, cd->ch[1].zc_snr_db_q8); + uint32_t min_snr = MIN(cd->ch[0].zc_snr_db_q8, cd->ch[1].zc_snr_db_q8); + uint64_t start_ms = MIN(cd->ch[0].first_pos_ms, cd->ch[1].first_pos_ms); + enum sof_ultrasound_event_type evt = SOF_US_EVT_NONE; + uint32_t carrier = best_carrier; + + if (cd->cfg.flags & SOF_US_RX_FLAG_SWAP_LR) + lag_q2 = -lag_q2; + + if (lag_q2 >= min_lag_q2 && lag_q2 <= max_lag_q2) { + evt = SOF_US_EVT_SWIPE_RIGHT; + carrier = cd->cfg.carrier_hz[0]; + } else if (-lag_q2 >= min_lag_q2 && -lag_q2 <= max_lag_q2) { + evt = SOF_US_EVT_SWIPE_LEFT; + carrier = cd->cfg.carrier_hz[1]; + } else if (abs_lag_q2 <= tap_max_lag_q2 && + cd->ch[0].peak_pos_mhz >= 40000 && + cd->ch[1].peak_pos_mhz >= 40000 && + cd->ch[0].peak_neg_mhz >= 35000 && + cd->ch[1].peak_neg_mhz >= 35000 && + min_snr >= cd->cfg.snr_threshold_q8 + (4U << 8) && + (!cd->pending_push.active || + cd->pending_push.active_hops <= 10U)) { + /* + * Deliberate radial TAP: brief in-and-back jab (<= 160 ms + * approach), simultaneous crossing on both mics (<= 6 ms lag), + * brisk velocity (>= 40/35 Hz), and +4 dB SNR margin. + */ + evt = SOF_US_EVT_TAP; + } + + if (evt != SOF_US_EVT_NONE) { + int64_t clamped_lag = lag_q2; + + if (clamped_lag > INT16_MAX) + clamped_lag = INT16_MAX; + else if (clamped_lag < INT16_MIN) + clamped_lag = INT16_MIN; + + struct us_rx_evt_meta meta = { + .duration_ms = (now_ms >= start_ms) ? + (uint32_t)(now_ms - start_ms + US_RX_HOP_SAMPLES) : + US_RX_HOP_SAMPLES, + .displacement_mm = (int32_t)(((cd->ch[0].pos_disp_um + + cd->ch[1].pos_disp_um) / 2LL) / + 1000LL), + .pos_x_permille = ultrasound_rx_calc_pos_x( + cd, cd->ch[0].pos_ex_sum, cd->ch[1].pos_ex_sum), + .zc_lag_ms_q2 = (int16_t)clamped_lag, + .peak_mag = MAX(cd->ch[0].zc_peak_mag, + cd->ch[1].zc_peak_mag), + }; + + ultrasound_rx_emit_event(mod, cd, evt, avg_doppler, max_snr, + carrier, &meta); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + cd->tail_suppress_dir = -1; + cd->tail_quiet_hops = 0; + return; + } + + /* + * Radial deceleration/recoil after a sustained PUSH (|lag| < swipe_min_lag, + * not a brisk TAP): emit PUSH and suppress trailing withdrawal rather than + * discarding the completed push stroke. + */ + if (abs_lag_q2 < min_lag_q2 && ultrasound_rx_push_qualified(cd)) { + ultrasound_rx_emit_pending_push(mod, cd, now_ms, -1); + return; + } + + /* Ambiguous or sluggish crossing: suppress without firing false TAP */ + ultrasound_rx_clear_gestures(cd); + return; + } + + if (cd->ch[0].zc_valid != cd->ch[1].zc_valid) { + struct us_rx_channel *c_done = cd->ch[0].zc_valid ? + &cd->ch[0] : &cd->ch[1]; + struct us_rx_channel *c_wait = cd->ch[0].zc_valid ? + &cd->ch[1] : &cd->ch[0]; + uint32_t wait_limit = c_wait->had_pos ? cd->cfg.swipe_max_lag_ms : 128U; + + if ((now_ms - c_done->zc_confirm_ms) < wait_limit) { + zc_pending = true; + } else { + /* + * A 1-channel (+ -> -) wobble after a sustained 2-channel PUSH + * should still emit the completed PUSH rather than dropping it. + */ + if (ultrasound_rx_push_qualified(cd)) { + ultrasound_rx_emit_pending_push(mod, cd, now_ms, -1); + return; + } + c_done->zc_valid = false; + c_done->had_pos = false; + cd->pending_push.active = false; + } + } + } + + /* 4. Push / Pull / Mono-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) { + bool stereo_agree = (cd->active_channels < 2) || + (cd->ch[0].hop_dir == cd->stroke_dir && + cd->ch[1].hop_dir == cd->stroke_dir); + int64_t hop_disp = (int64_t)ultrasound_rx_doppler_to_vel_mm_s( + best_doppler, best_carrier) * US_RX_HOP_SAMPLES; + uint64_t ex0 = cd->ch[0].hop_excess_mag; + uint64_t ex1 = (cd->active_channels > 1) ? cd->ch[1].hop_excess_mag : 0; + + if (cd->stroke_dir > 0) { + if (!cd->pending_push.active) { + /* + * If a deliberate PULL already qualified and the user reverses + * forward before the 64 ms quiet timeout expires, emit the PULL + * immediately instead of dropping it. + */ + if (cd->pending_pull.active && !zc_pending && + cd->pending_pull.active_hops >= 8U && + cd->pending_pull.peak_doppler_mhz <= -30000 && + (cd->active_channels < 2 || cd->pending_pull.both_ch_hops >= 4U)) { + struct us_rx_evt_meta meta = { + .duration_ms = (uint32_t)(cd->pending_pull.last_active_ms - + cd->pending_pull.start_ms + US_RX_HOP_SAMPLES), + .displacement_mm = (int32_t)(cd->pending_pull.disp_um / 1000LL), + .pos_x_permille = ultrasound_rx_calc_pos_x( + cd, cd->pending_pull.ch_ex_sum[0], + cd->pending_pull.ch_ex_sum[1]), + .peak_mag = cd->pending_pull.peak_mag, + }; + + 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, &meta); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + cd->tail_suppress_dir = -1; + cd->tail_quiet_hops = 0; + return; + } + + uint64_t back = (uint64_t)(cd->stroke_hops - 1U) * + US_RX_HOP_SAMPLES; + + cd->pending_push.active = true; + cd->pending_push.start_ms = (now_ms >= back) ? (now_ms - back) : 0; + cd->pending_push.last_active_ms = now_ms; + cd->pending_push.active_hops = cd->stroke_hops; + cd->pending_push.both_ch_hops = stereo_agree ? cd->stroke_hops : 0; + cd->pending_push.peak_doppler_mhz = best_doppler; + cd->pending_push.peak_snr_db_q8 = best_snr; + cd->pending_push.peak_mag = best_peak_mag; + cd->pending_push.carrier_hz = best_carrier; + cd->pending_push.disp_um = (int64_t)cd->stroke_hops * hop_disp; + cd->pending_push.ch_ex_sum[0] = ex0; + cd->pending_push.ch_ex_sum[1] = ex1; + cd->pending_pull.active = false; + } else { + cd->pending_push.last_active_ms = now_ms; + cd->pending_push.active_hops++; + if (stereo_agree) + cd->pending_push.both_ch_hops++; + if (best_doppler > cd->pending_push.peak_doppler_mhz) + cd->pending_push.peak_doppler_mhz = best_doppler; + if (best_snr > cd->pending_push.peak_snr_db_q8) { + cd->pending_push.peak_snr_db_q8 = best_snr; + cd->pending_push.carrier_hz = best_carrier; + } + if (best_peak_mag > cd->pending_push.peak_mag) + cd->pending_push.peak_mag = best_peak_mag; + cd->pending_push.disp_um += hop_disp; + cd->pending_push.ch_ex_sum[0] += ex0; + cd->pending_push.ch_ex_sum[1] += ex1; + } + } else { + if (cd->active_channels == 1 && cd->pending_push.active && + (now_ms - cd->pending_push.last_active_ms) <= + MIN(cd->cfg.tap_window_ms, 160U) && + cd->pending_push.peak_doppler_mhz >= 40000 && + -best_doppler >= 35000) { + int32_t peak_d = cd->pending_push.peak_doppler_mhz; + uint32_t peak_s = MAX(cd->pending_push.peak_snr_db_q8, best_snr); + struct us_rx_evt_meta meta = { + .duration_ms = (uint32_t)(now_ms - + cd->pending_push.start_ms + US_RX_HOP_SAMPLES), + .displacement_mm = (int32_t)(cd->pending_push.disp_um / + 1000LL), + .peak_mag = MAX(cd->pending_push.peak_mag, best_peak_mag), + }; + + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_TAP, + peak_d, peak_s, best_carrier, &meta); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + cd->tail_suppress_dir = -1; + cd->tail_quiet_hops = 0; + return; + } + + if (!cd->pending_pull.active && !cd->pending_push.active) { + uint64_t back = (uint64_t)(cd->stroke_hops - 1U) * + US_RX_HOP_SAMPLES; + + cd->pending_pull.active = true; + cd->pending_pull.start_ms = (now_ms >= back) ? (now_ms - back) : 0; + cd->pending_pull.last_active_ms = now_ms; + cd->pending_pull.active_hops = cd->stroke_hops; + cd->pending_pull.both_ch_hops = stereo_agree ? cd->stroke_hops : 0; + cd->pending_pull.peak_doppler_mhz = best_doppler; + cd->pending_pull.peak_snr_db_q8 = best_snr; + cd->pending_pull.peak_mag = best_peak_mag; + cd->pending_pull.carrier_hz = best_carrier; + cd->pending_pull.disp_um = (int64_t)cd->stroke_hops * hop_disp; + cd->pending_pull.ch_ex_sum[0] = ex0; + cd->pending_pull.ch_ex_sum[1] = ex1; + } else if (cd->pending_pull.active) { + cd->pending_pull.last_active_ms = now_ms; + cd->pending_pull.active_hops++; + if (stereo_agree) + cd->pending_pull.both_ch_hops++; + if (best_doppler < cd->pending_pull.peak_doppler_mhz) + cd->pending_pull.peak_doppler_mhz = best_doppler; + if (best_snr > cd->pending_pull.peak_snr_db_q8) { + cd->pending_pull.peak_snr_db_q8 = best_snr; + cd->pending_pull.carrier_hz = best_carrier; + } + if (best_peak_mag > cd->pending_pull.peak_mag) + cd->pending_pull.peak_mag = best_peak_mag; + cd->pending_pull.disp_um += hop_disp; + cd->pending_pull.ch_ex_sum[0] += ex0; + cd->pending_pull.ch_ex_sum[1] += ex1; + } + } + } + + /* + * Deferred PUSH emission: wait briefly (~96..100 ms) after approach pauses without + * reversing (avoids firing PUSH mid-swipe during a slow approach lead-in) and require + * >= 6 active hops (~96 ms, accounting for far-to-near 1/R^4 onset), peak >= 25 Hz, + * and stereo agreement >= 3 hops. + */ + push_quiet_ms = MIN(MAX(cd->cfg.tap_window_ms / 3U, 80U), 128U); + if (cd->pending_push.active && !zc_pending && + ((now_ms - cd->pending_push.last_active_ms) >= push_quiet_ms || + (now_ms - cd->pending_push.start_ms) >= 1200U)) { + if (ultrasound_rx_push_qualified(cd)) { + ultrasound_rx_emit_pending_push(mod, cd, now_ms, 1); + return; + } + cd->pending_push.active = false; + } + + /* + * Deliberate PULL emission: wait until recede pauses (64 ms) or hits 1200 ms cap + * so full pull duration and integrated radial displacement are captured, requiring + * >= 8 active hops (~128 ms), peak <= -30 Hz, and stereo agreement >= 4 hops. + */ + if (cd->pending_pull.active && !zc_pending && + ((now_ms - cd->pending_pull.last_active_ms) >= 64U || + (now_ms - cd->pending_pull.start_ms) >= 1200U)) { + if (cd->pending_pull.active_hops >= 8U && + cd->pending_pull.peak_doppler_mhz <= -30000 && + (cd->active_channels < 2 || cd->pending_pull.both_ch_hops >= 4U)) { + struct us_rx_evt_meta meta = { + .duration_ms = (uint32_t)(cd->pending_pull.last_active_ms - + cd->pending_pull.start_ms + US_RX_HOP_SAMPLES), + .displacement_mm = (int32_t)(cd->pending_pull.disp_um / 1000LL), + .pos_x_permille = ultrasound_rx_calc_pos_x( + cd, cd->pending_pull.ch_ex_sum[0], + cd->pending_pull.ch_ex_sum[1]), + .peak_mag = cd->pending_pull.peak_mag, + }; + + 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, &meta); + ultrasound_rx_clear_gestures(cd); + cd->cooldown_until_ms = now_ms + cd->cfg.cooldown_ms; + cd->tail_suppress_dir = -1; + cd->tail_quiet_hops = 0; + return; + } + cd->pending_pull.active = false; + } +} + +/* 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 (modular uint64_t avoids signed UB) */ + c->int1_i += (uint64_t)mix_i; + c->int2_i += c->int1_i; + c->int1_q += (uint64_t)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]; + uint64_t c1_i = c->int2_i - c->comb1_i; + uint64_t c2_i = c1_i - c->comb2_i; + uint64_t c1_q = c->int2_q - c->comb1_q; + uint64_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)(((int64_t)c2_i / d2) >> shift_right); + raw_q = (int32_t)(((int64_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; + size_t 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) { + source_release_data(source, 0); + 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; + size_t 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) { + source_release_data(source, 0); + 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 ? sign_extend_s24(sample) : (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_alloc_align(mod, sizeof(*cd), 8); + if (!cd) + return -ENOMEM; + memset(cd, 0, sizeof(*cd)); + + win_hann_16b(cd->hann_win, US_FFT_SIZE); + cd->fft_plan = mod_fft_plan_new(mod, cd->fft_in, cd->fft_out, US_FFT_SIZE, 32); + if (!cd->fft_plan) { + mod_free(mod, 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; + + 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; + } + + 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) + return source_to_sink_copy(source, sink, true, frames * cd->frame_bytes); + return source_drop_data(source, frames * cd->frame_bytes); + } + + 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; + } +} + +static void ultrasound_rx_handle_bypass(struct processing_module *mod, + struct ultrasound_rx_data *cd) +{ + if (cd->present) { + struct us_rx_evt_meta meta = { + .duration_ms = (cd->presence_start_ms && cd->bb_ms >= cd->presence_start_ms) ? + (uint32_t)(cd->bb_ms - cd->presence_start_ms) : 0U, + }; + + cd->present = false; + cd->presence_start_ms = 0; + ultrasound_set_presence(false); + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PRESENCE_LOST, + 0, 0, cd->cfg.carrier_hz[0], &meta); + } + ultrasound_rx_reset_detector(cd, false); +} + +__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 (param_id == SOF_IPC4_SWITCH_CONTROL_PARAM_ID) { + const struct sof_ipc4_control_msg_payload *ctl = + (const struct sof_ipc4_control_msg_payload *)fragment; + uint32_t new_enable; + + 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; + } + + new_enable = ctl->chanv[0].value ? 0 : 1; + cd->cfg.enable = new_enable; + if (!new_enable) + ultrasound_rx_handle_bypass(mod, cd); + comp_info(dev, "ultrasound_rx bypass=%u enable=%u", + ctl->chanv[0].value, cd->cfg.enable); + return 0; + } + + if (param_id == SOF_US_RX_PARAM_CONFIG) { + const struct sof_ultrasound_rx_config *new_cfg = + (const struct sof_ultrasound_rx_config *)fragment; + + if (pos != MODULE_CFG_FRAGMENT_SINGLE || fragment_size != sizeof(cd->cfg)) + return -EINVAL; + if (new_cfg->version != SOF_ULTRASOUND_ABI_VERSION || + new_cfg->input_gain_shift > 4) + return -EINVAL; + + if (cd->present) { + struct us_rx_evt_meta meta = { + .duration_ms = (cd->presence_start_ms && + cd->bb_ms >= cd->presence_start_ms) ? + (uint32_t)(cd->bb_ms - cd->presence_start_ms) : 0U, + }; + + cd->present = false; + cd->presence_start_ms = 0; + ultrasound_set_presence(false); + ultrasound_rx_emit_event(mod, cd, SOF_US_EVT_PRESENCE_LOST, + 0, 0, cd->cfg.carrier_hz[0], &meta); + } + memcpy_s(&cd->cfg, sizeof(cd->cfg), fragment, fragment_size); + ultrasound_rx_reset_detector(cd, false); + comp_info(dev, "ultrasound_rx cfg updated: en=%u f0=%u f1=%u snr_q8=%u pk=%u shift=%u flags=%#x", + cd->cfg.enable, cd->cfg.carrier_hz[0], cd->cfg.carrier_hz[1], + cd->cfg.snr_threshold_q8, cd->cfg.min_peak_level, + cd->cfg.input_gain_shift, cd->cfg.flags); + 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); + size_t max_len = (data_offset_size && *data_offset_size) ? + *data_offset_size : fragment_size; + + assert_can_be_cold(); + + if (param_id == SOF_US_RX_PARAM_CONFIG) { + if (max_len < sizeof(cd->cfg)) + return -EINVAL; + memcpy_s(fragment, max_len, &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(); + ultrasound_set_presence(false); + if (cd) { + mod_fft_plan_free(mod, cd->fft_plan); + 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..d9ee4c637213 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_rx.h @@ -0,0 +1,157 @@ +/* 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 +#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, unsigned wrap-safe) */ + uint64_t int1_i; + uint64_t int2_i; + uint64_t int1_q; + uint64_t int2_q; + uint64_t comb1_i; + uint64_t comb2_i; + uint64_t comb1_q; + uint64_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; + + /* Slow per-bin stationary background tracker (Q24.8, notches out steady fans/spurs) */ + uint32_t bin_bg_q8[US_FFT_SIZE]; + + /* 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; + uint32_t hop_excess_mag; + + /* Per-channel + -> - Doppler zero-crossing tracker (stereo swipe & tap disambiguation) */ + uint32_t pos_hops; + uint32_t neg_hops; + bool had_pos; + uint64_t first_pos_ms; + uint64_t last_pos_ms; + int32_t last_pos_mhz; + int32_t peak_pos_mhz; + uint32_t last_pos_snr; + uint32_t pos_peak_mag; + uint64_t pos_ex_sum; + int64_t pos_disp_um; + uint64_t first_neg_ms; + int32_t first_neg_mhz; + int32_t peak_neg_mhz; + bool zc_valid; + uint64_t zc_ms_q2; /* Sub-hop linearly interpolated zero-crossing time (0.25 ms LSB) */ + uint64_t zc_confirm_ms; + uint32_t zc_gap_ms; + uint32_t zc_snr_db_q8; + uint32_t zc_peak_mag; +}; + +struct us_rx_pending_stroke { + bool active; + uint64_t start_ms; + uint64_t last_active_ms; + uint32_t active_hops; + uint32_t both_ch_hops; + int32_t peak_doppler_mhz; + uint32_t peak_snr_db_q8; + uint32_t peak_mag; + uint32_t carrier_hz; + int64_t disp_um; + uint64_t ch_ex_sum[SOF_ULTRASOUND_MAX_CHANNELS]; +}; + +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; + uint64_t warmup_until_ms; + bool warmup_logged; + + struct us_rx_channel ch[SOF_ULTRASOUND_MAX_CHANNELS]; + + /* SOF math FFT library state (8-byte aligned for HiFi3 ae_int32x2 access) */ + struct icomplex32 fft_in[US_FFT_SIZE] __aligned(8); + struct icomplex32 fft_out[US_FFT_SIZE] __aligned(8); + int16_t hann_win[US_FFT_SIZE]; + struct fft_plan *fft_plan; + + /* Presence tracking */ + bool present; + uint32_t presence_consec; + uint64_t presence_start_ms; + uint64_t last_activity_ms; + + /* Gesture state machine */ + uint64_t cooldown_until_ms; + int8_t tail_suppress_dir; + uint32_t tail_quiet_hops; + 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; +}; + +void sys_comp_module_ultrasound_rx_interface_init(void); + +#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..0dead62baab0 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_tx.c @@ -0,0 +1,731 @@ +// 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 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 = MAX(cd->cfg.amplitude_q31, cd->env_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->presence_boost; + + 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) { + int64_t next = (int64_t)cd->env_q31 + cd->ramp_step_q31; + + cd->env_q31 = (next >= desired) ? desired : (int32_t)next; + } else if (cd->env_q31 > desired) { + int64_t next = (int64_t)cd->env_q31 - cd->ramp_step_q31; + + cd->env_q31 = (next <= desired) ? desired : (int32_t)next; + } + 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; + size_t 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]); + int32_t tone = (int32_t)(((int64_t)s_q15 * env) >> 31); + + cd->phase[ch] += cd->phase_inc[ch]; + *y = sat_int16(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; + size_t 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_int24((int32_t)(tone31 >> 8)) : sat_int32(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; +} + +/* + * 4th-order Butterworth ultrasonic-guard LPF (fc = 14 kHz @ 48 kHz, Q28): + * Flat (<0.5 dB) through 12 kHz while attenuating 19.25..20.5 kHz playback + * audio content by >30..38 dB so bright music/speech cannot mask Doppler shifts. + */ +static inline int32_t ultrasound_tx_biquad_q28(int32_t x, int32_t z[2], + int32_t b0, int32_t b1, int32_t b2, + int32_t a1, int32_t a2) +{ + int64_t y64 = (((int64_t)b0 * x) >> 28) + z[0]; + int32_t y = (int32_t)CLAMP(y64, (int64_t)INT32_MIN / 2, (int64_t)INT32_MAX / 2); + + z[0] = (int32_t)CLAMP((((int64_t)b1 * x - (int64_t)a1 * y) >> 28) + z[1], + (int64_t)INT32_MIN / 2, (int64_t)INT32_MAX / 2); + z[1] = (int32_t)CLAMP(((int64_t)b2 * x - (int64_t)a2 * y) >> 28, + (int64_t)INT32_MIN / 2, (int64_t)INT32_MAX / 2); + return y; +} + +static inline int32_t ultrasound_tx_guard_lpf_q27(struct ultrasound_tx_data *cd, + uint32_t ch, int32_t x_q27) +{ + /* Section 0: Q = 0.5412 */ + int32_t s = ultrasound_tx_biquad_q28(x_q27, cd->lpf_z[ch][0], + 89281290, 178562579, 89281290, + 73426592, 15263110); + + /* Section 1: Q = 1.3066 */ + return ultrasound_tx_biquad_q28(s, cd->lpf_z[ch][1], + 123357497, 246714994, 123357497, + 101451498, 123543033); +} + +static inline int32_t ultrasound_tx_guard_lpf_s16(struct ultrasound_tx_data *cd, + uint32_t ch, int32_t x_s16) +{ + if (cd->sample_rate != 48000 || ch >= SOF_ULTRASOUND_MAX_CHANNELS) + return x_s16; + + /* Process at 28-bit Q12 working precision for clean low-noise biquad states */ + int32_t s = ultrasound_tx_guard_lpf_q27(cd, ch, x_s16 << 12); + + return (s + (1 << 11)) >> 12; +} + +static inline int32_t ultrasound_tx_guard_lpf_s24(struct ultrasound_tx_data *cd, + uint32_t ch, int32_t x_s24) +{ + if (cd->sample_rate != 48000 || ch >= SOF_ULTRASOUND_MAX_CHANNELS) + return x_s24; + + int32_t s = ultrasound_tx_guard_lpf_q27(cd, ch, x_s24 << 4); + + return (s + (1 << 3)) >> 4; +} + +static inline int32_t ultrasound_tx_guard_lpf_s32(struct ultrasound_tx_data *cd, + uint32_t ch, int32_t x_s32) +{ + if (cd->sample_rate != 48000 || ch >= SOF_ULTRASOUND_MAX_CHANNELS) + return x_s32; + + int32_t s = ultrasound_tx_guard_lpf_q27(cd, ch, x_s32 >> 4); + + return sat_int32((int64_t)s << 4); +} + +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; + size_t 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) { + source_release_data(source, 0); + 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]); + int32_t tone = (int32_t)(((int64_t)s_q15 * env) >> 31); + + cd->phase[ch] += cd->phase_inc[ch]; + if (cd->cfg.mode == SOF_US_TX_MODE_REPLACE) { + *y = sat_int16(tone); + } else { + int32_t aud = ultrasound_tx_guard_lpf_s16(cd, ch, *x); + + *y = sat_int16(aud + tone); + } + } else if (ch < SOF_ULTRASOUND_MAX_CHANNELS && + cd->cfg.mode == SOF_US_TX_MODE_REPLACE) { + *y = 0; + } 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; + size_t 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) { + source_release_data(source, 0); + 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) { + int32_t in24 = sign_extend_s24(*x); + int32_t tone24 = (int32_t)(tone31 >> 8); + + if (cd->cfg.mode == SOF_US_TX_MODE_REPLACE) { + *y = sat_int24(tone24); + } else { + int32_t aud24 = ultrasound_tx_guard_lpf_s24(cd, ch, in24); + + *y = sat_int24(aud24 + tone24); + } + } else { + if (cd->cfg.mode == SOF_US_TX_MODE_REPLACE) { + *y = sat_int32(tone31); + } else { + int32_t aud32 = ultrasound_tx_guard_lpf_s32(cd, ch, *x); + + *y = sat_int32((int64_t)aud32 + tone31); + } + } + } else if (ch < SOF_ULTRASOUND_MAX_CHANNELS && + cd->cfg.mode == SOF_US_TX_MODE_REPLACE) { + *y = 0; + } 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 (mod->priv.cfg.nb_input_pins == 0) { + dev->direction = SOF_IPC_STREAM_PLAYBACK; + dev->direction_set = true; + cd->is_standalone = true; + } + + 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) { + ipc4_update_sink_format(sinks[0], &mod->priv.cfg.base_cfg.audio_fmt); + 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; + memset(cd->lpf_z, 0, sizeof(cd->lpf_z)); + cd->duty_sample_pos = 0; + cd->presence_boost = false; + 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; + + /* Cache presence state once per audio block to avoid per-frame syscalls */ + cd->presence_boost = (cd->target_env_q31 > 0 && cd->duty_period_samples > 0 && + cd->cfg.auto_boost_on_presence) ? + ultrasound_get_presence() : false; + + 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; + } + + /* Cache presence state once per audio block to avoid per-frame syscalls */ + cd->presence_boost = (cd->target_env_q31 > 0 && cd->duty_period_samples > 0 && + cd->cfg.auto_boost_on_presence) ? + ultrasound_get_presence() : false; + + 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 (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; + } + + if (param_id == SOF_US_TX_PARAM_CONFIG) { + const struct sof_ultrasound_tx_config *new_cfg = + (const struct sof_ultrasound_tx_config *)fragment; + + if (pos != MODULE_CFG_FRAGMENT_SINGLE || fragment_size != sizeof(cd->cfg)) + return -EINVAL; + if (new_cfg->version != SOF_ULTRASOUND_ABI_VERSION || + new_cfg->mode > SOF_US_TX_MODE_REPLACE || + new_cfg->amplitude_q31 < 0) + 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); + size_t max_len = (data_offset_size && *data_offset_size) ? + *data_offset_size : fragment_size; + + assert_can_be_cold(); + + if (param_id == SOF_US_TX_PARAM_CONFIG) { + if (max_len < sizeof(cd->cfg)) + return -EINVAL; + memcpy_s(fragment, max_len, &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; + memset(cd->lpf_z, 0, sizeof(cd->lpf_z)); + cd->duty_sample_pos = 0; + cd->presence_boost = false; + 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..fa69c7faf7f3 --- /dev/null +++ b/src/audio/ultrasound/ultrasound_tx.h @@ -0,0 +1,53 @@ +/* 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; + + /* 4th-order (2-biquad) 14 kHz ultrasonic-guard LPF state per channel (Q27) */ + int32_t lpf_z[SOF_ULTRASOUND_MAX_CHANNELS][2][2]; + + /* 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 presence_boost; + bool last_boosted; + bool boost_logged; +}; + +void sys_comp_module_ultrasound_tx_interface_init(void); + +#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..44c256a3a004 100644 --- a/src/include/ipc4/notification.h +++ b/src/include/ipc4/notification.h @@ -313,6 +313,34 @@ void ipc4_update_notification_mask(uint32_t ntfy_mask, uint32_t enabled_mask); */ __syscall bool send_resource_notif(uint32_t resource_id, uint32_t event_type, uint32_t resource_type, void *data, uint32_t data_size); + +/** + * \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. + */ +__syscall 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. + */ +__syscall 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. + */ +__syscall bool ultrasound_get_presence(void); + #include #else @@ -331,6 +359,36 @@ bool z_impl_send_resource_notif(uint32_t resource_id, uint32_t event_type, uint32_t resource_type, void *data, uint32_t data_size); #define send_resource_notif z_impl_send_resource_notif +/** + * \brief Implementation of send_module_notif_msg for non-Zephyr builds. + * \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 z_impl_send_module_notif_msg(uint16_t module_id, uint16_t instance_id, + uint32_t event_id, const void *data, uint32_t data_size); +#define send_module_notif_msg z_impl_send_module_notif_msg + +/** + * \brief Implementation of ultrasound_set_presence for non-Zephyr builds. + * \ingroup ipc4_notification_api + * \param present True when user/hand presence is active, false when lost. + */ +void z_impl_ultrasound_set_presence(bool present); +#define ultrasound_set_presence z_impl_ultrasound_set_presence + +/** + * \brief Implementation of ultrasound_get_presence for non-Zephyr builds. + * \ingroup ipc4_notification_api + * \return True if ultrasonic RX currently reports presence active. + */ +bool z_impl_ultrasound_get_presence(void); +#define ultrasound_get_presence z_impl_ultrasound_get_presence + #endif #endif /* __IPC4_NOTIFICATION_H__ */ diff --git a/src/include/user/ultrasound.h b/src/include/user/ultrasound.h new file mode 100644 index 000000000000..3c4a9288c830 --- /dev/null +++ b/src/include/user/ultrasound.h @@ -0,0 +1,106 @@ +/* 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_EVENT_ABI_VERSION 2 +#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_EVENT_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 */ + /* Event ABI v2: gesture duration, integrated travel & coarse position */ + uint32_t duration_ms; /* active gesture (or presence) duration in ms */ + int32_t displacement_mm; /* integrated radial travel in mm (+closer, -farther) */ + int16_t pos_x_permille; /* coarse lateral balance -1000 (L) .. +1000 (R) */ + int16_t zc_lag_ms_q2; /* stereo (+ -> -) zero-crossing lag (0.25 ms LSB) */ + uint16_t proximity; /* coarse reflection proximity score 0..1000 (far..near) */ + uint16_t reserved; /* alignment padding (0) */ +} __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))); + +/* RX configuration flags */ +#define SOF_US_RX_FLAG_SWAP_LR (1U << 0) /* Swap ch0/ch1 for L/R swipe polarity */ + +/** + * 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 13.5 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) */ + uint32_t flags; /* SOF_US_RX_FLAG_* bitmask */ +} __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..6e7a82158256 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,60 @@ void ipc4_update_notification_mask(uint32_t ntfy_mask, uint32_t enabled_mask) notification_mask |= enabled_mask & ntfy_mask; } +bool z_impl_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; + + if ((!data && data_size) || (data && !data_size)) + return false; + + if (data_size > SOF_IPC_MSG_MAX_SIZE - sizeof(*mod_data)) + return false; + + 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(z_impl_send_module_notif_msg); + +static atomic_t g_ultrasound_presence; + +void z_impl_ultrasound_set_presence(bool present) +{ + atomic_set(&g_ultrasound_presence, present ? 1 : 0); +} +EXPORT_SYMBOL(z_impl_ultrasound_set_presence); + +bool z_impl_ultrasound_get_presence(void) +{ + return atomic_read(&g_ultrasound_presence) != 0; +} +EXPORT_SYMBOL(z_impl_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, @@ -119,4 +177,34 @@ static inline bool z_vrfy_send_resource_notif(uint32_t resource_id, uint32_t eve return z_impl_send_resource_notif(resource_id, event_type, resource_type, data, data_size); } #include + +static inline bool z_vrfy_send_module_notif_msg(uint16_t module_id, uint16_t instance_id, + uint32_t event_id, const void *data, + uint32_t data_size) +{ + /* data and data_size must be consistent */ + K_OOPS(K_SYSCALL_VERIFY((!data && !data_size) || (data && data_size))); + + /* Payload must fit in an IPC4 module notification message without overflow */ + K_OOPS(K_SYSCALL_VERIFY(data_size <= + SOF_IPC_MSG_MAX_SIZE - sizeof(struct sof_ipc4_notify_module_data))); + + if (data && data_size) + K_OOPS(K_SYSCALL_MEMORY_READ(data, data_size)); + + return z_impl_send_module_notif_msg(module_id, instance_id, event_id, data, data_size); +} +#include + +static inline void z_vrfy_ultrasound_set_presence(bool present) +{ + z_impl_ultrasound_set_presence(present); +} +#include + +static inline bool z_vrfy_ultrasound_get_presence(void) +{ + return z_impl_ultrasound_get_presence(); +} +#include #endif /* CONFIG_USERSPACE */ 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/src/math/base2log.c b/src/math/base2log.c index 5ca3967d9a85..bb8e160017db 100644 --- a/src/math/base2log.c +++ b/src/math/base2log.c @@ -7,6 +7,7 @@ // #include +#include /* Defines Constant*/ #define BASE2LOG_WRAP_SCHAR_BITS 0xFF @@ -119,4 +120,5 @@ int32_t base2_logarithm(uint32_t u) l3_i = iv1[(slice_temp - 127) - 1]; return s_v + (((x & BASE2LOG_UPPERBYTES) * (int64_t)(l2_i - l3_i)) >> 24); } +EXPORT_SYMBOL(base2_logarithm); diff --git a/src/math/fft/fft_32.c b/src/math/fft/fft_32.c index a6f8b2aa1ab3..fa68879317ba 100644 --- a/src/math/fft/fft_32.c +++ b/src/math/fft/fft_32.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #ifdef FFT_GENERIC @@ -93,5 +94,6 @@ void fft_execute_32(struct fft_plan *plan, bool ifft) } } } +EXPORT_SYMBOL(fft_execute_32); #endif /* FFT_GENERIC */ diff --git a/src/math/fft/fft_32_hifi3.c b/src/math/fft/fft_32_hifi3.c index 1d00dacd1b7f..a078187e1742 100644 --- a/src/math/fft/fft_32_hifi3.c +++ b/src/math/fft/fft_32_hifi3.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #ifdef FFT_HIFI3 @@ -156,4 +157,5 @@ void fft_execute_32(struct fft_plan *plan, bool ifft) } } } +EXPORT_SYMBOL(fft_execute_32); #endif diff --git a/src/math/fft/fft_common.c b/src/math/fft/fft_common.c index 94c315537e3a..63e3e77f3ffa 100644 --- a/src/math/fft/fft_common.c +++ b/src/math/fft/fft_common.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include "fft_common.h" @@ -104,6 +105,7 @@ struct fft_plan *mod_fft_plan_new(struct processing_module *mod, void *inb, fft_plan_init_bit_reverse(plan->bit_reverse_idx, plan->size, plan->len); return plan; } +EXPORT_SYMBOL(mod_fft_plan_new); void mod_fft_plan_free(struct processing_module *mod, struct fft_plan *plan) { @@ -113,3 +115,4 @@ void mod_fft_plan_free(struct processing_module *mod, struct fft_plan *plan) mod_free(mod, plan->bit_reverse_idx); mod_free(mod, plan); } +EXPORT_SYMBOL(mod_fft_plan_free); diff --git a/src/math/window.c b/src/math/window.c index 39739ef24be3..a5092a2bdaa5 100644 --- a/src/math/window.c +++ b/src/math/window.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -118,6 +119,7 @@ void win_hann_16b(int16_t win[], int length) win[n] = sat_int16(val); } } +EXPORT_SYMBOL(win_hann_16b); void win_hann_32b(int32_t win[], int length) { 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