589 lines
18 KiB
C++
589 lines
18 KiB
C++
#include "audio/local_prompt_player.h"
|
|
|
|
#include "audio/packed_opus_reader.h"
|
|
#include "core/task_stack_budget.h"
|
|
|
|
#include <esp_heap_caps.h>
|
|
#include <esp_log.h>
|
|
#include <esp_random.h>
|
|
#include <esp_timer.h>
|
|
#include <freertos/FreeRTOS.h>
|
|
#include <freertos/idf_additions.h>
|
|
#include <freertos/task.h>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cmath>
|
|
#include <new>
|
|
|
|
namespace borla {
|
|
namespace {
|
|
|
|
constexpr const char* kTag = "LocalPromptPlayer2";
|
|
constexpr float kPi = 3.14159265358979323846f;
|
|
constexpr uint32_t kQueueBackpressureTimeoutMs = 1500;
|
|
constexpr uint16_t kActivationIntroGapMs = 1000;
|
|
constexpr uint16_t kActivationDigitGapMs = 150;
|
|
constexpr std::array<
|
|
int16_t,
|
|
PlaybackPipeline::kSamplesPerFrame> kSilence{};
|
|
|
|
struct ToneSegment {
|
|
uint16_t frequency_hz;
|
|
uint16_t duration_ms;
|
|
uint8_t amplitude_percent;
|
|
};
|
|
|
|
constexpr std::array<ToneSegment, 2> kBootFallback = {{
|
|
{523, 150, 24},
|
|
{659, 200, 30},
|
|
}};
|
|
constexpr std::array<ToneSegment, 3> kProvisioningFallback = {{
|
|
{440, 100, 24},
|
|
{554, 100, 26},
|
|
{659, 150, 30},
|
|
}};
|
|
constexpr std::array<ToneSegment, 3> kErrorFallback = {{
|
|
{220, 200, 28},
|
|
{0, 80, 0},
|
|
{220, 200, 28},
|
|
}};
|
|
constexpr std::array<ToneSegment, 2> kShutdownFallback = {{
|
|
{659, 150, 24},
|
|
{262, 250, 20},
|
|
}};
|
|
|
|
uint64_t NowMs()
|
|
{
|
|
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
struct LocalPromptPlayer::ProducerContext {
|
|
LocalPromptPlayer* player = nullptr;
|
|
PlaybackSessionId session_id = 0;
|
|
std::array<
|
|
EmbeddedPromptBlob,
|
|
kMaxLocalPromptSequenceItems> blobs{};
|
|
std::array<
|
|
LocalPrompt,
|
|
kMaxLocalPromptSequenceItems> prompts{};
|
|
size_t count = 0;
|
|
bool activation_sequence = false;
|
|
};
|
|
|
|
LocalPromptPlayer::LocalPromptPlayer(PlaybackPipeline& pipeline)
|
|
: pipeline_(pipeline)
|
|
{
|
|
}
|
|
|
|
LocalPromptPlayer::~LocalPromptPlayer()
|
|
{
|
|
producer_running_.store(false, std::memory_order_release);
|
|
if (producer_task_ != nullptr) {
|
|
if (xSemaphoreTake(
|
|
producer_stopped_, pdMS_TO_TICKS(2000)) != pdTRUE) {
|
|
ESP_LOGE(kTag, "prompt worker stop timed out");
|
|
}
|
|
vTaskDeleteWithCaps(producer_task_);
|
|
producer_task_ = nullptr;
|
|
}
|
|
if (producer_queue_ != nullptr) {
|
|
ProducerContext* pending = nullptr;
|
|
while (xQueueReceive(producer_queue_, &pending, 0) == pdTRUE) {
|
|
DestroyProducerContext(pending);
|
|
}
|
|
}
|
|
if (pcm_buffer_ != nullptr) {
|
|
heap_caps_free(pcm_buffer_);
|
|
}
|
|
if (context_pool_ != nullptr) {
|
|
heap_caps_free(context_pool_);
|
|
context_pool_ = nullptr;
|
|
}
|
|
}
|
|
|
|
bool LocalPromptPlayer::Initialize()
|
|
{
|
|
if (pcm_buffer_ != nullptr && producer_task_ != nullptr) {
|
|
return true;
|
|
}
|
|
if (pcm_buffer_ == nullptr) {
|
|
pcm_buffer_ = static_cast<int16_t*>(heap_caps_calloc(
|
|
PlaybackPipeline::kSamplesPerFrame,
|
|
sizeof(int16_t),
|
|
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
|
|
}
|
|
if (pcm_buffer_ == nullptr) {
|
|
ESP_LOGE(kTag, "failed to allocate PSRAM fallback buffer");
|
|
return false;
|
|
}
|
|
|
|
if (producer_queue_ == nullptr) {
|
|
producer_queue_ = xQueueCreateStatic(
|
|
kProducerQueueDepth,
|
|
sizeof(ProducerContext*),
|
|
producer_queue_bytes_.data(),
|
|
&producer_queue_storage_);
|
|
}
|
|
if (producer_stopped_ == nullptr) {
|
|
producer_stopped_ = xSemaphoreCreateBinaryStatic(
|
|
&producer_stopped_storage_);
|
|
}
|
|
// if (producer_queue_ == nullptr || producer_stopped_ == nullptr) {
|
|
// ESP_LOGE(kTag, "failed to create prompt worker controls");
|
|
// return false;
|
|
// }
|
|
if (context_pool_ == nullptr) {
|
|
context_pool_ = static_cast<ProducerContext*>(
|
|
heap_caps_calloc(
|
|
kProducerQueueDepth,
|
|
sizeof(ProducerContext),
|
|
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
|
|
}
|
|
if (free_slots_ == nullptr) {
|
|
free_slots_ = xQueueCreateStatic(
|
|
kProducerQueueDepth,
|
|
sizeof(uint8_t),
|
|
free_slots_bytes_.data(),
|
|
&free_slots_storage_);
|
|
if (free_slots_ != nullptr) {
|
|
for (uint8_t index = 0; index < kProducerQueueDepth; ++index) {
|
|
xQueueSend(free_slots_, &index, 0);
|
|
}
|
|
}
|
|
}
|
|
if (producer_queue_ == nullptr || producer_stopped_ == nullptr ||
|
|
context_pool_ == nullptr || free_slots_ == nullptr) {
|
|
ESP_LOGE(kTag, "failed to create prompt worker controls or pool");
|
|
return false;
|
|
}/////////
|
|
|
|
xSemaphoreTake(producer_stopped_, 0);
|
|
producer_running_.store(true, std::memory_order_release);
|
|
const BaseType_t created = xTaskCreatePinnedToCoreWithCaps(
|
|
&LocalPromptPlayer::ProducerTaskEntry,
|
|
"prompt_producer",
|
|
task_stack_budget::kLocalPromptProducerBytes,
|
|
this,
|
|
4,
|
|
&producer_task_,
|
|
0,
|
|
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
|
if (created != pdPASS) {
|
|
producer_running_.store(false, std::memory_order_release);
|
|
producer_task_ = nullptr;
|
|
ESP_LOGE(kTag, "failed to create PSRAM prompt worker");
|
|
return false;
|
|
}
|
|
ESP_LOGI(kTag, "worker started stack_bytes=%u memory=PSRAM queue=%u",
|
|
static_cast<unsigned>(
|
|
task_stack_budget::kLocalPromptProducerBytes),
|
|
static_cast<unsigned>(kProducerQueueDepth));
|
|
return true;
|
|
}
|
|
|
|
PlaybackSessionId LocalPromptPlayer::Play(
|
|
LocalPrompt prompt,
|
|
PlaybackPriority priority,
|
|
int16_t selector)
|
|
{
|
|
EmbeddedPromptBlob blob;
|
|
const uint32_t selected =
|
|
selector < 0
|
|
? esp_random()
|
|
: static_cast<uint32_t>(selector);
|
|
if (!EmbeddedPromptCatalog::Select(prompt, selected, &blob)) {
|
|
ESP_LOGW(kTag, "no embedded asset prompt=%s; using tone fallback",
|
|
ToString(prompt));
|
|
return PlayProceduralFallback(prompt, priority);
|
|
}
|
|
|
|
auto* context = AllocateProducerContext();
|
|
if (context == nullptr) {
|
|
ESP_LOGE(kTag, "failed to allocate PSRAM prompt context");
|
|
return 0;
|
|
}
|
|
context->player = this;
|
|
context->blobs[0] = blob;
|
|
context->prompts[0] = prompt;
|
|
context->count = 1;
|
|
return StartProducer(context, priority);
|
|
}
|
|
|
|
PlaybackSessionId LocalPromptPlayer::PlaySequence(
|
|
const LocalPromptSequence& sequence,
|
|
PlaybackPriority priority)
|
|
{
|
|
if (sequence.Empty() ||
|
|
sequence.count > kMaxLocalPromptSequenceItems) {
|
|
return 0;
|
|
}
|
|
auto* context = AllocateProducerContext();
|
|
if (context == nullptr) {
|
|
return 0;
|
|
}
|
|
context->player = this;
|
|
context->activation_sequence =
|
|
sequence.Contains(LocalPrompt::kActivationDevice);
|
|
for (size_t index = 0; index < sequence.count; ++index) {
|
|
const LocalPromptSequenceItem& item = sequence.items[index];
|
|
const uint32_t selected = item.selector < 0
|
|
? esp_random()
|
|
: static_cast<uint32_t>(item.selector);
|
|
if (!EmbeddedPromptCatalog::Select(
|
|
item.prompt,
|
|
selected,
|
|
&context->blobs[context->count])) {
|
|
ESP_LOGW(kTag,
|
|
"sequence asset missing prompt=%s",
|
|
ToString(item.prompt));
|
|
DestroyProducerContext(context);
|
|
return 0;
|
|
}
|
|
context->prompts[context->count] = item.prompt;
|
|
context->count++;
|
|
}
|
|
return StartProducer(context, priority);
|
|
}
|
|
|
|
PlaybackSessionId LocalPromptPlayer::StartProducer(
|
|
ProducerContext* context,
|
|
PlaybackPriority priority)
|
|
{
|
|
const PlaybackStartResult start = pipeline_.StartSession(
|
|
PlaybackSource::kLocalPrompt, priority);
|
|
if (start.status != PlaybackStartStatus::kStarted) {
|
|
ESP_LOGW(kTag, "prompt producer rejected status=%s",
|
|
ToString(start.status));
|
|
DestroyProducerContext(context);
|
|
return start.status == PlaybackStartStatus::kAlreadyActive
|
|
? start.session_id
|
|
: 0;
|
|
}
|
|
context->session_id = start.session_id;
|
|
const size_t item_count = context->count;
|
|
const char* first_filename = context->blobs[0].filename;
|
|
if (!producer_running_.load(std::memory_order_acquire) ||
|
|
xQueueSend(producer_queue_, &context, 0) != pdTRUE) {
|
|
DestroyProducerContext(context);
|
|
pipeline_.Cancel(start.session_id);
|
|
ESP_LOGE(kTag, "prompt worker unavailable or queue full");
|
|
return 0;
|
|
}
|
|
|
|
ESP_LOGI(kTag,
|
|
"prompt producer started items=%u first=%s session=%lu",
|
|
static_cast<unsigned>(item_count),
|
|
first_filename,
|
|
static_cast<unsigned long>(start.session_id));
|
|
return start.session_id;
|
|
}
|
|
|
|
void LocalPromptPlayer::ProducerTaskEntry(void* raw_context)
|
|
{
|
|
static_cast<LocalPromptPlayer*>(raw_context)->RunProducer();
|
|
}
|
|
|
|
LocalPromptPlayer::ProducerContext*
|
|
LocalPromptPlayer::AllocateProducerContext()
|
|
{
|
|
// void* storage = heap_caps_calloc(
|
|
// 1,
|
|
// sizeof(ProducerContext),
|
|
// MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
|
// return storage == nullptr
|
|
// ? nullptr
|
|
// : new (storage) ProducerContext{};///改堆分配为队列
|
|
if (context_pool_ == nullptr || free_slots_ == nullptr) {
|
|
return nullptr;
|
|
}
|
|
uint8_t index = 0;
|
|
if (xQueueReceive(free_slots_, &index, 0) != pdTRUE) {
|
|
return nullptr;
|
|
}
|
|
if (index >= kProducerQueueDepth) {
|
|
return nullptr;
|
|
}
|
|
ProducerContext* context = &context_pool_[index];
|
|
new (context) ProducerContext{};
|
|
return context;
|
|
}
|
|
|
|
void LocalPromptPlayer::DestroyProducerContext(
|
|
ProducerContext* context)
|
|
{
|
|
// if (context == nullptr) {
|
|
// return;
|
|
// }
|
|
if (context == nullptr || context_pool_ == nullptr ||
|
|
free_slots_ == nullptr) {
|
|
return;
|
|
}
|
|
const uint8_t index = static_cast<uint8_t>(
|
|
context - context_pool_);
|
|
if (index >= kProducerQueueDepth) {
|
|
return;
|
|
}
|
|
context->~ProducerContext();
|
|
//heap_caps_free(context);
|
|
xQueueSend(free_slots_, &index, 0);
|
|
}
|
|
|
|
void LocalPromptPlayer::RunProducer()
|
|
{
|
|
while (producer_running_.load(std::memory_order_acquire)) {
|
|
ProducerContext* context = nullptr;
|
|
if (xQueueReceive(
|
|
producer_queue_,
|
|
&context,
|
|
pdMS_TO_TICKS(100)) != pdTRUE) {
|
|
continue;
|
|
}
|
|
if (!producer_running_.load(std::memory_order_acquire)) {
|
|
DestroyProducerContext(context);
|
|
break;
|
|
}
|
|
Produce(*context);
|
|
DestroyProducerContext(context);
|
|
}
|
|
xSemaphoreGive(producer_stopped_);
|
|
for (;;) {
|
|
vTaskSuspend(nullptr);
|
|
}
|
|
}
|
|
|
|
void LocalPromptPlayer::Produce(ProducerContext& context)
|
|
{
|
|
for (size_t index = 0; index < context.count; ++index) {
|
|
if (!producer_running_.load(std::memory_order_acquire)) {
|
|
pipeline_.Cancel(context.session_id);
|
|
return;
|
|
}
|
|
if (!SubmitEmbedded(
|
|
context.blobs[index], context.session_id)) {
|
|
return;
|
|
}
|
|
if (context.activation_sequence &&
|
|
index + 1 < context.count) {
|
|
const uint16_t gap =
|
|
context.prompts[index] ==
|
|
LocalPrompt::kActivationDevice
|
|
? kActivationIntroGapMs
|
|
: kActivationDigitGapMs;
|
|
if (!SubmitSilence(context.session_id, gap)) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
if (!pipeline_.EndInput(context.session_id)) {
|
|
ESP_LOGW(kTag,
|
|
"prompt producer ended after preemption session=%lu",
|
|
static_cast<unsigned long>(context.session_id));
|
|
}
|
|
}
|
|
|
|
bool LocalPromptPlayer::SubmitEmbedded(
|
|
const EmbeddedPromptBlob& blob,
|
|
PlaybackSessionId session_id)
|
|
{
|
|
PackedOpusReader reader(blob.data, blob.size);
|
|
if (!reader.valid()) {
|
|
pipeline_.Cancel(session_id);
|
|
ESP_LOGE(kTag, "invalid packed prompt asset=%s", blob.filename);
|
|
return false;
|
|
}
|
|
|
|
const uint8_t* frame = nullptr;
|
|
size_t frame_size = 0;
|
|
while (reader.Next(&frame, &frame_size)) {
|
|
if (!producer_running_.load(std::memory_order_acquire)) {
|
|
pipeline_.Cancel(session_id);
|
|
return false;
|
|
}
|
|
const uint64_t wait_started = NowMs();
|
|
while (!pipeline_.SubmitOpus(session_id, frame, frame_size)) {
|
|
if (!producer_running_.load(std::memory_order_acquire)) {
|
|
pipeline_.Cancel(session_id);
|
|
return false;
|
|
}
|
|
const PlaybackSessionSnapshot current = pipeline_.Snapshot();
|
|
if (!current.active || current.id != session_id) {
|
|
ESP_LOGI(kTag,
|
|
"prompt producer preempted asset=%s session=%lu",
|
|
blob.filename,
|
|
static_cast<unsigned long>(session_id));
|
|
return false;
|
|
}
|
|
if (NowMs() - wait_started >=
|
|
kQueueBackpressureTimeoutMs) {
|
|
pipeline_.Cancel(session_id);
|
|
ESP_LOGE(kTag,
|
|
"prompt queue stalled asset=%s session=%lu",
|
|
blob.filename,
|
|
static_cast<unsigned long>(session_id));
|
|
return false;
|
|
}
|
|
vTaskDelay(pdMS_TO_TICKS(5));
|
|
}
|
|
}
|
|
|
|
if (!reader.complete()) {
|
|
pipeline_.Cancel(session_id);
|
|
ESP_LOGE(kTag, "truncated packed prompt asset=%s", blob.filename);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool LocalPromptPlayer::SubmitSilence(
|
|
PlaybackSessionId session_id,
|
|
uint16_t duration_ms)
|
|
{
|
|
size_t samples_remaining =
|
|
static_cast<size_t>(PlaybackPipeline::kSampleRate) *
|
|
duration_ms / 1000;
|
|
while (samples_remaining > 0) {
|
|
if (!producer_running_.load(std::memory_order_acquire)) {
|
|
pipeline_.Cancel(session_id);
|
|
return false;
|
|
}
|
|
const size_t samples = std::min(
|
|
samples_remaining,
|
|
PlaybackPipeline::kSamplesPerFrame);
|
|
const uint64_t wait_started = NowMs();
|
|
while (!pipeline_.SubmitPcm(
|
|
session_id, kSilence.data(), samples)) {
|
|
const PlaybackSessionSnapshot current = pipeline_.Snapshot();
|
|
if (!current.active || current.id != session_id) {
|
|
return false;
|
|
}
|
|
if (NowMs() - wait_started >=
|
|
kQueueBackpressureTimeoutMs) {
|
|
pipeline_.Cancel(session_id);
|
|
ESP_LOGE(kTag,
|
|
"sequence silence queue stalled session=%lu",
|
|
static_cast<unsigned long>(session_id));
|
|
return false;
|
|
}
|
|
vTaskDelay(pdMS_TO_TICKS(5));
|
|
}
|
|
samples_remaining -= samples;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
PlaybackSessionId LocalPromptPlayer::PlayProceduralFallback(
|
|
LocalPrompt prompt,
|
|
PlaybackPriority priority)
|
|
{
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
if (!Initialize()) {
|
|
return 0;
|
|
}
|
|
|
|
const PlaybackStartResult start = pipeline_.StartSession(
|
|
PlaybackSource::kLocalPrompt, priority);
|
|
if (start.status != PlaybackStartStatus::kStarted) {
|
|
return start.status == PlaybackStartStatus::kAlreadyActive
|
|
? start.session_id
|
|
: 0;
|
|
}
|
|
|
|
float phase = 0.0f;
|
|
const auto submit_sequence =
|
|
[this, &start, &phase](const auto& sequence) {
|
|
for (const auto& tone : sequence) {
|
|
if (!SubmitTone(
|
|
start.session_id,
|
|
tone.frequency_hz,
|
|
tone.duration_ms,
|
|
tone.amplitude_percent,
|
|
&phase)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
};
|
|
|
|
bool submitted = false;
|
|
switch (prompt) {
|
|
case LocalPrompt::kBoot:
|
|
submitted = submit_sequence(kBootFallback);
|
|
break;
|
|
case LocalPrompt::kProvisioning:
|
|
submitted = submit_sequence(kProvisioningFallback);
|
|
break;
|
|
case LocalPrompt::kShutdown:
|
|
submitted = submit_sequence(kShutdownFallback);
|
|
break;
|
|
default:
|
|
submitted = submit_sequence(kErrorFallback);
|
|
break;
|
|
}
|
|
|
|
if (!submitted || !pipeline_.EndInput(start.session_id)) {
|
|
pipeline_.Cancel(start.session_id);
|
|
return 0;
|
|
}
|
|
return start.session_id;
|
|
}
|
|
|
|
bool LocalPromptPlayer::SubmitTone(
|
|
PlaybackSessionId session_id,
|
|
uint16_t frequency_hz,
|
|
uint16_t duration_ms,
|
|
uint8_t amplitude_percent,
|
|
float* phase)
|
|
{
|
|
const size_t total_samples =
|
|
static_cast<size_t>(PlaybackPipeline::kSampleRate) *
|
|
duration_ms / 1000;
|
|
const float amplitude =
|
|
32767.0f * static_cast<float>(amplitude_percent) / 100.0f;
|
|
const size_t fade_samples =
|
|
PlaybackPipeline::kSampleRate / 100;
|
|
|
|
size_t generated = 0;
|
|
while (generated < total_samples) {
|
|
const size_t frame_samples = std::min(
|
|
PlaybackPipeline::kSamplesPerFrame,
|
|
total_samples - generated);
|
|
for (size_t index = 0; index < frame_samples; ++index) {
|
|
const size_t absolute = generated + index;
|
|
float envelope = 1.0f;
|
|
if (absolute < fade_samples) {
|
|
envelope = static_cast<float>(absolute) /
|
|
static_cast<float>(fade_samples);
|
|
} else if (total_samples - absolute < fade_samples) {
|
|
envelope = static_cast<float>(total_samples - absolute) /
|
|
static_cast<float>(fade_samples);
|
|
}
|
|
|
|
if (frequency_hz == 0) {
|
|
pcm_buffer_[index] = 0;
|
|
} else {
|
|
pcm_buffer_[index] = static_cast<int16_t>(
|
|
amplitude * envelope * std::sin(*phase));
|
|
*phase += 2.0f * kPi *
|
|
static_cast<float>(frequency_hz) /
|
|
static_cast<float>(
|
|
PlaybackPipeline::kSampleRate);
|
|
if (*phase >= 2.0f * kPi) {
|
|
*phase -= 2.0f * kPi;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!pipeline_.SubmitPcm(
|
|
session_id, pcm_buffer_, frame_samples)) {
|
|
return false;
|
|
}
|
|
generated += frame_samples;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
} // namespace borla
|