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

108 lines
2.9 KiB
C++

#include "audio/opus_frame_decoder.h"
#include <esp_log.h>
#include <opus.h>
namespace borla {
namespace {
constexpr const char* kTag = "OpusFrameDecoder2";
} // namespace
OpusFrameDecoder::~OpusFrameDecoder()
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
opus_decoder_destroy(decoder_);
}
}
bool OpusFrameDecoder::Initialize(
uint32_t sample_rate,
uint8_t channels)
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
return true;
}
int error = OPUS_OK;
decoder_ = opus_decoder_create(
static_cast<opus_int32>(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<unsigned long>(sample_rate),
static_cast<unsigned>(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<std::mutex> 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<opus_int32>(encoded_size),
pcm,
static_cast<int>(capacity_per_channel),
0);
if (decoded < 0) {
ESP_LOGE(kTag, "decode failed: %s", opus_strerror(decoded));
return false;
}
*decoded_samples =
static_cast<size_t>(decoded) * static_cast<size_t>(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<unsigned>(s_decode_seq),
static_cast<unsigned>(encoded_size),
static_cast<unsigned>(toc),
static_cast<unsigned>(*decoded_samples),
static_cast<int>(peak));
}//
return true;
}
void OpusFrameDecoder::Reset()
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
opus_decoder_ctl(decoder_, OPUS_RESET_STATE);
}
}
} // namespace borla