#include "audio/voice_dsp.h" #include #include #include #include #include #include #include namespace borla { namespace { constexpr const char* kTag = "VoiceDsp2"; constexpr float kTargetPeak = 0.42f; constexpr float kMinimumGain = 0.8f; constexpr float kMaximumGain = 4.0f; constexpr float kBargeInMaximumGain = 1.8f; constexpr float kNoiseGateAttenuation = 0.1f; constexpr float kBargeInNoiseGateAttenuation = 0.05f; // esp-sr allocates its AEC and NS state with plain malloc, and this build // routes allocations larger than 16 KB to PSRAM. An earlier revision forced // them into internal SRAM on the theory that the adaptive filter running over // the PSRAM bus explained the AEC's per-frame cost. Field measurement killed // that theory twice over: with the states internal the AEC still cost ~50 ms // per 60 ms frame (placement was worth at most a few ms), and the ~50 KB of // internal RAM they consumed starved lwIP (free=4415 min=531) until a TLS // send failed mid-conversation and dropped the WebSocket. PSRAM placement is // therefore the correct trade; the probes below keep reporting where the // states actually land so the question stays answered. } // namespace VoiceDsp::~VoiceDsp() { DisableEchoCancellation(); if (ns_ != nullptr) { ns_destroy(ns_); } } bool VoiceDsp::InitializeNoiseSuppression() { if (ns_ != nullptr) { return true; } const size_t internal_before = heap_caps_get_free_size(MALLOC_CAP_INTERNAL); ns_ = ns_pro_create(10, 2, 16000); if (ns_ == nullptr) { ESP_LOGE(kTag, "NS initialization failed"); return false; } ESP_LOGI(kTag, "NS state internal=%d bytes", static_cast( internal_before - heap_caps_get_free_size(MALLOC_CAP_INTERNAL))); return true; } bool VoiceDsp::EnableEchoCancellation(bool barge_in_profile) { if (aec_ != nullptr) { // Both profiles use identical aec_create parameters — the flag only // selects post-processing (NS off + conservative AGC for barge-in). // Never tear the state down for a profile flip: aec_create grabs // whatever internal RAM is free at that instant and keeps it for the // rest of the session, so a mid-session re-create once confiscated // the websocket's reconnect budget the moment it was released // (internal free pinned at 75 bytes, every TLS attempt failing). if (barge_in_profile_ != barge_in_profile) { barge_in_profile_ = barge_in_profile; Reset(); } return true; } // FD_LOW_COST left speech-shaped TTS residue at RMS 4k-12k on this // board. VOIP_HIGH_PERF/filter=4 is the field-proven ESP32-S3 setup for // both barge-in and calls. The profile flag selects conservative // post-processing for barge-in; it no longer selects a weaker AEC. const aec_mode_t mode = AEC_MODE_VOIP_HIGH_PERF; const int filter_length = 4; // The deltas logged below say where the state actually landed — see the // note above InitializeNoiseSuppression for why PSRAM is the intended // answer. const size_t internal_before = heap_caps_get_free_size(MALLOC_CAP_INTERNAL); const size_t psram_before = heap_caps_get_free_size(MALLOC_CAP_SPIRAM); aec_ = aec_create(16000, filter_length, 1, mode); ESP_LOGI(kTag, "AEC state allocated internal=%d psram=%d (bytes)", static_cast( internal_before - heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), static_cast( psram_before - heap_caps_get_free_size(MALLOC_CAP_SPIRAM))); if (aec_ == nullptr) { ESP_LOGE(kTag, "AEC initialization failed"); return false; } aec_chunk_samples_ = aec_get_chunksize(aec_); if (aec_chunk_samples_ <= 0 || aec_chunk_samples_ > static_cast(kMaximumAecChunk)) { ESP_LOGE(kTag, "unsupported AEC chunk=%d", aec_chunk_samples_); DisableEchoCancellation(); return false; } barge_in_profile_ = barge_in_profile; Reset(); ESP_LOGI(kTag, "AEC enabled mode=%s chunk=%d filter=%d profile=%s", aec_get_mode_string(mode), aec_chunk_samples_, filter_length, barge_in_profile ? "barge_in" : "call"); return true; } bool VoiceDsp::PrewarmEchoCancellation() { if (aec_ != nullptr) { return true; } // aec_create is opportunistic: it takes whatever internal RAM is free at // that instant (observed 2.6-12.4 KB across boots) and the handle then // lives for the whole session. Created lazily at the first TTS it once // grabbed 12 KB exactly as the dropped websocket released its buffers — // after that no TLS reconnect could ever allocate again. Placement is // speed-neutral on this board (~50 ms/frame measured both ways), so the // state belongs in PSRAM: create it ONCE at boot, before the WiFi driver // exists, with guard blocks squatting on internal RAM so esp-sr's greedy // pass lands in PSRAM, then release the guards. // Guard blocks sized to the CURRENT largest free block, not a fixed // size: the boot heap is a handful of region tails and DMA-pool chunks, // and a fixed-8KB loop bailed on the first sub-8KB fragment while // esp-sr's many small allocations then filled 24.9 KB of exactly those // fragments — leaving the WiFi driver so dry that phy_track_pll_init's // esp_timer_create aborted the boot. constexpr uint32_t kGuardCaps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT; constexpr size_t kInternalFloorBytes = 8 * 1024; constexpr size_t kMinimumGuardBytes = 1024; constexpr size_t kGuardHeadroomBytes = 256; std::array guards{}; size_t guard_count = 0; size_t guarded_bytes = 0; while (guard_count < guards.size() && heap_caps_get_free_size(kGuardCaps) > kInternalFloorBytes) { const size_t largest = heap_caps_get_largest_free_block(kGuardCaps); if (largest < kMinimumGuardBytes) { break; } const size_t take = largest - kGuardHeadroomBytes; void* block = heap_caps_malloc(take, kGuardCaps); if (block == nullptr) { break; } guards[guard_count++] = block; guarded_bytes += take; } ESP_LOGI(kTag, "AEC prewarm guards=%u held=%u free=%u largest=%u", static_cast(guard_count), static_cast(guarded_bytes), static_cast(heap_caps_get_free_size(kGuardCaps)), static_cast( heap_caps_get_largest_free_block(kGuardCaps))); const bool enabled = EnableEchoCancellation(true); for (size_t index = 0; index < guard_count; ++index) { heap_caps_free(guards[index]); } if (!enabled) { ESP_LOGE(kTag, "AEC prewarm failed"); return false; } Reset(); return true; } void VoiceDsp::SuspendEchoCancellation() { // Keep the adaptive filter warm across TTS turns. Reset() clears only // frame accumulators and AGC state; the ESP AEC handle retains its learned // acoustic path. if (aec_ != nullptr) { Reset(); } } void VoiceDsp::DisableEchoCancellation() { if (aec_ != nullptr) { aec_destroy(aec_); aec_ = nullptr; } aec_chunk_samples_ = 0; barge_in_profile_ = false; mic_count_ = 0; ref_count_ = 0; clean_count_ = 0; } void VoiceDsp::Reset() { mic_count_ = 0; ref_count_ = 0; clean_count_ = 0; if (aec_chunk_samples_ > 0) { clean_count_ = static_cast(aec_chunk_samples_); std::fill_n(clean_acc_.data(), clean_count_, 0); } envelope_ = 0.08f; gain_ = 1.0f; } bool VoiceDsp::Process( const int16_t* microphone, const int16_t* reference, bool echo_cancellation, int16_t* output, size_t sample_count, int16_t* wake_tap) { if (microphone == nullptr || output == nullptr || sample_count != kFrameSamples) { return false; } bool valid = true; if (echo_cancellation) { valid = reference != nullptr && ProcessAec( microphone, reference, output, sample_count); } else { std::memcpy( output, microphone, sample_count * sizeof(int16_t)); } if (!valid) { return false; } if (wake_tap != nullptr) { std::memcpy( wake_tap, output, sample_count * sizeof(int16_t)); } ProcessNsAndAgc( output, sample_count, echo_cancellation && barge_in_profile_); return true; } bool VoiceDsp::ProcessAec( const int16_t* microphone, const int16_t* reference, int16_t* output, size_t sample_count) { if (aec_ == nullptr || mic_count_ + sample_count > mic_acc_.size() || ref_count_ + sample_count > ref_acc_.size()) { return false; } std::memcpy( mic_acc_.data() + mic_count_, microphone, sample_count * sizeof(int16_t)); std::memcpy( ref_acc_.data() + ref_count_, reference, sample_count * sizeof(int16_t)); mic_count_ += sample_count; ref_count_ += sample_count; const size_t chunk = static_cast(aec_chunk_samples_); while (mic_count_ >= chunk && ref_count_ >= chunk) { if (clean_count_ + chunk > clean_acc_.size()) { return false; } aec_process( aec_, mic_acc_.data(), ref_acc_.data(), aec_chunk_.data()); std::memmove( mic_acc_.data(), mic_acc_.data() + chunk, (mic_count_ - chunk) * sizeof(int16_t)); std::memmove( ref_acc_.data(), ref_acc_.data() + chunk, (ref_count_ - chunk) * sizeof(int16_t)); mic_count_ -= chunk; ref_count_ -= chunk; std::memcpy( clean_acc_.data() + clean_count_, aec_chunk_.data(), chunk * sizeof(int16_t)); clean_count_ += chunk; // Hand the core back between chunks. This loop runs 3-4 times per 60 ms // frame on the capture task at priority 8, and aec_process() never // blocks, so without this the idle task on this core gets no runtime for // as long as duplex is active and the task watchdog fires. taskYIELD() // would not help: the idle task sits at priority 0 and only a blocking // delay lets it run. The previous firmware carried the same one-tick // yield in the same position for the same reason. At 1000 Hz a tick is // 1 ms, so the cost is ~4 ms per frame against a 60 ms budget. vTaskDelay(1); } if (clean_count_ < sample_count) { return false; } std::memcpy( output, clean_acc_.data(), sample_count * sizeof(int16_t)); std::memmove( clean_acc_.data(), clean_acc_.data() + sample_count, (clean_count_ - sample_count) * sizeof(int16_t)); clean_count_ -= sample_count; return true; } void VoiceDsp::ProcessNsAndAgc( int16_t* samples, size_t sample_count, bool barge_in_profile) { // Full NS remains active for normal capture and calls. During TTS it can // reshape residual echo and costs CPU, so barge-in uses high-performance // AEC plus the conservative gate/AGC below. if (ns_ != nullptr && !barge_in_profile) { for (size_t offset = 0; offset + kNsFrameSamples <= sample_count; offset += kNsFrameSamples) { ns_process( ns_, samples + offset, ns_frame_.data()); std::memcpy( samples + offset, ns_frame_.data(), kNsFrameSamples * sizeof(int16_t)); } } ApplyAgc(samples, sample_count, barge_in_profile); } void VoiceDsp::ApplyAgc( int16_t* samples, size_t sample_count, bool barge_in_profile) { int32_t peak = 0; uint64_t energy = 0; for (size_t index = 0; index < sample_count; ++index) { const int32_t value = samples[index]; peak = std::max(peak, std::abs(value)); energy += static_cast(value * value); } const float peak_normalized = static_cast(peak) / 32768.0f; const float rms = std::sqrt( static_cast(energy) / static_cast(sample_count)) / 32768.0f; if (rms < 0.004f && peak_normalized < 0.015f) { const float attenuation = barge_in_profile ? kBargeInNoiseGateAttenuation : kNoiseGateAttenuation; for (size_t index = 0; index < sample_count; ++index) { samples[index] = static_cast(samples[index] * attenuation); } return; } const float alpha = peak_normalized > envelope_ ? 0.45f : 0.12f; envelope_ += alpha * (peak_normalized - envelope_); envelope_ = std::max(envelope_, 0.01f); const float target = std::clamp( kTargetPeak / envelope_, kMinimumGain, barge_in_profile ? kBargeInMaximumGain : kMaximumGain); gain_ += 0.18f * (target - gain_); for (size_t index = 0; index < sample_count; ++index) { const float value = std::clamp( static_cast(samples[index]) * gain_, -32768.0f, 32767.0f); samples[index] = static_cast(value); } } } // namespace borla