#pragma once #include "audio/pcm_rate_converter.h" #include "audio/voice_activity_detector.h" #include "audio/voice_dsp.h" #include "audio/voice_frame_processor.h" #include "audio/wake_word_detector.h" #include "core/psram_object.h" #include "ports/event_publisher.h" #include #include #include #include #include #include #include #include #include #include namespace borla { struct VoiceFrontendMetrics { uint32_t processed_frames = 0; uint32_t reference_frames = 0; uint32_t reference_drops = 0; uint32_t reference_trims = 0; uint32_t wake_detections = 0; uint32_t aec_reference_misses = 0; uint32_t uplink_suppressions = 0; uint32_t self_capture_suppressions = 0; uint32_t self_wake_suppressions = 0; uint32_t vad_stops = 0; uint32_t dsp_failures = 0; // Barge-in gate: frames whose energy the leak line explained as residual // echo and which were therefore withheld from the uplink. uint32_t residual_gated = 0; // Local barge-in candidates raised, and how they ended when the server // did not decide them: probe heard silence after the pause (local reject) // or nothing arrived at all (timeout). uint32_t barge_in_candidates = 0; uint32_t barge_in_local_rejects = 0; uint32_t barge_in_timeouts = 0; }; // Rolling per-frame measurements of the capture chain, accumulated by the // capture task and drained by the diagnostics worker. The capture task only // does arithmetic here: it must never write to the console, because a log line // takes longer than the 60 ms frame budget it is already struggling to meet. struct VoiceFrameStats { uint32_t frames = 0; uint32_t microphone_rms_sum = 0; uint32_t processed_rms_sum = 0; uint32_t reference_rms_sum = 0; uint32_t microphone_rms_peak = 0; uint32_t processed_rms_peak = 0; uint32_t reference_rms_peak = 0; uint32_t reference_present_frames = 0; uint32_t reference_active_frames = 0; uint32_t reference_depth_sum = 0; uint32_t reference_depth_peak = 0; uint32_t vad_speech_frames = 0; uint32_t period_us_max = 0; uint64_t period_us_sum = 0; float agc_gain = 0.0F; bool aec_active = false; bool ns_active = false; bool barge_in_profile = false; AudioPolicy policy = AudioPolicy::kOff; }; class VoiceFrontend final : public IVoiceFrameProcessor, public IPlaybackReferenceSink { public: bool Initialize(); void SetEventPublisher(IEventPublisher* publisher); void SetWakeWordEnabled(bool enabled); void ApplyPolicy(AudioPolicy policy) override; bool Process( AudioPolicy policy, const int16_t* input, size_t sample_count, int16_t* output, size_t output_capacity) override; void OnPlaybackReference( const int16_t* samples, size_t sample_count) override; void ResetPlaybackReference() override; // Frees the WakeNet instance. Only for entering BLE provisioning, where the // BT controller needs every spare byte and the wake word is unused. Normal // policy changes must never call this: reloading the model takes ~110 ms // under processor_mutex_, which stalls the capture task and breaks AEC // mic/reference lockstep. See EnsureWakeWordLoaded(). void ReleaseWakeWord(); VoiceFrontendMetrics Metrics() const; void LogMetrics(const char* reason) const; // Returns the frames measured since the previous call and clears the // accumulator. Called by the diagnostics worker, never by the capture task. VoiceFrameStats ConsumeFrameStats(); private: static constexpr size_t kFrameSamples = 960; static constexpr size_t kReferenceDepth = 4; // Occupancy the ring is trimmed back to on every push, NOT the array size. // // The echo of a reference frame reaches the microphone about 1.5 x 60 ms // frames after it is queued (the I2S TX DMA holds 6 x 360 samples @ 24 kHz // = 90 ms). So the frame the AEC needs was pushed 1-2 frames ago, i.e. the // ring should sit at an occupancy of 2-3. It used to be 8 deep with a // drop-the-oldest overflow rule, which is the worst possible combination: // once the capture task falls behind, the ring pins itself at full and // every reference handed to the AEC is ~7 frames (420 ms) older than the // echo it is supposed to cancel. The adaptive filter spans roughly // filter_length x chunk = 4 x 16 ms, so it simply stopped cancelling and // the speaker leaked into the uplink — the device then answered its own // TTS. Field metrics showed 25-30% of reference frames being dropped that // way, i.e. a permanently full ring. // // Trimming to the newest frames costs AEC continuity when capture lags, // but a correctly aligned reference with occasional gaps cancels; a // chronically skewed one cancels nothing. static constexpr size_t kReferenceMaxLeadFrames = 3; // A freshly refilled ring must hold this many frames before serving the // AEC: the echo of the first pushed frames is still inside the TX DMA and // has not reached the microphone, so serving early pairs the filter with // a reference the echo lags by more than its 64 ms span. Field data tied // ref_depth >= ~2 to erl 16-20 dB and depth < 1 to <= 8 dB. static constexpr size_t kReferencePrimeFrames = 2; static constexpr size_t kWakeAccumulatorSamples = 4096; static constexpr uint64_t kWakeCooldownMs = 2000; static constexpr uint32_t kReferenceActiveRms = 300; // Frames to keep ignoring the microphone after the playback reference goes // quiet. The reference is queued before the I2S write, so it leads the // sound leaving the speaker by the DMA depth (6 x 240 frames @ 24 kHz = // 60 ms) plus PA and decay. Four 60 ms frames covers that tail without // eating into the child's answer, which may start the instant the prompt // stops. The previous firmware used a blunt 800 ms drain, but it only did // so before a one-shot idle probe, never inside a listening turn. static constexpr uint8_t kSelfCaptureHangoverFrames = 4; // How stale the last playback frame may be before the speaker counts as // quiet. OnPlaybackReference() fires once per decoded frame, so two frame // periods bridges normal jitter without keeping the gate open into silence. static constexpr uint64_t kSpeakerActiveWindowUs = 120ULL * 1000ULL; // --- Barge-in residual gate + local candidate (kBargeInDuplex only) --- // // The AEC on this board converges to 17-20 dB ERL but starts every TTS // session at 8-10 dB, and those first seconds of residual (out_rms up to // several thousand) were being uploaded and transcribed by the server's // ASR as user speech — the device then answered itself. Energy alone // cannot separate residual from speech (they overlap in RMS), but residual // is the only signal that scales with the playback reference. The gate // therefore tracks leak = out_rms / ref_rms over frames it suppresses and // withholds any frame whose energy the leak line explains; a frame that // jumps clear of the line is treated as the child speaking, flows to the // server, and after kCandidateFrames of it a local kBargeInCandidate // reversibly pauses playback. The pause doubles as a probe: with the // speaker silent the echo source is gone, so persistent energy means a // real voice (now uploaded clean for the server to confirm) and instant // silence means a false trigger, answered by a local kBargeInRejected. // kBargeInRejected/kBargeInConfirmed guards in the reducer make a // duplicate or late local verdict a no-op. static constexpr float kLeakMargin = 1.5F; static constexpr float kLeakAlpha = 0.0625F; // EMA 1/16 // EMA clamp floor ≈ the leak at 16 dB ERL — the best this AEC sustains // in-session, so the line has no business going lower. The first cut used // 0.05 and the gate seeded there (see the warm-up note in the .cc), which // made every louder-than-floor residual frame read as speech: candidates // fired with leak=0.05 while ERL was 7 dB and each one paused playback for // ~half a second — heard in the field as stutter. static constexpr float kLeakMinimum = 0.15F; static constexpr float kLeakMaximum = 6.0F; // Seed the line no lower than this once warm-up completes. Starting high // is self-correcting (the EMA walks it down on gated frames); starting low // is a trap (frames above the line never train it). static constexpr float kLeakSeedMinimum = 0.5F; // Loud-reference frames observed before the seed is trusted: long enough // for the echo of the first frames to actually arrive at the microphone. static constexpr uint8_t kLeakWarmupFrames = 8; // ~0.5 s // Absolute floors sized against the barge-in profile's noise floor, which // is NOT the quiet-capture one: NS is off in this profile and the AGC // (gain up to 1.8) amplifies room noise to ~250-300 RMS. The first cut // used 200/250 and inter-sentence TTS gaps — reference near zero, AGC- // amplified noise just over the floor — fired candidates that paused // playback for half a second: the field symptom was intermittent playback // stutter. Child speech through this path measures ≥2000, so 500/400 // keeps an order-of-magnitude gap on both sides. static constexpr uint32_t kResidualFloorRms = 500; static constexpr uint32_t kProbeSpeechFloorRms = 400; static constexpr uint8_t kCandidateFrames = 3; // 180 ms of speech static constexpr uint8_t kProbeSilenceFrames = 5; // 300 ms of silence // Nothing from the server and no probe verdict after this long: resume // playback rather than leaving it paused forever. The reducer ignores the // resulting kBargeInRejected if the server decided meanwhile. static constexpr uint64_t kCandidateTimeoutUs = 1500ULL * 1000ULL; // After a candidate is locally rejected or times out, no new candidate // may be raised until this much time has passed AND at least one frame // fell back below the leak line. Without it, the same sustained energy // re-raised immediately: field log showed one TTS session paused four // times for ~4.8 s total (three 1.5 s timeouts back to back) while the // server kept streaming — the 48-slot queue overflowed and ~1.8 s of // audio was dropped mid-sentence. During the hold the uplink still // flows, so the server's own abort arbitration stays fully armed. static constexpr uint64_t kCandidateRearmUs = 2000ULL * 1000ULL; // No candidate may be raised during the first ~0.9 s of loud reference // in each duplex window: the AEC re-converges at every session start // (erl ~8-10 dB vs 17-25 dB converged) and its elevated residual crosses // a leak line trained on the converged state. Field log: four candidate // pauses in one run, ALL within 1 s of a session start, none // mid-sentence. Real speech in that window still uploads and the server // can abort; only the local reversible pause waits. static constexpr uint16_t kCandidateHoldoffFrames = 15; // A candidate additionally needs the over-line streak's PEAK to reach // this level. Peak, not consecutive level: real speech is an envelope — // syllable peaks with dips between them — and "N consecutive frames all // loud" is unsatisfiable for it (field: with a consecutive-1100 rule the // gate raised zero candidates for genuine interjections; duplex read as // dead). Residual is the opposite shape, a plateau. The level is // calibrated against double-talk reality: the AEC attenuates near-end // speech while the far end plays (field tap: the child's voice sat // entirely below the leak line during TTS), so voice peaks at the gate // land near 900-1500, not the 2000-9000 seen without playback. False // positives are held off by the trim-settle window + holdoff + rearm, // not by this line alone. static constexpr uint32_t kCandidateStrongRms = 900; // A reference-ring trim jumps the reference timeline by a whole frame // (60 ms > the 64 ms AEC filter span): the filter is misaligned until it // re-adapts, and its residual reads as room energy. No candidate until // the echo path has settled; uplink gating is untouched. static constexpr uint64_t kAlignmentSettleUs = 2000ULL * 1000ULL; // Segment-level uplink gating. Per-frame RMS censorship shreds speech: // only the frames over the leak line survived, so the server's VAD/ASR // received disconnected 60 ms shards and its whole two-phase arbitration // starved (field tap: the child's voice was ENTIRELY absent from the // uplink during TTS). Once a streak of kUplinkPassStreak over-line // frames shows plausible voice, pass EVERYTHING for the next // kUplinkPassWindowUs — envelope dips included — and keep extending // while frames stay over the line. Suppression resumes when the window // lapses, so the steady-state uplink stays as silent as before; the // cost is a sub-second residual tail after a burst that opened a window. static constexpr uint64_t kUplinkPassWindowUs = 800ULL * 1000ULL; static constexpr uint8_t kUplinkPassStreak = 2; // The wake accumulator (8 KB) and the AEC reference ring (15 KB) used to // sit in the CompositionRoot's .bss, i.e. 23 KB of internal RAM held for // the whole uptime. Internal RAM is the scarce pool on this board: the BT // controller needs ~53 KB and the WiFi driver ~36 KB, and BLE provisioning // has to hold both at once when it re-attaches WiFi to test credentials. // Both buffers are only touched by the capture and playback tasks, whose // stacks already live in PSRAM, so moving them there costs nothing that // matters and buys back the headroom. struct ScratchBuffers { std::array wake_accumulator{}; std::array< std::array, kReferenceDepth> reference_ring{}; // Post-AEC, pre-AGC copy of the frame for WakeNet. The AGC pumps // hard during music+speech double-talk (gain swinging 0.9-1.8 inside // one phrase) and a phrase chopped by gain steps is what WakeNet // misses; idle detection feeds the raw microphone and never sees // this, which is why it stays sensitive. std::array wake_tap{}; }; bool WakeRequired(AudioPolicy policy) const; bool AecRequired(AudioPolicy policy) const; // Loads the WakeNet model at most once per boot. Deliberately lazy rather // than eager: BLE provisioning runs with AudioPolicy::kOff from boot, so // the model never loads there and the BT controller keeps the internal RAM // that esp_wifi_deinit() freed for it. bool EnsureWakeWordLoaded(); void FeedWakeWord( const int16_t* samples, size_t sample_count); bool PopReference(int16_t* output); void ClearReference(); // Runs the residual gate and the local candidate state machine for one // kBargeInDuplex frame. Returns true when the frame must be withheld from // the uplink. Called with processor_mutex_ held. bool UpdateBargeInGate( uint32_t out_rms, uint32_t reference_rms, bool has_reference, bool speaker_active, uint64_t now_us); void ResolveCandidateLocked( AppEventType verdict, const char* reason, uint64_t now_us); static uint32_t FrameRms( const int16_t* samples, size_t sample_count); void AccumulateFrameStats( AudioPolicy policy, uint32_t microphone_rms, uint32_t processed_rms, uint32_t reference_rms, bool has_reference); void Publish(const AppEvent& event); static void WakeScanTaskEntry(void* context); [[noreturn]] void RunWakeScan(); void QueueWakeAudio(const int16_t* samples); std::atomic publisher_{nullptr}; mutable std::mutex processor_mutex_; AudioPolicy policy_ = AudioPolicy::kOff; WakeWordDetector wake_word_; VoiceDsp dsp_; VoiceActivityDetector vad_; std::unique_ptr> buffers_; // --- Wake-word scan task (core 1) --- // On paper AEC (10-15 ms avg) plus WakeNet (~14 ms) fitted the 60 ms // capture budget; in the field the worst cases stacked to 59-84 ms of // process time (period_avg 66-70 ms): the microphone backlogged, the // reference ring pinned at its trim ceiling (ref_trims 4-9/window) and // the echo alignment wobbled — audible as residual ticks in the uplink. // Detection therefore runs on its own core-1 task fed through this // queue; the capture task only copies one frame and moves on. // wake_accumulator_/cooldown are owned by the scan task; wake_mutex_ // serializes Detect against model load/release. static constexpr size_t kWakeQueueFrames = 6; static constexpr uint32_t kWakeScanStackBytes = 12 * 1024; QueueHandle_t wake_queue_ = nullptr; TaskHandle_t wake_task_ = nullptr; std::mutex wake_mutex_; std::atomic wake_reset_pending_{false}; size_t wake_accumulator_count_ = 0; uint64_t wake_cooldown_until_ms_ = 0; uint8_t self_capture_hangover_ = 0; // Barge-in gate state. All owned by the capture task under // processor_mutex_. leak_ratio_ survives policy changes on purpose: the // echo path barely moves between TTS sessions, so the next session starts // with a trained gate instead of re-learning through a dirty window. float leak_ratio_ = 0.0F; bool leak_seeded_ = false; uint8_t leak_warmup_frames_ = 0; // The last two reference RMS values. Residual lags the reference by the // TX DMA depth (~1.5 frames), so a frame's echo is explained by the // loudest of the last three reference frames, never by the instantaneous // one alone. uint32_t previous_reference_rms_[2] = {0, 0}; bool candidate_active_ = false; uint64_t candidate_rearm_until_us_ = 0; bool candidate_needs_quiet_ = false; uint16_t window_ref_active_frames_ = 0; uint8_t consecutive_speech_frames_ = 0; uint32_t streak_peak_rms_ = 0; uint64_t uplink_pass_until_us_ = 0; std::atomic alignment_settle_until_us_{0}; uint8_t probe_silence_frames_ = 0; uint64_t candidate_deadline_us_ = 0; // Timestamp of the most recent frame handed to the speaker. Written by the // playback task, read by the capture task. // // This replaced "is the popped reference frame loud?" as the self-playback // test. That question is unanswerable when the reference ring is empty — // and it routinely is, because the ring gets cleared on every policy change // and playback session start, and trimmed on every push. Field log showed // ref_present=0 for the whole wake-acknowledgement window, so the guard // never armed and the VAD treated the device's own "我在" as the child // answering: speech_started 348 ms into the prompt, speech_ended 568 ms // after it stopped, turn closed 1.4 s after the wake word. The child had to // speak instantly or say the wake word again. std::atomic last_playback_frame_us_{0}; // Each ring slot is a 1920-byte frame. Copying that under a spinlock kept // interrupts disabled for tens of microseconds on every capture and // playback frame; both callers are tasks, so a mutex is the right lock. mutable std::mutex reference_mutex_; size_t reference_read_ = 0; size_t reference_write_ = 0; size_t reference_count_ = 0; bool reference_primed_ = false; //Pcm24kTo16kConverter reference_converter_; Pcm48kTo16kConverter reference_converter_; mutable portMUX_TYPE metrics_lock_ = portMUX_INITIALIZER_UNLOCKED; VoiceFrontendMetrics metrics_{}; VoiceFrameStats frame_stats_{}; uint64_t last_frame_us_ = 0; bool initialized_ = false; bool wake_word_enabled_ = true; }; } // namespace borla