#include "audio/opus_frame_encoder.h" #include #include namespace borla { namespace { constexpr const char* kTag = "OpusFrameEncoder2"; } // namespace OpusFrameEncoder::~OpusFrameEncoder() { std::lock_guard lock(mutex_); if (encoder_ != nullptr) { opus_encoder_destroy(encoder_); } } bool OpusFrameEncoder::Initialize( uint32_t sample_rate, uint8_t channels, uint32_t bitrate) { std::lock_guard lock(mutex_); if (encoder_ != nullptr) { return true; } int error = OPUS_OK; encoder_ = opus_encoder_create( static_cast(sample_rate), channels, OPUS_APPLICATION_VOIP, &error); if (encoder_ == nullptr || error != OPUS_OK) { ESP_LOGE(kTag, "encoder creation failed: %s", opus_strerror(error)); encoder_ = nullptr; return false; } channels_ = channels; // Complexity 3, matching the previous firmware ("ESP32 上用最低复杂度保证 // 实时性", audio_service.cc:14). At complexity 4 a 60 ms frame measured // 33 ms to encode with the core to itself and 82 ms averaged when TTS // playback shared core 1 — the task-watchdog backtraces all ended inside // silk_encode_frame_FIX. The uplink feeds server-side ASR at 16 kHz mono; // it does not need the marginal quality of the higher search depth. if (opus_encoder_ctl( encoder_, OPUS_SET_BITRATE(static_cast(bitrate))) != OPUS_OK || opus_encoder_ctl(encoder_, OPUS_SET_COMPLEXITY(3)) != OPUS_OK || opus_encoder_ctl(encoder_, OPUS_SET_VBR(1)) != OPUS_OK || opus_encoder_ctl(encoder_, OPUS_SET_DTX(0)) != OPUS_OK) { ESP_LOGE(kTag, "encoder configuration failed"); opus_encoder_destroy(encoder_); encoder_ = nullptr; return false; } ESP_LOGI(kTag, "initialized rate=%lu channels=%u bitrate=%lu", static_cast(sample_rate), static_cast(channels), static_cast(bitrate)); return true; } bool OpusFrameEncoder::Encode( const int16_t* pcm, size_t samples_per_channel, uint8_t* encoded, size_t capacity, size_t* encoded_size) { if (pcm == nullptr || encoded == nullptr || encoded_size == nullptr || samples_per_channel == 0 || capacity == 0 || capacity > INT32_MAX) { return false; } std::lock_guard lock(mutex_); if (encoder_ == nullptr) { return false; } const int result = opus_encode( encoder_, pcm, static_cast(samples_per_channel), encoded, static_cast(capacity)); if (result <= 0) { ESP_LOGE(kTag, "encode failed: %s", opus_strerror(result)); return false; } *encoded_size = static_cast(result); return true; } void OpusFrameEncoder::Reset() { std::lock_guard lock(mutex_); if (encoder_ != nullptr) { opus_encoder_ctl(encoder_, OPUS_RESET_STATE); } } } // namespace borla