Release 1.0.0

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-04 01:49:28 +03:00
1 parent df99b6ea7f
commit d146f11f02
63 files changed
+8331 -2709

No files matched your search

@@ -0,0 +1,93 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <span>
#include <vector>
namespace Echoion::Core
{
// Fixed-capacity ring buffer of audio samples for the playback thread.
//
// A std::vector<short> drained with erase(begin(), begin()+n) every 20ms
// is an O(n) shift of the whole remaining buffer on the real-time audio
// path. This ring buffer drains by advancing a head index (O(1)) and
// reuses one contiguous allocation, so steady-state playback performs
// zero per-frame allocations and no element shuffling. Capacity grows
// only if a decoder hands back an unusually large chunk (rare); steady
// state never reallocates.
//
// Single-threaded by design: owned and touched only by the playback
// engine thread.
class AudioRingBuffer
{
public:
void reserve(std::size_t capacity)
{
if (capacity > storage_.size()) {
grow(capacity);
}
}
[[nodiscard]] std::size_t size() const { return count_; }
[[nodiscard]] bool empty() const { return count_ == 0; }
// Read the i-th sample counting from the current head.
short operator[](std::size_t i) const
{
return storage_[(head_ + i) % storage_.size()];
}
void append(std::span<const short> data)
{
if (count_ + data.size() > storage_.size()) {
grow(count_ + data.size());
}
const std::size_t cap = storage_.size();
std::size_t tail = (head_ + count_) % cap;
for (short sample : data) {
storage_[tail] = sample;
tail = (tail + 1) % cap;
}
count_ += data.size();
}
// Drop the first n samples (advance head). O(1).
void popFront(std::size_t n)
{
n = std::min(n, count_);
head_ = (head_ + n) % storage_.size();
count_ -= n;
}
void clear()
{
head_ = 0;
count_ = 0;
}
private:
void grow(std::size_t needed)
{
// Linearise existing samples into a fresh, larger buffer.
std::size_t newCap = storage_.empty() ? 1 : storage_.size();
while (newCap < needed) {
newCap *= 2;
}
std::vector<short> next(newCap);
for (std::size_t i = 0; i < count_; ++i) {
next[i] = storage_[(head_ + i) % storage_.size()];
}
storage_ = std::move(next);
head_ = 0;
}
std::vector<short> storage_;
std::size_t head_ = 0;
std::size_t count_ = 0;
};
} // namespace Echoion::Core
@@ -0,0 +1,331 @@
#pragma once
#include "../AudioDecoder.hpp"
#include "AudioRingBuffer.hpp"
#include "PositionClock.hpp"
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <thread>
#include <variant>
namespace Echoion::Core
{
// Everything the engine needs from the outside world. Implemented by
// MusicManager; keeps queue policy, source resolution and event
// publication out of the real-time loop.
class IPlaybackHost
{
public:
virtual ~IPlaybackHost() = default;
// Emit one 20ms PCM chunk to the audio sink (TeamSpeak).
virtual void emitAudio(std::span<const short> samples) = 0;
// Resolve a playable URL / local file path for the entry.
// Blocking; the engine calls it on a detached async, never on the
// audio thread. preferDownload retries via the proxy-download
// path after a direct open failed.
virtual Api::Result<std::string>
resolveStream(const Api::QueueEntry& entry,
bool preferDownload) = 0;
// Queue access: peek what would play next / pop it if unchanged.
virtual std::optional<Api::QueueEntry> peekNextTrack() = 0;
virtual std::optional<Api::QueueEntry>
takeNextTrack(uint64_t expectedQueueId) = 0;
// Unconditional pop (fallback when the peeked entry vanished).
virtual std::optional<Api::QueueEntry> takeAnyNextTrack() = 0;
virtual bool repeatEnabled() const = 0;
// Lifecycle notifications (called on the engine thread).
virtual void onTrackStarted(const Api::QueueEntry& entry) = 0;
virtual void
onTrackFinished(const Api::QueueEntry& entry,
std::chrono::milliseconds finalPosition) = 0;
virtual void onPositionTick(const Api::QueueEntry& entry,
std::chrono::milliseconds position,
std::chrono::milliseconds duration) = 0;
// Queue ran dry; engine went idle.
virtual void onEngineIdle() = 0;
// A resolved local temp file finished playing and can be deleted.
virtual void onLocalFileDone(const std::string& path) = 0;
// A track failed to resolve or open (before the engine advanced
// past it). Called on the engine thread.
virtual void
onPlaybackError(const Api::Error& error,
const std::optional<Api::QueueEntry>& entry) = 0;
};
// Real-time playback engine with gapless track transitions.
//
// One fixed-cadence (20ms) loop owns BOTH AudioDecoder instances, the
// ring buffer and the position clock; no other thread ever touches them.
// Control arrives through a small command mailbox; state is published
// through atomics. While the current track plays, the next one is
// resolved asynchronously and its decoder pre-opened ("warm"), so at EOF
// the engine swaps slots and PCM flows without interruption.
class PlaybackEngine
{
public:
// Sample layout must match the TS3 custom device registration.
static constexpr uint32_t SAMPLE_RATE = 192000;
static constexpr uint32_t CHANNELS = 2;
static constexpr int CHUNK_MS = 20;
static constexpr size_t SHORTS_PER_CHUNK =
(SAMPLE_RATE * CHANNELS * CHUNK_MS) / 1000;
static constexpr auto PREFETCH_THRESHOLD =
std::chrono::seconds(15);
static constexpr int MAX_CONSECUTIVE_FAILURES = 5;
// How long the engine emits silence waiting for a late resolve
// before it gives up on the track and advances. Configurable via
// bot.trackTimeout.
void setResolveGrace(std::chrono::milliseconds grace)
{
if (grace.count() > 0) {
resolveGraceMs_.store(grace.count());
}
}
// Crossfade duration between tracks (bot.crossfadeMs);
// 0 = plain gapless handoff.
void setCrossfade(std::chrono::milliseconds duration)
{
crossfadeMs_.store(std::max<int64_t>(duration.count(), 0));
}
// Loudness normalization (features.normalizeLoudness /
// targetLoudnessDb): slow AGC toward the target RMS level,
// applied before the user volume.
void setNormalization(bool enabled, float targetDb)
{
normalizeTargetDb_.store(targetDb);
normalizeEnabled_.store(enabled);
}
explicit PlaybackEngine(IPlaybackHost& host);
~PlaybackEngine();
Api::Result<void> initialize(
const std::optional<Void::Net::ProxyConfig>& proxy);
void shutdown();
void setProxyConfig(
const std::optional<Void::Net::ProxyConfig>& proxy);
// ---- control (thread-safe, non-blocking) ---------------------
// Play this entry now, replacing whatever is playing. The URL was
// already resolved by the caller (so resolution errors could be
// reported to the user synchronously).
void playNow(Api::QueueEntry entry, std::string streamUrl,
bool isLocalFile);
// Wake the engine so it pulls from the queue if it is idle.
void start();
void pause();
void resume();
void stopPlayback(); // stop + drop current track (engine idles)
void skip(uint32_t count);
void seekTo(std::chrono::milliseconds position);
// Restore after hot reload: open url, seek, optionally stay
// paused.
void restore(Api::QueueEntry entry, std::string streamUrl,
std::chrono::milliseconds position, bool paused);
void setVolume(float volume) { volume_.store(volume); }
[[nodiscard]] float volume() const { return volume_.load(); }
// ---- state (thread-safe reads) --------------------------------
[[nodiscard]] bool isPlaying() const { return playing_.load(); }
[[nodiscard]] bool isPaused() const { return paused_.load(); }
[[nodiscard]] std::chrono::milliseconds position() const
{
return clock_.position();
}
[[nodiscard]] std::optional<Api::QueueEntry> currentEntry() const;
[[nodiscard]] std::chrono::milliseconds currentDuration() const;
private:
// ---- mailbox ---------------------------------------------------
struct CmdPlayNow {
Api::QueueEntry entry;
std::string url;
bool isLocalFile = false;
};
struct CmdStart {};
struct CmdPause {};
struct CmdResume {};
struct CmdStop {};
struct CmdSkip {
uint32_t count = 1;
};
struct CmdSeek {
std::chrono::milliseconds position;
};
struct CmdRestore {
Api::QueueEntry entry;
std::string url;
std::chrono::milliseconds position;
bool paused = false;
};
using Command =
std::variant<CmdPlayNow, CmdStart, CmdPause, CmdResume,
CmdStop, CmdSkip, CmdSeek, CmdRestore>;
void post(Command cmd);
// ---- decoder slots --------------------------------------------
struct ResolvedStream {
std::string url;
bool isLocalFile = false;
};
struct DecoderSlot {
enum class State {
Idle, // nothing assigned
Resolving, // resolveFuture in flight
Warming, // decoder open, pre-filling its queue
Active, // currently feeding the ring buffer
};
State state = State::Idle;
std::unique_ptr<AudioDecoder> decoder;
std::optional<Api::QueueEntry> entry;
std::future<Api::Result<std::string>> resolveFuture;
std::chrono::steady_clock::time_point resolveStartedAt{};
std::string openUrl;
bool isLocalFile = false;
// Whether the download-to-file fallback was already tried
// for this entry (bounds the retry to one attempt).
bool triedDownload = false;
void closeAndReset()
{
if (decoder) {
decoder->closeSource();
}
state = State::Idle;
entry.reset();
resolveFuture = {};
openUrl.clear();
isLocalFile = false;
triedDownload = false;
}
};
// Kick off an async download-to-file retry for the slot's entry
// (preferDownload=true). Returns false when no retry is possible
// (already tried, or no entry).
bool retryViaDownload(DecoderSlot& slot);
// ---- engine thread --------------------------------------------
void run(std::stop_token st);
void drainMailbox();
void handle(CmdPlayNow&& cmd);
void handle(CmdStart&&);
void handle(CmdPause&&);
void handle(CmdResume&&);
void handle(CmdStop&&);
void handle(CmdSkip&& cmd);
void handle(CmdSeek&& cmd);
void handle(CmdRestore&& cmd);
// Try to begin playing the next queued track in the current slot
// (used when idle). Returns true when a track started resolving
// or playing.
bool beginNextFromQueue();
// Kick off async resolution of the upcoming track into next_.
void maybeStartPrefetch();
// Move a finished resolve into an open, warming decoder.
void pollNextResolve();
// Current track hit EOF and drained: hand off or advance.
void handleTrackEnd();
// Crossfade: drain the current track's tail and swap to the warm
// slot early so emitChunk can mix the two.
void beginCrossfade();
void clearFade()
{
fadeTail_.clear();
fadePos_ = 0;
}
// AGC gain for one chunk (updates the internal RMS/gain state).
[[nodiscard]] float agcGainFor(std::size_t samples);
// Open `slot`'s decoder for `url`; false on failure.
bool openSlot(DecoderSlot& slot, const std::string& url,
bool isLocalFile);
void activateSlot(DecoderSlot& slot,
std::chrono::milliseconds startAt =
std::chrono::milliseconds(0));
void publishCurrent(const std::optional<Api::QueueEntry>& entry);
void emitChunk(bool fromRing);
void positionTick();
IPlaybackHost& host_;
// Mailbox
std::mutex mailboxMutex_;
std::deque<Command> mailbox_;
std::condition_variable mailboxCv_;
// Engine-thread-only state
DecoderSlot current_;
DecoderSlot next_;
AudioRingBuffer ring_;
std::vector<short> outChunk_;
std::vector<int16_t> incomingChunk_;
std::chrono::steady_clock::time_point nextTick_{};
std::chrono::steady_clock::time_point lastPositionTick_{};
std::chrono::steady_clock::time_point silenceSince_{};
int consecutiveFailures_ = 0;
// Crossfade state (engine thread only): the outgoing track's
// remaining PCM, mixed into the incoming track equal-power.
std::vector<short> fadeTail_;
std::size_t fadePos_ = 0;
// AGC state (engine thread only): EMA of mean-square level and
// the current smoothed gain in dB.
double agcMeanSquare_ = 0.0;
float agcGainDb_ = 0.0f;
// Published state
std::atomic<bool> playing_{false};
std::atomic<bool> paused_{false};
std::atomic<float> volume_{0.5f};
std::atomic<int64_t> resolveGraceMs_{10000};
std::atomic<int64_t> crossfadeMs_{0};
std::atomic<bool> normalizeEnabled_{false};
std::atomic<float> normalizeTargetDb_{-14.0f};
PositionClock clock_;
mutable std::mutex currentEntryMutex_;
std::optional<Api::QueueEntry> publishedEntry_;
std::atomic<int64_t> currentDurationMs_{0};
std::optional<Void::Net::ProxyConfig> proxy_;
std::jthread thread_;
std::atomic<bool> initialized_{false};
};
} // namespace Echoion::Core
@@ -0,0 +1,89 @@
#pragma once
#include <atomic>
#include <chrono>
#include <cstdint>
namespace Echoion::Core
{
// Wall-clock based playback position. Replaces the playbackPosition_ /
// playbackBasePosition_ / playbackStartTime_ triple whose reset logic was
// duplicated across play/resume/skip/seek/track-finished/restore.
//
// Lock-free: the engine thread writes, any thread reads a consistent
// position (worst case one field is a few ns stale, irrelevant at ms
// granularity for UI display).
class PositionClock
{
public:
using ms = std::chrono::milliseconds;
// Track started from zero (or restarted); clock runs.
void restart()
{
seekTo(ms{0});
running_.store(true);
}
// Jump to a position and keep running/paused state.
void seekTo(ms position)
{
baseMs_.store(position.count());
startedAtNs_.store(nowNs());
}
void pause()
{
if (!running_.exchange(false)) {
return;
}
baseMs_.store(currentMs());
}
void resume()
{
if (running_.load()) {
return; // already running; resetting startedAt would
// rewind the position
}
startedAtNs_.store(nowNs());
running_.store(true);
}
void stop()
{
running_.store(false);
baseMs_.store(0);
}
[[nodiscard]] bool running() const { return running_.load(); }
[[nodiscard]] ms position() const { return ms{currentMs()}; }
private:
[[nodiscard]] static int64_t nowNs()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
[[nodiscard]] int64_t currentMs() const
{
const int64_t base = baseMs_.load();
if (!running_.load()) {
return base;
}
const int64_t elapsedNs = nowNs() - startedAtNs_.load();
return base + elapsedNs / 1'000'000;
}
std::atomic<int64_t> baseMs_{0};
std::atomic<int64_t> startedAtNs_{0};
std::atomic<bool> running_{false};
};
} // namespace Echoion::Core
@@ -0,0 +1,97 @@
#pragma once
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <cstdint>
#include <mutex>
#include <optional>
#include <random>
#include <vector>
namespace Echoion::Core
{
// Owns the playback queue, shuffle order and repeat flag. Self-locking:
// every public method takes the internal mutex, so callers never manage
// queue locks (the old QueueManager exposed raw references and relied on
// MusicManager's shared_mutex, which several writers acquired shared).
//
// Shuffle model: shuffledIndices_ is a permutation of positions into
// entries_; shuffleIndex_ is the cursor of the next shuffled pick.
// Removing/moving/adding entries fixes the permutation up in place, so
// already-played order is preserved.
class QueueService
{
public:
using Entry = Api::QueueEntry;
// ---- mutation -------------------------------------------------
// Appends a track. Fails when the queue is at maxSize.
Api::Result<uint64_t> enqueue(const Api::TrackInfo& track,
std::string addedBy,
std::size_t maxSize);
// Removes the entry at `position`; returns it for event payloads.
Api::Result<Entry> removeAt(uint32_t position);
// Returns the number of entries removed.
uint32_t clear();
// Moves an entry; returns its queueId for event payloads.
Api::Result<uint64_t> move(uint32_t from, uint32_t to);
// Pops the next entry honouring shuffle order.
std::optional<Entry> popNext();
// Pops the next entry only if it is still the given one — the
// gapless engine peeks, warms a decoder, and commits at the swap;
// queue edits in between invalidate the warm slot.
std::optional<Entry> popIfNext(uint64_t queueId);
// Replace the whole queue (hot-reload restore).
void replaceAll(std::vector<Entry> entries);
// In-place random shuffle of the raw order (legacy !shufflequeue).
void shuffleInPlace();
// ---- shuffle / repeat -----------------------------------------
bool toggleShuffle();
void setShuffle(bool enabled);
[[nodiscard]] bool shuffleEnabled() const;
bool toggleRepeat();
void setRepeat(bool enabled);
[[nodiscard]] bool repeatEnabled() const;
// ---- inspection -----------------------------------------------
[[nodiscard]] std::optional<Entry> peekNext() const;
[[nodiscard]] std::vector<Entry> snapshot() const;
[[nodiscard]] std::size_t size() const;
[[nodiscard]] bool empty() const;
// Allocate a queue id for entries created outside the queue (the
// immediately-played track in play()).
[[nodiscard]] uint64_t allocateQueueId();
private:
// All *Locked helpers assume mutex_ is held.
void rebuildShuffledIndicesLocked();
[[nodiscard]] std::optional<std::size_t> nextPositionLocked() const;
std::optional<Entry> popNextLocked();
mutable std::mutex mutex_;
std::vector<Entry> entries_;
std::vector<std::size_t> shuffledIndices_;
std::size_t shuffleIndex_ = 0;
uint64_t nextQueueId_ = 1;
bool shuffle_ = false;
bool repeat_ = false;
std::mt19937 rng_{std::random_device{}()};
};
} // namespace Echoion::Core