Files
bolar_1/main/audio/audio_service.cc

1184 lines
46 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "audio_service.h"
#include <esp_log.h>
#include <cstring>
#include <cmath>
#define TAG "AudioService"
void AudioService::Initialize(AudioCodec *codec)
{
codec_ = codec;
// 创建 Opus 编码器:16kHz, 单声道, 60ms 帧
opus_encoder_ = std::make_unique<OpusEncoderWrapper>(kInputSampleRate, 1, OPUS_FRAME_DURATION_MS);
opus_encoder_->SetComplexity(3); // ESP32 上用最低复杂度保证实时性
// 创建 Opus 解码器:采样率由 ServerHello 决定,默认 24kHz
opus_decoder_ = std::make_unique<OpusDecoderWrapper>(24000, 1, OPUS_FRAME_DURATION_MS);
// 如果 codec 输入采样率 != 16kHz,需要重采样
if (codec_->input_sample_rate() != kInputSampleRate)
{
input_resampler_ = std::make_unique<OpusResampler>();
input_resampler_->Configure(codec_->input_sample_rate(), kInputSampleRate);
}
// 如果 codec 输出采样率 != 解码器采样率,需要重采样
if (codec_->output_sample_rate() != opus_decoder_->sample_rate())
{
output_resampler_ = std::make_unique<OpusResampler>();
output_resampler_->Configure(opus_decoder_->sample_rate(), codec_->output_sample_rate());
}
// AEC reference resampler: decoder rate → 16kHz (MIC rate). Only needed
// when decoder rate ≠ 16kHz; otherwise we copy as-is in call mode.
if (opus_decoder_->sample_rate() != kInputSampleRate)
{
aec_ref_resampler_ = std::make_unique<OpusResampler>();
aec_ref_resampler_->Configure(opus_decoder_->sample_rate(), kInputSampleRate);
}
ESP_LOGI(TAG, "Initialized: input=%dHz, output=%dHz, opus_enc=%dHz, opus_dec=%dHz",
codec_->input_sample_rate(), codec_->output_sample_rate(),
opus_encoder_->sample_rate(), opus_decoder_->sample_rate());
}
void AudioService::Start()
{
if (running_)
return;
running_ = true;
// 创建 3 个音频任务(与 xiaozhi 优先级对齐)
// audio_in 栈扩到 16KB:通话模式下 VoiceProcessor (AEC+NS+AGC) 在此
// task 内运行,esp_aec / ns_pro 的内部处理 + 多层 vector 操作会吃掉
// 原 6KB 栈导致 stack overflow。
xTaskCreatePinnedToCore(AudioInputTask, "audio_in", 16 * 1024, this, 8, &input_task_, 0);
xTaskCreatePinnedToCore(AudioOutputTask, "audio_out", 4 * 1024, this, 4, &output_task_, 1);
xTaskCreatePinnedToCore(OpusCodecTask, "opus_codec", 36 * 1024, this, 2, &codec_task_, 1);
ESP_LOGI(TAG, "Audio tasks started");
}
void AudioService::Stop()
{
if (!running_)
return;
running_ = false;
encode_cv_.notify_all();
decode_cv_.notify_all();
playback_cv_.notify_all();
vTaskDelay(pdMS_TO_TICKS(200));
if (input_task_)
{
vTaskDelete(input_task_);
input_task_ = nullptr;
}
if (output_task_)
{
vTaskDelete(output_task_);
output_task_ = nullptr;
}
if (codec_task_)
{
vTaskDelete(codec_task_);
codec_task_ = nullptr;
}
}
void AudioService::SetCallbacks(const AudioServiceCallbacks &callbacks)
{
callbacks_ = callbacks;
}
void AudioService::EnableVoiceProcessing(bool enable)
{
voice_processing_enabled_ = enable;
}
void AudioService::EnableCallMode(bool enable)
{
std::lock_guard<std::mutex> vp_lock(voice_processor_mutex_);
// No-op guard: SetDeviceState fires on every transition, so without this
// the Idle/Listening/Speaking path would log "Call mode disabled" a dozen
// times per second.
if (call_mode_enabled_.load() == enable)
return;
if (enable)
{
if (!voice_processor_)
{
voice_processor_ = std::make_unique<VoiceProcessor>();
}
if ((!voice_processor_->IsReady() || voice_processor_->IsLowCostMode()) && !voice_processor_->Init(false))
{
ESP_LOGE(TAG, "VoiceProcessor init failed, call AEC disabled");
voice_processor_.reset();
call_mode_enabled_ = false;
return;
}
voice_processor_->Reset();
vp_encoder_acc_.clear();
{
std::lock_guard<std::mutex> lock(aec_ref_mutex_);
aec_ref_queue_.clear();
}
call_mode_enabled_ = true;
ESP_LOGI(TAG, "Call mode enabled (AEC+NS+AGC active)");
}
else
{
call_mode_enabled_ = false;
vp_encoder_acc_.clear();
{
std::lock_guard<std::mutex> lock(aec_ref_mutex_);
aec_ref_queue_.clear();
}
if (!barge_in_mode_enabled_.load() && voice_processor_)
{
voice_processor_->Reset();
}
ESP_LOGI(TAG, "Call mode disabled");
}
}
void AudioService::EnableBargeInMode(bool enable)
{
std::lock_guard<std::mutex> vp_lock(voice_processor_mutex_);
if (barge_in_mode_enabled_.load() == enable)
return;
barge_in_mode_enabled_ = enable;
if (enable)
{
if (!voice_processor_)
{
voice_processor_ = std::make_unique<VoiceProcessor>();
}
if ((!voice_processor_->IsReady() || !voice_processor_->IsLowCostMode()) && !voice_processor_->Init(true))
{
ESP_LOGE(TAG, "VoiceProcessor init failed, TTS barge-in AEC disabled");
barge_in_mode_enabled_ = false;
return;
}
voice_processor_->Reset();
vp_encoder_acc_.clear();
{
std::lock_guard<std::mutex> lock(aec_ref_mutex_);
aec_ref_queue_.clear();
}
ESP_LOGI(TAG, "TTS barge-in enabled (FD low-cost AEC + AGC active, NS off)");
}
else
{
vp_encoder_acc_.clear();
{
std::lock_guard<std::mutex> lock(aec_ref_mutex_);
aec_ref_queue_.clear();
}
// Do not destroy the ESP-SR AEC/VAD instance on every TTS stop.
// Some esp-sr versions are fragile when create/destroy happens in a
// tight playback-control loop; keeping the low-cost processor warm
// avoids heap corruption while the disabled flag prevents processing.
if (voice_processor_)
{
voice_processor_->Reset();
}
ESP_LOGI(TAG, "TTS barge-in disabled (AEC kept warm)");
}
}
bool AudioService::InitWakeWord()
{
if (!wake_word_detector_.Initialize())
{
return false;
}
return true;
}
void AudioService::EnableWakeWordDetection(bool enable)
{
wake_word_enabled_ = enable;
}
void AudioService::EnableEnergyVad(bool enable)
{
if (enable)
{
vad_consecutive_frames_ = 0;
}
energy_vad_enabled_.store(enable);
}
void AudioService::SetPlaybackHint(bool playing)
{
playback_hint_ = playing;
// Starting a new playback session → clear any stale cancel signal left
// over from an earlier interrupted prompt.
if (playing)
{
playback_cancelled_.store(false);
}
}
// === Tone generation ===
void AudioService::PlayTone(int freq_hz, int duration_ms, float volume)
{
if (!codec_)
return;
int sample_rate = codec_->output_sample_rate();
int total_samples = sample_rate * duration_ms / 1000;
auto task = std::make_unique<AudioTask>();
task->type = AudioTask::kPlayback;
task->pcm.resize(total_samples);
float amplitude = 32767.0f * volume;
for (int i = 0; i < total_samples; i++)
{
float t = static_cast<float>(i) / sample_rate;
// Apply fade in/out (10ms) to avoid clicks
float envelope = 1.0f;
int fade_samples = sample_rate / 100; // 10ms
if (i < fade_samples)
{
envelope = static_cast<float>(i) / fade_samples;
}
else if (i > total_samples - fade_samples)
{
envelope = static_cast<float>(total_samples - i) / fade_samples;
}
task->pcm[i] = static_cast<int16_t>(amplitude * envelope * sinf(2.0f * M_PI * freq_hz * t));
}
{
std::lock_guard<std::mutex> lock(playback_mutex_);
playback_queue_.push_back(std::move(task));
}
playback_cv_.notify_one();
}
void AudioService::PlayBootSound()
{
// Two rising tones: C5 (523Hz) + E5 (659Hz)
PlayTone(523, 150, 0.25f);
PlayTone(659, 200, 0.3f);
}
void AudioService::PlayShutdownSound()
{
// Two falling tones: E5 (659Hz) + C4 (262Hz)
PlayTone(659, 150, 0.25f);
PlayTone(262, 250, 0.2f);
}
void AudioService::PlayConfigSound()
{
// Three quick ascending tones
PlayTone(440, 100, 0.25f);
PlayTone(554, 100, 0.25f);
PlayTone(659, 150, 0.3f);
}
void AudioService::PlayErrorSound()
{
// Two low tones
PlayTone(220, 200, 0.3f);
PlayTone(220, 200, 0.3f);
}
bool AudioService::IsIdle() const
{
std::lock_guard<std::mutex> lock1(const_cast<std::mutex &>(send_mutex_));
std::lock_guard<std::mutex> lock2(const_cast<std::mutex &>(playback_mutex_));
return send_queue_.empty() && playback_queue_.empty();
}
void AudioService::GetQueueEmptyStatus(bool& decode_empty, bool& play_empty)
{
std::lock_guard<std::mutex> d_lock(decode_mutex_);
std::lock_guard<std::mutex> p_lock(playback_mutex_);
decode_empty = decode_queue_.empty();
play_empty = playback_queue_.empty();
}
/*
void AudioService::WaitForPlaybackComplete(int timeout_ms)
{
int elapsed = 0;
constexpr int poll_interval = 50;
// PlayTask is an async producer — at the instant xTaskCreate returns, no
// frames have been pushed yet. Returning on the first empty observation
// races with the producer and reports completion before playback even
// starts (root cause of idle_check self-triggering its own energy VAD).
// Require the queue to be observed non-empty at least once before treating
// empty as "done".
bool seen_non_empty = false;
//2026-6-23 ckkj debug
// 初始等待:给异步任务时间启动并推入第一帧
int initial_wait_ms = 2000; // 最多等待2秒
while (elapsed < initial_wait_ms) {
if (playback_cancelled_.load()) {
ESP_LOGI(TAG, "WaitForPlaybackComplete cancelled during initial wait");
return;
}
bool empty;
{
std::lock_guard<std::mutex> lock1(decode_mutex_);
std::lock_guard<std::mutex> lock2(playback_mutex_);
empty = decode_queue_.empty() && playback_queue_.empty();
}
if (!empty) {
seen_non_empty = true;
break;
}
vTaskDelay(pdMS_TO_TICKS(poll_interval));
elapsed += poll_interval;
}
// 如果2秒后队列仍然为空,直接返回(没有需要播放的内容)
if (!seen_non_empty) {
ESP_LOGW(TAG, "WaitForPlaybackComplete: no frames pushed within %dms, returning early", initial_wait_ms);
return;
}
//debug end
// 继续等待播放完成
while (elapsed < timeout_ms) {
// Cancellation short-circuit: if ResetDecoder fired (e.g. wake word
// interrupted an alarm), return immediately so the caller can move on
// instead of polling a soon-to-be-emptied queue for the full timeout.
if (playback_cancelled_.load()) {
return;
}
bool empty;
{
std::lock_guard<std::mutex> lock1(decode_mutex_);
std::lock_guard<std::mutex> lock2(playback_mutex_);
empty = decode_queue_.empty() && playback_queue_.empty();
}
if (!empty) {
seen_non_empty = true;
} else if (seen_non_empty) {
return;
}
vTaskDelay(pdMS_TO_TICKS(poll_interval));
elapsed += poll_interval;
}
}
*/
/*void AudioService::WaitForPlaybackComplete(int timeout_ms)
{
constexpr int fast_exit_threshold = 300;
int elapsed = 0;
constexpr int poll_interval = 50;
// PlayTask is an async producer — at the instant xTaskCreate returns, no
// frames have been pushed yet. Returning on the first empty observation
// races with the producer and reports completion before playback even
// starts (root cause of idle_check self-triggering its own energy VAD).
// Require the queue to be observed non-empty at least once before treating
// empty as "done".
bool seen_non_empty = false;
bool empty;
// 【MOD 删除整块2秒初始等待分支,不再提前返回】
// 原2000ms空队列提前退出逻辑全部移除
// int initial_wait_ms = 2000;
// while (elapsed < initial_wait_ms) { ... }
// if (!seen_non_empty) { 打印警告return; }
playback_cancelled_.store(false, std::memory_order_relaxed); // 新增:每次等待前重置取消标记
// 【OPT2】使用条件变量替代固定50ms轮询,无音频变更时完全休眠,CPU 0占用
std::unique_lock<std::mutex> play_lock(playback_mutex_);
while (elapsed < timeout_ms)
{
// Cancellation short-circuit: if ResetDecoder fired (e.g. wake word
// interrupted an alarm), return immediately so the caller can move on
// instead of polling a soon-to-be-emptied queue for the full timeout.
if (playback_cancelled_.load(std::memory_order_relaxed))
{
ESP_LOGI(TAG, "WaitForPlaybackComplete: playback cancelled, exit early");
return;
}
// {
// std::lock_guard<std::mutex> lock1(decode_mutex_);
// std::lock_guard<std::mutex> lock2(playback_mutex_);
// empty = decode_queue_.empty() && playback_queue_.empty();
// }
// 一次性读取双队列状态,仅单次锁窗口,缩小锁持有时间
bool decode_empty;
{
std::lock_guard<std::mutex> decode_lock(decode_mutex_);
decode_empty = decode_queue_.empty();
}
// 外层play_lock持有playback_mutex_,读取播放队列完全安全
bool play_empty = playback_queue_.empty();
empty = decode_empty && play_empty;
if (!empty)
{
seen_non_empty = true;
}
else if (seen_non_empty)
{
ESP_LOGI(TAG, "WaitForPlaybackComplete: all audio frames finished playing");
return;
}
else if (elapsed >= fast_exit_threshold)
{
// 只有全程没生成任何音频,才快速切监听;如果已经出过帧,必须等播放完
if (!seen_non_empty && decode_empty && play_empty)
{
ESP_LOGI(TAG, "WaitForPlaybackComplete: no audio frames, exit fast");
return;
}
}
// vTaskDelay(pdMS_TO_TICKS(poll_interval));
playback_cv_.wait_for(play_lock, std::chrono::milliseconds(50));
elapsed += poll_interval;
}
// 【MOD 增加总超时日志,方便调试】
ESP_LOGW(TAG, "WaitForPlaybackComplete total timeout %dms reached", timeout_ms);
}
*/
void AudioService::WaitForPlaybackComplete(int timeout_ms)
{
constexpr int fast_exit_threshold = 300;
constexpr int poll_interval = 50;
int elapsed = 0;
bool seen_non_empty = false;
//playback_cancelled_.store(false, std::memory_order_relaxed);
//std::unique_lock<std::mutex> play_lock(playback_mutex_);
bool decode_empty, play_empty;
GetQueueEmptyStatus(decode_empty, play_empty);
if (decode_empty && play_empty) {
ESP_LOGI(TAG, "WaitForPlaybackComplete: queues already empty, exit immediately");
return;
}
while (elapsed < timeout_ms)
{
if (playback_cancelled_.load(std::memory_order_relaxed))
{
ESP_LOGI(TAG, "WaitForPlaybackComplete: playback cancelled, exit early");
return;
}
// 统一锁顺序读取队列
GetQueueEmptyStatus(decode_empty, play_empty);
const bool all_empty = decode_empty && play_empty;
if (!all_empty)
{
seen_non_empty = true;
}
else if (seen_non_empty)
{
ESP_LOGI(TAG, "WaitForPlaybackComplete: all audio frames finished playing");
return;
}
// 空队列快速退出判断提前
if (!seen_non_empty && all_empty && elapsed >= fast_exit_threshold)
{
ESP_LOGI(TAG, "WaitForPlaybackComplete: no audio frames, exit fast");
return;
}
//(void)playback_cv_.wait_for(play_lock, std::chrono::milliseconds(poll_interval));
// 使用 playback_cv_ 条件变量替代 vTaskDelay 忙轮询。
// playback_cv_ 在队列状态变更时被 notify(push/pop),
// 此处 wait_for 在无变更时休眠,有变更时立即唤醒,降低 CPU 占用。
// 仅持有 playback_mutex_ 等待,不跨 decode_mutex_ 持锁,避免死锁。
{
std::unique_lock<std::mutex> play_lock(playback_mutex_);
playback_cv_.wait_for(play_lock, std::chrono::milliseconds(poll_interval));
}
elapsed += poll_interval;
}
ESP_LOGW(TAG, "WaitForPlaybackComplete total timeout %dms reached, decode_empty=%d play_empty=%d",
timeout_ms, decode_empty, play_empty);
}
void AudioService::ResetDecoder()
{
ESP_LOGI(TAG, "[Playback] ResetDecoder called, cancelling current playback");
if (opus_decoder_)
{
opus_decoder_->ResetState();
}
// 清空解码和播放队列
{
std::lock_guard<std::mutex> lock(decode_mutex_);
size_t decode_size = decode_queue_.size();
decode_queue_.clear();
ESP_LOGI(TAG, "[Playback] Cleared decode queue, %zu frames removed", decode_size);
}
{
std::lock_guard<std::mutex> lock(playback_mutex_);
size_t playback_size = playback_queue_.size();
playback_queue_.clear();
ESP_LOGI(TAG, "[Playback] Cleared playback queue, %zu frames removed", playback_size);
}
// Signal any in-flight PlayEmbeddedOpus task to stop pushing new frames.
// Without this, the task would refill the queue we just cleared and the
// prompt would keep playing / fight with the new TTS stream.
playback_cancelled_.store(true);
ESP_LOGI(TAG, "[Playback] Playback cancelled flag set to true");
}
std::unique_ptr<AudioStreamPacket> AudioService::PopPacketFromSendQueue()
{
std::lock_guard<std::mutex> lock(send_mutex_);
if (send_queue_.empty())
return nullptr;
auto pkt = std::move(send_queue_.front());
send_queue_.pop_front();
return pkt;
}
void AudioService::PushPacketToDecodeQueue(std::unique_ptr<AudioStreamPacket> packet)
{
std::lock_guard<std::mutex> lock(decode_mutex_);
if (decode_queue_.size() >= kMaxDecodeQueueSize)
{
decode_queue_.pop_front();
}
decode_queue_.push_back(std::move(packet));
decode_cv_.notify_one();
// Also wake OpusCodecTask which waits on encode_cv_ when idle
encode_cv_.notify_one();
}
// === Task 1: 麦克风采集 → 唤醒词检测 or PCM 入编码队列 ===
void AudioService::AudioInputTask(void *arg)
{
auto *self = static_cast<AudioService *>(arg);
int codec_frame_samples = self->codec_->input_sample_rate() * OPUS_FRAME_DURATION_MS / 1000;
while (self->running_)
{
// When neither voice processing nor wake word detection is active, sleep
if (!self->voice_processing_enabled_ && !self->wake_word_enabled_)
{
vTaskDelay(pdMS_TO_TICKS(20));
continue;
}
std::vector<int16_t> read_buf(codec_frame_samples);
if (!self->codec_->InputData(read_buf))
continue;
// Resample to 16kHz if needed
std::vector<int16_t> pcm_16k;
if (self->input_resampler_)
{
int out_samples = self->input_resampler_->GetOutputSamples(read_buf.size());
pcm_16k.resize(out_samples);
self->input_resampler_->Process(read_buf.data(), read_buf.size(), pcm_16k.data());
}
else
{
pcm_16k = std::move(read_buf);
}
// Energy-threshold VAD (rough RMS detector). Runs in parallel with
// wake-word / voice-processing modes — must be inserted *before* the
// wake-word `continue` below so it works in idle (wake-word-only) state.
// Used by IdleWatchdog to detect any sustained voice in the post-prompt
// 15s window. One-shot: auto-disables after firing.
if (self->energy_vad_enabled_.load() && !pcm_16k.empty())
{
// 2026-6-30 ckkj debug 在 barge-in 模式下,能量 VAD 应该使用 AEC/NS 处理后的数据
std::vector<int16_t> vad_input;
if (self->voice_processing_enabled_ && self->voice_processor_ && self->voice_processor_->IsReady())
{
// Barge-in mode: get AEC/NS processed data for VAD
// This eliminates TTS playback echo from triggering VAD
std::vector<int16_t> ref_chunk;
ref_chunk.reserve(pcm_16k.size());
{
std::lock_guard<std::mutex> lock(self->aec_ref_mutex_);
while (!self->aec_ref_queue_.empty() && ref_chunk.size() < pcm_16k.size()) {
auto &front = self->aec_ref_queue_.front();
size_t need = pcm_16k.size() - ref_chunk.size();
size_t take = std::min(need, front.size());
ref_chunk.insert(ref_chunk.end(), front.begin(), front.begin() + take);
if (take == front.size())
{
self->aec_ref_queue_.pop_front();
}
else
{
front.erase(front.begin(), front.begin() + take);
}
}
}
ref_chunk.resize(pcm_16k.size(), 0);
{
std::lock_guard<std::mutex> vp_lock(self->voice_processor_mutex_);
self->voice_processor_->Process(pcm_16k.data(), ref_chunk.data(), pcm_16k.size(), vad_input);
}
// If no processed output, fall back to raw data
if (vad_input.empty()) {
vad_input = pcm_16k;
}
}
else
{
// Normal idle mode: use raw mic data
vad_input = pcm_16k;
}
//debug end
// Idle mode has no AEC, so the threshold needs to clear residual
// speaker echo / room reverb / fan noise. Raised from 1000 to 1500
// after observing the device self-triggering on its own idle_check
// tail (2026-04-27 验证).
//static constexpr int kVadRmsThreshold = 1500;
// 2026-6-23 ckkj debug 增加触发帧数,给用户更多时间开始说话,避免过早截断
static constexpr int kVadRmsThreshold = 2500;//过滤低音量环境噪音(如风扇声、远处人声)
static constexpr int kVadTriggerFrames = 3; // 3 frames (180ms)
int64_t sum_sq = 0;
//for (int16_t s : pcm_16k)
for (int16_t s : vad_input)
{
int32_t v = s;
sum_sq += v * v;
}
//int rms = (int)sqrtf((float)sum_sq / (float)pcm_16k.size());
int rms = (int)sqrtf((float)sum_sq / (float)vad_input.size());
if (rms >= kVadRmsThreshold)
{
if (++self->vad_consecutive_frames_ >= kVadTriggerFrames)
{
self->vad_consecutive_frames_ = 0;
self->energy_vad_enabled_.store(false);
if (self->callbacks_.on_voice_detected)
{
self->callbacks_.on_voice_detected();
}
}
}
else
{
self->vad_consecutive_frames_ = 0;
}
}
// Wake word detection mode: feed audio to WakeNet
// Two paths:
// 1) Normal idle path - raw mic frames when voice_processing is OFF.
// 2) Barge-in / call path - use VoiceProcessor output (AEC/NS result)
if (self->wake_word_enabled_ && self->wake_word_detector_.is_initialized())
{
int chunk_size = self->wake_word_detector_.chunk_size();
if (!self->voice_processing_enabled_)
{
// Idle: feed raw mic PCM
self->wake_word_buffer_.insert(
self->wake_word_buffer_.end(), pcm_16k.begin(), pcm_16k.end());
while ((int)self->wake_word_buffer_.size() >= chunk_size)
{
self->wake_word_detector_.Feed(self->wake_word_buffer_.data(), chunk_size);
self->wake_word_buffer_.erase(
self->wake_word_buffer_.begin(),
self->wake_word_buffer_.begin() + chunk_size);
}
// If wake word handled, skip further encoding path for this frame
continue;
} else {
// voice_processing is enabled (call / barge-in). Try to obtain
// a processed (AEC/NS/AGC) chunk from VoiceProcessor and feed it
// to WakeNet so wake detection works during playback.
std::vector<int16_t> ref_chunk;
ref_chunk.reserve(pcm_16k.size());
{
std::lock_guard<std::mutex> lock(self->aec_ref_mutex_);
while (!self->aec_ref_queue_.empty() && ref_chunk.size() < pcm_16k.size()) {
auto &front = self->aec_ref_queue_.front();
size_t need = pcm_16k.size() - ref_chunk.size();
size_t take = std::min(need, front.size());
ref_chunk.insert(ref_chunk.end(), front.begin(), front.begin() + take);
if (take == front.size())
{
self->aec_ref_queue_.pop_front();
}
else
{
front.erase(front.begin(), front.begin() + take);
}
}
}
ref_chunk.resize(pcm_16k.size(), 0);
// Process mic+ref through voice processor (low-cost/FD AEC path)
std::vector<int16_t> vp_out;
{
std::lock_guard<std::mutex> vp_lock(self->voice_processor_mutex_);
if (self->voice_processor_ && self->voice_processor_->IsReady())
{
// VoiceProcessor::Process appends processed frames into vp_out
self->voice_processor_->Process(pcm_16k.data(), ref_chunk.data(), pcm_16k.size(), vp_out);
}
}
if (!vp_out.empty())
{
self->wake_word_buffer_.insert(self->wake_word_buffer_.end(), vp_out.begin(), vp_out.end());
while ((int)self->wake_word_buffer_.size() >= chunk_size)
{
self->wake_word_detector_.Feed(self->wake_word_buffer_.data(), chunk_size);
self->wake_word_buffer_.erase(
self->wake_word_buffer_.begin(),
self->wake_word_buffer_.begin() + chunk_size);
}
// Feeded wake word from processed mic; continue to next capture
continue;
}
// If no processed output available, fallthrough to voice-processing path
}
}
// Voice processing mode: encode and send
if (self->voice_processing_enabled_) {
std::unique_lock<std::mutex> vp_lock(self->voice_processor_mutex_);
const bool use_vp = (self->call_mode_enabled_.load() || self->barge_in_mode_enabled_.load()) && self->voice_processor_ && self->voice_processor_->IsReady();
if (use_vp)
{
// Call-mode AEC+NS+AGC branch. VoiceProcessor emits chunks
// whose length depends on AEC/NS chunk alignment and will
// almost never match the Opus 60ms frame size (960 samples).
// We append its output to vp_encoder_acc_ and slice out
// 960-sample frames for the encoder.
std::vector<int16_t> ref_chunk;
ref_chunk.reserve(pcm_16k.size());
{
std::lock_guard<std::mutex> lock(self->aec_ref_mutex_);
while (!self->aec_ref_queue_.empty() && ref_chunk.size() < pcm_16k.size())
{
auto &front = self->aec_ref_queue_.front();
size_t need = pcm_16k.size() - ref_chunk.size();
size_t take = std::min(need, front.size());
ref_chunk.insert(ref_chunk.end(),
front.begin(), front.begin() + take);
if (take == front.size())
{
self->aec_ref_queue_.pop_front();
}
else
{
front.erase(front.begin(), front.begin() + take);
}
}
}
ref_chunk.resize(pcm_16k.size(), 0); // pad with silence
self->voice_processor_->Process(
pcm_16k.data(), ref_chunk.data(), pcm_16k.size(),
self->vp_encoder_acc_);
// Slice accumulated clean PCM into fixed 60ms frames.
const size_t FRAME = kInputSampleRate * OPUS_FRAME_DURATION_MS / 1000;
while (self->vp_encoder_acc_.size() >= FRAME)
{
auto task = std::make_unique<AudioTask>();
task->type = AudioTask::kEncode;
task->pcm.assign(
self->vp_encoder_acc_.begin(),
self->vp_encoder_acc_.begin() + FRAME);
self->vp_encoder_acc_.erase(
self->vp_encoder_acc_.begin(),
self->vp_encoder_acc_.begin() + FRAME);
//2026-6-30 ckkj debug 在上传麦克风数据之前,检查 RMS 阈值,只上传有效人声,避免上传环境噪音
if (self->barge_in_mode_enabled_.load()) {
int64_t sum_sq = 0;
for (int16_t s : task->pcm) {
int32_t v = s;
sum_sq += v * v;
}
float rms = sqrtf((float)sum_sq / (float)task->pcm.size());
// Threshold: 800 (~ -26dBFS), lower than energy VAD (2500)
// to allow quiet voices but filter out background noise
static constexpr float kBargeInRmsThreshold = 800.0f;
if (rms < kBargeInRmsThreshold) {
// Skip this frame - below threshold, likely noise
continue;
}
}
//debug end
{
std::lock_guard<std::mutex> lock(self->encode_mutex_);
if (self->encode_queue_.size() >= kMaxEncodeQueueSize)
{
self->encode_queue_.pop_front();
}
self->encode_queue_.push_back(std::move(task));
}
self->encode_cv_.notify_one();
}
}
else
{
vp_lock.unlock();
// Non-call: raw 60ms MIC frame direct to encoder.
auto task = std::make_unique<AudioTask>();
task->type = AudioTask::kEncode;
task->pcm = std::move(pcm_16k);
{
std::lock_guard<std::mutex> lock(self->encode_mutex_);
if (self->encode_queue_.size() >= kMaxEncodeQueueSize)
{
self->encode_queue_.pop_front();
}
self->encode_queue_.push_back(std::move(task));
}
self->encode_cv_.notify_one();
}
}
//vTaskDelay(pdMS_TO_TICKS(1));
}
vTaskDelete(nullptr);
}
// === Task 2: 播放队列 PCM → I2S 喇叭 ===
void AudioService::AudioOutputTask(void *arg)
{
constexpr int kOutputWarmupMs = 60;
auto *self = static_cast<AudioService *>(arg);
bool was_idle = true; // Track idle→playing transition for DAC warmup
while (self->running_)
{
std::unique_ptr<AudioTask> task;
{
std::unique_lock<std::mutex> lock(self->playback_mutex_);
self->playback_cv_.wait_for(lock, std::chrono::milliseconds(5),
[self]()
{ return !self->playback_queue_.empty() || !self->running_; });
if (!self->running_)
break;
if (self->playback_queue_.empty())
{
// Only mark idle when not in TTS playback mode
// to avoid spurious DAC warmup between TTS segments
if (!self->playback_hint_.load())
{
was_idle = true;
}
continue;
}
task = std::move(self->playback_queue_.front());
self->playback_queue_.pop_front();
}
if (task && !task->pcm.empty())
{
// Cancellation short-circuit: if a wake word fired between the
// pop above and now, drop this frame instead of writing it to
// I2S. Without this, a 60–180ms frame already held by us could
// continue blasting through the speaker after the abort.
// was_idle reset so the next legitimate playback re-warms the DAC.
if (self->playback_cancelled_.load())
{
was_idle = true;
continue;
}
// Warm up DAC/PA on idle→playing transition
if (was_idle)
{
was_idle = false;
int warmup_samples = self->codec_->output_sample_rate() * kOutputWarmupMs / 1000;
if (warmup_samples > 0)
{
std::vector<int16_t> warmup_pcm(static_cast<size_t>(warmup_samples), 0);
self->codec_->OutputData(warmup_pcm);
}
}
// Put the speaker reference into AEC queue before writing this frame to I2S.
// The acoustic echo reaches MIC after speaker/DAC/air delay, so REF must not
// arrive later than the MIC frame that contains its echo.
if ((self->call_mode_enabled_.load() || self->barge_in_mode_enabled_.load()) &&
self->codec_->output_sample_rate() == kInputSampleRate)
{
std::vector<int16_t> ref_pcm = task->pcm;
int vol = self->codec_->output_volume();
if (vol < 0)
vol = 0;
if (vol > 100)
vol = 100;
int32_t gain_fp = static_cast<int32_t>(
(static_cast<float>(vol) / 100.0f) * 256.0f);
for (auto &sample : ref_pcm)
{
int32_t s = (static_cast<int32_t>(sample) * gain_fp) >> 8;
if (s > 32767)
s = 32767;
if (s < -32768)
s = -32768;
sample = static_cast<int16_t>(s);
}
std::lock_guard<std::mutex> lock(self->aec_ref_mutex_);
if (self->aec_ref_queue_.size() >= kMaxAecRefFrames)
{
self->aec_ref_queue_.pop_front();
}
self->aec_ref_queue_.push_back(std::move(ref_pcm));
}
self->codec_->OutputData(task->pcm);
}
}
vTaskDelete(nullptr);
}
// === Task 3: Opus 编码(上行)+ 解码(下行)===
void AudioService::OpusCodecTask(void *arg)
{
auto *self = static_cast<AudioService *>(arg);
static int loop_count = 0;
while (self->running_)
{
bool did_work = false;
// 上行:PCM → Opus 编码 → 发送队列
// Skip encoding during TTS playback to prioritize decode throughput
if (!self->playback_hint_.load() || self->barge_in_mode_enabled_.load())
{
std::unique_ptr<AudioTask> encode_task;
{
std::unique_lock<std::mutex> lock(self->encode_mutex_);
if (!self->encode_queue_.empty())
{
encode_task = std::move(self->encode_queue_.front());
self->encode_queue_.pop_front();
}
}
if (encode_task && self->opus_encoder_)
{
std::vector<uint8_t> opus_data;
if (self->opus_encoder_->Encode(std::move(encode_task->pcm), opus_data))
{
auto pkt = std::make_unique<AudioStreamPacket>();
pkt->sample_rate = kInputSampleRate;
pkt->frame_duration = OPUS_FRAME_DURATION_MS;
pkt->payload = std::move(opus_data);
{
std::lock_guard<std::mutex> lock(self->send_mutex_);
if (self->send_queue_.size() >= kMaxSendQueueSize)
{
self->send_queue_.pop_front();
}
self->send_queue_.push_back(std::move(pkt));
}
if (self->callbacks_.on_send_queue_available)
{
self->callbacks_.on_send_queue_available();
}
}
did_work = true;
}
} // end if (!playback_hint_)
// 下行:Opus → PCM 解码 → 播放队列(批量解码,阻塞等待不丢帧)
while (self->running_)
{
std::unique_ptr<AudioStreamPacket> decode_pkt;
{
std::unique_lock<std::mutex> lock(self->decode_mutex_);
if (self->decode_queue_.empty())
break;
decode_pkt = std::move(self->decode_queue_.front());
self->decode_queue_.pop_front();
}
if (decode_pkt && self->opus_decoder_)
{
std::vector<int16_t> pcm;
if (self->opus_decoder_->Decode(std::move(decode_pkt->payload), pcm))
{
std::vector<int16_t> pcm_out;
if (self->output_resampler_)
{
int out_samples = self->output_resampler_->GetOutputSamples(pcm.size());
pcm_out.resize(out_samples);
self->output_resampler_->Process(pcm.data(), pcm.size(), pcm_out.data());
}
else
{
pcm_out = std::move(pcm);
}
auto task = std::make_unique<AudioTask>();
task->type = AudioTask::kPlayback;
task->pcm = std::move(pcm_out);
// Wait for space in playback queue instead of dropping frames
{
std::unique_lock<std::mutex> lock(self->playback_mutex_);
while (self->playback_queue_.size() >= kMaxPlaybackQueueSize && self->running_)
{
lock.unlock();
vTaskDelay(pdMS_TO_TICKS(5));
lock.lock();
}
self->playback_queue_.push_back(std::move(task));
}
self->playback_cv_.notify_one();
}
did_work = true;
}
}
if (!did_work)
{
// 两个队列都空时短暂等待
std::unique_lock<std::mutex> lock(self->encode_mutex_);
self->encode_cv_.wait_for(lock, std::chrono::milliseconds(5));
}
loop_count++;
if (loop_count % 5000 == 0)
{
// 监控栈剩余,低于2000字节要重视
UBaseType_t min_free_stack = uxTaskGetStackHighWaterMark(nullptr);
ESP_LOGI(TAG, "count=%d ,opus_codec min free stack: %u bytes", loop_count, min_free_stack * 4);
ESP_LOGI(TAG, "heap free: %lu, min free heap: %lu",
esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
}
}
vTaskDelete(nullptr);
}
/*
void AudioService::OpusCodecTask(void* arg)
{
auto* self = static_cast<AudioService*>(arg);
static int loop_count=0;
while (self->running_) {
bool did_work = false;
// 上行:PCM → Opus 编码 → 发送队列
// Skip encoding during TTS playback to prioritize decode throughput
if (!self->playback_hint_.load() || self->barge_in_mode_enabled_.load())
{
std::unique_ptr<AudioTask> encode_task;
{
std::unique_lock<std::mutex> lock(self->encode_mutex_);
if (!self->encode_queue_.empty()) {
encode_task = std::move(self->encode_queue_.front());
self->encode_queue_.pop_front();
}
}
if (encode_task && self->opus_encoder_) {
std::vector<uint8_t> opus_data;
if (self->opus_encoder_->Encode(std::move(encode_task->pcm), opus_data)) {
auto pkt = std::make_unique<AudioStreamPacket>();
pkt->sample_rate = kInputSampleRate;
pkt->frame_duration = OPUS_FRAME_DURATION_MS;
pkt->payload = std::move(opus_data);
{
std::lock_guard<std::mutex> lock(self->send_mutex_);
if (self->send_queue_.size() >= kMaxSendQueueSize) {
self->send_queue_.pop_front();
}
self->send_queue_.push_back(std::move(pkt));
}
if (self->callbacks_.on_send_queue_available) {
self->callbacks_.on_send_queue_available();
}
}
did_work = true;
}
} // end if (!playback_hint_)
// 下行:Opus → PCM 解码 → 播放队列(水位控制批量解码,防止编码饥饿)
{
size_t playback_size;
{
std::lock_guard<std::mutex> lock(self->playback_mutex_);
playback_size = self->playback_queue_.size();
}
if (playback_size < kPlaybackLowWatermark) {
while (self->running_) {
// 每次解码前检查播放队列是否已达高水位,是则停止让出 CPU 给编码
{
std::lock_guard<std::mutex> lock(self->playback_mutex_);
if (self->playback_queue_.size() >= kPlaybackHighWatermark) break;
}
std::unique_ptr<AudioStreamPacket> decode_pkt;
{
std::unique_lock<std::mutex> lock(self->decode_mutex_);
if (self->decode_queue_.empty()) break;
decode_pkt = std::move(self->decode_queue_.front());
self->decode_queue_.pop_front();
}
if (decode_pkt && self->opus_decoder_) {
std::vector<int16_t> pcm;
if (self->opus_decoder_->Decode(std::move(decode_pkt->payload), pcm)) {
std::vector<int16_t> pcm_out;
if (self->output_resampler_) {
int out_samples = self->output_resampler_->GetOutputSamples(pcm.size());
pcm_out.resize(out_samples);
self->output_resampler_->Process(pcm.data(), pcm.size(), pcm_out.data());
} else {
pcm_out = std::move(pcm);
}
auto task = std::make_unique<AudioTask>();
task->type = AudioTask::kPlayback;
task->pcm = std::move(pcm_out);
{
std::unique_lock<std::mutex> lock(self->playback_mutex_);
while (self->playback_queue_.size() >= kMaxPlaybackQueueSize && self->running_) {
lock.unlock();
vTaskDelay(pdMS_TO_TICKS(5));
lock.lock();
}
self->playback_queue_.push_back(std::move(task));
}
self->playback_cv_.notify_one();
}
did_work = true;
}
}
}
}
if (!did_work) {
// 两个队列都空时短暂等待
std::unique_lock<std::mutex> lock(self->encode_mutex_);
self->encode_cv_.wait_for(lock, std::chrono::milliseconds(5));
}
loop_count++;
if (loop_count % 5000 == 0) {
//监控栈剩余,低于2000字节要重视
UBaseType_t min_free_stack = uxTaskGetStackHighWaterMark(nullptr);
ESP_LOGI(TAG, "count=%d ,opus_codec min free stack: %u bytes", loop_count,min_free_stack*4);
ESP_LOGI(TAG, "heap free: %lu, min free heap: %lu",
esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
}
}
vTaskDelete(nullptr);
}*/