Files
EchoionCore/src/MusicManager.cpp
T
faumaray 7975f2b38e update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-25 23:44:42 +03:00

2049 lines
61 KiB
C++

#include "ConfigManager.hpp"
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/PlaylistLoader.hpp"
#include "echoion/core/sources/DirectUrlSource.hpp"
#include "echoion/core/state/StateVersions.hpp"
#include <Database.hpp>
#include <Events.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <format>
#include <limits>
#include <optional>
#include <set>
#include <thread>
namespace
{
// Radio never queues a track longer than this. Long items (livestreams,
// DJ sets, hour-long mixes) show up in YouTube "mix" playlists and derail
// the station; tracks with unknown duration are still allowed so radio
// doesn't stall on missing metadata.
constexpr auto kRadioMaxTrackDuration = std::chrono::minutes(12);
} // namespace
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);
database_ = database;
// 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));
}
if (!youTubeClient_) {
youTubeClient_ = std::make_shared<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);
}
// URL shortening is configured by Core after extension services load.
auto ytResult = youTubeClient_->initialize();
if (!ytResult) {
Void::Log::warn(
"MusicManager", "{}",
std::format("Failed to initialize YouTube client: {}",
ytResult.error().message));
}
// Persistent audio cache (advanced.cache*): downloaded files are
// reused across plays and restarts instead of re-downloading.
const auto& advanced = configManager_->getAdvanced();
trackCache_ = std::make_unique<TrackCache>(TrackCache::Config{
.enabled = advanced.cacheEnabled,
.maxBytes = std::max<uint64_t>(
TrackCache::parseSize(advanced.cacheMaxSize), 64ull << 20),
.ttl = std::chrono::seconds(advanced.cacheTTL)});
// Source-resolution chain: native innertube YouTube path and
// Yandex Music first, direct audio URLs, direct yt-dlp for
// non-YouTube extractors, proxied yt-dlp as the last resort.
const auto tempDir =
(std::filesystem::temp_directory_path() / "echoion_audio").string();
innertubeSource_ = std::make_shared<InnertubeSource>(networkClient_);
yandexSource_ = std::make_shared<YandexMusicSource>(networkClient_);
auto directUrl = std::make_shared<DirectUrlSource>();
auto ytdlpDirect = std::make_shared<YtDlpSource>(
youTubeClient_, YtDlpSource::Mode::Direct, tempDir);
ytdlpProxied_ = std::make_shared<YtDlpSource>(
youTubeClient_, YtDlpSource::Mode::Proxied, tempDir);
router_ = std::make_unique<SourceRouter>();
router_->setSources({innertubeSource_, yandexSource_, directUrl,
ytdlpDirect, ytdlpProxied_});
applySourcesConfig(configManager_->getSources());
// Playback engine owns both decoders and the audio thread.
engine_ = std::make_unique<PlaybackEngine>(
static_cast<IPlaybackHost&>(*this));
auto engineResult = engine_->initialize(
(networkConfig.proxy.has_value() && networkConfig.proxy->enabled())
? effectiveEngineProxy(networkConfig.proxy)
: std::nullopt);
if (!engineResult) {
return engineResult;
}
engine_->setVolume(botConfig.defaultVolume);
engine_->setResolveGrace(botConfig.trackTimeout);
engine_->setCrossfade(botConfig.crossfade);
// Subscription service: audience bookkeeping + pause-on-empty policy.
subscriptions_ = std::make_unique<SubscriptionService>();
subscriptions_->setEventBus(eventBus_);
if (clientInfoCallback_) {
subscriptions_->setClientInfoCallback(clientInfoCallback_);
}
if (uidToClientIdCallback_) {
subscriptions_->setUidToClientIdCallback(uidToClientIdCallback_);
}
if (subscriptionChangeCallback_) {
subscriptions_->setChangeCallback(subscriptionChangeCallback_);
}
subscriptions_->setPauseResumeHooks(
[this]() {
if (!engine_ || !engine_->isPlaying() || engine_->isPaused()) {
return false;
}
engine_->pause();
emitPauseState(true);
return true;
},
[this]() {
if (!engine_ || !engine_->isPaused()) {
return false;
}
engine_->resume();
emitPauseState(false);
return true;
});
auto subResult = subscriptions_->initialize(database);
if (!subResult) {
Void::Log::warn(
"MusicManager", "{}",
std::format("Failed to initialize subscription manager: {}",
subResult.error().message));
// Not fatal - continue without subscriptions
}
// Feature toggles: policy flags may change on reload; the initial
// shuffle/repeat state is cold-start only (runtime toggles win).
const auto& features = configManager_->getFeatures();
applyFeaturesConfig(features);
queue_.setShuffle(features.shuffleMode == "random");
queue_.setRepeat(features.repeatMode != "off" &&
!features.repeatMode.empty());
// Restore a queue/mode/autoplay snapshot persisted before the last
// shutdown so a full restart resumes where it left off. Runs after the
// engine/subscriptions/config are ready; maybeAutoStart() inside is a
// no-op until a subscriber is online (onClientConnected handles that).
restoreSession();
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 (engine_) {
engine_->setProxyConfig(effectiveEngineProxy(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::applyYouTubeConfig(const Api::YouTubeConfig& youtube)
{
if (!youTubeClient_) {
return;
}
// Empty string clears the key (hasApiKey() -> false), so search falls
// back to yt-dlp.
youTubeClient_->setApiKey(youtube.youtubeApiKey.value_or(""));
if (youtube.youtubeCookiesPath.has_value()) {
youTubeClient_->setCookiesPath(*youtube.youtubeCookiesPath);
} else if (youtube.cookiesFromBrowser.has_value()) {
youTubeClient_->setCookiesFromBrowser(*youtube.cookiesFromBrowser);
}
if (youtube.ytDlpMaxConcurrent > 0) {
youTubeClient_->setMaxConcurrentResolutions(
youtube.ytDlpMaxConcurrent);
}
const bool hasKey = youtube.youtubeApiKey.has_value() &&
!youtube.youtubeApiKey->empty();
Void::Log::info("MusicManager", "{}",
std::format("YouTube config re-applied (API key: {})",
hasKey ? "set" : "none (yt-dlp)"));
}
void MusicManager::applyBotConfig(const Api::BotConfig& bot)
{
config_ = bot;
if (engine_) {
engine_->setResolveGrace(bot.trackTimeout);
engine_->setCrossfade(bot.crossfade);
}
}
void MusicManager::applyFeaturesConfig(const Api::FeaturesConfig& features)
{
autoStartOnSubscribe_ = features.autoStartOnSubscribe;
voteSkipThreshold_ = features.voteSkipThreshold;
// A runtime !autoplay toggle (persisted in kv) always wins over the
// config default, so a reload doesn't silently flip radio back.
bool autoplayPref = features.autoplay;
if (database_) {
if (auto stored = database_->getKv("autoplay.enabled")) {
autoplayPref = (*stored == "1");
}
}
autoplay_ = autoplayPref;
if (engine_) {
engine_->setNormalization(features.normalizeLoudness,
features.targetLoudnessDb);
}
if (subscriptions_) {
subscriptions_->setPolicy(features.pauseOnEmptySubscribers,
features.resumeOnSubscriberReturn);
}
if (youTubeClient_) {
youTubeClient_->setAutoUpdateEnabled(
features.enableAutoUpdateCheck);
}
Void::Log::info("MusicManager", "{}", "Features config applied");
}
void MusicManager::setAutoplay(bool enabled)
{
autoplay_ = enabled;
if (database_) {
(void)database_->setKv("autoplay.enabled", enabled ? "1" : "0");
}
Void::Log::info(
"MusicManager", "{}",
std::format("Autoplay {}", enabled ? "enabled" : "disabled"));
persistSession();
// Enabling while nothing is playing: kick an immediate refill so the
// radio starts without waiting for the next track to finish.
if (enabled && engine_ && !engine_->isPlaying()) {
onEngineIdle();
}
}
void MusicManager::maybeAutoStart()
{
if (!engine_ || !hasOnlineSubscribers()) {
return;
}
if (!queue_.empty()) {
Void::Log::info(
"MusicManager", "{}",
"maybeAutoStart: queue has tracks, starting playback");
if (playbackStartCallback_) {
playbackStartCallback_();
}
engine_->start();
} else if (autoplay_.load()) {
Void::Log::info(
"MusicManager", "{}",
"maybeAutoStart: autoplay on with empty queue, starting radio");
onEngineIdle();
}
}
void MusicManager::setShuffle(bool enabled)
{
queue_.setShuffle(enabled);
persistSession();
}
void MusicManager::setRepeat(bool enabled)
{
queue_.setRepeat(enabled);
persistSession();
}
void MusicManager::persistSession(bool includeCurrent)
{
if (!database_ || restoringSession_.load()) {
return;
}
StateV1 st;
// The currently-playing track leads the persisted list so it replays
// from the start after a restart (its live stream URL is not reusable).
if (includeCurrent) {
if (auto cur = getCurrentTrack(); cur && cur->has_value()) {
StateV1::QueueEntryState e;
e.track = cur->value().track;
e.addedBy = cur->value().addedBy;
st.queue.push_back(std::move(e));
}
}
if (auto q = getQueue()) {
for (const auto& entry : *q) {
StateV1::QueueEntryState e;
e.track = entry.track;
e.addedBy = entry.addedBy;
st.queue.push_back(std::move(e));
}
}
st.playback.shuffle = queue_.shuffleEnabled();
st.playback.repeat = queue_.repeatEnabled();
st.autoplay = autoplay_.load();
std::string json = Void::Json::serialize(Void::Json::to_json(st));
if (!json.empty()) {
(void)database_->setKv("session.state", json);
}
}
void MusicManager::restoreSession()
{
if (!database_) {
return;
}
auto stored = database_->getKv("session.state");
if (!stored || !*stored || (*stored)->empty()) {
return;
}
auto parsed = Void::Json::parse(**stored);
if (!parsed) {
return;
}
auto st = Void::Json::from_json<StateV1>(*parsed);
if (!st) {
Void::Log::warn("MusicManager", "{}",
std::format("Failed to restore session: {}",
st.error().message));
return;
}
restoringSession_ = true;
queue_.setShuffle(st->playback.shuffle);
queue_.setRepeat(st->playback.repeat);
// Autoplay is deliberately NOT taken from the session snapshot: it has
// its own authoritative kv ("autoplay.enabled") already loaded by
// applyFeaturesConfig(), so a stale snapshot can't flip radio off.
size_t restored = 0;
for (const auto& entry : st->queue) {
if (queueTrack(entry.track, 0)) {
++restored;
}
}
restoringSession_ = false;
Void::Log::info(
"MusicManager", "{}",
std::format("Restored session: {} queued track(s), shuffle={}, "
"repeat={}, autoplay={}",
restored, st->playback.shuffle, st->playback.repeat,
autoplay_.load()));
maybeAutoStart();
}
void MusicManager::applySourcesConfig(const Api::SourcesConfig& sources)
{
if (!router_) {
return;
}
router_->setOrder(sources.order);
router_->setFailureCooldown(sources.failureCooldown);
if (innertubeSource_) {
innertubeSource_->configure(sources.innertubeEnabled,
sources.innertubeRequireProxy);
}
if (yandexSource_) {
yandexSource_->configure(sources.yandexEnabled,
sources.yandexToken.value_or(""));
}
router_->setHedgeDelay(sources.hedgeDelay);
Void::Log::info("MusicManager", "{}", "Sources config applied");
}
void MusicManager::addTrackSource(std::shared_ptr<ITrackSource> source)
{
if (router_) {
router_->addSource(std::move(source));
}
}
void MusicManager::shutdown()
{
// Background fetch threads touch queue_/engine_/sources; join them
// before tearing anything down.
if (autoplayThread_.joinable()) {
autoplayThread_.join();
}
if (importThread_.joinable()) {
importThread_.join();
}
// Stop playlist loading (the loader joins its background thread).
playlistLoader_.reset();
if (engine_) {
engine_->shutdown();
}
// The ffmpeg proxy bridge outlives the engine's decoders, never the
// other way around.
ffmpegProxyBridge_.reset();
// 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");
}
// ---- playback commands ---------------------------------------------
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));
// Yandex collections dropped into !play import the whole collection
// (tracks enqueue as their metadata lands).
const bool isCollection =
(yandexSource_ && yandexSource_->canHandle(query) &&
yandexSource_->isCollectionUrl(query));
if (isCollection) {
auto import = loadPlaylist(query, clientId);
if (!import) {
return std::unexpected(import.error());
}
return std::string("Importing the collection — tracks are being "
"added to the queue...");
}
auto track = resolveQuery(query);
if (!track) {
Void::Log::error("MusicManager", "{}",
std::format("Failed to resolve query '{}': {}",
query, track.error().message));
return std::unexpected(track.error());
}
const std::string nickname = nicknameFor(clientId);
// Idle: play immediately. Resolution happens here on the command
// thread so failures surface to the user synchronously.
if (engine_ && !engine_->isPlaying() && !engine_->currentEntry()) {
Api::QueueEntry entry{.queueId = queue_.allocateQueueId(),
.track = *track,
.addedAt = std::chrono::system_clock::now(),
.addedBy = nickname,
.isPlaying = true,
.position = std::chrono::milliseconds(0)};
auto streamUrl = resolveStream(entry, false);
if (!streamUrl) {
Void::Log::error("MusicManager", "{}",
std::format("Failed to get stream URL: {}",
streamUrl.error().message));
return std::unexpected(streamUrl.error());
}
const bool isLocal = !streamUrl->starts_with("http");
engine_->playNow(std::move(entry), std::move(*streamUrl), isLocal);
// Update the whisper list before audio starts flowing.
if (playbackStartCallback_) {
playbackStartCallback_();
}
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()
{
if (!engine_ || !engine_->isPlaying() || engine_->isPaused()) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
engine_->pause();
emitPauseState(true);
Void::Log::info("MusicManager", "{}",
std::format("Playback paused at {}ms",
engine_->position().count()));
return {};
}
Api::Result<void> MusicManager::resume()
{
if (!engine_ || !engine_->isPaused()) {
return Api::fail(Api::ErrorCode::InvalidArgument, "Not paused");
}
engine_->resume();
emitPauseState(false);
if (playbackStartCallback_) {
playbackStartCallback_();
}
Void::Log::info("MusicManager", "{}",
std::format("Playback resumed from {}ms",
engine_->position().count()));
return {};
}
Api::Result<void> MusicManager::stop()
{
// Capture before stopping: the PlaybackStopped event reports which
// track was interrupted.
std::optional<Api::TrackInfo> lastTrack;
std::chrono::milliseconds finalPosition{0};
if (engine_) {
if (auto entry = engine_->currentEntry()) {
lastTrack = entry->track;
}
finalPosition = engine_->position();
engine_->stopPlayback();
}
queue_.clear();
// An explicit stop also ends radio mode: no seed, no refill.
{
std::lock_guard<std::mutex> lock(autoplaySeedMutex_);
autoplaySeedId_.clear();
}
Void::Log::info("MusicManager", "{}", "Playback stopped");
emit(Api::Events::PlaybackStopped{.lastTrack = lastTrack,
.finalPosition = finalPosition});
// The engine clears its current entry asynchronously (CmdStop is
// posted to its thread); persisting it here would resurrect the
// stopped track after a restart. An explicit stop keeps nothing.
persistSession(/*includeCurrent=*/false);
return {};
}
Api::Result<void> MusicManager::skip(uint32_t count)
{
if (!engine_ || !engine_->isPlaying()) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
// Record the abandoned track for the skip-rate stats before it's
// replaced.
if (database_) {
if (auto entry = engine_->currentEntry()) {
(void)database_->recordSkip(entry->track, 0);
}
}
engine_->skip(count);
Void::Log::info("MusicManager", "{}",
std::format("Skipped {} track(s)", count));
persistSession();
return {};
}
uint32_t MusicManager::voteSkipNeeded() const
{
if (const uint32_t configured = voteSkipThreshold_.load();
configured > 0) {
return configured;
}
const size_t online = getOnlineSubscriberUids().size();
return static_cast<uint32_t>(std::max<size_t>(1, online / 2 + 1));
}
Api::Result<MusicManager::VoteSkipStatus>
MusicManager::voteSkip(const std::string& uid)
{
if (!engine_ || !engine_->isPlaying()) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
auto entry = engine_->currentEntry();
if (!entry) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
VoteSkipStatus status;
status.needed = voteSkipNeeded();
{
std::lock_guard<std::mutex> lock(voteSkipMutex_);
if (voteSkipQueueId_ != entry->queueId) {
voteSkipUids_.clear();
voteSkipQueueId_ = entry->queueId;
}
// Second vote from the same uid retracts the first.
if (auto [it, inserted] = voteSkipUids_.insert(uid); !inserted) {
voteSkipUids_.erase(it);
}
status.voted = voteSkipUids_.contains(uid);
status.votes = static_cast<uint32_t>(voteSkipUids_.size());
if (status.votes >= status.needed) {
voteSkipUids_.clear();
status.skipped = true;
}
}
if (status.skipped) {
Void::Log::info(
"MusicManager", "{}",
std::format("Vote-skip threshold reached ({}/{}), skipping",
status.votes, status.needed));
if (auto result = skip(1); !result) {
return std::unexpected(result.error());
}
}
return status;
}
MusicManager::VoteSkipStatus
MusicManager::voteSkipStatus(const std::string& uid) const
{
VoteSkipStatus status;
status.needed = voteSkipNeeded();
if (!engine_) {
return status;
}
auto entry = engine_->currentEntry();
if (!entry) {
return status;
}
std::lock_guard<std::mutex> lock(voteSkipMutex_);
if (voteSkipQueueId_ != entry->queueId) {
return status; // stale votes for a previous track
}
status.votes = static_cast<uint32_t>(voteSkipUids_.size());
status.voted = voteSkipUids_.contains(uid);
return status;
}
Api::Result<void> MusicManager::seek(std::chrono::milliseconds position)
{
if (!engine_ || !engine_->isPlaying()) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
engine_->seekTo(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 = engine_ ? engine_->volume() : 0.0f;
if (engine_) {
engine_->setVolume(volume);
}
Void::Log::info("MusicManager", "{}",
std::format("Volume set to {}", volume));
emit(Api::Events::VolumeChanged{
.oldVolume = oldVolume,
.newVolume = volume,
.changedByClientId = 0 // Will be set by caller if available
});
return {};
}
// ---- queue commands ---------------------------------------------------
Api::Result<uint64_t> MusicManager::queueTrack(const Api::TrackInfo& track,
uint64_t clientId)
{
// No synchronous stream validation here: enqueue is instant. The
// engine resolves the stream during its prefetch window; a dead
// track surfaces at play time and the failure budget advances past
// it automatically.
auto queueId =
queue_.enqueue(track, nicknameFor(clientId), config_.maxQueueSize);
if (!queueId) {
return queueId;
}
Void::Log::info(
"MusicManager", "{}",
std::format("Queued: {} - {}", track.title, track.artist));
// Daily counters / top-requesters stats. clientId 0 is radio/system
// (autoplay refill) — automatic adds don't count as user requests.
if (database_ && clientId != 0) {
(void)database_->logQueueAddition(clientUid(clientId).value_or(""),
nicknameFor(clientId));
}
// Auto-start when idle with an online audience.
if (autoStartOnSubscribe_.load() && engine_ && !engine_->isPlaying() &&
!engine_->currentEntry() && hasOnlineSubscribers()) {
Void::Log::info("MusicManager", "{}",
"Auto-starting playback for queued track");
if (playbackStartCallback_) {
playbackStartCallback_();
}
engine_->start();
}
persistSession();
return queueId;
}
Api::Result<void> MusicManager::removeFromQueue(uint32_t position)
{
auto removed = queue_.removeAt(position);
if (!removed) {
return std::unexpected(removed.error());
}
Void::Log::info("MusicManager", "{}",
std::format("Removed track at position {}", position));
emit(Api::Events::TrackRemoved{
.track = removed->track,
.queueId = removed->queueId,
.removedByClientId = 0,
.queueLength = static_cast<uint32_t>(queue_.size())});
persistSession();
return {};
}
Api::Result<void> MusicManager::clearQueue()
{
const uint32_t previousLength = queue_.clear();
Void::Log::info("MusicManager", "{}", "Queue cleared");
emit(Api::Events::QueueCleared{.clearedByClientId = 0,
.previousLength = previousLength});
persistSession();
return {};
}
Api::Result<std::vector<Api::QueueEntry>> MusicManager::getQueue() const
{
return queue_.snapshot();
}
Api::Result<void> MusicManager::moveInQueue(uint32_t from, uint32_t to)
{
auto moved = queue_.move(from, to);
if (!moved) {
return std::unexpected(moved.error());
}
Void::Log::info("MusicManager", "{}",
std::format("Moved track from {} to {}", from, to));
emit(Api::Events::QueueReordered{.queueId = *moved,
.oldPosition = from,
.newPosition = to,
.changedByClientId = 0});
persistSession();
return {};
}
Api::Result<bool> MusicManager::toggleShuffle()
{
const bool enabled = queue_.toggleShuffle();
Void::Log::info("MusicManager", "{}",
enabled ? "Shuffle enabled" : "Shuffle disabled");
emit(Api::Events::ShuffleChanged{.enabled = enabled,
.changedByClientId = 0});
persistSession();
return enabled;
}
Api::Result<bool> MusicManager::toggleRepeat()
{
const bool enabled = queue_.toggleRepeat();
Void::Log::info("MusicManager", "{}",
enabled ? "Repeat enabled" : "Repeat disabled");
emit(Api::Events::RepeatChanged{.enabled = enabled,
.changedByClientId = 0});
persistSession();
return enabled;
}
Api::Result<void> MusicManager::shuffleQueue()
{
queue_.shuffleInPlace();
emit(Api::Events::QueueShuffled{.triggeredByClientId = 0});
persistSession();
return {};
}
// ---- playlist / state ---------------------------------------------------
Api::Result<void>
MusicManager::loadPlaylist(const std::string& playlistIdOrUrl,
uint64_t clientId)
{
if (!config_.allowPlaylistImports) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Playlist imports are disabled");
}
// Yandex collections import through the source: the metadata fetch
// runs in the background, each track enqueues instantly, and stream
// resolution happens lazily in the engine.
const bool yandexCollection =
yandexSource_ && yandexSource_->canHandle(playlistIdOrUrl) &&
yandexSource_->isCollectionUrl(playlistIdOrUrl);
if (yandexCollection) {
bool expected = false;
if (!importRunning_.compare_exchange_strong(expected, true)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"A playlist import is already running");
}
if (importThread_.joinable()) {
importThread_.join(); // previous import already finished
}
importThread_ = std::jthread([this, playlistIdOrUrl, clientId]() {
auto tracks = yandexSource_->playlistTracks(playlistIdOrUrl);
if (!tracks) {
Void::Log::warn("MusicManager", "{}",
std::format("Collection import failed: {}",
tracks.error().message));
importRunning_ = false;
return;
}
if (youTubeClient_) {
youTubeClient_->populateShortenedUrls(*tracks);
}
size_t queued = 0;
for (const auto& track : *tracks) {
if (queueTrack(track, clientId)) {
++queued;
}
}
Void::Log::info(
"MusicManager", "{}",
std::format("Imported {} track(s) from collection",
queued));
if (queued > 0 && engine_) {
engine_->start();
}
importRunning_ = false;
});
return {};
}
if (!playlistLoader_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Playlist loader not available");
}
return playlistLoader_->load(playlistIdOrUrl, clientId);
}
void MusicManager::requestPlaybackStart()
{
// The engine's Start command is idempotent and cheap: if the queue is
// still empty (streaming race) the engine just stays idle and the
// next queueTrack pokes it again — no delay thread needed.
if (autoStartOnSubscribe_.load() && engine_ && hasOnlineSubscribers()) {
if (playbackStartCallback_) {
playbackStartCallback_();
}
engine_->start();
}
}
Api::Result<std::vector<Api::PlaylistInfo>>
MusicManager::getPlaylists() const
{
if (!database_) {
return std::vector<Api::PlaylistInfo>{};
}
auto playlists = database_->getAllPlaylists();
if (!playlists) {
return std::unexpected(playlists.error());
}
std::vector<Api::PlaylistInfo> result;
result.reserve(playlists->size());
for (const auto& p : *playlists) {
Api::PlaylistInfo info;
info.id = std::to_string(p.id);
info.name = p.name;
info.description = p.description;
info.owner = std::to_string(p.createdBy);
info.tracks = p.tracks;
info.createdAt = p.createdAt;
info.updatedAt = p.updatedAt;
result.push_back(std::move(info));
}
return result;
}
Api::Result<std::optional<Api::QueueEntry>>
MusicManager::getCurrentTrack() const
{
if (!engine_) {
return std::optional<Api::QueueEntry>{};
}
auto entry = engine_->currentEntry();
if (entry) {
entry->position = engine_->position();
}
return entry;
}
std::chrono::milliseconds MusicManager::getPlaybackPosition() const
{
return engine_ ? engine_->position() : std::chrono::milliseconds(0);
}
Api::Result<Api::PlaybackState> MusicManager::getPlaybackState() const
{
Api::PlaybackState state;
state.currentTrack = engine_ ? engine_->currentEntry() : std::nullopt;
state.queue = queue_.snapshot();
state.isPlaying = engine_ && engine_->isPlaying();
state.isPaused = engine_ && engine_->isPaused();
state.position = getPlaybackPosition();
state.volume = engine_ ? engine_->volume() : 0.0f;
state.repeat = queue_.repeatEnabled();
state.shuffle = queue_.shuffleEnabled();
state.lastUpdate = std::chrono::system_clock::now();
return state;
}
Api::Result<Api::SearchResult>
MusicManager::search(const std::string& query, SearchScope scope)
{
// YouTube search goes through the router (Invidious/Piped/ytdlp);
// Yandex is called directly (its canHandle rejects text, so the
// router never routes bare queries to it).
const auto applyShortening =
[this](Api::Result<Api::SearchResult> result) {
if (result && youTubeClient_) {
youTubeClient_->populateShortenedUrls(result->tracks);
}
return result;
};
const auto youtube = [&]() -> Api::Result<Api::SearchResult> {
if (router_) {
return applyShortening(router_->search(query));
}
if (youTubeClient_) {
return applyShortening(youTubeClient_->search(query));
}
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTube search unavailable");
};
const auto yandex = [&]() -> Api::Result<Api::SearchResult> {
if (yandexSource_ && yandexSource_->isAvailable()) {
return applyShortening(yandexSource_->search(query));
}
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Yandex Music not configured");
};
const auto soundcloud = [&]() -> Api::Result<Api::SearchResult> {
if (youTubeClient_) {
return applyShortening(youTubeClient_->searchSoundCloud(query));
}
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"SoundCloud search unavailable");
};
if (scope == SearchScope::YouTube) {
return youtube();
}
if (scope == SearchScope::Yandex) {
return yandex();
}
if (scope == SearchScope::SoundCloud) {
return soundcloud();
}
// All: merge both catalogs (YouTube first). Succeed if either does.
Api::SearchResult merged;
merged.query = query;
std::optional<Api::Error> lastError;
if (auto yt = youtube()) {
for (auto& t : yt->tracks) {
merged.tracks.push_back(std::move(t));
}
} else {
lastError = yt.error();
}
if (auto ya = yandex()) {
for (auto& t : ya->tracks) {
merged.tracks.push_back(std::move(t));
}
} else if (!lastError) {
lastError = ya.error();
}
if (merged.tracks.empty() && lastError) {
return std::unexpected(*lastError);
}
merged.totalResults = static_cast<uint32_t>(merged.tracks.size());
return merged;
}
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;
if (youTubeClient_) {
youTubeClient_->populateShortenedUrl(selected);
}
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
{
Api::HotReloadState state;
state.playback = getPlaybackState().value_or(Api::PlaybackState{});
state.queue = state.playback.queue;
if (state.playback.currentTrack &&
state.playback.currentTrack->track.streamUrl) {
state.currentStreamUrl =
state.playback.currentTrack->track.streamUrl;
}
state.playbackPosition = state.playback.position;
state.config = config_;
state.autoplay = autoplay_.load();
return state;
}
Api::Result<void>
MusicManager::restoreFromHotReload(const Api::HotReloadState& state)
{
config_ = state.config;
autoplay_ = state.autoplay;
queue_.setShuffle(state.playback.shuffle);
queue_.setRepeat(state.playback.repeat);
queue_.replaceAll(state.queue);
if (engine_) {
engine_->setVolume(state.playback.volume);
}
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 (engine_ && state.shouldPreservePlayback() &&
state.currentStreamUrl && state.playback.currentTrack) {
Void::Log::info("MusicManager", "{}",
std::format("Restoring playback from position {}ms",
state.playbackPosition.count()));
engine_->restore(*state.playback.currentTrack,
*state.currentStreamUrl, state.playbackPosition,
state.playback.isPaused);
if (playbackStartCallback_) {
playbackStartCallback_();
}
} else if (engine_ && !queue_.empty() && hasOnlineSubscribers()) {
Void::Log::info(
"MusicManager", "{}",
"Playback not restored but queue has items, auto-starting");
if (playbackStartCallback_) {
playbackStartCallback_();
}
engine_->start();
} else if (engine_ && autoplay_.load() && queue_.empty() &&
hasOnlineSubscribers()) {
// Radio was on before the reload: the transient radio queue is
// gone, so kick a refill instead of sitting idle. onEngineIdle()
// self-guards and seeds from history when no session seed exists.
Void::Log::info(
"MusicManager", "{}",
"Playback not restored, autoplay on with empty queue, "
"starting radio");
onEngineIdle();
}
Void::Log::info("MusicManager", "{}", "State restored from hot reload");
return {};
}
// ---- callbacks ---------------------------------------------------------
void MusicManager::setAudioDataCallback(const AudioDataCallback& callback)
{
audioCallback_ = callback;
}
void MusicManager::setSubscriptionChangeCallback(
const SubscriptionChangeCallback& callback)
{
subscriptionChangeCallback_ = callback;
if (subscriptions_) {
subscriptions_->setChangeCallback(callback);
}
}
void MusicManager::setPlaybackStartCallback(
const PlaybackStartCallback& callback)
{
playbackStartCallback_ = callback;
}
void MusicManager::setClientInfoCallback(const ClientInfoCallback& callback)
{
clientInfoCallback_ = callback;
if (subscriptions_) {
subscriptions_->setClientInfoCallback(callback);
}
}
void MusicManager::setUidToClientIdCallback(
const UidToClientIdCallback& callback)
{
uidToClientIdCallback_ = callback;
if (subscriptions_) {
subscriptions_->setUidToClientIdCallback(callback);
}
}
void MusicManager::setNicknameCallback(const NicknameCallback& callback)
{
nicknameCallback_ = callback;
}
// ---- IPlaybackHost -------------------------------------------------
void MusicManager::emitAudio(std::span<const short> samples)
{
if (audioCallback_) {
audioCallback_(samples);
}
}
Api::Result<std::string>
MusicManager::resolveStream(const Api::QueueEntry& entry,
bool preferDownload)
{
const std::string cacheKey =
entry.track.id.empty() ? entry.track.originalUrl : entry.track.id;
// A previously downloaded copy trumps every source: instant start,
// works offline.
if (trackCache_ && !preferDownload) {
if (auto cached = trackCache_->lookup(cacheKey)) {
Void::Log::info(
"MusicManager", "{}",
std::format("Track cache hit for {}", cacheKey));
return *cached;
}
}
// yt-dlp downloads the audio to a local file through the configured
// proxy — the fallback when a served URL turns out unplayable.
const auto downloadToFile = [this, &entry,
&cacheKey]() -> Api::Result<std::string> {
auto downloaded = downloadAudioForPlayback(entry.track);
if (downloaded) {
if (trackCache_ && trackCache_->enabled()) {
// Cache-owned files persist; nothing to track.
return trackCache_->store(cacheKey, *downloaded);
}
std::unique_lock<std::shared_mutex> lock(tempFilesMutex_);
tempFiles_.insert(*downloaded);
}
return downloaded;
};
// Retry after a failed open: the served URL was bad (expired cache
// entry or dead instance). Evict the cache and download instead.
if (preferDownload) {
if (router_) {
router_->invalidate(cacheKey);
}
return downloadToFile();
}
if (router_) {
auto handle = router_->getStream(entry.track);
if (!handle) {
return std::unexpected(handle.error());
}
if (handle->isLocalFile) {
std::unique_lock<std::shared_mutex> lock(tempFilesMutex_);
tempFiles_.insert(handle->url);
}
return handle->url;
}
return getStreamUrl(entry.track);
}
std::optional<Void::Net::ProxyConfig> MusicManager::effectiveEngineProxy(
const std::optional<Void::Net::ProxyConfig>& proxy)
{
const bool socks5 = proxy.has_value() && proxy->enabled() &&
proxy->kind == Void::Net::ProxyConfig::Kind::Socks5;
if (!socks5) {
// Http/none: ffmpeg handles these natively; drop a stale bridge.
if (ffmpegProxyBridge_) {
ffmpegProxyBridge_->stop();
}
return proxy;
}
if (!ffmpegProxyBridge_) {
ffmpegProxyBridge_ = std::make_unique<Socks5HttpBridge>();
}
// Reuse a running bridge when the SOCKS5 endpoint is unchanged
// (config reloads re-apply the network section unconditionally).
const auto current = ffmpegProxyBridge_->upstream();
if (!ffmpegProxyBridge_->running() || !current ||
current->host != proxy->host || current->port != proxy->port ||
current->username != proxy->username ||
current->password != proxy->password) {
auto port = ffmpegProxyBridge_->start(*proxy);
if (!port) {
Void::Log::error(
"MusicManager", "{}",
std::format("SOCKS5 bridge failed to start ({}); ffmpeg "
"will connect directly and rely on the "
"download fallback",
port.error().message));
return proxy; // decoder skips Socks5-kind configs
}
}
Void::Net::ProxyConfig bridged;
bridged.kind = Void::Net::ProxyConfig::Kind::Http;
bridged.host = "127.0.0.1";
bridged.port = ffmpegProxyBridge_->port();
return bridged;
}
std::optional<Api::QueueEntry> MusicManager::peekNextTrack()
{
return queue_.peekNext();
}
std::optional<Api::QueueEntry>
MusicManager::takeNextTrack(uint64_t expectedQueueId)
{
return queue_.popIfNext(expectedQueueId);
}
std::optional<Api::QueueEntry> MusicManager::takeAnyNextTrack()
{
return queue_.popNext();
}
bool MusicManager::repeatEnabled() const { return queue_.repeatEnabled(); }
void MusicManager::onTrackStarted(const Api::QueueEntry& entry)
{
Void::Log::info("MusicManager", "{}",
std::format("Now playing: {} - {}", entry.track.title,
entry.track.artist));
emit(Api::Events::PlaybackStarted{.track = entry.track,
.clientId = 0,
.position =
std::chrono::milliseconds(0)});
// Rewrite the snapshot on every track transition so it always leads
// with the entry that is actually playing — this also corrects the
// snapshot skip() writes while the engine is still switching tracks.
persistSession();
}
void MusicManager::onTrackFinished(const Api::QueueEntry& entry,
std::chrono::milliseconds finalPosition)
{
// Remember the last YouTube or Yandex track as the autoplay seed;
// radio pulls related tracks from whichever catalog it came from.
if (entry.track.source == Api::TrackSource::YouTube &&
!entry.track.id.empty()) {
std::lock_guard<std::mutex> lock(autoplaySeedMutex_);
autoplaySeedId_ = entry.track.id;
autoplaySeedSource_ = AutoplaySeedSource::YouTube;
} else if (entry.track.source == Api::TrackSource::Yandex &&
entry.track.id.starts_with("yandex:")) {
std::lock_guard<std::mutex> lock(autoplaySeedMutex_);
// Store the bare provider id; related() expects it unprefixed.
autoplaySeedId_ =
entry.track.id.substr(std::string("yandex:").size());
autoplaySeedSource_ = AutoplaySeedSource::Yandex;
}
emit(Api::Events::TrackFinished{.track = entry.track,
.autoSkipped = false,
.finalPosition = finalPosition});
}
void MusicManager::onPositionTick(const Api::QueueEntry& entry,
std::chrono::milliseconds position,
std::chrono::milliseconds duration)
{
float progress = 0.0f;
if (duration.count() > 0) {
progress = (static_cast<float>(position.count()) /
static_cast<float>(duration.count())) *
100.0f;
}
emit(Api::Events::PlaybackPositionChanged{.track = entry.track,
.position = position,
.duration = duration,
.progressPercent = progress});
}
std::optional<std::pair<std::string, MusicManager::AutoplaySeedSource>>
MusicManager::autoplaySeedFromHistory() const
{
if (!database_) {
return std::nullopt;
}
// Scan history newest-first for the first track that belongs to a
// catalog we can pull related tracks from — the most recent play may
// be a direct URL / other extractor with no radio.
auto recent = database_->getRecentlyPlayed(0, 50);
if (!recent) {
return std::nullopt;
}
for (const auto& track : *recent) {
const std::string& url = track.originalUrl;
if (youTubeClient_ && YouTubeClient::isYouTubeUrl(url)) {
if (auto id = youTubeClient_->extractVideoId(url);
id && !id->empty()) {
return std::make_pair(*id, AutoplaySeedSource::YouTube);
}
}
if (yandexSource_) {
if (auto id = yandexSource_->trackIdFromUrl(url);
id && !id->empty()) {
return std::make_pair(*id, AutoplaySeedSource::Yandex);
}
}
}
return std::nullopt;
}
void MusicManager::onEngineIdle()
{
Void::Log::info("MusicManager", "{}", "Queue empty, playback stopped");
// Radio mode: refill the queue with tracks related to the last
// played one. Runs on its own thread — this callback fires on the
// engine thread and the fetch does network I/O.
if (!autoplay_.load() || !queue_.empty() || !hasOnlineSubscribers()) {
return;
}
std::string seed;
AutoplaySeedSource seedSource = AutoplaySeedSource::None;
{
std::lock_guard<std::mutex> lock(autoplaySeedMutex_);
seed = autoplaySeedId_;
seedSource = autoplaySeedSource_;
}
// Nothing played this session (or the last track wasn't a
// YouTube/Yandex track): fall back to the most recent history entry
// so radio can still start.
if (seed.empty() || seedSource == AutoplaySeedSource::None) {
if (auto fromHistory = autoplaySeedFromHistory()) {
seed = fromHistory->first;
seedSource = fromHistory->second;
}
}
// Note: no early return when there is still no seed — the fetch thread
// falls back to a random music video so radio can start from cold.
bool expected = false;
if (!autoplayFetching_.compare_exchange_strong(expected, true)) {
return; // fetch already in flight
}
if (autoplayThread_.joinable()) {
autoplayThread_.join(); // previous fetch already finished
}
autoplayThread_ = std::jthread([this, seed, seedSource]() {
// Skip anything played recently to avoid radio loops.
std::set<std::string> recentUrls;
if (database_) {
if (auto recent = database_->getRecentlyPlayed(0, 50)) {
for (const auto& t : *recent) {
recentUrls.insert(t.originalUrl);
}
}
}
// Queue tracks that are both unplayed-recently and within the
// radio duration cap. Stops once maxToQueue have been queued.
auto queueRadio = [&](const std::vector<Api::TrackInfo>& tracks,
size_t maxToQueue) -> size_t {
size_t queued = 0;
for (const auto& track : tracks) {
if (recentUrls.contains(track.originalUrl)) {
continue;
}
if (track.duration &&
*track.duration > kRadioMaxTrackDuration) {
continue;
}
if (queueTrack(track, 0)) {
if (++queued >= maxToQueue) {
break;
}
}
}
return queued;
};
size_t queued = 0;
// Related tracks come from the same catalog as the seed:
// YouTube via a yt-dlp radio mix, Yandex via its similar-tracks
// endpoint.
if (!seed.empty() && seedSource != AutoplaySeedSource::None) {
Api::Result<std::vector<Api::TrackInfo>> related =
Api::fail(Api::ErrorCode::ServiceUnavailable,
"Autoplay source unavailable");
if (seedSource == AutoplaySeedSource::Yandex) {
if (yandexSource_) {
related = yandexSource_->related(seed, 10);
}
} else if (youTubeClient_) {
related = youTubeClient_->radioMix(seed, 10);
}
if (related && !related->empty()) {
queued = queueRadio(*related,
std::numeric_limits<size_t>::max());
if (queued > 0) {
Void::Log::info(
"MusicManager", "{}",
std::format("Autoplay queued {} related track(s)",
queued));
}
}
}
// No seed, empty mix, or every related track was recently played /
// too long: fall back to a single random music video. When it
// finishes it becomes the next seed, so related-track radio
// resumes from it on the following idle.
if (queued == 0 && youTubeClient_) {
if (auto random = youTubeClient_->randomMusicVideo(15);
random && !random->empty()) {
queued = queueRadio(*random, 1);
if (queued > 0) {
Void::Log::info("MusicManager", "{}",
"Autoplay queued a random music video "
"(no unplayed related track found)");
}
}
}
if (queued > 0) {
if (engine_) {
engine_->start();
}
} else {
Void::Log::debug("MusicManager", "{}",
"Autoplay found no track to queue");
}
autoplayFetching_ = false;
});
}
void MusicManager::onPlaybackError(
const Api::Error& error, const std::optional<Api::QueueEntry>& entry)
{
emit(Api::Events::PlaybackError{
.code = error.code,
.message = error.message,
.track = entry ? std::optional(entry->track) : std::nullopt});
}
void MusicManager::emitPauseState(bool paused)
{
if (!engine_) {
return;
}
auto entry = engine_->currentEntry();
if (!entry) {
return;
}
if (paused) {
emit(Api::Events::PlaybackPaused{.track = entry->track,
.position = engine_->position()});
} else {
emit(Api::Events::PlaybackResumed{.track = entry->track,
.position = engine_->position()});
}
}
void MusicManager::onLocalFileDone(const std::string& path)
{
// Cache-owned files are the cache's to evict, not ours to delete.
if (trackCache_ && trackCache_->owns(path)) {
return;
}
cleanupTempFile(path);
}
// ---- helpers -------------------------------------------------------
std::string MusicManager::nicknameFor(uint64_t clientId) const
{
// clientId 0 is the sentinel for system/radio-added tracks (autoplay).
// TeamSpeak client IDs are >= 1, so this never collides with a real
// user and gives the queue a friendly "(by radio)" instead of "(by 0)".
if (clientId == 0) {
return "radio";
}
if (nicknameCallback_) {
if (auto n = nicknameCallback_(clientId)) {
return *n;
}
}
return std::to_string(clientId);
}
Api::Result<Api::TrackInfo>
MusicManager::resolveQuery(const std::string& query)
{
const auto finalize = [this](Api::Result<Api::TrackInfo> result) {
if (result && youTubeClient_) {
youTubeClient_->populateShortenedUrl(*result);
}
return result;
};
// Playlist URLs are still resolved through the YouTube client (the
// router's sources resolve single tracks).
if (config_.allowPlaylistImports &&
YouTubeClient::isYouTubeUrl(query) &&
!youTubeClient_->extractVideoId(query).has_value()) {
if (auto playlistId = YouTubeClient::extractPlaylistId(query)) {
Void::Log::debug(
"MusicManager", "{}",
std::format("Extracted playlist ID: '{}'", *playlistId));
auto playlist = youTubeClient_->getPlaylist(*playlistId);
if (playlist && !playlist->tracks.empty()) {
return finalize(playlist->tracks[0]);
}
}
}
if (router_) {
return finalize(router_->resolve(query));
}
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 finalize(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;
}
// Route through the source chain; this also primes the router's
// stream cache, so the engine's later resolve is instant.
if (router_) {
auto handle = router_->getStream(track);
if (!handle) {
return std::unexpected(handle.error());
}
return handle->url;
}
return Api::fail(Api::ErrorCode::NotFound, "Could not get stream URL");
}
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)
!seek <+/-secs> - Seek within the track (+30, -10, or absolute 60)
!queue [page] - Show current queue (optionally specify page number)
!volume <0-100> - Set volume level
!search <query> - Search YouTube + Yandex Music
!youtube <query> - Search YouTube only (alias: yb, yt)
!yandex <query> - Search Yandex Music only (alias: ya)
!soundcloud <query> - Search SoundCloud only (alias: sc)
!history [n] - Show recently played tracks
!stats - Show playback statistics
!fav add|list|play <n> - Manage your favorite 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.)";
}
// ---- subscriptions (delegated) --------------------------------------
Api::Result<std::string> MusicManager::subscribe(uint64_t clientId)
{
if (!subscriptions_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
auto result = subscriptions_->subscribe(clientId);
if (result) {
// A newly-listening user should hear the restored queue / radio
// without also having to !play.
maybeAutoStart();
}
return result;
}
Api::Result<std::string> MusicManager::unsubscribe(uint64_t clientId)
{
if (!subscriptions_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
return subscriptions_->unsubscribe(clientId);
}
Api::Result<std::string>
MusicManager::unsubscribeByUid(const std::string& uid)
{
if (!subscriptions_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
return subscriptions_->unsubscribeByUid(uid);
}
Api::Result<std::string> MusicManager::clearAllSubscriptions()
{
if (!subscriptions_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
return subscriptions_->clearAllSubscriptions();
}
bool MusicManager::isSubscribed(uint64_t clientId) const
{
return subscriptions_ && subscriptions_->isSubscribed(clientId);
}
std::set<std::string> MusicManager::getOnlineSubscriberUids() const
{
return subscriptions_ ? subscriptions_->getOnlineSubscriberUids()
: std::set<std::string>{};
}
std::set<uint64_t> MusicManager::getSubscribedClients() const
{
return subscriptions_ ? subscriptions_->getSubscribedClients()
: std::set<uint64_t>{};
}
std::vector<SubscriptionManager::Subscriber>
MusicManager::getSubscribers() const
{
return subscriptions_ ? subscriptions_->getSubscribers()
: std::vector<SubscriptionManager::Subscriber>{};
}
bool MusicManager::hasSubscribers() const
{
return subscriptions_ && subscriptions_->hasSubscribers();
}
bool MusicManager::hasOnlineSubscribers() const
{
return subscriptions_ && subscriptions_->hasOnlineSubscribers();
}
void MusicManager::onClientConnected(uint64_t clientId)
{
Void::Log::info("MusicManager", "{}",
std::format("onClientConnected: client {}", clientId));
if (!subscriptions_) {
return;
}
const auto connect = subscriptions_->onClientConnected(clientId);
if (connect.mayAutoStart && autoStartOnSubscribe_.load() && engine_ &&
!engine_->isPlaying() && !engine_->currentEntry() &&
!queue_.empty()) {
Void::Log::info("MusicManager", "{}",
"Online subscriber connected with tracks in queue, "
"auto-starting");
if (playbackStartCallback_) {
playbackStartCallback_();
}
engine_->start();
} else if (connect.mayAutoStart && autoplay_.load() && engine_ &&
!engine_->isPlaying() && !engine_->currentEntry() &&
queue_.empty()) {
// First subscriber back after a restart with radio enabled but an
// empty queue: kick a refill so the radio starts without needing a
// manual !play. onEngineIdle() self-guards and seeds from history.
Void::Log::info(
"MusicManager", "{}",
"Online subscriber connected, autoplay on with empty queue, "
"starting radio");
onEngineIdle();
}
// Deliver a pending announcement to this subscriber once (uid was
// already resolved by the subscription service above).
if (connect.subscribedUid) {
deliverAnnouncementTo(clientId, *connect.subscribedUid);
}
}
size_t MusicManager::setAnnouncement(const std::string& text)
{
if (!database_) {
return 0;
}
// Bump the announcement id so this fresh post reaches every
// subscriber once (the per-uid seen-id gate does the dedup).
int64_t id = 1;
if (auto stored = database_->getKv("announcement.id");
stored && *stored) {
try {
id = std::stoll(**stored) + 1;
} catch (const std::exception&) {
id = 1;
}
}
(void)database_->setKv("announcement.text", text);
(void)database_->setKv("announcement.id", std::to_string(id));
// Deliver immediately to everyone currently online.
size_t reached = 0;
if (subscriptions_) {
for (uint64_t clientId : subscriptions_->getSubscribedClients()) {
if (auto uid = clientUid(clientId)) {
if (deliverAnnouncementTo(clientId, *uid)) {
++reached;
}
}
}
}
return reached;
}
bool MusicManager::deliverAnnouncementTo(uint64_t clientId,
const std::string& uid)
{
if (!database_ || !messageCallback_) {
return false;
}
auto textKv = database_->getKv("announcement.text");
auto idKv = database_->getKv("announcement.id");
if (!textKv || !*textKv || (*textKv)->empty() || !idKv || !*idKv) {
return false;
}
int64_t currentId = 0;
try {
currentId = std::stoll(**idKv);
} catch (const std::exception&) {
return false;
}
const std::string seenKey = "announcement.seen." + uid;
int64_t seenId = 0;
if (auto seen = database_->getKv(seenKey); seen && *seen) {
try {
seenId = std::stoll(**seen);
} catch (const std::exception&) {
seenId = 0;
}
}
if (seenId >= currentId) {
return false; // already delivered
}
messageCallback_(clientId, **textKv);
(void)database_->setKv(seenKey, std::to_string(currentId));
Void::Log::info("MusicManager", "{}",
std::format("Announcement (id {}) delivered to {}",
currentId, uid));
return true;
}
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 (subscriptions_) {
subscriptions_->onClientDisconnected(clientId);
}
}
// ---- temp files ---------------------------------------------------------
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));
}
}
} // namespace Echoion::Core