bolar_2 backup

This commit is contained in:
2026-11-27 16:38:11 +08:00
commit e96d6d19df
305 changed files with 43350 additions and 0 deletions

View File

@@ -0,0 +1,105 @@
#include "audio/opus_frame_encoder.h"
#include <esp_log.h>
#include <opus.h>
namespace borla {
namespace {
constexpr const char* kTag = "OpusFrameEncoder2";
} // namespace
OpusFrameEncoder::~OpusFrameEncoder()
{
std::lock_guard<std::mutex> 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<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
return true;
}
int error = OPUS_OK;
encoder_ = opus_encoder_create(
static_cast<opus_int32>(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<opus_int32>(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<unsigned long>(sample_rate),
static_cast<unsigned>(channels),
static_cast<unsigned long>(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<std::mutex> lock(mutex_);
if (encoder_ == nullptr) {
return false;
}
const int result = opus_encode(
encoder_,
pcm,
static_cast<int>(samples_per_channel),
encoded,
static_cast<opus_int32>(capacity));
if (result <= 0) {
ESP_LOGE(kTag, "encode failed: %s", opus_strerror(result));
return false;
}
*encoded_size = static_cast<size_t>(result);
return true;
}
void OpusFrameEncoder::Reset()
{
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
opus_encoder_ctl(encoder_, OPUS_RESET_STATE);
}
}
} // namespace borla