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>
2370 lines
72 KiB
C++
2370 lines
72 KiB
C++
#include "ConfigManager.hpp"
|
|
#include <Void/Log/Log.hpp>
|
|
#include "echoion/core/MusicManager.hpp"
|
|
#include "echoion/core/PlaylistLoader.hpp"
|
|
#include <Events.hpp>
|
|
#include <algorithm>
|
|
#include <execution>
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <fstream>
|
|
#include <optional>
|
|
#include <thread>
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
|
|
MusicManager::MusicManager() = default;
|
|
|
|
MusicManager::~MusicManager() { shutdown(); }
|
|
|
|
Api::Result<void>
|
|
MusicManager::initialize(std::shared_ptr<NetworkClient> networkClient,
|
|
std::shared_ptr<Api::Database>
|
|
database)
|
|
{
|
|
// Get config from global ConfigManager
|
|
const auto& botConfig = configManager_->getBot();
|
|
const auto& youtubeConfig = configManager_->getYouTube();
|
|
const auto& networkConfig = configManager_->getNetwork();
|
|
|
|
config_ = botConfig;
|
|
networkClient_ = std::move(networkClient);
|
|
|
|
// NetworkClient is already initialized by Core, just update proxy if
|
|
// needed
|
|
if (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) {
|
|
networkClient_->setProxy(networkConfig.proxy);
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"NetworkClient using {} proxy: {}:{}",
|
|
(networkConfig.proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5" : "HTTP",
|
|
networkConfig.proxy->host, networkConfig.proxy->port));
|
|
}
|
|
|
|
youTubeClient_ = std::make_unique<YouTubeClient>(networkClient_);
|
|
|
|
// Playlist loading runs off the audio path: it enqueues resolved
|
|
// tracks via queueTrack and pokes the playback loop on the first one.
|
|
playlistLoader_ = std::make_unique<PlaylistLoader>(
|
|
youTubeClient_.get(), eventBus_,
|
|
[this](const Api::TrackInfo& track, uint64_t clientId) {
|
|
return queueTrack(track, clientId).has_value();
|
|
},
|
|
[this]() { requestPlaybackStart(); });
|
|
|
|
// Configure YouTube cookies if provided
|
|
if (youtubeConfig.youtubeCookiesPath.has_value()) {
|
|
youTubeClient_->setCookiesPath(*youtubeConfig.youtubeCookiesPath);
|
|
Void::Log::info("MusicManager", "{}", std::format("Using YouTube cookies from file: {}",
|
|
*youtubeConfig.youtubeCookiesPath));
|
|
} else if (youtubeConfig.cookiesFromBrowser.has_value()) {
|
|
youTubeClient_->setCookiesFromBrowser(
|
|
*youtubeConfig.cookiesFromBrowser);
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Using YouTube cookies from browser: {}",
|
|
*youtubeConfig.cookiesFromBrowser));
|
|
}
|
|
|
|
// Configure proxy for YouTube client
|
|
if (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) {
|
|
youTubeClient_->setProxyConfig(networkConfig.proxy);
|
|
}
|
|
|
|
// Configure YouTube API key if provided
|
|
if (youtubeConfig.youtubeApiKey.has_value() &&
|
|
!youtubeConfig.youtubeApiKey->empty()) {
|
|
youTubeClient_->setApiKey(*youtubeConfig.youtubeApiKey);
|
|
}
|
|
|
|
// Configure concurrent resolution limit
|
|
if (youtubeConfig.ytDlpMaxConcurrent > 0) {
|
|
youTubeClient_->setMaxConcurrentResolutions(
|
|
youtubeConfig.ytDlpMaxConcurrent);
|
|
}
|
|
|
|
// Configure URL shortening
|
|
youTubeClient_->setUrlShorteningEnabled(
|
|
youtubeConfig.enableUrlShortening);
|
|
|
|
auto ytResult = youTubeClient_->initialize();
|
|
if (!ytResult) {
|
|
Void::Log::warn("MusicManager", "{}",
|
|
std::format("Failed to initialize YouTube client: {}",
|
|
ytResult.error().message));
|
|
}
|
|
|
|
audioDecoder_ = std::make_unique<AudioDecoder>();
|
|
auto decoderResult = audioDecoder_->initialize();
|
|
if (!decoderResult) {
|
|
return std::unexpected(decoderResult.error());
|
|
}
|
|
|
|
audioDecoder_->setOutputFormat(TEAMSPEAK_SAMPLE_RATE,
|
|
TEAMSPEAK_CHANNELS);
|
|
|
|
// Set proxy config from NetworkConfig if enabled
|
|
if (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) {
|
|
audioDecoder_->setProxyConfig(networkConfig.proxy);
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("AudioDecoder using {} proxy: {}:{}",
|
|
(networkConfig.proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5" : "HTTP",
|
|
networkConfig.proxy->host,
|
|
networkConfig.proxy->port));
|
|
}
|
|
|
|
// Initialize subscription manager with database
|
|
subscriptionManager_ = std::make_unique<SubscriptionManager>();
|
|
auto subResult = subscriptionManager_->initialize(database);
|
|
if (!subResult) {
|
|
Void::Log::warn("MusicManager", "{}",
|
|
std::format("Failed to initialize subscription manager: {}",
|
|
subResult.error().message));
|
|
// Not fatal - continue without subscriptions
|
|
}
|
|
|
|
volume_ = botConfig.defaultVolume;
|
|
|
|
Void::Log::info("MusicManager", "{}", "MusicManager initialized");
|
|
return {};
|
|
}
|
|
|
|
void MusicManager::applyNetworkConfig(const Api::NetworkConfig& network)
|
|
{
|
|
// Push the (possibly changed) proxy to every outbound client. Passing
|
|
// the optional straight through also clears the proxy everywhere when
|
|
// it is disabled/removed in the config.
|
|
const auto& proxy = network.proxy;
|
|
const bool enabled = proxy.has_value() && proxy->enabled();
|
|
|
|
if (networkClient_) {
|
|
networkClient_->setProxy(proxy);
|
|
}
|
|
if (youTubeClient_) {
|
|
youTubeClient_->setProxyConfig(proxy);
|
|
}
|
|
if (audioDecoder_) {
|
|
audioDecoder_->setProxyConfig(proxy);
|
|
}
|
|
|
|
if (enabled) {
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"Network config re-applied: {} proxy {}:{}",
|
|
(proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5"
|
|
: "HTTP",
|
|
proxy->host, proxy->port));
|
|
} else {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Network config re-applied: proxy disabled");
|
|
}
|
|
}
|
|
|
|
void MusicManager::shutdown()
|
|
{
|
|
isPlaying_ = false;
|
|
cv_.notify_all();
|
|
|
|
if (playbackThread_.joinable()) {
|
|
playbackThread_.join();
|
|
}
|
|
|
|
// Stop playlist loading (the loader joins its background thread).
|
|
playlistLoader_.reset();
|
|
|
|
// Join auto-start thread if still running
|
|
if (playlistAutoStartThread_.joinable()) {
|
|
playlistAutoStartThread_.join();
|
|
}
|
|
|
|
if (audioDecoder_) {
|
|
audioDecoder_->shutdown();
|
|
}
|
|
|
|
// Clean up temp files
|
|
std::unique_lock<std::shared_mutex> lock(tempFilesMutex_);
|
|
for (const auto& filepath : tempFiles_) {
|
|
std::error_code ec;
|
|
std::filesystem::remove(filepath, ec);
|
|
if (!ec) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Cleaned up temp file: {}", filepath));
|
|
}
|
|
}
|
|
tempFiles_.clear();
|
|
|
|
// Also clean up any remaining files in temp directory
|
|
auto cacheDir =
|
|
std::filesystem::temp_directory_path() / "echoion_audio";
|
|
std::error_code ec;
|
|
if (std::filesystem::exists(cacheDir, ec)) {
|
|
for (const auto& entry :
|
|
std::filesystem::directory_iterator(cacheDir, ec)) {
|
|
std::filesystem::remove(entry.path(), ec);
|
|
}
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", "MusicManager shutdown");
|
|
}
|
|
|
|
Api::Result<std::string> MusicManager::play(const std::string& query,
|
|
uint64_t clientId)
|
|
{
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Play request: '{}' from client {}", query, clientId));
|
|
auto startTime = std::chrono::steady_clock::now();
|
|
|
|
// Get nickname for the client
|
|
std::string nickname = std::to_string(clientId);
|
|
if (nicknameCallback_) {
|
|
if (auto n = nicknameCallback_(clientId)) {
|
|
nickname = *n;
|
|
}
|
|
}
|
|
|
|
auto track = resolveQuery(query);
|
|
auto afterResolve = std::chrono::steady_clock::now();
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("resolveQuery took {} ms",
|
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
afterResolve - startTime)
|
|
.count()));
|
|
if (!track) {
|
|
Void::Log::error("MusicManager", "{}", std::format("Failed to resolve query '{}': {}",
|
|
query, track.error().message));
|
|
return std::unexpected(track.error());
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"Resolved track: {} - {} ({}:{}", track->title, track->artist,
|
|
track->source == Api::TrackSource::YouTube ? "YouTube" : "Unknown",
|
|
track->streamUrl.has_value() ? "direct" : "needs extraction"));
|
|
|
|
if (!isPlaying_ && !currentTrack_.has_value()) {
|
|
currentTrack_ =
|
|
Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++,
|
|
.track = *track,
|
|
.addedAt = std::chrono::system_clock::now(),
|
|
.addedBy = nickname,
|
|
.isPlaying = true,
|
|
.position = std::chrono::milliseconds(0)};
|
|
|
|
Void::Log::debug("MusicManager", "{}", "Getting stream URL...");
|
|
auto streamStart = std::chrono::steady_clock::now();
|
|
auto streamUrl = getStreamUrl(*track);
|
|
Void::Log::debug("MusicManager", "{}", std::format(
|
|
"getStreamUrl took {} ms",
|
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
std::chrono::steady_clock::now() - streamStart)
|
|
.count()));
|
|
if (!streamUrl) {
|
|
Void::Log::error("MusicManager", "{}", std::format("Failed to get stream URL: {}",
|
|
streamUrl.error().message));
|
|
currentTrack_.reset();
|
|
return std::unexpected(streamUrl.error());
|
|
}
|
|
|
|
Void::Log::debug("MusicManager", "{}", "Opening audio source...");
|
|
|
|
const auto& networkConfig = configManager_->getNetwork();
|
|
const bool socks5Proxy =
|
|
networkConfig.proxy.has_value() &&
|
|
networkConfig.proxy->enabled() &&
|
|
networkConfig.proxy->kind ==
|
|
Void::Net::ProxyConfig::Kind::Socks5;
|
|
|
|
// Download the audio via yt-dlp and open the resulting local file.
|
|
auto downloadAndOpen = [&]() -> Api::Result<void> {
|
|
auto downloadedPath =
|
|
downloadAudioForPlayback(currentTrack_->track);
|
|
if (!downloadedPath) {
|
|
Void::Log::warn(
|
|
"MusicManager", "{}",
|
|
std::format("Failed to download audio: {}",
|
|
downloadedPath.error().message));
|
|
return std::unexpected(downloadedPath.error());
|
|
}
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Downloaded audio to: {}",
|
|
*downloadedPath));
|
|
auto opened = audioDecoder_->openSource(*downloadedPath);
|
|
if (opened) {
|
|
std::unique_lock<std::shared_mutex> lock(tempFilesMutex_);
|
|
tempFiles_.insert(*downloadedPath);
|
|
}
|
|
return opened;
|
|
};
|
|
|
|
Api::Result<void> openResult;
|
|
if (socks5Proxy) {
|
|
// ffmpeg can't use a SOCKS5 proxy for the IP-locked stream URL;
|
|
// go straight to the yt-dlp download (which can).
|
|
Void::Log::info(
|
|
"MusicManager", "{}",
|
|
"SOCKS5 proxy configured: downloading audio via yt-dlp...");
|
|
openResult = downloadAndOpen();
|
|
} else {
|
|
openResult = audioDecoder_->openSource(*streamUrl);
|
|
// HTTP/no proxy: if a direct open fails but a proxy is set,
|
|
// fall back to a yt-dlp download through it.
|
|
if (!openResult && networkConfig.proxy.has_value() &&
|
|
networkConfig.proxy->enabled()) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Direct open failed, trying download via "
|
|
"yt-dlp through proxy...");
|
|
openResult = downloadAndOpen();
|
|
}
|
|
}
|
|
|
|
if (!openResult) {
|
|
Void::Log::error("MusicManager", "{}", std::format("Failed to open audio source: {}",
|
|
openResult.error().message));
|
|
currentTrack_.reset();
|
|
return std::unexpected(openResult.error());
|
|
}
|
|
|
|
isPlaying_ = true;
|
|
isPaused_ = false;
|
|
|
|
// Initialize time-based position tracking
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
|
|
// Reset prefetch state for this new track
|
|
prefetchState_.hasPrefetched = false;
|
|
prefetchState_.isPrefetching = false;
|
|
|
|
// Send initial silence to prime the audio stream and prevent
|
|
// whisper glitch This ensures the audio callback is active before
|
|
// real audio data arrives
|
|
sendSilenceChunk();
|
|
|
|
// Notify that playback is starting (updates whisper list)
|
|
if (playbackStartCallback_) {
|
|
playbackStartCallback_();
|
|
}
|
|
|
|
// Start playback thread if not running (check both joinable and
|
|
// running flag)
|
|
if (!playbackThread_.joinable() || !playbackThreadRunning_) {
|
|
// Join old thread if it exists but isn't running
|
|
if (playbackThread_.joinable()) {
|
|
Void::Log::info("MusicManager", "{}", "Joining old playback thread before "
|
|
"starting new one...");
|
|
playbackThread_.join();
|
|
}
|
|
playbackThread_ =
|
|
std::jthread(&MusicManager::playbackThread, this);
|
|
Void::Log::info("MusicManager", "{}", "Playback thread started");
|
|
}
|
|
|
|
cv_.notify_one();
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format("Now playing: {} - {}", track->title,
|
|
track->artist));
|
|
return std::format("{} - {}", track->title, track->artist);
|
|
}
|
|
|
|
Void::Log::debug("MusicManager", "{}", "Already playing, adding to queue");
|
|
auto queueId = queueTrack(*track, clientId);
|
|
if (!queueId) {
|
|
return std::unexpected(queueId.error());
|
|
}
|
|
|
|
return std::format("Added to queue: {} - {}", track->title,
|
|
track->artist);
|
|
}
|
|
|
|
Api::Result<void> MusicManager::pause()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
if (!isPlaying_ || isPaused_) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Nothing is playing");
|
|
}
|
|
|
|
// Capture current position before pausing
|
|
playbackPosition_ = getPlaybackPosition();
|
|
isPaused_ = true;
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Playback paused at {}ms", playbackPosition_.count()));
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> MusicManager::resume()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
if (!isPlaying_ || !isPaused_) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument, "Not paused");
|
|
}
|
|
|
|
// Reset time tracking from current position
|
|
playbackBasePosition_ = playbackPosition_;
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
isPaused_ = false;
|
|
bool needToStartThread = false;
|
|
if (playbackThread_.joinable() && !playbackThreadRunning_) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Joining finished playback thread before starting new one...");
|
|
playbackThread_.join();
|
|
Void::Log::info("MusicManager", "{}", "Old thread joined");
|
|
needToStartThread = true;
|
|
}
|
|
|
|
if (needToStartThread ||
|
|
(!playbackThreadRunning_ &&
|
|
(!queueMgr_.entries().empty() || currentTrack_.has_value()))) {
|
|
// Start the playback thread
|
|
isPlaying_ = true;
|
|
isPaused_ = false;
|
|
|
|
// Initialize time-based position tracking
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
|
|
// Notify that playback is starting (updates whisper list)
|
|
if (playbackStartCallback_) {
|
|
playbackStartCallback_();
|
|
}
|
|
|
|
playbackThread_ = std::jthread(&MusicManager::playbackThread, this);
|
|
Void::Log::info("MusicManager", "{}", "Started playback thread");
|
|
}
|
|
|
|
// Notify the thread to process
|
|
cv_.notify_one();
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format("Playback resumed from {}ms",
|
|
playbackPosition_.count()));
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> MusicManager::stop()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
isPlaying_ = false;
|
|
isPaused_ = false;
|
|
currentTrack_.reset();
|
|
queueMgr_.entries().clear();
|
|
|
|
if (audioDecoder_) {
|
|
audioDecoder_->closeSource();
|
|
}
|
|
|
|
cv_.notify_one();
|
|
Void::Log::info("MusicManager", "{}", "Playback stopped");
|
|
|
|
// Publish playback stopped event
|
|
emit(Api::Events::PlaybackStopped{
|
|
.lastTrack = currentTrack_ ? std::optional(currentTrack_->track)
|
|
: std::nullopt,
|
|
.finalPosition = playbackPosition_});
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> MusicManager::skip(uint32_t count)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
if (!isPlaying_) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Nothing is playing");
|
|
}
|
|
|
|
for (uint32_t i = 0; i < count; ++i) {
|
|
if (queueMgr_.entries().empty()) {
|
|
if (repeat_ && currentTrack_.has_value()) {
|
|
continue;
|
|
}
|
|
isPlaying_ = false;
|
|
currentTrack_.reset();
|
|
audioDecoder_->closeSource();
|
|
break;
|
|
}
|
|
|
|
auto nextTrack = getNextTrack();
|
|
currentTrack_ =
|
|
Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++,
|
|
.track = nextTrack,
|
|
.addedAt = std::chrono::system_clock::now(),
|
|
.addedBy = currentTrack_->addedBy,
|
|
.isPlaying = true,
|
|
.position = std::chrono::milliseconds(0)};
|
|
|
|
// Reset position tracking for new track
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
|
|
auto streamUrl = getStreamUrl(nextTrack);
|
|
if (streamUrl) {
|
|
audioDecoder_->closeSource();
|
|
auto openResult = audioDecoder_->openSource(*streamUrl);
|
|
if (!openResult) {
|
|
Void::Log::error("MusicManager", "{}", std::format("Failed to open stream: {}",
|
|
openResult.error().message));
|
|
}
|
|
}
|
|
}
|
|
|
|
cv_.notify_one();
|
|
Void::Log::info("MusicManager", "{}", std::format("Skipped {} track(s)", count));
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> MusicManager::seek(std::chrono::milliseconds position)
|
|
{
|
|
if (!isPlaying_) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Nothing is playing");
|
|
}
|
|
|
|
auto result = audioDecoder_->seek(position);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
|
|
// Update time-based tracking
|
|
playbackPosition_ = position;
|
|
playbackBasePosition_ = position;
|
|
if (!isPaused_) {
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
}
|
|
|
|
if (currentTrack_) {
|
|
currentTrack_->position = position;
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format("Seeked to {} ms", position.count()));
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> MusicManager::setVolume(float volume)
|
|
{
|
|
if (volume < 0.0f || volume > 1.0f) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Volume must be 0.0-1.0");
|
|
}
|
|
|
|
float oldVolume = volume_;
|
|
volume_ = volume;
|
|
Void::Log::info("MusicManager", "{}", std::format("Volume set to {}", volume));
|
|
|
|
// Publish volume changed event
|
|
emit(Api::Events::VolumeChanged{
|
|
.oldVolume = oldVolume,
|
|
.newVolume = volume,
|
|
.changedByClientId = 0 // Will be set by caller if available
|
|
});
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<uint64_t> MusicManager::queueTrack(const Api::TrackInfo& track,
|
|
uint64_t clientId)
|
|
{
|
|
// Validate track before adding to queue - check if we can get a stream
|
|
// URL
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Validating track before queueing: {} - {}",
|
|
track.title, track.artist));
|
|
auto streamUrl = getStreamUrl(track);
|
|
if (!streamUrl) {
|
|
Void::Log::warn("MusicManager", "{}", std::format(
|
|
"Track validation failed for '{} - {}': {}", track.title,
|
|
track.artist, streamUrl.error().message));
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
std::format("Cannot play this track: {}",
|
|
streamUrl.error().message));
|
|
}
|
|
|
|
uint64_t queueId;
|
|
bool shouldStart = false;
|
|
bool needToStartThread = false;
|
|
|
|
// Get nickname for the client
|
|
std::string nickname = std::to_string(clientId);
|
|
if (nicknameCallback_) {
|
|
if (auto n = nicknameCallback_(clientId)) {
|
|
nickname = *n;
|
|
}
|
|
}
|
|
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
if (queueMgr_.entries().size() >= config_.maxQueueSize) {
|
|
return Api::fail(
|
|
Api::ErrorCode::InvalidArgument, "Queue is full");
|
|
}
|
|
|
|
queueId = queueMgr_.nextQueueId()++;
|
|
queueMgr_.entries().push_back(
|
|
Api::QueueEntry{.queueId = queueId,
|
|
.track = track,
|
|
.addedAt = std::chrono::system_clock::now(),
|
|
.addedBy = nickname,
|
|
.isPlaying = false,
|
|
.position = std::nullopt});
|
|
|
|
// If shuffle is enabled, add the new track to shuffled indices
|
|
if (shuffle_) {
|
|
// Insert at a random position among the remaining tracks
|
|
if (queueMgr_.shuffleIndex() < queueMgr_.shuffledIndices().size()) {
|
|
std::uniform_int_distribution<size_t> dist(
|
|
queueMgr_.shuffleIndex(), queueMgr_.shuffledIndices().size());
|
|
size_t insertPos = dist(queueMgr_.rng());
|
|
queueMgr_.shuffledIndices().insert(queueMgr_.shuffledIndices().begin() +
|
|
insertPos,
|
|
queueMgr_.entries().size() - 1);
|
|
} else {
|
|
queueMgr_.shuffledIndices().push_back(queueMgr_.entries().size() - 1);
|
|
}
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Queued: {} - {}", track.title, track.artist));
|
|
|
|
// Check if we should auto-start playback
|
|
// Conditions: not playing, not paused, has ONLINE subscribers, and
|
|
// this was the first track
|
|
shouldStart = !isPlaying_ && !isPaused_ &&
|
|
!currentTrack_.has_value() &&
|
|
hasOnlineSubscribers() && queueMgr_.entries().size() > 0;
|
|
needToStartThread =
|
|
!playbackThread_.joinable() && !playbackThreadRunning_;
|
|
|
|
Void::Log::debug("MusicManager", "{}", std::format(
|
|
"queueTrack debug: shouldStart={}, "
|
|
"needToStartThread={}, isPlaying_={}, "
|
|
"thread_joinable={}, thread_running={}, queue_size={}",
|
|
shouldStart, needToStartThread, isPlaying_.load(),
|
|
playbackThread_.joinable(), playbackThreadRunning_.load(),
|
|
queueMgr_.entries().size()));
|
|
}
|
|
|
|
if (shouldStart) {
|
|
Void::Log::info("MusicManager", "{}", "Auto-starting playback for first track in queue");
|
|
|
|
// Check if we need to handle an old thread that's done but still
|
|
// joinable
|
|
if (playbackThread_.joinable() && !playbackThreadRunning_) {
|
|
Void::Log::info("MusicManager", "{}", "Joining finished playback thread before "
|
|
"starting new one...");
|
|
playbackThread_.join();
|
|
Void::Log::info("MusicManager", "{}", "Old thread joined");
|
|
needToStartThread = true;
|
|
}
|
|
|
|
if (needToStartThread) {
|
|
// Start the playback thread
|
|
isPlaying_ = true;
|
|
isPaused_ = false;
|
|
|
|
// Initialize time-based position tracking
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
|
|
// Notify that playback is starting (updates whisper list)
|
|
if (playbackStartCallback_) {
|
|
playbackStartCallback_();
|
|
}
|
|
|
|
playbackThread_ =
|
|
std::jthread(&MusicManager::playbackThread, this);
|
|
Void::Log::info("MusicManager", "{}", "Started playback thread for auto-play");
|
|
}
|
|
|
|
// Notify the thread to process
|
|
cv_.notify_one();
|
|
}
|
|
|
|
return queueId;
|
|
}
|
|
|
|
Api::Result<void> MusicManager::removeFromQueue(uint32_t position)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
if (position >= queueMgr_.entries().size()) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Invalid position");
|
|
}
|
|
|
|
auto removedTrack = queueMgr_.entries()[position];
|
|
queueMgr_.entries().erase(queueMgr_.entries().begin() + position);
|
|
|
|
// Update shuffled indices if shuffle is enabled
|
|
if (shuffle_ && !queueMgr_.shuffledIndices().empty()) {
|
|
// Remove the index from shuffledIndices
|
|
auto it = std::find(queueMgr_.shuffledIndices().begin(),
|
|
queueMgr_.shuffledIndices().end(), position);
|
|
if (it != queueMgr_.shuffledIndices().end()) {
|
|
size_t removedShuffleIndex =
|
|
std::distance(queueMgr_.shuffledIndices().begin(), it);
|
|
queueMgr_.shuffledIndices().erase(it);
|
|
// If we removed an index before the current shuffle position,
|
|
// decrement it
|
|
if (removedShuffleIndex < queueMgr_.shuffleIndex()) {
|
|
queueMgr_.shuffleIndex()--;
|
|
}
|
|
}
|
|
// Decrement indices that were after the removed position
|
|
for (auto& idx : queueMgr_.shuffledIndices()) {
|
|
if (idx > position) {
|
|
idx--;
|
|
}
|
|
}
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format("Removed track at position {}", position));
|
|
|
|
// Publish track removed event
|
|
emit(Api::Events::TrackRemoved{
|
|
.track = removedTrack.track,
|
|
.queueId = removedTrack.queueId,
|
|
.removedByClientId = 0,
|
|
.queueLength = static_cast<uint32_t>(queueMgr_.entries().size())});
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> MusicManager::clearQueue()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
uint32_t previousLength = static_cast<uint32_t>(queueMgr_.entries().size());
|
|
queueMgr_.entries().clear();
|
|
|
|
// Clear shuffle state
|
|
if (shuffle_) {
|
|
queueMgr_.shuffledIndices().clear();
|
|
queueMgr_.shuffleIndex() = 0;
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", "Queue cleared");
|
|
|
|
// Publish queue cleared event
|
|
emit(Api::Events::QueueCleared{
|
|
.clearedByClientId = 0, .previousLength = previousLength});
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<std::vector<Api::QueueEntry>> MusicManager::getQueue() const
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
return queueMgr_.entries();
|
|
}
|
|
|
|
Api::Result<void> MusicManager::moveInQueue(uint32_t from, uint32_t to)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
if (from >= queueMgr_.entries().size() || to >= queueMgr_.entries().size()) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Invalid position");
|
|
}
|
|
|
|
auto entry = queueMgr_.entries()[from];
|
|
queueMgr_.entries().erase(queueMgr_.entries().begin() + from);
|
|
queueMgr_.entries().insert(queueMgr_.entries().begin() + to, entry);
|
|
|
|
// Update shuffled indices if shuffle is enabled
|
|
if (shuffle_ && !queueMgr_.shuffledIndices().empty()) {
|
|
// Find and update indices that are affected by the move
|
|
for (auto& idx : queueMgr_.shuffledIndices()) {
|
|
if (from < to) {
|
|
// Moving forward: indices in (from, to] decrement
|
|
if (idx > from && idx <= to) {
|
|
idx--;
|
|
} else if (idx == from) {
|
|
idx = to;
|
|
}
|
|
} else if (from > to) {
|
|
// Moving backward: indices in [to, from) increment
|
|
if (idx >= to && idx < from) {
|
|
idx++;
|
|
} else if (idx == from) {
|
|
idx = to;
|
|
}
|
|
}
|
|
// If from == to, nothing changes
|
|
}
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format("Moved track from {} to {}", from, to));
|
|
|
|
// Publish queue reordered event
|
|
emit(
|
|
Api::Events::QueueReordered{.queueId = entry.queueId,
|
|
.oldPosition = from,
|
|
.newPosition = to,
|
|
.changedByClientId = 0});
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<bool> MusicManager::toggleShuffle()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
shuffle_ = !shuffle_;
|
|
|
|
if (shuffle_) {
|
|
// Build shuffled indices for current queue
|
|
rebuildShuffledIndices();
|
|
queueMgr_.shuffleIndex() = 0;
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Shuffle enabled - queue shuffled with {} tracks",
|
|
queueMgr_.shuffledIndices().size()));
|
|
} else {
|
|
// Clear shuffle state
|
|
queueMgr_.shuffledIndices().clear();
|
|
queueMgr_.shuffleIndex() = 0;
|
|
Void::Log::info("MusicManager", "{}", "Shuffle disabled");
|
|
}
|
|
|
|
// Publish shuffle changed event
|
|
emit(Api::Events::ShuffleChanged{
|
|
.enabled = shuffle_, .changedByClientId = 0});
|
|
|
|
return shuffle_;
|
|
}
|
|
|
|
void MusicManager::rebuildShuffledIndices()
|
|
{
|
|
queueMgr_.shuffledIndices().clear();
|
|
queueMgr_.shuffledIndices().reserve(queueMgr_.entries().size());
|
|
|
|
// Create indices 0 to queue_size-1
|
|
for (size_t i = 0; i < queueMgr_.entries().size(); ++i) {
|
|
queueMgr_.shuffledIndices().push_back(i);
|
|
}
|
|
|
|
// Shuffle the indices using Fisher-Yates algorithm
|
|
std::shuffle(queueMgr_.shuffledIndices().begin(), queueMgr_.shuffledIndices().end(), queueMgr_.rng());
|
|
queueMgr_.shuffleIndex() = 0;
|
|
|
|
Void::Log::debug("MusicManager", "{}", std::format("Rebuilt shuffled indices: {} tracks",
|
|
queueMgr_.shuffledIndices().size()));
|
|
}
|
|
|
|
void MusicManager::reshuffleRemaining()
|
|
{
|
|
if (queueMgr_.shuffledIndices().empty() ||
|
|
queueMgr_.shuffleIndex() >= queueMgr_.shuffledIndices().size()) {
|
|
return;
|
|
}
|
|
|
|
// Only reshuffle the remaining indices (from queueMgr_.shuffleIndex() onwards)
|
|
// This preserves the already-played tracks order but reshuffles what's
|
|
// left
|
|
std::shuffle(queueMgr_.shuffledIndices().begin() + queueMgr_.shuffleIndex(),
|
|
queueMgr_.shuffledIndices().end(), queueMgr_.rng());
|
|
|
|
Void::Log::debug("MusicManager", "{}", std::format("Reshuffled remaining {} tracks",
|
|
queueMgr_.shuffledIndices().size() - queueMgr_.shuffleIndex()));
|
|
}
|
|
|
|
Api::Result<bool> MusicManager::toggleRepeat()
|
|
{
|
|
repeat_ = !repeat_;
|
|
Void::Log::info("MusicManager", "{}", repeat_ ? "Repeat enabled" : "Repeat disabled");
|
|
|
|
// Publish repeat changed event
|
|
emit(Api::Events::RepeatChanged{
|
|
.enabled = repeat_, .changedByClientId = 0});
|
|
|
|
return repeat_;
|
|
}
|
|
|
|
Api::Result<void>
|
|
MusicManager::loadPlaylist(const std::string& playlistIdOrUrl,
|
|
uint64_t clientId)
|
|
{
|
|
if (!playlistLoader_) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"Playlist loader not available");
|
|
}
|
|
return playlistLoader_->load(playlistIdOrUrl, clientId);
|
|
}
|
|
|
|
void MusicManager::requestPlaybackStart()
|
|
{
|
|
// Start playback in a background thread so streaming isn't blocked.
|
|
if (playlistAutoStartThread_.joinable()) {
|
|
playlistAutoStartThread_.join();
|
|
}
|
|
playlistAutoStartThread_ = std::thread([this]() {
|
|
// Small delay to ensure the queue is updated.
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
|
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
if (!isPlaying_ && !queueMgr_.entries().empty()) {
|
|
cv_.notify_one();
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Playback started from playlist");
|
|
}
|
|
});
|
|
}
|
|
|
|
Api::Result<std::vector<Api::PlaylistInfo>>
|
|
MusicManager::getPlaylists() const
|
|
{
|
|
return std::vector<Api::PlaylistInfo>{};
|
|
}
|
|
|
|
Api::Result<std::optional<Api::QueueEntry>>
|
|
MusicManager::getCurrentTrack() const
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
return currentTrack_;
|
|
}
|
|
|
|
std::chrono::milliseconds MusicManager::getPlaybackPosition() const
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
if (!isPlaying_) {
|
|
return std::chrono::milliseconds(0);
|
|
}
|
|
|
|
if (isPaused_) {
|
|
return playbackPosition_;
|
|
}
|
|
|
|
// Safety check: if playbackStartTime_ is not initialized, return base
|
|
// position
|
|
if (playbackStartTime_.time_since_epoch().count() == 0) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
"getPlaybackPosition: playbackStartTime_ not initialized");
|
|
return playbackBasePosition_;
|
|
}
|
|
|
|
// Calculate elapsed time since last start/resume
|
|
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
std::chrono::steady_clock::now() - playbackStartTime_);
|
|
auto position = playbackBasePosition_ + elapsed;
|
|
|
|
// Sanity check: position shouldn't be negative or more than 24 hours
|
|
if (position.count() < 0 || position.count() > 86400000) {
|
|
Void::Log::warn("MusicManager", "{}",
|
|
std::format("getPlaybackPosition: Invalid position: {}ms",
|
|
position.count()));
|
|
return std::chrono::milliseconds(0);
|
|
}
|
|
|
|
return position;
|
|
}
|
|
|
|
Api::Result<Api::PlaybackState> MusicManager::getPlaybackState() const
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
Api::PlaybackState state;
|
|
state.currentTrack = currentTrack_;
|
|
state.queue = queueMgr_.entries();
|
|
state.isPlaying = isPlaying_;
|
|
state.isPaused = isPaused_;
|
|
state.position = getPlaybackPosition();
|
|
state.volume = volume_;
|
|
state.repeat = repeat_;
|
|
state.shuffle = shuffle_;
|
|
state.lastUpdate = std::chrono::system_clock::now();
|
|
|
|
return state;
|
|
}
|
|
|
|
Api::Result<Api::SearchResult>
|
|
MusicManager::search(const std::string& query)
|
|
{
|
|
if (!youTubeClient_) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"YouTube client not available");
|
|
}
|
|
|
|
return youTubeClient_->search(query);
|
|
}
|
|
|
|
void MusicManager::storePendingSearch(
|
|
uint64_t clientId, const std::vector<Api::TrackInfo>& results)
|
|
{
|
|
std::lock_guard<std::mutex> lock(pendingSearchMutex_);
|
|
pendingSearches_[clientId] = results;
|
|
Void::Log::debug("MusicManager", "{}", std::format("Stored {} search results for client {}",
|
|
results.size(), clientId));
|
|
}
|
|
|
|
std::optional<std::vector<Api::TrackInfo>>
|
|
MusicManager::getPendingSearch(uint64_t clientId)
|
|
{
|
|
std::lock_guard<std::mutex> lock(pendingSearchMutex_);
|
|
auto it = pendingSearches_.find(clientId);
|
|
if (it != pendingSearches_.end()) {
|
|
auto results = std::move(it->second);
|
|
pendingSearches_.erase(it);
|
|
return results;
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
Api::Result<std::string>
|
|
MusicManager::selectSearchResult(uint64_t clientId, uint32_t index,
|
|
const std::string& invokerName)
|
|
{
|
|
|
|
if (index == 0) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Index must be 1 or greater");
|
|
}
|
|
|
|
auto pending = getPendingSearch(clientId);
|
|
if (!pending) {
|
|
return Api::fail(Api::ErrorCode::NotFound,
|
|
"No pending search results. Use search or play "
|
|
"commands first.");
|
|
}
|
|
|
|
if (index > pending->size()) {
|
|
return Api::fail(
|
|
Api::ErrorCode::NotFound,
|
|
std::format("Invalid selection. Only {} results available.",
|
|
pending->size()));
|
|
}
|
|
|
|
auto selected =
|
|
(*pending)[index - 1]; // Convert to 0-based (copy to modify)
|
|
selected.requestedBy = invokerName;
|
|
|
|
auto result = queueTrack(selected, clientId);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
|
|
std::string displayText = selected.title;
|
|
if (!selected.artist.empty()) {
|
|
displayText =
|
|
std::format("{} by {}", selected.title, selected.artist);
|
|
}
|
|
return std::format(
|
|
"Added to queue: [{}]({})", displayText,
|
|
selected.shortenedUrl.value_or(selected.originalUrl));
|
|
}
|
|
|
|
Api::HotReloadState MusicManager::getStateForHotReload() const
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
Api::HotReloadState state;
|
|
|
|
// Build playback state directly (don't call getPlaybackState to avoid
|
|
// double-lock)
|
|
state.playback.currentTrack = currentTrack_;
|
|
state.playback.queue = queueMgr_.entries();
|
|
state.playback.isPlaying = isPlaying_;
|
|
state.playback.isPaused = isPaused_;
|
|
// Calculate position directly using time-based tracking
|
|
if (isPlaying_ && !isPaused_) {
|
|
auto elapsed =
|
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
std::chrono::steady_clock::now() - playbackStartTime_);
|
|
state.playback.position = playbackBasePosition_ + elapsed;
|
|
} else {
|
|
state.playback.position =
|
|
isPaused_ ? playbackPosition_ : std::chrono::milliseconds(0);
|
|
}
|
|
state.playback.volume = volume_;
|
|
state.playback.repeat = repeat_;
|
|
state.playback.shuffle = shuffle_;
|
|
state.playback.lastUpdate = std::chrono::system_clock::now();
|
|
|
|
state.queue = queueMgr_.entries();
|
|
|
|
if (currentTrack_ && currentTrack_->track.streamUrl) {
|
|
state.currentStreamUrl = currentTrack_->track.streamUrl;
|
|
}
|
|
|
|
state.playbackPosition = state.playback.position;
|
|
state.config = config_;
|
|
|
|
return state;
|
|
}
|
|
|
|
Api::Result<void>
|
|
MusicManager::restoreFromHotReload(const Api::HotReloadState& state)
|
|
{
|
|
config_ = state.config;
|
|
queueMgr_.entries() = state.queue;
|
|
volume_ = state.playback.volume;
|
|
shuffle_ = state.playback.shuffle;
|
|
repeat_ = state.playback.repeat;
|
|
|
|
// Rebuild shuffle state if shuffle is enabled
|
|
if (shuffle_ && !queueMgr_.entries().empty()) {
|
|
rebuildShuffledIndices();
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("restoreFromHotReload: shouldPreservePlayback={}, "
|
|
"hasStreamUrl={}, isPlaying={}, hasCurrentTrack={}",
|
|
state.shouldPreservePlayback(),
|
|
state.currentStreamUrl.has_value(),
|
|
state.playback.isPlaying,
|
|
state.playback.currentTrack.has_value()));
|
|
|
|
if (state.shouldPreservePlayback() && state.currentStreamUrl) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Restoring playback from position {}ms",
|
|
state.playbackPosition.count()));
|
|
auto openResult =
|
|
audioDecoder_->openSource(*state.currentStreamUrl);
|
|
if (openResult) {
|
|
auto seekResult = audioDecoder_->seek(state.playbackPosition);
|
|
if (seekResult) {
|
|
currentTrack_ = state.playback.currentTrack;
|
|
isPlaying_ = true;
|
|
isPaused_ = state.playback.isPaused;
|
|
|
|
// Initialize position tracking from restored state
|
|
playbackPosition_ = state.playbackPosition;
|
|
playbackBasePosition_ = state.playbackPosition;
|
|
if (!isPaused_) {
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
}
|
|
|
|
// Start thread if not running (check both joinable and
|
|
// running flag)
|
|
if (!playbackThread_.joinable() ||
|
|
!playbackThreadRunning_) {
|
|
if (playbackThread_.joinable()) {
|
|
playbackThread_.join();
|
|
}
|
|
playbackThread_ =
|
|
std::jthread(&MusicManager::playbackThread, this);
|
|
}
|
|
|
|
cv_.notify_one();
|
|
Void::Log::info("MusicManager", "{}", "Playback restored successfully");
|
|
} else {
|
|
Void::Log::error("MusicManager", "{}",
|
|
std::format("Failed to seek to position {}ms: {}",
|
|
state.playbackPosition.count(),
|
|
seekResult.error().message));
|
|
}
|
|
} else {
|
|
Void::Log::error("MusicManager", "{}", std::format("Failed to open stream URL: {}",
|
|
openResult.error().message));
|
|
}
|
|
} else {
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Playback not restored: conditions not met "
|
|
"(isPlaying={}, hasTrack={}, hasUrl={})",
|
|
state.playback.isPlaying,
|
|
state.playback.currentTrack.has_value(),
|
|
state.currentStreamUrl.has_value()));
|
|
}
|
|
if (!currentTrack_.has_value() && !queueMgr_.entries().empty() &&
|
|
hasOnlineSubscribers()) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Playback not restored but queue has items, starting "
|
|
"thread for auto-start");
|
|
if (playbackThread_.joinable()) {
|
|
playbackThread_.join();
|
|
}
|
|
// Start the playback thread
|
|
isPlaying_ = true;
|
|
isPaused_ = false;
|
|
|
|
// Initialize time-based position tracking
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
|
|
// Notify that playback is starting (updates whisper list)
|
|
if (playbackStartCallback_) {
|
|
playbackStartCallback_();
|
|
}
|
|
|
|
if (!playbackThread_.joinable() || !playbackThreadRunning_) {
|
|
|
|
playbackThread_ =
|
|
std::jthread(&MusicManager::playbackThread, this);
|
|
}
|
|
cv_.notify_one();
|
|
} else if (state.playback.isPlaying && !queueMgr_.entries().empty()) {
|
|
isPaused_ = true;
|
|
isPlaying_ = true;
|
|
currentTrack_.reset();
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", "State restored from hot reload");
|
|
return {};
|
|
}
|
|
|
|
void MusicManager::setAudioDataCallback(const AudioDataCallback& callback)
|
|
{
|
|
audioCallback_ = callback;
|
|
}
|
|
|
|
void MusicManager::setSubscriptionChangeCallback(
|
|
const SubscriptionChangeCallback& callback)
|
|
{
|
|
subscriptionChangeCallback_ = callback;
|
|
}
|
|
|
|
void MusicManager::setPlaybackStartCallback(
|
|
const PlaybackStartCallback& callback)
|
|
{
|
|
playbackStartCallback_ = callback;
|
|
}
|
|
|
|
void MusicManager::setClientInfoCallback(const ClientInfoCallback& callback)
|
|
{
|
|
clientInfoCallback_ = callback;
|
|
}
|
|
|
|
void MusicManager::setUidToClientIdCallback(
|
|
const UidToClientIdCallback& callback)
|
|
{
|
|
uidToClientIdCallback_ = callback;
|
|
}
|
|
|
|
void MusicManager::setNicknameCallback(const NicknameCallback& callback)
|
|
{
|
|
nicknameCallback_ = callback;
|
|
}
|
|
|
|
void MusicManager::playbackThread()
|
|
{
|
|
Void::Log::debug("MusicManager", "{}", "Playback thread started");
|
|
playbackThreadRunning_ = true;
|
|
|
|
// Constants for 192kHz 20ms chunks (like reference)
|
|
constexpr int CHUNK_MS = 20;
|
|
constexpr size_t SHORTS_PER_CHUNK =
|
|
(TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000;
|
|
constexpr size_t MAX_BUFFER_SHORTS = SHORTS_PER_CHUNK * 50;
|
|
|
|
std::vector<short> localAudioBuffer;
|
|
auto next = std::chrono::steady_clock::now();
|
|
int chunksSent = 0;
|
|
|
|
while (true) {
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
|
cv_.wait(lock, [this] {
|
|
return !isPlaying_ || !isPaused_ ||
|
|
(hasOnlineSubscribers() && !queueMgr_.entries().empty() &&
|
|
!currentTrack_.has_value());
|
|
});
|
|
|
|
// Auto-start if we have ONLINE subscribers and queue but no
|
|
// current track
|
|
if (hasOnlineSubscribers() && !queueMgr_.entries().empty() &&
|
|
!currentTrack_.has_value() && !wasPausedForNoSubscribers_) {
|
|
if (!isPlaying_) {
|
|
isPlaying_ = true;
|
|
isPaused_ = false;
|
|
|
|
// Initialize time-based position tracking
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
|
|
// Notify that playback is starting (updates whisper
|
|
// list)
|
|
if (playbackStartCallback_) {
|
|
playbackStartCallback_();
|
|
}
|
|
}
|
|
// Start first track from queue
|
|
auto firstTrack = queueMgr_.entries().front();
|
|
queueMgr_.entries().erase(queueMgr_.entries().begin());
|
|
|
|
auto streamUrl = getStreamUrl(firstTrack.track);
|
|
if (streamUrl) {
|
|
currentTrack_ = Api::QueueEntry{
|
|
.queueId = firstTrack.queueId,
|
|
.track = firstTrack.track,
|
|
.addedAt = firstTrack.addedAt,
|
|
.addedBy = firstTrack.addedBy,
|
|
.isPlaying = true,
|
|
.position = std::chrono::milliseconds(0)};
|
|
|
|
lock.unlock();
|
|
|
|
// Send silence before opening source to keep audio
|
|
// stream alive
|
|
sendSilenceChunk();
|
|
|
|
auto openResult = audioDecoder_->openSource(*streamUrl);
|
|
if (!openResult) {
|
|
Void::Log::error("MusicManager", "{}",
|
|
std::format("Failed to open first track: {}",
|
|
openResult.error().message));
|
|
lock.lock();
|
|
currentTrack_.reset();
|
|
isPlaying_ = false;
|
|
continue;
|
|
}
|
|
lock.lock();
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"Auto-started playback: {} - {}",
|
|
firstTrack.track.title, firstTrack.track.artist));
|
|
}
|
|
}
|
|
|
|
if (!isPlaying_) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (isPaused_.load()) {
|
|
continue;
|
|
}
|
|
|
|
// Pull data from decoder (like reference)
|
|
if (localAudioBuffer.size() < MAX_BUFFER_SHORTS) {
|
|
std::vector<short> incomingChunk;
|
|
if (audioDecoder_->getNextChunk(incomingChunk)) {
|
|
localAudioBuffer.insert(localAudioBuffer.end(),
|
|
incomingChunk.begin(),
|
|
incomingChunk.end());
|
|
if (chunksSent == 0) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("First chunk received: {} samples",
|
|
incomingChunk.size()));
|
|
}
|
|
}
|
|
}
|
|
// Update current position periodically (every ~2 seconds)
|
|
if (chunksSent == 0 && currentTrack_.has_value()) {
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
currentTrack_->position = getPlaybackPosition();
|
|
}
|
|
// Check if we should prefetch next track for seamless transition
|
|
if (shouldPrefetch()) {
|
|
prefetchNextTrack();
|
|
}
|
|
|
|
// Note: Position is calculated on-demand via getPlaybackPosition()
|
|
// No need to periodically update currentTrack_->position
|
|
|
|
// Publish position update periodically
|
|
if (currentTrack_.has_value()) {
|
|
auto now = std::chrono::steady_clock::now();
|
|
if (now - lastPositionUpdate_ >= POSITION_UPDATE_INTERVAL) {
|
|
auto position = getPlaybackPosition();
|
|
auto streamInfo = audioDecoder_->getStreamInfo();
|
|
|
|
float progress = 0.0f;
|
|
if (streamInfo && streamInfo->duration.count() > 0) {
|
|
progress =
|
|
(static_cast<float>(position.count()) /
|
|
static_cast<float>(streamInfo->duration.count())) *
|
|
100.0f;
|
|
}
|
|
|
|
emit(
|
|
Api::Events::PlaybackPositionChanged{
|
|
.track = currentTrack_->track,
|
|
.position = position,
|
|
.duration = streamInfo
|
|
? streamInfo->duration
|
|
: std::chrono::milliseconds(0),
|
|
.progressPercent = progress});
|
|
lastPositionUpdate_ = now;
|
|
}
|
|
}
|
|
|
|
// Send audio when we have enough
|
|
if (localAudioBuffer.size() >= SHORTS_PER_CHUNK) {
|
|
// Apply volume (squared for better perception, not cubed to
|
|
// avoid over-amplification)
|
|
float volMult = std::pow(volume_.load(), 3.0f);
|
|
std::vector<short> audioChunk(SHORTS_PER_CHUNK);
|
|
|
|
// Debug: Check if audio data is valid (first chunk only)
|
|
if (chunksSent == 0) {
|
|
int nonZeroCount = 0;
|
|
int maxSample = 0;
|
|
for (size_t i = 0;
|
|
i < std::min(size_t(100), localAudioBuffer.size());
|
|
++i) {
|
|
if (localAudioBuffer[i] != 0) {
|
|
nonZeroCount++;
|
|
}
|
|
maxSample = std::max(
|
|
maxSample,
|
|
std::abs(static_cast<int>(localAudioBuffer[i])));
|
|
}
|
|
Void::Log::debug("MusicManager", "{}", std::format(
|
|
"Audio debug: volume={:.3f}, volMult={:.3f}, "
|
|
"nonZero={}/100, maxSample={}",
|
|
volume_.load(), volMult, nonZeroCount, maxSample));
|
|
}
|
|
|
|
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
|
|
// Apply volume with soft limiting to prevent clipping
|
|
int sample =
|
|
static_cast<int>(localAudioBuffer[i] * volMult);
|
|
audioChunk[i] =
|
|
static_cast<short>(std::clamp(sample, -32768, 32767));
|
|
}
|
|
|
|
localAudioBuffer.erase(localAudioBuffer.begin(),
|
|
localAudioBuffer.begin() +
|
|
SHORTS_PER_CHUNK);
|
|
|
|
// Send audio to callback
|
|
if (audioCallback_) {
|
|
audioCallback_(std::span<const short>(audioChunk.data(),
|
|
audioChunk.size()));
|
|
|
|
chunksSent++;
|
|
if (chunksSent == 1 || chunksSent % 100 == 0) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Sent {} chunks, buffer: {}",
|
|
chunksSent,
|
|
localAudioBuffer.size()));
|
|
}
|
|
} else if (chunksSent == 0) {
|
|
Void::Log::warn("MusicManager", "{}", "No audio callback set!");
|
|
}
|
|
|
|
// Precision timing (like reference)
|
|
next += std::chrono::milliseconds(CHUNK_MS);
|
|
std::this_thread::sleep_until(next);
|
|
} else {
|
|
// Buffer underrun - wait for more data
|
|
if (chunksSent == 0) {
|
|
Void::Log::debug("MusicManager", "{}", std::format("Waiting for data: {} < {}",
|
|
localAudioBuffer.size(),
|
|
SHORTS_PER_CHUNK));
|
|
}
|
|
|
|
std::vector<short> incoming;
|
|
if (audioDecoder_->getNextChunk(incoming,
|
|
true)) { // Blocking wait
|
|
localAudioBuffer.insert(localAudioBuffer.end(),
|
|
incoming.begin(), incoming.end());
|
|
continue;
|
|
}
|
|
|
|
// Check if finished
|
|
bool decoderFinished = audioDecoder_->isFinished();
|
|
|
|
if (decoderFinished) {
|
|
// Send ALL remaining data in multiple chunks if needed
|
|
// (LAST FLUSH)
|
|
size_t totalFlushed = 0;
|
|
while (!localAudioBuffer.empty()) {
|
|
size_t toSend =
|
|
std::min(localAudioBuffer.size(), SHORTS_PER_CHUNK);
|
|
totalFlushed += toSend;
|
|
|
|
float volMult = std::pow(volume_.load(), 3.0f);
|
|
|
|
std::vector<short> audioChunk(SHORTS_PER_CHUNK, 0);
|
|
|
|
// Copy actual data, rest is silence
|
|
for (size_t i = 0; i < toSend; ++i) {
|
|
// Apply volume with soft limiting
|
|
int sample =
|
|
static_cast<int>(localAudioBuffer[i] * volMult);
|
|
// Soft limiting to prevent clipping
|
|
audioChunk[i] = static_cast<short>(
|
|
std::clamp(sample, -32768, 32767));
|
|
}
|
|
|
|
if (audioCallback_) {
|
|
audioCallback_(std::span<const short>(
|
|
audioChunk.data(), audioChunk.size()));
|
|
chunksSent++;
|
|
|
|
// Small delay to let audio play
|
|
std::this_thread::sleep_for(
|
|
std::chrono::milliseconds(CHUNK_MS));
|
|
}
|
|
|
|
// Remove sent samples from buffer
|
|
localAudioBuffer.erase(localAudioBuffer.begin(),
|
|
localAudioBuffer.begin() +
|
|
toSend);
|
|
}
|
|
|
|
if (totalFlushed > 0) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
std::format("Playback finished with last flush, "
|
|
"sent {} chunks, flushed {} samples",
|
|
chunksSent, totalFlushed));
|
|
} else {
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"Playback finished, sent {} chunks", chunksSent));
|
|
}
|
|
|
|
onTrackFinished();
|
|
|
|
// Send low-level white noise during track transition to
|
|
// prevent audio glitch and keep microphone active
|
|
Void::Log::debug("MusicManager", "{}",
|
|
"Sending transition noise during track transition...");
|
|
auto transitionStart = std::chrono::steady_clock::now();
|
|
constexpr auto MAX_TRANSITION_TIME =
|
|
std::chrono::seconds(5);
|
|
|
|
// Random number generator for white noise
|
|
static std::random_device rd;
|
|
static std::mt19937 gen(rd());
|
|
// Very low amplitude noise (-60dB = ~0.001 in 16-bit range)
|
|
std::uniform_int_distribution<int> noiseDist(-20, 20);
|
|
|
|
while (std::chrono::steady_clock::now() - transitionStart <
|
|
MAX_TRANSITION_TIME) {
|
|
// Check if next track is ready
|
|
std::vector<short> incoming;
|
|
if (audioDecoder_->getNextChunk(incoming, false)) {
|
|
// Next track is ready, add to buffer and break
|
|
localAudioBuffer.insert(localAudioBuffer.end(),
|
|
incoming.begin(),
|
|
incoming.end());
|
|
Void::Log::debug("MusicManager", "{}",
|
|
"Next track ready, resuming playback");
|
|
break;
|
|
}
|
|
|
|
// Send low-level white noise to keep audio stream alive
|
|
// and microphone active (silence doesn't work)
|
|
if (audioCallback_) {
|
|
std::vector<short> noiseChunk(SHORTS_PER_CHUNK);
|
|
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
|
|
noiseChunk[i] =
|
|
static_cast<short>(noiseDist(gen));
|
|
}
|
|
audioCallback_(std::span<const short>(
|
|
noiseChunk.data(), noiseChunk.size()));
|
|
}
|
|
|
|
// Small delay to prevent busy-waiting
|
|
std::this_thread::sleep_for(
|
|
std::chrono::milliseconds(CHUNK_MS));
|
|
|
|
// Check if playback should stop
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
if (!isPlaying_) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Playback stopped during transition");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check if playback should continue (more tracks available)
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
Void::Log::debug("MusicManager", "{}", std::format(
|
|
"Playback thread: isPlaying_={}, queue_size={}, "
|
|
"currentTrack.has_value={}",
|
|
isPlaying_.load(), queueMgr_.entries().size(),
|
|
currentTrack_.has_value()));
|
|
if (!isPlaying_) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Playback thread exiting: isPlaying_ is false");
|
|
break; // Exit thread if no more tracks
|
|
}
|
|
}
|
|
|
|
// Reset for next track
|
|
chunksSent = 0;
|
|
next = std::chrono::steady_clock::now();
|
|
Void::Log::debug("MusicManager", "{}", "Continuing to next track...");
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
|
|
Void::Log::debug("MusicManager", "{}", "Playback thread exiting");
|
|
playbackThreadRunning_ = false;
|
|
}
|
|
|
|
Api::Result<Api::TrackInfo>
|
|
MusicManager::resolveQuery(const std::string& query)
|
|
{
|
|
if (YouTubeClient::isYouTubeUrl(query)) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Extracting video ID from URL: {}", query));
|
|
auto videoId = youTubeClient_->extractVideoId(query);
|
|
if (videoId) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Extracted video ID: '{}'", *videoId));
|
|
return youTubeClient_->getVideoInfo(*videoId);
|
|
} else {
|
|
Void::Log::warn("MusicManager", "{}", "Failed to extract video ID from URL");
|
|
}
|
|
|
|
auto playlistId = youTubeClient_->extractPlaylistId(query);
|
|
if (playlistId) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Extracted playlist ID: '{}'", *playlistId));
|
|
auto playlist = youTubeClient_->getPlaylist(*playlistId);
|
|
if (playlist && !playlist->tracks.empty()) {
|
|
return playlist->tracks[0];
|
|
}
|
|
}
|
|
}
|
|
|
|
auto searchResult = youTubeClient_->search(query);
|
|
if (!searchResult) {
|
|
return std::unexpected(searchResult.error());
|
|
}
|
|
|
|
if (searchResult->tracks.empty()) {
|
|
return Api::fail(Api::ErrorCode::NotFound, "No results found");
|
|
}
|
|
|
|
return searchResult->tracks[0];
|
|
}
|
|
|
|
Api::Result<std::string>
|
|
MusicManager::getStreamUrl(const Api::TrackInfo& track)
|
|
{
|
|
if (track.streamUrl) {
|
|
Void::Log::debug("MusicManager", "{}", "Using pre-resolved stream URL");
|
|
return *track.streamUrl;
|
|
}
|
|
|
|
if (track.source == Api::TrackSource::YouTube) {
|
|
auto videoId = youTubeClient_->extractVideoId(track.originalUrl);
|
|
if (videoId) {
|
|
Void::Log::debug("MusicManager", "{}", std::format(
|
|
"Extracting stream URL for YouTube video: {}", *videoId));
|
|
auto url = youTubeClient_->getStreamUrl(*videoId);
|
|
if (url) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Got stream URL: {}", url->c_str()));
|
|
} else {
|
|
Void::Log::error("MusicManager", "{}", std::format(
|
|
"Failed to get stream URL: {}", url.error().message));
|
|
}
|
|
return url;
|
|
}
|
|
Void::Log::warn("MusicManager", "{}", "Could not extract video ID from URL");
|
|
}
|
|
|
|
return Api::fail(Api::ErrorCode::NotFound, "Could not get stream URL");
|
|
}
|
|
|
|
void MusicManager::onTrackFinished()
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
// Publish track finished event
|
|
if (currentTrack_.has_value()) {
|
|
emit(Api::Events::TrackFinished{
|
|
.track = currentTrack_->track,
|
|
.autoSkipped = false,
|
|
.finalPosition = getPlaybackPosition()});
|
|
}
|
|
|
|
// Reset prefetch state for next track
|
|
prefetchState_.hasPrefetched = false;
|
|
|
|
if (repeat_ && currentTrack_.has_value()) {
|
|
auto streamUrl = getStreamUrl(currentTrack_->track);
|
|
if (streamUrl) {
|
|
audioDecoder_->closeSource();
|
|
audioDecoder_->openSource(*streamUrl);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (queueMgr_.entries().empty()) {
|
|
// Queue is empty - stop playback but keep thread running for next
|
|
// track
|
|
isPlaying_ = false;
|
|
currentTrack_.reset();
|
|
audioDecoder_->closeSource();
|
|
Void::Log::info("MusicManager", "{}", "Queue empty, playback stopped");
|
|
return;
|
|
}
|
|
|
|
// Play next track from queue
|
|
auto nextTrack = getNextTrack();
|
|
Void::Log::info("MusicManager", "{}", std::format("Playing next track: {} - {}",
|
|
nextTrack.title, nextTrack.artist));
|
|
|
|
currentTrack_ =
|
|
Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++,
|
|
.track = nextTrack,
|
|
.addedAt = std::chrono::system_clock::now(),
|
|
.addedBy = currentTrack_->addedBy,
|
|
.isPlaying = true,
|
|
.position = std::chrono::milliseconds(0)};
|
|
|
|
// Reset position tracking for new track
|
|
playbackPosition_ = std::chrono::milliseconds(0);
|
|
playbackBasePosition_ = std::chrono::milliseconds(0);
|
|
playbackStartTime_ = std::chrono::steady_clock::now();
|
|
|
|
// Try to use prefetched URL first (seamless transition)
|
|
std::optional<std::string> streamUrl;
|
|
if (prefetchState_.streamUrlFuture.valid()) {
|
|
auto status = prefetchState_.streamUrlFuture.wait_for(
|
|
std::chrono::seconds(0));
|
|
if (status == std::future_status::ready) {
|
|
auto result = prefetchState_.streamUrlFuture.get();
|
|
if (result) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Using prefetched stream URL for seamless transition");
|
|
streamUrl = *result;
|
|
}
|
|
}
|
|
}
|
|
|
|
// If prefetch not ready or failed, fetch synchronously
|
|
if (!streamUrl) {
|
|
if (prefetchState_.isPrefetching) {
|
|
Void::Log::info("MusicManager", "{}", "Waiting for prefetch to complete...");
|
|
auto result = prefetchState_.streamUrlFuture.get();
|
|
if (result) {
|
|
streamUrl = *result;
|
|
}
|
|
}
|
|
|
|
if (!streamUrl) {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
"No prefetched URL available, fetching synchronously");
|
|
auto result = getStreamUrl(nextTrack);
|
|
if (result) {
|
|
streamUrl = *result;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (streamUrl) {
|
|
audioDecoder_->closeSource();
|
|
auto result = audioDecoder_->openSource(*streamUrl);
|
|
if (!result) {
|
|
Void::Log::error("MusicManager", "{}", std::format("Failed to open next track: {}",
|
|
result.error().message));
|
|
// Remove the failed track and try next
|
|
queueMgr_.entries().erase(queueMgr_.entries().begin());
|
|
onTrackFinished();
|
|
}
|
|
} else {
|
|
Void::Log::error("MusicManager", "{}", "Failed to get stream URL for next track");
|
|
queueMgr_.entries().erase(queueMgr_.entries().begin());
|
|
onTrackFinished();
|
|
}
|
|
}
|
|
|
|
Api::TrackInfo MusicManager::getNextTrack()
|
|
{
|
|
if (queueMgr_.entries().empty()) {
|
|
return Api::TrackInfo{};
|
|
}
|
|
|
|
if (shuffle_ && !queueMgr_.shuffledIndices().empty()) {
|
|
// Use shuffled order
|
|
size_t queueIndex = queueMgr_.shuffledIndices()[queueMgr_.shuffleIndex()];
|
|
auto track = queueMgr_.entries()[queueIndex].track;
|
|
|
|
// Remove the track from queue and rebuild shuffled indices
|
|
queueMgr_.entries().erase(queueMgr_.entries().begin() + queueIndex);
|
|
queueMgr_.shuffleIndex()++;
|
|
|
|
// If we've played all tracks, rebuild for next cycle
|
|
if (queueMgr_.shuffleIndex() >= queueMgr_.shuffledIndices().size()) {
|
|
rebuildShuffledIndices();
|
|
} else {
|
|
// Rebuild indices to account for the removed track
|
|
// Decrement indices that were after the removed track
|
|
for (size_t i = queueMgr_.shuffleIndex(); i < queueMgr_.shuffledIndices().size();
|
|
++i) {
|
|
if (queueMgr_.shuffledIndices()[i] > queueIndex) {
|
|
queueMgr_.shuffledIndices()[i]--;
|
|
}
|
|
}
|
|
}
|
|
|
|
return track;
|
|
}
|
|
|
|
auto track = queueMgr_.entries().front().track;
|
|
queueMgr_.entries().erase(queueMgr_.entries().begin());
|
|
return track;
|
|
}
|
|
|
|
Api::Result<void> MusicManager::shuffleQueue()
|
|
{
|
|
std::shuffle(queueMgr_.entries().begin(), queueMgr_.entries().end(), queueMgr_.rng());
|
|
return {};
|
|
}
|
|
|
|
std::string MusicManager::getHelpText() const
|
|
{
|
|
return R"(Echoion Music Bot Commands:
|
|
!play <query> - Play a song or add to queue (supports YouTube URLs and search)
|
|
!pause - Pause playback
|
|
!resume - Resume playback
|
|
!stop - Stop playback and clear queue
|
|
!skip [n] - Skip current song (optionally skip n songs)
|
|
!queue [page] - Show current queue (optionally specify page number)
|
|
!volume <0-100> - Set volume level
|
|
!search <query> - Search for tracks
|
|
!subscribe - Subscribe to bot's audio output (whisper mode)
|
|
!unsubscribe - Unsubscribe from bot's audio output
|
|
!subscribers - List all subscribed users
|
|
!help - Show this help message
|
|
|
|
The bot only outputs audio to subscribed users. Subscribe to hear the music!
|
|
Subscriptions are persistent across server reconnects.)";
|
|
}
|
|
|
|
Api::Result<std::string> MusicManager::subscribe(uint64_t clientId)
|
|
{
|
|
if (!subscriptionManager_) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"Subscription manager not initialized");
|
|
}
|
|
|
|
// Get client info (UID and nickname) from the callback
|
|
if (!clientInfoCallback_) {
|
|
return Api::fail(Api::ErrorCode::NotInitialized,
|
|
"Client info callback not set");
|
|
}
|
|
|
|
auto clientInfo = clientInfoCallback_(clientId);
|
|
if (!clientInfo) {
|
|
return Api::fail(Api::ErrorCode::NotFound,
|
|
"Could not get client info");
|
|
}
|
|
|
|
const auto& [uid, nickname] = *clientInfo;
|
|
bool added = subscriptionManager_->subscribe(uid, nickname);
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format("Subscribe: client {} ({}), added={}",
|
|
clientId, nickname, added));
|
|
|
|
// If we have subscribers now and were paused due to no subscribers,
|
|
// resume
|
|
if (added && wasPausedForNoSubscribers_ && isPaused_) {
|
|
auto result = resume();
|
|
if (result) {
|
|
wasPausedForNoSubscribers_ = false;
|
|
}
|
|
}
|
|
|
|
// Notify about subscription change - always trigger for subscribe to
|
|
// update whisper list This ensures offline->online transitions update
|
|
// the whisper list
|
|
if (subscriptionChangeCallback_) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Subscribe: triggering subscriptionChangeCallback");
|
|
subscriptionChangeCallback_();
|
|
}
|
|
|
|
// Publish subscription event
|
|
emit(Api::Events::UserSubscribed{
|
|
.uid = uid, .nickname = nickname, .clientId = clientId});
|
|
|
|
if (added) {
|
|
return "You are now subscribed to the bot's audio output!";
|
|
} else {
|
|
return "You are still subscribed (was already in database).";
|
|
}
|
|
}
|
|
|
|
Api::Result<std::string> MusicManager::unsubscribe(uint64_t clientId)
|
|
{
|
|
if (!subscriptionManager_) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"Subscription manager not initialized");
|
|
}
|
|
|
|
// Get client UID from the callback
|
|
if (!clientInfoCallback_) {
|
|
return Api::fail(Api::ErrorCode::NotInitialized,
|
|
"Client info callback not set");
|
|
}
|
|
|
|
auto clientInfo = clientInfoCallback_(clientId);
|
|
if (!clientInfo) {
|
|
return Api::fail(Api::ErrorCode::NotFound,
|
|
"Could not get client info");
|
|
}
|
|
|
|
const auto& [uid, nickname] = *clientInfo;
|
|
bool removed = subscriptionManager_->unsubscribe(uid);
|
|
|
|
// If no online subscribers left and we're playing, pause
|
|
if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) {
|
|
Void::Log::info("MusicManager", "{}", "No online subscribers left, pausing playback");
|
|
auto result = pause();
|
|
if (result) {
|
|
wasPausedForNoSubscribers_ = true;
|
|
}
|
|
}
|
|
|
|
// Notify about subscription change
|
|
if (removed && subscriptionChangeCallback_) {
|
|
subscriptionChangeCallback_();
|
|
}
|
|
|
|
// Publish unsubscription event
|
|
if (removed) {
|
|
emit(
|
|
Api::Events::UserUnsubscribed{
|
|
.uid = uid, .nickname = nickname, .clientId = clientId});
|
|
return "You are now unsubscribed from the bot's audio output.";
|
|
} else {
|
|
return "You were not subscribed.";
|
|
}
|
|
}
|
|
|
|
Api::Result<std::string>
|
|
MusicManager::unsubscribeByUid(const std::string& uid)
|
|
{
|
|
if (!subscriptionManager_) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"Subscription manager not initialized");
|
|
}
|
|
|
|
bool removed = subscriptionManager_->unsubscribe(uid);
|
|
|
|
// If no online subscribers left and we're playing, pause
|
|
if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) {
|
|
Void::Log::info("MusicManager", "{}", "No online subscribers left, pausing playback");
|
|
auto result = pause();
|
|
if (result) {
|
|
wasPausedForNoSubscribers_ = true;
|
|
}
|
|
}
|
|
|
|
// Notify about subscription change
|
|
if (removed && subscriptionChangeCallback_) {
|
|
subscriptionChangeCallback_();
|
|
}
|
|
|
|
if (removed) {
|
|
return "Subscriber removed successfully.";
|
|
} else {
|
|
return "Subscriber not found.";
|
|
}
|
|
}
|
|
|
|
Api::Result<std::string> MusicManager::clearAllSubscriptions()
|
|
{
|
|
if (!subscriptionManager_) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"Subscription manager not initialized");
|
|
}
|
|
|
|
bool cleared = subscriptionManager_->clearAll();
|
|
|
|
// Pause playback if no subscribers
|
|
if (cleared && isPlaying_ && !isPaused_) {
|
|
Void::Log::info("MusicManager", "{}", "All subscriptions cleared, pausing playback");
|
|
auto result = pause();
|
|
if (result) {
|
|
wasPausedForNoSubscribers_ = true;
|
|
}
|
|
}
|
|
|
|
// Notify about subscription change
|
|
if (cleared && subscriptionChangeCallback_) {
|
|
subscriptionChangeCallback_();
|
|
}
|
|
|
|
if (cleared) {
|
|
return "All subscriptions cleared.";
|
|
} else {
|
|
return "Failed to clear subscriptions.";
|
|
}
|
|
}
|
|
|
|
bool MusicManager::isSubscribed(uint64_t clientId) const
|
|
{
|
|
if (!subscriptionManager_ || !clientInfoCallback_) {
|
|
return false;
|
|
}
|
|
auto clientInfo = clientInfoCallback_(clientId);
|
|
if (!clientInfo) {
|
|
return false;
|
|
}
|
|
return subscriptionManager_->isSubscribed(clientInfo->first);
|
|
}
|
|
|
|
std::set<std::string> MusicManager::getOnlineSubscriberUids() const
|
|
{
|
|
std::set<std::string> onlineUids;
|
|
if (!subscriptionManager_ || !uidToClientIdCallback_) {
|
|
return onlineUids;
|
|
}
|
|
|
|
auto allUids = subscriptionManager_->getSubscribedUids();
|
|
for (const auto& uid : allUids) {
|
|
// If we can resolve UID to a client ID, the user is online
|
|
if (uidToClientIdCallback_(uid).has_value()) {
|
|
onlineUids.insert(uid);
|
|
}
|
|
}
|
|
|
|
return onlineUids;
|
|
}
|
|
|
|
std::set<uint64_t> MusicManager::getSubscribedClients() const
|
|
{
|
|
if (!subscriptionManager_ || !uidToClientIdCallback_) {
|
|
return {};
|
|
}
|
|
|
|
// Resolve UIDs to current session client IDs
|
|
std::set<uint64_t> clientIds;
|
|
auto uids = subscriptionManager_->getSubscribedUids();
|
|
|
|
for (const auto& uid : uids) {
|
|
auto clientId = uidToClientIdCallback_(uid);
|
|
if (clientId) {
|
|
clientIds.insert(*clientId);
|
|
}
|
|
}
|
|
|
|
return clientIds;
|
|
}
|
|
|
|
std::vector<SubscriptionManager::Subscriber>
|
|
MusicManager::getSubscribers() const
|
|
{
|
|
if (!subscriptionManager_) {
|
|
return {};
|
|
}
|
|
return subscriptionManager_->getSubscribers();
|
|
}
|
|
|
|
bool MusicManager::hasSubscribers() const
|
|
{
|
|
if (!subscriptionManager_) {
|
|
return false;
|
|
}
|
|
return subscriptionManager_->hasSubscribers();
|
|
}
|
|
|
|
bool MusicManager::hasOnlineSubscribers() const
|
|
{
|
|
if (!subscriptionManager_ || !uidToClientIdCallback_) {
|
|
return false;
|
|
}
|
|
|
|
// Check if any subscribed UID can be resolved to a current client ID
|
|
auto uids = subscriptionManager_->getSubscribedUids();
|
|
for (const auto& uid : uids) {
|
|
if (uidToClientIdCallback_(uid).has_value()) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void MusicManager::onClientConnected(uint64_t clientId)
|
|
{
|
|
Void::Log::info("MusicManager", "{}", std::format("onClientConnected: client {}", clientId));
|
|
|
|
if (!subscriptionManager_ || !clientInfoCallback_) {
|
|
Void::Log::warn("MusicManager", "{}", "onClientConnected: subscriptionManager or "
|
|
"clientInfoCallback not set");
|
|
return;
|
|
}
|
|
|
|
// Get the client's UID
|
|
auto clientInfo = clientInfoCallback_(clientId);
|
|
if (!clientInfo) {
|
|
Void::Log::warn("MusicManager", "{}", std::format(
|
|
"onClientConnected: could not get client info for {}",
|
|
clientId));
|
|
return;
|
|
}
|
|
|
|
const auto& [uid, nickname] = *clientInfo;
|
|
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"onClientConnected: client {} ({}), uid={}, isSubscribed={}",
|
|
clientId, nickname, uid, subscriptionManager_->isSubscribed(uid)));
|
|
|
|
// Check if this user is subscribed (in offline subscribers)
|
|
if (subscriptionManager_->isSubscribed(uid)) {
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"Subscribed user {} ({}) connected, moving to online", nickname,
|
|
uid));
|
|
|
|
// Update their nickname in case it changed
|
|
subscriptionManager_->updateNickname(uid, nickname);
|
|
|
|
// Update whisper list to include them
|
|
if (subscriptionChangeCallback_) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"onClientConnected: triggering subscriptionChangeCallback");
|
|
subscriptionChangeCallback_();
|
|
}
|
|
|
|
// If we were paused due to no online subscribers, resume playback
|
|
if (wasPausedForNoSubscribers_ && isPlaying_ && isPaused_) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"Online subscriber returned, resuming playback");
|
|
auto result = resume();
|
|
if (result) {
|
|
wasPausedForNoSubscribers_ = false;
|
|
}
|
|
}
|
|
// If we're not playing but have tracks in queue, auto-start
|
|
else if (!isPlaying_ && !currentTrack_.has_value() &&
|
|
!queueMgr_.entries().empty()) {
|
|
Void::Log::info("MusicManager", "{}", "Online subscriber connected with tracks in "
|
|
"queue, auto-starting");
|
|
// Notify playback thread to start
|
|
cv_.notify_one();
|
|
}
|
|
}
|
|
// If not subscribed, do nothing
|
|
}
|
|
|
|
void MusicManager::onClientDisconnected(uint64_t clientId)
|
|
{
|
|
// Clean up any pending search results for this client
|
|
{
|
|
std::lock_guard<std::mutex> lock(pendingSearchMutex_);
|
|
pendingSearches_.erase(clientId);
|
|
}
|
|
|
|
if (!subscriptionManager_ || !clientInfoCallback_) {
|
|
return;
|
|
}
|
|
|
|
// Get the client's UID
|
|
auto clientInfo = clientInfoCallback_(clientId);
|
|
if (!clientInfo) {
|
|
return;
|
|
}
|
|
|
|
const auto& [uid, nickname] = *clientInfo;
|
|
|
|
// If this was a subscribed user, update whisper list
|
|
if (subscriptionManager_->isSubscribed(uid)) {
|
|
Void::Log::info("MusicManager", "{}", std::format(
|
|
"Subscribed user {} ({}) disconnected, moving to offline",
|
|
nickname, uid));
|
|
|
|
// Update whisper list to remove them
|
|
if (subscriptionChangeCallback_) {
|
|
subscriptionChangeCallback_();
|
|
}
|
|
|
|
// If no more online subscribers and we're playing, pause
|
|
if (!hasOnlineSubscribers() && isPlaying_ && !isPaused_) {
|
|
Void::Log::info("MusicManager", "{}",
|
|
"No online subscribers left, pausing playback");
|
|
auto result = pause();
|
|
if (result) {
|
|
wasPausedForNoSubscribers_ = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
Api::Result<std::string>
|
|
MusicManager::downloadAudioForPlayback(const Api::TrackInfo& track)
|
|
{
|
|
if (!youTubeClient_) {
|
|
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
|
"YouTube client not available");
|
|
}
|
|
|
|
// yt-dlp re-downloads through the configured proxy (it handles SOCKS5,
|
|
// which ffmpeg cannot) and writes the audio to disk, sidestepping both
|
|
// the IP-locked stream URL and any in-memory body limit. Re-download by
|
|
// the original video id/URL, not the (IP-locked) CDN stream URL.
|
|
const std::string idOrUrl =
|
|
!track.originalUrl.empty() ? track.originalUrl : track.id;
|
|
if (idOrUrl.empty()) {
|
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
|
"Track has no id/URL to download");
|
|
}
|
|
|
|
const auto cacheDir =
|
|
(std::filesystem::temp_directory_path() / "echoion_audio").string();
|
|
return youTubeClient_->downloadAudioToFile(idOrUrl, cacheDir);
|
|
}
|
|
|
|
void MusicManager::cleanupTempFile(const std::string& filepath)
|
|
{
|
|
std::unique_lock<std::shared_mutex> lock(tempFilesMutex_);
|
|
tempFiles_.erase(filepath);
|
|
|
|
std::error_code ec;
|
|
std::filesystem::remove(filepath, ec);
|
|
if (ec) {
|
|
Void::Log::warn("MusicManager", "{}", std::format("Failed to remove temp file {}: {}",
|
|
filepath, ec.message()));
|
|
} else {
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Cleaned up temp file: {}", filepath));
|
|
}
|
|
}
|
|
|
|
bool MusicManager::shouldPrefetch() const
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
|
|
// Don't prefetch if not playing, no current track, or queue is empty
|
|
if (!isPlaying_ || !currentTrack_.has_value() || queueMgr_.entries().empty()) {
|
|
return false;
|
|
}
|
|
|
|
// Don't prefetch if already prefetched or currently prefetching
|
|
if (prefetchState_.hasPrefetched.load() ||
|
|
prefetchState_.isPrefetching.load()) {
|
|
return false;
|
|
}
|
|
|
|
// Check if we're near the end of the current track
|
|
auto position = audioDecoder_->getPosition();
|
|
auto streamInfo = audioDecoder_->getStreamInfo();
|
|
|
|
if (!streamInfo) {
|
|
Void::Log::debug("MusicManager", "{}", "Prefetch: No stream info available");
|
|
return false;
|
|
}
|
|
|
|
// Handle short tracks: if total duration is less than prefetch
|
|
// threshold, start prefetching after we've played at least 2 seconds
|
|
// (to avoid immediate prefetch)
|
|
if (streamInfo->duration <= PREFETCH_THRESHOLD) {
|
|
bool shouldPrefetch = position >= std::chrono::seconds(2);
|
|
if (shouldPrefetch) {
|
|
Void::Log::debug("MusicManager", "{}", std::format("Prefetch: Short track ({}s), "
|
|
"position {}s - should prefetch",
|
|
streamInfo->duration.count(),
|
|
position.count()));
|
|
}
|
|
return shouldPrefetch;
|
|
}
|
|
|
|
// Normal case: Prefetch when we're within PREFETCH_THRESHOLD of the end
|
|
auto timeRemaining = streamInfo->duration - position;
|
|
bool shouldPrefetch = timeRemaining <= PREFETCH_THRESHOLD &&
|
|
timeRemaining > std::chrono::seconds(0);
|
|
|
|
// Log when we're getting close to prefetch threshold
|
|
if (timeRemaining <= std::chrono::seconds(20) &&
|
|
timeRemaining > std::chrono::seconds(0)) {
|
|
Void::Log::debug("MusicManager", "{}", std::format(
|
|
"Prefetch: Time remaining {}s, threshold {}s - {}",
|
|
std::chrono::duration_cast<std::chrono::seconds>(timeRemaining)
|
|
.count(),
|
|
PREFETCH_THRESHOLD.count(),
|
|
shouldPrefetch ? "WILL PREFETCH" : "waiting"));
|
|
}
|
|
|
|
return shouldPrefetch;
|
|
}
|
|
|
|
void MusicManager::prefetchNextTrack()
|
|
{
|
|
// Check and set prefetching flag
|
|
bool expected = false;
|
|
if (!prefetchState_.isPrefetching.compare_exchange_strong(expected,
|
|
true)) {
|
|
return; // Already prefetching
|
|
}
|
|
|
|
Void::Log::info("MusicManager", "{}", "Starting prefetch of next track stream URL");
|
|
|
|
// Get next track info (copy to avoid holding lock during async
|
|
// operation)
|
|
Api::TrackInfo nextTrack;
|
|
{
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
|
if (queueMgr_.entries().empty()) {
|
|
prefetchState_.isPrefetching = false;
|
|
return;
|
|
}
|
|
// Use shuffled order if shuffle is enabled
|
|
if (shuffle_ && !queueMgr_.shuffledIndices().empty() &&
|
|
queueMgr_.shuffleIndex() < queueMgr_.shuffledIndices().size()) {
|
|
nextTrack = queueMgr_.entries()[queueMgr_.shuffledIndices()[queueMgr_.shuffleIndex()]].track;
|
|
} else {
|
|
nextTrack = queueMgr_.entries()[0].track;
|
|
}
|
|
}
|
|
|
|
// Start async prefetch
|
|
prefetchState_.streamUrlFuture = std::async(
|
|
std::launch::async,
|
|
[this, nextTrack]() -> Api::Result<std::string> {
|
|
auto result = getStreamUrl(nextTrack);
|
|
if (result) {
|
|
Void::Log::info("MusicManager", "{}", "Prefetch completed successfully");
|
|
} else {
|
|
Void::Log::warn("MusicManager", "{}", std::format("Prefetch failed: {}",
|
|
result.error().message));
|
|
}
|
|
return result;
|
|
});
|
|
|
|
prefetchState_.hasPrefetched = true;
|
|
prefetchState_.isPrefetching = false;
|
|
}
|
|
|
|
void MusicManager::generateTransitionAudio(
|
|
std::chrono::milliseconds duration)
|
|
{
|
|
if (!audioCallback_) {
|
|
return;
|
|
}
|
|
|
|
constexpr int CHUNK_MS = 20;
|
|
constexpr size_t SHORTS_PER_CHUNK =
|
|
(TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000;
|
|
|
|
// Generate silence chunks for the specified duration
|
|
auto chunksNeeded = duration.count() / CHUNK_MS;
|
|
std::vector<short> silenceChunk(SHORTS_PER_CHUNK, 0);
|
|
|
|
Void::Log::debug("MusicManager", "{}",
|
|
std::format("Generating {}ms of transition silence ({} chunks)",
|
|
duration.count(), chunksNeeded));
|
|
|
|
for (int i = 0; i < chunksNeeded; ++i) {
|
|
audioCallback_(std::span<const short>(silenceChunk.data(),
|
|
silenceChunk.size()));
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(CHUNK_MS));
|
|
}
|
|
}
|
|
|
|
void MusicManager::sendSilenceChunk()
|
|
{
|
|
if (!audioCallback_) {
|
|
return;
|
|
}
|
|
|
|
constexpr int CHUNK_MS = 20;
|
|
constexpr size_t SHORTS_PER_CHUNK =
|
|
(TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000;
|
|
|
|
std::vector<short> silenceChunk(SHORTS_PER_CHUNK, 0);
|
|
audioCallback_(
|
|
std::span<const short>(silenceChunk.data(), silenceChunk.size()));
|
|
}
|
|
|
|
} // namespace Echoion::Core
|