bolar_2 backup
This commit is contained in:
492
main/adapters/esp_audio_engine.cc
Normal file
492
main/adapters/esp_audio_engine.cc
Normal file
@@ -0,0 +1,492 @@
|
||||
#include "adapters/esp_audio_engine.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include <new>
|
||||
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_log.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "EspAudioEngine2";
|
||||
constexpr uint32_t kAudioOutputInitializationError = 2001;
|
||||
constexpr uint32_t kPlaybackPipelineInitializationError = 2002;
|
||||
constexpr uint32_t kPrerollAllocationError = 2003;
|
||||
|
||||
} // namespace
|
||||
|
||||
EspAudioEngine::EspAudioEngine(
|
||||
IAudioOutput& output,
|
||||
IAudioInput& input)
|
||||
: output_(output),
|
||||
input_(input),
|
||||
playback_(output),
|
||||
prompts_(playback_),
|
||||
capture_(input)
|
||||
{
|
||||
capture_.SetProcessor(&voice_frontend_);
|
||||
playback_.SetReferenceSink(&voice_frontend_);
|
||||
}
|
||||
|
||||
void EspAudioEngine::SetUplinkSink(IEncodedAudioSink* sink)
|
||||
{
|
||||
capture_.SetSink(sink);
|
||||
}
|
||||
|
||||
EspAudioEngine::~EspAudioEngine()
|
||||
{
|
||||
Stop();
|
||||
if (preroll_ != nullptr) {
|
||||
preroll_->~DownlinkPrerollBuffer();
|
||||
heap_caps_free(preroll_);
|
||||
preroll_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void EspAudioEngine::SetEventPublisher(IEventPublisher* publisher)
|
||||
{
|
||||
publisher_ = publisher;
|
||||
playback_.SetEventPublisher(publisher);
|
||||
voice_frontend_.SetEventPublisher(publisher);
|
||||
}
|
||||
|
||||
bool EspAudioEngine::Start()
|
||||
{
|
||||
if (started_) {
|
||||
return true;
|
||||
}
|
||||
if (preroll_ == nullptr) {
|
||||
void* storage = heap_caps_malloc(
|
||||
sizeof(DownlinkPrerollBuffer),
|
||||
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (storage == nullptr) {
|
||||
PublishFatalError(kPrerollAllocationError);
|
||||
return false;
|
||||
}
|
||||
preroll_ = new (storage) DownlinkPrerollBuffer();
|
||||
}
|
||||
if (!output_.Initialize()) {
|
||||
PublishFatalError(kAudioOutputInitializationError);
|
||||
return false;
|
||||
}
|
||||
if (!playback_.Initialize() || !prompts_.Initialize() ||
|
||||
!voice_frontend_.Initialize() ||
|
||||
!capture_.Initialize() || !playback_.Start() ||
|
||||
!capture_.Start()) {
|
||||
capture_.Stop();
|
||||
playback_.Stop();
|
||||
output_.Shutdown();
|
||||
PublishFatalError(kPlaybackPipelineInitializationError);
|
||||
return false;
|
||||
}
|
||||
|
||||
started_ = true;
|
||||
ESP_LOGI(kTag, "audio output and playback pipeline started");
|
||||
return true;
|
||||
}
|
||||
|
||||
void EspAudioEngine::Stop()
|
||||
{
|
||||
if (!started_) {
|
||||
return;
|
||||
}
|
||||
capture_.Stop();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downlink_mutex_);
|
||||
ClearPrerollLocked();
|
||||
playback_.Stop();
|
||||
}
|
||||
output_.Shutdown();
|
||||
started_ = false;
|
||||
}
|
||||
|
||||
void EspAudioEngine::ApplyPolicy(AudioPolicy policy)
|
||||
{
|
||||
requested_policy_.store(policy);
|
||||
RefreshEffectivePolicy();
|
||||
}
|
||||
|
||||
void EspAudioEngine::SetVolume(uint8_t volume_percent)
|
||||
{
|
||||
output_.SetVolume(volume_percent);
|
||||
}
|
||||
|
||||
void EspAudioEngine::SetWakeWordEnabled(bool enabled)
|
||||
{
|
||||
wake_word_enabled_.store(enabled);
|
||||
RefreshEffectivePolicy();
|
||||
}
|
||||
|
||||
void EspAudioEngine::SetBargeInEnabled(bool enabled)
|
||||
{
|
||||
barge_in_enabled_.store(enabled);
|
||||
RefreshEffectivePolicy();
|
||||
}
|
||||
|
||||
void EspAudioEngine::SetPlaybackPaused(bool paused)
|
||||
{
|
||||
playback_.SetPaused(paused);
|
||||
}
|
||||
|
||||
void EspAudioEngine::RefreshEffectivePolicy()
|
||||
{
|
||||
const AudioPolicy requested = requested_policy_.load();
|
||||
const bool wake_word = wake_word_enabled_.load();
|
||||
const bool barge_in = barge_in_enabled_.load();
|
||||
AudioPolicy effective = requested;
|
||||
if (requested == AudioPolicy::kWakeWordOnly && !wake_word) {
|
||||
effective = AudioPolicy::kOff;
|
||||
} else if (
|
||||
requested == AudioPolicy::kBargeInDuplex && !barge_in) {
|
||||
effective = wake_word
|
||||
? AudioPolicy::kWakeWordDuplex
|
||||
: AudioPolicy::kPlaybackOnly;
|
||||
}
|
||||
voice_frontend_.SetWakeWordEnabled(wake_word);
|
||||
capture_.ApplyPolicy(effective);
|
||||
ESP_LOGI(
|
||||
kTag,
|
||||
"audio policy requested=%s effective=%s wake=%d barge=%d",
|
||||
ToString(requested),
|
||||
ToString(effective),
|
||||
wake_word ? 1 : 0,
|
||||
barge_in ? 1 : 0);
|
||||
}
|
||||
|
||||
void EspAudioEngine::OnRealtimeBinary(
|
||||
const uint8_t* data,
|
||||
size_t size,
|
||||
uint32_t playback_session_id)
|
||||
{
|
||||
if (!SubmitOpusFrame(playback_session_id, data, size)) {
|
||||
ESP_LOGW(kTag,
|
||||
"downlink Opus dropped session=%lu size=%u",
|
||||
static_cast<unsigned long>(playback_session_id),
|
||||
static_cast<unsigned>(size));
|
||||
}
|
||||
}
|
||||
|
||||
void EspAudioEngine::CancelPlayback(PlaybackSessionId session_id)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downlink_mutex_);
|
||||
ClearPrerollLocked();
|
||||
playback_.Cancel(session_id);
|
||||
}
|
||||
|
||||
void EspAudioEngine::BeginRemotePlayback(
|
||||
PlaybackSessionId session_id,
|
||||
PlaybackPriority priority)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downlink_mutex_);
|
||||
const PlaybackSource source =
|
||||
priority == PlaybackPriority::kCall
|
||||
? PlaybackSource::kCall
|
||||
: PlaybackSource::kRemoteTts;
|
||||
const PlaybackStartResult result = playback_.StartSession(
|
||||
source, priority, session_id);
|
||||
if (result.status != PlaybackStartStatus::kStarted &&
|
||||
result.status != PlaybackStartStatus::kAlreadyActive) {
|
||||
if (preroll_ != nullptr &&
|
||||
preroll_->session_id() == session_id) {
|
||||
ClearPrerollLocked();
|
||||
}
|
||||
ESP_LOGW(kTag,
|
||||
"remote playback rejected status=%s session=%lu priority=%s",
|
||||
ToString(result.status),
|
||||
static_cast<unsigned long>(session_id),
|
||||
ToString(priority));
|
||||
return;
|
||||
}
|
||||
FlushPrerollLocked(session_id);
|
||||
}
|
||||
|
||||
void EspAudioEngine::EndPlaybackInput(PlaybackSessionId session_id)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downlink_mutex_);
|
||||
if (!playback_.EndInput(session_id)) {
|
||||
if (preroll_ != nullptr &&
|
||||
preroll_->session_id() == session_id) {
|
||||
ClearPrerollLocked();
|
||||
}
|
||||
ESP_LOGW(kTag, "ignored end input for stale session=%lu",
|
||||
static_cast<unsigned long>(session_id));
|
||||
}
|
||||
}
|
||||
|
||||
bool EspAudioEngine::SubmitOpusFrame(
|
||||
PlaybackSessionId session_id,
|
||||
const uint8_t* data,
|
||||
size_t size)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(downlink_mutex_);
|
||||
if (playback_.SubmitOpus(session_id, data, size)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const PlaybackSessionSnapshot snapshot = playback_.Snapshot();
|
||||
if ((snapshot.active && snapshot.id == session_id) ||
|
||||
preroll_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
return preroll_->Push(session_id, data, size);
|
||||
}
|
||||
|
||||
void EspAudioEngine::ClearPrerollLocked()
|
||||
{
|
||||
if (preroll_ != nullptr) {
|
||||
preroll_->Reset();
|
||||
}
|
||||
}
|
||||
|
||||
void EspAudioEngine::FlushPrerollLocked(PlaybackSessionId session_id)
|
||||
{
|
||||
if (preroll_ == nullptr ||
|
||||
preroll_->session_id() != session_id) {
|
||||
return;
|
||||
}
|
||||
const size_t frame_count = preroll_->frame_count();
|
||||
size_t submitted = 0;
|
||||
for (; submitted < frame_count; ++submitted) {
|
||||
if (!playback_.SubmitOpus(
|
||||
session_id,
|
||||
preroll_->FrameData(submitted),
|
||||
preroll_->FrameSize(submitted))) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
preroll_->Reset();
|
||||
if (submitted != frame_count) {
|
||||
ESP_LOGW(
|
||||
kTag,
|
||||
"downlink pre-roll flush incomplete session=%lu submitted=%u total=%u",
|
||||
static_cast<unsigned long>(session_id),
|
||||
static_cast<unsigned>(submitted),
|
||||
static_cast<unsigned>(frame_count));
|
||||
} else if (frame_count != 0) {
|
||||
ESP_LOGD(
|
||||
kTag,
|
||||
"downlink pre-roll flushed session=%lu frames=%u",
|
||||
static_cast<unsigned long>(session_id),
|
||||
static_cast<unsigned>(frame_count));
|
||||
}
|
||||
}
|
||||
|
||||
PlaybackSessionId EspAudioEngine::PlayLocalPrompt(
|
||||
LocalPrompt prompt,
|
||||
PlaybackPriority priority,
|
||||
int16_t selector)
|
||||
{
|
||||
const PlaybackSessionId session_id =
|
||||
prompts_.Play(prompt, priority, selector);
|
||||
if (session_id == 0 && publisher_ != nullptr) {
|
||||
publisher_->Publish(
|
||||
AppEvent::Make(AppEventType::kPlaybackFailed));
|
||||
} else if (publisher_ != nullptr) {
|
||||
publisher_->Publish(AppEvent::Make(
|
||||
AppEventType::kLocalPromptStarted,
|
||||
session_id,
|
||||
static_cast<int32_t>(prompt),
|
||||
static_cast<uint32_t>(priority)));
|
||||
}
|
||||
return session_id;
|
||||
}
|
||||
|
||||
PlaybackSessionId EspAudioEngine::PlayDetachedPrompt(
|
||||
LocalPrompt prompt,
|
||||
PlaybackPriority priority)
|
||||
{
|
||||
// Deliberately silent on the control plane: no kLocalPromptStarted, no
|
||||
// kPlaybackFailed. The caller's conversation state must survive this
|
||||
// prompt unchanged.
|
||||
const PlaybackSessionId session_id =
|
||||
prompts_.Play(prompt, priority, -1);
|
||||
if (session_id == 0) {
|
||||
ESP_LOGW(kTag, "detached prompt rejected prompt=%s",
|
||||
ToString(prompt));
|
||||
}
|
||||
return session_id;
|
||||
}
|
||||
|
||||
uint8_t EspAudioEngine::OutputVolumePercent() const
|
||||
{
|
||||
return output_.VolumePercent();
|
||||
}
|
||||
|
||||
PlaybackSessionId EspAudioEngine::PlayLocalSequence(
|
||||
const LocalPromptSequence& sequence,
|
||||
PlaybackPriority priority)
|
||||
{
|
||||
const PlaybackSessionId session_id =
|
||||
prompts_.PlaySequence(sequence, priority);
|
||||
if (session_id == 0 && publisher_ != nullptr) {
|
||||
publisher_->Publish(
|
||||
AppEvent::Make(AppEventType::kPlaybackFailed));
|
||||
} else if (publisher_ != nullptr) {
|
||||
publisher_->Publish(AppEvent::Make(
|
||||
AppEventType::kLocalSequenceStarted,
|
||||
session_id,
|
||||
static_cast<int32_t>(sequence.count),
|
||||
static_cast<uint32_t>(priority)));
|
||||
}
|
||||
return session_id;
|
||||
}
|
||||
|
||||
PlaybackSessionSnapshot EspAudioEngine::PlaybackSnapshot() const
|
||||
{
|
||||
return playback_.Snapshot();
|
||||
}
|
||||
|
||||
PlaybackMetrics EspAudioEngine::PlaybackMetricsSnapshot() const
|
||||
{
|
||||
return playback_.Metrics();
|
||||
}
|
||||
|
||||
CaptureMetrics EspAudioEngine::CaptureMetricsSnapshot() const
|
||||
{
|
||||
return capture_.Metrics();
|
||||
}
|
||||
|
||||
VoiceFrontendMetrics EspAudioEngine::VoiceMetricsSnapshot() const
|
||||
{
|
||||
return voice_frontend_.Metrics();
|
||||
}
|
||||
|
||||
void EspAudioEngine::ReleaseWakeWord()
|
||||
{
|
||||
voice_frontend_.ReleaseWakeWord();
|
||||
}
|
||||
|
||||
bool EspAudioEngine::WaitForPlaybackIdle(uint32_t timeout_ms)
|
||||
{
|
||||
constexpr uint32_t kPollIntervalMs = 20;
|
||||
uint32_t waited_ms = 0;
|
||||
while (playback_.Active()) {
|
||||
if (waited_ms >= timeout_ms) {
|
||||
ESP_LOGW(kTag, "playback still active after %lums",
|
||||
static_cast<unsigned long>(timeout_ms));
|
||||
return false;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(kPollIntervalMs));
|
||||
waited_ms += kPollIntervalMs;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void EspAudioEngine::LogAudioMetrics(const char* reason)
|
||||
{
|
||||
voice_frontend_.LogMetrics(reason);
|
||||
// The capture counters answer the question the voice counters raise: when
|
||||
// the reference ring keeps overrunning, it is because this task is not
|
||||
// consuming one frame per 60 ms. read_failures and encode_failures say
|
||||
// whether frames are being lost at the I2S read or in the DSP/encoder.
|
||||
const CaptureMetrics capture = capture_.Metrics();
|
||||
ESP_LOGI(kTag,
|
||||
"capture metrics (%s) read=%lu encoded=%lu sent=%lu "
|
||||
"read_fail=%lu encode_fail=%lu backpressure=%lu max_bytes=%lu",
|
||||
reason,
|
||||
static_cast<unsigned long>(capture.frames_read),
|
||||
static_cast<unsigned long>(capture.frames_encoded),
|
||||
static_cast<unsigned long>(capture.frames_sent),
|
||||
static_cast<unsigned long>(capture.read_failures),
|
||||
static_cast<unsigned long>(capture.encode_failures),
|
||||
static_cast<unsigned long>(capture.backpressure_drops),
|
||||
static_cast<unsigned long>(capture.maximum_encoded_bytes));
|
||||
}
|
||||
|
||||
bool EspAudioEngine::LogAudioFrameStats()
|
||||
{
|
||||
const VoiceFrameStats stats = voice_frontend_.ConsumeFrameStats();
|
||||
if (stats.frames == 0) {
|
||||
return false;
|
||||
}
|
||||
// Only duplex windows carry information worth a log line: idle wake-word
|
||||
// and quiet capture windows printed all-zero ERL/reference columns every
|
||||
// two seconds and drowned the conversation log. The accumulators above
|
||||
// are still consumed either way so a later interesting window reports
|
||||
// only its own frames.
|
||||
const bool duplex_window =
|
||||
stats.policy == AudioPolicy::kBargeInDuplex ||
|
||||
stats.policy == AudioPolicy::kCallDuplex ||
|
||||
stats.reference_present_frames != 0;
|
||||
if (!duplex_window) {
|
||||
capture_.ConsumeTimings();
|
||||
return false;
|
||||
}
|
||||
const uint32_t frames = stats.frames;
|
||||
const uint32_t microphone_rms = stats.microphone_rms_sum / frames;
|
||||
const uint32_t processed_rms = stats.processed_rms_sum / frames;
|
||||
const uint32_t reference_rms = stats.reference_rms_sum / frames;
|
||||
// Echo return loss: how much quieter the chain made the microphone. With a
|
||||
// correctly aligned reference this is strongly positive while the speaker
|
||||
// is playing; near 0 dB means the AEC is not cancelling and the device is
|
||||
// about to hear itself.
|
||||
float echo_return_loss_db = 0.0F;
|
||||
if (microphone_rms > 0 && processed_rms > 0) {
|
||||
echo_return_loss_db = 20.0F * std::log10(
|
||||
static_cast<float>(microphone_rms) /
|
||||
static_cast<float>(processed_rms));
|
||||
}
|
||||
const uint32_t period_us_avg = frames > 1
|
||||
? static_cast<uint32_t>(stats.period_us_sum / (frames - 1))
|
||||
: 0;
|
||||
const CaptureTimings timings = capture_.ConsumeTimings();
|
||||
if (timings.frames != 0) {
|
||||
const uint32_t n = timings.frames;
|
||||
ESP_LOGI(
|
||||
kTag,
|
||||
"capture timing n=%lu read=%lu/%lu convert=%lu process=%lu/%lu "
|
||||
"encode=%lu/%lu submit=%lu/%lu (us, avg/max)",
|
||||
static_cast<unsigned long>(n),
|
||||
static_cast<unsigned long>(timings.read_us / n),
|
||||
static_cast<unsigned long>(timings.read_us_max),
|
||||
static_cast<unsigned long>(timings.convert_us / n),
|
||||
static_cast<unsigned long>(timings.process_us / n),
|
||||
static_cast<unsigned long>(timings.process_us_max),
|
||||
static_cast<unsigned long>(timings.encode_us / n),
|
||||
static_cast<unsigned long>(timings.encode_us_max),
|
||||
static_cast<unsigned long>(timings.submit_us / n),
|
||||
static_cast<unsigned long>(timings.submit_us_max));
|
||||
}
|
||||
ESP_LOGI(
|
||||
kTag,
|
||||
"frame stats policy=%s n=%lu mic_rms=%lu/%lu out_rms=%lu/%lu "
|
||||
"erl=%.1fdB ref_rms=%lu/%lu ref_present=%lu ref_active=%lu "
|
||||
"ref_depth=%.1f/%lu aec=%d ns=%d barge_profile=%d agc_gain=%.2f "
|
||||
"vad_speech=%lu period_avg=%.1fms period_max=%.1fms",
|
||||
ToString(stats.policy),
|
||||
static_cast<unsigned long>(frames),
|
||||
static_cast<unsigned long>(microphone_rms),
|
||||
static_cast<unsigned long>(stats.microphone_rms_peak),
|
||||
static_cast<unsigned long>(processed_rms),
|
||||
static_cast<unsigned long>(stats.processed_rms_peak),
|
||||
echo_return_loss_db,
|
||||
static_cast<unsigned long>(reference_rms),
|
||||
static_cast<unsigned long>(stats.reference_rms_peak),
|
||||
static_cast<unsigned long>(stats.reference_present_frames),
|
||||
static_cast<unsigned long>(stats.reference_active_frames),
|
||||
static_cast<double>(stats.reference_depth_sum) /
|
||||
static_cast<double>(frames),
|
||||
static_cast<unsigned long>(stats.reference_depth_peak),
|
||||
stats.aec_active ? 1 : 0,
|
||||
stats.ns_active ? 1 : 0,
|
||||
stats.barge_in_profile ? 1 : 0,
|
||||
static_cast<double>(stats.agc_gain),
|
||||
static_cast<unsigned long>(stats.vad_speech_frames),
|
||||
static_cast<double>(period_us_avg) / 1000.0,
|
||||
static_cast<double>(stats.period_us_max) / 1000.0);
|
||||
return true;
|
||||
}
|
||||
|
||||
void EspAudioEngine::PublishFatalError(uint32_t error_id)
|
||||
{
|
||||
ESP_LOGE(kTag, "fatal audio initialization error=%lu",
|
||||
static_cast<unsigned long>(error_id));
|
||||
if (publisher_ != nullptr) {
|
||||
publisher_->Publish(
|
||||
AppEvent::Make(AppEventType::kFatalError, error_id));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
Reference in New Issue
Block a user