#include "audio/playback_pipeline.h" #include "core/task_stack_budget.h" #include #include #include #include #include #include #include namespace borla { namespace { constexpr const char* kTag = "PlaybackPipeline2"; constexpr uint32_t kProducerStartTimeoutMs = 2000; constexpr uint32_t kStalledTimeoutMs = 10000; // How long a late frame may be held waiting for a companion after the ready // queue ran dry. Playout health showed why: the server re-anchors its rate // control after a TTS generation stall and never refills the burst cushion, // so a starved stretch played as a run of 60-80 ms micro-gaps (16 in one // session). Holding once converts that into a single short pause followed by // smooth playout. Draining sessions never hold — every frame is already // queued once EndInput has been seen. constexpr uint32_t kDryRebuildHoldMs = 150; // Fixed hold before the FIRST write of a remote TTS session. The server runs // 6 frames (360 ms) ahead and never refills after a generation stall (it // re-anchors instead), so the cushion only ever shrinks over a reply. // Delaying playout start grows the server's effective lead by exactly the // hold: 360 + 180 = 540 ms of stall budget, which absorbs typical // inter-sentence TTS generation gaps that were audible as mid-reply breaks. // Local prompts are exempt — they are fully buffered and latency-sensitive. constexpr uint32_t kStartupPrebufferMs = 180; } // namespace PlaybackPipeline::PlaybackPipeline(IAudioOutput& output) : output_(output) { } PlaybackPipeline::~PlaybackPipeline() { Stop(); if (frame_pool_ != nullptr) { heap_caps_free(frame_pool_); } if (decode_buffer_ != nullptr) { heap_caps_free(decode_buffer_); } if (reference_buffer_ != nullptr) { heap_caps_free(reference_buffer_); } } void PlaybackPipeline::SetEventPublisher(IEventPublisher* publisher) { publisher_.store(publisher, std::memory_order_release); } bool PlaybackPipeline::Initialize() { if (initialized_) { return true; } if (output_.SampleRate() != kSampleRate) { ESP_LOGE(kTag, "output rate=%lu does not match pipeline rate=%lu", static_cast(output_.SampleRate()), static_cast(kSampleRate)); return false; } if (!decoder_.Initialize(kSampleRate, 1)) { return false; } if (stopped_signal_ == nullptr) { stopped_signal_ = xSemaphoreCreateBinaryStatic(&stopped_signal_storage_); if (stopped_signal_ == nullptr) { ESP_LOGE(kTag, "task stop signal creation failed"); return false; } } if (frame_pool_ == nullptr) { frame_pool_ = static_cast(heap_caps_calloc(kFramePoolSize, sizeof(FrameSlot), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); } if (decode_buffer_ == nullptr) { decode_buffer_ = static_cast(heap_caps_calloc(kSamplesPerFrame, sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); } if (reference_buffer_ == nullptr) { reference_buffer_ = static_cast(heap_caps_calloc(kSamplesPerFrame, sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); } if (frame_pool_ == nullptr || decode_buffer_ == nullptr || reference_buffer_ == nullptr) { ESP_LOGE(kTag, "PSRAM allocation failed pool=%p decode=%p reference=%p", frame_pool_, decode_buffer_, reference_buffer_); return false; } for (size_t index = 0; index < kFramePoolSize; ++index) { new (&frame_pool_[index]) FrameSlot(); } free_slots_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t), free_slots_queue_bytes_, &free_slots_storage_); ready_frames_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t), ready_frames_queue_bytes_, &ready_frames_storage_); if (free_slots_ == nullptr || ready_frames_ == nullptr) { ESP_LOGE(kTag, "static queue creation failed"); return false; } for (uint16_t index = 0; index < kFramePoolSize; ++index) { if (xQueueSend(free_slots_, &index, 0) != pdTRUE) { ESP_LOGE(kTag, "failed to seed frame slot=%u", index); return false; } } initialized_ = true; ESP_LOGI(kTag, "initialized frames=%u slot_bytes=%u PSRAM=%u bytes", static_cast(kFramePoolSize), static_cast(sizeof(FrameSlot)), static_cast(kFramePoolSize * sizeof(FrameSlot) + 2 * kSamplesPerFrame * sizeof(int16_t))); return true; } bool PlaybackPipeline::Start() { if (running_.load(std::memory_order_acquire)) { return true; } if (!initialized_ && !Initialize()) { return false; } xSemaphoreTake(stopped_signal_, 0); running_.store(true, std::memory_order_release); const BaseType_t result = xTaskCreatePinnedToCoreWithCaps(&PlaybackPipeline::TaskEntry, "playback", task_stack_budget::kPlaybackBytes, this, task_priority::kPlaybackLoop, &task_, 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); if (result != pdPASS) { running_.store(false, std::memory_order_release); task_ = nullptr; ESP_LOGE(kTag, "failed to create playback task"); return false; } ESP_LOGI(kTag, "task started stack_bytes=%u memory=PSRAM", static_cast(task_stack_budget::kPlaybackBytes)); return true; } void PlaybackPipeline::Stop() { paused_.store(false, std::memory_order_release); if (!running_.exchange(false, std::memory_order_acq_rel)) { return; } if (task_ != nullptr) { if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) { ESP_LOGE(kTag, "speaker-owner task stop timed out"); } vTaskDeleteWithCaps(task_); task_ = nullptr; } std::lock_guard lock(mutex_); controller_.Cancel(0); DrainReadyQueueLocked(); decoder_.Reset(); } PlaybackStartResult PlaybackPipeline::StartSession(PlaybackSource source, PlaybackPriority priority, PlaybackSessionId requested_id) { if (!running_.load(std::memory_order_acquire)) { return {}; } PlaybackStartResult result; { std::lock_guard lock(mutex_); result = controller_.StartSession(source, priority, requested_id, NowMs()); if (result.status == PlaybackStartStatus::kStarted) { paused_.store(false, std::memory_order_release); backpressure_logged_session_.store( 0, std::memory_order_release); DrainReadyQueueLocked(); // The decoder is reset by the playback task itself, right before // the next Decode: this path runs on the application task while // Run() may be inside Decode() — which happens OUTSIDE mutex_ — // and libopus state is not reentrant. The flag is honoured before // the new session's first frame, which is all the reset is for. decoder_reset_pending_.store( true, std::memory_order_release); // Drop any reference frames stranded from the previous session so // the AEC starts this one in phase with the speaker. IPlaybackReferenceSink* reference_sink = reference_sink_.load(std::memory_order_acquire); if (reference_sink != nullptr) { reference_sink->ResetPlaybackReference(); } ESP_LOGI(kTag, "session start id=%lu generation=%lu source=%s " "priority=%s preempted=%lu", static_cast(result.session_id), static_cast(result.generation), ToString(source), ToString(priority), static_cast(result.preempted_session_id)); } else { ESP_LOGW(kTag, "session request status=%s requested=%lu source=%s " "priority=%s", ToString(result.status), static_cast(requested_id), ToString(source), ToString(priority)); } } if (result.preempted_session_id != 0) { PublishPlaybackEvent(AppEventType::kPlaybackPreempted, result.preempted_session_id, result.session_id); } return result; } bool PlaybackPipeline::SubmitOpus( PlaybackSessionId session_id, const uint8_t* data, size_t size) { if (data == nullptr || size == 0 || size > kMaxOpusBytes) { ESP_LOGW( kTag, "invalid Opus frame size=%u", static_cast(size)); return false; } return SubmitFrame(session_id, FrameFormat::kOpus, data, size, 0); } bool PlaybackPipeline::SubmitPcm( PlaybackSessionId session_id, const int16_t* samples, size_t sample_count) { if (samples == nullptr || sample_count == 0 || sample_count > kSamplesPerFrame) { return false; } return SubmitFrame(session_id, FrameFormat::kPcm, samples, sample_count * sizeof(int16_t), sample_count); } bool PlaybackPipeline::EndInput(PlaybackSessionId session_id) { PlaybackSessionId completed = 0; { std::lock_guard lock(mutex_); if (!controller_.EndInput(session_id, NowMs())) { return false; } completed = controller_.TryComplete(); } if (completed != 0) { PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed); } return true; } bool PlaybackPipeline::Cancel(PlaybackSessionId session_id) { paused_.store(false, std::memory_order_release); std::lock_guard lock(mutex_); const PlaybackSessionId cancelled = controller_.Cancel(session_id); if (cancelled == 0) { return false; } DrainReadyQueueLocked(); // Same reentrancy rule as StartSession: Decode() runs outside mutex_ on // the playback task, so the reset must happen there, not here. decoder_reset_pending_.store(true, std::memory_order_release); ESP_LOGI(kTag, "session cancelled id=%lu", static_cast(cancelled)); return true; } void PlaybackPipeline::SetPaused(bool paused) { const bool previous = paused_.exchange( paused, std::memory_order_acq_rel); if (previous != paused) { ESP_LOGI(kTag, "playback %s for barge-in candidate", paused ? "paused" : "resumed"); } } PlaybackSessionSnapshot PlaybackPipeline::Snapshot() const { std::lock_guard lock(mutex_); return controller_.snapshot(); } PlaybackMetrics PlaybackPipeline::Metrics() const { std::lock_guard lock(mutex_); return controller_.metrics(); } void PlaybackPipeline::TaskEntry(void* context) { static_cast(context)->Run(); } void PlaybackPipeline::Run() { ESP_LOGI(kTag, "speaker-owner task started"); while (running_.load(std::memory_order_acquire)) { uint16_t slot_index = 0; if (xQueueReceive(ready_frames_, &slot_index, pdMS_TO_TICKS(20)) != pdTRUE) { CheckTimeout(); continue; } if (slot_index >= kFramePoolSize) { ESP_LOGE(kTag, "invalid frame slot=%u", slot_index); continue; } const uint32_t ready_depth = static_cast( uxQueueMessagesWaiting(ready_frames_)); // Candidate barge-in is reversible. Keep the dequeued head frame and // every queued frame intact until the server confirms or rejects the // ASR result. A frame already inside synchronous I2S Write() may finish, // so pause latency is bounded by one 60 ms frame. if (paused_.load(std::memory_order_acquire)) { // A deliberate hold is not starvation; skip the next gap sample. health_skip_gap_ = true; } while (running_.load(std::memory_order_acquire) && paused_.load(std::memory_order_acquire)) { vTaskDelay(pdMS_TO_TICKS(10)); } if (!running_.load(std::memory_order_acquire)) { ReleaseSlot(slot_index); break; } FrameSlot& slot = frame_pool_[slot_index]; if (slot.session_id != health_session_) { // First frame of a new session: see kStartupPrebufferMs. bool prebuffer = false; { std::lock_guard lock(mutex_); prebuffer = controller_.IsCurrent(slot.session_id) && controller_.snapshot().source == PlaybackSource::kRemoteTts; } if (prebuffer) { const uint64_t deadline_us = static_cast(esp_timer_get_time()) + kStartupPrebufferMs * 1000ULL; bool still_current = true; while (still_current && running_.load(std::memory_order_acquire) && !paused_.load(std::memory_order_acquire) && static_cast(esp_timer_get_time()) < deadline_us) { vTaskDelay(pdMS_TO_TICKS(10)); std::lock_guard lock(mutex_); still_current = controller_.IsCurrent(slot.session_id); } } } else if (last_write_end_us_ != 0 && static_cast(esp_timer_get_time()) - last_write_end_us_ > kFrameDurationMs * 1000ULL) { // De-jitter rebuild: reaching this frame more than one period // after the previous write finished means the queue ran dry and // the DMA is draining right now. Hold briefly for a companion // frame so the dry spell plays as one pause instead of a // micro-gap per frame. Also covers the post-candidate resume, // which restarts with zero cushion. bool input_ended = false; { std::lock_guard lock(mutex_); input_ended = !controller_.IsCurrent(slot.session_id) || controller_.snapshot().input_ended; } const uint64_t hold_deadline_us = static_cast(esp_timer_get_time()) + kDryRebuildHoldMs * 1000ULL; while (!input_ended && running_.load(std::memory_order_acquire) && !paused_.load(std::memory_order_acquire) && uxQueueMessagesWaiting(ready_frames_) == 0 && static_cast(esp_timer_get_time()) < hold_deadline_us) { vTaskDelay(pdMS_TO_TICKS(10)); std::lock_guard lock(mutex_); input_ended = controller_.snapshot().input_ended; } } bool process = false; { std::lock_guard lock(mutex_); process = controller_.BeginFrame(slot.session_id, NowMs()); if (!process) { controller_.RecordStaleFrame(); } } if (!process) { ReleaseSlot(slot_index); continue; } size_t decoded_samples = 0; bool decoded = false; if (slot.format == FrameFormat::kOpus) { if (decoder_reset_pending_.exchange( false, std::memory_order_acq_rel)) { decoder_.Reset(); } decoded = decoder_.Decode(slot.payload, slot.payload_size, decode_buffer_, kSamplesPerFrame, &decoded_samples); } else { decoded_samples = slot.sample_count; std::memcpy(decode_buffer_, slot.payload, decoded_samples * sizeof(int16_t)); decoded = true; } PlaybackSessionId completed = 0; PlaybackSessionId failed = 0; { std::lock_guard lock(mutex_); if (!controller_.IsCurrent(slot.session_id)) { controller_.RecordStaleFrame(); } else if (!decoded) { failed = controller_.Fail(slot.session_id); DrainReadyQueueLocked(); } else { // Hold the ownership lock across the synchronous I2S write. // A preemption waits at most one 60 ms frame, and after it // returns no frame from the old session can reach the PA. IPlaybackReferenceSink* reference_sink = reference_sink_.load(std::memory_order_acquire); if (reference_sink != nullptr) { // Mirror the software volume applied inside Write(). AEC // must receive the PCM amplitude that reaches the DAC, // not the unscaled decoder output. const int32_t gain = static_cast(output_.VolumePercent()) * 256 / 100; for (size_t index = 0; index < decoded_samples; ++index) { const int32_t scaled = (static_cast(decode_buffer_[index]) * gain) >> 8; reference_buffer_[index] = static_cast(std::clamp( scaled, -32768, 32767)); } reference_sink->OnPlaybackReference( reference_buffer_, decoded_samples); } if (slot.session_id != health_session_) { FlushPlayoutHealth(); health_session_ = slot.session_id; health_skip_gap_ = true; health_depth_min_ = ready_depth; health_depth_max_ = ready_depth; } const uint64_t write_start_us = static_cast(esp_timer_get_time()); if (!health_skip_gap_ && last_write_end_us_ != 0) { const uint32_t gap_ms = static_cast( (write_start_us - last_write_end_us_) / 1000ULL); health_max_gap_ms_ = std::max(health_max_gap_ms_, gap_ms); if (gap_ms > kFrameDurationMs) { health_gap_over_frame_++; } if (gap_ms > 90) { health_gap_over_dma_++; } } health_skip_gap_ = false; health_frames_++; health_depth_min_ = std::min(health_depth_min_, ready_depth); health_depth_max_ = std::max(health_depth_max_, ready_depth); const bool written = output_.Write(decode_buffer_, decoded_samples); last_write_end_us_ = static_cast(esp_timer_get_time()); controller_.FinishFrame(slot.session_id, written, NowMs()); if (!written) { failed = controller_.Fail(slot.session_id); DrainReadyQueueLocked(); } else { completed = controller_.TryComplete(); } } } ReleaseSlot(slot_index); if (failed != 0 || completed != 0) { FlushPlayoutHealth(); } if (failed != 0) { PublishPlaybackEvent(AppEventType::kPlaybackFailed, failed); } else if (completed != 0) { PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed); } } FlushPlayoutHealth(); xSemaphoreGive(stopped_signal_); for (;;) { vTaskSuspend(nullptr); } } void PlaybackPipeline::FlushPlayoutHealth() { if (health_frames_ > 1) { // One line per session. gaps>frame means the queue ran dry longer // than one frame period (cushion gone); gaps>dma means the 90 ms // I2S buffer also drained and the break reached the speaker. ESP_LOGI(kTag, "playout health id=%lu frames=%lu max_gap=%lums " "gaps>frame=%lu gaps>dma=%lu depth=%lu..%lu", static_cast(health_session_), static_cast(health_frames_), static_cast(health_max_gap_ms_), static_cast(health_gap_over_frame_), static_cast(health_gap_over_dma_), static_cast(health_depth_min_), static_cast(health_depth_max_)); } health_session_ = 0; health_frames_ = 0; health_max_gap_ms_ = 0; health_gap_over_frame_ = 0; health_gap_over_dma_ = 0; health_depth_min_ = 0; health_depth_max_ = 0; last_write_end_us_ = 0; health_skip_gap_ = false; } bool PlaybackPipeline::SubmitFrame(PlaybackSessionId session_id, FrameFormat format, const void* data, size_t byte_count, size_t sample_count) { if (!running_.load(std::memory_order_acquire) || data == nullptr || byte_count > kMaxFrameBytes) { return false; } uint16_t slot_index = 0; if (xQueueReceive(free_slots_, &slot_index, 0) != pdTRUE) { const PlaybackSessionId already_logged = backpressure_logged_session_.exchange( session_id, std::memory_order_acq_rel); if (already_logged != session_id) { ESP_LOGD(kTag, "producer pacing session=%lu; frame pool temporarily full", static_cast(session_id)); } return false; } FrameSlot& slot = frame_pool_[slot_index]; slot.session_id = session_id; slot.format = format; slot.payload_size = static_cast(byte_count); slot.sample_count = static_cast(sample_count); std::memcpy(slot.payload, data, byte_count); { std::lock_guard lock(mutex_); if (!controller_.QueueFrame(session_id, NowMs())) { controller_.RecordStaleFrame(); ReleaseSlot(slot_index); return false; } if (xQueueSend(ready_frames_, &slot_index, 0) != pdTRUE) { controller_.RollbackQueuedFrame(session_id); ReleaseSlot(slot_index); ESP_LOGE(kTag, "ready queue unexpectedly full"); return false; } } return true; } void PlaybackPipeline::DrainReadyQueueLocked() { uint16_t slot_index = 0; while (xQueueReceive(ready_frames_, &slot_index, 0) == pdTRUE) { ReleaseSlot(slot_index); } } void PlaybackPipeline::ReleaseSlot(uint16_t slot_index) { if (xQueueSend(free_slots_, &slot_index, 0) != pdTRUE) { ESP_LOGE(kTag, "failed to release frame slot=%u", slot_index); } } void PlaybackPipeline::CheckTimeout() { PlaybackTimeoutResult timeout; { std::lock_guard lock(mutex_); timeout = controller_.CheckTimeout( NowMs(), kProducerStartTimeoutMs, kStalledTimeoutMs); if (timeout.session_id != 0) { DrainReadyQueueLocked(); decoder_.Reset(); } } if (timeout.session_id != 0) { ESP_LOGE(kTag, "session timeout id=%lu reason=%s", static_cast(timeout.session_id), ToString(timeout.reason)); PublishPlaybackEvent(AppEventType::kPlaybackFailed, timeout.session_id); } } void PlaybackPipeline::PublishPlaybackEvent(AppEventType type, PlaybackSessionId session_id, PlaybackSessionId replacement_session_id) { IEventPublisher* publisher = publisher_.load(std::memory_order_acquire); if (publisher == nullptr || !publisher->Publish( AppEvent::Make(type, session_id, 0, replacement_session_id))) { ESP_LOGE(kTag, "failed to publish playback event=%s session=%lu", ToString(type), static_cast(session_id)); } } uint64_t PlaybackPipeline::NowMs() { return static_cast(esp_timer_get_time() / 1000); } } // namespace borla