#pragma once #include "Database.hpp" #include "NetworkClient.hpp" #include "PlaylistLoader.hpp" #include "RpcTypes.hpp" #include "Socks5HttpBridge.hpp" #include "SubscriptionManager.hpp" #include "SubscriptionService.hpp" #include "TrackCache.hpp" #include "YouTubeClient.hpp" #include "playback/PlaybackEngine.hpp" #include "playback/QueueService.hpp" #include "sources/InnertubeSource.hpp" #include "sources/YandexMusicSource.hpp" #include "sources/SourceRouter.hpp" #include "sources/YtDlpSource.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Echoion::Core { // Facade over the playback services. Public surface is unchanged (Core, // the RPC handlers and ~27 commands call it); internally it wires: // - PlaybackEngine: real-time loop, both decoders, gapless handoff // - QueueService: queue + shuffle/repeat (self-locking) // - SubscriptionService: audience bookkeeping + pause-on-empty policy // and implements IPlaybackHost for the engine (stream resolution, queue // access, event publication). class MusicManager : private IPlaybackHost { public: MusicManager(); ~MusicManager() override; Api::Result initialize(std::shared_ptr networkClient, std::shared_ptr database = nullptr); void shutdown(); // Inject the application event bus (owned by Core). Must be set // before playback so emitted events reach subscribers. void setEventBus(Void::EventBus::EventBus* bus) { eventBus_ = bus; } // Inject the config holder (owned by Core). Must be set before // initialize() so config sections resolve. void setConfigManager(Api::ConfigManager* cfg) { configManager_ = cfg; } // Re-apply network settings (proxy) to every outbound client: // the HTTP NetworkClient (YouTube Data API, URL shortener), the // yt-dlp subprocess, and the ffmpeg decoders. Call after a // config reload so proxy changes actually take effect everywhere // instead of only living in the config copy. void applyNetworkConfig(const Api::NetworkConfig& network); // Re-apply YouTube settings (API key, cookies, concurrency, URL // shortening) to the YouTube client after a config reload. Passing // an empty/absent API key clears it, restoring the yt-dlp fallback. void applyYouTubeConfig(const Api::YouTubeConfig& youtube); // Re-apply the source-chain settings (order, cooldown, instance // lists) after a config reload. void applySourcesConfig(const Api::SourcesConfig& sources); void addTrackSource(std::shared_ptr source); void setSharedYouTubeClient(std::shared_ptr client) { youTubeClient_ = std::move(client); } [[nodiscard]] std::shared_ptr sharedYouTubeClient() const { return youTubeClient_; } // Re-apply bot settings (queue size, track timeout, playlist // import gate) after a config reload. Does not touch the live // volume. void applyBotConfig(const Api::BotConfig& bot); // Re-apply feature toggles (subscriber pause/resume policy, // auto-start, history size, autoplay) after a config reload. // shuffleMode/repeatMode are applied at cold start only. void applyFeaturesConfig(const Api::FeaturesConfig& features); [[nodiscard]] Api::Result play(const std::string& query, uint64_t clientId); [[nodiscard]] Api::Result pause(); [[nodiscard]] Api::Result resume(); [[nodiscard]] Api::Result stop(); [[nodiscard]] Api::Result skip(uint32_t count = 1); [[nodiscard]] Api::Result seek(std::chrono::milliseconds position); [[nodiscard]] Api::Result setVolume(float volume); // Vote-to-skip the current track. Votes are keyed by the voter's // stable uid and reset whenever the current track changes. The // threshold is features.voteSkipThreshold, or a majority of // online subscribers when 0. Reaching it skips the track. struct VoteSkipStatus { uint32_t votes = 0; uint32_t needed = 0; bool voted = false; // caller has an active vote bool skipped = false; }; [[nodiscard]] Api::Result voteSkip(const std::string& uid); [[nodiscard]] VoteSkipStatus voteSkipStatus(const std::string& uid) const; [[nodiscard]] Api::Result queueTrack(const Api::TrackInfo& track, uint64_t clientId); [[nodiscard]] Api::Result removeFromQueue(uint32_t position); [[nodiscard]] Api::Result clearQueue(); [[nodiscard]] Api::Result> getQueue() const; [[nodiscard]] Api::Result moveInQueue(uint32_t from, uint32_t to); [[nodiscard]] Api::Result toggleShuffle(); [[nodiscard]] Api::Result toggleRepeat(); [[nodiscard]] Api::Result shuffleQueue(); // Load playlist asynchronously - returns immediately, processes in // background Api::Result loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId); [[nodiscard]] bool isPlaylistLoading() const { return playlistLoader_ && playlistLoader_->isLoading(); } [[nodiscard]] size_t getPlaylistLoadProgress() const { return playlistLoader_ ? playlistLoader_->loadedCount() : 0; } [[nodiscard]] Api::Result> getPlaylists() const; [[nodiscard]] Api::Result> getCurrentTrack() const; [[nodiscard]] Api::Result getPlaybackState() const; [[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const; // Which catalog(s) a text search targets. enum class SearchScope { All, YouTube, Yandex, SoundCloud }; [[nodiscard]] Api::Result search(const std::string& query, SearchScope scope = SearchScope::All); // Search result selection (client-specific) void storePendingSearch(uint64_t clientId, const std::vector& results); [[nodiscard]] std::optional> getPendingSearch(uint64_t clientId); [[nodiscard]] Api::Result selectSearchResult(uint64_t clientId, uint32_t index, const std::string& invokerName); // Radio/autoplay toggle. Persisted in kv so it survives restart; // enabling while idle kicks an immediate related-track refill. void setAutoplay(bool enabled); [[nodiscard]] bool autoplayEnabled() const { return autoplay_.load(); } // Start playback (or seed radio) if nothing is playing and an // online subscriber is listening. Idempotent — safe to call after a // restore/hot-reload or when a subscriber connects, so radio resumes // without a manual !play / !radio toggle. void maybeAutoStart(); // Set shuffle/repeat mode directly (used when restoring persisted // state); persists the session snapshot. void setShuffle(bool enabled); void setRepeat(bool enabled); // Help command [[nodiscard]] std::string getHelpText() const; // Subscription management (by client ID - internally uses UID for // persistence) [[nodiscard]] Api::Result subscribe(uint64_t clientId); [[nodiscard]] Api::Result unsubscribe(uint64_t clientId); [[nodiscard]] bool isSubscribed(uint64_t clientId) const; [[nodiscard]] std::set getSubscribedClients() const; // Returns only ONLINE subscribers' client IDs [[nodiscard]] bool hasSubscribers() const; // Returns true if any subscribers exist // (online or offline) [[nodiscard]] bool hasOnlineSubscribers() const; // Returns true only if there are online subscribers [[nodiscard]] std::vector getSubscribers() const; [[nodiscard]] Api::Result unsubscribeByUid(const std::string& uid); [[nodiscard]] Api::Result clearAllSubscriptions(); // Get UIDs of subscribers who are currently online [[nodiscard]] std::set getOnlineSubscriberUids() const; // Called when a client connects to the server void onClientConnected(uint64_t clientId); [[nodiscard]] Api::HotReloadState getStateForHotReload() const; [[nodiscard]] Api::Result restoreFromHotReload(const Api::HotReloadState& state); using AudioDataCallback = std::function)>; void setAudioDataCallback(const AudioDataCallback& callback); using SubscriptionChangeCallback = std::function; void setSubscriptionChangeCallback( const SubscriptionChangeCallback& callback); using PlaybackStartCallback = std::function; void setPlaybackStartCallback(const PlaybackStartCallback& callback); // Callback to resolve client info (UID and nickname) from client ID using ClientInfoCallback = std::function>(uint64_t clientId)>; void setClientInfoCallback(const ClientInfoCallback& callback); // Callback to resolve client ID from UID using UidToClientIdCallback = std::function(const std::string& uid)>; void setUidToClientIdCallback(const UidToClientIdCallback& callback); // Callback to resolve nickname from client ID using NicknameCallback = std::function(uint64_t clientId)>; void setNicknameCallback(const NicknameCallback& callback); // Callback to send a private text message to a client (wired by // Core to the plugin). Used for proactive announcements. using MessageCallback = std::function; void setMessageCallback(const MessageCallback& callback) { messageCallback_ = callback; } // Set the current announcement (admin !announce) and deliver it // to online subscribers now. Bumps the stored announcement id so // a fresh post reaches everyone once. Returns how many online // subscribers were reached immediately. [[nodiscard]] size_t setAnnouncement(const std::string& text); // Called when a client leaves the server void onClientDisconnected(uint64_t clientId); // Resolve the stable TS3 unique identifier for a session client // id (used to key per-user persistent data such as favorites). [[nodiscard]] std::optional clientUid(uint64_t clientId) const { if (clientInfoCallback_) { if (auto info = clientInfoCallback_(clientId)) { return info->first; } } return std::nullopt; } // Persistent storage shared with commands (may be null when the // database failed to open). [[nodiscard]] std::shared_ptr database() const { return database_; } private: // ---- IPlaybackHost (called from the engine) -------------------- void emitAudio(std::span samples) override; Api::Result resolveStream(const Api::QueueEntry& entry, bool preferDownload) override; std::optional peekNextTrack() override; std::optional takeNextTrack(uint64_t expectedQueueId) override; std::optional takeAnyNextTrack() override; bool repeatEnabled() const override; void onTrackStarted(const Api::QueueEntry& entry) override; void onTrackFinished(const Api::QueueEntry& entry, std::chrono::milliseconds finalPosition) override; void onPositionTick(const Api::QueueEntry& entry, std::chrono::milliseconds position, std::chrono::milliseconds duration) override; void onEngineIdle() override; void onLocalFileDone(const std::string& path) override; // Persist the live queue + shuffle/repeat/autoplay to the database // (kv "session.state") so a full restart can restore them; restore // them at startup. persistSession() is a no-op while a restore is in // progress to avoid recursive writes. includeCurrent=false drops // the currently-playing track from the snapshot — used by stop(), // where the engine clears its entry asynchronously and would // otherwise be persisted as still queued. void persistSession(bool includeCurrent = true); void restoreSession(); std::atomic restoringSession_{false}; void onPlaybackError(const Api::Error& error, const std::optional& entry) override; // ---- helpers --------------------------------------------------- // Publish a domain event on the injected bus (no-op until set). template void emit(T event) { if (eventBus_) { eventBus_->publish(std::move(event)); } } // Auto-start the playback loop when a playlist's first track lands. void requestPlaybackStart(); // Publish PlaybackPaused/PlaybackResumed with the current track // and position (called from pause/resume and the subscriber // policy hooks so the Desktop sees every pause-state change). void emitPauseState(bool paused); [[nodiscard]] Api::Result resolveQuery(const std::string& query); [[nodiscard]] Api::Result getStreamUrl(const Api::TrackInfo& track); [[nodiscard]] std::string nicknameFor(uint64_t clientId) const; // Download audio through proxy for playback [[nodiscard]] Api::Result downloadAudioForPlayback(const Api::TrackInfo& track); void cleanupTempFile(const std::string& filepath); // The proxy the playback engine (ffmpeg) should use. ffmpeg only // speaks HTTP CONNECT, so a SOCKS5 config starts the local // Socks5HttpBridge and is rewritten to an Http proxy pointing at // it; Http/none pass through unchanged (and stop the bridge). [[nodiscard]] std::optional effectiveEngineProxy( const std::optional& proxy); // ---- state ----------------------------------------------------- // Temporary file tracking std::set tempFiles_; mutable std::shared_mutex tempFilesMutex_; // Async playlist loading (background thread owned by the loader). std::unique_ptr playlistLoader_; std::shared_ptr networkClient_; std::shared_ptr database_; // Non-owning application event bus (provided by Core). Void::EventBus::EventBus* eventBus_ = nullptr; // Non-owning config holder (provided by Core). Api::ConfigManager* configManager_ = nullptr; std::shared_ptr youTubeClient_; // Source-resolution chain (proxy-free first, proxied last). std::unique_ptr router_; std::shared_ptr innertubeSource_; std::shared_ptr yandexSource_; std::shared_ptr ytdlpProxied_; Api::BotConfig config_; std::atomic autoStartOnSubscribe_{true}; std::atomic autoplay_{false}; QueueService queue_; std::unique_ptr trackCache_; // Vote-to-skip state: voter uids for the queue entry identified // by voteSkipQueueId_ (cleared lazily when the track changes). mutable std::mutex voteSkipMutex_; std::set voteSkipUids_; uint64_t voteSkipQueueId_ = 0; std::atomic voteSkipThreshold_{0}; // 0 = auto majority [[nodiscard]] uint32_t voteSkipNeeded() const; // Autoplay state: seed track for recommendations + re-entrancy // guard for the async fetch. The seed's catalog decides where // related tracks are pulled from (YouTube radio mix vs. Yandex // similar tracks). enum class AutoplaySeedSource { None, YouTube, Yandex }; mutable std::mutex autoplaySeedMutex_; std::string autoplaySeedId_; AutoplaySeedSource autoplaySeedSource_ = AutoplaySeedSource::None; std::atomic autoplayFetching_{false}; std::jthread autoplayThread_; // Fallback seed for radio when nothing has been played this // session: derive one from the most recent history entry. [[nodiscard]] std::optional< std::pair> autoplaySeedFromHistory() const; // Spotify/Yandex collection imports (background metadata fetch; // enqueue itself is instant). std::atomic importRunning_{false}; std::jthread importThread_; std::unique_ptr engine_; // HTTP CONNECT -> SOCKS5 tunnel for ffmpeg (see // effectiveEngineProxy); only running while the configured proxy // is SOCKS5. std::unique_ptr ffmpegProxyBridge_; std::unique_ptr subscriptions_; // Pending search results per client (for select command) std::unordered_map> pendingSearches_; mutable std::mutex pendingSearchMutex_; // Callbacks are stored here as well as forwarded to the // subscription service: Core may register them before // initialize() has created the service. AudioDataCallback audioCallback_; PlaybackStartCallback playbackStartCallback_; NicknameCallback nicknameCallback_; MessageCallback messageCallback_; // Deliver the current announcement to (clientId, uid) if that // subscriber hasn't seen it yet (per-uid seen-id in kv_store). // Returns true when a message was actually sent. bool deliverAnnouncementTo(uint64_t clientId, const std::string& uid); SubscriptionChangeCallback subscriptionChangeCallback_; ClientInfoCallback clientInfoCallback_; UidToClientIdCallback uidToClientIdCallback_; }; } // namespace Echoion::Core