Two gaps let network calls escape the configured proxy: 1. NetworkClient::executeRequest read proxy_ without holding mutex_, while setProxy()/initialize() write it from other threads (init, config reload). A torn read of optional<ProxyConfig> (it holds std::string host/user/pass) could yield an empty host -> enabled()==false -> a silent DIRECT connection. yt-dlp/ffmpeg snapshot their proxy under their own mutexes, so only the HTTP path (YouTube Data API, URL shortener) was affected — matching the observed "YouTube API without proxy". Snapshot proxy_ under the lock. 2. Core::reloadConfig updated only the config copy + command manager; it never re-applied the proxy to the network stack, so editing the proxy and running !reloadconfig left every client on the old/no proxy. Add MusicManager::applyNetworkConfig() to push the proxy to the NetworkClient, the yt-dlp subprocess, and the ffmpeg AudioDecoder at once, and call it from both reloadConfig and updateConfig (which previously touched only the HTTP client). reloadConfig now also syncs the shared ConfigManager. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
302 lines
11 KiB
C++
302 lines
11 KiB
C++
#pragma once
|
|
|
|
#include "AudioDecoder.hpp"
|
|
#include "Database.hpp"
|
|
#include "NetworkClient.hpp"
|
|
#include "PlaylistLoader.hpp"
|
|
#include "QueueManager.hpp"
|
|
#include "RpcTypes.hpp"
|
|
#include "SubscriptionManager.hpp"
|
|
#include "YouTubeClient.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 <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; }
|
|
|
|
// 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 AudioDecoder. 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);
|
|
|
|
[[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 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;
|
|
|
|
[[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();
|
|
// Auto-start the playback loop when a playlist's first track lands.
|
|
void requestPlaybackStart();
|
|
[[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 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
|
|
|
|
// 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_;
|
|
// 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_;
|
|
|
|
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
|
|
|
|
// 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};
|
|
|
|
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_;
|
|
|
|
// 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
|