Files
faumaray 5c036d91fb making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:45:17 +03:00

349 lines
11 KiB
C++

#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;
// 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<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();
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<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.
// 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<short> 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<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