#include "audio/opus_frame_decoder.h" #include #include namespace borla { namespace { constexpr const char* kTag = "OpusFrameDecoder2"; } // namespace OpusFrameDecoder::~OpusFrameDecoder() { std::lock_guard lock(mutex_); if (decoder_ != nullptr) { opus_decoder_destroy(decoder_); } } bool OpusFrameDecoder::Initialize( uint32_t sample_rate, uint8_t channels) { std::lock_guard lock(mutex_); if (decoder_ != nullptr) { return true; } int error = OPUS_OK; decoder_ = opus_decoder_create( static_cast(sample_rate), channels, &error); if (decoder_ == nullptr || error != OPUS_OK) { ESP_LOGE(kTag, "opus decoder creation failed: %s", opus_strerror(error)); decoder_ = nullptr; return false; } channels_ = channels; ESP_LOGI(kTag, "decoder initialized rate=%lu channels=%u", static_cast(sample_rate), static_cast(channels)); return true; } bool OpusFrameDecoder::Decode( const uint8_t* encoded, size_t encoded_size, int16_t* pcm, size_t pcm_capacity, size_t* decoded_samples) { if (pcm == nullptr || decoded_samples == nullptr || pcm_capacity == 0 || (encoded_size > 0 && encoded == nullptr)) { return false; } std::lock_guard lock(mutex_); if (decoder_ == nullptr) { return false; } const size_t capacity_per_channel = pcm_capacity / channels_; const int decoded = opus_decode( decoder_, encoded, static_cast(encoded_size), pcm, static_cast(capacity_per_channel), 0); if (decoded < 0) { ESP_LOGE(kTag, "decode failed: %s", opus_strerror(decoded)); return false; } *decoded_samples = static_cast(decoded) * static_cast(channels_); // 2026-8-28 CKKJ temp debug: log first 10 frames peak + raw Opus info static uint32_t s_decode_seq = 0; if (s_decode_seq < 10) { s_decode_seq++; int32_t peak = 0; for (size_t i = 0; i < *decoded_samples; ++i) { int32_t a = pcm[i] < 0 ? -pcm[i] : pcm[i]; if (a > peak) peak = a; } const uint8_t toc = encoded_size > 0 ? encoded[0] : 0; ESP_LOGI(kTag, "decode seq=%u enc_size=%u toc=0x%02x decoded=%u peak=%d", static_cast(s_decode_seq), static_cast(encoded_size), static_cast(toc), static_cast(*decoded_samples), static_cast(peak)); }// return true; } void OpusFrameDecoder::Reset() { std::lock_guard lock(mutex_); if (decoder_ != nullptr) { opus_decoder_ctl(decoder_, OPUS_RESET_STATE); } } } // namespace borla