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

+167 -81
View File
@@ -1,39 +1,52 @@
#pragma once
#include "AudioDecoder.hpp"
#include "Database.hpp"
#include "NetworkClient.hpp"
#include "PlaylistLoader.hpp"
#include "QueueManager.hpp"
#include "RpcTypes.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 <condition_variable>
#include <filesystem>
#include <future>
#include <functional>
#include <memory>
#include <mutex>
#include <queue>
#include <random>
#include <optional>
#include <set>
#include <shared_mutex>
#include <thread>
#include <span>
#include <string>
#include <unordered_map>
#include <vector>
namespace Echoion::Core
{
class MusicManager
// 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();
~MusicManager() override;
Api::Result<void>
initialize(std::shared_ptr<NetworkClient> networkClient,
@@ -53,7 +66,7 @@ namespace Echoion::Core
// Re-apply network settings (proxy) to every outbound client:
// the HTTP NetworkClient (YouTube Data API, URL shortener), the
// yt-dlp subprocess, and the ffmpeg AudioDecoder. Call after a
// 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);
@@ -63,6 +76,20 @@ namespace Echoion::Core
// 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);
// 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();
@@ -106,8 +133,12 @@ namespace Echoion::Core
getPlaybackState() const;
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
// Which catalog(s) a text search targets.
enum class SearchScope { All, YouTube, Yandex };
[[nodiscard]] Api::Result<Api::SearchResult>
search(const std::string& query);
search(const std::string& query,
SearchScope scope = SearchScope::All);
// Search result selection (client-specific)
void storePendingSearch(uint64_t clientId,
@@ -119,6 +150,14 @@ namespace Echoion::Core
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();
}
// Help command
[[nodiscard]] std::string getHelpText() const;
@@ -179,11 +218,72 @@ namespace Echoion::Core
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;
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)
{
@@ -192,115 +292,101 @@ namespace Echoion::Core
}
}
void playbackThread();
// 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);
void onTrackFinished();
[[nodiscard]] Api::TrackInfo getNextTrack();
// Generate silence/sine wave to keep audio stream alive during
// transitions
void generateTransitionAudio(std::chrono::milliseconds duration);
void sendSilenceChunk();
static constexpr auto TRANSITION_SILENCE_DURATION =
std::chrono::milliseconds(100);
static constexpr auto TRANSITION_FADE_DURATION =
std::chrono::milliseconds(50);
[[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);
// Prefetch next track for seamless transitions
void prefetchNextTrack();
[[nodiscard]] bool shouldPrefetch() const;
static constexpr auto PREFETCH_THRESHOLD =
std::chrono::seconds(15); // Start prefetch 15s before end
// True when a SOCKS5 proxy is configured: ffmpeg cannot route
// IP-locked googlevideo URLs through it, so those are downloaded.
[[nodiscard]] bool socksProxyActive() const;
// ---- state -----------------------------------------------------
// Temporary file tracking
std::set<std::string> tempFiles_;
mutable std::shared_mutex tempFilesMutex_;
// Prefetch state for seamless playback
struct PrefetchState {
std::future<Api::Result<std::string>> streamUrlFuture;
std::atomic<bool> isPrefetching{false};
std::atomic<bool> hasPrefetched{false};
std::optional<std::string> prefetchedUrl;
} prefetchState_;
// Async playlist loading (background thread owned by the loader).
std::unique_ptr<PlaylistLoader> playlistLoader_;
// Auto-start thread: pokes the playback loop when a playlist's
// first track lands. Owned here because it touches the audio loop.
std::thread playlistAutoStartThread_;
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::unique_ptr<YouTubeClient> youTubeClient_;
std::unique_ptr<AudioDecoder> audioDecoder_;
std::unique_ptr<SubscriptionManager> subscriptionManager_;
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_;
// Playback queue + shuffle state (driven under mutex_).
QueueManager queueMgr_;
std::optional<Api::QueueEntry> currentTrack_;
std::atomic<bool> isPlaying_{false};
std::atomic<bool> isPaused_{false};
std::atomic<bool> wasPausedForNoSubscribers_{
false}; // Track if we auto-paused
std::atomic<bool> autoStartOnSubscribe_{true};
std::atomic<bool> autoplay_{false};
QueueService queue_;
std::unique_ptr<TrackCache> trackCache_;
// Accurate playback position tracking
std::chrono::milliseconds playbackPosition_{0}; // Current position
std::chrono::steady_clock::time_point
playbackStartTime_; // When current segment started
std::chrono::milliseconds playbackBasePosition_{
0}; // Position at start of current segment
std::atomic<float> volume_{0.5f};
std::atomic<bool> shuffle_{false};
std::atomic<bool> repeat_{false};
// 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_;
void rebuildShuffledIndices();
void reshuffleRemaining();
// 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;
std::jthread playbackThread_;
mutable std::shared_mutex mutex_;
std::condition_variable_any cv_;
std::atomic<bool> playbackThreadRunning_{
false}; // True while thread is actively running
// Spotify/Yandex collection imports (background metadata fetch;
// enqueue itself is instant).
std::atomic<bool> importRunning_{false};
std::jthread importThread_;
std::unique_ptr<PlaybackEngine> engine_;
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_;
SubscriptionChangeCallback subscriptionChangeCallback_;
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_;
NicknameCallback nicknameCallback_;
// Position tracking for periodic event updates
std::chrono::steady_clock::time_point lastPositionUpdate_{};
static constexpr auto POSITION_UPDATE_INTERVAL =
std::chrono::seconds(1);
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
static constexpr size_t AUDIO_BUFFER_SIZE =
7680; // 20ms @ 192kHz stereo
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
};
} // namespace Echoion::Core