Files
EchoionCore/include/echoion/core/MusicManager.hpp
faumaray 39aff68d8d Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:49:57 +03:00

455 lines
17 KiB
C++

#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 <ConfigManager.hpp>
#include <ConfigTypes.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <Void/Async/EventBus.hpp>
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <shared_mutex>
#include <span>
#include <string>
#include <unordered_map>
#include <vector>
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<void>
initialize(std::shared_ptr<NetworkClient> networkClient,
std::shared_ptr<Api::Database> 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<ITrackSource> source);
void setSharedYouTubeClient(std::shared_ptr<YouTubeClient> client)
{
youTubeClient_ = std::move(client);
}
[[nodiscard]] std::shared_ptr<YouTubeClient> 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<std::string>
play(const std::string& query, uint64_t clientId);
[[nodiscard]] Api::Result<void> pause();
[[nodiscard]] Api::Result<void> resume();
[[nodiscard]] Api::Result<void> stop();
[[nodiscard]] Api::Result<void> skip(uint32_t count = 1);
[[nodiscard]] Api::Result<void>
seek(std::chrono::milliseconds position);
[[nodiscard]] Api::Result<void> 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<VoteSkipStatus>
voteSkip(const std::string& uid);
[[nodiscard]] VoteSkipStatus
voteSkipStatus(const std::string& uid) const;
[[nodiscard]] Api::Result<uint64_t>
queueTrack(const Api::TrackInfo& track, uint64_t clientId);
[[nodiscard]] Api::Result<void> removeFromQueue(uint32_t position);
[[nodiscard]] Api::Result<void> clearQueue();
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
getQueue() const;
[[nodiscard]] Api::Result<void> moveInQueue(uint32_t from,
uint32_t to);
[[nodiscard]] Api::Result<bool> toggleShuffle();
[[nodiscard]] Api::Result<bool> toggleRepeat();
[[nodiscard]] Api::Result<void> shuffleQueue();
// Load playlist asynchronously - returns immediately, processes in
// background
Api::Result<void> 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<std::vector<Api::PlaylistInfo>>
getPlaylists() const;
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
getCurrentTrack() const;
[[nodiscard]] Api::Result<Api::PlaybackState>
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<Api::SearchResult>
search(const std::string& query,
SearchScope scope = SearchScope::All);
// Search result selection (client-specific)
void storePendingSearch(uint64_t clientId,
const std::vector<Api::TrackInfo>& results);
[[nodiscard]] std::optional<std::vector<Api::TrackInfo>>
getPendingSearch(uint64_t clientId);
[[nodiscard]] Api::Result<std::string>
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<std::string> subscribe(uint64_t clientId);
[[nodiscard]] Api::Result<std::string>
unsubscribe(uint64_t clientId);
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
[[nodiscard]] std::set<uint64_t> 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<SubscriptionManager::Subscriber>
getSubscribers() const;
[[nodiscard]] Api::Result<std::string>
unsubscribeByUid(const std::string& uid);
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
// Get UIDs of subscribers who are currently online
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
// Called when a client connects to the server
void onClientConnected(uint64_t clientId);
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
[[nodiscard]] Api::Result<void>
restoreFromHotReload(const Api::HotReloadState& state);
using AudioDataCallback =
std::function<void(const std::span<const short>)>;
void setAudioDataCallback(const AudioDataCallback& callback);
using SubscriptionChangeCallback = std::function<void()>;
void setSubscriptionChangeCallback(
const SubscriptionChangeCallback& callback);
using PlaybackStartCallback = std::function<void()>;
void
setPlaybackStartCallback(const PlaybackStartCallback& callback);
// Callback to resolve client info (UID and nickname) from client ID
using ClientInfoCallback = std::function<std::optional<
std::pair<std::string, std::string>>(uint64_t clientId)>;
void setClientInfoCallback(const ClientInfoCallback& callback);
// Callback to resolve client ID from UID
using UidToClientIdCallback =
std::function<std::optional<uint64_t>(const std::string& uid)>;
void
setUidToClientIdCallback(const UidToClientIdCallback& callback);
// Callback to resolve nickname from client ID
using NicknameCallback =
std::function<std::optional<std::string>(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(uint64_t clientId, const std::string&)>;
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<std::string>
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<Api::Database> database() const
{
return database_;
}
private:
// ---- IPlaybackHost (called from the engine) --------------------
void emitAudio(std::span<const short> samples) override;
Api::Result<std::string>
resolveStream(const Api::QueueEntry& entry,
bool preferDownload) override;
std::optional<Api::QueueEntry> peekNextTrack() override;
std::optional<Api::QueueEntry>
takeNextTrack(uint64_t expectedQueueId) override;
std::optional<Api::QueueEntry> 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<bool> restoringSession_{false};
void onPlaybackError(const Api::Error& error,
const std::optional<Api::QueueEntry>& entry)
override;
// ---- helpers ---------------------------------------------------
// Publish a domain event on the injected bus (no-op until set).
template <typename T> void emit(T event)
{
if (eventBus_) {
eventBus_->publish<T>(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<Api::TrackInfo>
resolveQuery(const std::string& query);
[[nodiscard]] Api::Result<std::string>
getStreamUrl(const Api::TrackInfo& track);
[[nodiscard]] std::string nicknameFor(uint64_t clientId) const;
// Download audio through proxy for playback
[[nodiscard]] Api::Result<std::string>
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<Void::Net::ProxyConfig>
effectiveEngineProxy(
const std::optional<Void::Net::ProxyConfig>& proxy);
// ---- state -----------------------------------------------------
// Temporary file tracking
std::set<std::string> tempFiles_;
mutable std::shared_mutex tempFilesMutex_;
// Async playlist loading (background thread owned by the loader).
std::unique_ptr<PlaylistLoader> playlistLoader_;
std::shared_ptr<NetworkClient> networkClient_;
std::shared_ptr<Api::Database> 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> youTubeClient_;
// Source-resolution chain (proxy-free first, proxied last).
std::unique_ptr<SourceRouter> router_;
std::shared_ptr<InnertubeSource> innertubeSource_;
std::shared_ptr<YandexMusicSource> yandexSource_;
std::shared_ptr<YtDlpSource> ytdlpProxied_;
Api::BotConfig config_;
std::atomic<bool> autoStartOnSubscribe_{true};
std::atomic<bool> autoplay_{false};
QueueService queue_;
std::unique_ptr<TrackCache> 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<std::string> voteSkipUids_;
uint64_t voteSkipQueueId_ = 0;
std::atomic<uint32_t> 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<bool> 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<std::string, AutoplaySeedSource>>
autoplaySeedFromHistory() const;
// Spotify/Yandex collection imports (background metadata fetch;
// enqueue itself is instant).
std::atomic<bool> importRunning_{false};
std::jthread importThread_;
std::unique_ptr<PlaybackEngine> engine_;
// HTTP CONNECT -> SOCKS5 tunnel for ffmpeg (see
// effectiveEngineProxy); only running while the configured proxy
// is SOCKS5.
std::unique_ptr<Socks5HttpBridge> ffmpegProxyBridge_;
std::unique_ptr<SubscriptionService> subscriptions_;
// Pending search results per client (for select command)
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>>
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