bolar_2 backup

This commit is contained in:
2026-11-27 16:38:11 +08:00
commit e96d6d19df
305 changed files with 43350 additions and 0 deletions

View File

@@ -0,0 +1,969 @@
#include "audio/voice_frontend.h"
#include "core/task_stack_budget.h"
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/idf_additions.h>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace borla {
namespace {
constexpr const char* kTag = "VoiceFrontend2";
} // namespace
bool VoiceFrontend::Initialize()
{
std::lock_guard<std::mutex> lock(processor_mutex_);
if (initialized_) {
return true;
}
buffers_ = MakePsramObject<ScratchBuffers>();
if (!buffers_) {
ESP_LOGE(kTag, "voice scratch buffer allocation failed");
return false;
}
if (!dsp_.InitializeNoiseSuppression()) {
buffers_.reset();
return false;
}
// Boot runs before the WiFi driver exists, so this is the one moment the
// internal heap is rich and unfragmented. Non-fatal: without the prewarm
// the first duplex turn creates the state mid-conversation and steals the
// websocket's reconnect budget.
dsp_.PrewarmEchoCancellation();
wake_queue_ = xQueueCreateWithCaps(
kWakeQueueFrames,
kFrameSamples * sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (wake_queue_ == nullptr) {
ESP_LOGE(kTag, "wake queue allocation failed");
buffers_.reset();
return false;
}
const BaseType_t created = xTaskCreatePinnedToCoreWithCaps(
&VoiceFrontend::WakeScanTaskEntry,
"wake_scan2",
kWakeScanStackBytes,
this,
task_priority::kAudioCodec,
&wake_task_,
1,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (created != pdPASS) {
ESP_LOGE(kTag, "wake scan task creation failed");
vQueueDeleteWithCaps(wake_queue_);
wake_queue_ = nullptr;
buffers_.reset();
return false;
}
ESP_LOGI(kTag,
"wake scan task started core=1 stack_bytes=%u queue=%u",
static_cast<unsigned>(kWakeScanStackBytes),
static_cast<unsigned>(kWakeQueueFrames));
initialized_ = true;
return true;
}
void VoiceFrontend::WakeScanTaskEntry(void* context)
{
static_cast<VoiceFrontend*>(context)->RunWakeScan();
}
[[noreturn]] void VoiceFrontend::RunWakeScan()
{
// PSRAM stack is fine here: WakeNet's weights already live in PSRAM and
// the detect cost is dominated by the model math, not stack traffic.
std::array<int16_t, kFrameSamples> frame{};
while (true) {
if (wake_reset_pending_.exchange(
false, std::memory_order_acq_rel)) {
wake_accumulator_count_ = 0;
}
if (xQueueReceive(
wake_queue_, frame.data(), pdMS_TO_TICKS(100)) ==
pdTRUE) {
FeedWakeWord(frame.data(), frame.size());
}
}
}
void VoiceFrontend::QueueWakeAudio(const int16_t* samples)
{
if (wake_queue_ == nullptr) {
return;
}
// Zero timeout: the capture task must never block on the scanner. A full
// queue means the scanner is more than 360 ms behind — dropping is the
// only option that keeps the microphone stream (and AEC alignment) alive.
xQueueSend(wake_queue_, samples, 0);
}
void VoiceFrontend::SetEventPublisher(IEventPublisher* publisher)
{
publisher_.store(publisher);
}
bool VoiceFrontend::EnsureWakeWordLoaded()
{
if (wake_word_.initialized()) {
return true;
}
// esp_srmodel_init() + create() reads the model partition and takes ~110 ms
// on this board. It happens at most once per boot; the previous code ran it
// on every policy change that needed the wake word, i.e. twice per
// conversation turn, while holding processor_mutex_. That stalled the
// capture task for two whole 60 ms frames right as TTS playback started,
// which both blinded the wake word during the exact window a child would
// use it and scrambled the AEC mic/reference phase so the speaker echo
// reached the server uncancelled. The previous firmware kept the model
// resident for the whole uptime and only toggled a flag; so do we.
std::lock_guard<std::mutex> lock(wake_mutex_);
return wake_word_.Initialize();
}
void VoiceFrontend::ReleaseWakeWord()
{
std::lock_guard<std::mutex> lock(processor_mutex_);
std::lock_guard<std::mutex> wake_lock(wake_mutex_);
if (!wake_word_.initialized()) {
return;
}
wake_word_.Deinitialize();
wake_reset_pending_.store(true, std::memory_order_release);
ESP_LOGI(kTag, "WakeNet released");
}
void VoiceFrontend::SetWakeWordEnabled(bool enabled)
{
std::lock_guard<std::mutex> lock(processor_mutex_);
if (wake_word_enabled_ == enabled) {
return;
}
wake_word_enabled_ = enabled;
if (!enabled) {
// Keep the model loaded; only stop feeding it. Destroying it here is
// what made the reload expensive in the first place.
wake_reset_pending_.store(true, std::memory_order_release);
} else if (initialized_ && WakeRequired(policy_) &&
!EnsureWakeWordLoaded()) {
ESP_LOGE(kTag, "WakeNet unavailable after remote enable");
}
ESP_LOGI(kTag, "remote wake word=%d", enabled ? 1 : 0);
}
void VoiceFrontend::ApplyPolicy(AudioPolicy policy)
{
bool wake_ready = false;
bool aec_active = false;
bool duplex_window_closed = false;
// The mutex is scoped so the log lines below are written with it released.
// A ~150 character line takes on the order of 10 ms to drain at the console
// baud rate, and the capture task blocks on this same mutex once per 60 ms
// frame; holding it across the write is the same class of stall that the
// per-turn WakeNet reload used to cause.
{
std::lock_guard<std::mutex> lock(processor_mutex_);
if (!initialized_ || policy_ == policy) {
policy_ = policy;
return;
}
if (WakeRequired(policy) && !EnsureWakeWordLoaded()) {
ESP_LOGE(kTag, "WakeNet unavailable for policy=%s",
ToString(policy));
}
if (!WakeRequired(policy)) {
// The model stays resident; only the accumulator is dropped so the
// next duplex window does not start mid-phrase. The accumulator
// is owned by the wake-scan task, so hand it a reset flag rather
// than racing it.
wake_reset_pending_.store(true, std::memory_order_release);
}
const bool old_aec_required = AecRequired(policy_);
const bool new_aec_required = AecRequired(policy);
if (new_aec_required) {
const bool barge_in_profile =
policy != AudioPolicy::kCallDuplex;
if (!dsp_.EnableEchoCancellation(barge_in_profile)) {
ESP_LOGE(kTag, "AEC unavailable for policy=%s",
ToString(policy));
}
} else {
dsp_.SuspendEchoCancellation();
}
if (old_aec_required != new_aec_required) {
ClearReference();
}
if (policy == AudioPolicy::kConversationCapture ||
policy_ == AudioPolicy::kConversationCapture) {
vad_.Reset();
self_capture_hangover_ = 0;
}
if (policy != AudioPolicy::kBargeInDuplex) {
// The policy change means the control plane already decided the
// turn; a pending candidate must not publish a stale verdict on
// top. leak_ratio_ intentionally survives — the echo path barely
// moves between sessions, so the next duplex window starts with a
// trained gate instead of re-learning through a dirty one.
candidate_active_ = false;
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
uplink_pass_until_us_ = 0;
probe_silence_frames_ = 0;
candidate_deadline_us_ = 0;
candidate_rearm_until_us_ = 0;
candidate_needs_quiet_ = false;
window_ref_active_frames_ = 0;
previous_reference_rms_[0] = 0;
previous_reference_rms_[1] = 0;
}
policy_ = policy;
wake_ready = wake_word_.initialized();
aec_active = new_aec_required;
duplex_window_closed = old_aec_required && !new_aec_required;
}
// Debug: the engine's one-line summary (requested/effective/wake/barge)
// already covers every policy change at INFO.
ESP_LOGD(kTag, "policy=%s wake=%d aec=%d",
ToString(policy),
wake_ready ? 1 : 0,
aec_active ? 1 : 0);
if (duplex_window_closed) {
// One line per duplex window. aec_reference_misses is the number that
// matters: every miss is a 60 ms frame the AEC could not cancel, i.e.
// a frame of the device's own TTS that would have reached the server.
LogMetrics("duplex window closed");
}
}
void VoiceFrontend::LogMetrics(const char* reason) const
{
// Snapshot under the spinlock, format outside it.
const VoiceFrontendMetrics snapshot = Metrics();
ESP_LOGI(kTag,
"voice metrics (%s) frames=%lu ref_frames=%lu ref_drops=%lu "
"ref_trims=%lu "
"ref_misses=%lu uplink_suppressed=%lu self_capture=%lu "
"gated=%lu cand=%lu cand_local_rej=%lu cand_timeout=%lu "
"wake=%lu self_wake=%lu "
"vad_stops=%lu dsp_fail=%lu",
reason,
static_cast<unsigned long>(snapshot.processed_frames),
static_cast<unsigned long>(snapshot.reference_frames),
static_cast<unsigned long>(snapshot.reference_drops),
static_cast<unsigned long>(snapshot.reference_trims),
static_cast<unsigned long>(snapshot.aec_reference_misses),
static_cast<unsigned long>(snapshot.uplink_suppressions),
static_cast<unsigned long>(snapshot.self_capture_suppressions),
static_cast<unsigned long>(snapshot.residual_gated),
static_cast<unsigned long>(snapshot.barge_in_candidates),
static_cast<unsigned long>(snapshot.barge_in_local_rejects),
static_cast<unsigned long>(snapshot.barge_in_timeouts),
static_cast<unsigned long>(snapshot.wake_detections),
static_cast<unsigned long>(snapshot.self_wake_suppressions),
static_cast<unsigned long>(snapshot.vad_stops),
static_cast<unsigned long>(snapshot.dsp_failures));
}
bool VoiceFrontend::Process(
AudioPolicy policy,
const int16_t* input,
size_t sample_count,
int16_t* output,
size_t output_capacity)
{
if (input == nullptr || output == nullptr ||
sample_count != kFrameSamples ||
output_capacity < kFrameSamples) {
return false;
}
std::lock_guard<std::mutex> lock(processor_mutex_);
std::array<int16_t, kFrameSamples> reference{};
const bool has_reference = PopReference(reference.data());
const uint32_t microphone_rms = FrameRms(input, sample_count);
const uint32_t reference_rms =
has_reference ? FrameRms(reference.data(), reference.size()) : 0;
// Authoritative "is our own speaker running right now" test, shared by the
// VAD gate below and the wake-word self-trigger guard further down. Derived
// from the playback task's per-frame callback rather than from the energy of
// a popped reference frame, because the reference ring is empty whenever it
// has just been cleared or trimmed — and then the energy test silently
// reports "quiet" while the speaker is at full volume.
const uint64_t now_us =
static_cast<uint64_t>(esp_timer_get_time());
const uint64_t last_playback_us =
last_playback_frame_us_.load(std::memory_order_relaxed);
const bool speaker_active =
last_playback_us != 0 &&
now_us - last_playback_us < kSpeakerActiveWindowUs;
bool processed = true;
bool uplink_suppressed = false;
if (policy == AudioPolicy::kConversationCapture) {
processed = dsp_.Process(
input, nullptr, false, output, sample_count);
// Local prompts play while this policy is active — the wake
// acknowledgement "我在" is emitted immediately after the device enters
// listening — and this policy deliberately runs without AEC, so the
// microphone hears them at full level. Uploading that feeds the
// server's ASR the device's own voice, so the frames are dropped and
// the VAD is held in reset while the speaker runs. The server owns
// the authoritative auto-stop (listen mode="auto"), so a turn cannot
// hang here when the child stays quiet.
if (speaker_active) {
self_capture_hangover_ = kSelfCaptureHangoverFrames;
}
if (self_capture_hangover_ > 0) {
--self_capture_hangover_;
vad_.Reset();
uplink_suppressed = true;
portENTER_CRITICAL(&metrics_lock_);
metrics_.self_capture_suppressions++;
portEXIT_CRITICAL(&metrics_lock_);
} else if (processed) {
// Observability only. The turn end is owned by the server
// (listen mode="auto", protocols/websocket_protocol.md): its VAD
// pads and finalizes the ASR segment. Publishing a local stop
// here used to close the turn early — WakeNet fires mid-phrase,
// so the wake word's own tail (>=2 loud frames = 120 ms) read as
// "speech started" and 13 quiet frames later the device tore the
// listening window down before the child had said a word.
const VoiceActivityResult vad =
vad_.Process(output, sample_count);
// Two short lines per turn. Kept on this task on purpose: the
// instant a turn opens and closes is exactly what needs a
// timestamp, and aggregating it would lose that.
if (vad == VoiceActivityResult::kSpeechStarted) {
ESP_LOGI(kTag, "vad speech_started rms=%lu",
static_cast<unsigned long>(vad_.LastRms()));
} else if (vad == VoiceActivityResult::kSpeechEnded) {
ESP_LOGI(kTag, "vad speech_ended rms=%lu",
static_cast<unsigned long>(vad_.LastRms()));
portENTER_CRITICAL(&metrics_lock_);
metrics_.vad_stops++;
portEXIT_CRITICAL(&metrics_lock_);
}
}
} else if (AecRequired(policy)) {
processed = dsp_.Process(
input,
reference.data(),
true,
output,
sample_count,
buffers_->wake_tap.data());
if (processed &&
policy == AudioPolicy::kBargeInDuplex &&
UpdateBargeInGate(
FrameRms(output, sample_count),
reference_rms,
has_reference,
speaker_active,
now_us)) {
uplink_suppressed = true;
portENTER_CRITICAL(&metrics_lock_);
metrics_.residual_gated++;
portEXIT_CRITICAL(&metrics_lock_);
}
if (processed && !uplink_suppressed &&
!has_reference && speaker_active) {
// The speaker is running but the reference ring was empty for this
// frame, so the AEC subtracted nothing and the frame still carries
// the full echo. Uploading it makes the server's ASR transcribe the
// device's own TTS and raise a barge-in against itself. Drop it from
// the uplink but keep it for the local wake word below, which is
// exactly the path that has to survive so "你好波乐" can still
// interrupt playback.
//
// speaker_active is load-bearing. This used to suppress on "no
// reference" alone — but an empty reference ring is overwhelmingly
// the signature of "nothing is playing", not of a missed frame. In
// kCallDuplex the far end is silent for most of a call, so no
// playback frame ever arrives, the ring stays empty, and every
// single microphone frame was dropped: the uplink was mute for the
// whole call. kWakeWordDuplex and the tail of a kBargeInDuplex turn
// had the same hole. No playback means no echo, so those frames are
// safe to send and must be sent — that silence was the child's turn.
uplink_suppressed = true;
portENTER_CRITICAL(&metrics_lock_);
metrics_.aec_reference_misses++;
portEXIT_CRITICAL(&metrics_lock_);
}
// Both duplex flavors feed WakeNet the AEC-cleaned output: it is the
// only interrupt in kWakeWordDuplex (no uplink there), and the fast
// "你好播乐 cuts the reply" path in kBargeInDuplex — natural speech
// there still goes through server VAD/ASR arbitration. Fed from the
// pre-AGC tap, not `output`: the AGC swings 0.9-1.8 during
// music+speech double-talk and the gain steps chop the phrase.
// A missing playback reference must not create a blind WakeNet frame:
// with a zero reference the DSP output is still a usable microphone
// fallback, and dropping it could cut an arbitrary part of the wake
// phrase.
if (processed && WakeRequired(policy)) {
QueueWakeAudio(buffers_->wake_tap.data());
}
} else {
std::memcpy(
output, input, sample_count * sizeof(int16_t));
if (WakeRequired(policy)) {
// Same hazard as the VAD gate: idle-mode prompts (idle_check,
// alarms, the shutdown prompt) reach the microphone unattenuated
// because this path has no AEC, and WakeNet will happily trigger on
// the device's own voice. The previous firmware hit this in the
// field (2026-07-03: idle_check "你还在吗小朋友" self-triggering)
// and muted detection around the prompt for the same reason.
if (speaker_active || self_capture_hangover_ > 0) {
if (self_capture_hangover_ > 0) {
--self_capture_hangover_;
}
if (speaker_active) {
self_capture_hangover_ = kSelfCaptureHangoverFrames;
}
portENTER_CRITICAL(&metrics_lock_);
metrics_.self_wake_suppressions++;
portEXIT_CRITICAL(&metrics_lock_);
} else {
QueueWakeAudio(output);
}
}
}
AccumulateFrameStats(
policy,
microphone_rms,
FrameRms(output, sample_count),
reference_rms,
has_reference);
portENTER_CRITICAL(&metrics_lock_);
metrics_.processed_frames++;
if (!processed) {
metrics_.dsp_failures++;
}
if (uplink_suppressed) {
metrics_.uplink_suppressions++;
}
portEXIT_CRITICAL(&metrics_lock_);
// Returning false makes CapturePipeline skip the encode/uplink for this
// frame. The wake word has already consumed it above.
return processed && !uplink_suppressed;
}
void VoiceFrontend::OnPlaybackReference(
const int16_t* samples,
size_t sample_count)
{
// Stamp first: this call means a frame is on its way to the DAC, which is
// the fact the capture side needs. Whether it also lands in the reference
// ring is a separate question.
last_playback_frame_us_.store(
static_cast<uint64_t>(esp_timer_get_time()),
std::memory_order_relaxed);
std::array<int16_t, kFrameSamples> converted{};
if (!reference_converter_.Convert(
samples,
sample_count,
converted.data(),
converted.size())) {
return;
}
uint32_t discarded = 0;
{
std::lock_guard<std::mutex> lock(reference_mutex_);
if (!buffers_) {
return;
}
// Trim before pushing so occupancy after this call never exceeds
// kReferenceMaxLeadFrames. See the constant for why the old
// drop-one-when-full rule pinned the skew at its maximum instead of
// bounding it.
while (reference_count_ >= kReferenceMaxLeadFrames) {
reference_read_ =
(reference_read_ + 1) % kReferenceDepth;
reference_count_--;
discarded++;
}
buffers_->reference_ring[reference_write_] = converted;
reference_write_ =
(reference_write_ + 1) % kReferenceDepth;
reference_count_++;
}
if (discarded != 0) {
// The reference just jumped a frame relative to the echo still in
// flight; the AEC runs misaligned until it re-adapts and its residual
// bursts over the floor. Field run: 15 trims, ~17 false candidates,
// each pausing playback 0.4-1.5 s. Hold candidates while it settles.
alignment_settle_until_us_.store(
static_cast<uint64_t>(esp_timer_get_time()) + kAlignmentSettleUs,
std::memory_order_relaxed);
}
portENTER_CRITICAL(&metrics_lock_);
metrics_.reference_frames++;
if (discarded != 0) {
metrics_.reference_drops += discarded;
metrics_.reference_trims++;
}
portEXIT_CRITICAL(&metrics_lock_);
}
void VoiceFrontend::ResetPlaybackReference()
{
ClearReference();
}
VoiceFrontendMetrics VoiceFrontend::Metrics() const
{
portENTER_CRITICAL(&metrics_lock_);
const VoiceFrontendMetrics snapshot = metrics_;
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
bool VoiceFrontend::WakeRequired(AudioPolicy policy) const
{
// kBargeInDuplex feeds WakeNet too, so "你好播乐" interrupts a playing
// reply (product requirement). This was disabled while AEC+WakeNet
// measured 68 ms per 60 ms frame — but that number had Opus encode on the
// same task. With the encoder on core 1 and complexity 3 the duplex
// process step averages 10-15 ms (max ~37 ms); WakeNet's ~14 ms fits the
// budget. Watch period_avg in the frame stats: if it climbs past ~65 ms
// the fallback is a dedicated core-1 wake task (audit option R7).
// Self-trigger safety: the feed is post-AEC (echo at -10..-20 dB), and a
// rare false fire lands in the state machine as an ordinary barge-in.
//
// kWakeWordDuplex keeps it for the no-uplink prompt/alert windows where
// the wake word is the only interrupt.
return wake_word_enabled_ &&
(policy == AudioPolicy::kWakeWordOnly ||
policy == AudioPolicy::kWakeWordDuplex ||
policy == AudioPolicy::kBargeInDuplex);
}
bool VoiceFrontend::AecRequired(AudioPolicy policy) const
{
return policy == AudioPolicy::kWakeWordDuplex ||
policy == AudioPolicy::kBargeInDuplex ||
policy == AudioPolicy::kCallDuplex;
}
void VoiceFrontend::FeedWakeWord(
const int16_t* samples,
size_t sample_count)
{
// Wake-scan task only. The lock serializes Detect against the model
// being loaded (ApplyPolicy) or released (BLE provisioning).
std::lock_guard<std::mutex> lock(wake_mutex_);
if (!buffers_ || !wake_word_.initialized() ||
wake_word_.ChunkSamples() == 0) {
return;
}
auto& wake_accumulator = buffers_->wake_accumulator;
const uint64_t now_ms = static_cast<uint64_t>(
esp_timer_get_time() / 1000);
if (now_ms < wake_cooldown_until_ms_) {
return;
}
if (wake_accumulator_count_ + sample_count >
wake_accumulator.size()) {
wake_accumulator_count_ = 0;
}
std::memcpy(
wake_accumulator.data() + wake_accumulator_count_,
samples,
sample_count * sizeof(int16_t));
wake_accumulator_count_ += sample_count;
const size_t chunk = wake_word_.ChunkSamples();
while (wake_accumulator_count_ >= chunk) {
const bool detected = wake_word_.Detect(
wake_accumulator.data(), chunk);
std::memmove(
wake_accumulator.data(),
wake_accumulator.data() + chunk,
(wake_accumulator_count_ - chunk) * sizeof(int16_t));
wake_accumulator_count_ -= chunk;
if (detected) {
// ConversationCapture does not feed WakeNet. A frame counter used
// to freeze for the whole user question, then blind the first two
// seconds of the following TTS reply. Wall time keeps the intended
// duplicate-trigger protection without carrying that blind spot.
wake_cooldown_until_ms_ = now_ms + kWakeCooldownMs;
portENTER_CRITICAL(&metrics_lock_);
metrics_.wake_detections++;
portEXIT_CRITICAL(&metrics_lock_);
Publish(AppEvent::Make(
AppEventType::kWakeWordDetected));
wake_accumulator_count_ = 0;
break;
}
}
}
void VoiceFrontend::ResolveCandidateLocked(
AppEventType verdict,
const char* reason,
uint64_t now_us)
{
candidate_active_ = false;
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
probe_silence_frames_ = 0;
candidate_deadline_us_ = 0;
// No new candidate until the energy has both cooled off in time and
// dipped below the leak line at least once — see kCandidateRearmUs.
candidate_rearm_until_us_ = now_us + kCandidateRearmUs;
candidate_needs_quiet_ = true;
ESP_LOGI(kTag, "barge-in candidate %s", reason);
Publish(AppEvent::Make(verdict));
}
bool VoiceFrontend::UpdateBargeInGate(
uint32_t out_rms,
uint32_t reference_rms,
bool has_reference,
bool speaker_active,
uint64_t now_us)
{
if (candidate_active_) {
if (now_us >= candidate_deadline_us_) {
// Neither the server nor the probe decided. Resume playback; the
// reducer drops this if the server confirmed meanwhile.
portENTER_CRITICAL(&metrics_lock_);
metrics_.barge_in_timeouts++;
portEXIT_CRITICAL(&metrics_lock_);
// Sustained energy the server chose not to act on is most likely
// a raised noise floor; lift the line so it stops re-triggering.
leak_ratio_ = std::min(leak_ratio_ * 1.25F, kLeakMaximum);
ResolveCandidateLocked(
AppEventType::kBargeInRejected, "timed out, resuming",
now_us);
} else if (!speaker_active) {
// Playback paused, so the echo source is gone: whatever the
// microphone hears now is ground truth.
if (out_rms < kProbeSpeechFloorRms) {
if (++probe_silence_frames_ >= kProbeSilenceFrames) {
// The energy vanished with the speaker — it was residual.
// Raise the leak line so the same level does not trigger
// again, and resume.
leak_ratio_ = std::min(
leak_ratio_ * 1.5F, kLeakMaximum);
portENTER_CRITICAL(&metrics_lock_);
metrics_.barge_in_local_rejects++;
portEXIT_CRITICAL(&metrics_lock_);
ResolveCandidateLocked(
AppEventType::kBargeInRejected,
"probe heard silence, resuming",
now_us);
}
} else {
// A voice that survives the pause is a real voice; it is now
// uploading clean. Leave the verdict to the server's STT.
probe_silence_frames_ = 0;
}
}
}
if (!speaker_active) {
// Speaker quiet (idle gap or candidate pause): no echo to gate, every
// frame belongs to the room. Upload freely.
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
return false;
}
if (!has_reference) {
// Full echo with nothing to subtract; the caller's reference-miss rule
// suppresses it. It carries no gate information either way.
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
return false;
}
// Residual lags the reference by the TX DMA depth (~1.5 frames), so the
// echo in this frame is explained by the loudest of the LAST THREE
// reference frames, not by the instantaneous one. Judged against the
// instantaneous value the per-frame ratio swung between ~0.1 and ~1.0
// with alignment jitter (field: out=1437 against ref=1450 one moment,
// out=787 against ref=7325 the next) — no single line covers that spread
// without also swallowing speech.
const uint32_t reference_peak = std::max(
{reference_rms,
previous_reference_rms_[0],
previous_reference_rms_[1]});
previous_reference_rms_[1] = previous_reference_rms_[0];
previous_reference_rms_[0] = reference_rms;
// Leak information only exists while the reference actually carries
// energy. In an inter-sentence TTS gap the ratio degenerates — training
// on it would drag the line to a clamp and blind the gate for the next
// sentence. Gap frames are judged by the absolute floor alone.
const bool reference_active =
reference_peak >= kReferenceActiveRms;
if (reference_active &&
window_ref_active_frames_ < UINT16_MAX) {
window_ref_active_frames_++;
}
const float ratio =
static_cast<float>(out_rms) /
static_cast<float>(reference_peak != 0 ? reference_peak : 1);
if (!leak_seeded_ && reference_active) {
// Warm-up. The first reference frames PRECEDE their own echo (the
// reference is queued ~1.5 frames before the sound leaves the
// speaker), so seeding from the first frame reads out≈noise and pins
// the line at the floor — the field failure was candidates raised
// with leak=0.05 while ERL was 7 dB, each pausing playback for half a
// second. Instead: withhold the first kLeakWarmupFrames loud frames
// outright, remember the WORST ratio seen, and floor the seed. A high
// start self-corrects (the EMA below only trains on gated frames, so
// the line can walk down to truth but never up past speech); a low
// start is a trap.
leak_ratio_ = std::clamp(
std::max(leak_ratio_, ratio),
kLeakMinimum,
kLeakMaximum);
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
if (++leak_warmup_frames_ >= kLeakWarmupFrames) {
leak_ratio_ = std::max(leak_ratio_, kLeakSeedMinimum);
leak_seeded_ = true;
ESP_LOGI(kTag, "barge-in gate seeded leak=%.2f",
static_cast<double>(leak_ratio_));
}
return true;
}
float threshold = leak_seeded_
? leak_ratio_ * static_cast<float>(reference_peak) *
kLeakMargin
: 0.0F;
threshold = std::max(
threshold, static_cast<float>(kResidualFloorRms));
if (static_cast<float>(out_rms) <= threshold) {
// The dip below the line still re-arms the candidate gate either way.
candidate_needs_quiet_ = false;
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
if (now_us < uplink_pass_until_us_) {
// Inside an open voice segment this is an envelope dip, not
// residual: pass it so the server hears one contiguous
// utterance, and do NOT train the leak line on it — the frame
// may carry voice and training would drag the line upward.
return false;
}
// Explainable as residual: withhold it from the uplink, and train the
// leak line when the frame carries usable ratio information.
if (leak_seeded_ && reference_active) {
leak_ratio_ = std::clamp(
leak_ratio_ + kLeakAlpha * (ratio - leak_ratio_),
kLeakMinimum,
kLeakMaximum);
}
return true;
}
// Above the leak line: treat as the child speaking over the TTS. The frame
// flows to the server, and enough of them in a row raises the reversible
// pause. The leak estimate is deliberately not trained on these frames.
if (consecutive_speech_frames_ < 255) {
++consecutive_speech_frames_;
}
streak_peak_rms_ = std::max(streak_peak_rms_, out_rms);
if (consecutive_speech_frames_ >= kUplinkPassStreak) {
// Plausible voice: open (or extend) the segment window so the whole
// utterance reaches the server in one piece.
uplink_pass_until_us_ = now_us + kUplinkPassWindowUs;
}
// Candidates only where the pause-probe has value: gate seeded, the
// reference loud enough that echo could explain the energy, past the
// per-window AEC convergence holdoff, and not inside the re-adaptation
// window a reference trim opens. The trigger itself is shape-based:
// a sustained streak whose peak reached voice level — residual plateaus
// never peak, speech always does. Everything else still uploads and is
// the server's call.
if (!candidate_active_ &&
leak_seeded_ &&
reference_active &&
window_ref_active_frames_ >= kCandidateHoldoffFrames &&
now_us >= alignment_settle_until_us_.load(
std::memory_order_relaxed) &&
!candidate_needs_quiet_ &&
now_us >= candidate_rearm_until_us_ &&
consecutive_speech_frames_ >= kCandidateFrames &&
streak_peak_rms_ >= kCandidateStrongRms) {
candidate_active_ = true;
probe_silence_frames_ = 0;
candidate_deadline_us_ = now_us + kCandidateTimeoutUs;
portENTER_CRITICAL(&metrics_lock_);
metrics_.barge_in_candidates++;
portEXIT_CRITICAL(&metrics_lock_);
ESP_LOGI(kTag,
"barge-in candidate raised out_rms=%lu peak=%lu ref_rms=%lu "
"leak=%.2f",
static_cast<unsigned long>(out_rms),
static_cast<unsigned long>(streak_peak_rms_),
static_cast<unsigned long>(reference_rms),
static_cast<double>(leak_ratio_));
Publish(AppEvent::Make(AppEventType::kBargeInCandidate));
}
if (now_us < uplink_pass_until_us_) {
return false;
}
if (consecutive_speech_frames_ == 1 && !candidate_active_) {
// Single-frame excursions over the leak line are the signature of a
// syllable-onset residual spike (the adaptive filter under-cancels
// transients); real speech sustains. Withhold the first frame and
// pass from the second on — costs 60 ms of a genuine barge-in onset,
// which the server's ASR tolerates, and removes the last rhythmic
// residual ticks from the uplink.
return true;
}
return false;
}
bool VoiceFrontend::PopReference(int16_t* output)
{
std::lock_guard<std::mutex> lock(reference_mutex_);
if (!buffers_ || reference_count_ == 0) {
// Ring drained: the next burst must re-prime before serving, or the
// whole burst runs echo-misaligned (see reference_primed_).
reference_primed_ = false;
std::fill_n(output, kFrameSamples, 0);
return false;
}
if (!reference_primed_) {
if (reference_count_ < kReferencePrimeFrames) {
// The echo of these first frames is still inside the ~90 ms TX
// DMA and has not reached the microphone; serving them now would
// pair the AEC with a reference the echo lags by more than the
// 64 ms filter span. Field data: ref_depth >= ~2 tracked
// erl 16-20 dB, depth < 1 tracked erl <= 8 dB — every playback
// gap drained the ring and the following burst leaked rhythmic
// TTS residual into the uplink until depth recovered by luck.
std::fill_n(output, kFrameSamples, 0);
return false;
}
reference_primed_ = true;
}
std::memcpy(
output,
buffers_->reference_ring[reference_read_].data(),
kFrameSamples * sizeof(int16_t));
reference_read_ =
(reference_read_ + 1) % kReferenceDepth;
reference_count_--;
return true;
}
void VoiceFrontend::ClearReference()
{
std::lock_guard<std::mutex> lock(reference_mutex_);
reference_read_ = 0;
reference_write_ = 0;
reference_count_ = 0;
reference_primed_ = false;
}
uint32_t VoiceFrontend::FrameRms(
const int16_t* samples,
size_t sample_count)
{
if (samples == nullptr || sample_count == 0) {
return 0;
}
uint64_t energy = 0;
for (size_t index = 0; index < sample_count; ++index) {
const int32_t value = samples[index];
energy += static_cast<uint64_t>(value * value);
}
return static_cast<uint32_t>(
std::sqrt(
static_cast<double>(energy) /
static_cast<double>(sample_count)));
}
void VoiceFrontend::AccumulateFrameStats(
AudioPolicy policy,
uint32_t microphone_rms,
uint32_t processed_rms,
uint32_t reference_rms,
bool has_reference)
{
const uint64_t now_us =
static_cast<uint64_t>(esp_timer_get_time());
uint32_t depth = 0;
{
std::lock_guard<std::mutex> lock(reference_mutex_);
depth = static_cast<uint32_t>(reference_count_);
}
portENTER_CRITICAL(&metrics_lock_);
if (last_frame_us_ != 0 && now_us > last_frame_us_) {
const uint32_t period_us =
static_cast<uint32_t>(now_us - last_frame_us_);
frame_stats_.period_us_sum += period_us;
frame_stats_.period_us_max =
std::max(frame_stats_.period_us_max, period_us);
}
last_frame_us_ = now_us;
frame_stats_.frames++;
frame_stats_.policy = policy;
frame_stats_.microphone_rms_sum += microphone_rms;
frame_stats_.processed_rms_sum += processed_rms;
frame_stats_.reference_rms_sum += reference_rms;
frame_stats_.microphone_rms_peak =
std::max(frame_stats_.microphone_rms_peak, microphone_rms);
frame_stats_.processed_rms_peak =
std::max(frame_stats_.processed_rms_peak, processed_rms);
frame_stats_.reference_rms_peak =
std::max(frame_stats_.reference_rms_peak, reference_rms);
if (has_reference) {
frame_stats_.reference_present_frames++;
}
if (reference_rms >= kReferenceActiveRms) {
frame_stats_.reference_active_frames++;
}
frame_stats_.reference_depth_sum += depth;
frame_stats_.reference_depth_peak =
std::max(frame_stats_.reference_depth_peak, depth);
if (vad_.speech_active()) {
frame_stats_.vad_speech_frames++;
}
frame_stats_.agc_gain = dsp_.AgcGain();
frame_stats_.aec_active = dsp_.EchoCancellationActive();
frame_stats_.ns_active =
dsp_.NoiseSuppressionActive() && !dsp_.BargeInProfile();
frame_stats_.barge_in_profile = dsp_.BargeInProfile();
portEXIT_CRITICAL(&metrics_lock_);
}
VoiceFrameStats VoiceFrontend::ConsumeFrameStats()
{
portENTER_CRITICAL(&metrics_lock_);
const VoiceFrameStats snapshot = frame_stats_;
const AudioPolicy policy = frame_stats_.policy;
frame_stats_ = VoiceFrameStats{};
frame_stats_.policy = policy;
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
void VoiceFrontend::Publish(const AppEvent& event)
{
IEventPublisher* publisher = publisher_.load();
if (publisher == nullptr || !publisher->Publish(event)) {
ESP_LOGE(kTag, "event publish failed type=%s",
ToString(event.type));
}
}
} // namespace borla