Files
bolar_1/main/audio/voice_processor.cc

255 lines
10 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 "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);
}
}