Core holds a Void::EventBus::EventBus (Async), provides it as a service, and runs its 18 event subscriptions against it directly (setupEventBusSubscriptions is no longer const since it now mutates the owned bus). MusicManager gets the bus via setEventBus() and publishes through a small emit<T>() helper (14 former GlobalEventBus publish sites). Delete EventBus.cpp (the singleton definition). Build green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
287 lines
10 KiB
C++
287 lines
10 KiB
C++
#pragma once
|
|
|
|
#include "AudioDecoder.hpp"
|
|
#include "Database.hpp"
|
|
#include "NetworkClient.hpp"
|
|
#include "RpcTypes.hpp"
|
|
#include "SubscriptionManager.hpp"
|
|
#include "YouTubeClient.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 <mutex>
|
|
#include <queue>
|
|
#include <random>
|
|
#include <set>
|
|
#include <shared_mutex>
|
|
#include <thread>
|
|
#include <unordered_map>
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
|
|
class MusicManager
|
|
{
|
|
public:
|
|
|
|
MusicManager();
|
|
~MusicManager();
|
|
|
|
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; }
|
|
|
|
[[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);
|
|
|
|
[[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 playlistLoading_.load();
|
|
}
|
|
[[nodiscard]] size_t getPlaylistLoadProgress() const
|
|
{
|
|
return playlistLoadedCount_.load();
|
|
}
|
|
[[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;
|
|
|
|
[[nodiscard]] Api::Result<Api::SearchResult>
|
|
search(const std::string& query);
|
|
|
|
// 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);
|
|
|
|
// 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);
|
|
|
|
// Called when a client leaves the server
|
|
void onClientDisconnected(uint64_t clientId);
|
|
|
|
private:
|
|
|
|
// 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));
|
|
}
|
|
}
|
|
|
|
void playbackThread();
|
|
[[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);
|
|
|
|
// Download audio through proxy for playback
|
|
[[nodiscard]] Api::Result<std::string>
|
|
downloadAudioForPlayback(const std::string& url);
|
|
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
|
|
|
|
// 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 state
|
|
std::thread playlistLoadThread_;
|
|
std::atomic<bool> playlistLoading_{false};
|
|
std::atomic<size_t> playlistLoadedCount_{0};
|
|
std::atomic<size_t> playlistTotalCount_{0};
|
|
|
|
// Auto-start thread for playlist (must be joined, not detached)
|
|
std::thread playlistAutoStartThread_;
|
|
|
|
std::shared_ptr<NetworkClient> networkClient_;
|
|
// Non-owning application event bus (provided by Core).
|
|
Void::EventBus::EventBus* eventBus_ = nullptr;
|
|
std::unique_ptr<YouTubeClient> youTubeClient_;
|
|
std::unique_ptr<AudioDecoder> audioDecoder_;
|
|
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
|
|
|
Api::BotConfig config_;
|
|
std::vector<Api::QueueEntry> queue_;
|
|
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
|
|
|
|
// 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};
|
|
uint64_t nextQueueId_ = 1;
|
|
|
|
// Shuffle state - maintains shuffled order of queue indices
|
|
std::vector<size_t> shuffledIndices_;
|
|
size_t shuffleIndex_ = 0;
|
|
void rebuildShuffledIndices();
|
|
void reshuffleRemaining();
|
|
|
|
std::jthread playbackThread_;
|
|
mutable std::shared_mutex mutex_;
|
|
std::condition_variable_any cv_;
|
|
std::atomic<bool> playbackThreadRunning_{
|
|
false}; // True while thread is actively running
|
|
|
|
// Pending search results per client (for select command)
|
|
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>>
|
|
pendingSearches_;
|
|
mutable std::mutex pendingSearchMutex_;
|
|
|
|
AudioDataCallback audioCallback_;
|
|
SubscriptionChangeCallback subscriptionChangeCallback_;
|
|
PlaybackStartCallback playbackStartCallback_;
|
|
ClientInfoCallback clientInfoCallback_;
|
|
UidToClientIdCallback uidToClientIdCallback_;
|
|
NicknameCallback nicknameCallback_;
|
|
std::mt19937 rng_{std::random_device{}()};
|
|
|
|
// 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
|