Files
bolar_2/main/audio/voice_dsp.h
2026-11-27 16:38:11 +08:00

85 lines
2.7 KiB
C++

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