#pragma once #include "../AudioDecoder.hpp" #include "AudioRingBuffer.hpp" #include "PositionClock.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include 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 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 resolveStream(const Api::QueueEntry& entry, bool preferDownload) = 0; // Queue access: peek what would play next / pop it if unchanged. virtual std::optional peekNextTrack() = 0; virtual std::optional takeNextTrack(uint64_t expectedQueueId) = 0; // Unconditional pop (fallback when the peeked entry vanished). virtual std::optional 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& 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; // Grace while a download-to-file retry is in flight. Must cover // YouTubeClient::downloadAudioToFile's 180s wait — the normal // resolve grace (bot.trackTimeout, ~10s) would skip the track // long before the download lands. static constexpr int64_t DOWNLOAD_GRACE_MS = 200'000; // 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(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 initialize(const std::optional& proxy); void shutdown(); void setProxyConfig( const std::optional& 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 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; 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 decoder; std::optional entry; std::future> 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(); fadeTailPos_ = 0; fadeEnvPos_ = 0; fadeIncomingStarved_ = false; } // 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& entry); void emitChunk(bool fromRing); void positionTick(); IPlaybackHost& host_; // Mailbox std::mutex mailboxMutex_; std::deque mailbox_; std::condition_variable mailboxCv_; // Engine-thread-only state DecoderSlot current_; DecoderSlot next_; AudioRingBuffer ring_; std::vector outChunk_; std::vector 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. // The tail cursor and the envelope advance independently: the // tail plays continuously, while the envelope only progresses as // incoming audio is actually delivered — so a network-starved // incoming stream stretches the fade instead of being chopped // against a racing envelope. std::vector fadeTail_; std::size_t fadeTailPos_ = 0; std::size_t fadeEnvPos_ = 0; bool fadeIncomingStarved_ = false; // 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 playing_{false}; std::atomic paused_{false}; std::atomic volume_{0.5f}; std::atomic resolveGraceMs_{10000}; std::atomic crossfadeMs_{0}; std::atomic normalizeEnabled_{false}; std::atomic normalizeTargetDb_{-14.0f}; PositionClock clock_; mutable std::mutex currentEntryMutex_; std::optional publishedEntry_; std::atomic currentDurationMs_{0}; std::optional proxy_; std::jthread thread_; std::atomic initialized_{false}; }; } // namespace Echoion::Core