bolar_1 date 2026-7-1 d:/proc

This commit is contained in:
2026-11-27 17:44:38 +08:00
commit 0dbdfa57bc
890 changed files with 325428 additions and 0 deletions

79
main/audio/audio_codec.cc Normal file
View File

@@ -0,0 +1,79 @@
#include "audio_codec.h"
#include "settings.h"
#include <esp_log.h>
#include <cstring>
#include <driver/i2s_common.h>
#define TAG "AudioCodec"
AudioCodec::AudioCodec() {}
AudioCodec::~AudioCodec() {}
void AudioCodec::OutputData(std::vector<int16_t>& data)
{
Write(data.data(), data.size());
}
bool AudioCodec::InputData(std::vector<int16_t>& data)
{
int samples = Read(data.data(), data.size());
return samples > 0;
}
void AudioCodec::Start()
{
Settings settings("audio", false);
output_volume_ = settings.GetInt("output_volume", output_volume_);
if (output_volume_ < AUDIO_CODEC_MIN_OUTPUT_VOLUME) {
ESP_LOGW(TAG, "Output volume (%d) too small, setting to %d",
output_volume_, AUDIO_CODEC_MIN_OUTPUT_VOLUME);
output_volume_ = AUDIO_CODEC_MIN_OUTPUT_VOLUME;
} else if (output_volume_ > AUDIO_CODEC_MAX_OUTPUT_VOLUME) {
output_volume_ = AUDIO_CODEC_MAX_OUTPUT_VOLUME;
}
if (tx_handle_) {
ESP_ERROR_CHECK(i2s_channel_enable(tx_handle_));
}
if (rx_handle_) {
ESP_ERROR_CHECK(i2s_channel_enable(rx_handle_));
}
EnableInput(true);
EnableOutput(true);
ESP_LOGI(TAG, "Audio codec started");
}
void AudioCodec::SetOutputVolume(int volume)
{
if (volume < AUDIO_CODEC_MIN_OUTPUT_VOLUME) {
volume = AUDIO_CODEC_MIN_OUTPUT_VOLUME;
} else if (volume > AUDIO_CODEC_MAX_OUTPUT_VOLUME) {
volume = AUDIO_CODEC_MAX_OUTPUT_VOLUME;
}
output_volume_ = volume;
ESP_LOGI(TAG, "Set output volume to %d", output_volume_);
Settings settings("audio", true);
settings.SetInt("output_volume", output_volume_);
}
void AudioCodec::SetInputGain(float gain)
{
input_gain_ = gain;
ESP_LOGI(TAG, "Set input gain to %.1f", input_gain_);
}
void AudioCodec::EnableInput(bool enable)
{
if (enable == input_enabled_) return;
input_enabled_ = enable;
ESP_LOGI(TAG, "Set input enable to %s", enable ? "true" : "false");
}
void AudioCodec::EnableOutput(bool enable)
{
if (enable == output_enabled_) return;
output_enabled_ = enable;
ESP_LOGI(TAG, "Set output enable to %s", enable ? "true" : "false");
}

61
main/audio/audio_codec.h Normal file
View File

@@ -0,0 +1,61 @@
#ifndef _AUDIO_CODEC_H
#define _AUDIO_CODEC_H
#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <driver/i2s_std.h>
#include <vector>
#include <string>
#include <functional>
#define AUDIO_CODEC_DMA_DESC_NUM 6
#define AUDIO_CODEC_DMA_FRAME_NUM 240
#define AUDIO_CODEC_MIN_OUTPUT_VOLUME 15
#define AUDIO_CODEC_MAX_OUTPUT_VOLUME 100
class AudioCodec {
public:
AudioCodec();
virtual ~AudioCodec();
virtual void SetOutputVolume(int volume);
virtual void SetInputGain(float gain);
virtual void EnableInput(bool enable);
virtual void EnableOutput(bool enable);
virtual void OutputData(std::vector<int16_t>& data);
virtual bool InputData(std::vector<int16_t>& data);
virtual void Start();
inline bool duplex() const { return duplex_; }
inline bool input_reference() const { return input_reference_; }
inline int input_sample_rate() const { return input_sample_rate_; }
inline int output_sample_rate() const { return output_sample_rate_; }
inline int input_channels() const { return input_channels_; }
inline int output_channels() const { return output_channels_; }
inline int output_volume() const { return output_volume_; }
inline float input_gain() const { return input_gain_; }
inline bool input_enabled() const { return input_enabled_; }
inline bool output_enabled() const { return output_enabled_; }
protected:
i2s_chan_handle_t tx_handle_ = nullptr;
i2s_chan_handle_t rx_handle_ = nullptr;
bool duplex_ = false;
bool input_reference_ = false;
bool input_enabled_ = false;
bool output_enabled_ = false;
int input_sample_rate_ = 0;
int output_sample_rate_ = 0;
int input_channels_ = 1;
int output_channels_ = 1;
int output_volume_ = 70;
float input_gain_ = 0.0;
virtual int Read(int16_t* dest, int samples) = 0;
virtual int Write(const int16_t* data, int samples) = 0;
};
#endif // _AUDIO_CODEC_H

341
main/audio/audio_prompt.cc Normal file
View File

@@ -0,0 +1,341 @@
#include "audio_prompt.h"
#include "audio_prompts_data.h"
#include "protocols/protocol.h"
#include <esp_log.h>
#include <esp_random.h>
#include <cstring>
#define TAG "AudioPrompt"
struct PromptGroupInfo {
const uint8_t** files;
const size_t* sizes;
int count;
};
static PromptGroupInfo GetGroupInfo(PromptGroup group)
{
PromptGroupInfo info = {nullptr, nullptr, 0};
switch (group) {
case kPromptWelcome:
info.files = audio_welcome_files;
info.sizes = audio_welcome_sizes;
info.count = audio_welcome_count;
break;
case kPromptShutdown:
info.files = audio_shutdown_files;
info.sizes = audio_shutdown_sizes;
info.count = audio_shutdown_count;
break;
case kPromptNoNetwork:
info.files = audio_no_network_files;
info.sizes = audio_no_network_sizes;
info.count = audio_no_network_count;
break;
case kPromptError:
info.files = audio_error_files;
info.sizes = audio_error_sizes;
info.count = audio_error_count;
break;
case kPromptWifiConfig:
info.files = audio_wifi_config_files;
info.sizes = audio_wifi_config_sizes;
info.count = audio_wifi_config_count;
break;
case kPromptAlarmSet:
info.files = audio_alarm_set_files;
info.sizes = audio_alarm_set_sizes;
info.count = audio_alarm_set_count;
break;
case kPromptAlarmWake:
info.files = audio_alarm_wake_files;
info.sizes = audio_alarm_wake_sizes;
info.count = audio_alarm_wake_count;
break;
case kPromptDeviceAlreadyBound:
info.files = audio_device_already_bound_files;
info.sizes = audio_device_already_bound_sizes;
info.count = audio_device_already_bound_count;
break;
case kPromptBoot:
info.files = audio_boot_files;
info.sizes = audio_boot_sizes;
info.count = audio_boot_count;
break;
case kPromptServerError:
info.files = audio_server_error_files;
info.sizes = audio_server_error_sizes;
info.count = audio_server_error_count;
break;
case kPromptStoryExpired:
info.files = audio_story_expired_files;
info.sizes = audio_story_expired_sizes;
info.count = audio_story_expired_count;
break;
case kPromptWakeResponse:
info.files = audio_wake_response_files;
info.sizes = audio_wake_response_sizes;
info.count = audio_wake_response_count;
break;
case kPromptIdleCheck:
info.files = audio_idle_check_files;
info.sizes = audio_idle_check_sizes;
info.count = audio_idle_check_count;
break;
case kPromptIdleGoodbye:
info.files = audio_idle_goodbye_files;
info.sizes = audio_idle_goodbye_sizes;
info.count = audio_idle_goodbye_count;
break;
case kPromptWifiSuccess:
info.files = audio_wifi_success_files;
info.sizes = audio_wifi_success_sizes;
info.count = audio_wifi_success_count;
break;
case kPromptLowBattery20:
info.files = audio_low_battery_20_files;
info.sizes = audio_low_battery_20_sizes;
info.count = audio_low_battery_20_count;
break;
case kPromptLowBattery10:
info.files = audio_low_battery_10_files;
info.sizes = audio_low_battery_10_sizes;
info.count = audio_low_battery_10_count;
break;
case kPromptActivationDevice:
info.files = audio_activation_device_files;
info.sizes = audio_activation_device_sizes;
info.count = audio_activation_device_count;
break;
case kPromptDigit0:
info.files = audio_digit_0_files;
info.sizes = audio_digit_0_sizes;
info.count = audio_digit_0_count;
break;
case kPromptDigit1:
info.files = audio_digit_1_files;
info.sizes = audio_digit_1_sizes;
info.count = audio_digit_1_count;
break;
case kPromptDigit2:
info.files = audio_digit_2_files;
info.sizes = audio_digit_2_sizes;
info.count = audio_digit_2_count;
break;
case kPromptDigit3:
info.files = audio_digit_3_files;
info.sizes = audio_digit_3_sizes;
info.count = audio_digit_3_count;
break;
case kPromptDigit4:
info.files = audio_digit_4_files;
info.sizes = audio_digit_4_sizes;
info.count = audio_digit_4_count;
break;
case kPromptDigit5:
info.files = audio_digit_5_files;
info.sizes = audio_digit_5_sizes;
info.count = audio_digit_5_count;
break;
case kPromptDigit6:
info.files = audio_digit_6_files;
info.sizes = audio_digit_6_sizes;
info.count = audio_digit_6_count;
break;
case kPromptDigit7:
info.files = audio_digit_7_files;
info.sizes = audio_digit_7_sizes;
info.count = audio_digit_7_count;
break;
case kPromptDigit8:
info.files = audio_digit_8_files;
info.sizes = audio_digit_8_sizes;
info.count = audio_digit_8_count;
break;
case kPromptDigit9:
info.files = audio_digit_9_files;
info.sizes = audio_digit_9_sizes;
info.count = audio_digit_9_count;
break;
}
return info;
}
bool AudioPrompt::HasPrompts(PromptGroup group) const
{
auto info = GetGroupInfo(group);
return info.count > 0;
}
int AudioPrompt::GetFrameCount(PromptGroup group, int index) const
{
auto info = GetGroupInfo(group);
if (info.count <= 0 || index < 0 || index >= info.count) return 0;
const uint8_t* data = info.files[index];
if (!data) return 0;
// Header layout produced by gen_audio_prompts.py:
// [num_frames:u16 LE][frame_size:u16 LE, frame_data:bytes]...
return data[0] | (data[1] << 8);
}
struct PlayTaskParams {
AudioPrompt* self;
const uint8_t* data;
size_t size;
AudioService* audio;
int generation; // captured at xTaskCreate time
};
static void PlayTask(void* arg)
{
auto* params = static_cast<PlayTaskParams*>(arg);
// NOTE: BeginNewPlayback is now called *synchronously* by the caller
// (PlayByIndex / PlayRandom) before xTaskCreate. Doing it here used to
// race with wake-word-triggered ResetDecoder: a wake word fired after
// PlayLocal scheduled this task would set cancelled=true, then this
// BeginNewPlayback would clear it, swallowing the abort.
params->self->PlayEmbeddedOpus(params->data, params->size, *params->audio,
params->generation);
delete params;
vTaskDelete(nullptr);
}
bool AudioPrompt::PlayByIndex(PromptGroup group, int index, AudioService& audio)
{
auto info = GetGroupInfo(group);
if (info.count <= 0) return false;
if (index < 0 || index >= info.count) {
return PlayRandom(group, audio);
}
ESP_LOGI(TAG, "Playing prompt group=%d, index=%d/%d (by index)", group, index, info.count);
// Clear any stale cancel flag from a previous prompt that was aborted.
// Must happen synchronously, before scheduling PlayTask, otherwise a
// wake-word interrupt landing between here and the task starting would
// be undone by the old in-task BeginNewPlayback.
audio.BeginNewPlayback();
int gen = audio.CurrentPlaybackGeneration();
auto* params = new PlayTaskParams{this, info.files[index], info.sizes[index], &audio, gen};
xTaskCreate(PlayTask, "audio_prompt", 4096, params, 3, nullptr);
return true;
}
bool AudioPrompt::PlayRandom(PromptGroup group, AudioService& audio)
{
auto info = GetGroupInfo(group);
if (info.count <= 0) return false;
int idx = esp_random() % info.count;
ESP_LOGI(TAG, "Playing prompt group=%d, index=%d/%d", group, idx, info.count);
// See PlayByIndex comment — BeginNewPlayback must be synchronous so a
// subsequent ResetDecoder (e.g. from wake word) survives until consumed.
audio.BeginNewPlayback();
int gen = audio.CurrentPlaybackGeneration();
// Run in a separate task to avoid blocking the main event loop
auto* params = new PlayTaskParams{this, info.files[idx], info.sizes[idx], &audio, gen};
xTaskCreate(PlayTask, "audio_prompt", 4096, params, 3, nullptr);
return true;
}
namespace {
void SendPlayLocalSignal(Protocol* protocol, const char* state, const std::string& group) {
// 验证假设:暂时禁用 play_local start/done 消息上报。
// 日志显示本地音频播完后发 "done" 60 字节小消息会正好落在 ML307 radio
// 刚进 idle 的窗口,MIPSEND 连续失败触发 WS 断连 + 4G 反注册。
// 原版 xiaozhi 没有 play_local 机制,所以没这个断连触发器。
// 如果禁用后 4G 能稳定 2 分钟以上,说明根因确认。
ESP_LOGI("PlayLocal", "[DISABLED] skip sending play_local state=%s group=%s",
state, group.c_str());
(void)protocol;
}
}
bool AudioPrompt::PlayLocal(PromptGroup group, AudioService& audio,
Protocol* protocol, const std::string& group_name)
{
// 1. Tell server first so it stops pushing TTS/music frames ASAP.
SendPlayLocalSignal(protocol, "start", group_name);
// 2. Clear any residual frames from a previous stream (e.g. stale TTS
// during reconnect). PlayTask will re-arm the cancel flag on startup.
audio.ResetDecoder();
// 3. Launch the local playback (async PlayTask internally).
bool ok = PlayRandom(group, audio);
if (!ok) {
// Playback failed to start — emit done immediately so server doesn't
// hang in "speaking" state forever.
SendPlayLocalSignal(protocol, "done", group_name);
}
// Caller must call NotifyLocalDone() after WaitForPlaybackComplete.
return ok;
}
bool AudioPrompt::PlayLocalByIndex(PromptGroup group, int index, AudioService& audio,
Protocol* protocol, const std::string& group_name)
{
SendPlayLocalSignal(protocol, "start", group_name);
audio.ResetDecoder();
bool ok = PlayByIndex(group, index, audio);
if (!ok) {
SendPlayLocalSignal(protocol, "done", group_name);
}
return ok;
}
void AudioPrompt::NotifyLocalDone(Protocol* protocol, const std::string& group_name)
{
SendPlayLocalSignal(protocol, "done", group_name);
}
bool AudioPrompt::PlayEmbeddedOpus(const uint8_t* data, size_t size, AudioService& audio,
int my_generation)
{
if (!data || size < 2) return false;
// Parse format: [num_frames:u16][frame_size:u16, frame_data:bytes]...
size_t pos = 0;
uint16_t num_frames = data[pos] | (data[pos+1] << 8);
pos += 2;
ESP_LOGI(TAG, "Playing %d Opus frames (%zu bytes), gen=%d",
num_frames, size, my_generation);
for (uint16_t i = 0; i < num_frames && pos + 2 <= size; i++) {
// Abort if caller signalled cancel (e.g. wake word interrupt, or
// a new playback preempted via ResetDecoder). Without this check the
// task keeps pushing frames even after the queue was cleared.
if (audio.IsPlaybackCancelled()) {
ESP_LOGI(TAG, "Playback cancelled at frame %u/%u (gen=%d)",
i, num_frames, my_generation);
return false;
}
// Generation guard — a newer Reset+BeginNewPlayback cycle started.
// Cancel flag may already have been re-cleared to false by the new
// BeginNewPlayback, so cancel-only check would let us keep pushing
// and corrupt the new playback. Generation never decreases.
if (audio.CurrentPlaybackGeneration() != my_generation) {
ESP_LOGI(TAG, "Generation changed (mine=%d cur=%d) at frame %u/%u — exit",
my_generation, audio.CurrentPlaybackGeneration(), i, num_frames);
return false;
}
uint16_t frame_size = data[pos] | (data[pos+1] << 8);
pos += 2;
if (pos + frame_size > size) break;
auto pkt = std::make_unique<AudioStreamPacket>();
pkt->sample_rate = 24000;
pkt->frame_duration = 20;
pkt->timestamp = i * 20;
pkt->payload.assign(data + pos, data + pos + frame_size);
audio.PushPacketToDecodeQueue(std::move(pkt));
pos += frame_size;
// Feed at playback rate: each frame is ~20ms, delay every frame
vTaskDelay(pdMS_TO_TICKS(18));
}
return true;
}

92
main/audio/audio_prompt.h Normal file
View File

@@ -0,0 +1,92 @@
#pragma once
#include "audio_service.h"
#include <cstdint>
#include <string>
class Protocol; // fwd-decl to avoid pulling protocol.h
enum PromptGroup {
kPromptWelcome,
kPromptShutdown,
kPromptNoNetwork,
kPromptError,
kPromptWifiConfig,
kPromptAlarmSet,
kPromptAlarmWake,
kPromptDeviceAlreadyBound,
kPromptBoot, // 长按开机 - 立即播放,不等 WebSocket
kPromptServerError, // 服务器连接失败(404 / 超时)
kPromptStoryExpired, // 故事断点过期提示
kPromptWakeResponse, // 唤醒应答 - 每次 wake word 触发后播放("我在。")
kPromptIdleCheck, // 空闲提醒 - T+3min 无活动时播放("你还在吗?小朋友")
kPromptIdleGoodbye, // 空闲告别 - T+10min 无活动时播放("那我先退下来…"),播完进 light sleep
kPromptWifiSuccess, // 配网成功 - BLE 配网联通 WiFi 瞬间播放("配网成功啦。")
kPromptLowBattery20, // 低电量提醒 - 电量降到 20% 时播放(每 10 分钟提醒一次)
kPromptLowBattery10, // 低电量关机 - 电量降到 10% 时播放后关机
// Activation-code sequence playback: spoken prompt + per-digit OGGs
kPromptActivationDevice,
kPromptDigit0,
kPromptDigit1,
kPromptDigit2,
kPromptDigit3,
kPromptDigit4,
kPromptDigit5,
kPromptDigit6,
kPromptDigit7,
kPromptDigit8,
kPromptDigit9,
};
class AudioPrompt {
public:
// Check if local prompts are available
bool HasPrompts(PromptGroup group) const;
// Play a random prompt from the group through the audio pipeline
bool PlayRandom(PromptGroup group, AudioService& audio);
// Play a specific prompt by index (0-based). Falls back to PlayRandom if index invalid.
bool PlayByIndex(PromptGroup group, int index, AudioService& audio);
// Parse num_frames from the embedded-opus header so callers can derive
// playback duration (each frame = 20ms audio). Returns 0 on invalid
// group/index — caller must skip that item.
int GetFrameCount(PromptGroup group, int index) const;
// Parse embedded Opus frames and push to decode queue. `my_generation` is
// captured at task launch (right after BeginNewPlayback bumped it) and
// checked each frame; mismatch with AudioService::CurrentPlaybackGeneration
// means a newer playback cycle started and this task must self-exit.
bool PlayEmbeddedOpus(const uint8_t* data, size_t size, AudioService& audio,
int my_generation);
// === ADR-004 anti-mixing: unified local playback with server signalling ===
//
// PlayLocal wraps PlayRandom/PlayByIndex and sends
// {"type":"play_local","state":"start","group":"<name>"}
// to the server so the server can stop any in-flight TTS / music stream,
// preventing overlap with the local OGG. Caller must call NotifyDone()
// after WaitForPlaybackComplete (PlayTask is async, so "done" must be
// emitted on completion, not here).
//
// If protocol is null or WS not open, falls back silently to PlayRandom —
// the local prompt still plays, just without the server hand-shake. This
// covers boot prompt / connection-failure prompts where WS doesn't exist
// yet (no server in flight = no mixing risk anyway).
//
// group_name: the string server would see (e.g. "welcome", "alarm_wake").
// Must match the PromptGroup argument semantically — used only for the
// server message body.
bool PlayLocal(PromptGroup group, AudioService& audio,
Protocol* protocol, const std::string& group_name);
// Variant that picks a specific index inside the group.
bool PlayLocalByIndex(PromptGroup group, int index, AudioService& audio,
Protocol* protocol, const std::string& group_name);
// Send the "done" notification. Must be called by the caller after
// WaitForPlaybackComplete or equivalent, so server unlocks TTS lane.
// Safe to call with null/closed protocol (no-op).
void NotifyLocalDone(Protocol* protocol, const std::string& group_name);
};

File diff suppressed because it is too large Load Diff

1184
main/audio/audio_service.cc Normal file

File diff suppressed because it is too large Load Diff

210
main/audio/audio_service.h Normal file
View File

@@ -0,0 +1,210 @@
#pragma once
#include "audio_codec.h"
#include "wake_word.h"
#include "voice_processor.h"
#include <opus_encoder.h>
#include <opus_decoder.h>
#include <opus_resampler.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <functional>
#include <memory>
#include <deque>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <atomic>
#define OPUS_FRAME_DURATION_MS 60
// 音频任务项
struct AudioTask {
enum Type { kEncode, kPlayback };
Type type;
std::vector<int16_t> pcm;
};
// 音频流包(与 Protocol 层交互)
struct AudioStreamPacket {
int sample_rate = 0;
int frame_duration = 0;
uint32_t timestamp = 0;
std::vector<uint8_t> payload;
};
struct AudioServiceCallbacks {
std::function<void()> on_send_queue_available;
// Fired by energy-threshold VAD (rough RMS detector) when sustained voice
// energy is observed. One-shot: VAD auto-disables after firing. Used by
// IdleWatchdog to detect "child responded" inside the post-prompt window.
std::function<void()> on_voice_detected;
};
// 音频服务:管理 3 个 FreeRTOS 任务实现音频采集 → Opus 编码 → 发送
// 接收 → Opus 解码 → 播放
class AudioService {
public:
void Initialize(AudioCodec* codec);
void Start();
void Stop();
void SetCallbacks(const AudioServiceCallbacks& callbacks);
// Play a generated tone through the speaker
// freq_hz: frequency, duration_ms: length, volume: 0.0-1.0
void PlayTone(int freq_hz, int duration_ms, float volume = 0.3f);
// Play predefined sound effects
void PlayBootSound();
void PlayShutdownSound();
void PlayConfigSound();
void PlayErrorSound();
// 上行:编码后的 Opus 包从发送队列弹出
std::unique_ptr<AudioStreamPacket> PopPacketFromSendQueue();
// 下行:收到 server Opus 音频包,入解码队列
void PushPacketToDecodeQueue(std::unique_ptr<AudioStreamPacket> packet);
// 播放控制
void SetPlaybackHint(bool playing);
void ResetDecoder();
// 2026-6-29 ckkj debug 获取解码、播放队列是否为空
void GetQueueEmptyStatus(bool& decode_empty, bool& play_empty);
// Clear the cancel flag and bump the generation counter before starting a
// new local prompt. Generation lets in-flight PlayTask from the previous
// iteration self-exit even if its cancel-flag check is racing against this
// BeginNewPlayback() (cancel may have been re-cleared to false before the
// old task wakes from vTaskDelay). Must be called right before
// xTaskCreate(PlayTask, ...).
void BeginNewPlayback() {
playback_cancelled_.store(false);
playback_generation_.fetch_add(1, std::memory_order_relaxed);
}
bool IsPlaybackCancelled() const { return playback_cancelled_.load(); }
int CurrentPlaybackGeneration() const {
return playback_generation_.load(std::memory_order_relaxed);
}
// 录音控制(语音处理开关)
void EnableVoiceProcessing(bool enable);
// Phone-call mode: enable AEC+NS+AGC on MIC path, with downlink PCM as
// the speaker reference signal. On enable the VoiceProcessor is lazy-
// initialized; on disable the processor is torn down and the reference
// queue cleared.
void EnableCallMode(bool enable);
bool IsCallModeEnabled() const { return call_mode_enabled_.load(); }
// TTS barge-in mode: keep MIC upload active during Speaking and reuse the
// VoiceProcessor/AEC reference path so the server can hear the child
// without treating the speaker's own TTS as speech.
void EnableBargeInMode(bool enable);
bool IsBargeInModeEnabled() const { return barge_in_mode_enabled_.load(); }
// 能量阈值粗 VAD(用于 IdleWatchdog 检测 15s 等待窗口内是否有声音)
// 一次性触发:on_voice_detected 回调后自动 disable,需重新 enable。
// 仅在 wake_word 或 voice_processing 已启用(MIC 在采集)时生效。
void EnableEnergyVad(bool enable);
bool IsEnergyVadEnabled() const { return energy_vad_enabled_.load(); }
// 唤醒词检测
bool InitWakeWord();
void EnableWakeWordDetection(bool enable);
bool IsWakeWordDetectionEnabled() const { return wake_word_enabled_.load(); }
WakeWordDetector& wake_word_detector() { return wake_word_detector_; }
bool IsIdle() const;
// Wait until decode and playback queues are empty (audio finished playing)
void WaitForPlaybackComplete(int timeout_ms);
private:
static void AudioInputTask(void* arg);
static void AudioOutputTask(void* arg);
static void OpusCodecTask(void* arg);
AudioCodec* codec_ = nullptr;
AudioServiceCallbacks callbacks_;
// Opus 编解码器
std::unique_ptr<OpusEncoderWrapper> opus_encoder_;
std::unique_ptr<OpusDecoderWrapper> opus_decoder_;
std::unique_ptr<OpusResampler> input_resampler_;
std::unique_ptr<OpusResampler> output_resampler_;
// Downsamples decoded downlink PCM (at decoder rate, typically 24k)
// to 16kHz for the AEC reference path. Only used in call mode.
std::unique_ptr<OpusResampler> aec_ref_resampler_;
// 队列(用 deque + mutex + cv 替代 FreeRTOS Queue,与 xiaozhi 对齐)
std::deque<std::unique_ptr<AudioTask>> encode_queue_;
std::mutex encode_mutex_;
std::condition_variable encode_cv_;
std::deque<std::unique_ptr<AudioStreamPacket>> decode_queue_;
std::mutex decode_mutex_;
std::condition_variable decode_cv_;
std::deque<std::unique_ptr<AudioStreamPacket>> send_queue_;
std::mutex send_mutex_;
std::deque<std::unique_ptr<AudioTask>> playback_queue_;
std::mutex playback_mutex_;
std::condition_variable playback_cv_;
// FreeRTOS 任务
TaskHandle_t input_task_ = nullptr;
TaskHandle_t output_task_ = nullptr;
TaskHandle_t codec_task_ = nullptr;
std::atomic<bool> running_{false};
std::atomic<bool> voice_processing_enabled_{false};
std::atomic<bool> wake_word_enabled_{false};
std::atomic<bool> playback_hint_{false};
std::atomic<bool> call_mode_enabled_{false}; // AEC+NS+AGC active when true
std::atomic<bool> barge_in_mode_enabled_{false};
std::atomic<bool> energy_vad_enabled_{false}; // Rough RMS-based VAD for IdleWatchdog
int vad_consecutive_frames_ = 0;
// Voice processing pipeline for phone-call mode. Lazy-inited on first
// EnableCallMode(true); torn down on EnableCallMode(false).
std::mutex voice_processor_mutex_;
std::unique_ptr<VoiceProcessor> voice_processor_;
// Reference PCM queue — 16kHz mono int16 frames written by AudioOutputTask
// when downlink audio is actually sent to the speaker, then consumed by
// AudioInputTask paired with freshly-captured MIC PCM for AEC.
// Keeping this tied to real playback timing avoids feeding the canceller
// an early reference while frames are still buffered in playback_queue_.
std::deque<std::vector<int16_t>> aec_ref_queue_;
std::mutex aec_ref_mutex_;
static constexpr size_t kMaxAecRefFrames = 10; // ~600ms buffer
// Encoder accumulator for call mode. VoiceProcessor emits chunks whose
// size depends on AEC/NS alignment (not 60ms). This buffer collects
// clean PCM and hands it to OpusEncoder in fixed 960-sample (60ms@16k)
// frames. Only used in call mode — the non-call path sends raw 60ms
// frames directly.
std::vector<int16_t> vp_encoder_acc_;
// Set true by ResetDecoder; PlayEmbeddedOpus (audio_prompt) checks it each
// frame and breaks early so the local-prompt task stops re-filling the
// queue after an abort (e.g. wake-word interrupt during alarm ringing).
std::atomic<bool> playback_cancelled_{false};
// Bumped by BeginNewPlayback. Each PlayTask captures the value at start
// and self-exits when CurrentPlaybackGeneration() != captured value —
// immune to the cancel-flag race in tight Reset→BeginNew sequences.
std::atomic<int> playback_generation_{0};
WakeWordDetector wake_word_detector_;
std::vector<int16_t> wake_word_buffer_;
static constexpr int kInputSampleRate = 16000;
static constexpr int kMaxEncodeQueueSize = 2;
static constexpr int kMaxDecodeQueueSize = 40; // 2400ms / 60ms
static constexpr int kMaxSendQueueSize = 40;
static constexpr int kMaxPlaybackQueueSize = 8;
};

View File

@@ -0,0 +1,301 @@
#include "es8311_audio_codec.h"
#include <vector>
#include <esp_log.h>
#define TAG "Es8311AudioCodec"
Es8311AudioCodec::Es8311AudioCodec(void* i2c_master_handle, i2c_port_t i2c_port, int input_sample_rate, int output_sample_rate,
gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din,
gpio_num_t pa_pin, uint8_t es8311_addr, bool use_mclk, bool pa_inverted) {
duplex_ = true; // 是否双工
input_reference_ = false; // 是否使用参考输入,实现回声消除
input_channels_ = 1; // 输入通道数
input_sample_rate_ = input_sample_rate;
output_sample_rate_ = output_sample_rate;
pa_pin_ = pa_pin;
pa_inverted_ = pa_inverted;
input_gain_ = 30;
assert(input_sample_rate_ == output_sample_rate_);
CreateDuplexChannels(mclk, bclk, ws, dout, din);
// Do initialize of related interface: data_if, ctrl_if and gpio_if
audio_codec_i2s_cfg_t i2s_cfg = {
.port = I2S_NUM_0,
.rx_handle = rx_handle_,
.tx_handle = tx_handle_,
};
data_if_ = audio_codec_new_i2s_data(&i2s_cfg);
assert(data_if_ != NULL);
// Output
audio_codec_i2c_cfg_t i2c_cfg = {
.port = i2c_port,
.addr = es8311_addr,
.bus_handle = i2c_master_handle,
};
ctrl_if_ = audio_codec_new_i2c_ctrl(&i2c_cfg);
assert(ctrl_if_ != NULL);
gpio_if_ = audio_codec_new_gpio();
assert(gpio_if_ != NULL);
es8311_codec_cfg_t es8311_cfg = {};
es8311_cfg.ctrl_if = ctrl_if_;
es8311_cfg.gpio_if = gpio_if_;
es8311_cfg.codec_mode = ESP_CODEC_DEV_WORK_MODE_BOTH;
es8311_cfg.pa_pin = pa_pin;
es8311_cfg.use_mclk = use_mclk;
es8311_cfg.hw_gain.pa_voltage = 5.0;
es8311_cfg.hw_gain.codec_dac_voltage = 3.3;
es8311_cfg.pa_reverted = pa_inverted_;
codec_if_ = es8311_codec_new(&es8311_cfg);
if (codec_if_ == nullptr) {
ESP_LOGE(TAG, "Failed to create Es8311AudioCodec");
} else {
ESP_LOGI(TAG, "Es8311AudioCodec initialized");
}
}
Es8311AudioCodec::~Es8311AudioCodec() {
esp_codec_dev_delete(dev_);
audio_codec_delete_codec_if(codec_if_);
audio_codec_delete_ctrl_if(ctrl_if_);
audio_codec_delete_gpio_if(gpio_if_);
audio_codec_delete_data_if(data_if_);
}
void Es8311AudioCodec::UpdateDeviceState() {
if ((input_enabled_ || output_enabled_) && dev_ == nullptr) {
esp_codec_dev_cfg_t dev_cfg = {
.dev_type = ESP_CODEC_DEV_TYPE_IN_OUT,
.codec_if = codec_if_,
.data_if = data_if_,
};
dev_ = esp_codec_dev_new(&dev_cfg);
assert(dev_ != NULL);
esp_codec_dev_sample_info_t fs = {
.bits_per_sample = 16,
.channel = 1,
.channel_mask = 0,
.sample_rate = (uint32_t)input_sample_rate_,
.mclk_multiple = 0,
};
esp_err_t err = esp_codec_dev_open(dev_, &fs);
if (err != ESP_OK) {
if (!device_open_error_reported_) {
ESP_LOGE(TAG, "Failed to open ES8311 codec device: %s", esp_err_to_name(err));
device_open_error_reported_ = true;
}
esp_codec_dev_delete(dev_);
dev_ = nullptr;
return;
}
err = esp_codec_dev_set_in_gain(dev_, input_gain_);
if (err != ESP_OK) {
if (!device_open_error_reported_) {
ESP_LOGE(TAG, "Failed to set ES8311 input gain: %s", esp_err_to_name(err));
device_open_error_reported_ = true;
}
esp_codec_dev_close(dev_);
esp_codec_dev_delete(dev_);
dev_ = nullptr;
return;
}
// Always pin the hardware DAC at 100% so software gain in Write()
// gets the full output headroom. SetOutputVolume() never re-touches
// the hardware DAC — it only updates output_volume_ used by the
// software gain. If we wrote NVS-cached value here, vol later set to
// 100 would max software gain but hit a hardware ceiling, sounding
// identical to vol=70.
err = esp_codec_dev_set_out_vol(dev_, 100);
if (err != ESP_OK) {
if (!device_open_error_reported_) {
ESP_LOGE(TAG, "Failed to set ES8311 output volume: %s", esp_err_to_name(err));
device_open_error_reported_ = true;
}
esp_codec_dev_close(dev_);
esp_codec_dev_delete(dev_);
dev_ = nullptr;
return;
}
} else if (!input_enabled_ && !output_enabled_ && dev_ != nullptr) {
esp_codec_dev_close(dev_);
dev_ = nullptr;
}
if (pa_pin_ != GPIO_NUM_NC) {
int level = output_enabled_ ? 1 : 0;
gpio_set_level(pa_pin_, pa_inverted_ ? !level : level);
}
if (dev_ != nullptr && device_open_error_reported_) {
device_open_error_reported_ = false;
}
}
void Es8311AudioCodec::CreateDuplexChannels(gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din) {
assert(input_sample_rate_ == output_sample_rate_);
i2s_chan_config_t chan_cfg = {
.id = I2S_NUM_0,
.role = I2S_ROLE_MASTER,
.dma_desc_num = AUDIO_CODEC_DMA_DESC_NUM,
.dma_frame_num = AUDIO_CODEC_DMA_FRAME_NUM,
.auto_clear_after_cb = true,
.auto_clear_before_cb = false,
.intr_priority = 0,
};
ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, &tx_handle_, &rx_handle_));
i2s_std_config_t std_cfg = {
.clk_cfg = {
.sample_rate_hz = (uint32_t)output_sample_rate_,
.clk_src = I2S_CLK_SRC_DEFAULT,
.mclk_multiple = I2S_MCLK_MULTIPLE_256,
#ifdef I2S_HW_VERSION_2
.ext_clk_freq_hz = 0,
#endif
},
.slot_cfg = {
.data_bit_width = I2S_DATA_BIT_WIDTH_16BIT,
.slot_bit_width = I2S_SLOT_BIT_WIDTH_AUTO,
.slot_mode = I2S_SLOT_MODE_MONO,
.slot_mask = I2S_STD_SLOT_LEFT,
.ws_width = I2S_DATA_BIT_WIDTH_16BIT,
.ws_pol = false,
.bit_shift = true,
#ifdef I2S_HW_VERSION_2
.left_align = true,
.big_endian = false,
.bit_order_lsb = false
#endif
},
.gpio_cfg = {
.mclk = mclk,
.bclk = bclk,
.ws = ws,
.dout = dout,
.din = din,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false
}
}
};
ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_handle_, &std_cfg));
ESP_ERROR_CHECK(i2s_channel_init_std_mode(rx_handle_, &std_cfg));
ESP_LOGI(TAG, "Duplex channels created");
}
void Es8311AudioCodec::SetOutputVolume(int volume) {
if (volume == output_volume_) return;
// Software volume scaling happens in Write(); just update member + NVS.
AudioCodec::SetOutputVolume(volume);
ESP_LOGI(TAG, "Output volume set to %d (software scaling)", volume);
}
//ALEX 重写
void Es8311AudioCodec::SetInputGain(float gain) {
std::lock_guard<std::mutex> lock(data_if_mutex_);
if (codec_if_ == nullptr) return;
if (gain == input_gain_) return;
AudioCodec::SetInputGain(gain); // 调用基类设置变量
UpdateDeviceState(); // 关键:更新硬件寄存器
ESP_LOGI(TAG, "ES8311 hardware gain set to %.1f", gain);
}
void Es8311AudioCodec::EnableInput(bool enable) {
std::lock_guard<std::mutex> lock(data_if_mutex_);
if (codec_if_ == nullptr) {
return;
}
if (enable == input_enabled_) {
return;
}
AudioCodec::EnableInput(enable);
UpdateDeviceState();
}
void Es8311AudioCodec::EnableOutput(bool enable) {
std::lock_guard<std::mutex> lock(data_if_mutex_);
if (codec_if_ == nullptr) {
return;
}
if (enable == output_enabled_) {
return;
}
AudioCodec::EnableOutput(enable);
UpdateDeviceState();
}
int Es8311AudioCodec::Read(int16_t* dest, int samples) {
if (input_enabled_) {
//2026-6-19 ckkj debug
if (dev_ == nullptr) {
ESP_LOGW(TAG, "Read called before codec device is ready; retrying");
UpdateDeviceState();
if (dev_ == nullptr) {
ESP_LOGW(TAG, "ES8311 input unavailable, dropping %d samples", samples);
return samples;
}
}
//end debug
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_read(dev_, (void*)dest, samples * sizeof(int16_t)));
}
return samples;
}
int Es8311AudioCodec::Write(const int16_t* data, int samples) {
//if (!output_enabled_) return samples;
//2026-6-19 ckkj debug
if (!output_enabled_) {
ESP_LOGD(TAG, "Codec output disabled, skip write");
return samples;
}
if (dev_ == nullptr) {
ESP_LOGW(TAG, "Write called before codec device is ready; retrying");
UpdateDeviceState();
if (dev_ == nullptr) {
ESP_LOGW(TAG, "ES8311 output unavailable, dropping %d samples", samples);
return samples;
}
}
//end debug
if (data == nullptr || samples <= 0) {
return 0;
}
// Volume curve: linear software gain on top of a hardware DAC pinned at 100%.
// gain = output_volume_ / 100 (0..1.0)
// Hardware ceiling is the true 100% acoustic output; we never amplify
// beyond it, so vol=100 is the genuine maximum (no clipping/distortion).
if (output_volume_ <= 0) {
std::vector<int16_t> silence(samples, 0);
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_write(dev_, silence.data(), samples * sizeof(int16_t)));
return samples;
}
int vol = output_volume_;
if (vol > 100) vol = 100;
float gain = static_cast<float>(vol) / 100.0f;
// Fixed-point: gain × 256 (range 0..256)
int32_t gain_fp = static_cast<int32_t>(gain * 256.0f);
std::vector<int16_t> scaled(samples);
for (int i = 0; i < samples; i++) {
int32_t s = (static_cast<int32_t>(data[i]) * gain_fp) >> 8;
// Clamp to int16 range
if (s > 32767) s = 32767;
if (s < -32768) s = -32768;
scaled[i] = static_cast<int16_t>(s);
}
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_write(dev_, scaled.data(), samples * sizeof(int16_t)));
return samples;
}

View File

@@ -0,0 +1,44 @@
#ifndef _ES8311_AUDIO_CODEC_H
#define _ES8311_AUDIO_CODEC_H
#include "audio/audio_codec.h"
#include <driver/i2c_master.h>
#include <driver/gpio.h>
#include <esp_codec_dev.h>
#include <esp_codec_dev_defaults.h>
#include <mutex>
class Es8311AudioCodec : public AudioCodec {
private:
const audio_codec_data_if_t* data_if_ = nullptr;
const audio_codec_ctrl_if_t* ctrl_if_ = nullptr;
const audio_codec_if_t* codec_if_ = nullptr;
const audio_codec_gpio_if_t* gpio_if_ = nullptr;
esp_codec_dev_handle_t dev_ = nullptr;
gpio_num_t pa_pin_ = GPIO_NUM_NC;
bool pa_inverted_ = false;
bool device_open_error_reported_ = false;
std::mutex data_if_mutex_;
void CreateDuplexChannels(gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din);
void UpdateDeviceState();
virtual int Read(int16_t* dest, int samples) override;
virtual int Write(const int16_t* data, int samples) override;
public:
Es8311AudioCodec(void* i2c_master_handle, i2c_port_t i2c_port, int input_sample_rate, int output_sample_rate,
gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din,
gpio_num_t pa_pin, uint8_t es8311_addr, bool use_mclk = true, bool pa_inverted = false);
virtual ~Es8311AudioCodec();
//ALEX 重写
void SetInputGain(float gain) override;
virtual void SetOutputVolume(int volume) override;
virtual void EnableInput(bool enable) override;
virtual void EnableOutput(bool enable) override;
};
#endif // _ES8311_AUDIO_CODEC_H

View File

@@ -0,0 +1,254 @@
#include "voice_processor.h"
#include <esp_log.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#define TAG "VoiceProc"
// AEC filter length — recommended 4 for ESP32-S3 (see esp_afe_aec.h).
// Higher filter = better echo tail but more CPU.
static constexpr int AEC_FILTER_LENGTH_CALL = 4;
//static constexpr int AEC_FILTER_LENGTH_BARGE_IN = 4;
static constexpr int AEC_FILTER_LENGTH_BARGE_IN = 8;//(~128ms)能覆盖更长的回声路径
// NS pro frame length in ms. pro_create supports only 10ms.
// Renamed from kNsFrameLengthMs — esp_ns.h already uses that as a macro.
static constexpr int kNsFrameLengthMs = 10;
// AGC target envelope (normalized 0..1) and smoothing constants.
// Call audio should land near normal TTS loudness without boosting the room
// floor into a hiss. Track both peak and RMS: peak protects from clipping, RMS
// gates very low-level residual echo/noise.
static constexpr float AGC_TARGET_PEAK = 0.42f; // near -7.5 dBFS peak
static constexpr float AGC_MAX_GAIN = 6.0f; // enough for quiet child speech
//static constexpr float AGC_MAX_GAIN_BARGE_IN = 2.2f; // avoid boosting residual TTS echo
static constexpr float AGC_MIN_GAIN = 0.8f;
static constexpr float AGC_ENV_ATTACK = 0.45f; // fast reduction on loud peaks
static constexpr float AGC_ENV_RELEASE = 0.12f; // recover within ~1s, not 7s+
static constexpr float AGC_GAIN_SMOOTH = 0.18f; // responsive but not pumping
//static constexpr float NOISE_GATE_RMS = 0.006f; // -44 dBFS
//static constexpr float NOISE_GATE_PEAK = 0.018f; // -35 dBFS
static constexpr float NOISE_GATE_ATTENUATION = 0.20f;
//static constexpr float NOISE_GATE_ATTENUATION_BARGE_IN = 0.08f;
// 修改后,更激进地抑制低音量环境噪音
static constexpr float AGC_MAX_GAIN_BARGE_IN = 1.8f; // reduced to avoid boosting residual TTS echo
static constexpr float NOISE_GATE_RMS = 0.004f; // -48 dBFS,更激进的噪音门控
static constexpr float NOISE_GATE_PEAK = 0.015f; // -38 dBFS
static constexpr float NOISE_GATE_ATTENUATION_BARGE_IN = 0.05f; // barge-in模式更激
VoiceProcessor::VoiceProcessor() = default;
VoiceProcessor::~VoiceProcessor() { Deinit(); }
bool VoiceProcessor::Init(bool low_cost) {
if (aec_handle_) {
if (low_cost_mode_ == low_cost) return true; // already inited
Deinit();
}
low_cost_mode_ = low_cost;
const int filter_length = low_cost ? AEC_FILTER_LENGTH_BARGE_IN : AEC_FILTER_LENGTH_CALL;
// Barge-in is full-duplex human-device speech while TTS is playing.
// FD_LOW_COST is a better fit than VOIP_LOW_COST for this scenario and keeps
// CPU/memory lower than FD_HIGH_PERF.
const aec_mode_t mode = low_cost ? AEC_MODE_FD_LOW_COST : AEC_MODE_VOIP_HIGH_PERF;
// Single mic + single reference, 16kHz.
aec_handle_ = aec_create(16000, filter_length, 1, mode);
if (!aec_handle_) {
ESP_LOGE(TAG, "aec_create failed");
return false;
}
chunk_samples_ = aec_get_chunksize(aec_handle_);
if (chunk_samples_ <= 0) {
ESP_LOGE(TAG, "aec_get_chunksize returned %d", chunk_samples_);
aec_destroy(aec_handle_);
aec_handle_ = nullptr;
return false;
}
ns_frame_samples_ = 16 * kNsFrameLengthMs; // 160 samples @ 16kHz
if (!low_cost_mode_) {
ns_handle_ = ns_pro_create(kNsFrameLengthMs, /*mode=aggressive*/ 2, 16000);
if (!ns_handle_) {
ESP_LOGW(TAG, "ns_pro_create failed, continuing without NS");
}
} else {
// Barge-in runs inside the real-time audio input task while TTS is
// playing. WebRTC NS FFT processing has shown watchdog pressure on
// ESP32-S3 here, so keep the interrupt path to AEC + conservative
// AGC/gate only.
ns_handle_ = nullptr;
}
aec_out_chunk_.resize(chunk_samples_);
ns_out_chunk_.resize(ns_frame_samples_);
mic_acc_.reserve(chunk_samples_ * 2);
ref_acc_.reserve(chunk_samples_ * 2);
ns_in_acc_.reserve(ns_frame_samples_ * 2);
ESP_LOGI(TAG, "VoiceProcessor initialized: mode=%s, AEC chunk=%d, NS=%s frame=%d samples",
aec_get_mode_string(mode), chunk_samples_, ns_handle_ ? "on" : "off",
ns_frame_samples_);
return true;
}
void VoiceProcessor::Deinit() {
if (aec_handle_) {
aec_destroy(aec_handle_);
aec_handle_ = nullptr;
}
if (ns_handle_) {
ns_destroy(ns_handle_);
ns_handle_ = nullptr;
}
chunk_samples_ = 0;
ns_frame_samples_ = 0;
mic_acc_.clear();
ref_acc_.clear();
ns_in_acc_.clear();
mic_acc_pos_ = 0;
ref_acc_pos_ = 0;
ns_in_acc_pos_ = 0;
low_cost_mode_ = false;
envelope_ = 0.08f;
gain_ = 1.0f;
}
void VoiceProcessor::Reset() {
mic_acc_.clear();
ref_acc_.clear();
ns_in_acc_.clear();
mic_acc_pos_ = 0;
ref_acc_pos_ = 0;
ns_in_acc_pos_ = 0;
envelope_ = 0.08f;
gain_ = 1.0f;
}
bool VoiceProcessor::Process(const int16_t* mic, const int16_t* ref,
size_t samples, std::vector<int16_t>& out) {
if (!aec_handle_ || !mic || !ref) return false;
// Append this batch onto accumulators.
mic_acc_.insert(mic_acc_.end(), mic, mic + samples);
ref_acc_.insert(ref_acc_.end(), ref, ref + samples);
// Process AEC chunks while both accumulators hold enough. Use cursor
// offsets instead of vector.erase(begin...), which was moving most of the
// buffer several times per 60ms frame and could starve the idle task.
while (mic_acc_.size() - mic_acc_pos_ >= static_cast<size_t>(chunk_samples_) &&
ref_acc_.size() - ref_acc_pos_ >= static_cast<size_t>(chunk_samples_)) {
aec_process(aec_handle_,
mic_acc_.data() + mic_acc_pos_,
ref_acc_.data() + ref_acc_pos_,
aec_out_chunk_.data());
mic_acc_pos_ += chunk_samples_;
ref_acc_pos_ += chunk_samples_;
if (ns_handle_) {
// Hand AEC output to NS accumulator only when NS is active. In
// low-cost TTS barge-in mode NS is intentionally off; feeding this
// buffer there would grow it forever and eventually abort on OOM.
ns_in_acc_.insert(ns_in_acc_.end(),
aec_out_chunk_.begin(), aec_out_chunk_.end());
// NS processes 160-sample frames. AEC chunks are typically 256 so
// we'll usually run 1-2 NS frames per AEC chunk.
while (ns_in_acc_.size() - ns_in_acc_pos_ >= static_cast<size_t>(ns_frame_samples_)) {
ns_process(ns_handle_, ns_in_acc_.data() + ns_in_acc_pos_, ns_out_chunk_.data());
ApplyAgc(ns_out_chunk_.data(), ns_out_chunk_.size());
out.insert(out.end(),
ns_out_chunk_.begin(), ns_out_chunk_.end());
ns_in_acc_pos_ += ns_frame_samples_;
}
} else {
// Fallback: no NS available: push AEC output directly after AGC.
ApplyAgc(aec_out_chunk_.data(), aec_out_chunk_.size());
out.insert(out.end(),
aec_out_chunk_.begin(), aec_out_chunk_.end());
}
CompactAccumulatorsIfNeeded();
//2026-6-23 ckkj debug
vTaskDelay(1); // 让出 CPU 给 IDLE 任务,防止 Task Watchdog 触发
}
return true;
}
void VoiceProcessor::CompactAccumulatorsIfNeeded() {
const size_t compact_threshold =
static_cast<size_t>(chunk_samples_ > 0 ? chunk_samples_ * 4 : 1024);
if (mic_acc_pos_ > 0 &&
(mic_acc_pos_ >= compact_threshold || mic_acc_pos_ * 2 >= mic_acc_.size())) {
mic_acc_.erase(mic_acc_.begin(), mic_acc_.begin() + mic_acc_pos_);
mic_acc_pos_ = 0;
}
if (ref_acc_pos_ > 0 &&
(ref_acc_pos_ >= compact_threshold || ref_acc_pos_ * 2 >= ref_acc_.size())) {
ref_acc_.erase(ref_acc_.begin(), ref_acc_.begin() + ref_acc_pos_);
ref_acc_pos_ = 0;
}
const size_t ns_threshold =
static_cast<size_t>(ns_frame_samples_ > 0 ? ns_frame_samples_ * 8 : 1024);
if (ns_in_acc_pos_ > 0 &&
(ns_in_acc_pos_ >= ns_threshold || ns_in_acc_pos_ * 2 >= ns_in_acc_.size())) {
ns_in_acc_.erase(ns_in_acc_.begin(), ns_in_acc_.begin() + ns_in_acc_pos_);
ns_in_acc_pos_ = 0;
}
}
void VoiceProcessor::ApplyAgc(int16_t* samples, size_t n) {
// Update envelope from peak of this block and compute RMS for a very
// conservative residual-noise gate.
int16_t peak = 0;
int64_t sum_sq = 0;
for (size_t i = 0; i < n; ++i) {
int32_t v = samples[i];
int32_t a32 = v < 0 ? -v : v;
int16_t a = a32 > 32767 ? 32767 : static_cast<int16_t>(a32);
if (a > peak) peak = a;
sum_sq += v * v;
}
float peak_norm = peak / 32768.0f;
float rms_norm = 0.0f;
if (n > 0) {
rms_norm = sqrtf(static_cast<float>(sum_sq) / static_cast<float>(n)) / 32768.0f;
}
// If AEC/NS leaves only very low-level residue, attenuate it and avoid
// letting AGC turn it into audible hiss when two devices are close.
if (rms_norm < NOISE_GATE_RMS && peak_norm < NOISE_GATE_PEAK) {
float attenuation = low_cost_mode_ ? NOISE_GATE_ATTENUATION_BARGE_IN : NOISE_GATE_ATTENUATION;
for (size_t i = 0; i < n; ++i) {
samples[i] = static_cast<int16_t>(samples[i] * attenuation);
}
return;
}
// Asymmetric envelope tracker: fast attack, slow release
float alpha = (peak_norm > envelope_) ? AGC_ENV_ATTACK : AGC_ENV_RELEASE;
envelope_ += alpha * (peak_norm - envelope_);
if (envelope_ < 0.01f) envelope_ = 0.01f; // avoid div-by-zero + noise boost
// Target gain so envelope reaches AGC_TARGET_PEAK
float target_gain = AGC_TARGET_PEAK / envelope_;
float max_gain = low_cost_mode_ ? AGC_MAX_GAIN_BARGE_IN : AGC_MAX_GAIN;
if (target_gain > max_gain) target_gain = max_gain;
if (target_gain < AGC_MIN_GAIN) target_gain = AGC_MIN_GAIN;
// Smooth gain changes (prevent pumping / breathing artefacts)
gain_ += AGC_GAIN_SMOOTH * (target_gain - gain_);
// Apply with hard limiter clip
for (size_t i = 0; i < n; ++i) {
float v = samples[i] * gain_;
if (v > 32767.0f) v = 32767.0f;
if (v < -32768.0f) v = -32768.0f;
samples[i] = static_cast<int16_t>(v);
}
}

View File

@@ -0,0 +1,92 @@
#pragma once
/**
* Voice processing front-end for phone-call mode.
*
* Chain (16kHz mono int16):
* MIC ─┐
* ├─→ AEC (VOIP_HIGH_PERF, filter_length=4) ─→ NS (pro, aggressive) ─→ AGC (soft) ─→ clean PCM
* REF ─┘
*
* AEC_MODE_VOIP_HIGH_PERF already includes nonlinear residual echo
* suppression — the explicit NS step on top is mainly for ambient noise
* (kid-voice / room hum), not echo. AGC is a simple envelope normalizer in
* software (ESP-SR's AGC API is coarse; children voice amplitude swing is
* better handled by a gentle limiter).
*
* Chunk handling: AEC has a fixed internal chunk size (typically 256 samples
* @ 16kHz). The input and reference buffers for one Process() call can be of
* any length; unprocessed tail samples are held in internal accumulators and
* processed on the next call.
*/
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
#include "esp_aec.h"
#include "esp_ns.h"
class VoiceProcessor {
public:
VoiceProcessor();
~VoiceProcessor();
// Initialize AEC and AGC. Call mode also enables NS; barge-in keeps NS off
// to reduce CPU on the audio input path.
// Safe to call multiple times; second call is a no-op if already inited.
bool Init(bool low_cost = false);
// Free all allocated resources. Safe to call repeatedly.
void Deinit();
bool IsReady() const { return aec_handle_ != nullptr; }
bool IsLowCostMode() const { return low_cost_mode_; }
// AEC's fixed chunk size in samples (at 16kHz). 0 if not inited.
int ChunkSamples() const { return chunk_samples_; }
// Process one batch of mic + reference PCM (both 16kHz mono int16, equal
// length required). Clean output is appended to `out` (length depends on
// chunk alignment — unprocessed tail is buffered for next call).
//
// Returns false if not initialized or sizes mismatch.
bool Process(const int16_t* mic, const int16_t* ref, size_t samples,
std::vector<int16_t>& out);
// Clear internal accumulators. Call when entering/leaving call mode.
void Reset();
private:
aec_handle_t* aec_handle_ = nullptr;
ns_handle_t ns_handle_ = nullptr;
bool low_cost_mode_ = false;
int chunk_samples_ = 0; // AEC chunk size in samples (e.g. 256)
int ns_frame_samples_ = 0; // NS pro requires 10ms = 160 samples @ 16kHz
// Accumulators for chunk alignment. AEC reads N=chunk_samples_ at a time;
// any leftover from a partial Process() stays here until next call.
std::vector<int16_t> mic_acc_;
std::vector<int16_t> ref_acc_;
size_t mic_acc_pos_ = 0;
size_t ref_acc_pos_ = 0;
// NS operates on a different chunk (160 samples). Second-stage accumulator
// sits between AEC output and NS input.
std::vector<int16_t> ns_in_acc_;
size_t ns_in_acc_pos_ = 0;
// Pre-allocated scratch buffers for one chunk — avoid per-call alloc.
std::vector<int16_t> aec_out_chunk_;
std::vector<int16_t> ns_out_chunk_;
// Soft AGC state: simple envelope tracker + gain smoother.
float envelope_ = 1.0f; // EMA of recent sample peak
float gain_ = 1.0f; // current applied gain
// Apply soft AGC in-place on `samples`. Gain moves slowly toward a target
// that keeps peak envelope near ~0.3 * full-scale (10kRMS).
void ApplyAgc(int16_t* samples, size_t n);
void CompactAccumulatorsIfNeeded();
};

71
main/audio/wake_word.cc Normal file
View File

@@ -0,0 +1,71 @@
#include "wake_word.h"
#include <esp_log.h>
#include <esp_wn_iface.h>
#include <esp_wn_models.h>
#include <model_path.h>
#include <cstring>
#define TAG "WakeWord"
bool WakeWordDetector::Initialize()
{
srmodel_list_t* models = esp_srmodel_init("model");
if (!models) {
ESP_LOGE(TAG, "Failed to init SR models");
return false;
}
// Find the custom wake word model (你好播乐 = ni3hao3bo1le4)
char* model_name = esp_srmodel_filter(models, ESP_WN_PREFIX, "ni3hao3bo1le4");
if (!model_name) {
// Fallback: use any available wake word model
model_name = esp_srmodel_filter(models, ESP_WN_PREFIX, NULL);
}
if (!model_name) {
ESP_LOGE(TAG, "No wake word model found");
return false;
}
ESP_LOGI(TAG, "Using wake word model: %s", model_name);
const esp_wn_iface_t* iface = esp_wn_handle_from_name(model_name);
if (!iface) {
ESP_LOGE(TAG, "Failed to get WakeNet interface");
return false;
}
wakenet_iface_ = iface;
wakenet_handle_ = iface->create(model_name, DET_MODE_90);
if (!wakenet_handle_) {
ESP_LOGE(TAG, "Failed to create WakeNet instance");
return false;
}
chunk_size_ = iface->get_samp_chunksize(static_cast<model_iface_data_t*>(wakenet_handle_));
int sample_rate = iface->get_samp_rate(static_cast<model_iface_data_t*>(wakenet_handle_));
ESP_LOGI(TAG, "WakeNet ready: chunk_size=%d, sample_rate=%d", chunk_size_, sample_rate);
initialized_ = true;
return true;
}
void WakeWordDetector::SetCallback(DetectedCallback callback)
{
callback_ = callback;
}
void WakeWordDetector::Feed(const int16_t* samples, int count)
{
if (!initialized_ || !wakenet_iface_ || !wakenet_handle_) return;
auto* iface = static_cast<const esp_wn_iface_t*>(wakenet_iface_);
int result = iface->detect(static_cast<model_iface_data_t*>(wakenet_handle_), const_cast<int16_t*>(samples));
if (result > 0) {
ESP_LOGI(TAG, "Wake word detected!");
if (callback_) {
callback_();
}
}
}

30
main/audio/wake_word.h Normal file
View File

@@ -0,0 +1,30 @@
#pragma once
#include <functional>
#include <atomic>
#include <cstdint>
/**
* WakeNet-based wake word detector.
* Feeds 16kHz PCM audio to ESP-SR WakeNet and triggers callback on detection.
*/
class WakeWordDetector {
public:
using DetectedCallback = std::function<void()>;
bool Initialize();
void SetCallback(DetectedCallback callback);
// Feed 16kHz 16-bit mono PCM samples. Caller must provide chunk_size() samples.
void Feed(const int16_t* samples, int count);
int chunk_size() const { return chunk_size_; }
bool is_initialized() const { return initialized_; }
private:
void* wakenet_handle_ = nullptr;
const void* wakenet_iface_ = nullptr;
DetectedCallback callback_;
int chunk_size_ = 0;
bool initialized_ = false;
};