Files
EchoionCore/src/playback/PlaybackEngine.cpp
T
faumaray d146f11f02 Release 1.0.0
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-04 01:49:28 +03:00

940 lines
26 KiB
C++

#include "echoion/core/playback/PlaybackEngine.hpp"
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <cmath>
#include <format>
namespace Echoion::Core
{
namespace
{
constexpr size_t MAX_BUFFER_SHORTS =
PlaybackEngine::SHORTS_PER_CHUNK * 50;
} // namespace
PlaybackEngine::PlaybackEngine(IPlaybackHost& host) : host_(host) {}
PlaybackEngine::~PlaybackEngine() { shutdown(); }
Api::Result<void> PlaybackEngine::initialize(
const std::optional<Void::Net::ProxyConfig>& proxy)
{
if (initialized_.exchange(true)) {
return {};
}
proxy_ = proxy;
for (DecoderSlot* slot : {&current_, &next_}) {
slot->decoder = std::make_unique<AudioDecoder>();
auto result = slot->decoder->initialize();
if (!result) {
initialized_ = false;
return result;
}
slot->decoder->setOutputFormat(SAMPLE_RATE, CHANNELS);
slot->decoder->setProxyConfig(proxy_);
}
ring_.reserve(MAX_BUFFER_SHORTS + SHORTS_PER_CHUNK);
outChunk_.assign(SHORTS_PER_CHUNK, 0);
thread_ = std::jthread([this](std::stop_token st) { run(st); });
Void::Log::info("PlaybackEngine", "{}", "Playback engine started");
return {};
}
void PlaybackEngine::shutdown()
{
if (!initialized_.exchange(false)) {
return;
}
thread_.request_stop();
mailboxCv_.notify_all();
if (thread_.joinable()) {
thread_.join();
}
current_.closeAndReset();
next_.closeAndReset();
if (current_.decoder) {
current_.decoder->shutdown();
}
if (next_.decoder) {
next_.decoder->shutdown();
}
Void::Log::info("PlaybackEngine", "{}", "Playback engine stopped");
}
void PlaybackEngine::setProxyConfig(
const std::optional<Void::Net::ProxyConfig>& proxy)
{
proxy_ = proxy;
// Applies to the NEXT openSource; in-flight decodes keep their
// connection.
if (current_.decoder) {
current_.decoder->setProxyConfig(proxy);
}
if (next_.decoder) {
next_.decoder->setProxyConfig(proxy);
}
}
// ---- control -------------------------------------------------------
void PlaybackEngine::post(Command cmd)
{
{
std::lock_guard<std::mutex> lock(mailboxMutex_);
mailbox_.push_back(std::move(cmd));
}
mailboxCv_.notify_one();
}
void PlaybackEngine::playNow(Api::QueueEntry entry, std::string streamUrl,
bool isLocalFile)
{
post(CmdPlayNow{.entry = std::move(entry),
.url = std::move(streamUrl),
.isLocalFile = isLocalFile});
}
void PlaybackEngine::start() { post(CmdStart{}); }
void PlaybackEngine::pause() { post(CmdPause{}); }
void PlaybackEngine::resume() { post(CmdResume{}); }
void PlaybackEngine::stopPlayback() { post(CmdStop{}); }
void PlaybackEngine::skip(uint32_t count) { post(CmdSkip{count}); }
void PlaybackEngine::seekTo(std::chrono::milliseconds position)
{
post(CmdSeek{position});
}
void PlaybackEngine::restore(Api::QueueEntry entry, std::string streamUrl,
std::chrono::milliseconds position,
bool paused)
{
post(CmdRestore{.entry = std::move(entry),
.url = std::move(streamUrl),
.position = position,
.paused = paused});
}
std::optional<Api::QueueEntry> PlaybackEngine::currentEntry() const
{
std::lock_guard<std::mutex> lock(currentEntryMutex_);
return publishedEntry_;
}
std::chrono::milliseconds PlaybackEngine::currentDuration() const
{
return std::chrono::milliseconds(currentDurationMs_.load());
}
// ---- engine thread ---------------------------------------------------
void PlaybackEngine::run(std::stop_token st)
{
Void::Log::debug("PlaybackEngine", "{}", "Engine thread running");
while (!st.stop_requested()) {
// Idle: nothing playing and nothing warming — sleep on mailbox.
if (current_.state == DecoderSlot::State::Idle) {
std::unique_lock<std::mutex> lock(mailboxMutex_);
mailboxCv_.wait(lock, [&] {
return !mailbox_.empty() || st.stop_requested();
});
lock.unlock();
if (st.stop_requested()) {
break;
}
drainMailbox();
if (current_.state == DecoderSlot::State::Idle) {
continue;
}
// A track just started: reset cadence.
nextTick_ = std::chrono::steady_clock::now();
}
drainMailbox();
if (st.stop_requested() ||
current_.state == DecoderSlot::State::Idle) {
continue;
}
if (paused_.load()) {
// Keep commands responsive; emit nothing while paused.
std::unique_lock<std::mutex> lock(mailboxMutex_);
mailboxCv_.wait_for(lock, std::chrono::milliseconds(50), [&] {
return !mailbox_.empty() || st.stop_requested();
});
nextTick_ = std::chrono::steady_clock::now();
continue;
}
// Current slot may still be resolving (late resolve / playNow
// failed fallback): emit silence on cadence within grace.
if (current_.state == DecoderSlot::State::Resolving) {
pollNextResolve(); // also polls current_ (see below)
}
// 1) Fill the ring buffer from the active decoder.
if (current_.state == DecoderSlot::State::Active ||
current_.state == DecoderSlot::State::Warming) {
if (current_.state == DecoderSlot::State::Warming) {
activateSlot(current_);
}
while (ring_.size() < MAX_BUFFER_SHORTS &&
current_.decoder->getNextChunk(incomingChunk_)) {
ring_.append(std::span<const short>(
incomingChunk_.data(), incomingChunk_.size()));
}
}
// 2) Prefetch the next track near the end of the current one.
maybeStartPrefetch();
pollNextResolve();
// 2b) Crossfade: swap to the warm slot early and mix the
// outgoing tail into the incoming audio.
{
const auto fade = crossfadeMs_.load();
if (fade > 0 && fadeTail_.empty() &&
current_.state == DecoderSlot::State::Active &&
next_.state == DecoderSlot::State::Warming &&
!host_.repeatEnabled()) {
const auto duration = std::chrono::milliseconds(
currentDurationMs_.load());
const auto position = clock_.position();
if (duration.count() > 0 &&
duration - position <=
std::chrono::milliseconds(fade)) {
beginCrossfade();
}
}
}
// 3) Position bookkeeping / events.
positionTick();
// 4) Emit one chunk per 20ms tick.
const bool fading =
!fadeTail_.empty() && fadePos_ < fadeTail_.size();
if (ring_.size() >= SHORTS_PER_CHUNK || fading) {
// Full chunk available, OR a crossfade is in progress (the
// outgoing tail covers a not-yet-full incoming ring so the
// handoff has no silent gap).
silenceSince_ = {};
emitChunk(true);
} else if (current_.state == DecoderSlot::State::Active &&
current_.decoder->isFinished()) {
// Flush the tail (shorter than one chunk), zero-padded.
if (!ring_.empty()) {
emitChunk(true);
} else {
handleTrackEnd();
continue; // cadence continues; no extra sleep
}
} else if (current_.state == DecoderSlot::State::Resolving) {
// Waiting for a late resolve: keep the stream alive with
// silence, bounded by the configured resolve grace.
if (silenceSince_.time_since_epoch().count() == 0) {
silenceSince_ = std::chrono::steady_clock::now();
}
if (std::chrono::steady_clock::now() - silenceSince_ >
std::chrono::milliseconds(resolveGraceMs_.load())) {
Void::Log::warn(
"PlaybackEngine", "{}",
"Track resolve exceeded grace period, skipping");
host_.onPlaybackError(
Api::Error{Api::ErrorCode::NetworkError,
"Stream resolve timed out"},
current_.entry);
current_.closeAndReset();
silenceSince_ = {};
if (!beginNextFromQueue()) {
publishCurrent(std::nullopt);
playing_ = false;
clock_.stop();
host_.onEngineIdle();
}
continue;
}
emitChunk(false); // silence
} else {
// Underrun: decoder alive but momentarily starved (slow
// network, or the incoming decoder spinning up after a
// handoff). Emit SILENCE on the normal cadence — the TS3
// custom capture device pops ("reopens the channel") if the
// audio callback stops firing, so we must keep feeding it
// every 20ms even when there's no music yet.
emitChunk(false);
}
nextTick_ += std::chrono::milliseconds(CHUNK_MS);
std::this_thread::sleep_until(nextTick_);
}
Void::Log::debug("PlaybackEngine", "{}", "Engine thread exiting");
}
void PlaybackEngine::drainMailbox()
{
std::deque<Command> commands;
{
std::lock_guard<std::mutex> lock(mailboxMutex_);
commands.swap(mailbox_);
}
for (auto& cmd : commands) {
std::visit([this](auto&& c) { handle(std::move(c)); },
std::move(cmd));
}
}
void PlaybackEngine::handle(CmdPlayNow&& cmd)
{
// Replace whatever is playing.
ring_.clear();
clearFade();
current_.closeAndReset();
next_.closeAndReset();
consecutiveFailures_ = 0;
current_.entry = std::move(cmd.entry);
if (openSlot(current_, cmd.url, cmd.isLocalFile)) {
activateSlot(current_);
} else {
// Open failed — retry via the download-to-file path.
retryViaDownload(current_);
}
playing_ = true;
paused_ = false;
nextTick_ = std::chrono::steady_clock::now();
}
bool PlaybackEngine::retryViaDownload(DecoderSlot& slot)
{
if (!slot.entry || slot.triedDownload) {
return false;
}
slot.triedDownload = true;
auto entry = *slot.entry;
slot.state = DecoderSlot::State::Resolving;
slot.resolveStartedAt = std::chrono::steady_clock::now();
slot.resolveFuture = std::async(std::launch::async, [this, entry]() {
// preferDownload=true evicts the poisoned cache entry and
// downloads through the proxy (yt-dlp handles SOCKS5).
return host_.resolveStream(entry, true);
});
Void::Log::info("PlaybackEngine", "{}",
"Open failed; retrying via download-to-file");
return true;
}
void PlaybackEngine::handle(CmdStart&&)
{
if (current_.state != DecoderSlot::State::Idle || paused_.load()) {
return;
}
if (beginNextFromQueue()) {
playing_ = true;
nextTick_ = std::chrono::steady_clock::now();
}
}
void PlaybackEngine::handle(CmdPause&&)
{
if (!playing_.load() || paused_.exchange(true)) {
return;
}
clock_.pause();
}
void PlaybackEngine::handle(CmdResume&&)
{
if (!paused_.exchange(false)) {
return;
}
clock_.resume();
nextTick_ = std::chrono::steady_clock::now();
}
void PlaybackEngine::handle(CmdStop&&)
{
ring_.clear();
clearFade();
if (current_.isLocalFile && !current_.openUrl.empty()) {
host_.onLocalFileDone(current_.openUrl);
}
if (next_.isLocalFile && !next_.openUrl.empty()) {
host_.onLocalFileDone(next_.openUrl);
}
current_.closeAndReset();
next_.closeAndReset();
playing_ = false;
paused_ = false;
clock_.stop();
publishCurrent(std::nullopt);
currentDurationMs_ = 0;
}
void PlaybackEngine::handle(CmdSkip&& cmd)
{
if (current_.state == DecoderSlot::State::Idle) {
return;
}
if (current_.entry) {
host_.onTrackFinished(*current_.entry, clock_.position());
}
ring_.clear();
clearFade();
if (current_.isLocalFile && !current_.openUrl.empty()) {
host_.onLocalFileDone(current_.openUrl);
}
current_.closeAndReset();
// Consume (count - 1) additional entries from the queue.
for (uint32_t i = 1; i < cmd.count; ++i) {
if (!host_.takeAnyNextTrack()) {
break;
}
}
// Gapless skip: if the warm slot holds the next track and we skipped
// exactly one, promote it instantly.
if (cmd.count == 1 && next_.state == DecoderSlot::State::Warming) {
std::swap(current_, next_);
next_.closeAndReset();
// Commit the queue pop that the prefetch only peeked; a stale
// peek (queue edited meanwhile) falls through to a re-resolve.
if (current_.entry &&
host_.takeNextTrack(current_.entry->queueId)) {
activateSlot(current_);
return;
}
current_.closeAndReset();
}
next_.closeAndReset();
if (!beginNextFromQueue()) {
playing_ = false;
clock_.stop();
publishCurrent(std::nullopt);
host_.onEngineIdle();
}
}
void PlaybackEngine::handle(CmdSeek&& cmd)
{
if (current_.state != DecoderSlot::State::Active ||
!current_.decoder) {
return;
}
ring_.clear();
clearFade();
auto result = current_.decoder->seek(cmd.position);
if (result) {
clock_.seekTo(cmd.position);
} else {
Void::Log::error("PlaybackEngine", "{}",
std::format("Seek failed: {}",
result.error().message));
}
}
void PlaybackEngine::handle(CmdRestore&& cmd)
{
ring_.clear();
clearFade();
current_.closeAndReset();
next_.closeAndReset();
current_.entry = std::move(cmd.entry);
if (!openSlot(current_, cmd.url, false)) {
Void::Log::error("PlaybackEngine", "{}",
"Hot-reload restore failed to open source");
current_.closeAndReset();
return;
}
if (cmd.position.count() > 0) {
auto seekResult = current_.decoder->seek(cmd.position);
if (!seekResult) {
Void::Log::warn("PlaybackEngine", "{}",
"Restore seek failed; playing from start");
}
}
activateSlot(current_, cmd.position);
playing_ = true;
paused_ = cmd.paused;
if (cmd.paused) {
clock_.pause();
}
nextTick_ = std::chrono::steady_clock::now();
}
// ---- track flow ------------------------------------------------------
bool PlaybackEngine::beginNextFromQueue()
{
auto entry = host_.takeAnyNextTrack();
if (!entry) {
return false;
}
current_.entry = std::move(entry);
current_.state = DecoderSlot::State::Resolving;
current_.resolveStartedAt = std::chrono::steady_clock::now();
auto entryCopy = *current_.entry;
current_.resolveFuture =
std::async(std::launch::async, [this, entryCopy]() {
return host_.resolveStream(entryCopy, false);
});
playing_ = true;
return true;
}
void PlaybackEngine::maybeStartPrefetch()
{
if (current_.state != DecoderSlot::State::Active ||
next_.state != DecoderSlot::State::Idle) {
return;
}
const auto duration =
std::chrono::milliseconds(currentDurationMs_.load());
if (duration.count() <= 0) {
return;
}
const auto position = clock_.position();
const bool nearEnd =
duration <= PREFETCH_THRESHOLD
? position >= std::chrono::seconds(2)
: (duration - position) <= PREFETCH_THRESHOLD;
if (!nearEnd) {
return;
}
// Repeat replays the current entry; the resolve is usually cached.
std::optional<Api::QueueEntry> upcoming =
host_.repeatEnabled() ? current_.entry : host_.peekNextTrack();
if (!upcoming) {
return;
}
next_.entry = std::move(upcoming);
next_.state = DecoderSlot::State::Resolving;
next_.resolveStartedAt = std::chrono::steady_clock::now();
auto entryCopy = *next_.entry;
next_.resolveFuture =
std::async(std::launch::async, [this, entryCopy]() {
return host_.resolveStream(entryCopy, false);
});
Void::Log::info(
"PlaybackEngine", "{}",
std::format("Prefetching next track: {} - {}",
entryCopy.track.title, entryCopy.track.artist));
}
void PlaybackEngine::pollNextResolve()
{
for (DecoderSlot* slot : {&next_, &current_}) {
if (slot->state != DecoderSlot::State::Resolving ||
!slot->resolveFuture.valid()) {
continue;
}
if (slot->resolveFuture.wait_for(std::chrono::seconds(0)) !=
std::future_status::ready) {
continue;
}
auto result = slot->resolveFuture.get();
if (!result) {
Void::Log::warn(
"PlaybackEngine", "{}",
std::format("Stream resolve failed: {}",
result.error().message));
host_.onPlaybackError(result.error(), slot->entry);
const bool wasCurrent = (slot == &current_);
slot->closeAndReset();
if (wasCurrent) {
if (++consecutiveFailures_ >= MAX_CONSECUTIVE_FAILURES ||
!beginNextFromQueue()) {
playing_ = false;
clock_.stop();
publishCurrent(std::nullopt);
host_.onEngineIdle();
}
}
continue;
}
// Heuristic: download fallback paths land in the temp dir; the
// host tells us via resolveStream contract (paths vs URLs).
const bool isLocal = !result->starts_with("http");
if (!openSlot(*slot, *result, isLocal)) {
// A non-local URL that won't open (expired, IP-locked
// googlevideo under SOCKS5, dead instance): retry once via
// download-to-file before giving up on this track.
if (!isLocal && retryViaDownload(*slot)) {
continue;
}
host_.onPlaybackError(
Api::Error{Api::ErrorCode::AudioError,
"Failed to open resolved stream"},
slot->entry);
const bool wasCurrent = (slot == &current_);
slot->closeAndReset();
if (wasCurrent) {
if (++consecutiveFailures_ >= MAX_CONSECUTIVE_FAILURES ||
!beginNextFromQueue()) {
playing_ = false;
clock_.stop();
publishCurrent(std::nullopt);
host_.onEngineIdle();
}
}
continue;
}
if (slot == &current_) {
activateSlot(current_);
} else {
slot->state = DecoderSlot::State::Warming;
Void::Log::info("PlaybackEngine", "{}",
"Next track warmed for gapless handoff");
}
}
}
void PlaybackEngine::beginCrossfade()
{
// Bound the tail: what's already in the ring plus at most the
// crossfade duration from the decoder (it is within crossfadeMs of
// EOF, so its remaining queue is small and already buffered).
const auto maxTailSamples = static_cast<std::size_t>(
crossfadeMs_.load() * SAMPLE_RATE * CHANNELS / 1000);
fadeTail_.clear();
fadePos_ = 0;
fadeTail_.reserve(ring_.size() + maxTailSamples);
for (std::size_t i = 0; i < ring_.size(); ++i) {
fadeTail_.push_back(ring_[i]);
}
// NOT clearFade() here — the tail was just built from the ring.
ring_.clear();
while (fadeTail_.size() < maxTailSamples + SHORTS_PER_CHUNK &&
current_.decoder->getNextChunk(incomingChunk_)) {
fadeTail_.insert(fadeTail_.end(), incomingChunk_.begin(),
incomingChunk_.end());
}
if (current_.entry) {
host_.onTrackFinished(*current_.entry, clock_.position());
}
if (current_.isLocalFile && !current_.openUrl.empty()) {
host_.onLocalFileDone(current_.openUrl);
}
// Commit the warm slot (same stale-peek protocol as the EOF
// handoff).
current_.closeAndReset();
std::swap(current_, next_);
if (!current_.entry ||
!host_.takeNextTrack(current_.entry->queueId)) {
// Queue changed under the peek: put the tail back as normal
// output and advance conventionally later.
Void::Log::info("PlaybackEngine", "{}",
"Queue changed during crossfade; aborting fade");
current_.closeAndReset();
ring_.append(std::span<const short>(fadeTail_.data(),
fadeTail_.size()));
clearFade();
if (!beginNextFromQueue()) {
playing_ = false;
clock_.stop();
publishCurrent(std::nullopt);
host_.onEngineIdle();
}
return;
}
activateSlot(current_);
Void::Log::info(
"PlaybackEngine", "{}",
std::format("Crossfading over {} samples", fadeTail_.size()));
}
void PlaybackEngine::handleTrackEnd()
{
if (current_.entry) {
host_.onTrackFinished(*current_.entry, clock_.position());
}
if (current_.isLocalFile && !current_.openUrl.empty()) {
host_.onLocalFileDone(current_.openUrl);
}
consecutiveFailures_ = 0;
// Repeat: reopen the same source (decoder EOF'd, so reopen).
if (host_.repeatEnabled() && current_.entry) {
const std::string url = current_.openUrl;
const bool isLocal = current_.isLocalFile;
auto entry = *current_.entry;
// The warm slot may hold the same track (prefetch prefers the
// current entry under repeat) — use it if so.
if (next_.state == DecoderSlot::State::Warming && next_.entry &&
next_.entry->queueId == entry.queueId) {
current_.closeAndReset();
std::swap(current_, next_);
activateSlot(current_);
return;
}
current_.closeAndReset();
current_.entry = entry;
if (!url.empty() && openSlot(current_, url, isLocal)) {
activateSlot(current_);
return;
}
// Fall through to queue advance when the reopen failed.
}
// Gapless handoff to the warm slot.
if (next_.state == DecoderSlot::State::Warming) {
current_.closeAndReset();
std::swap(current_, next_);
if (current_.entry) {
// Commit the pop; if the queue changed since the peek the
// warm track is stale — drop it and advance normally.
auto committed = host_.takeNextTrack(current_.entry->queueId);
if (!committed) {
Void::Log::info(
"PlaybackEngine", "{}",
"Queue changed during prefetch; re-resolving");
current_.closeAndReset();
if (!beginNextFromQueue()) {
playing_ = false;
clock_.stop();
publishCurrent(std::nullopt);
host_.onEngineIdle();
}
return;
}
}
activateSlot(current_);
return;
}
// Next still resolving: keep its future, move it into current_ and
// let the silence-grace path in run() wait for it.
if (next_.state == DecoderSlot::State::Resolving) {
current_.closeAndReset();
std::swap(current_, next_);
// The peeked entry must be consumed from the queue now; if the
// queue changed the in-flight resolve is stale — drop it.
if (!current_.entry ||
!host_.takeNextTrack(current_.entry->queueId)) {
current_.closeAndReset();
if (!beginNextFromQueue()) {
playing_ = false;
clock_.stop();
publishCurrent(std::nullopt);
host_.onEngineIdle();
}
return;
}
silenceSince_ = std::chrono::steady_clock::now();
return;
}
// Nothing prefetched: advance from the queue.
current_.closeAndReset();
if (!beginNextFromQueue()) {
playing_ = false;
clock_.stop();
publishCurrent(std::nullopt);
currentDurationMs_ = 0;
host_.onEngineIdle();
}
}
bool PlaybackEngine::openSlot(DecoderSlot& slot, const std::string& url,
bool isLocalFile)
{
auto result = slot.decoder->openSource(url);
if (!result) {
Void::Log::error("PlaybackEngine", "{}",
std::format("Failed to open source: {}",
result.error().message));
return false;
}
slot.openUrl = url;
slot.isLocalFile = isLocalFile;
return true;
}
void PlaybackEngine::activateSlot(DecoderSlot& slot,
std::chrono::milliseconds startAt)
{
slot.state = DecoderSlot::State::Active;
consecutiveFailures_ = 0;
silenceSince_ = {};
clock_.seekTo(startAt);
clock_.resume();
if (slot.entry) {
slot.entry->isPlaying = true;
slot.entry->position = startAt;
}
publishCurrent(slot.entry);
if (auto info = slot.decoder->getStreamInfo()) {
currentDurationMs_ = info->duration.count();
} else {
currentDurationMs_ = 0;
}
if (slot.entry) {
host_.onTrackStarted(*slot.entry);
}
}
void PlaybackEngine::publishCurrent(
const std::optional<Api::QueueEntry>& entry)
{
std::lock_guard<std::mutex> lock(currentEntryMutex_);
publishedEntry_ = entry;
}
void PlaybackEngine::emitChunk(bool fromRing)
{
if (fromRing) {
const size_t available = std::min(ring_.size(), SHORTS_PER_CHUNK);
const bool fading =
!fadeTail_.empty() && fadePos_ < fadeTail_.size();
// The number of output samples we actually fill: during a fade
// we emit a FULL chunk even when the incoming ring is still
// short (the outgoing tail covers the gap), so a track handoff
// never leaves the TS3 device starved. Otherwise it's just what
// the ring holds.
const size_t filled = fading ? SHORTS_PER_CHUNK : available;
if (fading) {
// Equal-power blend: incoming (ring, or 0 if not ready yet)
// rises while the outgoing tail falls, across the whole
// chunk.
const auto fadeLen = static_cast<float>(fadeTail_.size());
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
const float incoming =
i < available ? static_cast<float>(ring_[i]) : 0.0f;
float mixed = incoming;
if (fadePos_ < fadeTail_.size()) {
const float theta =
(static_cast<float>(fadePos_) / fadeLen) *
1.57079632679f; // pi/2
mixed = incoming * std::sin(theta) +
static_cast<float>(fadeTail_[fadePos_]) *
std::cos(theta);
++fadePos_;
}
outChunk_[i] = static_cast<short>(std::clamp(
static_cast<int>(mixed), -32768, 32767));
}
if (fadePos_ >= fadeTail_.size()) {
clearFade();
}
} else {
for (size_t i = 0; i < available; ++i) {
outChunk_[i] = ring_[i];
}
}
// Loudness AGC (before user volume) + cubic user volume.
float gain = std::pow(volume_.load(), 3.0f);
if (normalizeEnabled_.load()) {
gain *= agcGainFor(filled);
}
if (gain != 1.0f) {
for (size_t i = 0; i < filled; ++i) {
const int sample = static_cast<int>(
static_cast<float>(outChunk_[i]) * gain);
outChunk_[i] = static_cast<short>(
std::clamp(sample, -32768, 32767));
}
}
// Zero-pad the remainder of a short chunk.
std::fill(outChunk_.begin() +
static_cast<std::ptrdiff_t>(filled),
outChunk_.end(), 0);
ring_.popFront(available);
} else {
std::fill(outChunk_.begin(), outChunk_.end(), 0);
}
host_.emitAudio(
std::span<const short>(outChunk_.data(), outChunk_.size()));
}
float PlaybackEngine::agcGainFor(std::size_t samples)
{
if (samples == 0) {
return 1.0f;
}
// Mean square of the (pre-gain) chunk, folded into a ~400ms EMA.
double sum = 0.0;
for (std::size_t i = 0; i < samples; ++i) {
const double v = static_cast<double>(outChunk_[i]);
sum += v * v;
}
const double chunkMs = sum / static_cast<double>(samples);
// Don't chase silence — hold the gain through quiet passages.
constexpr double kSilenceFloor = 32768.0 * 32768.0 * 1e-6; // -60dB
if (chunkMs > kSilenceFloor) {
constexpr double alpha = 0.05; // ~400ms at 20ms chunks
agcMeanSquare_ =
agcMeanSquare_ <= 0.0
? chunkMs
: agcMeanSquare_ + alpha * (chunkMs - agcMeanSquare_);
const float rmsDb = static_cast<float>(
10.0 * std::log10(agcMeanSquare_ /
(32768.0 * 32768.0)));
const float wantedDb = normalizeTargetDb_.load() - rmsDb;
// Slew: fast attack (turn down), slow release (turn up).
constexpr float kAttackPerChunk = 0.4f; // 20 dB/s
constexpr float kReleasePerChunk = 0.06f; // 3 dB/s
const float delta = wantedDb - agcGainDb_;
if (delta < 0.0f) {
agcGainDb_ += std::max(delta, -kAttackPerChunk);
} else {
agcGainDb_ += std::min(delta, kReleasePerChunk);
}
agcGainDb_ = std::clamp(agcGainDb_, -20.0f, 12.0f);
}
return std::clamp(std::pow(10.0f, agcGainDb_ / 20.0f), 0.1f, 4.0f);
}
void PlaybackEngine::positionTick()
{
if (current_.state != DecoderSlot::State::Active ||
!current_.entry) {
return;
}
const auto now = std::chrono::steady_clock::now();
if (now - lastPositionTick_ < std::chrono::seconds(1)) {
return;
}
lastPositionTick_ = now;
host_.onPositionTick(*current_.entry, clock_.position(),
std::chrono::milliseconds(
currentDurationMs_.load()));
}
} // namespace Echoion::Core