From 65f0357a7ed6698dad12db097d6835d842e126c9 Mon Sep 17 00:00:00 2001 From: Liam Girdwood Date: Mon, 16 Nov 2026 12:05:45 +0000 Subject: [PATCH 1/4] notifier, ipc4: add WOV and D0iX power state notifier events Add NOTIFIER_ID_WOV_DETECT, NOTIFIER_ID_WOV_CTRL, and NOTIFIER_ID_D0IX_STATE notifier IDs along with the D0iX state payload and WOV arbiter notifier/control ABI header. Dispatch NOTIFIER_ID_D0IX_STATE from ipc4_module_process_d0ix() so components such as microWakeWord can switch to low-power D0i3 operation. Signed-off-by: Liam Girdwood --- src/include/sof/audio/wov_arbiter.h | 56 ++++++++++++++++++++++++++++ src/include/sof/lib/notifier.h | 15 ++++++++ src/kernel/ipc/ipc4/handler-kernel.c | 12 ++++++ 3 files changed, 83 insertions(+) create mode 100644 src/include/sof/audio/wov_arbiter.h diff --git a/src/include/sof/audio/wov_arbiter.h b/src/include/sof/audio/wov_arbiter.h new file mode 100644 index 000000000000..0dff468fd275 --- /dev/null +++ b/src/include/sof/audio/wov_arbiter.h @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Copyright(c) 2024 Intel Corporation. All rights reserved. + */ + +#ifndef __SOF_AUDIO_WOV_ARBITER_H__ +#define __SOF_AUDIO_WOV_ARBITER_H__ + +/* Maximum number of WOV detector slots (= KPB host-sink input pins). */ +#define WOV_ARB_MAX_SLOTS 8 + +/* Sentinel: no slot is currently draining. */ +#define WOV_ARB_NO_ACTIVE 0xff + +/** Host enum control IDs exposed by the WoV arbiter topology. */ +#define WOV_ARB_ACTIVE_SLOT_CONTROL_ID 1 +#define WOV_ARB_CALL_STATE_CONTROL_ID 2 + +/** Values of the host WoV call-state enum control. */ +#define WOV_ARB_CALL_STATE_LISTENING 0 +#define WOV_ARB_CALL_STATE_ACTIVE 1 + +/* + * IPC4 SET_LARGE_CONFIG param ID used to set the arbiter's active input + * explicitly from the host (testing / override). + */ +#define IPC4_WOV_ARB_SET_ACTIVE_SLOT 1 + +/* + * IPC4 GET_LARGE_CONFIG param ID: read the currently active slot. + * Host uses this for the volatile RO kcontrol; returns WOV_ARB_NO_ACTIVE + * when no drain is in progress. + */ +#define IPC4_WOV_ARB_GET_ACTIVE_SLOT 2 + +/* Command codes for WOV_CTRL notifier payload (arbiter → detectors). */ +#define WOV_ARB_CMD_PAUSE 0 +#define WOV_ARB_CMD_RESUME 1 + +/* WOV detect notifier payload (detector → arbiter). */ +struct wov_detect_notif { + uint8_t slot_id; /* 0-based detector slot that fired */ +}; + +/* WOV ctrl notifier payload (arbiter → detectors). */ +struct wov_ctrl_notif { + uint8_t cmd; /* WOV_ARB_CMD_PAUSE or WOV_ARB_CMD_RESUME */ + uint8_t slot_id; /* winning slot; receivers skip if this is their own slot */ +}; + +/* Sentinel value matching WOV_SLOT_INVALID in ams_msg.h */ +#define WOV_SLOT_INVALID 0xff + +void sys_comp_wov_arbiter_init(void); + +#endif /* __SOF_AUDIO_WOV_ARBITER_H__ */ diff --git a/src/include/sof/lib/notifier.h b/src/include/sof/lib/notifier.h index e5413a512cb4..c0b07113bb10 100644 --- a/src/include/sof/lib/notifier.h +++ b/src/include/sof/lib/notifier.h @@ -12,6 +12,7 @@ #include #include #include +#include #include /* notifier target core masks */ @@ -19,6 +20,17 @@ #define NOTIFIER_TARGET_CORE_LOCAL NOTIFIER_TARGET_CORE_MASK(cpu_get_id()) #define NOTIFIER_TARGET_CORE_ALL_MASK 0xFFFFFFFF +/** + * \brief NOTIFIER_ID_D0IX_STATE payload. + * + * Raised when the host changes the DSP D0 substate via SOF_IPC4_MOD_SET_D0IX. + * Components that must keep working while the host is in S0iX can use this to + * tell "host asleep, DSP still running" from normal operation. + */ +struct d0ix_state_notif { + bool entering; /**< true: entering D0i3, false: returning to D0i0 */ +}; + enum notify_id { NOTIFIER_ID_CPU_FREQ = 0, /* struct clock_notify_data * */ NOTIFIER_ID_SSP_FREQ, /* struct clock_notify_data * */ @@ -29,6 +41,9 @@ enum notify_id { NOTIFIER_ID_DAI_TRIGGER, /* struct dai_group * */ NOTIFIER_ID_MIC_PRIVACY_STATE_CHANGE, /* struct mic_privacy_settings * */ NOTIFIER_ID_VAD, /* int * (WEBRTC_VAD_SPEECH / WEBRTC_VAD_SILENCE) */ + NOTIFIER_ID_WOV_DETECT, /* struct wov_detect_notif *: keyword detected */ + NOTIFIER_ID_WOV_CTRL, /* struct wov_ctrl_notif *: pause/resume detectors */ + NOTIFIER_ID_D0IX_STATE, /* struct d0ix_state_notif *: host D0i3 entry/exit */ NOTIFIER_ID_COUNT }; diff --git a/src/kernel/ipc/ipc4/handler-kernel.c b/src/kernel/ipc/ipc4/handler-kernel.c index b8d02c3771ae..62b717318807 100644 --- a/src/kernel/ipc/ipc4/handler-kernel.c +++ b/src/kernel/ipc/ipc4/handler-kernel.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -332,6 +333,17 @@ __cold static int ipc4_module_process_d0ix(struct ipc4_message_request *ipc4) else pm_runtime_enable(PM_RUNTIME_DSP, PLATFORM_PRIMARY_CORE_ID); + /* Tell interested components that the host is entering or leaving S0iX. + * prevent_power_gating is set on the way back to D0i0 and clear when the + * host allows the DSP to power gate, i.e. when the host is going to sleep. + */ + struct d0ix_state_notif notif = { + .entering = !d0ix.extension.r.prevent_power_gating, + }; + + notifier_event(NULL, NOTIFIER_ID_D0IX_STATE, NOTIFIER_TARGET_CORE_ALL_MASK, + ¬if, sizeof(notif)); + return 0; } From b2f59241111d02afc9a659ada597d38c359bb5ea Mon Sep 17 00:00:00 2001 From: Liam Girdwood Date: Mon, 16 Nov 2026 12:05:45 +0000 Subject: [PATCH 2/4] audio: kpb: add multi-client WOV detector triggering and dynamic sample rates Support multiple downstream WOV detector pipelines sharing a single KPB history buffer: - Support multi-sink topology binding, dynamic sample rates, and synchronous IPC4 reset. - Fix drain boundary copy, cross-core drain request coherency, and buffer parameter configuration races. - Continue history buffering when a selector sink is full, and disable synchronous draining mode blocking. - Increase KPB_MAX_NO_OF_CLIENTS default to 4 and KPB_MAX_BUFF_TIME to 6000 ms on ACE 3.0+. Signed-off-by: Liam Girdwood Co-authored-by: Seppo Ingalsuo Signed-off-by: Seppo Ingalsuo --- src/audio/Kconfig | 14 ++ src/audio/kpb.c | 482 ++++++++++++++++++++++++++---------- src/audio/kpb.toml | 7 +- src/include/ipc4/kpb.h | 2 + src/include/sof/audio/kpb.h | 13 +- 5 files changed, 383 insertions(+), 135 deletions(-) diff --git a/src/audio/Kconfig b/src/audio/Kconfig index fecbf0d25afa..8468570fe45a 100644 --- a/src/audio/Kconfig +++ b/src/audio/Kconfig @@ -174,6 +174,20 @@ config KPB_NOTIFIER This transport can be enabled independently of the Async Messaging Service (AMS), including together with AMS. +config KPB_MAX_NO_OF_CLIENTS + int "Maximum number of KPB clients" + default 4 + help + Maximum number of simultaneous KPB drain clients (host + WOV detectors). + Increase if more than 4 clients need concurrent KPB access. + +config KPB_MAX_BUFF_TIME + int "KPB history buffer time (ms)" + default 6000 if XCHAL_HW_VERSION_MAJOR >= 300 + default 2100 + help + KPB history ring-buffer length in milliseconds. + config KPB_FORCE_COPY_TYPE_NORMAL bool "KPB force copy type normal" default y diff --git a/src/audio/kpb.c b/src/audio/kpb.c index f0f3ff743584..679cf16097c3 100644 --- a/src/audio/kpb.c +++ b/src/audio/kpb.c @@ -18,12 +18,18 @@ #include #include #include +#include +#define SOF_MODULE_API_PRIVATE +#include +#include #include #include #include #include +#include #include #include +#include #include #include #include @@ -102,6 +108,7 @@ struct comp_data { enum comp_copy_type force_copy_type; /**< should we force copy_type on kpb sink? */ #ifdef CONFIG_IPC_MAJOR_4 struct ipc4_kpb_module_cfg ipc4_cfg; + uint32_t buff_time_ms; /**< history depth in ms; 0 = CONFIG_KPB_MAX_BUFF_TIME */ #endif /* CONFIG_IPC_MAJOR_4 */ uint32_t num_of_sel_mic; uint32_t num_of_in_channels; @@ -133,6 +140,7 @@ K_KERNEL_STACK_DEFINE(kpb_stack, 4096); #if CONFIG_KPB_NOTIFIER static void kpb_event_handler(void *arg, enum notify_id type, void *event_data); +static void kpb_on_wov_ctrl(void *arg, enum notify_id id, void *data); static int kpb_register_client(struct comp_data *kpb, struct kpb_client *cli); #endif @@ -142,7 +150,6 @@ static int kpb_buffer_data(struct comp_dev *dev, const struct comp_buffer *source, size_t size); static size_t kpb_allocate_history_buffer(struct comp_data *kpb, size_t hb_size_req); -static void kpb_clear_history_buffer(struct history_buffer *buff); static void kpb_free_history_buffer(struct history_buffer *buff); static inline bool kpb_is_sample_width_supported(uint32_t sampling_width); static void kpb_copy_samples(struct comp_buffer *sink, @@ -250,6 +257,17 @@ static void kpb_lock_init(struct comp_data *kpb) #endif /* __ZEPHYR__ */ + +/* Return per-instance history depth (ms); fall back to Kconfig if not set via topology. */ +static inline uint32_t kpb_get_buff_time_ms(const struct comp_data *kpb) +{ +#if CONFIG_IPC_MAJOR_4 + return kpb->buff_time_ms ? kpb->buff_time_ms : CONFIG_KPB_MAX_BUFF_TIME; +#else + return CONFIG_KPB_MAX_BUFF_TIME; +#endif +} + #if CONFIG_IPC_MAJOR_4 /** * \brief Set and verify ipc params. @@ -285,8 +303,9 @@ __cold static int kpb_set_verify_ipc_params(struct comp_dev *dev, return -EINVAL; } - if (kpb->config.sampling_freq != KPB_SAMPLNG_FREQUENCY) { - comp_err(dev, "requested sampling frequency not supported"); + if (kpb->config.sampling_freq != 16000 && kpb->config.sampling_freq != 48000) { + comp_err(dev, "requested sampling frequency %u not supported", + kpb->config.sampling_freq); return -EINVAL; } @@ -314,7 +333,7 @@ static void kpb_set_params(struct comp_dev *dev, params->sample_valid_bytes = kpb->ipc4_cfg.base_cfg.audio_fmt.valid_bit_depth / 8; params->buffer_fmt = kpb->ipc4_cfg.base_cfg.audio_fmt.interleaving_style; - params->buffer.size = kpb->ipc4_cfg.base_cfg.ibs * KPB_MAX_BUFF_TIME * params->channels; + params->buffer.size = kpb->ipc4_cfg.base_cfg.ibs * kpb_get_buff_time_ms(kpb) * params->channels; params->host_period_bytes = params->channels * params->sample_container_bytes * @@ -391,6 +410,9 @@ __cold static int kpb_bind(struct comp_dev *dev, const struct bind_info *bind_da sink_buf_id = buf_get_id(sink); if (sink_buf_id == buf_id) { + __maybe_unused struct comp_dev *sc = comp_buffer_get_sink_component(sink); + comp_dbg(dev, "kpb_bind: buf_id=%d sink_comp=0x%x -> %s", + buf_id, sc ? dev_comp_id(sc) : 0, sink_buf_id == 0 ? "sel_sink" : "host_sink"); if (sink_buf_id == 0) kpb->sel_sink = sink; else @@ -468,8 +490,9 @@ __cold static int kpb_set_verify_ipc_params(struct comp_dev *dev, return -EINVAL; } - if (kpb->config.sampling_freq != KPB_SAMPLNG_FREQUENCY) { - comp_err(dev, "requested sampling frequency not supported"); + if (kpb->config.sampling_freq != 16000 && kpb->config.sampling_freq != 48000) { + comp_err(dev, "requested sampling frequency %u not supported", + kpb->config.sampling_freq); return -EINVAL; } @@ -691,7 +714,7 @@ static size_t kpb_allocate_history_buffer(struct comp_data *kpb, hb_size -= ca_size; hb->next = kpb->hd.c_hb; /* Do we need another buffer? */ - if (hb_size > 0) { + if (hb_size > 0 && i + 1 < ARRAY_SIZE(hb_mcp)) { /* Yes, we still need at least one more buffer. * Let's first create new container for it. */ @@ -792,6 +815,7 @@ __cold static void kpb_free(struct comp_dev *dev) #if CONFIG_KPB_NOTIFIER /* Unregister KPB from notifications */ notifier_unregister(dev, NULL, NOTIFIER_ID_KPB_CLIENT_EVT); + notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_CTRL); #endif/* CONFIG_KPB_NOTIFIER */ /* Reclaim memory occupied by history buffer */ @@ -800,6 +824,7 @@ __cold static void kpb_free(struct comp_dev *dev) kpb->hd.buffer_size = 0; /* remove scheduling */ + schedule_task_cancel(&kpb->draining_task); schedule_task_free(&kpb->draining_task); /* change state */ @@ -889,7 +914,11 @@ static int kpb_prepare(struct comp_dev *dev) struct sof_ipc_stream_params params; int ret = 0; int i; - size_t hb_size_req = KPB_MAX_BUFFER_SIZE(kpb->config.sampling_width, kpb->config.channels); + /* Use topology-set depth if provided; otherwise Kconfig default. */ + uint32_t buff_ms = kpb_get_buff_time_ms(kpb); + size_t hb_size_req = (kpb->config.sampling_freq / 1000) * + (KPB_SAMPLE_CONTAINER_SIZE(kpb->config.sampling_width) / 8) * + buff_ms * kpb->config.channels; comp_dbg(dev, "entry"); @@ -902,6 +931,11 @@ static int kpb_prepare(struct comp_dev *dev) return -EINVAL; } + if (kpb->sel_sink) + buffer_set_params(kpb->sel_sink, ¶ms, true); + if (kpb->host_sink) + buffer_set_params(kpb->host_sink, ¶ms, true); + if (kpb->state == KPB_STATE_RESETTING || kpb->state == KPB_STATE_RESET_FINISHING) { comp_cl_err(&comp_kpb, "can not prepare KPB due to ongoing reset, state log %x", @@ -958,8 +992,12 @@ static int kpb_prepare(struct comp_dev *dev) } #if CONFIG_KPB_NOTIFIER - /* Register KPB for notification *on the current core* */ + /* Register KPB for notification *on the current core* (ensure no duplicate registrations) */ + notifier_unregister(dev, NULL, NOTIFIER_ID_KPB_CLIENT_EVT); + notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_CTRL); ret = notifier_register(dev, NULL, NOTIFIER_ID_KPB_CLIENT_EVT, kpb_event_handler); + if (ret >= 0) + ret = notifier_register(dev, NULL, NOTIFIER_ID_WOV_CTRL, kpb_on_wov_ctrl); if (ret < 0) { kpb_free_history_buffer(kpb->hd.c_hb); @@ -985,6 +1023,51 @@ static int kpb_prepare(struct comp_dev *dev) #endif /* CONFIG_AMS */ #endif + struct comp_buffer *sink; + /* Output pin IDs: IPC4_COMP_ID(src_queue, dst_queue) = (dst_queue<<16)|src_queue. + * In a multi-KPB topology each KPB connects to a different arbiter input pin so + * dst_queue varies (0,1,2...) but src_queue is always 0 (sel) or 1 (host). + * Match on src_queue only (lower 16 bits of buf_id). */ + enum { KPB_PIN_SEL_SINK = 0, KPB_PIN_HOST_SINK_SRC = 1 }; + comp_dev_for_each_consumer(dev, sink) { + uint32_t src_q = buf_get_id(sink) & 0xFFFF; + + if (src_q == KPB_PIN_SEL_SINK) + kpb->sel_sink = sink; + else if (src_q == KPB_PIN_HOST_SINK_SRC && !kpb->host_sink) + kpb->host_sink = sink; + else + comp_warn(dev, "kpb_prepare: unexpected consumer pin, buf_id=0x%x", + buf_get_id(sink)); + } + comp_dbg(dev, "kpb_params: sel_sink=%p host_sink=%p", + kpb->sel_sink, kpb->host_sink); + + /* Cross-pipeline prepare: the WOV detector (detect_test) lives on a + * separate IPC4 pipeline and won't be prepared by the normal IPC4 walk, + * so KPB bootstraps it here during its own prepare phase. + */ + if (kpb->sel_sink) { + struct comp_dev *sink_comp = comp_buffer_get_sink_component(kpb->sel_sink); + if (sink_comp && sink_comp->state == COMP_STATE_INIT) { + struct sof_ipc_stream_params sink_params; + memset_s(&sink_params, sizeof(sink_params), 0, sizeof(sink_params)); + sink_params.channels = kpb->config.channels ? kpb->config.channels : 2; + sink_params.rate = kpb->config.sampling_freq ? kpb->config.sampling_freq : 16000; + sink_params.sample_container_bytes = 4; + sink_params.sample_valid_bytes = 4; + sink_params.frame_fmt = SOF_IPC_FRAME_S32_LE; + comp_params(sink_comp, &sink_params); + ret = comp_prepare(sink_comp); + if (ret < 0) { + comp_err(dev, "kpb_prepare: cross-pipeline prepare of wov detector failed: %d", ret); + return ret; + } + } + } + + kpb_change_state(kpb, KPB_STATE_RUN); + #ifndef CONFIG_IPC_MAJOR_4 /* Search for KPB related sinks. * NOTE! We assume here that channel selector component device @@ -1034,13 +1117,45 @@ static int kpb_prepare(struct comp_dev *dev) } #endif /* CONFIG_IPC_MAJOR_4 */ + /* Fallback: iterate consumers to assign sel_sink and host_sink in order. + * The guards ensure each is set at most once — no overwrite on later iterations. */ + if (!kpb->sel_sink && !kpb->host_sink) { + struct comp_buffer *sink; + + comp_dev_for_each_consumer(dev, sink) { + if (!kpb->sel_sink) + kpb->sel_sink = sink; + else if (!kpb->host_sink) + kpb->host_sink = sink; + } + } + if (!kpb->sel_sink) { comp_err(dev, "could not find sink: sel_sink %p", kpb->sel_sink); ret = -EIO; + } else { + struct comp_dev *sink_comp = comp_buffer_get_sink_component(kpb->sel_sink); + if (sink_comp && sink_comp->state == COMP_STATE_INIT) { + struct sof_ipc_stream_params sink_params; + memset_s(&sink_params, sizeof(sink_params), 0, sizeof(sink_params)); + sink_params.channels = kpb->config.channels ? kpb->config.channels : 2; + sink_params.rate = kpb->config.sampling_freq ? kpb->config.sampling_freq : 16000; + sink_params.sample_container_bytes = 4; + sink_params.sample_valid_bytes = 4; + sink_params.frame_fmt = SOF_IPC_FRAME_S32_LE; + comp_params(sink_comp, &sink_params); + ret = comp_prepare(sink_comp); + comp_info(dev, "kpb_prepare: prepared downstream sink_comp %d in state %d", + dev_comp_id(sink_comp), sink_comp->state); + if (ret < 0) { + comp_err(dev, "kpb_prepare: cross-pipeline prepare failed: %d", ret); + return ret; + } + } } - kpb->sync_draining_mode = true; + kpb->sync_draining_mode = false; kpb_change_state(kpb, KPB_STATE_RUN); @@ -1076,14 +1191,52 @@ static int kpb_reset(struct comp_dev *dev) comp_cl_info(&comp_kpb, "resetting from state %d, state log %x", kpb->state, kpb->state_log); +#ifndef CONFIG_AMS + /* Unregister KPB from notifications */ + notifier_unregister(dev, NULL, NOTIFIER_ID_KPB_CLIENT_EVT); + notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_CTRL); +#endif + switch (kpb->state) { case KPB_STATE_BUFFERING: case KPB_STATE_DRAINING: - /* KPB is performing some task now, - * terminate it gently. + case KPB_STATE_HOST_COPY: + /* Cancel any scheduled draining task immediately on reset */ + schedule_task_cancel(&kpb->draining_task); + + /* If a dedicated host drain is in progress to a separate host sink, + * let kpb_copy complete the reset once scheduled. + * If host_sink is NULL or same as sel_sink (unified WOV pipeline), + * or state is BUFFERING, reset immediately. + * Under IPC4, pipeline triggers and resets are synchronous; + * returning -EBUSY breaks the pipeline state machine and causes + * host teardown to fail. */ - kpb_change_state(kpb, KPB_STATE_RESETTING); - ret = -EBUSY; +#if !CONFIG_IPC_MAJOR_4 + if (kpb->host_sink && kpb->host_sink != kpb->sel_sink && + kpb->state == KPB_STATE_DRAINING) { + kpb_change_state(kpb, KPB_STATE_RESETTING); + ret = -EBUSY; + break; + } +#endif + /* host_sink == NULL or unified WOV path: immediate full reset */ + kpb->hd.buffered = 0; + kpb->sel_sink = NULL; + kpb->host_sink = NULL; + kpb->host_buffer_size = 0; + kpb->host_period_size = 0; + for (i = 0; i < KPB_MAX_NO_OF_CLIENTS; i++) { + kpb->clients[i].state = KPB_CLIENT_UNREGISTERED; + kpb->clients[i].r_ptr = NULL; + } + if (kpb->hd.c_hb) + kpb_reset_history_buffer(kpb->hd.c_hb); + /* Must transition away from KPB_STATE_RUN before returning so that + * a subsequent kpb_copy() does not see a stale RUN state and + * immediately begin copying before the next prepare completes. */ + kpb_change_state(kpb, KPB_STATE_PREPARING); + ret = comp_set_state(dev, COMP_TRIGGER_RESET); break; case KPB_STATE_DISABLED: case KPB_STATE_CREATED: @@ -1091,6 +1244,7 @@ static int kpb_reset(struct comp_dev *dev) ret = comp_set_state(dev, COMP_TRIGGER_RESET); break; default: + schedule_task_cancel(&kpb->draining_task); kpb->hd.buffered = 0; kpb->sel_sink = NULL; kpb->host_sink = NULL; @@ -1112,6 +1266,7 @@ static int kpb_reset(struct comp_dev *dev) #if CONFIG_KPB_NOTIFIER /* Unregister KPB from notifications */ notifier_unregister(dev, NULL, NOTIFIER_ID_KPB_CLIENT_EVT); + notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_CTRL); #endif /* Finally KPB is ready after reset */ kpb_change_state(kpb, KPB_STATE_PREPARING); @@ -1395,20 +1550,16 @@ static int kpb_copy(struct comp_dev *dev) /* In normal RUN state we simply copy to our sink. */ sink = kpb->sel_sink; + comp_dbg(dev, "kpb_copy: source_buf=%p sel_sink=%p avail=%u", + source, sink, audio_stream_get_avail_bytes(&source->stream)); + if (!sink) { - comp_err(dev, "no sink."); + comp_warn(dev, "no sink."); ret = -EINVAL; break; } - /* Discard data if sink is not active */ - if (comp_buffer_get_sink_component(sink)->state != COMP_STATE_ACTIVE) { - copy_bytes = audio_stream_get_avail_bytes(&source->stream); - comp_update_buffer_consume(source, copy_bytes); - comp_dbg(dev, "KD not active, dropping %zu bytes...", copy_bytes); - ret = PPL_STATUS_PATH_STOP; - break; - } + /* Allow downstream WOV detector copy regardless of state */ /* Validate sink */ if (!audio_stream_get_wptr(&sink->stream)) { @@ -1417,44 +1568,44 @@ static int kpb_copy(struct comp_dev *dev) break; } - copy_bytes = audio_stream_get_copy_bytes(&source->stream, &sink->stream); - if (!copy_bytes) { - comp_err(dev, "nothing to copy sink->free %u source->avail %u", - audio_stream_get_free_bytes(&sink->stream), - audio_stream_get_avail_bytes(&source->stream)); - if (!audio_stream_get_avail_bytes(&sink->stream)) - ret = PPL_STATUS_PATH_STOP; + uint32_t src_avail = audio_stream_get_avail_bytes(&source->stream); + uint32_t snk_free = audio_stream_get_free_bytes(&sink->stream); + size_t frame_bytes = (sample_width >> 3) * channels; + size_t consume_bytes = 0; + + if (!src_avail) { + ret = PPL_STATUS_PATH_STOP; break; } + copy_bytes = MIN(src_avail, snk_free); + if (frame_bytes) + copy_bytes = ROUND_DOWN(copy_bytes, frame_bytes); + if (kpb->num_of_sel_mic == 0) { - kpb_copy_samples(sink, source, copy_bytes, sample_width, channels); + if (copy_bytes) + kpb_copy_samples(sink, source, copy_bytes, sample_width, channels); + consume_bytes = copy_bytes ? copy_bytes : (frame_bytes ? ROUND_DOWN(src_avail, frame_bytes) : 0); } else { - uint32_t avail = audio_stream_get_avail_bytes(&source->stream); - uint32_t free = audio_stream_get_free_bytes(&sink->stream); + uint32_t free = snk_free; - copy_bytes = MIN(avail, free * channels / kpb->num_of_sel_mic); + copy_bytes = MIN(src_avail, free * channels / kpb->num_of_sel_mic); copy_bytes = ROUND_DOWN(copy_bytes, (sample_width >> 3) * channels); unsigned int total_bytes_per_sample = (sample_width >> 3) * kpb->num_of_sel_mic; produced_bytes = copy_bytes * kpb->num_of_sel_mic / channels; produced_bytes = ROUND_DOWN(produced_bytes, total_bytes_per_sample); - if (!copy_bytes) { - comp_err(dev, "nothing to copy sink->free %u source->avail %u", - free, - avail); - if (!audio_stream_get_avail_bytes(&sink->stream)) - ret = PPL_STATUS_PATH_STOP; - break; - } - kpb_micselect_copy(dev, sink, source, produced_bytes, channels); + if (copy_bytes) + kpb_micselect_copy(dev, sink, source, produced_bytes, channels); + consume_bytes = copy_bytes ? copy_bytes : (frame_bytes ? ROUND_DOWN(src_avail, frame_bytes) : 0); } - /* Buffer source data internally in history buffer for future - * use by clients. + + /* Buffer into history buffer (consume_bytes ensures history ring keeps filling + * and upstream ECNS never stalls even if downstream sel_sink is full). */ - if (copy_bytes <= kpb->hd.buffer_size) { - ret = kpb_buffer_data(dev, source, copy_bytes); + if (consume_bytes && consume_bytes <= kpb->hd.buffer_size) { + ret = kpb_buffer_data(dev, source, consume_bytes); if (ret) { comp_err(dev, "internal buffering failed."); @@ -1466,17 +1617,29 @@ static int kpb_copy(struct comp_dev *dev) */ kpb->hd.buffered += MIN(kpb->hd.buffer_size - kpb->hd.buffered, - copy_bytes); - } else { + consume_bytes); + } else if (consume_bytes > kpb->hd.buffer_size) { comp_err(dev, "too much data to buffer."); } - if (kpb->num_of_sel_mic == 0) - comp_update_buffer_produce(sink, copy_bytes); - else - comp_update_buffer_produce(sink, produced_bytes); + if (copy_bytes) { + if (kpb->num_of_sel_mic == 0) + comp_update_buffer_produce(sink, copy_bytes); + else + comp_update_buffer_produce(sink, produced_bytes); - comp_update_buffer_consume(source, copy_bytes); + struct comp_dev *wov_comp = sink ? comp_buffer_get_sink_component(sink) : NULL; + if (wov_comp) { + comp_dbg(dev, "kpb_copy: produced=%u bytes, triggering wov=0x%x", + copy_bytes, dev_comp_id(wov_comp)); + comp_copy(wov_comp); + } else { + comp_warn(dev, "kpb_copy: downstream sink_comp returned NULL!"); + } + } + + if (consume_bytes) + comp_update_buffer_consume(source, consume_bytes); break; case KPB_STATE_HOST_COPY: @@ -1506,13 +1669,22 @@ static int kpb_copy(struct comp_dev *dev) * (no HOST DMA IRQs) we need to call host copy * anyway so it can update its pointers. */ + struct comp_dev *host_comp = sink ? comp_buffer_get_sink_component(sink) : NULL; + if (host_comp) + comp_copy(host_comp); + ret = PPL_STATUS_PATH_STOP; break; } kpb_copy_samples(sink, source, copy_bytes, sample_width, channels); + buffer_stream_writeback(sink, copy_bytes); comp_update_buffer_produce(sink, copy_bytes); + struct comp_dev *host_comp = sink ? comp_buffer_get_sink_component(sink) : NULL; + if (host_comp) + comp_copy(host_comp); comp_update_buffer_consume(source, copy_bytes); + ret = PPL_STATUS_PATH_STOP; break; case KPB_STATE_INIT_DRAINING: @@ -1571,7 +1743,6 @@ static int kpb_buffer_data(struct comp_dev *dev, uint32_t offset = 0; uint64_t timeout = 0; uint64_t current_time; - enum kpb_state state_preserved = kpb->state; size_t sample_width = kpb->config.sampling_width; comp_dbg(dev, "entry"); @@ -1588,8 +1759,6 @@ static int kpb_buffer_data(struct comp_dev *dev, return PPL_STATUS_PATH_STOP; } - kpb_change_state(kpb, KPB_STATE_BUFFERING); - timeout = sof_cycle_get_64() + k_ms_to_cyc_ceil64(1); /* Let's store audio stream data in internal history buffer */ while (size_to_copy) { @@ -1674,10 +1843,35 @@ static int kpb_buffer_data(struct comp_dev *dev, } } - kpb_change_state(kpb, state_preserved); return ret; } +#if CONFIG_KPB_NOTIFIER +static void kpb_on_wov_ctrl(void *arg, enum notify_id id, void *data) +{ + struct comp_dev *dev = arg; + struct comp_data *kpb = comp_get_drvdata(dev); + const struct wov_ctrl_notif *n = data; + + if (n->cmd == WOV_ARB_CMD_RESUME) { + comp_info(dev, "kpb: received WOV_ARB_CMD_RESUME, current state=%d", kpb->state); + kpb_lock(kpb); + if (kpb->state == KPB_STATE_DRAINING || + kpb->state == KPB_STATE_INIT_DRAINING || + kpb->state == KPB_STATE_HOST_COPY) { + schedule_task_cancel(&kpb->draining_task); + kpb->draining_task_data.drain_req = 0; + if (kpb->hd.c_hb) + kpb_reset_history_buffer(kpb->hd.c_hb); + kpb->hd.buffered = 0; + kpb->hd.free = kpb->hd.buffer_size; + kpb_change_state(kpb, KPB_STATE_RUN); + comp_info(dev, "kpb: resumed to RUN state"); + } + kpb_unlock(kpb); + } +} +#endif /* CONFIG_KPB_NOTIFIER */ /** * \brief Main event dispatcher. * \param[in] arg - KPB component internal data. @@ -1693,6 +1887,11 @@ static void kpb_event_handler(void *arg, enum notify_id type, void *event_data) struct kpb_event_data *evd = event_data; struct kpb_client *cli = evd->client_data; + /* client data may have been written by another core */ + if (cli) + dcache_invalidate_region((__sparse_force void __sparse_cache *)cli, + sizeof(*cli)); + comp_info(dev, "received event with ID: %d ", evd->event_id); @@ -1786,11 +1985,12 @@ static void kpb_init_draining(struct comp_dev *dev, struct kpb_client *cli) size_t buffered = 0; size_t local_buffered; size_t drain_interval; - size_t host_period_size = kpb->host_period_size; - size_t bytes_per_ms = (size_t)KPB_SAMPLES_PER_MS * + size_t host_period_size; + size_t bytes_per_ms = (size_t)(kpb->config.sampling_freq / 1000) * (KPB_SAMPLE_CONTAINER_SIZE(sample_width) / 8) * kpb->config.channels; size_t period_bytes_limit; + bool is_sink_ready; comp_info(dev, "requested draining of %d [ms] from history buffer", cli->drain_req); @@ -1801,23 +2001,33 @@ static void kpb_init_draining(struct comp_dev *dev, struct kpb_client *cli) return; } + if (!kpb->host_period_size) { + kpb->host_period_size = bytes_per_ms; + kpb->host_buffer_size = audio_stream_get_size(&kpb->host_sink->stream); + } + host_period_size = kpb->host_period_size; + is_sink_ready = (comp_buffer_get_sink_state(kpb->host_sink) == COMP_STATE_ACTIVE || + comp_buffer_get_sink_state(kpb->host_sink) == COMP_STATE_PREPARE); + if (kpb->state != KPB_STATE_RUN) { - comp_err(dev, "wrong KPB state"); + comp_err(dev, "wrong KPB state: %d", kpb->state); } else if (cli->id > KPB_MAX_NO_OF_CLIENTS) { - comp_err(dev, "wrong client id"); + comp_err(dev, "wrong client id: %u", cli->id); /* TODO: check also if client is registered */ /* sel_sink is NULL before bind and after reset/unbind */ - } else if (!kpb->sel_sink || - comp_buffer_get_sink_state(kpb->host_sink) != COMP_STATE_ACTIVE) { - comp_err(dev, "sink not ready for draining"); - } else if (kpb->hd.buffered < drain_req || - cli->drain_req > KPB_MAX_DRAINING_REQ) { - comp_cl_err(&comp_kpb, "not enough data in history buffer"); + } else if (!kpb->sel_sink || !is_sink_ready) { + comp_err(dev, "sink not ready for draining (sel_sink=%p sink_state=%d)", + kpb->sel_sink, comp_buffer_get_sink_state(kpb->host_sink)); + } else if (cli->drain_req > kpb_get_buff_time_ms(kpb)) { + comp_cl_err(&comp_kpb, "drain request exceeds max"); } else { - /* Draining accepted, find proper buffer to start reading - * At this point we are guaranteed that there is enough data - * in the history buffer. All we have to do now is to calculate - * read pointer from which we will start draining. + if (kpb->hd.buffered < drain_req) { + comp_cl_warn(&comp_kpb, "partial pre-roll: capping drain to buffered"); + drain_req = kpb->hd.buffered; + } + /* Draining accepted, find proper buffer to start reading. + * If less history than requested is buffered, drain_req is + * capped above so we drain whatever is available. */ kpb_lock(kpb); @@ -1888,8 +2098,7 @@ static void kpb_init_draining(struct comp_dev *dev, struct kpb_client *cli) * shall take place. This time will be used to * synchronize us with application interrupts. */ - drain_interval = k_ms_to_cyc_ceil64(host_period_size / bytes_per_ms) / - KPB_DRAIN_NUM_OF_PPL_PERIODS_AT_ONCE; + drain_interval = k_ms_to_cyc_ceil64(host_period_size / bytes_per_ms); period_bytes_limit = host_period_size; comp_info(dev, "sync_draining_mode selected with interval %u [uS].", (unsigned int)k_cyc_to_us_near64(drain_interval)); @@ -1927,8 +2136,7 @@ static void kpb_init_draining(struct comp_dev *dev, struct kpb_client *cli) comp_set_attribute(comp_buffer_get_sink_component(kpb->host_sink), COMP_ATTR_COPY_TYPE, &kpb->force_copy_type); - /* Pause selector copy. */ - comp_buffer_get_sink_component(kpb->sel_sink)->state = COMP_STATE_PAUSED; + /* Do not pause selector copy; downstream detectors manage their own pause states */ if (!pm_runtime_is_active(PM_RUNTIME_DSP, PLATFORM_PRIMARY_CORE_ID)) pm_runtime_disable(PM_RUNTIME_DSP, PLATFORM_PRIMARY_CORE_ID); @@ -1967,10 +2175,10 @@ static void adjust_drain_interval(struct comp_data *kpb, struct draining_data *d /* average drained bytes per second */ actual_pace = (size_t)k_ms_to_cyc_ceil64(1000) / elapsed * drained; - pipeline_period = (size_t)KPB_SAMPLES_PER_MS * + pipeline_period = (size_t)(kpb->config.sampling_freq / 1000) * (KPB_SAMPLE_CONTAINER_SIZE(dd->sample_width) / 8) * kpb->config.channels; /* desired draining pace in bytes per second */ - optimal_pace = pipeline_period * KPB_DRAIN_NUM_OF_PPL_PERIODS_AT_ONCE * 1000; + optimal_pace = pipeline_period * 1000; /* just in case to prevent div by 0 if draining is stuck (e.g. because of host) */ if (actual_pace) { @@ -2035,6 +2243,11 @@ static enum task_state kpb_draining_task(void *arg) goto out; } + if (kpb->state != KPB_STATE_DRAINING) { + draining_data->drain_req = 0; + goto out; + } + adjust_drain_interval(kpb, draining_data); if (draining_data->drain_req > 0) { @@ -2077,20 +2290,23 @@ static enum task_state kpb_draining_task(void *arg) } if (size_to_copy) { + buffer_stream_writeback(sink, size_to_copy); comp_update_buffer_produce(sink, size_to_copy); - comp_copy(comp_buffer_get_sink_component(sink)); - } else if (!audio_stream_get_free_bytes(&sink->stream)) { - /* There is no free space in sink buffer. - * Call .copy() on sink component so it can - * process its data further. - */ - comp_copy(comp_buffer_get_sink_component(sink)); + struct comp_dev *host_comp = sink ? comp_buffer_get_sink_component(sink) : NULL; + if (host_comp) + comp_copy(host_comp); } if (sync_mode_on && draining_data->period_bytes >= period_bytes_limit) { draining_data->next_copy_time = draining_data->period_copy_start + draining_data->drain_interval; draining_data->period_copy_start = 0; + } else if (size_to_copy == 0 && draining_data->drain_req > 0) { + struct comp_dev *host_comp = sink ? comp_buffer_get_sink_component(sink) : NULL; + if (host_comp) + comp_copy(host_comp); + draining_data->next_copy_time = sof_cycle_get_64() + + (draining_data->drain_interval ? draining_data->drain_interval : k_ms_to_cyc_ceil64(1)); } else { draining_data->next_copy_time = 0; } @@ -2098,23 +2314,51 @@ static enum task_state kpb_draining_task(void *arg) /* also reached with a zero-length (no history) draining request */ if (draining_data->drain_req == 0) { - /* We have finished draining of requested data however - * while we were draining real time stream could provided - * new data which needs to be copy to host. - */ - comp_cl_info(&comp_kpb, "kpb: update drain_req by %zu", - *rt_stream_update); kpb_lock(kpb); - draining_data->drain_req += *rt_stream_update; - *rt_stream_update = 0; - if (!draining_data->drain_req && kpb->state == KPB_STATE_DRAINING) { - /* Draining is done. Now switch KPB to copy real time - * stream to client's sink. This state is called - * "draining on demand" - * Note! If KPB state changed during draining due to - * i.e reset request we should not change that state. + /* + * While draining of pre-roll history was underway, the real-time + * stream buffered newly arrived frames into the history buffer + * (*rt_stream_update). Drain them directly into the sink before + * transitioning to HOST_COPY so no frames are lost at the boundary. */ + while (*rt_stream_update > 0) { + buff = draining_data->hb; + avail = (uintptr_t)buff->end_addr - (uintptr_t)buff->r_ptr; + size_to_copy = MIN(avail, + MIN(*rt_stream_update, + audio_stream_get_free_bytes(&sink->stream))); + if (!size_to_copy) + break; + + kpb_drain_samples(buff->r_ptr, &sink->stream, size_to_copy, + sample_width); + + buff->r_ptr = (char *)buff->r_ptr + (uint32_t)size_to_copy; + *rt_stream_update -= size_to_copy; + draining_data->drained += size_to_copy; + kpb->hd.free += MIN(kpb->hd.buffer_size - + kpb->hd.free, size_to_copy); + + if (size_to_copy == avail) { + buff->r_ptr = buff->start_addr; + draining_data->hb = buff->next; + } + + buffer_stream_writeback(sink, size_to_copy); + comp_update_buffer_produce(sink, size_to_copy); + struct comp_dev *host_comp = sink ? comp_buffer_get_sink_component(sink) : NULL; + if (host_comp) + comp_copy(host_comp); + } + + if (*rt_stream_update == 0 && kpb->state == KPB_STATE_DRAINING) { + /* Draining is completely done. Switch KPB to copy real time + * stream to client's sink (HOST_COPY state). + */ kpb_change_state(kpb, KPB_STATE_HOST_COPY); + } else if (*rt_stream_update > 0) { + draining_data->drain_req = *rt_stream_update; + *rt_stream_update = 0; } kpb_unlock(kpb); } @@ -2378,30 +2622,6 @@ static void kpb_buffer_samples(const struct audio_stream *source, } } -/** - * \brief Initialize history buffer by zeroing its memory. - * \param[in] buff - pointer to current history buffer. - * - * \return: none. - */ -static void kpb_clear_history_buffer(struct history_buffer *buff) -{ - struct history_buffer *first_buff = buff; - void *start_addr; - size_t size; - - comp_cl_info(&comp_kpb, "entry"); - - do { - start_addr = buff->start_addr; - size = (uintptr_t)buff->end_addr - (uintptr_t)start_addr; - - bzero(start_addr, size); - - buff = buff->next; - } while (buff != first_buff); -} - static inline bool kpb_is_sample_width_supported(uint32_t sampling_width) { bool ret; @@ -2546,9 +2766,11 @@ static void kpb_reset_history_buffer(struct history_buffer *buff) if (!buff) return; - kpb_clear_history_buffer(buff); + do { + /* Reset to start so no stale data from a prior drain session is + * re-played on the next KPB activation. */ buff->w_ptr = buff->start_addr; buff->r_ptr = buff->start_addr; buff->state = KPB_BUFFER_FREE; @@ -2574,7 +2796,7 @@ static inline bool validate_host_params(struct comp_dev *dev, */ struct comp_data *kpb = comp_get_drvdata(dev); size_t sample_width = kpb->config.sampling_width; - size_t bytes_per_ms = (size_t)KPB_SAMPLES_PER_MS * + size_t bytes_per_ms = (size_t)(kpb->config.sampling_freq / 1000) * (KPB_SAMPLE_CONTAINER_SIZE(sample_width) / 8) * kpb->config.channels; size_t pipeline_period_size = (dev->pipeline->period / 1000) @@ -2898,6 +3120,16 @@ __cold static int kpb_set_large_config(struct comp_dev *dev, uint32_t param_id, #endif case KP_BUF_CLIENT_MIC_SELECT: return kpb_set_micselect(dev, data, data_offset); +#if CONFIG_IPC_MAJOR_4 + case KP_BUF_CFG_BUFF_TIME_MS: { + struct comp_data *kpb = comp_get_drvdata(dev); + if (data_offset < sizeof(uint32_t)) + return -EINVAL; + kpb->buff_time_ms = *(const uint32_t *)data; + comp_info(dev, "kpb: buff_time_ms set to %u ms", kpb->buff_time_ms); + return 0; + } +#endif default: return -EINVAL; } diff --git a/src/audio/kpb.toml b/src/audio/kpb.toml index e384632c1be8..60626997b96f 100644 --- a/src/audio/kpb.toml +++ b/src/audio/kpb.toml @@ -2,7 +2,7 @@ name = "KPB" uuid = UUIDREG_STR_KPB4 affinity_mask = "0x1" - instance_count = "1" + instance_count = "4" domain_types = "0" load_type = "0" module_type = "0xB" @@ -10,7 +10,12 @@ sched_caps = [1, 0x00008000] REM # pin = [dir, type, sample rate, size, container, channel-cfg] + REM # 1 source, 2 sinks: kpb.c drives a sel_sink (buf_id 0, the real-time + REM # feed to the detectors) and a host_sink (buf_id 1, the drain that + REM # bursts pre-roll to the host). Only one sink was declared here, so + REM # the drain path could not be bound from topology. pin = [0, 0, 0xfeef, 0xf, 0xf, 0x45ff, + 1, 0, 0xfeef, 0xf, 0xa, 0x45ff, 1, 0, 0xfeef, 0xf, 0xa, 0x45ff] REM # mod_cfg [PAR_0 PAR_1 PAR_2 PAR_3 IS_BYTES CPS IBS OBS MOD_FLAGS CPC OBLS] diff --git a/src/include/ipc4/kpb.h b/src/include/ipc4/kpb.h index 18476604728b..eb314ec2a600 100644 --- a/src/include/ipc4/kpb.h +++ b/src/include/ipc4/kpb.h @@ -32,6 +32,8 @@ struct ipc4_kpb_module_cfg { enum ipc4_kpb_module_config_params { /** Configure module IDs that execute within Fast Mode (FM) draining tasks. */ KP_BUF_CFG_FM_MODULE = 1, + /** Set history ring-buffer duration; 0 = use CONFIG_KPB_MAX_BUFF_TIME. */ + KP_BUF_CFG_BUFF_TIME_MS = 2, /** Real-time sink microphone channel selector ID. */ KP_BUF_CLIENT_MIC_SELECT = 11, }; diff --git a/src/include/sof/audio/kpb.h b/src/include/sof/audio/kpb.h index 74eeae964539..6c8007821637 100644 --- a/src/include/sof/audio/kpb.h +++ b/src/include/sof/audio/kpb.h @@ -26,17 +26,12 @@ #endif struct comp_buffer; +struct comp_dev *get_wov_detector_comp(uint32_t ppl_id); /* KPB internal defines */ -#if CONFIG_TIGERLAKE -#define KPB_MAX_BUFF_TIME 3000 /**< time of buffering in miliseconds */ -#define HOST_WAKEUP_TIME 1000 /* aprox. time of host DMA wakup from suspend [ms] */ -#else -/** Due to memory constraints on non-TGL platforms, the buffers are smaller. */ -#define KPB_MAX_BUFF_TIME 2100 /**< time of buffering in miliseconds */ -#define HOST_WAKEUP_TIME 0 /* aprox. time of host DMA wakup from suspend [ms] */ -#endif +#define KPB_MAX_BUFF_TIME CONFIG_KPB_MAX_BUFF_TIME /**< time of buffering in miliseconds */ +#define HOST_WAKEUP_TIME 0 /* host DMA already live; see CONFIG_KPB_MAX_BUFF_TIME */ #define KPB_MAX_DRAINING_REQ (KPB_MAX_BUFF_TIME - HOST_WAKEUP_TIME) #define KPB_MAX_SUPPORTED_CHANNELS 6 /**< number of supported channels */ @@ -47,7 +42,7 @@ struct comp_buffer; #define KPB_MAX_BUFFER_SIZE(sw, channels_number) ((KPB_SAMPLNG_FREQUENCY / 1000) * \ (KPB_SAMPLE_CONTAINER_SIZE(sw) / 8) * KPB_MAX_BUFF_TIME * \ (channels_number)) -#define KPB_MAX_NO_OF_CLIENTS 4 +#define KPB_MAX_NO_OF_CLIENTS CONFIG_KPB_MAX_NO_OF_CLIENTS #define KPB_MAX_SINK_CNT (1 + KPB_MAX_NO_OF_CLIENTS) #define KPB_NO_OF_HISTORY_BUFFERS 2 /**< no of internal buffers */ #define KPB_ALLOCATION_STEP 0x100 From fcd7f60008effffde13cb26b0dc25fc982ddaa0a Mon Sep 17 00:00:00 2001 From: Liam Girdwood Date: Mon, 16 Nov 2026 12:05:45 +0000 Subject: [PATCH 3/4] audio: wov_arbiter: add multi-slot WOV arbiter component Add the WOV arbiter component (CONFIG_COMP_WOV_ARBITER) to arbitrate between multiple concurrent keyword detector slots sharing a single host WoV capture PCM: - First-wins slot arbitration on NOTIFIER_ID_WOV_DETECT, broadcasting NOTIFIER_ID_WOV_CTRL pause/resume to sibling detectors. - Rate-limited PHRASE_DETECTED host notifications (sent once per detection) and active slot reset without requiring pipeline teardown. - Support mixed 16/32-bit sample widths, single active WoV PCM gating, and call-state gate control. Signed-off-by: Liam Girdwood Co-authored-by: Naveen Manohar Signed-off-by: Naveen Manohar Co-authored-by: Seppo Ingalsuo Signed-off-by: Seppo Ingalsuo Co-authored-by: Peter Ujfalusi Signed-off-by: Peter Ujfalusi --- src/audio/CMakeLists.txt | 3 + src/audio/Kconfig | 11 + src/audio/wov_arbiter/CMakeLists.txt | 3 + src/audio/wov_arbiter/README.md | 1502 ++++++++++++++++++++++++ src/audio/wov_arbiter/wov_arbiter.c | 813 +++++++++++++ src/audio/wov_arbiter/wov_arbiter.toml | 19 + src/include/sof/audio/component.h | 1 + tools/rimage/config/nvl.toml.h | 4 + tools/rimage/config/ptl.toml.h | 4 + tools/rimage/config/tgl.toml.h | 4 + tools/rimage/config/wcl.toml.h | 4 + uuid-registry.txt | 1 + 12 files changed, 2369 insertions(+) create mode 100644 src/audio/wov_arbiter/CMakeLists.txt create mode 100644 src/audio/wov_arbiter/README.md create mode 100644 src/audio/wov_arbiter/wov_arbiter.c create mode 100644 src/audio/wov_arbiter/wov_arbiter.toml diff --git a/src/audio/CMakeLists.txt b/src/audio/CMakeLists.txt index 0ca532950f5c..205b7479ee24 100644 --- a/src/audio/CMakeLists.txt +++ b/src/audio/CMakeLists.txt @@ -122,6 +122,9 @@ endif() if(CONFIG_COMP_WEBRTC_HPF) add_subdirectory(webrtc_hpf) endif() +if(CONFIG_COMP_WOV_ARBITER) + add_subdirectory(wov_arbiter) +endif() if(CONFIG_DTS_CODEC) add_subdirectory(codec) endif() diff --git a/src/audio/Kconfig b/src/audio/Kconfig index 8468570fe45a..8a3579b1cd08 100644 --- a/src/audio/Kconfig +++ b/src/audio/Kconfig @@ -153,6 +153,17 @@ config COMP_STUBS Select to force all 3P blocks to link against stubs rather than their libraries. This should only be used in testing environments like fuzzers or CI. +config COMP_WOV_ARBITER + bool "WOV arbiter component" + depends on COMP_KPB + depends on IPC_MAJOR_4 + help + Select to build the WOV (Wake-on-Voice) arbiter. The arbiter sits + between multiple KPB host-drain outputs and a single host PCM copier. + When a keyword is detected by one of the WOV detectors the arbiter + routes that KPB's drain stream to the host and instructs the remaining + detectors to pause. + config COMP_KPB bool "KPB component" default y diff --git a/src/audio/wov_arbiter/CMakeLists.txt b/src/audio/wov_arbiter/CMakeLists.txt new file mode 100644 index 000000000000..fd15150321c6 --- /dev/null +++ b/src/audio/wov_arbiter/CMakeLists.txt @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: BSD-3-Clause + +add_local_sources(sof wov_arbiter.c) diff --git a/src/audio/wov_arbiter/README.md b/src/audio/wov_arbiter/README.md new file mode 100644 index 000000000000..e9b18fbe8d80 --- /dev/null +++ b/src/audio/wov_arbiter/README.md @@ -0,0 +1,1502 @@ +# Multi-Slot Wake-On-Voice (WOV) Architecture & Arbitration + +## Overview + +The Multi-Slot WOV subsystem lets a single DMIC feed concurrent keyword detectors +running on the DSP. Audio is captured directly over a standard ALSA PCM capture device +(`hw:0,11`, 16 kHz, 2-channel, S16_LE / S32_LE). + +Audio stream capture and device verification are executed using direct Linux ALSA UAPI ioctls +(`tools/wov_capture/wov_capture_app`) or standard ALSA tools (`arecord`). + +--- + +## Table of Contents + +1. [System Architecture](#system-architecture) +2. [Signal Processing Flow](#signal-processing-flow) +3. [Arbiter State Machine](#arbiter-state-machine) +4. [Pipeline State Transitions & Re-Arm Cycle](#pipeline-state-transitions--re-arm-cycle) + - [WoV Call-State Control](#wov-call-state-control) +5. [SOF Notifier Inter-Module Signaling](#sof-notifier-inter-module-signaling) +6. [Firmware API Reference](#firmware-api-reference) +7. [Linux Host API Reference](#linux-host-api-reference) +8. [Adding a New WOV Algorithm](#adding-a-new-wov-algorithm) +9. [Topology: Build and Deploy](#topology-build-and-deploy) +10. [Build System Configuration](#build-system-configuration) +11. [Testing and Verification](#testing-and-verification) + +--- + +## System Architecture + +The Multi-Slot WOV subsystem supports two primary topology architectures: +1. **4-Channel Native 16 kHz DMIC with ECNS & Multi-Slot WOV** (PTL, TGL, WCL 4ch native manifests). +2. **2-Channel DMIC / SSP Direct Multi-Slot WOV** (2ch manifests). + +--- + +#### Architecture A: Dual-Rate DMIC with ECNS & microWakeWord (MWW) Multi-Slot WOV + +In this architecture, two dedicated physical PDM digital microphone interfaces feed the **ECNS DP module** running at a 20 ms period: +- **PDM1 (`dmic16k`)**: Dedicated 16 kHz stereo stream via Pipeline 119 feeding ECNS Input Pin 0. +- **PDM0 (`dmic01`)**: Dedicated 48 kHz stereo stream via Pipeline 110 feeding ECNS Input Pin 1. + +The ECNS module processes both streams and outputs: +- **Pin 0 (mono clean speech)**: Extracts the Left channel from Pin 0 in to produce a 16 kHz mono clean stream. Routes to KPB (Pipeline 116, 2.0s history depth = 64 KB mono buffer), then fans out via `mixin.116.1` to 3 concurrent **microWakeWord (MWW)** keyword spotting slots (running MFCC feature extraction + TFLM streaming graph in lock-step). Upon keyword detection, the detector notifies KPB (`NOTIFIER_ID_KPB_CLIENT_EVT`) to drain and the WOV Arbiter (`NOTIFIER_ID_WOV_DETECT`) to set `wov_active_slot` and pause sibling slots. The WOV Arbiter routes the active slot audio (pre-roll + live) to ALSA PCM 12 (`hw:0,12`, `DMIC Multi-WOV`, `capture_compatible_d0i3: true`). +- **Pin 1 (stereo clean speech)**: Performs a 1-to-1 copy of Pin 1 in to produce a 48 kHz stereo clean stream routed to Host Copier 11 (ALSA PCM 11, `hw:0,11`, `DMIC ECNS Capture`, `capture_compatible_d0i3: true`). + +```mermaid +flowchart TD + %% Hardware PDM Interfaces + subgraph PDM_INTERFACES ["Digital Microphone Interfaces (2 Separate PDM DAIs)"] + direction LR + PDM_48K["PDM Interface: dmic01
DAI Index: 0 (PDM0)
Rate: 48 kHz · 2ch Stereo · 16-bit"] + PDM_16K["PDM Interface: dmic16k
DAI Index: 1 (PDM1)
Rate: 16 kHz · 2ch Stereo · 16-bit"] + end + + %% Pipeline 110: 48 kHz DAI Capture + subgraph P110 ["Pipeline 110: 48 kHz DAI Capture (Core 0, LL 1ms)"] + DAI_48K["dai-copier.DMIC.dmic01.capture
(48 kHz · 2ch · S16_LE)"] + MIXIN_110["mixin.110.1
(48 kHz · 2ch)"] + DAI_48K --> MIXIN_110 + end + + %% Pipeline 119: 16 kHz DAI Capture + subgraph P119 ["Pipeline 119: 16 kHz DAI Capture (Core 0, LL 1ms)"] + DAI_16K["dai-copier.DMIC.dmic16k.capture
(16 kHz · 2ch · S16_LE)"] + MIXIN_119["mixin.119.1
(16 kHz · 2ch)"] + DAI_16K --> MIXIN_119 + end + + PDM_48K --> DAI_48K + PDM_16K --> DAI_16K + + %% Pipeline 115: Dual-Rate ECNS DP Pipeline + subgraph P115 ["Pipeline 115: ECNS Engine (Core 0, DP 20ms, lp_mode 1)"] + direction TB + + MIXOUT_115_2["mixout.115.2
(Pin 0 In: 16 kHz · 2ch stereo)"] + MIXOUT_115_1["mixout.115.1
(Pin 1 In: 48 kHz · 2ch stereo)"] + + ECNS["ecns.115.1 (DP Component · 20ms Period)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Pin 0 In: 16 kHz, 2ch (IBS 1280 bytes)
Pin 1 In: 48 kHz, 2ch (IBS 3840 bytes)
─────────────────────────────
Processing:
• Pin 0: Extract Left Ch → 16k Mono Clean
• Pin 1: 1-to-1 Stereo Copy → 48k Stereo Clean
─────────────────────────────
Pin 0 Out: 16 kHz, 1ch mono (OBS 640 bytes)
Pin 1 Out: 48 kHz, 2ch stereo (OBS 3840 bytes)"] + + MIXOUT_115_2 -->|"Pin 0 In (16k)"| ECNS + MIXOUT_115_1 -->|"Pin 1 In (48k)"| ECNS + end + + MIXIN_119 --> MIXOUT_115_2 + MIXIN_110 --> MIXOUT_115_1 + + %% Pipeline 117: Host Capture PCM 11 + subgraph P117 ["Pipeline 117: ECNS Clean Host Capture (Core 0, LL 1ms)"] + HOST_11["host-copier.11.capture
(PCM 11: 'DMIC ECNS Capture'
hw:0,11 · d0i3_compatible=true)"] + end + + %% Pipeline 116: KPB History Buffer + subgraph P116 ["Pipeline 116: Key Phrase Buffer (Core 0, DP 20ms)"] + KPB["kpb.116.1
(2000 ms mono history = 64 KB)"] + MIXIN_116["mixin.116.1
(3-way detector fanout)"] + KPB -->|"Pin 0 (Live Feed)"| MIXIN_116 + end + + ECNS -->|"Pin 1 Out (Stereo 48k clean direct)"| HOST_11 + ECNS -->|"Pin 0 Out (Mono 16k clean direct)"| KPB + + %% WoV 3-Slot Detector Subgraph + subgraph SLOTS ["Wake-on-Voice Keyword Detector Slots (16 kHz mono)"] + subgraph S1 ["Slot 0 (Pipeline 111)"] + M1["mixout.111.1"] --> MF1["mfcc.111.1"] --> MW1["mww.111.1"] + end + subgraph S2 ["Slot 1 (Pipeline 112)"] + M2["mixout.112.1"] --> MF2["mfcc.112.1"] --> MW2["mww.112.1"] + end + subgraph S3 ["Slot 2 (Pipeline 113)"] + M3["mixout.113.1"] --> MF3["mfcc.113.1"] --> MW3["mww.113.1"] + end + end + + MIXIN_116 --> M1 + MIXIN_116 --> M2 + MIXIN_116 --> M3 + + %% Pipeline 114: WoV Arbiter & Host Capture PCM 12 + subgraph P114 ["Pipeline 114: WoV Arbiter (Core 0, LL 1ms)"] + ARB["wov-arbiter.114.1
• Pin 0: Drained audio stream
• Pins 1-3: Keyword triggers"] + HOST_12["host-copier.12.capture
(PCM 12: 'DMIC Multi-WOV'
hw:0,12 · d0i3_compatible=true)"] + ARB --> HOST_12 + end + + KPB -->|"Pin 1 (Host Sink Drain)"| ARB + MW1 -->|"Pin 1 (Trigger 0)"| ARB + MW2 -->|"Pin 2 (Trigger 1)"| ARB + MW3 -->|"Pin 3 (Trigger 2)"| ARB + + MW1 -. "Notifier WOV_DETECT (slot=0)" .-> ARB + MW2 -. "Notifier WOV_DETECT (slot=1)" .-> ARB + MW3 -. "Notifier WOV_DETECT (slot=2)" .-> ARB + MW1 -. "Notifier KPB_CLIENT_EVT (DRAIN 2s)" .-> KPB + MW2 -. "Notifier KPB_CLIENT_EVT (DRAIN 2s)" .-> KPB + MW3 -. "Notifier KPB_CLIENT_EVT (DRAIN 2s)" .-> KPB + ARB -. "Notifier WOV_CTRL (PAUSE/RESUME)" .-> MW1 + ARB -. "Notifier WOV_CTRL (PAUSE/RESUME)" .-> MW2 + ARB -. "Notifier WOV_CTRL (PAUSE/RESUME)" .-> MW3 + + style ECNS fill:#1b4f72,stroke:#555,color:#fff + style KPB fill:#1c4966,stroke:#555,color:#fff + style ARB fill:#4a235a,stroke:#555,color:#fff + style HOST_11 fill:#1e8449,stroke:#555,color:#fff + style HOST_12 fill:#2d5a27,stroke:#555,color:#fff +``` + +#### Dual-Rate Architecture Specifications across Target Platforms (PTL, TGL, WCL) + +The dual-rate DMIC architecture is deployed across **Panther Lake (PTL)**, **Tiger Lake (TGL)**, and **Wildcat Lake (WCL)** via `platform/intel/dmic-wov-multi.conf` and `dmic-wov-feature.conf`: + +| Property | ECNS Clean Stream (PCM 11) | WOV Stream (PCM 12) | +|---|---|---| +| ALSA Device | `hw:0,11` (`pcmC0D11c`) | `hw:0,12` (`pcmC0D12c`) | +| Sample Rate | 48 kHz | 16 kHz | +| Channels | 2 (Stereo clean mic) | 1 (Mono clean mic) | +| Sample Format | S16_LE / S32_LE | S16_LE / S32_LE | +| History / Pre-roll | Live streaming | 2.0 s (64 KB mono buffer in KPB) | +| Keyword Spotters | N/A | 3 concurrent slots: 0="strawberry", 1="hi intel", 2="orange" | +| Keyword Control | N/A | `wov_active_slot` enum (0=Listening, 1=Slot 0, 2=Slot 1, 3=Slot 2) | +| Scheduling | Core 0 (LL 1ms) | Core 0 (LL 1ms arbiter + DP 20ms KPB + DP 10ms MWW) | +| Processing Source | ECNS Pin 1 (1-to-1 copy of 48k `dmic01`) | ECNS Pin 0 (mono Left ch of 16k `dmic16k`) via KPB & WOV Arbiter | +| D0i3 Low Power | **Yes** (`capture_compatible_d0i3: true`) | **Yes** (`capture_compatible_d0i3: true`) | + +--- + +### Architecture B: 2-Channel Direct DMIC / SSP Multi-Slot WOV + +For 2-channel capture topologies (`dmic-wov-multi-manifest.conf`, `sspX-wov-multi-manifest.conf`): + +```mermaid +graph TD + subgraph P100["Pipeline 100 — Capture & History Buffer (Core 0)"] + DAI["DAI Copier\n(48 kHz 4ch NHLT / 16 kHz SSP)"] + SRC["SRC (optional)\n(48 kHz -> 16 kHz)"] + KPB["kpb\n(16 kHz shared history ring buffer)"] + MIX["mixin\n(fan-out)"] + DAI --> SRC --> KPB --> MIX + end + + subgraph P101["Pipeline 101 — Slot 0 (Core 0)"] + MO0["mixout 0"] + D0["detect_test\nSlot 0\n(Male 80–170 Hz)"] + MO0 --> D0 + end + + subgraph P102["Pipeline 102 — Slot 1 (Core 0)"] + MO1["mixout 1"] + D1["detect_test\nSlot 1\n(Female 175–270 Hz)"] + MO1 --> D1 + end + + subgraph P103["Pipeline 103 — Slot 2 (Multi-slot) (Core 1)"] + MO2["mixout 2"] + D2["detect_test\nSlot 2\n(Child 275–500 Hz)"] + MO2 --> D2 + end + + subgraph P104["Pipeline 104 — Host Regular PCM Capture (Core 0)"] + ARB["wov_arbiter\n(3 input pins)"] + HC["host-copier\npcmC0D11c (hw:0,11)\n'DMIC Multi-WOV'"] + ARB --> HC + end + + MIX --> MO0 + MIX --> MO1 + MIX --> MO2 + + D0 --> ARB + D1 --> ARB + D2 --> ARB + + D0 -- "Notifier WOV_DETECT\n(slot_id=0)" --> ARB + D1 -- "Notifier WOV_DETECT\n(slot_id=1)" --> ARB + D2 -- "Notifier WOV_DETECT\n(slot_id=2)" --> ARB + ARB -- "Notifier WOV_CTRL\n(PAUSE/RESUME)" --> D0 + ARB -- "Notifier WOV_CTRL\n(PAUSE/RESUME)" --> D1 + ARB -- "Notifier WOV_CTRL\n(PAUSE/RESUME)" --> D2 + + style KPB fill:#1c4966,stroke:#555,color:#fff + style D0 fill:#663300,stroke:#555,color:#fff + style D1 fill:#660033,stroke:#555,color:#fff + style D2 fill:#003366,stroke:#555,color:#fff + style ARB fill:#4a235a,stroke:#555,color:#fff + style HC fill:#2d5a27,stroke:#555,color:#fff +``` + +#### 2-Channel Architecture Specifications + +| Property | Value | +|---|---| +| Audio format | 16 kHz · 2ch · S16_LE / S32_LE | +| KPB pre-roll (TigerLake) | 6 000 ms (192 000 bytes) | +| KPB pre-roll (other) | 2 100 ms | +| Max arbiter slots | 3 (topology), 8 (header constant) | +| Arbitration policy | First-wins; subsequent detections ignored until RESUME | +| Slot 2 core affinity | DSP Core 1 (cross-core scheduling validation) | +| Host capture device | card 0, device 11 — `hw:0,11` / `pcmC0D11c` (ALSA PCM) | +| Audio Delivery | Standard ALSA PCM capture stream (16 kHz, 2-channel, 16-bit / 32-bit) | +| D0i3 / S0iX | Supported — `capture_compatible_d0i3 true` on host-copier and PCM widget | + +--- + +## Signal Processing Flow + +### LL Thread Path (every 1 ms) + +```mermaid +flowchart LR + HW["HW DMA\n(DMIC interrupt)"] + DAI_COPY["dai_copier.copy()\nPipeline 100"] + SRC_COPY["src.copy()\n48k -> 16k"] + KPB_COPY["kpb.copy()\n16k ring buffer"] + MIXIN["mixin.copy()\nfan-out"] + MIXOUT["mixout_N.copy()"] + DT_COPY["detect_test.copy()\naccumulate 320 frames\nthen k_sem_give()"] + + HW --> DAI_COPY --> SRC_COPY --> KPB_COPY --> MIXIN + MIXIN --> MIXOUT --> DT_COPY +``` + +### DP Thread Path (every 20 ms per slot) + +Each slot has its own `k_thread` at `K_PRIO_PREEMPT(12)` executing batch processing. + +```mermaid +flowchart TD + SEM["k_sem_take()"] + CHECK{dp_thread_active?} + BUF["read dp_buf[read_slot]\n320 × S16_LE samples"] + DETECT["run detection algorithm\n(zero-crossing + energy)"] + FOUND{match?} + NOTIFY["detect_test_notify(dev)\n① IPC4 → host\n② KPB drain (notify_event)\n③ Notifier WOV_DETECT → arbiter"] + AUTOTRIG["auto-trigger\n(test only, limit=320 frames)"] + LOOP(["loop"]) + + SEM --> CHECK + CHECK -- "false" --> EXIT(["thread exits"]) + CHECK -- "true" --> BUF --> DETECT --> FOUND + FOUND -- "yes" --> NOTIFY --> LOOP + FOUND -- "no" --> AUTOTRIG --> LOOP + LOOP --> SEM +``` + +### KPB Drain Sequence (triggered by Notifier) + +```mermaid +flowchart LR + NOTIF_EVT["Notifier WOV_DETECT\n→ arb_on_detect()"] + DRAIN["drain KPB history ring buffer\n(up to 6 s pre-roll)\nto host capture buffer"] + LIVE["continue forwarding\nlive audio to host PCM"] + + NOTIF_EVT --> DRAIN --> LIVE +``` + +--- + +## Arbiter State Machine + +```mermaid +stateDiagram-v2 + [*] --> Idle : wov_arb_new() / prepare()\nactive_slot = NO_ACTIVE\nbroadcast RESUME + + Idle --> Active : Notifier WOV_DETECT(slot_id=N)\nactive_slot = N\nbroadcast PAUSE(N) + + Active --> Active : Notifier WOV_DETECT(slot_id=M)\n[first-wins: ignored] + + Active --> Idle : trigger(STOP or PAUSE)\nactive_slot = NO_ACTIVE\nbroadcast RESUME + + Idle --> [*] : wov_arb_free() +``` + +### `wov_arb_copy()` Routing Logic + +| Condition | Active slot buffer | Idle slot buffers | Sink output | +|---|---|---|---| +| `active_slot == NO_ACTIVE` | — | drained and discarded | filled with silence (memset 0) | +| `active_slot == N` | copied frame-aligned to sink | drained and discarded | pre-roll + live audio | + +The first-wins guard in `arb_on_detect()`: + +```c +if (cd->active_slot != WOV_ARB_NO_ACTIVE) { + comp_warn(dev, "wov_arb: slot %u fired but slot %u already active, ignoring", + det->slot_id, cd->active_slot); + return; +} +``` + +--- + +## Pipeline State Transitions & Re-Arm Cycle + +### Usage Flow (PCM Capture Stream Lifecycle) + +The PCM capture stream can be opened at startup or on-demand: + +```text +Host Kernel / ASoC Firmware +──── ───────────── ──────── +open pcmC0D11c ──► SET_PIPELINE_STATE(RUNNING) ──► KPBs: KPB_STATE_BUFFERING (filling history) + detect_tests: dp_thread running, listening + +─────────────────────── Listening / Capture ─────────────────────────── +arecord / wov_capture_app captures frames at 16 kHz 2-channel from hw:0,11 +``` + +### State Transition Summary + +| State | Transition | Trigger | PCM Capture device | +|---|---|---|---| +| Listening → Active | WOV_DETECT | detect_test fires | Stays OPEN | +| Active → Listening | STOP/PAUSE | host or driver closes/re-arms | Stays OPEN (re-armed) | +| Any → closed | close() | host exits | Closed | + +### WoV Call-State Control + +Set `DMIC WoV Call State` to `Call Active` to pause all detectors. The arbiter +acknowledges after detector callbacks complete; set it to `Listening` to resume. + +The acknowledgement confirms detector gating, not pipeline teardown. The Audio +HAL must close the WoV pipeline and wait for teardown before starting the call +path. On call end, close the call path before reopening WoV. + +--- + +## SOF Notifier Inter-Module Signaling + +The SOF Notifier system (`src/include/sof/lib/notifier.h`) is SOF's intra-DSP +publish/subscribe bus. It works on all platforms (no `CONFIG_AMS` required) and +is already used for KPB client events. Signals are delivered synchronously to +all registered listeners on the calling core. + +### Signal Catalog + +| Notifier ID | Direction | Payload struct | Purpose | +|---|---|---|---| +| `NOTIFIER_ID_WOV_DETECT` | detector → arbiter | `struct wov_detect_notif { uint8_t slot_id; }` | Announce keyword detection | +| `NOTIFIER_ID_WOV_CTRL` | arbiter → all detectors | `struct wov_ctrl_notif { uint8_t cmd; }` | Pause/resume detectors | + +`cmd` values: `WOV_ARB_CMD_PAUSE`, `WOV_ARB_CMD_RESUME` (defined in `wov_arbiter.h`). + +### Full Detect-to-Drain Sequence + +```mermaid +sequenceDiagram + autonumber + participant DMIC as DMIC (HW) + participant KPB as KPB N + participant DET as detect_test (slot N) + participant ARB as wov_arbiter + participant HOST as Host PCM (hw:0,11) + participant OTHER as detect_test (slots ≠ N) + + Note over DMIC,OTHER: Listening state — all slots accumulating pre-roll + + loop Every 1 ms (LL period) + DMIC->>KPB: DAI DMA frames + KPB->>DET: sel_sink copy + end + + loop Every 20 ms (DP batch) + DET->>DET: run algorithm on 320-frame batch + end + + Note over DET,ARB: Keyword detected on slot N + + DET->>HOST: ① IPC4 SOF_IPC4_NOTIFY_PHRASE_DETECTED\n (word_id = slot_id) + DET->>KPB: ② notifier_event(WOV_DETECT) [KPB already wired via kpb_client] + DET->>ARB: ③ notifier_event(NOTIFIER_ID_WOV_DETECT, slot_id=N) + + ARB->>ARB: active_slot = N + ARB->>OTHER: notifier_event(NOTIFIER_ID_WOV_CTRL, cmd=PAUSE) + OTHER->>OTHER: cd->paused = true\n(stops DP batching) + + KPB->>ARB: stream pre-roll (up to 6 s) via host_sink + ARB->>HOST: route slot-N audio to host PCM + + Note over HOST,ARB: Host finishes reading / closes PCM + + HOST->>ARB: trigger STOP (ALSA hw_free / snd_pcm_close) + ARB->>ARB: active_slot = NO_ACTIVE + ARB->>OTHER: notifier_event(NOTIFIER_ID_WOV_CTRL, cmd=RESUME) + ARB->>DET: notifier_event(NOTIFIER_ID_WOV_CTRL, cmd=RESUME) + OTHER->>OTHER: cd->paused = false\ncd->detected = 0\nresumed listening +``` + +--- + +## Firmware API Reference + +### IPC4 Module Parameters (`LARGE_CONFIG_SET`) + +#### `detect_test` — automatic slot assignment via pipeline ID + +Each `detect_test` instance is automatically assigned its slot ID in `test_keyword_new()` +based on its pipeline ID: + +| Pipeline ID | Target module | Core | Assigned Slot | +|---|---|---|---| +| 101 | `wov.101.1` | Core 0 | Slot 0 | +| 102 | `wov.102.1` | Core 0 | Slot 1 | +| 103 | `wov.103.1` | Core 1 | Slot 2 | + +No user-space initialization kcontrols are required. + +#### `wov_arbiter` — active slot status via `Phrase Detect ID` enum kcontrol + +The `wov_arbiter` instances expose a volatile read-only ALSA enum kcontrol named `DMIC Phrase Detect ID` +(for DMIC WoV graphs) or `Jack In Phrase Detect ID` (for SoundWire headset WoV graphs; legacy topologies +use `wov_active_slot`) that reports the current arbitration and keyword detection state: + +| Enum Index | Item Name | Meaning | +|---|---|---| +| `0` | `Listening` | No keyword detected / idle / listening | +| `1` | `Slot 1` | Slot 0 (Pipeline 101/111/201) triggered and active | +| `2` | `Slot 2` | Slot 1 (Pipeline 102/112/202) triggered and active | +| `3` | `Slot 3` | Slot 2 (Pipeline 103/113/203) triggered and active | + +When a keyword detector fires, the arbiter updates `cd->active_slot` and automatically sends an +ALSA control change notification (`SOF_IPC4_MODULE_NOTIFICATION` with `SOF_IPC4_ENUM_CONTROL_PARAM_ID`) +to notify the kernel / ALSA mixer of the state transition. When the capture stream is stopped or reset, +the arbiter transitions back to `Listening` (`0`) and sends a notification. + +Query the control from userspace: + +```bash +# For DMIC WoV: +amixer -c 0 cget name='DMIC Phrase Detect ID' + +# For SDW Headset WoV: +amixer -c 0 cget name='Jack In Phrase Detect ID' +``` + +#### `detect_test` — per-slot mute via `wov_mute_1NN` switch kcontrol + +Each `detect_test` instance also exposes a boolean switch kcontrol that gates +detection at runtime without tearing down the pipeline. + +| ALSA kcontrol name | numid (TGL) | Default | Effect when set | +|---|---|---|---| +| `wov_mute_101` | 13 | `off` | `off` = muted (no detection), `on` = detection active | +| `wov_mute_102` | 16 | `off` | `off` = muted (no detection), `on` = detection active | +| `wov_mute_103` | 19 | `off` | `off` = muted (no detection), `on` = detection active | + +The default at pipeline open is `off` (muted). Userspace must explicitly write `on` +to arm a slot. When muted, `test_keyword_copy` drains the source buffer and returns +without running the detection algorithm, keeping the LL scheduler running at zero +detection cost. When re-enabled, detection resumes immediately on the next LL tick. + +Wire format: `LARGE_CONFIG_SET` with `PARAM_ID = 200` +(`SOF_IPC4_SWITCH_CONTROL_PARAM_ID`), payload +`struct sof_ipc4_control_msg_payload { .id=0, .num_elems=1, .chanv[0].value=0|1 }`. + +```bash +# Arm slot 1 for detection (numid=16 = wov_mute_102) +amixer -c 0 cset numid=16 on + +# Mute slot 1 again +amixer -c 0 cset numid=16 off +``` + +#### `detect_test` — momentary test trigger via `wov_test_1NN` switch kcontrol + +Each `detect_test` instance exposes a momentary boolean switch kcontrol that forces an +immediate keyword detection trigger on the slot. + +| ALSA kcontrol name | numid (TGL) | Default | Effect when set | +|---|---|---|---| +| `wov_test_101` | 14 | `off` | Write `on` to trigger detection for slot 0; auto-resets to `off` | +| `wov_test_102` | 17 | `off` | Write `on` to trigger detection for slot 1; auto-resets to `off` | +| `wov_test_103` | 20 | `off` | Write `on` to trigger detection for slot 2; auto-resets to `off` | + +Wire format: `LARGE_CONFIG_SET` with `PARAM_ID = 200` (`SOF_IPC4_SWITCH_CONTROL_PARAM_ID`), +payload `struct sof_ipc4_control_msg_payload { .id=1, .num_elems=1, .chanv[0].value=1 }`. + +When `wov_test_1NN` receives a write of value `1`: +1. The firmware logs `kd_test: TEST SWITCH TRIGGER for slot N!`. +2. It sets `cd->detected = 1` and calls `detect_test_notify(dev)` to trigger KPB history buffer drain and notify the WOV arbiter. +3. The firmware sends an IPC4 module notification (`SOF_IPC4_MODULE_NOTIFICATION` with `SOF_IPC4_NOTIFY_MODULE_EVENTID_ALSA_MAGIC_VAL | SOF_IPC4_SWITCH_CONTROL_PARAM_ID`) to reset the ALSA mixer switch value back to `0` (`off`) on the host. + +```bash +# Trigger detection on slot 0 (numid=14 = wov_test_101) +amixer -c 0 cset numid=14 on + +# Trigger detection on slot 1 (numid=17 = wov_test_102) +amixer -c 0 cset numid=17 on + +# Trigger detection on slot 2 (numid=20 = wov_test_103) +amixer -c 0 cset numid=20 on +``` + + +### `wov_arbiter` — slot count from `nb_input_pins` + +The arbiter reads the number of active slots from `ipc4_base_module_cfg_ext.nb_input_pins` +(set in `wov-arbiter.conf` via `num_input_pins = 3`). + +### Notifier Registration + +A WOV detector must register for `WOV_CTRL` notifications during `prepare()`: + +```c +notifier_register(dev, NULL, NOTIFIER_ID_WOV_CTRL, on_wov_ctrl); +``` + +Unregister in `free()`: + +```c +notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_CTRL); +``` + +### `detect_test_notify(dev)` — Detection Announcement + +Call this from your detection algorithm when a keyword is confirmed: + +```c +void detect_test_notify(const struct comp_dev *dev); +``` + +Internally executes three steps: +1. Sends `SOF_IPC4_NOTIFY_PHRASE_DETECTED` IPC4 notification to host +2. Sends `kpb_client` notifier event to KPB → triggers pre-roll drain on `host_sink` +3. Fires `notifier_event(NOTIFIER_ID_WOV_DETECT)` → `wov_arbiter.arb_on_detect()` activates this slot + +### DP Thread Ping-Pong Buffer Contract + +| Field | Type | Semantics | +|---|---|---| +| `dp_buf[2][320]` | `int16_t` | ping-pong accumulation buffer | +| `dp_buf_frames` | `uint32_t` | frames in write slot (0 to 319) | +| `dp_write_slot` | `uint8_t` | index (0 or 1) LL writes into | +| `dp_read_slot` | `uint8_t` | index DP thread reads from | +| `dp_sem` | `struct k_sem` | binary semaphore, max count = 1 | +| `dp_thread_active` | `bool` | false → thread exits on next wake | + +LL thread gives semaphore after every 320 accumulated frames. +DP thread takes semaphore and processes `dp_buf[dp_read_slot]`. +Missing a give (while thread is still processing) drops that batch silently +(semaphore max count = 1 prevents accumulation). + +--- + +## Linux Host API Reference + +### ALSA Regular PCM Capture + +The WOV audio is exposed as a standard **ALSA PCM** capture device (`hw:0,11` or `/dev/snd/pcmC0D11c`). +Standard tools like `arecord` and the zero-dependency C capture utility `wov_capture_app` interact directly with this endpoint: + +```text +Card: 0 PCM device: 11 Name: "DMIC Multi-WOV" (/dev/snd/pcmC0D11c) +Formats: S16_LE / S32_LE (raw PCM) +Rate: 16000 Hz +Channels: 2 (stereo) +``` + +Capture using `arecord`: + +```bash +arecord -D hw:0,11 -f S16_LE -r 16000 -c 2 -d 3 /tmp/wov_capture.wav +``` + +Zero-dependency C API flow using direct Linux ALSA kernel UAPI ioctls: + +```c +#include +#include +#include +#include + +int fd = open("/dev/snd/pcmC0D11c", O_RDWR); + +/* 1. Configure HW parameters (rate, channels, format, periods) */ +struct snd_pcm_hw_params params; +snd_pcm_hw_params_any(¶ms); +/* ... set rate=16000, channels=2, format=SNDRV_PCM_FORMAT_S16_LE ... */ +ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, ¶ms); + +/* 2. Configure SW parameters and prepare */ +ioctl(fd, SNDRV_PCM_IOCTL_PREPARE); + +/* 3. Start stream and capture frames via SNDRV_PCM_IOCTL_READI_FRAMES */ +struct snd_xferi xfer = { .buf = audio_buffer, .frames = period_size }; +ioctl(fd, SNDRV_PCM_IOCTL_READI_FRAMES, &xfer); + +/* 4. Stop and close */ +ioctl(fd, SNDRV_PCM_IOCTL_DROP); +close(fd); +``` + +### Voice Detection Notification from Firmware + +When a keyword is detected, the `detect_test` DP thread calls `detect_test_notify()` which: + +1. Sends `SOF_IPC4_NOTIFY_PHRASE_DETECTED` (IPC4 global notification, type=4) to the host. +2. Fires the KPB notifier to stream audio on the host capture pipeline. +3. Fires the `NOTIFIER_ID_WOV_DETECT` SOF notifier to the `wov_arbiter`. + +The `word_id` field (bits 15:0 of the primary DW) carries the `wov_slot_id` (0, 1, or 2). + +### D0i3 / S0iX Support + +The WOV capture stream supports D0i3 runtime PM autosuspend and wake-up transitions: + +```text +# dmic-wov-multi-manifest.conf +Object.Widget.host-copier."...": + capture_compatible_d0i3 true # host-copier allows D0i3 + +Object.PCM.pcm."$DMIC_PCM_ID": + capture_compatible_d0i3 true # PCM object allows D0i3 +``` + +### IPC4 Module Control via `sof-ctl` + +Override the slot assignment for a `detect_test` instance using the SOF IPC4 +LARGE_CONFIG_SET path (requires `sof-ctl` tool or equivalent hwdep ioctl): + +```bash +# Set detect_test in pipeline 102 to use slot_id = 1 +sof-ctl -c hw:0 -t large_config_set \ + -m -i \ + -p 202 -b 00000000 01 # param_id=202 (SOF_IPC4_BYTES_CONTROL_PARAM_ID), slot_id=1 +``` + +--- + +## Adding a New WOV Algorithm + +The reference implementation (`detect_test.c`) is intentionally simple — it looks for +zero-crossing rate and signal energy in fixed frequency bands. Replace it with any +algorithm by following one of the approaches below. + +### Approach A — Modify `detect_test.c` directly + +This is simplest for prototyping. The DP thread calls `default_detect_test_buf()` on +every 320-frame batch. Replace its body with your algorithm: + +```c +/* src/samples/audio/detect_test.c */ + +static void default_detect_test_buf(struct comp_dev *dev, + const int16_t *samples, uint32_t frames) +{ + struct comp_data *cd = comp_get_drvdata(dev); + + if (cd->detected || cd->paused) + return; + + /* === YOUR ALGORITHM HERE === + * Input: samples — pointer to 'frames' interleaved S16_LE samples + * frames — always KD_DP_FRAMES (320) = 20 ms @ 16 kHz + * Output: call detect_test_notify(dev) when keyword is confirmed. + * =========================== + */ + bool keyword_found = my_algorithm_process(cd->algo_state, samples, frames); + + if (keyword_found) { + comp_err(dev, "KWD detected on slot %u", cd->wov_slot_id); + if (!cd->drain_req) + cd->drain_req = cd->config.drain_req ? cd->config.drain_req : 5000; + detect_test_notify(dev); + cd->detected = 1; + } +} +``` + +Store per-slot algorithm state in `struct comp_data` (add fields to the struct). +The slot index is available as `cd->wov_slot_id` (0, 1, or 2) so each KPB pipeline's +detector can hold independent model state. + +### Approach B — New Native SOF Module + +For a production algorithm create a new SOF module following the standard +`src/audio/template/` skeleton and integrate it with the arbiter via SOF notifier: + +**Step 1: Create the module files** + +``` +src/audio/my_kwd/ +├── CMakeLists.txt +├── my_kwd.c +└── my_kwd.h +``` + +**Step 2: Implement the module driver** + +```c +/* src/audio/my_kwd/my_kwd.c */ +#include +#include +#include +#include + +struct my_kwd_data { + uint8_t wov_slot_id; + bool paused; + bool detected; + /* ... algorithm state ... */ +}; + +/* Called by arbiter when a sibling slot fires (NOTIFIER_ID_WOV_CTRL) */ +static void on_wov_ctrl(void *arg, enum notify_id id, void *data) +{ + struct comp_dev *dev = arg; + struct my_kwd_data *cd = comp_get_drvdata(dev); + const struct wov_ctrl_notif *ctrl = data; + + if (ctrl->cmd == WOV_ARB_CMD_PAUSE) + cd->paused = true; + else if (ctrl->cmd == WOV_ARB_CMD_RESUME) { + cd->paused = false; + cd->detected = 0; + } +} + +/* Notify arbiter + KPB + host that this slot fired */ +static void my_kwd_notify(struct comp_dev *dev) +{ + struct my_kwd_data *cd = comp_get_drvdata(dev); + + /* 1. IPC4 notification to host */ + struct ipc4_voice_cmd_notification notif = {}; + notif.primary.r.word_id = cd->wov_slot_id; + notif.primary.r.notif_type = SOF_IPC4_NOTIFY_PHRASE_DETECTED; + notif.primary.r.type = SOF_IPC4_GLB_NOTIFICATION; + /* ... fill in module_id / instance_id ... */ + ipc_msg_send(cd->msg, ¬if, true); + + /* 2. Tell KPB to start draining */ + /* (re-use existing kpb_client notifier path) */ + + /* 3. Tell arbiter slot fired */ + struct wov_detect_notif det = { .slot_id = cd->wov_slot_id }; + notifier_event(dev, NOTIFIER_ID_WOV_DETECT, NOTIFIER_TARGET_CORE_ALL_MASK, + &det, sizeof(det)); +} + +static int my_kwd_prepare(struct comp_dev *dev) +{ + struct my_kwd_data *cd = comp_get_drvdata(dev); + + /* Derive slot from pipeline ID */ + uint32_t ppl = dev->ipc_config.pipeline_id; + cd->wov_slot_id = (ppl == 101 || ppl == 1) ? 0 : + (ppl == 102 || ppl == 3) ? 1 : + (ppl == 103 || ppl == 4) ? 2 : WOV_SLOT_INVALID; + + if (cd->wov_slot_id != WOV_SLOT_INVALID) + notifier_register(dev, NULL, NOTIFIER_ID_WOV_CTRL, on_wov_ctrl); + + return comp_set_state(dev, COMP_TRIGGER_PREPARE); +} + +static int my_kwd_copy(struct comp_dev *dev) +{ + struct my_kwd_data *cd = comp_get_drvdata(dev); + struct comp_buffer *source = comp_dev_get_first_data_producer(dev); + + if (!audio_stream_get_avail(&source->stream)) + return PPL_STATUS_PATH_STOP; + + uint32_t frames = audio_stream_get_avail_frames(&source->stream); + uint32_t avail_b = audio_stream_get_avail_bytes(&source->stream); + buffer_stream_invalidate(source, avail_b); + + /* Pass-through to arbiter input */ + struct comp_buffer *sink = comp_dev_get_first_data_consumer(dev); + if (sink && audio_stream_get_free_bytes(&sink->stream) >= avail_b) { + audio_stream_copy(&source->stream, 0, &sink->stream, 0, + frames * audio_stream_get_channels(&source->stream)); + buffer_stream_writeback(sink, avail_b); + comp_update_buffer_produce(sink, avail_b); + } + + if (!cd->paused && !cd->detected) { + /* Run your algorithm on the frames */ + if (my_algorithm_run(cd, &source->stream, frames)) { + my_kwd_notify(dev); + cd->detected = 1; + } + } + + comp_update_buffer_consume(source, avail_b); + return 0; +} +``` + +**Step 3: Register the UUID** + +Add to `uuid-registry.txt`: + +``` +MY_KWD_UUID_HEX my_kwd +``` + +Add to `src/audio/my_kwd/CMakeLists.txt`: + +```cmake +add_local_sources(sof my_kwd.c) +``` + +Add to `src/audio/CMakeLists.txt`: + +```cmake +if(CONFIG_COMP_MY_KWD) + add_subdirectory(my_kwd) +endif() +``` + +Add `src/audio/Kconfig`: + +```kconfig +config COMP_MY_KWD + bool "My keyword detector" + depends on COMP_KPB && IPC_MAJOR_4 + # no AMS required (uses SOF notifier) +``` + +**Step 4: Update the topology** + +In `dmic-wov-multi.conf`, replace `KWD_TEST_UUID` with the UUID bytes for `my_kwd` +in the `wov.101.1`, `wov.102.1`, `wov.103.1` widgets. + +### Approach C — IADK / LLEXT loadable module + +For algorithms that must ship as separate binaries (third-party IP, updatable +without reflashing), use the SOF IADK module adapter framework. The algorithm +is compiled as an LLEXT `.so` and loaded at runtime from the kernel filesystem. +See `src/audio/module_adapter/README.md` for the full IADK API. + +The notifier signaling path (steps 2 and 3 of `my_kwd_notify`) remains the same; +only the binary delivery mechanism changes. + +### Algorithm State Isolation + +Each pipeline instance (101/102/103) creates its own `comp_dev` with independent +`comp_data`. Detector state is never shared between slots. The `wov_slot_id` field +identifies which pipeline a given instance belongs to: + +``` +Pipeline 101 → wov_slot_id=0 → kd_dp_stack_0 / kd_dp_threads[0] +Pipeline 102 → wov_slot_id=1 → kd_dp_stack_1 / kd_dp_threads[1] +Pipeline 103 → wov_slot_id=2 → kd_dp_stack_2 / kd_dp_threads[2] (Core 1) +``` + +--- + +## Topology: Build and Deploy + +### Topology Source Layout + +``` +tools/topology/topology2/ +├── platform/intel/ +│ └── dmic-wov-multi.conf ← main topology (edit here) +├── include/components/ +│ ├── wov.conf ← detect_test widget class (wov_mute + wov_test kcontrols) +│ └── wov-arbiter.conf ← wov_arbiter widget class definition +├── include/controls/ +│ └── mixer.conf ← Class.Control.mixer definition (required by wov.conf) +└── dmic-wov-multi-manifest.conf ← top-level manifest (includes above) +``` + +### Compile Topology to `.tplg` + +From the root of the SOF repository: + +```bash +# Run from the repo root (e.g. ~/work/sof-tgl/sof-wov) +TPLG2=$(pwd)/tools/topology/topology2 +ALSA_TMP=/tmp/alsa-tplg-wov + +mkdir -p $ALSA_TMP +cp /usr/share/alsa/alsa.conf $ALSA_TMP/ +ln -sf $TPLG2/include $ALSA_TMP/include +ln -sf $TPLG2/platform $ALSA_TMP/platform + +# 1. Standard 2-Channel Multi-WOV Topology (with SRC 48k -> 16k) +ALSA_CONFIG_DIR=$ALSA_TMP ALSA_TOPOLOGY_PLUGIN_DIR=/usr/lib/alsa-topology alsatplg \ + -I $TPLG2 -p \ + -c tools/topology/topology2/dmic-wov-multi-manifest.conf \ + -o /tmp/sof-tgl-dmic-wov-multi.tplg + +# 2. Native 16 kHz 4-Channel Multi-WOV Topology (No SRC, with embedded NHLT) +ALSA_CONFIG_DIR=$ALSA_TMP ALSA_TOPOLOGY_PLUGIN_DIR=/usr/lib/alsa-topology alsatplg \ + -I $TPLG2 -p \ + -c tools/topology/topology2/dmic-wov-multi-4ch-manifest.conf \ + -o /tmp/sof-tgl-dmic-wov-multi-4ch.tplg +``` + +`ALSA_CONFIG_DIR` must point to a directory that contains `alsa.conf` plus +`include/` and `platform/` symlinks into `topology2/`. `ALSA_TOPOLOGY_PLUGIN_DIR` points to +the directory containing `libalsatplg_module_nhlt.so` so the NHLT preprocessor plugin can +generate and embed the hardware ACPI NHLT table into the manifest binary. + +Copy the compiled topology to the DUT: + +```bash +scp /tmp/sof-tgl-dmic-wov-multi-4ch.tplg \ + root@:/lib/firmware/intel/sof-ipc4-tplg/sof-tgl-dmic-wov-multi-4ch.tplg +``` + +### BIOS NHLT Table Override (`sof_use_tplg_nhlt=1`) + +On development DUTs (such as Spider / Tiger Lake), the BIOS ACPI NHLT table may have +corrupted checksums or lack endpoint descriptors for non-standard DMIC clock rates +(such as opening DMIC natively at 16 kHz across 4 channels without an SRC downsampler). + +The SOF Linux kernel driver supports **overriding the BIOS NHLT table** using the NHLT +table embedded in the topology manifest binary. + +#### 1. How Topology NHLT is Embedded +In the topology manifest (`dmic-wov-multi-4ch-manifest.conf`): +- `Define { PREPROCESS_PLUGINS "nhlt" }` enables the NHLT compiler plugin. +- `Object.Dai.DMIC` defines the DAI parameters (`sample_rate 16000`, `num_pdm_active 2`, 4 active mics). +- `Object.Base.manifest.1 { nhlt "true" }` packages the NHLT table into a `SOF_MANIFEST_DATA_TYPE_NHLT` (1) TLV data block inside the compiled `.tplg` binary. + +#### 2. Enabling NHLT Override in the SOF Driver +Set `sof_use_tplg_nhlt=1` for the `snd_sof_intel_hda_common` kernel module. + +Edit `/etc/modprobe.d/sof.conf` on the DUT: + +```ini +# /etc/modprobe.d/sof.conf +options snd_sof tplg_path=intel/sof-ipc4-tplg tplg_filename=sof-tgl-dmic-wov-multi-4ch.tplg +options snd_sof_intel_hda_common sof_use_tplg_nhlt=1 +``` + +#### 3. Reloading Driver Stack with NHLT Override +Because `snd_sof_intel_hda_common` is referenced by child modules, unload the SOF stack in dependency order, then reload with `sof_use_tplg_nhlt=1`: + +```bash +ssh root@ ' + rmmod snd_sof_probes snd_sof_ipc_msg_injector snd_sof_fw_gdb \ + snd_soc_skl_hda_dsp snd_sof_pci_intel_tgl snd_sof_pci_intel_cnl \ + snd_sof_intel_hda_generic soundwire_intel snd_sof_intel_hda_sdw_bpt \ + snd_sof_intel_hda_common snd_sof_intel_hda_mlink snd_sof_intel_hda \ + snd_sof_pci snd_sof_xtensa_dsp snd_sof + modprobe snd_sof_intel_hda_common sof_use_tplg_nhlt=1 + modprobe snd_sof_pci_intel_tgl +' +``` + +#### 4. Verifying NHLT Override on DUT +```bash +# Verify kernel parameter is active +cat /sys/module/snd_sof_intel_hda_common/parameters/sof_use_tplg_nhlt +# Output: Y + +# Verify 4-channel DMIC audio capture +arecord -D hw:0,11 -c 4 -r 16000 -f S16_LE -d 3 /tmp/wov_4ch.wav +``` + +### Build Firmware with WOV Arbiter + +Configure a build directory with the required Kconfig options (see +[Build System Configuration](#build-system-configuration)), then build: + +```bash +ninja -C +``` + +Copy the firmware image to the DUT (path varies by platform): + +```bash +# TigerLake example +scp /zephyr/zephyr.ri \ + root@:/lib/firmware/intel/sof-ipc4/tgl/community/sof-tgl.ri +``` + +Reload the driver on the DUT: + +```bash +rmmod snd_sof_pci_intel_tgl && modprobe snd_sof_pci_intel_tgl +``` + +### Kernel Requirements & Build + +The Multi-Slot WOV and ALSA regular PCM pipeline requires: + +- **Kernel Repository**: `git@github.com:lgirdwood/linux.git` +- **Kernel Branch**: `feature/wov-multi-kpb-v2` +- **Firmware Repository**: `git@github.com:lgirdwood/sof.git` +- **Firmware Branch**: `feature/wov-multi-kpb-v2` + +#### Checkout and Build Kernel + +```bash +# Clone or fetch the kernel branch +git clone -b feature/wov-multi-kpb-v2 git@github.com:lgirdwood/linux.git linux-wov +cd linux-wov + +# Configure for x86_64 with SOF audio support +make x86_64_defconfig +# Ensure CONFIG_SND_SOC_SOF=m, CONFIG_SND_SOC_SOF_INTEL_TOPLEVEL=y, +# CONFIG_SND_SOC_SOF_HDA=m + +# Build kernel and modules +make -j$(nproc) bzImage modules + +# Install modules and kernel to DUT (e.g. TigerLake DUT) +INSTALL_MOD_PATH=/tmp/modules make modules_install +scp -r /tmp/modules/lib/modules/* root@:/lib/modules/ +scp arch/x86/boot/bzImage root@:/boot/vmlinuz-wov +``` + +### Topology Configuration Reference + +Key parameters in `dmic-wov-multi.conf`: + +| Constant | Default | Description | +|---|---|---| +| `DMIC_PCM_ID` | `11` | ALSA PCM device index | +| `DMIC_DAI_INDEX` | `1` | HDA DAI instance | +| `KWD_CPC` | `100000` | cycles per chunk for detector widgets | +| `WOV_ARB_CPC` | `20000` | cycles per chunk for arbiter | +| `FORMAT` | `s32le` (TGL/CAVS2.5) | audio format; `s16le` on other platforms | + +> **KPB history depth is configurable via topology.** Set `KPB_BUFF_TIME_MS` in the topology +> manifest (e.g. `dmic-wov-multi-manifest.conf`) to override `CONFIG_KPB_MAX_BUFF_TIME` at +> runtime — no firmware rebuild required. Omit the define or set it to `0` to fall back to +> the Kconfig default (6000 ms on TGL/CAVS2.5, 2100 ms on other platforms). + +Slot 2 (`Pipeline 103`) is deliberately placed on Core 1 (`core_id = 1`) to validate +cross-core scheduling. Set all three to `core_id = 0` if a single-core topology is needed. + +### Adding a Fourth Slot + +1. Add `Pipeline 104` (new KPB + detector) following the pattern of pipelines 101–103. + Route the new `wov.104.1 → wov-arbiter.105.1`. +2. Update `wov_arbiter.conf`: set `num_input_pins = 4`. +3. Update `wov_arbiter.h`: `WOV_ARB_MAX_SLOTS 8` already supports it. +4. Add the new `pipeline_id → wov_slot_id` mapping in `test_keyword_new()`. +5. Add a fourth `K_THREAD_STACK_DEFINE` and update `kd_dp_stacks[]`. + +--- + +## Build System Configuration + +### Kconfig (minimum required set) + +```kconfig +# Mandatory +CONFIG_COMP_WOV_ARBITER=y +CONFIG_COMP_KPB=y +CONFIG_COMP_MIXIN_MIXOUT=y +CONFIG_IPC_MAJOR_4=y + +# For the detect_test reference detector +CONFIG_COMP_KWD_DETECT=y + +# Multi-core scheduling (required for slot 2 on Core 1) +CONFIG_SMP=y +CONFIG_MP_MAX_NUM_CPUS=4 # TGL has 4 DSP cores +CONFIG_SCHED_CPU_MASK_PIN_ONLY=y + +# KPB history buffer length — compile-time floor; topology can override at runtime. +# Default: 6000 ms on CAVS2.5+ (TigerLake), 2100 ms on all other platforms. +CONFIG_KPB_MAX_BUFF_TIME=6000 # TGL / CAVS2.5 +``` + +The KPB history depth can be set **per-platform in the topology manifest** without a +firmware rebuild. The buffer size is computed at prepare time from whichever source wins: + +| Source | Priority | How to set | +|---|---|---| +| Topology `KPB_BUFF_TIME_MS` | **highest** | `Define { KPB_BUFF_TIME_MS "6000" }` in manifest | +| `CONFIG_KPB_MAX_BUFF_TIME` | fallback | `west build -- -DCONFIG_KPB_MAX_BUFF_TIME=4000` | + +Buffer byte formula (16 kHz S16LE mono): + +``` +buffer_bytes = 16 x 2 x buff_time_ms x channels + = 16 x 2 x 6000 x 1 = 192 000 bytes (TGL, S16LE mono, 6000 ms) + = 16 x 2 x 2100 x 1 = 67 200 bytes (other platforms, 2100 ms) +``` + +The topology kcontrol `kpb_cfg_` carries a 36-byte SOF ABI blob with +`type = KP_BUF_CFG_BUFF_TIME_MS = 2` and a 4-byte `uint32_t` payload. It is sent +automatically to the firmware LARGE_CONFIG_SET handler when the pipeline is first opened; +no userspace script is required. Supported values in `kpb.conf`: `6000`, `4000`, `2100`. +To add a new value, compute the 4-byte LE payload and add an `IncludeByKey` entry. + +To change the compile-time fallback, rebuild with `-DCONFIG_KPB_MAX_BUFF_TIME=`. + +These can be set via `west build -- -DCONFIG_...=y` or by editing the build directory's `zephyr/.config`. + +### Module UUIDs + +| Component | UUID | +|---|---| +| `detect_test` (KWD_TEST) | `1f:d5:a8:eb:27:78:b5:47:82:ee:de:6e:77:43:af:67` | +| `wov_arbiter` | `4a5b6c7d-8e9f-4a1b-2c3d-4e5f60718293` | + +--- + +## Testing and Verification + +### Quick Start (TigerLake / spider DUT) + +```bash +# 0. Load the driver with the WOV firmware and topology +rmmod snd_sof_pci_intel_tgl +modprobe snd_sof_pci_intel_tgl \ + fw_path=intel/sof-ipc4/tgl/community \ + tplg_filename=intel/sof-ipc4-tplg/sof-tgl-dmic-4ch.tplg + +# 1. Verify the PCM capture device is visible +arecord -l # expect: card 0, device 11: DMIC Multi-WOV +cat /proc/asound/card0/pcm11c/info + +# 2. Run capture test with arecord or wov_capture_app +arecord -D hw:0,11 -f S16_LE -r 16000 -c 2 -d 3 /tmp/wov_test.wav +wov_capture_app -D 0 -d 11 -r 16000 -c 2 -t 3.0 -o /tmp +``` + +--- + +### kcontrol numid reference + +After driver load with the deployed single-KPB topology (`sof-tgl-dmic-4ch.tplg` / `dmic-wov-multi-manifest.conf`), the WOV kcontrol set is: + +| numid | name | type | Purpose | +|---|---|---|---| +| 11 | `kpb_cfg_100` | bytes TLV | Shared KPB 0 buffer config in Pipeline 100 (history depth in ms) | +| 12 | `wov_mute_101` | boolean switch | Arm (`on`) / mute (`off`) detection for slot 0 (Core 0) | +| 13 | `wov_test_101` | boolean switch | Momentary trigger switch for slot 0 (auto-resets to `off`) | +| 14 | `wov_mute_102` | boolean switch | Arm (`on`) / mute (`off`) detection for slot 1 (Core 0) | +| 15 | `wov_test_102` | boolean switch | Momentary trigger switch for slot 1 (auto-resets to `off`) | +| 16 | `wov_mute_103` | boolean switch | Arm (`on`) / mute (`off`) detection for slot 2 (Core 1) | +| 17 | `wov_test_103` | boolean switch | Momentary trigger switch for slot 2 (auto-resets to `off`) | +| 18 | `wov_active_slot` | enumerated | Read-only arbiter active slot state (`Listening`, `Slot 1`, `Slot 2`, `Slot 3`) | + +> **Note:** numids are assigned in ALSA registration order. Run `amixer -c 0 controls` +> to confirm actual numids on your sound card. + +**Runtime usage summary:** + +| kcontrol | When to use | +|---|---| +| `kpb_cfg_100` (11) | Written automatically by the kernel from topology at pipeline open. Sets history depth (e.g. 6000 ms). | +| `wov_mute_1NN` (12/14/16) | Write `on` to arm a slot for detection. Default is `off` (muted). | +| `wov_test_1NN` (13/15/17) | Write `on` to immediately force a keyword trigger for testing. The control auto-resets to `off`. | +| `wov_active_slot` (18) | Query with `amixer` to check currently active slot (`Listening` or `Slot 1`..`Slot 3`). | + +--- + +### Reading Active Slot Status via `wov_active_slot` Enum Control + +The arbiter updates `wov_active_slot` to reflect the active triggered detector slot: + +```bash +# Query current state (returns 'Listening', 'Slot 1', 'Slot 2', or 'Slot 3') +amixer -c 0 cget name='wov_active_slot' +``` + +--- + +### Per-Slot Trigger Test + +The `detect_test` DP thread auto-triggers after accumulating **320 frames** (one 20 ms +batch, `frames_total >= KD_DP_FRAMES`). The first batch fires the trigger approximately +14–25 ms after pipeline RUNNING. No physical audio source is required. + +#### Test all three slots simultaneously + +```bash +dmesg -C +arecord -D hw:0,11 -r 16000 -c 2 -f S16_LE -d 10 /tmp/wov_all.wav & +AREC=$! +# Arm all three slots +amixer -c 0 cset numid=12 on # wov_mute_101 +amixer -c 0 cset numid=14 on # wov_mute_102 +amixer -c 0 cset numid=16 on # wov_mute_103 +wait $AREC +echo "rc=$?" +``` + +Expected: `rc=0`. Slot 0 fires first (timing-dependent); the arbiter pauses slots 1 and 2 +via `NOTIFIER_ID_WOV_CTRL` and sets `wov_active_slot` to `Slot 1`. + +#### Test manual trigger via `wov_test_1NN` kcontrol switch + +```bash +# Start capture without auto-trigger wait +arecord -D hw:0,11 -r 16000 -c 2 -f S16_LE -d 10 /tmp/wov_manual.wav & +AREC=$! +# Arm slots +amixer -c 0 cset numid=12 on +amixer -c 0 cset numid=14 on +amixer -c 0 cset numid=16 on + +# Force trigger Slot 1 on demand: +amixer -c 0 cset numid=15 on # wov_test_102 triggers detection and auto-resets to off + +# Check active slot in arbiter: +amixer -c 0 cget name='wov_active_slot' # Returns 'Item #1 Slot 2' + +wait $AREC +echo "rc=$?" +``` + +#### Test a single slot in isolation + +```bash +arecord -D hw:0,11 -r 16000 -c 2 -f S16_LE -d 8 /tmp/wov_s2.wav & +AREC=$! +# Arm only Slot 2 (Core 1) +amixer -c 0 cset numid=16 on # arm wov_mute_103 +wait $AREC +echo "rc=$?" +``` + +--- + +### Per-Slot Mute Test + +Verify that `wov_mute_1NN` suppresses detection when `off` and restores it when `on`. + +```bash +# Reload driver for a clean state +rmmod snd_sof_pci_intel_tgl && modprobe snd_sof_pci_intel_tgl && sleep 4 + +# Open PCM capture device (keeps DSP in D0) +arecord -D hw:0,11 -f S16_LE -r 16000 -c 2 -d 30 /dev/null & +AREC=$! +sleep 2 + +# Leave all wov_mute controls at default (off = muted) +# Arm slot 1 +amixer -c 0 cset numid=14 on +echo "Slot 1 armed for detection" + +kill $AREC +``` + +#### Multi-Slot Automated Test Suite (`wov_multi_slot_test.py`) + +`tools/wov_capture/wov_multi_slot_test.py` runs an automated multi-cycle test verifying all 3 detector slots, momentary test trigger switches (`wov_test_101`, `wov_test_102`, `wov_test_103`), automatic switch reset to `off`, and `wov_active_slot` enum transitions (`Listening` -> `Slot N` -> `Listening`): + +```bash +# Run 10-cycle automated test suite across all 3 slots +python3 tools/wov_capture/wov_multi_slot_test.py --cycles 10 +``` + +Example output: +``` +================================================================ + WOV 3-Slot Automated Trigger & Arbitration 10-Cycle Suite +================================================================ + +[Cycle 01] Testing Slot 1 (wov_test_101)... + Active Slot during trigger : 1 (Expected: 1) + Test Switch state : off (Expected: off) + Active Slot after stop : 0 (Expected: 0) + Captured WAV File : /tmp/wov_slot_test_cyc1_1.wav (192044 bytes, 3.10s) + [Cycle 01 - Slot 1] => PASSED +... +================================================================ + RESULTS: 10/10 passed (100.0%) +================================================================ +``` + +#### Verify audio content + +Silence precedes the trigger; real DMIC audio follows. +The silence-to-audio boundary marks the trigger point (∼20 ms into the file). + +```python +import struct, math, sys + +for fname in sys.argv[1:]: + data = open(fname, 'rb').read()[44:] # skip 44-byte WAV header + n = len(data) // 2 + samp = struct.unpack_from(f'<{n}h', data) + nz = next((i for i, x in enumerate(samp) if x != 0), n) + rms = math.sqrt(sum(x*x for x in samp[800:]) / max(len(samp) - 800, 1)) + print(f'{fname}: first_nz={nz*1000/16000:.1f}ms post_trigger_RMS={rms:.0f}') + +# Expected on TGL (silent room): +# first_nz=14-25 ms (arbiter activates after first DP batch) +# post_trigger_RMS > 100 (ambient DMIC noise -- not silence) +``` + +--- + +### Reading Firmware Trace (mtrace) + +The mtrace ring is at `/sys/kernel/debug/sof/mtrace/core{0,1}`. Each `dd` call +advances the FIFO read pointer; start reading **before** the arecord session to +capture pipeline-prepare and trigger messages. + +```bash +# Capture ~1 MB of firmware trace concurrently with an arecord session +dd if=/sys/kernel/debug/sof/mtrace/core0 bs=65536 count=16 of=/tmp/mt.bin & +arecord -D hw:0,11 -f S16_LE -r 16000 -c 2 -d 8 /tmp/wov.wav & +amixer -c 0 cset numid=12 on && amixer -c 0 cset numid=14 on +amixer -c 0 cset numid=13 on && amixer -c 0 cset numid=16 on +wait + +# strings works because SOF embeds full format strings in the binary +grep -a 'kd_test\|wov_arb\|AUTO-TRIGGER\|TRIGGERED' /tmp/mt.bin +``` + +--- + +### Expected Trace Events + +After opening `/dev/snd/pcmC0D11c` (`hw:0,11`) (pipeline prepare + RUNNING): + +``` +kd_test.test_keyword_prepare: comp:4 0x2000d kd_dp thread started for slot 0 +kd_test.test_keyword_prepare: comp:3 0x1000d kd_dp thread started for slot 1 +wov_arbiter.wov_arb_trigger: comp:2 0x10 wov_arb_trigger cmd 1 +``` + +On auto-trigger (slot 0 fires first): + +``` +kd_test.default_detect_test_buf: comp:4 0x2000d kd_test dp: AUTO-TRIGGER slot=0 +kd_test.notify_host: comp:4 0x2000d notify_host: WOV module_id=0x2 instance_id=0xd slot_id=0 detected +wov_arbiter.arb_on_detect: comp:2 0x10 wov_arb: activating slot 0 +kd_test.on_wov_ctrl: comp:3 0x1000d kd: paused (slot 0 active) +kd_test.on_wov_ctrl: comp:4 0x2000d kd: resumed by arbiter +``` + +On stream stop (arecord exits): + +``` +wov_arbiter.wov_arb_trigger: comp:2 0x10 wov_arb_trigger cmd 0 +kd_test.on_wov_ctrl: comp:3 0x1000d kd: resumed by arbiter +kd_test.on_wov_ctrl: comp:4 0x2000d kd: resumed by arbiter +``` + + + +--- + +### Real-Audio Frequency Sweep Test + +Inject tones at known frequencies to trigger specific slots. Run `arecord` or `wov_capture_app` on the +DUT and `speaker-test` on a test machine whose audio output is wired to the DUT mic input: + +```bash +# On the DUT: start capture and arm all slots +arecord -D hw:0,11 -f S16_LE -r 16000 -c 2 -d 8 /tmp/wov_sweep.wav & +amixer -c 0 cset numid=12 on && amixer -c 0 cset numid=14 on +amixer -c 0 cset numid=13 on && amixer -c 0 cset numid=16 on + +# On test machine: drive tone sweep (one frequency band per slot) +speaker-test -c 1 -t sine -f 120 -l 3 # -> slot 0 (Male 80-170 Hz) +speaker-test -c 1 -t sine -f 220 -l 3 # -> slot 1 (Female 175-270 Hz) +wait +``` + +--- + +### Multi-Cycle PCM Verification Daemon (`wov_daemon.py`) + +`tools/wov_capture/wov_daemon.py` runs an automated multi-cycle regular PCM capture loop on the +DUT (`hw:0,11` at 16 kHz 2-channel S16_LE) with integrated audio signal verification. + +```bash +# Basic usage — 3 cycles of 2.0s capture with audio signal analysis +python3 wov_daemon.py + +# Multi-cycle test with DSP runtime PM D3 autosuspend verification between cycles +python3 wov_daemon.py --cycles 5 --duration 3.0 --test-pm + +# Options +python3 wov_daemon.py --help +``` + +``` +usage: wov_daemon.py [-h] [--cycles CYCLES] [--duration DURATION] + [--delay DELAY] [--card CARD] [--device DEVICE] + [--rate RATE] [--channels CHANNELS] [--format FORMAT] + [--out OUT] [--test-pm] [--verify] + + --cycles N Number of capture cycles to run (0=unlimited, default: 3) + --duration S Duration per cycle in seconds (default: 2.0) + --delay S Delay between cycles in seconds (default: 0.5) + --card N Sound card number (default: 0) + --device N PCM device number (default: 11) + --rate N Sample rate in Hz (default: 16000) + --channels N Number of channels (default: 2) + --format FMT ALSA format (default: S16_LE) + --out PATH Output WAV file or pattern (default: /tmp/wov_daemon_cycle_{n}.wav) + --test-pm Sleep 3.0s between cycles to verify DSP D3 autosuspend / wake + --verify Perform deep audio signal energy analysis (default: True) +``` + +--- + +### C Host Application (`wov_capture_app`) + +`tools/wov_capture/wov_capture_app.c` is a self-contained, zero-dependency C host application +that captures regular PCM audio via direct Linux ALSA kernel UAPI ioctls (`/dev/snd/pcmC0D11c`). +It writes valid RIFF WAV files with exact byte headers and calculates per-channel DC offset, +AC RMS, Peak amplitude, and Peak dBFS metrics. + +#### Build + +```bash +cd tools/wov_capture + +# Builds wov_capture_app locally with standard GCC (no external libraries needed) +make + +# Install to DUT (scp) +make install DUT=root@spider +``` + +#### Usage + +``` +Usage: wov_capture_app [options] + +Options: + -D CARD Sound card number (default: 0) + -d DEV PCM device number (default: 11) + -r RATE Sample rate in Hz (default: 16000) + -c CHANS Number of channels (default: 2) + -f FORMAT Sample format: S16_LE (default) or S32_LE + -t DURATION Capture duration in seconds (default: 3.0, 0 = unlimited) + -n CYCLES Number of capture cycles (default: 1, 0 = unlimited) + -w DELAY Delay between cycles in seconds (default: 0.5) + -o DIR Output directory for WAV files (default: /tmp) + -F FILE Explicit output WAV file path + -v Verbose output (print extra debug info) + -h Show help +``` + +**Quick start on spider:** + +```bash +# Capture 3 seconds of 16 kHz stereo audio to /tmp +wov_capture_app -D 0 -d 11 -r 16000 -c 2 -t 3.0 -o /tmp + +# Multi-cycle repeat test (5 consecutive cycles with 1s delay) +wov_capture_app -D 0 -d 11 -n 5 -t 2.0 -w 1.0 +``` + +#### Log Format + +All output is prefixed with a timestamp tag: + +``` +[YYYY-MM-DD HH:MM:SS.mmm] [INFO ] Starting WOV PCM Capture App (Card=0, Dev=11, Rate=16000, Ch=2, Format=S16_LE) +[YYYY-MM-DD HH:MM:SS.mmm] [STATE] Cycle 1: Opening capture device /dev/snd/pcmC0D11c (rate=16000, ch=2) +[YYYY-MM-DD HH:MM:SS.mmm] [STATE] Cycle 1: Capturing audio -> /tmp/wov_20260905_120000_cyc001.wav +[YYYY-MM-DD HH:MM:SS.mmm] [STATE] Cycle 1: Captured 48000 frames (3.00s, 192000 bytes) -> /tmp/wov_20260905_120000_cyc001.wav +[YYYY-MM-DD HH:MM:SS.mmm] [INFO ] Channel 0: Min=-1245 Max=1432 DC=-12.4 RMS=432.1 (-37.6 dBFS) Peak=1432.0 (-27.2 dBFS) +[YYYY-MM-DD HH:MM:SS.mmm] [INFO ] Channel 1: Min=-1180 Max=1390 DC=-10.1 RMS=418.6 (-37.9 dBFS) Peak=1390.0 (-27.4 dBFS) +``` + diff --git a/src/audio/wov_arbiter/wov_arbiter.c b/src/audio/wov_arbiter/wov_arbiter.c new file mode 100644 index 000000000000..35cb315ed9b5 --- /dev/null +++ b/src/audio/wov_arbiter/wov_arbiter.c @@ -0,0 +1,813 @@ +// SPDX-License-Identifier: BSD-3-Clause +// +// Copyright(c) 2026 Intel Corporation +// +// WOV Arbiter -- routes the drain output of one-of-N KPB host sinks to the +// single host PCM copier, while silencing the idle inputs and coordinating +// pause/resume of sibling WOV detectors via the SOF notifier system. +// +// Topology connectivity (per KPB slot i): +// KPB_i host_sink (output pin 1) --> wov_arbiter input pin i +// wov_arbiter output pin 0 --> host copier +// +// Notifier events: +// Subscribes to NOTIFIER_ID_WOV_DETECT (detector -> arbiter on keyword) +// Publishes NOTIFIER_ID_WOV_CTRL (arbiter -> detectors: pause/resume) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +LOG_MODULE_REGISTER(wov_arbiter, CONFIG_SOF_LOG_LEVEL); + +SOF_DEFINE_REG_UUID(wov_arbiter); +DECLARE_TR_CTX(wov_arbiter_tr, SOF_UUID(wov_arbiter_uuid), LOG_LEVEL_INFO); + +/* Private runtime data. */ +struct wov_arb_data { + struct ipc4_base_module_cfg base_cfg; + /* + * Index of the currently active KPB slot (0..num_slots-1). + * WOV_ARB_NO_ACTIVE when no drain is in progress. + * Protected by the scheduler; no extra lock needed. + */ + uint8_t active_slot; + atomic_t call_active; + /* Number of input pins (= KPB slots); read from nb_input_pins at init. */ + uint8_t num_slots; + uint16_t active_slot_ctl_id; + uint16_t call_state_ctl_id; + uint32_t copy_count; + uint32_t drain_frames_copied; + uint32_t drain_frames_total; +#if CONFIG_IPC_MAJOR_4 + /* Notification messages, allocated on first use and reused */ + struct ipc_msg *ctl_msg; + struct ipc_msg *detect_msg; +#endif +}; + +/* + * Only one WOV graph (DMIC or headset) may be active at a time: detectors + * share NOTIFIER_ID_WOV_DETECT and DSP memory only fits one detector set. + * IPC handling is serialized, so no lock is needed. + */ +static unsigned int wov_arb_instances; + +#if CONFIG_IPC_MAJOR_4 +static void notify_control_change(const struct comp_dev *dev, struct wov_arb_data *cd, + uint16_t control_id, uint32_t val) +{ + struct sof_ipc4_notify_module_data *msg_module_data; + struct sof_ipc4_control_msg_payload *msg_payload; + struct ipc_msg *msg; + uint32_t data_size = sizeof(struct sof_ipc4_notify_module_data) + + sizeof(struct sof_ipc4_control_msg_payload) + + sizeof(struct sof_ipc4_ctrl_value_chan); + struct ipc4_voice_cmd_notification notif; + + if (!cd->ctl_msg) { + memset_s(¬if, sizeof(notif), 0, sizeof(notif)); + notif.primary.r.notif_type = SOF_IPC4_MODULE_NOTIFICATION; + notif.primary.r.type = SOF_IPC4_GLB_NOTIFICATION; + notif.primary.r.rsp = SOF_IPC4_MESSAGE_DIR_MSG_REQUEST; + notif.primary.r.msg_tgt = SOF_IPC4_MESSAGE_TARGET_FW_GEN_MSG; + + cd->ctl_msg = ipc_msg_w_ext_init(NULL, notif.primary.dat, 0, data_size); + if (!cd->ctl_msg) + return; + } + msg = cd->ctl_msg; + + msg_module_data = (struct sof_ipc4_notify_module_data *)msg->tx_data; + msg_module_data->instance_id = IPC4_INST_ID(dev->ipc_config.id); + msg_module_data->module_id = IPC4_MOD_ID(dev->ipc_config.id); + msg_module_data->event_id = SOF_IPC4_NOTIFY_MODULE_EVENTID_ALSA_MAGIC_VAL | + SOF_IPC4_ENUM_CONTROL_PARAM_ID; + msg_module_data->event_data_size = sizeof(struct sof_ipc4_control_msg_payload) + + sizeof(struct sof_ipc4_ctrl_value_chan); + + msg_payload = (struct sof_ipc4_control_msg_payload *)msg_module_data->event_data; + msg_payload->id = control_id; + msg_payload->num_elems = 1; + msg_payload->chanv[0].channel = 0; + msg_payload->chanv[0].value = val; + + ipc_msg_send(msg, NULL, true); +} + +/* Wake the host: a blocking read() on the WOV capture PCM has no other way + * to learn that a detection just pushed a burst of drained KPB data into the + * host DMA buffer (the stream runs with SNDRV_PCM_INFO_NO_PERIOD_WAKEUP so + * ALSA's normal period-elapsed IRQ path is not relied on here). This mirrors + * detect_test.c's notify_host() so the kernel's sof_ipc4_rx_msg() can key off + * SOF_IPC4_NOTIFY_PHRASE_DETECTED and call snd_sof_pcm_period_elapsed(). + * Sent once per detection (from arb_on_detect()), not repeated per copy(): + * it is a one-shot simulated interrupt, not a substitute for the host's own + * period-elapsed mechanism on streams that never requested no-period-wakeup. + */ +static void notify_host_detect(const struct comp_dev *dev, struct wov_arb_data *cd, + uint32_t slot_id) +{ + struct ipc4_voice_cmd_notification notif; + + memset_s(¬if, sizeof(notif), 0, sizeof(notif)); + notif.primary.r.word_id = slot_id; + notif.primary.r.notif_type = SOF_IPC4_NOTIFY_PHRASE_DETECTED; + notif.primary.r.type = SOF_IPC4_GLB_NOTIFICATION; + notif.primary.r.rsp = SOF_IPC4_MESSAGE_DIR_MSG_REQUEST; + notif.primary.r.msg_tgt = SOF_IPC4_MESSAGE_TARGET_FW_GEN_MSG; + + notif.extension.r.sv_score = (uint16_t)(dev_comp_id(dev) & 0xffff); + notif.extension.r.rsvd1 = (uint32_t)(dev_comp_id(dev) >> 16); + + if (!cd->detect_msg) { + cd->detect_msg = ipc_msg_w_ext_init(NULL, notif.primary.dat, + notif.extension.dat, 0); + if (!cd->detect_msg) + return; + } + /* The header carries the slot, update it for each detection */ + cd->detect_msg->header = notif.primary.dat; + + ipc_msg_send(cd->detect_msg, NULL, true); +} +#endif + +/* ------------------------------------------------------------------------- + * Notifier callbacks + * ---------------------------------------------------------------------- */ + +/* Notifier callback: a WOV detector has fired. Activates the winning slot + * and broadcasts PAUSE to all detectors via NOTIFIER_ID_WOV_CTRL. */ +static void arb_on_detect(void *arg, enum notify_id id, void *data) +{ + struct comp_dev *dev = arg; + struct wov_arb_data *cd = comp_get_drvdata(dev); + const struct wov_detect_notif *det = data; + + if (det->slot_id >= cd->num_slots) { + comp_err(dev, "wov_arb: bad slot_id %u num_slots=%u", + det->slot_id, cd->num_slots); + return; + } + + if (atomic_read(&cd->call_active)) { + comp_dbg(dev, "wov_arb: ignoring slot %u detection while call is active", + det->slot_id); + return; + } + + /* First-wins: ignore if another slot is already draining. */ + if (cd->active_slot != WOV_ARB_NO_ACTIVE) { + comp_warn(dev, "wov_arb: slot %u detected but slot %u active, ignoring", + det->slot_id, cd->active_slot); + return; + } + + comp_info(dev, "wov_arb: activating slot %u", det->slot_id); + cd->active_slot = det->slot_id; + +#if CONFIG_IPC_MAJOR_4 + /* Notify host ALSA enum control: 1..N corresponds to Slot 1..N (0 is Listening) */ + notify_control_change(dev, cd, cd->active_slot_ctl_id, (uint32_t)cd->active_slot + 1); + /* Wake a blocking read() on the host WOV capture PCM - see notify_host_detect(). */ + notify_host_detect(dev, cd, det->slot_id); +#endif + + /* Broadcast PAUSE to all detectors. The winning slot continues draining + * its KPB history buffer; all others suspend detection until RESUME. */ + struct wov_ctrl_notif ctrl = { .cmd = WOV_ARB_CMD_PAUSE, .slot_id = det->slot_id }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, NOTIFIER_TARGET_CORE_ALL_MASK, + &ctrl, sizeof(ctrl)); +} + +/* ------------------------------------------------------------------------- + * Component lifecycle + * ---------------------------------------------------------------------- */ + +static struct comp_dev *wov_arb_new(const struct comp_driver *drv, + const struct comp_ipc_config *config, + const void *spec) +{ + struct comp_dev *dev; + struct wov_arb_data *cd; + + comp_cl_info(drv, "wov_arb_new"); + + if (wov_arb_instances) { + comp_cl_err(drv, "wov_arb_new: another WOV PCM is already active"); + return NULL; + } + + dev = comp_alloc(drv, sizeof(*dev)); + if (!dev) + return NULL; + dev->ipc_config = *config; + + cd = rzalloc(SOF_MEM_FLAG_USER, sizeof(*cd)); + if (!cd) { + comp_free_device(dev); + return NULL; + } + + const struct ipc4_base_module_cfg *base_cfg = spec; + memcpy_s(&cd->base_cfg, sizeof(cd->base_cfg), base_cfg, sizeof(*base_cfg)); + + /* Detection notifications arrive via notifier bus across pipelines, so support up to MAX_SLOTS */ + cd->num_slots = WOV_ARB_MAX_SLOTS; + cd->active_slot_ctl_id = WOV_ARB_ACTIVE_SLOT_CONTROL_ID; + + /* Start with no active slot; first WOV_DETECT notifier will activate one. */ + cd->active_slot = WOV_ARB_NO_ACTIVE; + + comp_set_drvdata(dev, cd); + /* Arbiter produces a capture stream that feeds the host PCM copier. */ + dev->direction = SOF_IPC_STREAM_CAPTURE; + dev->direction_set = true; + dev->state = COMP_STATE_READY; + +#if CONFIG_IPC_MAJOR_4 + struct ipc_comp_dev *ipc_pipe; + struct ipc *ipc = ipc_get(); + + ipc_pipe = ipc_get_comp_by_ppl_id(ipc, COMP_TYPE_PIPELINE, config->pipeline_id, + IPC_COMP_IGNORE_REMOTE); + if (ipc_pipe && ipc_pipe->pipeline) { + dev->pipeline = ipc_pipe->pipeline; + if (dev->ipc_config.proc_domain == COMP_PROCESSING_DOMAIN_LL || !dev->period) + dev->period = ipc_pipe->pipeline->period; + } + + if (!dev->period) + dev->period = 10000; + + component_set_nearest_period_frames(dev, cd->base_cfg.audio_fmt.sampling_frequency); + if (!dev->frames) + dev->frames = 160; +#endif + + comp_info(dev, "wov_arb_new: num_slots=%u, ppl=%u, period=%u, frames=%u", + cd->num_slots, config->pipeline_id, dev->period, dev->frames); + + wov_arb_instances++; + + return dev; +} + +static void wov_arb_free(struct comp_dev *dev) +{ + comp_info(dev, "wov_arb_free"); + + struct wov_arb_data *cd = comp_get_drvdata(dev); + + if (cd && cd->active_slot != WOV_ARB_NO_ACTIVE) { + cd->active_slot = WOV_ARB_NO_ACTIVE; + struct wov_ctrl_notif c = { .cmd = WOV_ARB_CMD_RESUME }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, + NOTIFIER_TARGET_CORE_ALL_MASK, + &c, sizeof(c)); + } + + notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_DETECT); + +#if CONFIG_IPC_MAJOR_4 + if (cd) { + ipc_msg_free(cd->ctl_msg); + ipc_msg_free(cd->detect_msg); + } +#endif + rfree(cd); + comp_free_device(dev); + + if (wov_arb_instances) + wov_arb_instances--; +} + +static int wov_arb_params(struct comp_dev *dev, + struct sof_ipc_stream_params *params); + +static int wov_arb_prepare(struct comp_dev *dev) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + + comp_info(dev, "wov_arb_prepare: period=%u, frames=%u", dev->period, dev->frames); + + cd->active_slot = WOV_ARB_NO_ACTIVE; + cd->copy_count = 0; + cd->drain_frames_copied = 0; + cd->drain_frames_total = 0; + +#if CONFIG_IPC_MAJOR_4 + notify_control_change(dev, cd, cd->active_slot_ctl_id, 0); + if (cd->call_state_ctl_id) + notify_control_change(dev, cd, cd->call_state_ctl_id, + atomic_read(&cd->call_active) ? + WOV_ARB_CALL_STATE_ACTIVE : WOV_ARB_CALL_STATE_LISTENING); +#endif + + if (!dev->frames) { + component_set_nearest_period_frames(dev, cd->base_cfg.audio_fmt.sampling_frequency); + if (!dev->frames) + dev->frames = 160; + } + + struct comp_buffer *sink = comp_dev_get_first_data_consumer(dev); + if (sink) { +#if CONFIG_IPC_MAJOR_4 + ipc4_update_buffer_format(sink, &cd->base_cfg.audio_fmt); +#else + struct sof_ipc_stream_params p; + wov_arb_params(dev, &p); + buffer_set_params(sink, &p, true); +#endif + } + + struct comp_buffer *source; + struct list_item *src_item; + list_for_item(src_item, &dev->bsource_list) { + source = list_item(src_item, struct comp_buffer, sink_list); + if ((buf_get_id(source) >> 16) == 0) { + /* Pin 0 is audio from KPB: 1ch mono S32_LE */ +#if CONFIG_IPC_MAJOR_4 + ipc4_update_buffer_format(source, &cd->base_cfg.audio_fmt); +#else + struct sof_ipc_stream_params p; + wov_arb_params(dev, &p); + buffer_set_params(source, &p, true); +#endif + } + } + + /* Subscribe to keyword-detected events from any WOV detector. */ + notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_DETECT); + notifier_register(dev, NULL, NOTIFIER_ID_WOV_DETECT, arb_on_detect); + + /* Preserve the call gate if the host re-prepares the pipeline. */ + struct wov_ctrl_notif ctrl = { + .cmd = atomic_read(&cd->call_active) ? WOV_ARB_CMD_PAUSE : WOV_ARB_CMD_RESUME, + .slot_id = WOV_ARB_NO_ACTIVE, + }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, NOTIFIER_TARGET_CORE_ALL_MASK, + &ctrl, sizeof(ctrl)); + + return comp_set_state(dev, COMP_TRIGGER_PREPARE); +} + +static int wov_arb_reset(struct comp_dev *dev) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + + comp_info(dev, "wov_arb_reset"); + + if (cd && cd->active_slot != WOV_ARB_NO_ACTIVE) { + cd->active_slot = WOV_ARB_NO_ACTIVE; + if (!atomic_read(&cd->call_active)) { + struct wov_ctrl_notif c = { .cmd = WOV_ARB_CMD_RESUME }; + + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, + NOTIFIER_TARGET_CORE_ALL_MASK, + &c, sizeof(c)); + } + } + + cd->drain_frames_copied = 0; + cd->drain_frames_total = 0; + + notifier_unregister(dev, NULL, NOTIFIER_ID_WOV_DETECT); + + return comp_set_state(dev, COMP_TRIGGER_RESET); +} + +static int wov_arb_trigger(struct comp_dev *dev, int cmd) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + int ret; + + comp_info(dev, "wov_arb_trigger cmd %d", cmd); + + ret = comp_set_state(dev, cmd); + if (ret) + return ret; + + /* + * Stream stopped or paused: deactivate the active slot and resume + * all detectors so they return to listening mode. + */ + if (cmd == COMP_TRIGGER_STOP || cmd == COMP_TRIGGER_PAUSE) { + cd->drain_frames_copied = 0; + cd->drain_frames_total = 0; + if (cd->active_slot != WOV_ARB_NO_ACTIVE) { + comp_info(dev, "wov_arb: stream stopped, resuming all slots"); + cd->active_slot = WOV_ARB_NO_ACTIVE; +#if CONFIG_IPC_MAJOR_4 + notify_control_change(dev, cd, cd->active_slot_ctl_id, 0); +#endif + struct wov_ctrl_notif c = { .cmd = WOV_ARB_CMD_RESUME }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, + NOTIFIER_TARGET_CORE_ALL_MASK, + &c, sizeof(c)); + } + } + + return 0; +} + +static int wov_arb_params(struct comp_dev *dev, + struct sof_ipc_stream_params *params) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + +#if CONFIG_IPC_MAJOR_4 + ipc4_base_module_cfg_to_stream_params(&cd->base_cfg, params); +#else + /* Translate IPC4 base_cfg audio_fmt to IPC3-style stream params. */ + memset(params, 0, sizeof(*params)); + params->channels = cd->base_cfg.audio_fmt.channels_count; + params->rate = cd->base_cfg.audio_fmt.sampling_frequency; + params->sample_container_bytes = cd->base_cfg.audio_fmt.depth / 8; + params->sample_valid_bytes = + cd->base_cfg.audio_fmt.valid_bit_depth / 8; + params->buffer_fmt = cd->base_cfg.audio_fmt.interleaving_style; +#endif + component_set_nearest_period_frames(dev, params->rate); + + return 0; +} + +/* ------------------------------------------------------------------------- + * IPC4 large-config: allow host to force-select a slot (debug/test use). + * ---------------------------------------------------------------------- */ + +static int wov_arb_set_large_config(struct comp_dev *dev, + uint32_t param_id, + bool first_block, + bool last_block, + uint32_t data_offset, + const char *data) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + + switch (param_id) { + case SOF_IPC4_ENUM_CONTROL_PARAM_ID: { + const struct sof_ipc4_control_msg_payload *cp = + (const struct sof_ipc4_control_msg_payload *)data; + + if (cp->id == WOV_ARB_CALL_STATE_CONTROL_ID) { + cd->call_state_ctl_id = cp->id; + if (cp->num_elems > 0) { + uint32_t val = cp->chanv[0].value; + + if (val != WOV_ARB_CALL_STATE_LISTENING && + val != WOV_ARB_CALL_STATE_ACTIVE) + return -EINVAL; + + bool call_active = val == WOV_ARB_CALL_STATE_ACTIVE; + + atomic_set(&cd->call_active, call_active); + cd->active_slot = WOV_ARB_NO_ACTIVE; + struct wov_ctrl_notif c = { + .cmd = call_active ? WOV_ARB_CMD_PAUSE : WOV_ARB_CMD_RESUME, + .slot_id = WOV_ARB_NO_ACTIVE, + }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, + NOTIFIER_TARGET_CORE_ALL_MASK, + &c, sizeof(c)); + notify_control_change(dev, cd, cp->id, val); + comp_info(dev, "wov_arb: call state %s; detector control complete", + call_active ? "active" : "listening"); + } + return 0; + } + + if (cp->id != WOV_ARB_ACTIVE_SLOT_CONTROL_ID) + return -EINVAL; + + cd->active_slot_ctl_id = cp->id; + if (cp->num_elems > 0) { + uint32_t val = cp->chanv[0].value; + + if (atomic_read(&cd->call_active)) + return -EBUSY; + + if (val > cd->num_slots) + return -EINVAL; + + if (val == 0) { + comp_info(dev, "wov_arb: reset active_slot to listening (0)"); + cd->active_slot = WOV_ARB_NO_ACTIVE; + struct wov_ctrl_notif c = { .cmd = WOV_ARB_CMD_RESUME }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, + NOTIFIER_TARGET_CORE_ALL_MASK, + &c, sizeof(c)); + } else { + uint8_t selected_slot = (uint8_t)(val - 1); + + comp_info(dev, "wov_arb: filter listening to slot=%u via kcontrol", + selected_slot); + /* Keep listening mode while pausing all but the selected slot. */ + cd->active_slot = WOV_ARB_NO_ACTIVE; + struct wov_ctrl_notif r = { .cmd = WOV_ARB_CMD_RESUME }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, + NOTIFIER_TARGET_CORE_ALL_MASK, + &r, sizeof(r)); + struct wov_ctrl_notif p = { + .cmd = WOV_ARB_CMD_PAUSE, + .slot_id = selected_slot, + }; + notifier_event(dev, NOTIFIER_ID_WOV_CTRL, + NOTIFIER_TARGET_CORE_ALL_MASK, + &p, sizeof(p)); + } + } + return 0; + } + case SOF_IPC4_BYTES_CONTROL_PARAM_ID: + case IPC4_WOV_ARB_GET_ACTIVE_SLOT: + return 0; + case IPC4_WOV_ARB_SET_ACTIVE_SLOT: + cd->active_slot = *(const uint8_t *)data; + comp_info(dev, "wov_arb: force active_slot=%u", cd->active_slot); + return 0; + default: + return -EINVAL; + } +} + +static int wov_arb_get_attribute(struct comp_dev *dev, + uint32_t type, void *value) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + + if (type == COMP_ATTR_BASE_CONFIG) { + *(struct ipc4_base_module_cfg *)value = cd->base_cfg; + return 0; + } + return -EINVAL; +} + +/* ------------------------------------------------------------------------- + * copy() -- main audio processing + * + * For the active input pin: forward frames to the output. + * For all other input pins: consume and discard to prevent buffer stalls. + * + * Input buffers are ordered by connection order in bsource_list. + * Slot 0 = first connected source, etc. + * ---------------------------------------------------------------------- */ +static int wov_arb_copy(struct comp_dev *dev) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + struct comp_buffer *sink; + struct comp_buffer *source; + struct list_item *src_item; + uint32_t sink_free; + uint32_t active_avail = 0; + + comp_dbg(dev, "wov_arb_copy active=%u", cd->active_slot); + + sink = comp_dev_get_first_data_consumer(dev); + if (!sink) + return 0; + + sink_free = audio_stream_get_free_bytes(&sink->stream); + + uint32_t num_sources = 0; + uint32_t num_kpb_sources = 0; + list_for_item(src_item, &dev->bsource_list) { + source = list_item(src_item, struct comp_buffer, sink_list); + num_sources++; + if (source->source && dev_comp_type(source->source) == SOF_COMP_KPB) + num_kpb_sources++; + } + + /* + * Do NOT force a lone source "active" while listening: the host PCM must + * stay silent/idle (no data, no host-copier IRQs) until a real WOV + * detection (or the fake-wake test path) sets cd->active_slot via + * on_wov_detect(). That is what lets the host block in read() and the + * platform actually reach D0i3/suspend instead of being kept awake by a + * continuous keep-alive stream. + */ + uint32_t eff_active_slot = cd->active_slot; + struct comp_buffer *active_source = NULL; + + /* Find active audio source buffer if a slot is triggered */ + if (eff_active_slot != WOV_ARB_NO_ACTIVE) { + list_for_item(src_item, &dev->bsource_list) { + source = list_item(src_item, struct comp_buffer, sink_list); + if ((source->source && (source->source->drv->type == SOF_COMP_KPB || + dev_comp_type(source->source) == SOF_COMP_KPB)) || + (buf_get_id(source) >> 16) == 0) { + active_source = source; + break; + } + } + + if (active_source) + active_avail = audio_stream_get_avail_bytes(&active_source->stream); + } + + uint32_t copied_dst_bytes = 0; + + /* Second pass: copy active audio slot, silently drain idle/detector slots. */ + list_for_item(src_item, &dev->bsource_list) { + source = list_item(src_item, struct comp_buffer, sink_list); + + if (source == active_source) { + if (active_avail > 0 && sink_free > 0) { + uint32_t src_frame_bytes = audio_stream_frame_bytes(&source->stream); + uint32_t dst_frame_bytes = audio_stream_frame_bytes(&sink->stream); + if (!src_frame_bytes) + src_frame_bytes = cd->base_cfg.audio_fmt.depth ? + (cd->base_cfg.audio_fmt.channels_count * cd->base_cfg.audio_fmt.depth / 8) : 4; + if (!dst_frame_bytes) + dst_frame_bytes = cd->base_cfg.audio_fmt.depth ? + (cd->base_cfg.audio_fmt.channels_count * cd->base_cfg.audio_fmt.depth / 8) : 4; + + uint32_t src_frames = active_avail / src_frame_bytes; + uint32_t dst_frames = sink_free / dst_frame_bytes; + uint32_t frames = MIN(src_frames, dst_frames); + + if (frames > 0) { + uint32_t src_bytes = frames * src_frame_bytes; + uint32_t dst_bytes = frames * dst_frame_bytes; + uint32_t src_ch = audio_stream_get_channels(&source->stream); + uint32_t dst_ch = audio_stream_get_channels(&sink->stream); + uint32_t src_sb = audio_stream_sample_bytes(&source->stream); + uint32_t dst_sb = audio_stream_sample_bytes(&sink->stream); + + buffer_stream_invalidate(source, src_bytes); + + if (src_ch == 1 && dst_ch == 2) { + for (uint32_t i = 0; i < frames; i++) { + int32_t s = (src_sb == sizeof(int32_t)) ? + *(int32_t *)audio_stream_read_frag_s32(&source->stream, i) : + (((int32_t)*(int16_t *)audio_stream_read_frag_s16(&source->stream, i)) << 16); + if (dst_sb == sizeof(int32_t)) { + *(int32_t *)audio_stream_write_frag_s32(&sink->stream, 2 * i) = s; + *(int32_t *)audio_stream_write_frag_s32(&sink->stream, 2 * i + 1) = s; + } else { + int16_t s16 = (int16_t)(s >> 16); + *(int16_t *)audio_stream_write_frag_s16(&sink->stream, 2 * i) = s16; + *(int16_t *)audio_stream_write_frag_s16(&sink->stream, 2 * i + 1) = s16; + } + } + } else if (src_sb != dst_sb) { + if (src_sb == sizeof(int32_t) && dst_sb == sizeof(int16_t)) { + for (uint32_t i = 0; i < frames * src_ch; i++) { + int32_t s = *(int32_t *)audio_stream_read_frag_s32(&source->stream, i); + *(int16_t *)audio_stream_write_frag_s16(&sink->stream, i) = (int16_t)(s >> 16); + } + } else if (src_sb == sizeof(int16_t) && dst_sb == sizeof(int32_t)) { + for (uint32_t i = 0; i < frames * src_ch; i++) { + int16_t s = *(int16_t *)audio_stream_read_frag_s16(&source->stream, i); + *(int32_t *)audio_stream_write_frag_s32(&sink->stream, i) = ((int32_t)s) << 16; + } + } else { + audio_stream_copy(&source->stream, 0, + &sink->stream, 0, + frames * src_ch); + } + } else { + audio_stream_copy(&source->stream, 0, + &sink->stream, 0, + frames * src_ch); + } + + comp_update_buffer_consume(source, src_bytes); + buffer_stream_writeback(sink, dst_bytes); + comp_update_buffer_produce(sink, dst_bytes); + copied_dst_bytes = dst_bytes; + + cd->drain_frames_total += frames; + } + } + } else { + uint32_t avail = audio_stream_get_avail_bytes(&source->stream); + + if (avail > 0) + comp_update_buffer_consume(source, avail); + } + } + + cd->copy_count++; + if ((cd->copy_count % 100) == 1) { + comp_dbg(dev, "wov_arb_copy #%u: active=%u, num_src=%u, act_avail=%u, copied=%u, sink_free=%u", + cd->copy_count, cd->active_slot, num_sources, active_avail, copied_dst_bytes, sink_free); + } + + return 0; +} + +/* ------------------------------------------------------------------------- + * IPC4 large-config (get): expose active slot to userspace as a volatile + * RO enum kcontrol; the host reads this via GET_MODULE_LARGE_CONFIG. + * ---------------------------------------------------------------------- */ + +static int wov_arb_get_large_config(struct comp_dev *dev, + uint32_t param_id, + bool first_block, + bool last_block, + uint32_t *data_offset, + char *data) +{ + struct wov_arb_data *cd = comp_get_drvdata(dev); + + switch (param_id) { + case SOF_IPC4_ENUM_CONTROL_PARAM_ID: { + struct sof_ipc4_control_msg_payload *cp = + (struct sof_ipc4_control_msg_payload *)data; + uint16_t ctl_id = cp->id; + uint32_t resp_size = sizeof(struct sof_ipc4_control_msg_payload) + + sizeof(struct sof_ipc4_ctrl_value_chan); + + if (resp_size > *data_offset) { + comp_err(dev, "wrong enum control response size %u vs %u", + resp_size, *data_offset); + return -EINVAL; + } + + cd->active_slot_ctl_id = ctl_id; + *data_offset = resp_size; + memset_s(cp, resp_size, 0, resp_size); + cp->id = ctl_id; + cp->num_elems = 1; + cp->chanv[0].channel = 0; + /* 0 for Listening, 1..N for triggered slots */ + if (cd->active_slot == WOV_ARB_NO_ACTIVE) + cp->chanv[0].value = 0; + else + cp->chanv[0].value = (uint32_t)cd->active_slot + 1; + return 0; + } + case IPC4_WOV_ARB_GET_ACTIVE_SLOT: + *(uint32_t *)data = (uint32_t)cd->active_slot; + *data_offset = sizeof(uint32_t); + return 0; + default: + return -EINVAL; + } +} + +/* ------------------------------------------------------------------------- + * Component driver registration + * ---------------------------------------------------------------------- */ + +static const struct comp_driver wov_arbiter_drv = { + .type = SOF_COMP_KEYWORD_DETECT, + .uid = SOF_RT_UUID(wov_arbiter_uuid), +#if !CONFIG_ZEPHYR_LOG + .tctx = &wov_arbiter_tr, +#endif + .ops = { + .create = wov_arb_new, + .free = wov_arb_free, + .params = wov_arb_params, + .trigger = wov_arb_trigger, + .copy = wov_arb_copy, + .prepare = wov_arb_prepare, + .reset = wov_arb_reset, + .set_large_config = wov_arb_set_large_config, + .get_large_config = wov_arb_get_large_config, + .get_attribute = wov_arb_get_attribute, + }, +}; + +static struct comp_driver_info wov_arbiter_info = { + .drv = &wov_arbiter_drv, +}; + +UT_STATIC void sys_comp_wov_arbiter_init(void) +{ + comp_register(&wov_arbiter_info); +} + +DECLARE_MODULE(sys_comp_wov_arbiter_init); +SOF_MODULE_INIT(wov_arbiter, sys_comp_wov_arbiter_init); diff --git a/src/audio/wov_arbiter/wov_arbiter.toml b/src/audio/wov_arbiter/wov_arbiter.toml new file mode 100644 index 000000000000..9a7251627ab8 --- /dev/null +++ b/src/audio/wov_arbiter/wov_arbiter.toml @@ -0,0 +1,19 @@ + [[module.entry]] + name = "WOVARB" + uuid = UUIDREG_STR_WOV_ARBITER + affinity_mask = "0x1" + instance_count = "3" + domain_types = "0" + load_type = "0" + module_type = "0xB" + 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, 0xa, 0x45ff] + + 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, 14400, 1114000, 32, 32, 0, 0, 0] + + index = __COUNTER__ diff --git a/src/include/sof/audio/component.h b/src/include/sof/audio/component.h index e879888053b0..729fe470dde9 100644 --- a/src/include/sof/audio/component.h +++ b/src/include/sof/audio/component.h @@ -886,6 +886,7 @@ void sys_comp_dai_init(void); void sys_comp_host_init(void); void sys_comp_kpb_init(void); void sys_comp_selector_init(void); +void sys_comp_wov_arbiter_init(void); /* Start of modules in alphabetical order */ void sys_comp_module_aria_interface_init(void); diff --git a/tools/rimage/config/nvl.toml.h b/tools/rimage/config/nvl.toml.h index e1f4ebfb6336..fd530d561258 100644 --- a/tools/rimage/config/nvl.toml.h +++ b/tools/rimage/config/nvl.toml.h @@ -189,5 +189,9 @@ index = __COUNTER__ #include