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

19
main/audio/audio_input.h Normal file
View File

@@ -0,0 +1,19 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class IAudioInput {
public:
virtual ~IAudioInput() = default;
virtual bool Read(
int16_t* samples,
size_t sample_count,
uint32_t timeout_ms) = 0;
virtual uint32_t InputSampleRate() const = 0;
};
} // namespace borla

20
main/audio/audio_output.h Normal file
View File

@@ -0,0 +1,20 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class IAudioOutput {
public:
virtual ~IAudioOutput() = default;
virtual bool Initialize() = 0;
virtual void Shutdown() = 0;
virtual bool Write(const int16_t* samples, size_t sample_count) = 0;
virtual void SetVolume(uint8_t volume_percent) = 0;
virtual uint8_t VolumePercent() const = 0;
virtual uint32_t SampleRate() const = 0;
};
} // namespace borla

View File

@@ -0,0 +1,483 @@
#include "audio/capture_pipeline.h"
#include "diagnostics/audio_tap.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/idf_additions.h>
#include <algorithm>
#include <cstring>
#include <cstdint>
namespace borla {
namespace {
constexpr const char* kTag = "CapturePipeline2";
constexpr uint32_t kOpusBitrate = 24000;
} // namespace
CapturePipeline::CapturePipeline(IAudioInput& input)
: input_(input)
{
}
CapturePipeline::~CapturePipeline()
{
Stop();
heap_caps_free(hardware_pcm_);
heap_caps_free(raw_protocol_pcm_);
heap_caps_free(processed_protocol_pcm_);
heap_caps_free(encoded_);
}
bool CapturePipeline::Initialize()
{
if (initialized_) {
return true;
}
if (input_.InputSampleRate() != kHardwareSampleRate
|| !encoder_.Initialize(kProtocolSampleRate, 1, kOpusBitrate)) {
ESP_LOGE(kTag, "input rate/encoder initialization failed");
return false;
}
// Internal RAM: these four are touched several times per frame by the
// resampler, the AEC and the encoder, and together they are only ~7 KB.
// The bulk storage that genuinely belongs in PSRAM is encode_slots_ below,
// which is written and read once per frame as a straight memcpy.
hardware_pcm_ = static_cast<int16_t*>(
//heap_caps_calloc(Pcm24kTo16kConverter::kInputSamples, sizeof(int16_t),
heap_caps_calloc(Pcm48kTo16kConverter::kInputSamples, sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));//2026-9-3 ckkj debug :wifi start fail
//MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
raw_protocol_pcm_ = static_cast<int16_t*>(
//heap_caps_calloc(Pcm24kTo16kConverter::kOutputSamples, sizeof(int16_t),
//MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
heap_caps_calloc(Pcm48kTo16kConverter::kOutputSamples, sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));//2026-9-3 ckkj debug :wifi start fail
processed_protocol_pcm_ = static_cast<int16_t*>(
//heap_caps_calloc(Pcm24kTo16kConverter::kOutputSamples, sizeof(int16_t),
heap_caps_calloc(Pcm48kTo16kConverter::kOutputSamples, sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
encoded_ = static_cast<uint8_t*>(
heap_caps_calloc(kBinaryAudioMaximumUplinkOpusBytes, sizeof(uint8_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
encode_slots_ = static_cast<int16_t*>(
//heap_caps_calloc(kEncodeSlots * Pcm24kTo16kConverter::kOutputSamples,
heap_caps_calloc(kEncodeSlots * Pcm48kTo16kConverter::kOutputSamples,
sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
stopped_signal_ = xSemaphoreCreateBinaryStatic(&stopped_signal_storage_);
encoder_stopped_signal_ =
xSemaphoreCreateBinaryStatic(&encoder_stopped_signal_storage_);
encode_ready_ = xQueueCreate(kEncodeSlots, sizeof(uint8_t));
encode_free_ = xQueueCreate(kEncodeSlots, sizeof(uint8_t));
if (hardware_pcm_ == nullptr || raw_protocol_pcm_ == nullptr
|| processed_protocol_pcm_ == nullptr
|| encoded_ == nullptr || stopped_signal_ == nullptr
|| encode_slots_ == nullptr || encode_ready_ == nullptr
|| encode_free_ == nullptr || encoder_stopped_signal_ == nullptr) {
ESP_LOGE(kTag, "capture buffers/signal allocation failed");
return false;
}
initialized_ = true;
ESP_LOGI(kTag,
"initialized hardware=48k protocol=16k frame=60ms bitrate=%lu",
static_cast<unsigned long>(kOpusBitrate));
return true;
}
// bool CapturePipeline::Start()
// {
// if (running_.load()) {
// return true;
// }
// if (!initialized_ && !Initialize()) {
// return false;
// }
// xSemaphoreTake(stopped_signal_, 0);
// xSemaphoreTake(encoder_stopped_signal_, 0);
// xQueueReset(encode_ready_);
// xQueueReset(encode_free_);
// for (uint8_t slot = 0; slot < kEncodeSlots; ++slot) {
// xQueueSend(encode_free_, &slot, 0);
// }
// running_.store(true);
// // Plain xTaskCreate: the stack comes from the internal heap and goes back
// // to it on Stop(), which is what BLE provisioning relies on when it
// // releases the audio engine to make room for the WiFi driver.
// const BaseType_t result
// = xTaskCreatePinnedToCore(&CapturePipeline::TaskEntry,
// "capture2", task_stack_budget::kCaptureBytes, this,
// task_priority::kCaptureLoop, &task_, 0);
// if (result != pdPASS) {
// running_.store(false);
// return false;
// }
// return true;
// }
bool CapturePipeline::Start()
{
if (running_.load()) {
return true;
}
if (!initialized_ && !Initialize()) {
return false;
}
xSemaphoreTake(stopped_signal_, 0);
xSemaphoreTake(encoder_stopped_signal_, 0);
xQueueReset(encode_ready_);
xQueueReset(encode_free_);
for (uint8_t slot = 0; slot < kEncodeSlots; ++slot) {
xQueueSend(encode_free_, &slot, 0);
}
running_.store(true);
// Plain xTaskCreate: the stack comes from the internal heap and goes back
// to it on Stop(), which is what BLE provisioning relies on when it
// releases the audio engine to make room for the WiFi driver.
const BaseType_t result
= xTaskCreatePinnedToCore(&CapturePipeline::TaskEntry,
"capture2", task_stack_budget::kCaptureBytes,
this,
task_priority::kCaptureLoop, &task_, 0);
if (result != pdPASS) {
running_.store(false);
task_ = nullptr;
ESP_LOGE(kTag, "capture task creation failed");
return false;
}
// Core 1: capture is pinned to core 0, so this is real parallelism.
const BaseType_t encoder_result
= xTaskCreatePinnedToCoreWithCaps(&CapturePipeline::EncoderTaskEntry,
"capture_enc2", task_stack_budget::kCaptureEncoderBytes, this,
task_priority::kAudioCodec, &encoder_task_, 1,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (encoder_result != pdPASS) {
running_.store(false);
encoder_task_ = nullptr;
// The capture task above was already created; without this it would
// park itself in vTaskSuspend forever and strand its internal-RAM
// stack — on the pool this whole exercise is trying to protect.
if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "capture task stop timed out");
}
vTaskDelete(task_);
task_ = nullptr;
ESP_LOGE(kTag, "capture encoder task creation failed");
return false;
}
ESP_LOGI(kTag, "task started stack_bytes=%u memory=internal prio=%u",
static_cast<unsigned>(task_stack_budget::kCaptureBytes),
static_cast<unsigned>(task_priority::kCaptureLoop));
return true;
}
void CapturePipeline::Stop()
{
if (!running_.exchange(false)) {
return;
}
policy_.store(AudioPolicy::kOff);
if (task_ != nullptr) {
if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "capture task stop timed out");
}
vTaskDelete(task_);
task_ = nullptr;
}
if (encoder_task_ != nullptr) {
if (xSemaphoreTake(
encoder_stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "capture encoder task stop timed out");
}
vTaskDeleteWithCaps(encoder_task_);
encoder_task_ = nullptr;
}
IEncodedAudioSink* sink = sink_.load();
if (sink != nullptr) {
sink->FlushEncodedAudio();
}
}
void CapturePipeline::SetSink(IEncodedAudioSink* sink) { sink_.store(sink); }
void CapturePipeline::SetAudioTap(AudioTap* tap)
{
audio_tap_.store(tap, std::memory_order_release);
}
void CapturePipeline::SetProcessor(IVoiceFrameProcessor* processor)
{
processor_.store(processor);
}
void CapturePipeline::ApplyPolicy(AudioPolicy policy)
{
const AudioPolicy previous = policy_.exchange(policy);
IVoiceFrameProcessor* processor = processor_.load();
if (processor != nullptr) {
processor->ApplyPolicy(policy);
}
if (CaptureEnabled(previous) && !CaptureEnabled(policy)) {
// The encoder state must be reset by the encoder task itself, not
// here: this runs on the application task while RunEncoder may be in
// the middle of encoder_.Encode() on core 1, and libopus state is not
// reentrant — a concurrent Reset() tears the state mid-frame. Every
// conversation turn ends by leaving a capture policy, so the race was
// armed constantly.
encoder_reset_pending_.store(true);
IEncodedAudioSink* sink = sink_.load();
if (sink != nullptr) {
sink->FlushEncodedAudio();
}
}
// Debug: the engine's one-line summary already reports every change.
ESP_LOGD(kTag, "policy=%s capture=%d", ToString(policy),
CaptureEnabled(policy) ? 1 : 0);
}
CaptureMetrics CapturePipeline::Metrics() const
{
portENTER_CRITICAL(&metrics_lock_);
const CaptureMetrics snapshot = metrics_;
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
void CapturePipeline::TaskEntry(void* context)
{
static_cast<CapturePipeline*>(context)->Run();
}
[[noreturn]] void CapturePipeline::Run()
{
ESP_LOGI(kTag, "capture owner task started");
while (running_.load()) {
const AudioPolicy policy = policy_.load();
if (!InputEnabled(policy)) {
vTaskDelay(pdMS_TO_TICKS(20));
continue;
}
const uint64_t read_start_us =
static_cast<uint64_t>(esp_timer_get_time());
if (!input_.Read(
//hardware_pcm_, Pcm24kTo16kConverter::kInputSamples, 100)) {
hardware_pcm_, Pcm48kTo16kConverter::kInputSamples, 100)) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.read_failures++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
const uint64_t convert_start_us =
static_cast<uint64_t>(esp_timer_get_time());
portENTER_CRITICAL(&metrics_lock_);
metrics_.frames_read++;
portEXIT_CRITICAL(&metrics_lock_);
if (!converter_.Convert(hardware_pcm_,
// Pcm24kTo16kConverter::kInputSamples, raw_protocol_pcm_,
// Pcm24kTo16kConverter::kOutputSamples)) {
Pcm48kTo16kConverter::kInputSamples, raw_protocol_pcm_,
Pcm48kTo16kConverter::kOutputSamples)) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.encode_failures++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
const uint64_t process_start_us =
static_cast<uint64_t>(esp_timer_get_time());
IVoiceFrameProcessor* processor = processor_.load();
const bool frame_passed = processor == nullptr
|| processor->Process(policy, raw_protocol_pcm_,
//Pcm24kTo16kConverter::kOutputSamples,
Pcm48kTo16kConverter::kOutputSamples,
processed_protocol_pcm_,
//Pcm24kTo16kConverter::kOutputSamples);
Pcm48kTo16kConverter::kOutputSamples);
const int16_t* upload_pcm = processor != nullptr
? processed_protocol_pcm_
: raw_protocol_pcm_;
// Server's-ear channel: exactly the PCM that goes to the encoder, or
// silence when this frame is suppressed/not uplinked — so listening
// to uplink.wav answers "what did the server hear at second N".
if (AudioTap* tap =
audio_tap_.load(std::memory_order_acquire)) {
const bool uplinked = frame_passed && CaptureEnabled(policy);
tap->PushUplink(uplinked ? upload_pcm : nullptr,
//Pcm24kTo16kConverter::kOutputSamples);
Pcm48kTo16kConverter::kOutputSamples);
}
if (!frame_passed) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.encode_failures++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
if (!CaptureEnabled(policy)) {
continue;
}
const uint64_t handoff_start_us =
static_cast<uint64_t>(esp_timer_get_time());
// Hand the frame to the encoder task instead of encoding here. A full
// free queue means the encoder is behind; dropping the newest frame is
// better than stalling capture, because a stalled capture loses the
// microphone stream itself and with it the AEC alignment.
uint8_t slot = 0;
if (xQueueReceive(encode_free_, &slot, 0) != pdTRUE) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.backpressure_drops++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
std::memcpy(
//encode_slots_ + slot * Pcm24kTo16kConverter::kOutputSamples,
encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples,
upload_pcm,
//Pcm24kTo16kConverter::kOutputSamples * sizeof(int16_t));
Pcm48kTo16kConverter::kOutputSamples * sizeof(int16_t));
if (xQueueSend(encode_ready_, &slot, 0) != pdTRUE) {
xQueueSend(encode_free_, &slot, 0);
portENTER_CRITICAL(&metrics_lock_);
metrics_.backpressure_drops++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
const uint64_t handoff_end_us =
static_cast<uint64_t>(esp_timer_get_time());
RecordTimings(
static_cast<uint32_t>(convert_start_us - read_start_us),
static_cast<uint32_t>(process_start_us - convert_start_us),
static_cast<uint32_t>(handoff_start_us - process_start_us),
0,
static_cast<uint32_t>(handoff_end_us - handoff_start_us));
}
xSemaphoreGive(stopped_signal_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void CapturePipeline::EncoderTaskEntry(void* context)
{
static_cast<CapturePipeline*>(context)->RunEncoder();
}
[[noreturn]] void CapturePipeline::RunEncoder()
{
ESP_LOGI(kTag, "capture encoder task started stack_bytes=%u memory=PSRAM",
static_cast<unsigned>(task_stack_budget::kCaptureEncoderBytes));
while (running_.load()) {
if (encoder_reset_pending_.exchange(false)) {
encoder_.Reset();
}
uint8_t slot = 0;
if (xQueueReceive(encode_ready_, &slot, pdMS_TO_TICKS(100))
!= pdTRUE) {
continue;
}
const int16_t* pcm =
//encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples;
encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples;
const uint64_t encode_start_us =
static_cast<uint64_t>(esp_timer_get_time());
size_t encoded_size = 0;
const bool encoded = encoder_.Encode(pcm,
//Pcm24kTo16kConverter::kOutputSamples, encoded_,
Pcm48kTo16kConverter::kOutputSamples, encoded_,
kBinaryAudioMaximumUplinkOpusBytes, &encoded_size);
const uint64_t encode_end_us =
static_cast<uint64_t>(esp_timer_get_time());
bool sent = false;
if (encoded) {
IEncodedAudioSink* sink = sink_.load();
sent = sink != nullptr
&& sink->SubmitEncodedAudio(encoded_, encoded_size);
}
const uint64_t submit_end_us =
static_cast<uint64_t>(esp_timer_get_time());
xQueueSend(encode_free_, &slot, 0);
portENTER_CRITICAL(&metrics_lock_);
if (!encoded) {
metrics_.encode_failures++;
} else {
metrics_.frames_encoded++;
metrics_.maximum_encoded_bytes
= std::max(metrics_.maximum_encoded_bytes,
static_cast<uint32_t>(encoded_size));
if (sent) {
metrics_.frames_sent++;
} else {
metrics_.backpressure_drops++;
}
}
timings_.encode_us += encode_end_us - encode_start_us;
timings_.encode_us_max = std::max(timings_.encode_us_max,
static_cast<uint32_t>(encode_end_us - encode_start_us));
timings_.submit_us += submit_end_us - encode_end_us;
portEXIT_CRITICAL(&metrics_lock_);
// One tick between frames so IDLE1 gets runtime while the slot queue
// is backlogged. A single opus_encode() call cannot yield internally,
// and when frames queue up the xQueueReceive above returns instantly,
// so without this the loop monopolises core 1 for as long as the
// backlog lasts and the task watchdog fires — every backtrace it
// printed ended inside silk_encode. Costs 1 ms per 60 ms frame.
vTaskDelay(1);
}
xSemaphoreGive(encoder_stopped_signal_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void CapturePipeline::RecordTimings(uint32_t read_us, uint32_t convert_us,
uint32_t process_us, uint32_t encode_us, uint32_t submit_us)
{
portENTER_CRITICAL(&metrics_lock_);
timings_.frames++;
timings_.read_us += read_us;
timings_.convert_us += convert_us;
timings_.process_us += process_us;
timings_.encode_us += encode_us;
timings_.submit_us += submit_us;
timings_.read_us_max = std::max(timings_.read_us_max, read_us);
timings_.process_us_max = std::max(timings_.process_us_max, process_us);
timings_.encode_us_max = std::max(timings_.encode_us_max, encode_us);
timings_.submit_us_max = std::max(timings_.submit_us_max, submit_us);
portEXIT_CRITICAL(&metrics_lock_);
}
CaptureTimings CapturePipeline::ConsumeTimings()
{
portENTER_CRITICAL(&metrics_lock_);
const CaptureTimings snapshot = timings_;
timings_ = CaptureTimings{};
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
bool CapturePipeline::CaptureEnabled(AudioPolicy policy) const
{
return policy == AudioPolicy::kConversationCapture
|| policy == AudioPolicy::kBargeInDuplex
|| policy == AudioPolicy::kCallDuplex;
}
bool CapturePipeline::InputEnabled(AudioPolicy policy) const
{
return policy == AudioPolicy::kWakeWordOnly ||
policy == AudioPolicy::kWakeWordDuplex ||
CaptureEnabled(policy);
}
} // namespace borla

View File

@@ -0,0 +1,133 @@
#pragma once
#include "audio/audio_input.h"
#include "audio/encoded_audio_sink.h"
#include "audio/opus_frame_encoder.h"
#include "audio/pcm_rate_converter.h"
#include "audio/voice_frame_processor.h"
#include "core/runtime_state.h"
#include "core/task_stack_budget.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
namespace borla {
class AudioTap;
}
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
struct CaptureMetrics {
uint32_t frames_read = 0;
uint32_t frames_encoded = 0;
uint32_t frames_sent = 0;
uint32_t read_failures = 0;
uint32_t encode_failures = 0;
uint32_t backpressure_drops = 0;
uint32_t maximum_encoded_bytes = 0;
};
// Per-stage cost of the capture loop, accumulated by the capture task and
// drained by diagnostics. Added because the loop was measured at 94.6 ms per
// frame against a 60 ms budget while duplex was active — over budget means the
// I2S RX DMA overflows, frames are lost, and the AEC's microphone/reference
// alignment drifts, which is what capped echo cancellation at 13 dB and let the
// device's own TTS reach the server's ASR. Which stage is responsible was pure
// guesswork without these numbers.
struct CaptureTimings {
uint32_t frames = 0;
uint64_t read_us = 0;
uint64_t convert_us = 0;
uint64_t process_us = 0;
uint64_t encode_us = 0;
uint64_t submit_us = 0;
uint32_t read_us_max = 0;
uint32_t process_us_max = 0;
uint32_t encode_us_max = 0;
uint32_t submit_us_max = 0;
};
class CapturePipeline final {
public:
static constexpr uint32_t kHardwareSampleRate = 48000;//24000;
static constexpr uint32_t kProtocolSampleRate = 16000;
static constexpr uint32_t kFrameDurationMs = 60;
explicit CapturePipeline(IAudioInput& input);
~CapturePipeline();
bool Initialize();
bool Start();
void Stop();
void SetSink(IEncodedAudioSink* sink);
void SetProcessor(IVoiceFrameProcessor* processor);
// Debug recorder for the "what does the server actually hear" channel.
void SetAudioTap(AudioTap* tap);
void ApplyPolicy(AudioPolicy policy);
CaptureMetrics Metrics() const;
CaptureTimings ConsumeTimings();
private:
// Opus encoding costs ~42 ms per 60 ms frame on this board (measured), and
// it used to run inline on the capture task together with the ~56 ms of
// AEC + wake-word work. Total ~104 ms against a 60 ms budget meant the I2S
// RX DMA overflowed every frame: audio was lost, the AEC's microphone and
// reference streams drifted apart, echo cancellation collapsed to ~9 dB and
// the device's own TTS reached the server's ASR — it answered itself.
//
// The previous firmware never had this problem because encoding lived on a
// separate task (audio_service.cc "Task 3: Opus 编码/解码"). Same split
// here, pinned to the other core so it genuinely runs in parallel with
// capture rather than merely interleaving with it.
static constexpr size_t kEncodeSlots = 4;
static void TaskEntry(void* context);
[[noreturn]] void Run();
static void EncoderTaskEntry(void* context);
[[noreturn]] void RunEncoder();
void RecordTimings(uint32_t read_us, uint32_t convert_us,
uint32_t process_us, uint32_t encode_us, uint32_t submit_us);
bool CaptureEnabled(AudioPolicy policy) const;
bool InputEnabled(AudioPolicy policy) const;
IAudioInput& input_;
std::atomic<IEncodedAudioSink*> sink_ { nullptr };
std::atomic<IVoiceFrameProcessor*> processor_ { nullptr };
std::atomic<AudioTap*> audio_tap_ { nullptr };
std::atomic<AudioPolicy> policy_ { AudioPolicy::kOff };
OpusFrameEncoder encoder_;
//Pcm24kTo16kConverter converter_;
Pcm48kTo16kConverter converter_;
// Set by ApplyPolicy when leaving a capture policy; consumed by the
// encoder task, which is the only task allowed to touch encoder_ state.
std::atomic<bool> encoder_reset_pending_ { false };
int16_t* encode_slots_ = nullptr;
QueueHandle_t encode_ready_ = nullptr;
QueueHandle_t encode_free_ = nullptr;
TaskHandle_t encoder_task_ = nullptr;
SemaphoreHandle_t encoder_stopped_signal_ = nullptr;
StaticSemaphore_t encoder_stopped_signal_storage_ {};
int16_t* hardware_pcm_ = nullptr;
int16_t* raw_protocol_pcm_ = nullptr;
int16_t* processed_protocol_pcm_ = nullptr;
uint8_t* encoded_ = nullptr;
mutable portMUX_TYPE metrics_lock_ = portMUX_INITIALIZER_UNLOCKED;
CaptureMetrics metrics_ {};
CaptureTimings timings_ {};
TaskHandle_t task_ = nullptr;
SemaphoreHandle_t stopped_signal_ = nullptr;
StaticSemaphore_t stopped_signal_storage_ {};
bool initialized_ = false;
std::atomic<bool> running_ { false };
};
} // namespace borla

View File

@@ -0,0 +1,74 @@
#pragma once
#include "protocol/binary_audio_protocol.h"
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
namespace borla {
// Holds the small number of downlink frames that can arrive after the
// protocol has announced a TTS session but before Application has applied the
// corresponding BeginRemotePlayback effect. The object is allocated in
// PSRAM by EspAudioEngine so the fixed frame storage does not consume
// internal DRAM.
class DownlinkPrerollBuffer final {
public:
static constexpr size_t kCapacity = 8;
bool Push(
uint32_t session_id,
const uint8_t* data,
size_t size)
{
if (session_id == 0 || data == nullptr || size == 0 ||
size > kBinaryAudioMaximumOpusBytes) {
return false;
}
if (session_id_ != session_id) {
Reset(session_id);
}
if (frame_count_ >= frames_.size()) {
return false;
}
Frame& frame = frames_[frame_count_++];
frame.size = static_cast<uint16_t>(size);
std::memcpy(frame.payload.data(), data, size);
return true;
}
void Reset(uint32_t session_id = 0)
{
session_id_ = session_id;
frame_count_ = 0;
}
uint32_t session_id() const { return session_id_; }
size_t frame_count() const { return frame_count_; }
const uint8_t* FrameData(size_t index) const
{
return index < frame_count_
? frames_[index].payload.data()
: nullptr;
}
size_t FrameSize(size_t index) const
{
return index < frame_count_ ? frames_[index].size : 0;
}
private:
struct Frame {
uint16_t size = 0;
std::array<uint8_t, kBinaryAudioMaximumOpusBytes> payload{};
};
std::array<Frame, kCapacity> frames_{};
uint32_t session_id_ = 0;
size_t frame_count_ = 0;
};
} // namespace borla

View File

@@ -0,0 +1,143 @@
#include "audio/embedded_prompt_catalog.h"
#include "audio_prompts_data.h"
#include <cstring>
namespace borla {
namespace {
const char* AssetGroup(LocalPrompt prompt)
{
switch (prompt) {
case LocalPrompt::kActivationDevice:
return "activation_device";
case LocalPrompt::kDeviceAlreadyBound:
return "device_already_bound";
case LocalPrompt::kServerError:
return "server_error";
case LocalPrompt::kAlarmWake:
return "alarm_wake";
case LocalPrompt::kAlarmSet:
return "alarm_set";
case LocalPrompt::kNoNetwork:
return "no_network";
case LocalPrompt::kProvisioning:
return "wifi_config";
case LocalPrompt::kWakeResponse:
return "wake_response";
case LocalPrompt::kStoryExpired:
return "story_expired";
case LocalPrompt::kIdleCheck:
return "idle_check";
case LocalPrompt::kIdleGoodbye:
return "idle_goodbye";
case LocalPrompt::kSnoreLight:
return "snore_light";
case LocalPrompt::kWifiSuccess:
return "wifi_success";
case LocalPrompt::kWelcome:
return "welcome";
case LocalPrompt::kShutdown:
return "shutdown";
case LocalPrompt::kBoot:
return "boot";
case LocalPrompt::kError:
return "error";
case LocalPrompt::kLowBattery20:
return "low_battery_20";
case LocalPrompt::kLowBattery10:
return "low_battery_10";
case LocalPrompt::kNet4gBootOn:
return "net4g_boot_on";
case LocalPrompt::kNet4gOff:
return "net4g_off";
case LocalPrompt::kNet4gOn:
return "net4g_on";
case LocalPrompt::kNet4gNoWifi:
return "net4g_no_wifi";
case LocalPrompt::kCallWait:
// Explicit compatibility fallbacks until dedicated call assets exist.
return "wake_response";
case LocalPrompt::kCallRing:
return "alarm_wake";
case LocalPrompt::kCallConnected:
return "wifi_success";
case LocalPrompt::kCallEnded:
return "error";
case LocalPrompt::kDigit0:
return "digit_0";
case LocalPrompt::kDigit1:
return "digit_1";
case LocalPrompt::kDigit2:
return "digit_2";
case LocalPrompt::kDigit3:
return "digit_3";
case LocalPrompt::kDigit4:
return "digit_4";
case LocalPrompt::kDigit5:
return "digit_5";
case LocalPrompt::kDigit6:
return "digit_6";
case LocalPrompt::kDigit7:
return "digit_7";
case LocalPrompt::kDigit8:
return "digit_8";
case LocalPrompt::kDigit9:
return "digit_9";
}
return "";
}
} // namespace
size_t EmbeddedPromptCatalog::Count(LocalPrompt prompt)
{
const char* group = AssetGroup(prompt);
size_t count = 0;
for (size_t index = 0;
index < generated_prompts::kPromptBlobCount;
++index) {
if (std::strcmp(
generated_prompts::kPromptBlobs[index].group,
group) == 0) {
count++;
}
}
return count;
}
bool EmbeddedPromptCatalog::Select(
LocalPrompt prompt,
uint32_t selector,
EmbeddedPromptBlob* blob)
{
if (blob == nullptr) {
return false;
}
const char* group = AssetGroup(prompt);
const size_t count = Count(prompt);
if (count == 0) {
return false;
}
size_t desired = selector % count;
for (size_t index = 0;
index < generated_prompts::kPromptBlobCount;
++index) {
const auto& candidate =
generated_prompts::kPromptBlobs[index];
if (std::strcmp(candidate.group, group) != 0) {
continue;
}
if (desired-- == 0) {
blob->data = candidate.data;
blob->size = candidate.size;
blob->filename = candidate.filename;
return true;
}
}
return false;
}
} // namespace borla

View File

@@ -0,0 +1,25 @@
#pragma once
#include "core/playback_types.h"
#include <cstddef>
#include <cstdint>
namespace borla {
struct EmbeddedPromptBlob {
const uint8_t* data = nullptr;
size_t size = 0;
const char* filename = nullptr;
};
class EmbeddedPromptCatalog final {
public:
static bool Select(
LocalPrompt prompt,
uint32_t selector,
EmbeddedPromptBlob* blob);
static size_t Count(LocalPrompt prompt);
};
} // namespace borla

View File

@@ -0,0 +1,17 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class IEncodedAudioSink {
public:
virtual ~IEncodedAudioSink() = default;
virtual bool SubmitEncodedAudio(
const uint8_t* data,
size_t size) = 0;
virtual void FlushEncodedAudio() = 0;
};
} // namespace borla

View File

@@ -0,0 +1,588 @@
#include "audio/local_prompt_player.h"
#include "audio/packed_opus_reader.h"
#include "core/task_stack_budget.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_random.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/idf_additions.h>
#include <freertos/task.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <new>
namespace borla {
namespace {
constexpr const char* kTag = "LocalPromptPlayer2";
constexpr float kPi = 3.14159265358979323846f;
constexpr uint32_t kQueueBackpressureTimeoutMs = 1500;
constexpr uint16_t kActivationIntroGapMs = 1000;
constexpr uint16_t kActivationDigitGapMs = 150;
constexpr std::array<
int16_t,
PlaybackPipeline::kSamplesPerFrame> kSilence{};
struct ToneSegment {
uint16_t frequency_hz;
uint16_t duration_ms;
uint8_t amplitude_percent;
};
constexpr std::array<ToneSegment, 2> kBootFallback = {{
{523, 150, 24},
{659, 200, 30},
}};
constexpr std::array<ToneSegment, 3> kProvisioningFallback = {{
{440, 100, 24},
{554, 100, 26},
{659, 150, 30},
}};
constexpr std::array<ToneSegment, 3> kErrorFallback = {{
{220, 200, 28},
{0, 80, 0},
{220, 200, 28},
}};
constexpr std::array<ToneSegment, 2> kShutdownFallback = {{
{659, 150, 24},
{262, 250, 20},
}};
uint64_t NowMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace
struct LocalPromptPlayer::ProducerContext {
LocalPromptPlayer* player = nullptr;
PlaybackSessionId session_id = 0;
std::array<
EmbeddedPromptBlob,
kMaxLocalPromptSequenceItems> blobs{};
std::array<
LocalPrompt,
kMaxLocalPromptSequenceItems> prompts{};
size_t count = 0;
bool activation_sequence = false;
};
LocalPromptPlayer::LocalPromptPlayer(PlaybackPipeline& pipeline)
: pipeline_(pipeline)
{
}
LocalPromptPlayer::~LocalPromptPlayer()
{
producer_running_.store(false, std::memory_order_release);
if (producer_task_ != nullptr) {
if (xSemaphoreTake(
producer_stopped_, pdMS_TO_TICKS(2000)) != pdTRUE) {
ESP_LOGE(kTag, "prompt worker stop timed out");
}
vTaskDeleteWithCaps(producer_task_);
producer_task_ = nullptr;
}
if (producer_queue_ != nullptr) {
ProducerContext* pending = nullptr;
while (xQueueReceive(producer_queue_, &pending, 0) == pdTRUE) {
DestroyProducerContext(pending);
}
}
if (pcm_buffer_ != nullptr) {
heap_caps_free(pcm_buffer_);
}
if (context_pool_ != nullptr) {
heap_caps_free(context_pool_);
context_pool_ = nullptr;
}
}
bool LocalPromptPlayer::Initialize()
{
if (pcm_buffer_ != nullptr && producer_task_ != nullptr) {
return true;
}
if (pcm_buffer_ == nullptr) {
pcm_buffer_ = static_cast<int16_t*>(heap_caps_calloc(
PlaybackPipeline::kSamplesPerFrame,
sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (pcm_buffer_ == nullptr) {
ESP_LOGE(kTag, "failed to allocate PSRAM fallback buffer");
return false;
}
if (producer_queue_ == nullptr) {
producer_queue_ = xQueueCreateStatic(
kProducerQueueDepth,
sizeof(ProducerContext*),
producer_queue_bytes_.data(),
&producer_queue_storage_);
}
if (producer_stopped_ == nullptr) {
producer_stopped_ = xSemaphoreCreateBinaryStatic(
&producer_stopped_storage_);
}
// if (producer_queue_ == nullptr || producer_stopped_ == nullptr) {
// ESP_LOGE(kTag, "failed to create prompt worker controls");
// return false;
// }
if (context_pool_ == nullptr) {
context_pool_ = static_cast<ProducerContext*>(
heap_caps_calloc(
kProducerQueueDepth,
sizeof(ProducerContext),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (free_slots_ == nullptr) {
free_slots_ = xQueueCreateStatic(
kProducerQueueDepth,
sizeof(uint8_t),
free_slots_bytes_.data(),
&free_slots_storage_);
if (free_slots_ != nullptr) {
for (uint8_t index = 0; index < kProducerQueueDepth; ++index) {
xQueueSend(free_slots_, &index, 0);
}
}
}
if (producer_queue_ == nullptr || producer_stopped_ == nullptr ||
context_pool_ == nullptr || free_slots_ == nullptr) {
ESP_LOGE(kTag, "failed to create prompt worker controls or pool");
return false;
}/////////
xSemaphoreTake(producer_stopped_, 0);
producer_running_.store(true, std::memory_order_release);
const BaseType_t created = xTaskCreatePinnedToCoreWithCaps(
&LocalPromptPlayer::ProducerTaskEntry,
"prompt_producer",
task_stack_budget::kLocalPromptProducerBytes,
this,
4,
&producer_task_,
0,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (created != pdPASS) {
producer_running_.store(false, std::memory_order_release);
producer_task_ = nullptr;
ESP_LOGE(kTag, "failed to create PSRAM prompt worker");
return false;
}
ESP_LOGI(kTag, "worker started stack_bytes=%u memory=PSRAM queue=%u",
static_cast<unsigned>(
task_stack_budget::kLocalPromptProducerBytes),
static_cast<unsigned>(kProducerQueueDepth));
return true;
}
PlaybackSessionId LocalPromptPlayer::Play(
LocalPrompt prompt,
PlaybackPriority priority,
int16_t selector)
{
EmbeddedPromptBlob blob;
const uint32_t selected =
selector < 0
? esp_random()
: static_cast<uint32_t>(selector);
if (!EmbeddedPromptCatalog::Select(prompt, selected, &blob)) {
ESP_LOGW(kTag, "no embedded asset prompt=%s; using tone fallback",
ToString(prompt));
return PlayProceduralFallback(prompt, priority);
}
auto* context = AllocateProducerContext();
if (context == nullptr) {
ESP_LOGE(kTag, "failed to allocate PSRAM prompt context");
return 0;
}
context->player = this;
context->blobs[0] = blob;
context->prompts[0] = prompt;
context->count = 1;
return StartProducer(context, priority);
}
PlaybackSessionId LocalPromptPlayer::PlaySequence(
const LocalPromptSequence& sequence,
PlaybackPriority priority)
{
if (sequence.Empty() ||
sequence.count > kMaxLocalPromptSequenceItems) {
return 0;
}
auto* context = AllocateProducerContext();
if (context == nullptr) {
return 0;
}
context->player = this;
context->activation_sequence =
sequence.Contains(LocalPrompt::kActivationDevice);
for (size_t index = 0; index < sequence.count; ++index) {
const LocalPromptSequenceItem& item = sequence.items[index];
const uint32_t selected = item.selector < 0
? esp_random()
: static_cast<uint32_t>(item.selector);
if (!EmbeddedPromptCatalog::Select(
item.prompt,
selected,
&context->blobs[context->count])) {
ESP_LOGW(kTag,
"sequence asset missing prompt=%s",
ToString(item.prompt));
DestroyProducerContext(context);
return 0;
}
context->prompts[context->count] = item.prompt;
context->count++;
}
return StartProducer(context, priority);
}
PlaybackSessionId LocalPromptPlayer::StartProducer(
ProducerContext* context,
PlaybackPriority priority)
{
const PlaybackStartResult start = pipeline_.StartSession(
PlaybackSource::kLocalPrompt, priority);
if (start.status != PlaybackStartStatus::kStarted) {
ESP_LOGW(kTag, "prompt producer rejected status=%s",
ToString(start.status));
DestroyProducerContext(context);
return start.status == PlaybackStartStatus::kAlreadyActive
? start.session_id
: 0;
}
context->session_id = start.session_id;
const size_t item_count = context->count;
const char* first_filename = context->blobs[0].filename;
if (!producer_running_.load(std::memory_order_acquire) ||
xQueueSend(producer_queue_, &context, 0) != pdTRUE) {
DestroyProducerContext(context);
pipeline_.Cancel(start.session_id);
ESP_LOGE(kTag, "prompt worker unavailable or queue full");
return 0;
}
ESP_LOGI(kTag,
"prompt producer started items=%u first=%s session=%lu",
static_cast<unsigned>(item_count),
first_filename,
static_cast<unsigned long>(start.session_id));
return start.session_id;
}
void LocalPromptPlayer::ProducerTaskEntry(void* raw_context)
{
static_cast<LocalPromptPlayer*>(raw_context)->RunProducer();
}
LocalPromptPlayer::ProducerContext*
LocalPromptPlayer::AllocateProducerContext()
{
// void* storage = heap_caps_calloc(
// 1,
// sizeof(ProducerContext),
// MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
// return storage == nullptr
// ? nullptr
// : new (storage) ProducerContext{};///改堆分配为队列
if (context_pool_ == nullptr || free_slots_ == nullptr) {
return nullptr;
}
uint8_t index = 0;
if (xQueueReceive(free_slots_, &index, 0) != pdTRUE) {
return nullptr;
}
if (index >= kProducerQueueDepth) {
return nullptr;
}
ProducerContext* context = &context_pool_[index];
new (context) ProducerContext{};
return context;
}
void LocalPromptPlayer::DestroyProducerContext(
ProducerContext* context)
{
// if (context == nullptr) {
// return;
// }
if (context == nullptr || context_pool_ == nullptr ||
free_slots_ == nullptr) {
return;
}
const uint8_t index = static_cast<uint8_t>(
context - context_pool_);
if (index >= kProducerQueueDepth) {
return;
}
context->~ProducerContext();
//heap_caps_free(context);
xQueueSend(free_slots_, &index, 0);
}
void LocalPromptPlayer::RunProducer()
{
while (producer_running_.load(std::memory_order_acquire)) {
ProducerContext* context = nullptr;
if (xQueueReceive(
producer_queue_,
&context,
pdMS_TO_TICKS(100)) != pdTRUE) {
continue;
}
if (!producer_running_.load(std::memory_order_acquire)) {
DestroyProducerContext(context);
break;
}
Produce(*context);
DestroyProducerContext(context);
}
xSemaphoreGive(producer_stopped_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void LocalPromptPlayer::Produce(ProducerContext& context)
{
for (size_t index = 0; index < context.count; ++index) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(context.session_id);
return;
}
if (!SubmitEmbedded(
context.blobs[index], context.session_id)) {
return;
}
if (context.activation_sequence &&
index + 1 < context.count) {
const uint16_t gap =
context.prompts[index] ==
LocalPrompt::kActivationDevice
? kActivationIntroGapMs
: kActivationDigitGapMs;
if (!SubmitSilence(context.session_id, gap)) {
return;
}
}
}
if (!pipeline_.EndInput(context.session_id)) {
ESP_LOGW(kTag,
"prompt producer ended after preemption session=%lu",
static_cast<unsigned long>(context.session_id));
}
}
bool LocalPromptPlayer::SubmitEmbedded(
const EmbeddedPromptBlob& blob,
PlaybackSessionId session_id)
{
PackedOpusReader reader(blob.data, blob.size);
if (!reader.valid()) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag, "invalid packed prompt asset=%s", blob.filename);
return false;
}
const uint8_t* frame = nullptr;
size_t frame_size = 0;
while (reader.Next(&frame, &frame_size)) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(session_id);
return false;
}
const uint64_t wait_started = NowMs();
while (!pipeline_.SubmitOpus(session_id, frame, frame_size)) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(session_id);
return false;
}
const PlaybackSessionSnapshot current = pipeline_.Snapshot();
if (!current.active || current.id != session_id) {
ESP_LOGI(kTag,
"prompt producer preempted asset=%s session=%lu",
blob.filename,
static_cast<unsigned long>(session_id));
return false;
}
if (NowMs() - wait_started >=
kQueueBackpressureTimeoutMs) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag,
"prompt queue stalled asset=%s session=%lu",
blob.filename,
static_cast<unsigned long>(session_id));
return false;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
}
if (!reader.complete()) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag, "truncated packed prompt asset=%s", blob.filename);
return false;
}
return true;
}
bool LocalPromptPlayer::SubmitSilence(
PlaybackSessionId session_id,
uint16_t duration_ms)
{
size_t samples_remaining =
static_cast<size_t>(PlaybackPipeline::kSampleRate) *
duration_ms / 1000;
while (samples_remaining > 0) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(session_id);
return false;
}
const size_t samples = std::min(
samples_remaining,
PlaybackPipeline::kSamplesPerFrame);
const uint64_t wait_started = NowMs();
while (!pipeline_.SubmitPcm(
session_id, kSilence.data(), samples)) {
const PlaybackSessionSnapshot current = pipeline_.Snapshot();
if (!current.active || current.id != session_id) {
return false;
}
if (NowMs() - wait_started >=
kQueueBackpressureTimeoutMs) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag,
"sequence silence queue stalled session=%lu",
static_cast<unsigned long>(session_id));
return false;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
samples_remaining -= samples;
}
return true;
}
PlaybackSessionId LocalPromptPlayer::PlayProceduralFallback(
LocalPrompt prompt,
PlaybackPriority priority)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!Initialize()) {
return 0;
}
const PlaybackStartResult start = pipeline_.StartSession(
PlaybackSource::kLocalPrompt, priority);
if (start.status != PlaybackStartStatus::kStarted) {
return start.status == PlaybackStartStatus::kAlreadyActive
? start.session_id
: 0;
}
float phase = 0.0f;
const auto submit_sequence =
[this, &start, &phase](const auto& sequence) {
for (const auto& tone : sequence) {
if (!SubmitTone(
start.session_id,
tone.frequency_hz,
tone.duration_ms,
tone.amplitude_percent,
&phase)) {
return false;
}
}
return true;
};
bool submitted = false;
switch (prompt) {
case LocalPrompt::kBoot:
submitted = submit_sequence(kBootFallback);
break;
case LocalPrompt::kProvisioning:
submitted = submit_sequence(kProvisioningFallback);
break;
case LocalPrompt::kShutdown:
submitted = submit_sequence(kShutdownFallback);
break;
default:
submitted = submit_sequence(kErrorFallback);
break;
}
if (!submitted || !pipeline_.EndInput(start.session_id)) {
pipeline_.Cancel(start.session_id);
return 0;
}
return start.session_id;
}
bool LocalPromptPlayer::SubmitTone(
PlaybackSessionId session_id,
uint16_t frequency_hz,
uint16_t duration_ms,
uint8_t amplitude_percent,
float* phase)
{
const size_t total_samples =
static_cast<size_t>(PlaybackPipeline::kSampleRate) *
duration_ms / 1000;
const float amplitude =
32767.0f * static_cast<float>(amplitude_percent) / 100.0f;
const size_t fade_samples =
PlaybackPipeline::kSampleRate / 100;
size_t generated = 0;
while (generated < total_samples) {
const size_t frame_samples = std::min(
PlaybackPipeline::kSamplesPerFrame,
total_samples - generated);
for (size_t index = 0; index < frame_samples; ++index) {
const size_t absolute = generated + index;
float envelope = 1.0f;
if (absolute < fade_samples) {
envelope = static_cast<float>(absolute) /
static_cast<float>(fade_samples);
} else if (total_samples - absolute < fade_samples) {
envelope = static_cast<float>(total_samples - absolute) /
static_cast<float>(fade_samples);
}
if (frequency_hz == 0) {
pcm_buffer_[index] = 0;
} else {
pcm_buffer_[index] = static_cast<int16_t>(
amplitude * envelope * std::sin(*phase));
*phase += 2.0f * kPi *
static_cast<float>(frequency_hz) /
static_cast<float>(
PlaybackPipeline::kSampleRate);
if (*phase >= 2.0f * kPi) {
*phase -= 2.0f * kPi;
}
}
}
if (!pipeline_.SubmitPcm(
session_id, pcm_buffer_, frame_samples)) {
return false;
}
generated += frame_samples;
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,83 @@
#pragma once
#include "audio/embedded_prompt_catalog.h"
#include "audio/playback_pipeline.h"
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <mutex>
namespace borla {
class LocalPromptPlayer final {
public:
explicit LocalPromptPlayer(PlaybackPipeline& pipeline);
~LocalPromptPlayer();
bool Initialize();
PlaybackSessionId Play(
LocalPrompt prompt,
PlaybackPriority priority,
int16_t selector = -1);
PlaybackSessionId PlaySequence(
const LocalPromptSequence& sequence,
PlaybackPriority priority);
private:
struct ProducerContext;
static constexpr size_t kProducerQueueDepth = 4;
static void ProducerTaskEntry(void* context);
// static ProducerContext* AllocateProducerContext();
// static void DestroyProducerContext(ProducerContext* context);
ProducerContext* AllocateProducerContext();
void DestroyProducerContext(ProducerContext* context);
void RunProducer();
void Produce(ProducerContext& context);
bool SubmitEmbedded(
const EmbeddedPromptBlob& blob,
PlaybackSessionId session_id);
bool SubmitSilence(
PlaybackSessionId session_id,
uint16_t duration_ms);
PlaybackSessionId StartProducer(
ProducerContext* context,
PlaybackPriority priority);
PlaybackSessionId PlayProceduralFallback(
LocalPrompt prompt,
PlaybackPriority priority);
bool SubmitTone(
PlaybackSessionId session_id,
uint16_t frequency_hz,
uint16_t duration_ms,
uint8_t amplitude_percent,
float* phase);
PlaybackPipeline& pipeline_;
std::mutex mutex_;
int16_t* pcm_buffer_ = nullptr;
std::array<
uint8_t,
kProducerQueueDepth * sizeof(ProducerContext*)>
producer_queue_bytes_{};
StaticQueue_t producer_queue_storage_{};
QueueHandle_t producer_queue_ = nullptr;
StaticSemaphore_t producer_stopped_storage_{};
SemaphoreHandle_t producer_stopped_ = nullptr;
std::atomic<bool> producer_running_{false};
/////
TaskHandle_t producer_task_ = nullptr;
ProducerContext* context_pool_ = nullptr;
std::array<uint8_t, kProducerQueueDepth> free_slots_bytes_{};
StaticQueue_t free_slots_storage_{};
QueueHandle_t free_slots_ = nullptr;
};
} // namespace borla

View File

@@ -0,0 +1,107 @@
#include "audio/opus_frame_decoder.h"
#include <esp_log.h>
#include <opus.h>
namespace borla {
namespace {
constexpr const char* kTag = "OpusFrameDecoder2";
} // namespace
OpusFrameDecoder::~OpusFrameDecoder()
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
opus_decoder_destroy(decoder_);
}
}
bool OpusFrameDecoder::Initialize(
uint32_t sample_rate,
uint8_t channels)
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
return true;
}
int error = OPUS_OK;
decoder_ = opus_decoder_create(
static_cast<opus_int32>(sample_rate), channels, &error);
if (decoder_ == nullptr || error != OPUS_OK) {
ESP_LOGE(kTag, "opus decoder creation failed: %s",
opus_strerror(error));
decoder_ = nullptr;
return false;
}
channels_ = channels;
ESP_LOGI(kTag, "decoder initialized rate=%lu channels=%u",
static_cast<unsigned long>(sample_rate),
static_cast<unsigned>(channels));
return true;
}
bool OpusFrameDecoder::Decode(
const uint8_t* encoded,
size_t encoded_size,
int16_t* pcm,
size_t pcm_capacity,
size_t* decoded_samples)
{
if (pcm == nullptr || decoded_samples == nullptr ||
pcm_capacity == 0 ||
(encoded_size > 0 && encoded == nullptr)) {
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ == nullptr) {
return false;
}
const size_t capacity_per_channel = pcm_capacity / channels_;
const int decoded = opus_decode(
decoder_,
encoded,
static_cast<opus_int32>(encoded_size),
pcm,
static_cast<int>(capacity_per_channel),
0);
if (decoded < 0) {
ESP_LOGE(kTag, "decode failed: %s", opus_strerror(decoded));
return false;
}
*decoded_samples =
static_cast<size_t>(decoded) * static_cast<size_t>(channels_);
// 2026-8-28 CKKJ temp debug: log first 10 frames peak + raw Opus info
static uint32_t s_decode_seq = 0;
if (s_decode_seq < 10) {
s_decode_seq++;
int32_t peak = 0;
for (size_t i = 0; i < *decoded_samples; ++i) {
int32_t a = pcm[i] < 0 ? -pcm[i] : pcm[i];
if (a > peak) peak = a;
}
const uint8_t toc = encoded_size > 0 ? encoded[0] : 0;
ESP_LOGI(kTag, "decode seq=%u enc_size=%u toc=0x%02x decoded=%u peak=%d",
static_cast<unsigned>(s_decode_seq),
static_cast<unsigned>(encoded_size),
static_cast<unsigned>(toc),
static_cast<unsigned>(*decoded_samples),
static_cast<int>(peak));
}//
return true;
}
void OpusFrameDecoder::Reset()
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
opus_decoder_ctl(decoder_, OPUS_RESET_STATE);
}
}
} // namespace borla

View File

@@ -0,0 +1,31 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <mutex>
struct OpusDecoder;
namespace borla {
class OpusFrameDecoder final {
public:
OpusFrameDecoder() = default;
~OpusFrameDecoder();
bool Initialize(uint32_t sample_rate, uint8_t channels);
bool Decode(
const uint8_t* encoded,
size_t encoded_size,
int16_t* pcm,
size_t pcm_capacity,
size_t* decoded_samples);
void Reset();
private:
std::mutex mutex_;
OpusDecoder* decoder_ = nullptr;
uint8_t channels_ = 1;
};
} // namespace borla

View File

@@ -0,0 +1,105 @@
#include "audio/opus_frame_encoder.h"
#include <esp_log.h>
#include <opus.h>
namespace borla {
namespace {
constexpr const char* kTag = "OpusFrameEncoder2";
} // namespace
OpusFrameEncoder::~OpusFrameEncoder()
{
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
opus_encoder_destroy(encoder_);
}
}
bool OpusFrameEncoder::Initialize(
uint32_t sample_rate,
uint8_t channels,
uint32_t bitrate)
{
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
return true;
}
int error = OPUS_OK;
encoder_ = opus_encoder_create(
static_cast<opus_int32>(sample_rate),
channels,
OPUS_APPLICATION_VOIP,
&error);
if (encoder_ == nullptr || error != OPUS_OK) {
ESP_LOGE(kTag, "encoder creation failed: %s",
opus_strerror(error));
encoder_ = nullptr;
return false;
}
channels_ = channels;
// Complexity 3, matching the previous firmware ("ESP32 上用最低复杂度保证
// 实时性", audio_service.cc:14). At complexity 4 a 60 ms frame measured
// 33 ms to encode with the core to itself and 82 ms averaged when TTS
// playback shared core 1 — the task-watchdog backtraces all ended inside
// silk_encode_frame_FIX. The uplink feeds server-side ASR at 16 kHz mono;
// it does not need the marginal quality of the higher search depth.
if (opus_encoder_ctl(
encoder_,
OPUS_SET_BITRATE(static_cast<opus_int32>(bitrate))) != OPUS_OK ||
opus_encoder_ctl(encoder_, OPUS_SET_COMPLEXITY(3)) != OPUS_OK ||
opus_encoder_ctl(encoder_, OPUS_SET_VBR(1)) != OPUS_OK ||
opus_encoder_ctl(encoder_, OPUS_SET_DTX(0)) != OPUS_OK) {
ESP_LOGE(kTag, "encoder configuration failed");
opus_encoder_destroy(encoder_);
encoder_ = nullptr;
return false;
}
ESP_LOGI(kTag, "initialized rate=%lu channels=%u bitrate=%lu",
static_cast<unsigned long>(sample_rate),
static_cast<unsigned>(channels),
static_cast<unsigned long>(bitrate));
return true;
}
bool OpusFrameEncoder::Encode(
const int16_t* pcm,
size_t samples_per_channel,
uint8_t* encoded,
size_t capacity,
size_t* encoded_size)
{
if (pcm == nullptr || encoded == nullptr ||
encoded_size == nullptr || samples_per_channel == 0 ||
capacity == 0 || capacity > INT32_MAX) {
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ == nullptr) {
return false;
}
const int result = opus_encode(
encoder_,
pcm,
static_cast<int>(samples_per_channel),
encoded,
static_cast<opus_int32>(capacity));
if (result <= 0) {
ESP_LOGE(kTag, "encode failed: %s", opus_strerror(result));
return false;
}
*encoded_size = static_cast<size_t>(result);
return true;
}
void OpusFrameEncoder::Reset()
{
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
opus_encoder_ctl(encoder_, OPUS_RESET_STATE);
}
}
} // namespace borla

View File

@@ -0,0 +1,36 @@
#pragma once
#include "protocol/binary_audio_protocol.h"
#include <cstddef>
#include <cstdint>
#include <mutex>
struct OpusEncoder;
namespace borla {
class OpusFrameEncoder final {
public:
OpusFrameEncoder() = default;
~OpusFrameEncoder();
bool Initialize(
uint32_t sample_rate,
uint8_t channels,
uint32_t bitrate);
bool Encode(
const int16_t* pcm,
size_t samples_per_channel,
uint8_t* encoded,
size_t capacity,
size_t* encoded_size);
void Reset();
private:
std::mutex mutex_;
OpusEncoder* encoder_ = nullptr;
uint8_t channels_ = 1;
};
} // namespace borla

View File

@@ -0,0 +1,61 @@
#include "audio/packed_opus_reader.h"
namespace borla {
namespace {
uint16_t ReadLe16(const uint8_t* data)
{
return static_cast<uint16_t>(
static_cast<uint16_t>(data[0]) |
(static_cast<uint16_t>(data[1]) << 8));
}
} // namespace
PackedOpusReader::PackedOpusReader(
const uint8_t* data,
size_t size)
: data_(data),
size_(size)
{
if (data_ == nullptr || size_ < 2) {
return;
}
frame_count_ = ReadLe16(data_);
offset_ = 2;
valid_ = frame_count_ > 0;
}
bool PackedOpusReader::Next(
const uint8_t** frame,
size_t* frame_size)
{
if (!valid_ || frame == nullptr || frame_size == nullptr ||
frames_read_ >= frame_count_) {
return false;
}
if (offset_ + 2 > size_) {
valid_ = false;
return false;
}
const uint16_t size = ReadLe16(data_ + offset_);
offset_ += 2;
if (size == 0 || offset_ + size > size_) {
valid_ = false;
return false;
}
*frame = data_ + offset_;
*frame_size = size;
offset_ += size;
frames_read_++;
return true;
}
bool PackedOpusReader::complete() const
{
return valid_ && frames_read_ == frame_count_ && offset_ == size_;
}
} // namespace borla

View File

@@ -0,0 +1,27 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class PackedOpusReader final {
public:
PackedOpusReader(const uint8_t* data, size_t size);
bool Next(const uint8_t** frame, size_t* frame_size);
bool valid() const { return valid_; }
bool complete() const;
uint16_t frame_count() const { return frame_count_; }
uint16_t frames_read() const { return frames_read_; }
private:
const uint8_t* data_ = nullptr;
size_t size_ = 0;
size_t offset_ = 0;
uint16_t frame_count_ = 0;
uint16_t frames_read_ = 0;
bool valid_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,45 @@
#include "audio/pcm_rate_converter.h"
#include <algorithm>
namespace borla {
constexpr int32_t kMicDigitalGain = 16;
//bool Pcm24kTo16kConverter::Convert(
bool Pcm48kTo16kConverter::Convert(
const int16_t* input,
size_t input_samples,
int16_t* output,
size_t output_capacity) const
{
if (input == nullptr || output == nullptr ||
input_samples != kInputSamples ||
output_capacity < kOutputSamples) {
return false;
}
// 24k -> 16k is a 3:2 ratio. Even outputs copy an input sample and odd
// outputs interpolate the two adjacent samples. The exact frame boundary
// is preserved, which is more important than a streaming fractional
// accumulator for the fixed 60 ms protocol.
for (size_t index = 0; index < kOutputSamples; ++index) {
const size_t base = (index * 3U) / 2U *2U;
int32_t value;
if ((index & 1U) == 0U) {
value = static_cast<int32_t>(input[base]);
} else {
value = (static_cast<int32_t>(input[base]) + static_cast<int32_t>(input[base + 2U])) / 2;
}
value *= kMicDigitalGain;
output[index] = static_cast<int16_t>(std::clamp<int32_t>(value, -32768, 32767));
// const size_t base = index * 3U;
// const int32_t mixed =
// static_cast<int32_t>(input[base]) +
// static_cast<int32_t>(input[base + 1]) +
// static_cast<int32_t>(input[base + 2]);
// output[index] = static_cast<int16_t>(
// std::clamp<int32_t>(mixed / 3, -32768, 32767));
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,25 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
// Stateless conversion for exact 60 ms frames. The hardware codec runs at
// 24 kHz so RX and TX can share one I2S clock; uplink is converted to the
// protocol's fixed 16 kHz rate before voice processing/Opus.
//class Pcm24kTo16kConverter final {
class Pcm48kTo16kConverter final {
public:
//static constexpr size_t kInputSamples = 1440;
static constexpr size_t kInputSamples = 2880;
static constexpr size_t kOutputSamples = 960;
bool Convert(
const int16_t* input,
size_t input_samples,
int16_t* output,
size_t output_capacity) const;
};
} // namespace borla

View File

@@ -0,0 +1,321 @@
#include "audio/playback_controller.h"
#include <algorithm>
#include <limits>
namespace borla {
namespace {
constexpr PlaybackSessionId kLocalSessionIdBase = 0x80000000U;
bool IsRemoteSource(PlaybackSource source)
{
return source == PlaybackSource::kRemoteTts ||
source == PlaybackSource::kRemoteMusic;
}
} // namespace
PlaybackStartResult PlaybackController::StartSession(
PlaybackSource source,
PlaybackPriority priority,
PlaybackSessionId requested_id,
uint64_t now_ms)
{
if (IsRemoteSource(source) &&
(requested_id == 0 || requested_id >= kLocalSessionIdBase)) {
return {
PlaybackStartStatus::kRejectedInvalidSessionId,
0,
0,
0,
};
}
if (session_.active && requested_id != 0 &&
requested_id == session_.id && source == session_.source) {
return {
PlaybackStartStatus::kAlreadyActive,
session_.id,
0,
session_.generation,
};
}
if (session_.active &&
static_cast<uint8_t>(priority) <
static_cast<uint8_t>(session_.priority)) {
metrics_.lower_priority_rejections++;
return {
PlaybackStartStatus::kRejectedLowerPriority,
0,
0,
0,
};
}
PlaybackSessionId preempted = 0;
if (session_.active) {
preempted = session_.id;
session_.state = PlaybackSessionState::kCancelled;
session_.active = false;
metrics_.sessions_cancelled++;
metrics_.sessions_preempted++;
}
session_ = {};
session_.id = AllocateSessionId(requested_id);
session_.generation = next_generation_++;
if (next_generation_ == 0) {
next_generation_ = 1;
}
session_.source = source;
session_.priority = priority;
session_.state = PlaybackSessionState::kPending;
session_.active = true;
started_at_ms_ = now_ms;
last_progress_ms_ = now_ms;
metrics_.sessions_started++;
return {
PlaybackStartStatus::kStarted,
session_.id,
preempted,
session_.generation,
};
}
bool PlaybackController::CanAcceptFrame(
PlaybackSessionId session_id) const
{
return session_.active && session_id != 0 &&
session_.id == session_id;
}
bool PlaybackController::QueueFrame(
PlaybackSessionId session_id,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id)) {
return false;
}
session_.producer_started = true;
session_.queued_frames++;
session_.state = session_.input_ended
? PlaybackSessionState::kDraining
: PlaybackSessionState::kStreaming;
metrics_.frames_queued++;
metrics_.queue_high_watermark =
std::max(metrics_.queue_high_watermark, session_.queued_frames);
Touch(now_ms);
return true;
}
bool PlaybackController::RollbackQueuedFrame(
PlaybackSessionId session_id)
{
if (!IsCurrent(session_id) || session_.queued_frames == 0) {
return false;
}
session_.queued_frames--;
metrics_.frames_dropped++;
return true;
}
bool PlaybackController::BeginFrame(
PlaybackSessionId session_id,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id) || session_.queued_frames == 0) {
return false;
}
session_.queued_frames--;
session_.in_flight_frames++;
Touch(now_ms);
return true;
}
bool PlaybackController::FinishFrame(
PlaybackSessionId session_id,
bool write_succeeded,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id) ||
session_.in_flight_frames == 0) {
return false;
}
session_.in_flight_frames--;
if (write_succeeded) {
session_.written_frames++;
metrics_.frames_written++;
} else {
metrics_.frames_dropped++;
}
Touch(now_ms);
return true;
}
bool PlaybackController::EndInput(
PlaybackSessionId session_id,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id)) {
return false;
}
session_.input_ended = true;
session_.state = PlaybackSessionState::kDraining;
Touch(now_ms);
return true;
}
PlaybackSessionId PlaybackController::TryComplete()
{
if (!session_.active || !session_.producer_started ||
!session_.input_ended || session_.queued_frames != 0 ||
session_.in_flight_frames != 0) {
return 0;
}
session_.state = PlaybackSessionState::kCompleted;
session_.active = false;
metrics_.sessions_completed++;
return session_.id;
}
PlaybackSessionId PlaybackController::Cancel(
PlaybackSessionId session_id)
{
if (!session_.active ||
(session_id != 0 && session_id != session_.id)) {
return 0;
}
session_.state = PlaybackSessionState::kCancelled;
session_.active = false;
session_.queued_frames = 0;
metrics_.sessions_cancelled++;
return session_.id;
}
PlaybackSessionId PlaybackController::Fail(
PlaybackSessionId session_id)
{
if (!session_.active || session_id != session_.id) {
return 0;
}
session_.state = PlaybackSessionState::kFailed;
session_.active = false;
session_.queued_frames = 0;
metrics_.sessions_failed++;
return session_.id;
}
PlaybackTimeoutResult PlaybackController::CheckTimeout(
uint64_t now_ms,
uint32_t producer_start_timeout_ms,
uint32_t stalled_timeout_ms)
{
if (!session_.active) {
return {};
}
if (!session_.producer_started &&
now_ms - started_at_ms_ >= producer_start_timeout_ms) {
const PlaybackSessionId failed = Fail(session_.id);
metrics_.producer_start_timeouts++;
return {PlaybackTimeoutReason::kProducerStart, failed};
}
if (session_.producer_started && stalled_timeout_ms > 0 &&
now_ms - last_progress_ms_ >= stalled_timeout_ms) {
const PlaybackSessionId failed = Fail(session_.id);
metrics_.stalled_timeouts++;
return {PlaybackTimeoutReason::kStalled, failed};
}
return {};
}
void PlaybackController::RecordStaleFrame()
{
metrics_.stale_frames_rejected++;
metrics_.frames_dropped++;
}
bool PlaybackController::IsCurrent(
PlaybackSessionId session_id) const
{
return session_.active && session_.id == session_id;
}
PlaybackSessionId PlaybackController::AllocateSessionId(
PlaybackSessionId requested_id)
{
if (requested_id != 0) {
return requested_id;
}
const PlaybackSessionId allocated = next_session_id_;
next_session_id_++;
if (next_session_id_ < kLocalSessionIdBase) {
next_session_id_ = kLocalSessionIdBase;
}
return allocated;
}
void PlaybackController::Touch(uint64_t now_ms)
{
last_progress_ms_ = now_ms;
}
const char* ToString(PlaybackSessionState state)
{
switch (state) {
case PlaybackSessionState::kPending:
return "pending";
case PlaybackSessionState::kStreaming:
return "streaming";
case PlaybackSessionState::kDraining:
return "draining";
case PlaybackSessionState::kCancelled:
return "cancelled";
case PlaybackSessionState::kCompleted:
return "completed";
case PlaybackSessionState::kFailed:
return "failed";
}
return "unknown";
}
const char* ToString(PlaybackStartStatus status)
{
switch (status) {
case PlaybackStartStatus::kStarted:
return "started";
case PlaybackStartStatus::kAlreadyActive:
return "already_active";
case PlaybackStartStatus::kRejectedLowerPriority:
return "rejected_lower_priority";
case PlaybackStartStatus::kRejectedInvalidSessionId:
return "rejected_invalid_session_id";
}
return "unknown";
}
const char* ToString(PlaybackTimeoutReason reason)
{
switch (reason) {
case PlaybackTimeoutReason::kNone:
return "none";
case PlaybackTimeoutReason::kProducerStart:
return "producer_start";
case PlaybackTimeoutReason::kStalled:
return "stalled";
}
return "unknown";
}
} // namespace borla

View File

@@ -0,0 +1,121 @@
#pragma once
#include "core/playback_types.h"
#include <cstddef>
#include <cstdint>
namespace borla {
enum class PlaybackSessionState : uint8_t {
kPending,
kStreaming,
kDraining,
kCancelled,
kCompleted,
kFailed,
};
enum class PlaybackStartStatus : uint8_t {
kStarted,
kAlreadyActive,
kRejectedLowerPriority,
kRejectedInvalidSessionId,
};
enum class PlaybackTimeoutReason : uint8_t {
kNone,
kProducerStart,
kStalled,
};
struct PlaybackSessionSnapshot {
PlaybackSessionId id = 0;
uint32_t generation = 0;
PlaybackSource source = PlaybackSource::kRemoteTts;
PlaybackPriority priority = PlaybackPriority::kConversation;
PlaybackSessionState state = PlaybackSessionState::kCompleted;
size_t queued_frames = 0;
size_t in_flight_frames = 0;
uint32_t written_frames = 0;
bool active = false;
bool producer_started = false;
bool input_ended = false;
};
struct PlaybackMetrics {
uint32_t sessions_started = 0;
uint32_t sessions_completed = 0;
uint32_t sessions_cancelled = 0;
uint32_t sessions_failed = 0;
uint32_t sessions_preempted = 0;
uint32_t lower_priority_rejections = 0;
uint32_t stale_frames_rejected = 0;
uint32_t frames_queued = 0;
uint32_t frames_written = 0;
uint32_t frames_dropped = 0;
uint32_t producer_start_timeouts = 0;
uint32_t stalled_timeouts = 0;
size_t queue_high_watermark = 0;
};
struct PlaybackStartResult {
PlaybackStartStatus status = PlaybackStartStatus::kRejectedLowerPriority;
PlaybackSessionId session_id = 0;
PlaybackSessionId preempted_session_id = 0;
uint32_t generation = 0;
};
struct PlaybackTimeoutResult {
PlaybackTimeoutReason reason = PlaybackTimeoutReason::kNone;
PlaybackSessionId session_id = 0;
};
class PlaybackController final {
public:
PlaybackStartResult StartSession(
PlaybackSource source,
PlaybackPriority priority,
PlaybackSessionId requested_id,
uint64_t now_ms);
bool CanAcceptFrame(PlaybackSessionId session_id) const;
bool QueueFrame(PlaybackSessionId session_id, uint64_t now_ms);
bool RollbackQueuedFrame(PlaybackSessionId session_id);
bool BeginFrame(PlaybackSessionId session_id, uint64_t now_ms);
bool FinishFrame(
PlaybackSessionId session_id,
bool write_succeeded,
uint64_t now_ms);
bool EndInput(PlaybackSessionId session_id, uint64_t now_ms);
PlaybackSessionId TryComplete();
PlaybackSessionId Cancel(PlaybackSessionId session_id);
PlaybackSessionId Fail(PlaybackSessionId session_id);
PlaybackTimeoutResult CheckTimeout(
uint64_t now_ms,
uint32_t producer_start_timeout_ms,
uint32_t stalled_timeout_ms);
void RecordStaleFrame();
bool IsCurrent(PlaybackSessionId session_id) const;
const PlaybackSessionSnapshot& snapshot() const { return session_; }
const PlaybackMetrics& metrics() const { return metrics_; }
private:
PlaybackSessionId AllocateSessionId(PlaybackSessionId requested_id);
void Touch(uint64_t now_ms);
PlaybackSessionSnapshot session_{};
PlaybackMetrics metrics_{};
PlaybackSessionId next_session_id_ = 0x80000000U;
uint32_t next_generation_ = 1;
uint64_t started_at_ms_ = 0;
uint64_t last_progress_ms_ = 0;
};
const char* ToString(PlaybackSessionState state);
const char* ToString(PlaybackStartStatus status);
const char* ToString(PlaybackTimeoutReason reason);
} // namespace borla

View File

@@ -0,0 +1,660 @@
#include "audio/playback_pipeline.h"
#include "core/task_stack_budget.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/idf_additions.h>
#include <algorithm>
#include <cstring>
#include <new>
namespace borla {
namespace {
constexpr const char* kTag = "PlaybackPipeline2";
constexpr uint32_t kProducerStartTimeoutMs = 2000;
constexpr uint32_t kStalledTimeoutMs = 10000;
// How long a late frame may be held waiting for a companion after the ready
// queue ran dry. Playout health showed why: the server re-anchors its rate
// control after a TTS generation stall and never refills the burst cushion,
// so a starved stretch played as a run of 60-80 ms micro-gaps (16 in one
// session). Holding once converts that into a single short pause followed by
// smooth playout. Draining sessions never hold — every frame is already
// queued once EndInput has been seen.
constexpr uint32_t kDryRebuildHoldMs = 150;
// Fixed hold before the FIRST write of a remote TTS session. The server runs
// 6 frames (360 ms) ahead and never refills after a generation stall (it
// re-anchors instead), so the cushion only ever shrinks over a reply.
// Delaying playout start grows the server's effective lead by exactly the
// hold: 360 + 180 = 540 ms of stall budget, which absorbs typical
// inter-sentence TTS generation gaps that were audible as mid-reply breaks.
// Local prompts are exempt — they are fully buffered and latency-sensitive.
constexpr uint32_t kStartupPrebufferMs = 180;
} // namespace
PlaybackPipeline::PlaybackPipeline(IAudioOutput& output)
: output_(output)
{
}
PlaybackPipeline::~PlaybackPipeline()
{
Stop();
if (frame_pool_ != nullptr) {
heap_caps_free(frame_pool_);
}
if (decode_buffer_ != nullptr) {
heap_caps_free(decode_buffer_);
}
if (reference_buffer_ != nullptr) {
heap_caps_free(reference_buffer_);
}
}
void PlaybackPipeline::SetEventPublisher(IEventPublisher* publisher)
{
publisher_.store(publisher, std::memory_order_release);
}
bool PlaybackPipeline::Initialize()
{
if (initialized_) {
return true;
}
if (output_.SampleRate() != kSampleRate) {
ESP_LOGE(kTag, "output rate=%lu does not match pipeline rate=%lu",
static_cast<unsigned long>(output_.SampleRate()),
static_cast<unsigned long>(kSampleRate));
return false;
}
if (!decoder_.Initialize(kSampleRate, 1)) {
return false;
}
if (stopped_signal_ == nullptr) {
stopped_signal_
= xSemaphoreCreateBinaryStatic(&stopped_signal_storage_);
if (stopped_signal_ == nullptr) {
ESP_LOGE(kTag, "task stop signal creation failed");
return false;
}
}
if (frame_pool_ == nullptr) {
frame_pool_ = static_cast<FrameSlot*>(heap_caps_calloc(kFramePoolSize,
sizeof(FrameSlot), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (decode_buffer_ == nullptr) {
decode_buffer_
= static_cast<int16_t*>(heap_caps_calloc(kSamplesPerFrame,
sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (reference_buffer_ == nullptr) {
reference_buffer_
= static_cast<int16_t*>(heap_caps_calloc(kSamplesPerFrame,
sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (frame_pool_ == nullptr || decode_buffer_ == nullptr ||
reference_buffer_ == nullptr) {
ESP_LOGE(kTag,
"PSRAM allocation failed pool=%p decode=%p reference=%p",
frame_pool_, decode_buffer_, reference_buffer_);
return false;
}
for (size_t index = 0; index < kFramePoolSize; ++index) {
new (&frame_pool_[index]) FrameSlot();
}
free_slots_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t),
free_slots_queue_bytes_, &free_slots_storage_);
ready_frames_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t),
ready_frames_queue_bytes_, &ready_frames_storage_);
if (free_slots_ == nullptr || ready_frames_ == nullptr) {
ESP_LOGE(kTag, "static queue creation failed");
return false;
}
for (uint16_t index = 0; index < kFramePoolSize; ++index) {
if (xQueueSend(free_slots_, &index, 0) != pdTRUE) {
ESP_LOGE(kTag, "failed to seed frame slot=%u", index);
return false;
}
}
initialized_ = true;
ESP_LOGI(kTag, "initialized frames=%u slot_bytes=%u PSRAM=%u bytes",
static_cast<unsigned>(kFramePoolSize),
static_cast<unsigned>(sizeof(FrameSlot)),
static_cast<unsigned>(kFramePoolSize * sizeof(FrameSlot)
+ 2 * kSamplesPerFrame * sizeof(int16_t)));
return true;
}
bool PlaybackPipeline::Start()
{
if (running_.load(std::memory_order_acquire)) {
return true;
}
if (!initialized_ && !Initialize()) {
return false;
}
xSemaphoreTake(stopped_signal_, 0);
running_.store(true, std::memory_order_release);
const BaseType_t result
= xTaskCreatePinnedToCoreWithCaps(&PlaybackPipeline::TaskEntry,
"playback", task_stack_budget::kPlaybackBytes, this,
task_priority::kPlaybackLoop, &task_, 1,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (result != pdPASS) {
running_.store(false, std::memory_order_release);
task_ = nullptr;
ESP_LOGE(kTag, "failed to create playback task");
return false;
}
ESP_LOGI(kTag, "task started stack_bytes=%u memory=PSRAM",
static_cast<unsigned>(task_stack_budget::kPlaybackBytes));
return true;
}
void PlaybackPipeline::Stop()
{
paused_.store(false, std::memory_order_release);
if (!running_.exchange(false, std::memory_order_acq_rel)) {
return;
}
if (task_ != nullptr) {
if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "speaker-owner task stop timed out");
}
vTaskDeleteWithCaps(task_);
task_ = nullptr;
}
std::lock_guard<std::mutex> lock(mutex_);
controller_.Cancel(0);
DrainReadyQueueLocked();
decoder_.Reset();
}
PlaybackStartResult PlaybackPipeline::StartSession(PlaybackSource source,
PlaybackPriority priority, PlaybackSessionId requested_id)
{
if (!running_.load(std::memory_order_acquire)) {
return {};
}
PlaybackStartResult result;
{
std::lock_guard<std::mutex> lock(mutex_);
result
= controller_.StartSession(source, priority, requested_id, NowMs());
if (result.status == PlaybackStartStatus::kStarted) {
paused_.store(false, std::memory_order_release);
backpressure_logged_session_.store(
0, std::memory_order_release);
DrainReadyQueueLocked();
// The decoder is reset by the playback task itself, right before
// the next Decode: this path runs on the application task while
// Run() may be inside Decode() — which happens OUTSIDE mutex_ —
// and libopus state is not reentrant. The flag is honoured before
// the new session's first frame, which is all the reset is for.
decoder_reset_pending_.store(
true, std::memory_order_release);
// Drop any reference frames stranded from the previous session so
// the AEC starts this one in phase with the speaker.
IPlaybackReferenceSink* reference_sink
= reference_sink_.load(std::memory_order_acquire);
if (reference_sink != nullptr) {
reference_sink->ResetPlaybackReference();
}
ESP_LOGI(kTag,
"session start id=%lu generation=%lu source=%s "
"priority=%s preempted=%lu",
static_cast<unsigned long>(result.session_id),
static_cast<unsigned long>(result.generation), ToString(source),
ToString(priority),
static_cast<unsigned long>(result.preempted_session_id));
} else {
ESP_LOGW(kTag,
"session request status=%s requested=%lu source=%s "
"priority=%s",
ToString(result.status),
static_cast<unsigned long>(requested_id), ToString(source),
ToString(priority));
}
}
if (result.preempted_session_id != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackPreempted,
result.preempted_session_id, result.session_id);
}
return result;
}
bool PlaybackPipeline::SubmitOpus(
PlaybackSessionId session_id, const uint8_t* data, size_t size)
{
if (data == nullptr || size == 0 || size > kMaxOpusBytes) {
ESP_LOGW(
kTag, "invalid Opus frame size=%u", static_cast<unsigned>(size));
return false;
}
return SubmitFrame(session_id, FrameFormat::kOpus, data, size, 0);
}
bool PlaybackPipeline::SubmitPcm(
PlaybackSessionId session_id, const int16_t* samples, size_t sample_count)
{
if (samples == nullptr || sample_count == 0
|| sample_count > kSamplesPerFrame) {
return false;
}
return SubmitFrame(session_id, FrameFormat::kPcm, samples,
sample_count * sizeof(int16_t), sample_count);
}
bool PlaybackPipeline::EndInput(PlaybackSessionId session_id)
{
PlaybackSessionId completed = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!controller_.EndInput(session_id, NowMs())) {
return false;
}
completed = controller_.TryComplete();
}
if (completed != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed);
}
return true;
}
bool PlaybackPipeline::Cancel(PlaybackSessionId session_id)
{
paused_.store(false, std::memory_order_release);
std::lock_guard<std::mutex> lock(mutex_);
const PlaybackSessionId cancelled = controller_.Cancel(session_id);
if (cancelled == 0) {
return false;
}
DrainReadyQueueLocked();
// Same reentrancy rule as StartSession: Decode() runs outside mutex_ on
// the playback task, so the reset must happen there, not here.
decoder_reset_pending_.store(true, std::memory_order_release);
ESP_LOGI(kTag, "session cancelled id=%lu",
static_cast<unsigned long>(cancelled));
return true;
}
void PlaybackPipeline::SetPaused(bool paused)
{
const bool previous = paused_.exchange(
paused, std::memory_order_acq_rel);
if (previous != paused) {
ESP_LOGI(kTag, "playback %s for barge-in candidate",
paused ? "paused" : "resumed");
}
}
PlaybackSessionSnapshot PlaybackPipeline::Snapshot() const
{
std::lock_guard<std::mutex> lock(mutex_);
return controller_.snapshot();
}
PlaybackMetrics PlaybackPipeline::Metrics() const
{
std::lock_guard<std::mutex> lock(mutex_);
return controller_.metrics();
}
void PlaybackPipeline::TaskEntry(void* context)
{
static_cast<PlaybackPipeline*>(context)->Run();
}
void PlaybackPipeline::Run()
{
ESP_LOGI(kTag, "speaker-owner task started");
while (running_.load(std::memory_order_acquire)) {
uint16_t slot_index = 0;
if (xQueueReceive(ready_frames_, &slot_index, pdMS_TO_TICKS(20))
!= pdTRUE) {
CheckTimeout();
continue;
}
if (slot_index >= kFramePoolSize) {
ESP_LOGE(kTag, "invalid frame slot=%u", slot_index);
continue;
}
const uint32_t ready_depth = static_cast<uint32_t>(
uxQueueMessagesWaiting(ready_frames_));
// Candidate barge-in is reversible. Keep the dequeued head frame and
// every queued frame intact until the server confirms or rejects the
// ASR result. A frame already inside synchronous I2S Write() may finish,
// so pause latency is bounded by one 60 ms frame.
if (paused_.load(std::memory_order_acquire)) {
// A deliberate hold is not starvation; skip the next gap sample.
health_skip_gap_ = true;
}
while (running_.load(std::memory_order_acquire) &&
paused_.load(std::memory_order_acquire)) {
vTaskDelay(pdMS_TO_TICKS(10));
}
if (!running_.load(std::memory_order_acquire)) {
ReleaseSlot(slot_index);
break;
}
FrameSlot& slot = frame_pool_[slot_index];
if (slot.session_id != health_session_) {
// First frame of a new session: see kStartupPrebufferMs.
bool prebuffer = false;
{
std::lock_guard<std::mutex> lock(mutex_);
prebuffer = controller_.IsCurrent(slot.session_id) &&
controller_.snapshot().source ==
PlaybackSource::kRemoteTts;
}
if (prebuffer) {
const uint64_t deadline_us =
static_cast<uint64_t>(esp_timer_get_time()) +
kStartupPrebufferMs * 1000ULL;
bool still_current = true;
while (still_current &&
running_.load(std::memory_order_acquire) &&
!paused_.load(std::memory_order_acquire) &&
static_cast<uint64_t>(esp_timer_get_time()) <
deadline_us) {
vTaskDelay(pdMS_TO_TICKS(10));
std::lock_guard<std::mutex> lock(mutex_);
still_current =
controller_.IsCurrent(slot.session_id);
}
}
} else if (last_write_end_us_ != 0 &&
static_cast<uint64_t>(esp_timer_get_time()) -
last_write_end_us_ >
kFrameDurationMs * 1000ULL) {
// De-jitter rebuild: reaching this frame more than one period
// after the previous write finished means the queue ran dry and
// the DMA is draining right now. Hold briefly for a companion
// frame so the dry spell plays as one pause instead of a
// micro-gap per frame. Also covers the post-candidate resume,
// which restarts with zero cushion.
bool input_ended = false;
{
std::lock_guard<std::mutex> lock(mutex_);
input_ended = !controller_.IsCurrent(slot.session_id) ||
controller_.snapshot().input_ended;
}
const uint64_t hold_deadline_us =
static_cast<uint64_t>(esp_timer_get_time()) +
kDryRebuildHoldMs * 1000ULL;
while (!input_ended &&
running_.load(std::memory_order_acquire) &&
!paused_.load(std::memory_order_acquire) &&
uxQueueMessagesWaiting(ready_frames_) == 0 &&
static_cast<uint64_t>(esp_timer_get_time()) <
hold_deadline_us) {
vTaskDelay(pdMS_TO_TICKS(10));
std::lock_guard<std::mutex> lock(mutex_);
input_ended = controller_.snapshot().input_ended;
}
}
bool process = false;
{
std::lock_guard<std::mutex> lock(mutex_);
process = controller_.BeginFrame(slot.session_id, NowMs());
if (!process) {
controller_.RecordStaleFrame();
}
}
if (!process) {
ReleaseSlot(slot_index);
continue;
}
size_t decoded_samples = 0;
bool decoded = false;
if (slot.format == FrameFormat::kOpus) {
if (decoder_reset_pending_.exchange(
false, std::memory_order_acq_rel)) {
decoder_.Reset();
}
decoded = decoder_.Decode(slot.payload, slot.payload_size,
decode_buffer_, kSamplesPerFrame, &decoded_samples);
} else {
decoded_samples = slot.sample_count;
std::memcpy(decode_buffer_, slot.payload,
decoded_samples * sizeof(int16_t));
decoded = true;
}
PlaybackSessionId completed = 0;
PlaybackSessionId failed = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!controller_.IsCurrent(slot.session_id)) {
controller_.RecordStaleFrame();
} else if (!decoded) {
failed = controller_.Fail(slot.session_id);
DrainReadyQueueLocked();
} else {
// Hold the ownership lock across the synchronous I2S write.
// A preemption waits at most one 60 ms frame, and after it
// returns no frame from the old session can reach the PA.
IPlaybackReferenceSink* reference_sink
= reference_sink_.load(std::memory_order_acquire);
if (reference_sink != nullptr) {
// Mirror the software volume applied inside Write(). AEC
// must receive the PCM amplitude that reaches the DAC,
// not the unscaled decoder output.
const int32_t gain =
static_cast<int32_t>(output_.VolumePercent()) *
256 / 100;
for (size_t index = 0;
index < decoded_samples;
++index) {
const int32_t scaled =
(static_cast<int32_t>(decode_buffer_[index]) *
gain) >> 8;
reference_buffer_[index] =
static_cast<int16_t>(std::clamp<int32_t>(
scaled, -32768, 32767));
}
reference_sink->OnPlaybackReference(
reference_buffer_, decoded_samples);
}
if (slot.session_id != health_session_) {
FlushPlayoutHealth();
health_session_ = slot.session_id;
health_skip_gap_ = true;
health_depth_min_ = ready_depth;
health_depth_max_ = ready_depth;
}
const uint64_t write_start_us =
static_cast<uint64_t>(esp_timer_get_time());
if (!health_skip_gap_ && last_write_end_us_ != 0) {
const uint32_t gap_ms = static_cast<uint32_t>(
(write_start_us - last_write_end_us_) / 1000ULL);
health_max_gap_ms_ =
std::max(health_max_gap_ms_, gap_ms);
if (gap_ms > kFrameDurationMs) {
health_gap_over_frame_++;
}
if (gap_ms > 90) {
health_gap_over_dma_++;
}
}
health_skip_gap_ = false;
health_frames_++;
health_depth_min_ =
std::min(health_depth_min_, ready_depth);
health_depth_max_ =
std::max(health_depth_max_, ready_depth);
const bool written
= output_.Write(decode_buffer_, decoded_samples);
last_write_end_us_ =
static_cast<uint64_t>(esp_timer_get_time());
controller_.FinishFrame(slot.session_id, written, NowMs());
if (!written) {
failed = controller_.Fail(slot.session_id);
DrainReadyQueueLocked();
} else {
completed = controller_.TryComplete();
}
}
}
ReleaseSlot(slot_index);
if (failed != 0 || completed != 0) {
FlushPlayoutHealth();
}
if (failed != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackFailed, failed);
} else if (completed != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed);
}
}
FlushPlayoutHealth();
xSemaphoreGive(stopped_signal_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void PlaybackPipeline::FlushPlayoutHealth()
{
if (health_frames_ > 1) {
// One line per session. gaps>frame means the queue ran dry longer
// than one frame period (cushion gone); gaps>dma means the 90 ms
// I2S buffer also drained and the break reached the speaker.
ESP_LOGI(kTag,
"playout health id=%lu frames=%lu max_gap=%lums "
"gaps>frame=%lu gaps>dma=%lu depth=%lu..%lu",
static_cast<unsigned long>(health_session_),
static_cast<unsigned long>(health_frames_),
static_cast<unsigned long>(health_max_gap_ms_),
static_cast<unsigned long>(health_gap_over_frame_),
static_cast<unsigned long>(health_gap_over_dma_),
static_cast<unsigned long>(health_depth_min_),
static_cast<unsigned long>(health_depth_max_));
}
health_session_ = 0;
health_frames_ = 0;
health_max_gap_ms_ = 0;
health_gap_over_frame_ = 0;
health_gap_over_dma_ = 0;
health_depth_min_ = 0;
health_depth_max_ = 0;
last_write_end_us_ = 0;
health_skip_gap_ = false;
}
bool PlaybackPipeline::SubmitFrame(PlaybackSessionId session_id,
FrameFormat format, const void* data, size_t byte_count,
size_t sample_count)
{
if (!running_.load(std::memory_order_acquire) || data == nullptr
|| byte_count > kMaxFrameBytes) {
return false;
}
uint16_t slot_index = 0;
if (xQueueReceive(free_slots_, &slot_index, 0) != pdTRUE) {
const PlaybackSessionId already_logged
= backpressure_logged_session_.exchange(
session_id, std::memory_order_acq_rel);
if (already_logged != session_id) {
ESP_LOGD(kTag,
"producer pacing session=%lu; frame pool temporarily full",
static_cast<unsigned long>(session_id));
}
return false;
}
FrameSlot& slot = frame_pool_[slot_index];
slot.session_id = session_id;
slot.format = format;
slot.payload_size = static_cast<uint16_t>(byte_count);
slot.sample_count = static_cast<uint16_t>(sample_count);
std::memcpy(slot.payload, data, byte_count);
{
std::lock_guard<std::mutex> lock(mutex_);
if (!controller_.QueueFrame(session_id, NowMs())) {
controller_.RecordStaleFrame();
ReleaseSlot(slot_index);
return false;
}
if (xQueueSend(ready_frames_, &slot_index, 0) != pdTRUE) {
controller_.RollbackQueuedFrame(session_id);
ReleaseSlot(slot_index);
ESP_LOGE(kTag, "ready queue unexpectedly full");
return false;
}
}
return true;
}
void PlaybackPipeline::DrainReadyQueueLocked()
{
uint16_t slot_index = 0;
while (xQueueReceive(ready_frames_, &slot_index, 0) == pdTRUE) {
ReleaseSlot(slot_index);
}
}
void PlaybackPipeline::ReleaseSlot(uint16_t slot_index)
{
if (xQueueSend(free_slots_, &slot_index, 0) != pdTRUE) {
ESP_LOGE(kTag, "failed to release frame slot=%u", slot_index);
}
}
void PlaybackPipeline::CheckTimeout()
{
PlaybackTimeoutResult timeout;
{
std::lock_guard<std::mutex> lock(mutex_);
timeout = controller_.CheckTimeout(
NowMs(), kProducerStartTimeoutMs, kStalledTimeoutMs);
if (timeout.session_id != 0) {
DrainReadyQueueLocked();
decoder_.Reset();
}
}
if (timeout.session_id != 0) {
ESP_LOGE(kTag, "session timeout id=%lu reason=%s",
static_cast<unsigned long>(timeout.session_id),
ToString(timeout.reason));
PublishPlaybackEvent(AppEventType::kPlaybackFailed, timeout.session_id);
}
}
void PlaybackPipeline::PublishPlaybackEvent(AppEventType type,
PlaybackSessionId session_id, PlaybackSessionId replacement_session_id)
{
IEventPublisher* publisher = publisher_.load(std::memory_order_acquire);
if (publisher == nullptr
|| !publisher->Publish(
AppEvent::Make(type, session_id, 0, replacement_session_id))) {
ESP_LOGE(kTag, "failed to publish playback event=%s session=%lu",
ToString(type), static_cast<unsigned long>(session_id));
}
}
uint64_t PlaybackPipeline::NowMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace borla

View File

@@ -0,0 +1,151 @@
#pragma once
#include "audio/audio_output.h"
#include "audio/opus_frame_decoder.h"
#include "audio/playback_controller.h"
#include "audio/voice_frame_processor.h"
#include "ports/event_publisher.h"
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <mutex>
namespace borla {
class PlaybackPipeline final {
public:
static constexpr uint32_t kSampleRate = 48000;//24000;
static constexpr uint32_t kFrameDurationMs = 60;
static constexpr size_t kSamplesPerFrame =
kSampleRate * kFrameDurationMs / 1000;
static constexpr size_t kMaxFrameBytes =
kSamplesPerFrame * sizeof(int16_t);
static constexpr size_t kMaxOpusBytes = 1536;
static constexpr size_t kFramePoolSize = 48;
explicit PlaybackPipeline(IAudioOutput& output);
~PlaybackPipeline();
void SetEventPublisher(IEventPublisher* publisher);
// True while a session still owns the speaker. Used to hold off a reboot
// until the prompt that explains the reboot has actually been heard.
bool Active() const
{
std::lock_guard<std::mutex> lock(mutex_);
return controller_.snapshot().active;
}
void SetReferenceSink(IPlaybackReferenceSink* sink)
{
reference_sink_.store(sink);
}
bool Initialize();
bool Start();
void Stop();
PlaybackStartResult StartSession(
PlaybackSource source,
PlaybackPriority priority,
PlaybackSessionId requested_id = 0);
bool SubmitOpus(
PlaybackSessionId session_id,
const uint8_t* data,
size_t size);
bool SubmitPcm(
PlaybackSessionId session_id,
const int16_t* samples,
size_t sample_count);
bool EndInput(PlaybackSessionId session_id);
void SetPaused(bool paused);
bool Cancel(PlaybackSessionId session_id = 0);
PlaybackSessionSnapshot Snapshot() const;
PlaybackMetrics Metrics() const;
private:
enum class FrameFormat : uint8_t {
kOpus,
kPcm,
};
struct FrameSlot {
PlaybackSessionId session_id = 0;
FrameFormat format = FrameFormat::kOpus;
uint16_t payload_size = 0;
uint16_t sample_count = 0;
alignas(int16_t) uint8_t payload[kMaxFrameBytes]{};
};
static void TaskEntry(void* context);
void Run();
void FlushPlayoutHealth();
bool SubmitFrame(
PlaybackSessionId session_id,
FrameFormat format,
const void* data,
size_t byte_count,
size_t sample_count);
void DrainReadyQueueLocked();
void ReleaseSlot(uint16_t slot_index);
void CheckTimeout();
void PublishPlaybackEvent(
AppEventType type,
PlaybackSessionId session_id,
PlaybackSessionId replacement_session_id = 0);
static uint64_t NowMs();
IAudioOutput& output_;
std::atomic<IEventPublisher*> publisher_{nullptr};
std::atomic<IPlaybackReferenceSink*> reference_sink_{nullptr};
OpusFrameDecoder decoder_;
mutable std::mutex mutex_;
PlaybackController controller_;
FrameSlot* frame_pool_ = nullptr;
int16_t* decode_buffer_ = nullptr;
int16_t* reference_buffer_ = nullptr;
QueueHandle_t free_slots_ = nullptr;
QueueHandle_t ready_frames_ = nullptr;
StaticQueue_t free_slots_storage_{};
StaticQueue_t ready_frames_storage_{};
uint8_t free_slots_queue_bytes_[kFramePoolSize * sizeof(uint16_t)]{};
uint8_t ready_frames_queue_bytes_[kFramePoolSize * sizeof(uint16_t)]{};
SemaphoreHandle_t stopped_signal_ = nullptr;
StaticSemaphore_t stopped_signal_storage_{};
TaskHandle_t task_ = nullptr;
bool initialized_ = false;
std::atomic<bool> running_{false};
std::atomic<bool> paused_{false};
// Playout health accounting, owned exclusively by the speaker task.
// The server paces frames in real time after a 6-frame (360 ms) burst,
// so the whole jitter cushion is that burst plus the 90 ms I2S DMA.
// These counters turn "偶发卡顿" into one measurable line per session:
// an inter-write gap > 60 ms means the cushion fully eroded, > 90 ms
// means the DMA drained and the break was audible.
PlaybackSessionId health_session_ = 0;
uint64_t last_write_end_us_ = 0;
bool health_skip_gap_ = false;
uint32_t health_frames_ = 0;
uint32_t health_gap_over_frame_ = 0;
uint32_t health_gap_over_dma_ = 0;
uint32_t health_max_gap_ms_ = 0;
uint32_t health_depth_min_ = 0;
uint32_t health_depth_max_ = 0;
// Set by StartSession/Cancel (application task); consumed by Run() right
// before Decode(), the only place allowed to touch decoder_ while the
// playback task lives. Decode() runs outside mutex_, so a direct Reset()
// from another task would race it.
std::atomic<bool> decoder_reset_pending_{false};
std::atomic<PlaybackSessionId> backpressure_logged_session_{0};
};
} // namespace borla

View File

@@ -0,0 +1,68 @@
#include "audio/voice_activity_detector.h"
#include <cmath>
namespace borla {
VoiceActivityDetector::VoiceActivityDetector(
VoiceActivityConfig config)
: config_(config)
{
if (config_.start_frames == 0) {
config_.start_frames = 1;
}
if (config_.stop_frames == 0) {
config_.stop_frames = 1;
}
}
VoiceActivityResult VoiceActivityDetector::Process(
const int16_t* samples,
size_t sample_count)
{
if (samples == nullptr || sample_count == 0) {
return VoiceActivityResult::kSilence;
}
uint64_t energy = 0;
for (size_t index = 0; index < sample_count; ++index) {
const int32_t sample = samples[index];
energy += static_cast<uint64_t>(sample * sample);
}
last_rms_ = static_cast<uint32_t>(
std::sqrt(
static_cast<double>(energy) /
static_cast<double>(sample_count)));
const bool loud = last_rms_ >= config_.rms_threshold;
if (!speech_active_) {
quiet_frames_ = 0;
loud_frames_ = loud ? static_cast<uint8_t>(loud_frames_ + 1) : 0;
if (loud_frames_ >= config_.start_frames) {
speech_active_ = true;
loud_frames_ = 0;
return VoiceActivityResult::kSpeechStarted;
}
return VoiceActivityResult::kSilence;
}
if (loud) {
quiet_frames_ = 0;
return VoiceActivityResult::kSpeech;
}
if (++quiet_frames_ >= config_.stop_frames) {
speech_active_ = false;
quiet_frames_ = 0;
return VoiceActivityResult::kSpeechEnded;
}
return VoiceActivityResult::kSpeech;
}
void VoiceActivityDetector::Reset()
{
loud_frames_ = 0;
quiet_frames_ = 0;
speech_active_ = false;
last_rms_ = 0;
}
} // namespace borla

View File

@@ -0,0 +1,41 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
enum class VoiceActivityResult : uint8_t {
kSilence,
kSpeechStarted,
kSpeech,
kSpeechEnded,
};
struct VoiceActivityConfig {
uint16_t rms_threshold = 650;
uint8_t start_frames = 2;
uint8_t stop_frames = 13;
};
class VoiceActivityDetector final {
public:
explicit VoiceActivityDetector(
VoiceActivityConfig config = {});
VoiceActivityResult Process(
const int16_t* samples,
size_t sample_count);
void Reset();
bool speech_active() const { return speech_active_; }
uint32_t LastRms() const { return last_rms_; }
private:
VoiceActivityConfig config_;
uint8_t loud_frames_ = 0;
uint8_t quiet_frames_ = 0;
bool speech_active_ = false;
uint32_t last_rms_ = 0;
};
} // namespace borla

403
main/audio/voice_dsp.cc Normal file
View File

@@ -0,0 +1,403 @@
#include "audio/voice_dsp.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace borla {
namespace {
constexpr const char* kTag = "VoiceDsp2";
constexpr float kTargetPeak = 0.42f;
constexpr float kMinimumGain = 0.8f;
constexpr float kMaximumGain = 4.0f;
constexpr float kBargeInMaximumGain = 1.8f;
constexpr float kNoiseGateAttenuation = 0.1f;
constexpr float kBargeInNoiseGateAttenuation = 0.05f;
// esp-sr allocates its AEC and NS state with plain malloc, and this build
// routes allocations larger than 16 KB to PSRAM. An earlier revision forced
// them into internal SRAM on the theory that the adaptive filter running over
// the PSRAM bus explained the AEC's per-frame cost. Field measurement killed
// that theory twice over: with the states internal the AEC still cost ~50 ms
// per 60 ms frame (placement was worth at most a few ms), and the ~50 KB of
// internal RAM they consumed starved lwIP (free=4415 min=531) until a TLS
// send failed mid-conversation and dropped the WebSocket. PSRAM placement is
// therefore the correct trade; the probes below keep reporting where the
// states actually land so the question stays answered.
} // namespace
VoiceDsp::~VoiceDsp()
{
DisableEchoCancellation();
if (ns_ != nullptr) {
ns_destroy(ns_);
}
}
bool VoiceDsp::InitializeNoiseSuppression()
{
if (ns_ != nullptr) {
return true;
}
const size_t internal_before =
heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
ns_ = ns_pro_create(10, 2, 16000);
if (ns_ == nullptr) {
ESP_LOGE(kTag, "NS initialization failed");
return false;
}
ESP_LOGI(kTag, "NS state internal=%d bytes",
static_cast<int>(
internal_before -
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)));
return true;
}
bool VoiceDsp::EnableEchoCancellation(bool barge_in_profile)
{
if (aec_ != nullptr) {
// Both profiles use identical aec_create parameters — the flag only
// selects post-processing (NS off + conservative AGC for barge-in).
// Never tear the state down for a profile flip: aec_create grabs
// whatever internal RAM is free at that instant and keeps it for the
// rest of the session, so a mid-session re-create once confiscated
// the websocket's reconnect budget the moment it was released
// (internal free pinned at 75 bytes, every TLS attempt failing).
if (barge_in_profile_ != barge_in_profile) {
barge_in_profile_ = barge_in_profile;
Reset();
}
return true;
}
// FD_LOW_COST left speech-shaped TTS residue at RMS 4k-12k on this
// board. VOIP_HIGH_PERF/filter=4 is the field-proven ESP32-S3 setup for
// both barge-in and calls. The profile flag selects conservative
// post-processing for barge-in; it no longer selects a weaker AEC.
const aec_mode_t mode = AEC_MODE_VOIP_HIGH_PERF;
const int filter_length = 4;
// The deltas logged below say where the state actually landed — see the
// note above InitializeNoiseSuppression for why PSRAM is the intended
// answer.
const size_t internal_before =
heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
const size_t psram_before =
heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
aec_ = aec_create(16000, filter_length, 1, mode);
ESP_LOGI(kTag,
"AEC state allocated internal=%d psram=%d (bytes)",
static_cast<int>(
internal_before -
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
static_cast<int>(
psram_before -
heap_caps_get_free_size(MALLOC_CAP_SPIRAM)));
if (aec_ == nullptr) {
ESP_LOGE(kTag, "AEC initialization failed");
return false;
}
aec_chunk_samples_ = aec_get_chunksize(aec_);
if (aec_chunk_samples_ <= 0 ||
aec_chunk_samples_ >
static_cast<int>(kMaximumAecChunk)) {
ESP_LOGE(kTag, "unsupported AEC chunk=%d",
aec_chunk_samples_);
DisableEchoCancellation();
return false;
}
barge_in_profile_ = barge_in_profile;
Reset();
ESP_LOGI(kTag, "AEC enabled mode=%s chunk=%d filter=%d profile=%s",
aec_get_mode_string(mode),
aec_chunk_samples_,
filter_length,
barge_in_profile ? "barge_in" : "call");
return true;
}
bool VoiceDsp::PrewarmEchoCancellation()
{
if (aec_ != nullptr) {
return true;
}
// aec_create is opportunistic: it takes whatever internal RAM is free at
// that instant (observed 2.6-12.4 KB across boots) and the handle then
// lives for the whole session. Created lazily at the first TTS it once
// grabbed 12 KB exactly as the dropped websocket released its buffers —
// after that no TLS reconnect could ever allocate again. Placement is
// speed-neutral on this board (~50 ms/frame measured both ways), so the
// state belongs in PSRAM: create it ONCE at boot, before the WiFi driver
// exists, with guard blocks squatting on internal RAM so esp-sr's greedy
// pass lands in PSRAM, then release the guards.
// Guard blocks sized to the CURRENT largest free block, not a fixed
// size: the boot heap is a handful of region tails and DMA-pool chunks,
// and a fixed-8KB loop bailed on the first sub-8KB fragment while
// esp-sr's many small allocations then filled 24.9 KB of exactly those
// fragments — leaving the WiFi driver so dry that phy_track_pll_init's
// esp_timer_create aborted the boot.
constexpr uint32_t kGuardCaps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT;
constexpr size_t kInternalFloorBytes = 8 * 1024;
constexpr size_t kMinimumGuardBytes = 1024;
constexpr size_t kGuardHeadroomBytes = 256;
std::array<void*, 32> guards{};
size_t guard_count = 0;
size_t guarded_bytes = 0;
while (guard_count < guards.size() &&
heap_caps_get_free_size(kGuardCaps) > kInternalFloorBytes) {
const size_t largest =
heap_caps_get_largest_free_block(kGuardCaps);
if (largest < kMinimumGuardBytes) {
break;
}
const size_t take = largest - kGuardHeadroomBytes;
void* block = heap_caps_malloc(take, kGuardCaps);
if (block == nullptr) {
break;
}
guards[guard_count++] = block;
guarded_bytes += take;
}
ESP_LOGI(kTag,
"AEC prewarm guards=%u held=%u free=%u largest=%u",
static_cast<unsigned>(guard_count),
static_cast<unsigned>(guarded_bytes),
static_cast<unsigned>(heap_caps_get_free_size(kGuardCaps)),
static_cast<unsigned>(
heap_caps_get_largest_free_block(kGuardCaps)));
const bool enabled = EnableEchoCancellation(true);
for (size_t index = 0; index < guard_count; ++index) {
heap_caps_free(guards[index]);
}
if (!enabled) {
ESP_LOGE(kTag, "AEC prewarm failed");
return false;
}
Reset();
return true;
}
void VoiceDsp::SuspendEchoCancellation()
{
// Keep the adaptive filter warm across TTS turns. Reset() clears only
// frame accumulators and AGC state; the ESP AEC handle retains its learned
// acoustic path.
if (aec_ != nullptr) {
Reset();
}
}
void VoiceDsp::DisableEchoCancellation()
{
if (aec_ != nullptr) {
aec_destroy(aec_);
aec_ = nullptr;
}
aec_chunk_samples_ = 0;
barge_in_profile_ = false;
mic_count_ = 0;
ref_count_ = 0;
clean_count_ = 0;
}
void VoiceDsp::Reset()
{
mic_count_ = 0;
ref_count_ = 0;
clean_count_ = 0;
if (aec_chunk_samples_ > 0) {
clean_count_ = static_cast<size_t>(aec_chunk_samples_);
std::fill_n(clean_acc_.data(), clean_count_, 0);
}
envelope_ = 0.08f;
gain_ = 1.0f;
}
bool VoiceDsp::Process(
const int16_t* microphone,
const int16_t* reference,
bool echo_cancellation,
int16_t* output,
size_t sample_count,
int16_t* wake_tap)
{
if (microphone == nullptr || output == nullptr ||
sample_count != kFrameSamples) {
return false;
}
bool valid = true;
if (echo_cancellation) {
valid = reference != nullptr &&
ProcessAec(
microphone, reference, output, sample_count);
} else {
std::memcpy(
output,
microphone,
sample_count * sizeof(int16_t));
}
if (!valid) {
return false;
}
if (wake_tap != nullptr) {
std::memcpy(
wake_tap, output, sample_count * sizeof(int16_t));
}
ProcessNsAndAgc(
output,
sample_count,
echo_cancellation && barge_in_profile_);
return true;
}
bool VoiceDsp::ProcessAec(
const int16_t* microphone,
const int16_t* reference,
int16_t* output,
size_t sample_count)
{
if (aec_ == nullptr ||
mic_count_ + sample_count > mic_acc_.size() ||
ref_count_ + sample_count > ref_acc_.size()) {
return false;
}
std::memcpy(
mic_acc_.data() + mic_count_,
microphone,
sample_count * sizeof(int16_t));
std::memcpy(
ref_acc_.data() + ref_count_,
reference,
sample_count * sizeof(int16_t));
mic_count_ += sample_count;
ref_count_ += sample_count;
const size_t chunk =
static_cast<size_t>(aec_chunk_samples_);
while (mic_count_ >= chunk && ref_count_ >= chunk) {
if (clean_count_ + chunk > clean_acc_.size()) {
return false;
}
aec_process(
aec_,
mic_acc_.data(),
ref_acc_.data(),
aec_chunk_.data());
std::memmove(
mic_acc_.data(),
mic_acc_.data() + chunk,
(mic_count_ - chunk) * sizeof(int16_t));
std::memmove(
ref_acc_.data(),
ref_acc_.data() + chunk,
(ref_count_ - chunk) * sizeof(int16_t));
mic_count_ -= chunk;
ref_count_ -= chunk;
std::memcpy(
clean_acc_.data() + clean_count_,
aec_chunk_.data(),
chunk * sizeof(int16_t));
clean_count_ += chunk;
// Hand the core back between chunks. This loop runs 3-4 times per 60 ms
// frame on the capture task at priority 8, and aec_process() never
// blocks, so without this the idle task on this core gets no runtime for
// as long as duplex is active and the task watchdog fires. taskYIELD()
// would not help: the idle task sits at priority 0 and only a blocking
// delay lets it run. The previous firmware carried the same one-tick
// yield in the same position for the same reason. At 1000 Hz a tick is
// 1 ms, so the cost is ~4 ms per frame against a 60 ms budget.
vTaskDelay(1);
}
if (clean_count_ < sample_count) {
return false;
}
std::memcpy(
output,
clean_acc_.data(),
sample_count * sizeof(int16_t));
std::memmove(
clean_acc_.data(),
clean_acc_.data() + sample_count,
(clean_count_ - sample_count) * sizeof(int16_t));
clean_count_ -= sample_count;
return true;
}
void VoiceDsp::ProcessNsAndAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile)
{
// Full NS remains active for normal capture and calls. During TTS it can
// reshape residual echo and costs CPU, so barge-in uses high-performance
// AEC plus the conservative gate/AGC below.
if (ns_ != nullptr && !barge_in_profile) {
for (size_t offset = 0;
offset + kNsFrameSamples <= sample_count;
offset += kNsFrameSamples) {
ns_process(
ns_, samples + offset, ns_frame_.data());
std::memcpy(
samples + offset,
ns_frame_.data(),
kNsFrameSamples * sizeof(int16_t));
}
}
ApplyAgc(samples, sample_count, barge_in_profile);
}
void VoiceDsp::ApplyAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile)
{
int32_t peak = 0;
uint64_t energy = 0;
for (size_t index = 0; index < sample_count; ++index) {
const int32_t value = samples[index];
peak = std::max(peak, std::abs(value));
energy += static_cast<uint64_t>(value * value);
}
const float peak_normalized =
static_cast<float>(peak) / 32768.0f;
const float rms = std::sqrt(
static_cast<float>(energy) /
static_cast<float>(sample_count)) / 32768.0f;
if (rms < 0.004f && peak_normalized < 0.015f) {
const float attenuation = barge_in_profile
? kBargeInNoiseGateAttenuation
: kNoiseGateAttenuation;
for (size_t index = 0; index < sample_count; ++index) {
samples[index] =
static_cast<int16_t>(samples[index] * attenuation);
}
return;
}
const float alpha =
peak_normalized > envelope_ ? 0.45f : 0.12f;
envelope_ += alpha * (peak_normalized - envelope_);
envelope_ = std::max(envelope_, 0.01f);
const float target = std::clamp(
kTargetPeak / envelope_,
kMinimumGain,
barge_in_profile
? kBargeInMaximumGain
: kMaximumGain);
gain_ += 0.18f * (target - gain_);
for (size_t index = 0; index < sample_count; ++index) {
const float value = std::clamp(
static_cast<float>(samples[index]) * gain_,
-32768.0f,
32767.0f);
samples[index] = static_cast<int16_t>(value);
}
}
} // namespace borla

84
main/audio/voice_dsp.h Normal file
View File

@@ -0,0 +1,84 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <esp_aec.h>
#include <esp_ns.h>
namespace borla {
class VoiceDsp final {
public:
static constexpr size_t kFrameSamples = 960;
~VoiceDsp();
bool InitializeNoiseSuppression();
// Creates the AEC state once at boot (guarded so it lands in PSRAM) and
// leaves it suspended. See the implementation for why lazy creation was
// a session-killer.
bool PrewarmEchoCancellation();
bool EnableEchoCancellation(bool barge_in_profile);
void SuspendEchoCancellation();
void DisableEchoCancellation();
void Reset();
// wake_tap, when provided, receives the post-AEC pre-NS/AGC samples —
// the signal WakeNet should hear. The AGC pumps during double-talk and a
// gain-chopped phrase defeats the detector.
bool Process(
const int16_t* microphone,
const int16_t* reference,
bool echo_cancellation,
int16_t* output,
size_t sample_count,
int16_t* wake_tap = nullptr);
// Diagnostics. Cheap accessors so the frame statistics can report what the
// DSP is actually doing rather than what the policy asked for.
bool EchoCancellationActive() const { return aec_ != nullptr; }
bool NoiseSuppressionActive() const { return ns_ != nullptr; }
// NS is deliberately skipped in the barge-in profile; see ProcessNsAndAgc.
bool BargeInProfile() const { return barge_in_profile_; }
int AecChunkSamples() const { return aec_chunk_samples_; }
float AgcGain() const { return gain_; }
float AgcEnvelope() const { return envelope_; }
private:
static constexpr size_t kAccumulatorCapacity = 4096;
static constexpr size_t kMaximumAecChunk = 1024;
static constexpr size_t kNsFrameSamples = 160;
bool ProcessAec(
const int16_t* microphone,
const int16_t* reference,
int16_t* output,
size_t sample_count);
void ProcessNsAndAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile);
void ApplyAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile);
aec_handle_t* aec_ = nullptr;
ns_handle_t ns_ = nullptr;
int aec_chunk_samples_ = 0;
bool barge_in_profile_ = false;
std::array<int16_t, kAccumulatorCapacity> mic_acc_{};
std::array<int16_t, kAccumulatorCapacity> ref_acc_{};
std::array<int16_t, kAccumulatorCapacity> clean_acc_{};
std::array<int16_t, kMaximumAecChunk> aec_chunk_{};
std::array<int16_t, kNsFrameSamples> ns_frame_{};
size_t mic_count_ = 0;
size_t ref_count_ = 0;
size_t clean_count_ = 0;
float envelope_ = 0.08f;
float gain_ = 1.0f;
};
} // namespace borla

View File

@@ -0,0 +1,36 @@
#pragma once
#include "core/runtime_state.h"
#include <cstddef>
#include <cstdint>
namespace borla {
class IVoiceFrameProcessor {
public:
virtual ~IVoiceFrameProcessor() = default;
virtual void ApplyPolicy(AudioPolicy policy) = 0;
virtual bool Process(
AudioPolicy policy,
const int16_t* input,
size_t sample_count,
int16_t* output,
size_t output_capacity) = 0;
};
class IPlaybackReferenceSink {
public:
virtual ~IPlaybackReferenceSink() = default;
virtual void OnPlaybackReference(
const int16_t* samples,
size_t sample_count) = 0;
// Called when a new playback session begins. Frames queued for the
// previous session are acoustically unrelated to what the microphone is
// about to hear, and leaving them in the ring offsets every reference by
// however many were stranded. Emptying it here phase-locks the reference
// stream to the session that is actually about to reach the speaker.
virtual void ResetPlaybackReference() = 0;
};
} // namespace borla

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

392
main/audio/voice_frontend.h Normal file
View File

@@ -0,0 +1,392 @@
#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 <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
#include <freertos/queue.h>
#include <freertos/task.h>
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<int16_t, kWakeAccumulatorSamples> wake_accumulator{};
std::array<
std::array<int16_t, kFrameSamples>,
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<int16_t, kFrameSamples> 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<IEventPublisher*> publisher_{nullptr};
mutable std::mutex processor_mutex_;
AudioPolicy policy_ = AudioPolicy::kOff;
WakeWordDetector wake_word_;
VoiceDsp dsp_;
VoiceActivityDetector vad_;
std::unique_ptr<ScratchBuffers, PsramObjectDeleter<ScratchBuffers>>
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<bool> 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<uint64_t> 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<uint64_t> 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

View File

@@ -0,0 +1,103 @@
#include "audio/wake_word_detector.h"
#include <esp_log.h>
#include <esp_wn_iface.h>
#include <esp_wn_models.h>
#include <model_path.h>
#include <cstdio>
namespace borla {
namespace {
constexpr const char* kTag = "WakeWord2";
constexpr const char* kBorlaModelHint = "ni3hao3bo1le4";
} // namespace
WakeWordDetector::~WakeWordDetector()
{
Deinitialize();
}
bool WakeWordDetector::Initialize()
{
if (handle_ != nullptr) {
return true;
}
srmodel_list_t* models = esp_srmodel_init("model");
if (models == nullptr) {
ESP_LOGE(kTag, "model partition initialization failed");
return false;
}
char* selected = esp_srmodel_filter(
models, ESP_WN_PREFIX, kBorlaModelHint);
if (selected == nullptr) {
selected = esp_srmodel_filter(
models, ESP_WN_PREFIX, nullptr);
}
if (selected == nullptr) {
ESP_LOGE(kTag, "no WakeNet model in model partition");
esp_srmodel_deinit(models);
return false;
}
std::snprintf(
model_name_.data(), model_name_.size(), "%s", selected);
interface_ = esp_wn_handle_from_name(model_name_.data());
if (interface_ == nullptr) {
ESP_LOGE(kTag, "WakeNet interface lookup failed");
esp_srmodel_deinit(models);
return false;
}
handle_ = interface_->create(
model_name_.data(), DET_MODE_90);
esp_srmodel_deinit(models);
if (handle_ == nullptr) {
ESP_LOGE(kTag, "WakeNet instance creation failed");
interface_ = nullptr;
return false;
}
auto* model = static_cast<model_iface_data_t*>(handle_);
chunk_samples_ = static_cast<size_t>(
interface_->get_samp_chunksize(model));
const int sample_rate = interface_->get_samp_rate(model);
if (chunk_samples_ == 0 || sample_rate != 16000) {
ESP_LOGE(kTag, "invalid model format rate=%d chunk=%u",
sample_rate,
static_cast<unsigned>(chunk_samples_));
Deinitialize();
return false;
}
ESP_LOGI(kTag, "ready model=%s chunk=%u rate=%d",
model_name_.data(),
static_cast<unsigned>(chunk_samples_),
sample_rate);
return true;
}
void WakeWordDetector::Deinitialize()
{
if (interface_ != nullptr && handle_ != nullptr) {
interface_->destroy(
static_cast<model_iface_data_t*>(handle_));
}
interface_ = nullptr;
handle_ = nullptr;
chunk_samples_ = 0;
}
bool WakeWordDetector::Detect(
const int16_t* samples,
size_t sample_count)
{
if (interface_ == nullptr || handle_ == nullptr ||
samples == nullptr || sample_count != chunk_samples_) {
return false;
}
const int result = interface_->detect(
static_cast<model_iface_data_t*>(handle_),
const_cast<int16_t*>(samples));
return result > 0;
}
} // namespace borla

View File

@@ -0,0 +1,29 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <esp_wn_iface.h>
namespace borla {
class WakeWordDetector final {
public:
~WakeWordDetector();
bool Initialize();
void Deinitialize();
bool Detect(const int16_t* samples, size_t sample_count);
bool initialized() const { return handle_ != nullptr; }
size_t ChunkSamples() const { return chunk_samples_; }
const char* ModelName() const { return model_name_.data(); }
private:
const esp_wn_iface_t* interface_ = nullptr;
void* handle_ = nullptr;
size_t chunk_samples_ = 0;
std::array<char, 64> model_name_{};
};
} // namespace borla