#include "ConfigManager.hpp" #include "LoggerInterface.hpp" #include "echoion/core/MusicManager.hpp" #include #include #include #include #include #include #include #include namespace Echoion::Core { MusicManager::MusicManager() = default; MusicManager::~MusicManager() { shutdown(); } Api::Result MusicManager::initialize(std::shared_ptr networkClient, std::shared_ptr database) { // Get config from global ConfigManager const auto& botConfig = ECHOION_BOT; const auto& youtubeConfig = ECHOION_YOUTUBE; const auto& networkConfig = ECHOION_NETWORK; config_ = botConfig; networkClient_ = std::move(networkClient); // NetworkClient is already initialized by Core, just update proxy if // needed if (networkConfig.proxy.has_value() && networkConfig.proxy->isValid()) { networkClient_->setProxy(networkConfig.proxy); ECHOION_LOG_INFO(std::format( "NetworkClient using {} proxy: {}:{}", networkConfig.proxy->isSocks5() ? "SOCKS5" : "HTTP", networkConfig.proxy->host, networkConfig.proxy->port)); } youTubeClient_ = std::make_unique(networkClient_); // Configure YouTube cookies if provided if (youtubeConfig.youtubeCookiesPath.has_value()) { youTubeClient_->setCookiesPath(*youtubeConfig.youtubeCookiesPath); ECHOION_LOG_INFO(std::format("Using YouTube cookies from file: {}", *youtubeConfig.youtubeCookiesPath)); } else if (youtubeConfig.cookiesFromBrowser.has_value()) { youTubeClient_->setCookiesFromBrowser( *youtubeConfig.cookiesFromBrowser); ECHOION_LOG_INFO( std::format("Using YouTube cookies from browser: {}", *youtubeConfig.cookiesFromBrowser)); } // Configure proxy for YouTube client if (networkConfig.proxy.has_value() && networkConfig.proxy->isValid()) { 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) { ECHOION_LOG_WARNING( std::format("Failed to initialize YouTube client: {}", ytResult.error().message)); } audioDecoder_ = std::make_unique(); 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->isValid()) { audioDecoder_->setProxyConfig(networkConfig.proxy); ECHOION_LOG_INFO( std::format("AudioDecoder using {} proxy: {}:{}", networkConfig.proxy->isSocks5() ? "SOCKS5" : "HTTP", networkConfig.proxy->host, networkConfig.proxy->port)); } // Initialize subscription manager with database subscriptionManager_ = std::make_unique(); auto subResult = subscriptionManager_->initialize(database); if (!subResult) { ECHOION_LOG_WARNING( std::format("Failed to initialize subscription manager: {}", subResult.error().message)); // Not fatal - continue without subscriptions } volume_ = botConfig.defaultVolume; ECHOION_LOG_INFO("MusicManager initialized"); return {}; } void MusicManager::shutdown() { isPlaying_ = false; cv_.notify_all(); if (playbackThread_.joinable()) { playbackThread_.join(); } // Join playlist loading thread if still running (don't detach - unsafe) if (playlistLoadThread_.joinable()) { playlistLoadThread_.join(); } // Join auto-start thread if still running if (playlistAutoStartThread_.joinable()) { playlistAutoStartThread_.join(); } if (audioDecoder_) { audioDecoder_->shutdown(); } // Clean up temp files std::unique_lock lock(tempFilesMutex_); for (const auto& filepath : tempFiles_) { std::error_code ec; std::filesystem::remove(filepath, ec); if (!ec) { ECHOION_LOG_DEBUG( 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); } } ECHOION_LOG_INFO("MusicManager shutdown"); } Api::Result MusicManager::play(const std::string& query, uint64_t clientId) { ECHOION_LOG_INFO( 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(); ECHOION_LOG_DEBUG( std::format("resolveQuery took {} ms", std::chrono::duration_cast( afterResolve - startTime) .count())); if (!track) { ECHOION_LOG_ERROR(std::format("Failed to resolve query '{}': {}", query, track.error().message)); return std::unexpected(track.error()); } ECHOION_LOG_INFO(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 = nextQueueId_++, .track = *track, .addedAt = std::chrono::system_clock::now(), .addedBy = nickname, .isPlaying = true, .position = std::chrono::milliseconds(0)}; ECHOION_LOG_DEBUG("Getting stream URL..."); auto streamStart = std::chrono::steady_clock::now(); auto streamUrl = getStreamUrl(*track); ECHOION_LOG_DEBUG(std::format( "getStreamUrl took {} ms", std::chrono::duration_cast( std::chrono::steady_clock::now() - streamStart) .count())); if (!streamUrl) { ECHOION_LOG_ERROR(std::format("Failed to get stream URL: {}", streamUrl.error().message)); currentTrack_.reset(); return std::unexpected(streamUrl.error()); } ECHOION_LOG_DEBUG("Opening audio source..."); auto openResult = audioDecoder_->openSource(*streamUrl); // If direct open fails and we have a proxy, try downloading through // proxy const auto& networkConfig = ECHOION_NETWORK; if (!openResult && networkConfig.proxy.has_value() && networkConfig.proxy->isValid()) { ECHOION_LOG_INFO( "Direct open failed, trying download through proxy..."); auto downloadedPath = downloadAudioForPlayback(*streamUrl); if (downloadedPath) { ECHOION_LOG_INFO(std::format("Downloaded audio to: {}", *downloadedPath)); openResult = audioDecoder_->openSource(*downloadedPath); if (openResult) { // Track temp file for cleanup std::unique_lock lock( tempFilesMutex_); tempFiles_.insert(*downloadedPath); } } else { ECHOION_LOG_WARNING( std::format("Failed to download through proxy: {}", downloadedPath.error().message)); } } if (!openResult) { ECHOION_LOG_ERROR(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()) { ECHOION_LOG_INFO("Joining old playback thread before " "starting new one..."); playbackThread_.join(); } playbackThread_ = std::jthread(&MusicManager::playbackThread, this); ECHOION_LOG_INFO("Playback thread started"); } cv_.notify_one(); ECHOION_LOG_INFO(std::format("Now playing: {} - {}", track->title, track->artist)); return std::format("{} - {}", track->title, track->artist); } ECHOION_LOG_DEBUG("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 MusicManager::pause() { std::shared_lock lock(mutex_); if (!isPlaying_ || isPaused_) { return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Nothing is playing")); } // Capture current position before pausing playbackPosition_ = getPlaybackPosition(); isPaused_ = true; ECHOION_LOG_INFO( std::format("Playback paused at {}ms", playbackPosition_.count())); return {}; } Api::Result MusicManager::resume() { std::shared_lock lock(mutex_); if (!isPlaying_ || !isPaused_) { return std::unexpected( Api::Error(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_) { ECHOION_LOG_INFO( "Joining finished playback thread before starting new one..."); playbackThread_.join(); ECHOION_LOG_INFO("Old thread joined"); needToStartThread = true; } if (needToStartThread || (!playbackThreadRunning_ && (!queue_.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); ECHOION_LOG_INFO("Started playback thread"); } // Notify the thread to process cv_.notify_one(); ECHOION_LOG_INFO(std::format("Playback resumed from {}ms", playbackPosition_.count())); return {}; } Api::Result MusicManager::stop() { std::shared_lock lock(mutex_); isPlaying_ = false; isPaused_ = false; currentTrack_.reset(); queue_.clear(); if (audioDecoder_) { audioDecoder_->closeSource(); } cv_.notify_one(); ECHOION_LOG_INFO("Playback stopped"); // Publish playback stopped event Api::GlobalEventBus::instance().publish(Api::Events::PlaybackStopped{ .lastTrack = currentTrack_ ? std::optional(currentTrack_->track) : std::nullopt, .finalPosition = playbackPosition_}); return {}; } Api::Result MusicManager::skip(uint32_t count) { std::shared_lock lock(mutex_); if (!isPlaying_) { return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Nothing is playing")); } for (uint32_t i = 0; i < count; ++i) { if (queue_.empty()) { if (repeat_ && currentTrack_.has_value()) { continue; } isPlaying_ = false; currentTrack_.reset(); audioDecoder_->closeSource(); break; } auto nextTrack = getNextTrack(); currentTrack_ = Api::QueueEntry{.queueId = 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) { ECHOION_LOG_ERROR(std::format("Failed to open stream: {}", openResult.error().message)); } } } cv_.notify_one(); ECHOION_LOG_INFO(std::format("Skipped {} track(s)", count)); return {}; } Api::Result MusicManager::seek(std::chrono::milliseconds position) { if (!isPlaying_) { return std::unexpected(Api::Error(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; } ECHOION_LOG_INFO(std::format("Seeked to {} ms", position.count())); return {}; } Api::Result MusicManager::setVolume(float volume) { if (volume < 0.0f || volume > 1.0f) { return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Volume must be 0.0-1.0")); } float oldVolume = volume_; volume_ = volume; ECHOION_LOG_INFO(std::format("Volume set to {}", volume)); // Publish volume changed event Api::GlobalEventBus::instance().publish(Api::Events::VolumeChanged{ .oldVolume = oldVolume, .newVolume = volume, .changedByClientId = 0 // Will be set by caller if available }); return {}; } Api::Result MusicManager::queueTrack(const Api::TrackInfo& track, uint64_t clientId) { // Validate track before adding to queue - check if we can get a stream // URL ECHOION_LOG_INFO( std::format("Validating track before queueing: {} - {}", track.title, track.artist)); auto streamUrl = getStreamUrl(track); if (!streamUrl) { ECHOION_LOG_WARNING(std::format( "Track validation failed for '{} - {}': {}", track.title, track.artist, streamUrl.error().message)); return std::unexpected( Api::Error(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 lock(mutex_); if (queue_.size() >= config_.maxQueueSize) { return std::unexpected(Api::Error( Api::ErrorCode::InvalidArgument, "Queue is full")); } queueId = nextQueueId_++; queue_.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 (shuffleIndex_ < shuffledIndices_.size()) { std::uniform_int_distribution dist( shuffleIndex_, shuffledIndices_.size()); size_t insertPos = dist(rng_); shuffledIndices_.insert(shuffledIndices_.begin() + insertPos, queue_.size() - 1); } else { shuffledIndices_.push_back(queue_.size() - 1); } } ECHOION_LOG_INFO( 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() && queue_.size() > 0; needToStartThread = !playbackThread_.joinable() && !playbackThreadRunning_; ECHOION_LOG_DEBUG(std::format( "queueTrack debug: shouldStart={}, " "needToStartThread={}, isPlaying_={}, " "thread_joinable={}, thread_running={}, queue_size={}", shouldStart, needToStartThread, isPlaying_.load(), playbackThread_.joinable(), playbackThreadRunning_.load(), queue_.size())); } if (shouldStart) { ECHOION_LOG_INFO("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_) { ECHOION_LOG_INFO("Joining finished playback thread before " "starting new one..."); playbackThread_.join(); ECHOION_LOG_INFO("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); ECHOION_LOG_INFO("Started playback thread for auto-play"); } // Notify the thread to process cv_.notify_one(); } return queueId; } Api::Result MusicManager::removeFromQueue(uint32_t position) { std::shared_lock lock(mutex_); if (position >= queue_.size()) { return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Invalid position")); } auto removedTrack = queue_[position]; queue_.erase(queue_.begin() + position); // Update shuffled indices if shuffle is enabled if (shuffle_ && !shuffledIndices_.empty()) { // Remove the index from shuffledIndices auto it = std::find(shuffledIndices_.begin(), shuffledIndices_.end(), position); if (it != shuffledIndices_.end()) { size_t removedShuffleIndex = std::distance(shuffledIndices_.begin(), it); shuffledIndices_.erase(it); // If we removed an index before the current shuffle position, // decrement it if (removedShuffleIndex < shuffleIndex_) { shuffleIndex_--; } } // Decrement indices that were after the removed position for (auto& idx : shuffledIndices_) { if (idx > position) { idx--; } } } ECHOION_LOG_INFO(std::format("Removed track at position {}", position)); // Publish track removed event Api::GlobalEventBus::instance().publish(Api::Events::TrackRemoved{ .track = removedTrack.track, .queueId = removedTrack.queueId, .removedByClientId = 0, .queueLength = static_cast(queue_.size())}); return {}; } Api::Result MusicManager::clearQueue() { std::shared_lock lock(mutex_); uint32_t previousLength = static_cast(queue_.size()); queue_.clear(); // Clear shuffle state if (shuffle_) { shuffledIndices_.clear(); shuffleIndex_ = 0; } ECHOION_LOG_INFO("Queue cleared"); // Publish queue cleared event Api::GlobalEventBus::instance().publish(Api::Events::QueueCleared{ .clearedByClientId = 0, .previousLength = previousLength}); return {}; } Api::Result> MusicManager::getQueue() const { std::shared_lock lock(mutex_); return queue_; } Api::Result MusicManager::moveInQueue(uint32_t from, uint32_t to) { std::shared_lock lock(mutex_); if (from >= queue_.size() || to >= queue_.size()) { return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Invalid position")); } auto entry = queue_[from]; queue_.erase(queue_.begin() + from); queue_.insert(queue_.begin() + to, entry); // Update shuffled indices if shuffle is enabled if (shuffle_ && !shuffledIndices_.empty()) { // Find and update indices that are affected by the move for (auto& idx : 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 } } ECHOION_LOG_INFO(std::format("Moved track from {} to {}", from, to)); // Publish queue reordered event Api::GlobalEventBus::instance().publish( Api::Events::QueueReordered{.queueId = entry.queueId, .oldPosition = from, .newPosition = to, .changedByClientId = 0}); return {}; } Api::Result MusicManager::toggleShuffle() { std::shared_lock lock(mutex_); shuffle_ = !shuffle_; if (shuffle_) { // Build shuffled indices for current queue rebuildShuffledIndices(); shuffleIndex_ = 0; ECHOION_LOG_INFO( std::format("Shuffle enabled - queue shuffled with {} tracks", shuffledIndices_.size())); } else { // Clear shuffle state shuffledIndices_.clear(); shuffleIndex_ = 0; ECHOION_LOG_INFO("Shuffle disabled"); } // Publish shuffle changed event Api::GlobalEventBus::instance().publish(Api::Events::ShuffleChanged{ .enabled = shuffle_, .changedByClientId = 0}); return shuffle_; } void MusicManager::rebuildShuffledIndices() { shuffledIndices_.clear(); shuffledIndices_.reserve(queue_.size()); // Create indices 0 to queue_size-1 for (size_t i = 0; i < queue_.size(); ++i) { shuffledIndices_.push_back(i); } // Shuffle the indices using Fisher-Yates algorithm std::shuffle(shuffledIndices_.begin(), shuffledIndices_.end(), rng_); shuffleIndex_ = 0; ECHOION_LOG_DEBUG(std::format("Rebuilt shuffled indices: {} tracks", shuffledIndices_.size())); } void MusicManager::reshuffleRemaining() { if (shuffledIndices_.empty() || shuffleIndex_ >= shuffledIndices_.size()) { return; } // Only reshuffle the remaining indices (from shuffleIndex_ onwards) // This preserves the already-played tracks order but reshuffles what's // left std::shuffle(shuffledIndices_.begin() + shuffleIndex_, shuffledIndices_.end(), rng_); ECHOION_LOG_DEBUG(std::format("Reshuffled remaining {} tracks", shuffledIndices_.size() - shuffleIndex_)); } Api::Result MusicManager::toggleRepeat() { repeat_ = !repeat_; ECHOION_LOG_INFO(repeat_ ? "Repeat enabled" : "Repeat disabled"); // Publish repeat changed event Api::GlobalEventBus::instance().publish(Api::Events::RepeatChanged{ .enabled = repeat_, .changedByClientId = 0}); return repeat_; } Api::Result MusicManager::loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId) { if (!youTubeClient_) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTube client not available")); } // Check if already loading a playlist if (playlistLoading_.load()) { return std::unexpected( Api::Error(Api::ErrorCode::AlreadyExists, "Already loading a playlist, please wait")); } // Extract playlist ID if a full URL was provided std::string playlistId = playlistIdOrUrl; if (YouTubeClient::isYouTubeUrl(playlistIdOrUrl)) { auto extractedId = youTubeClient_->extractPlaylistId(playlistIdOrUrl); if (extractedId) { playlistId = *extractedId; ECHOION_LOG_DEBUG(std::format( "Extracted playlist ID '{}' from URL", playlistId)); } else { return std::unexpected( Api::Error(Api::ErrorCode::InvalidArgument, "Could not extract playlist ID from URL")); } } // Join previous thread if any (don't detach - unsafe) if (playlistLoadThread_.joinable()) { playlistLoadThread_.join(); } // Reset loading state playlistLoading_ = true; playlistLoadedCount_ = 0; playlistTotalCount_ = 0; ECHOION_LOG_INFO( std::format("Starting async playlist load: {}", playlistId)); // Publish playlist load started event Api::GlobalEventBus::instance().publish( Api::Events::PlaylistLoadStarted{.playlistId = playlistId, .requestedByClientId = clientId}); // Start playlist loading in background thread playlistLoadThread_ = std::thread([this, playlistId, clientId]() { std::atomic added{0}; std::atomic firstTrackAdded{false}; std::mutex startPlaybackMutex; // Use streaming playlist loading - tracks are added as soon as they // are resolved youTubeClient_->getPlaylistStreaming( playlistId, // Track callback - called for each track as it is resolved [this, &added, &firstTrackAdded, &startPlaybackMutex, clientId, playlistId](Api::TrackInfo&& track) { playlistLoadedCount_.fetch_add(1); bool isFirst = false; { std::lock_guard lock(startPlaybackMutex); isFirst = !firstTrackAdded.load(); if (isFirst) { firstTrackAdded = true; } } // Add track to queue auto result = queueTrack(track, clientId); if (result) { added.fetch_add(1); // Publish playlist track loaded event Api::GlobalEventBus::instance().publish( Api::Events::PlaylistTrackLoaded{ .playlistId = playlistId, .track = track, .loadedCount = static_cast( playlistLoadedCount_.load()), .totalCount = static_cast( playlistTotalCount_.load())}); // Start playback immediately on first track if (isFirst) { ECHOION_LOG_INFO( std::format("First track resolved: {} - {}. " "Starting playback...", track.title, track.artist)); // Start playback in background thread to not block // streaming // Join any previous auto-start thread first if (playlistAutoStartThread_.joinable()) { playlistAutoStartThread_.join(); } playlistAutoStartThread_ = std::thread([this]() { // Small delay to ensure queue is updated std::this_thread::sleep_for( std::chrono::milliseconds(100)); std::shared_lock lock( mutex_); if (!isPlaying_ && !queue_.empty()) { // Trigger playback start cv_.notify_one(); ECHOION_LOG_INFO( "Playback started from playlist"); } }); } } }, // On playlist info callback - called when total track count is // known [this, playlistId](size_t totalTracks) { playlistTotalCount_ = totalTracks; ECHOION_LOG_INFO( std::format("Playlist '{}' has {} tracks, resolving...", playlistId, totalTracks)); }, // On complete callback [this, &added, playlistId]() { ECHOION_LOG_INFO(std::format( "Playlist streaming complete. Added {} tracks", added.load())); playlistLoading_ = false; // Publish playlist load completed event Api::GlobalEventBus::instance().publish( Api::Events::PlaylistLoadCompleted{ .playlistId = playlistId, .totalTracksLoaded = added.load(), .success = true, .error = std::nullopt}); }); }); // End of background thread return {}; // Return immediately, loading continues in background } Api::Result> MusicManager::getPlaylists() const { return std::vector{}; } Api::Result> MusicManager::getCurrentTrack() const { std::shared_lock lock(mutex_); return currentTrack_; } std::chrono::milliseconds MusicManager::getPlaybackPosition() const { std::shared_lock 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) { ECHOION_LOG_DEBUG( "getPlaybackPosition: playbackStartTime_ not initialized"); return playbackBasePosition_; } // Calculate elapsed time since last start/resume auto elapsed = std::chrono::duration_cast( 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) { ECHOION_LOG_WARNING( std::format("getPlaybackPosition: Invalid position: {}ms", position.count())); return std::chrono::milliseconds(0); } return position; } Api::Result MusicManager::getPlaybackState() const { std::shared_lock lock(mutex_); Api::PlaybackState state; state.currentTrack = currentTrack_; state.queue = queue_; 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 MusicManager::search(const std::string& query) { if (!youTubeClient_) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTube client not available")); } return youTubeClient_->search(query); } void MusicManager::storePendingSearch( uint64_t clientId, const std::vector& results) { std::lock_guard lock(pendingSearchMutex_); pendingSearches_[clientId] = results; ECHOION_LOG_DEBUG(std::format("Stored {} search results for client {}", results.size(), clientId)); } std::optional> MusicManager::getPendingSearch(uint64_t clientId) { std::lock_guard 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 MusicManager::selectSearchResult(uint64_t clientId, uint32_t index, const std::string& invokerName) { if (index == 0) { return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Index must be 1 or greater")); } auto pending = getPendingSearch(clientId); if (!pending) { return std::unexpected( Api::Error(Api::ErrorCode::NotFound, "No pending search results. Use search or play " "commands first.")); } if (index > pending->size()) { return std::unexpected(Api::Error( 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 lock(mutex_); Api::HotReloadState state; // Build playback state directly (don't call getPlaybackState to avoid // double-lock) state.playback.currentTrack = currentTrack_; state.playback.queue = queue_; 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::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 = queue_; if (currentTrack_ && currentTrack_->track.streamUrl) { state.currentStreamUrl = currentTrack_->track.streamUrl; } state.playbackPosition = state.playback.position; state.config = config_; return state; } Api::Result MusicManager::restoreFromHotReload(const Api::HotReloadState& state) { config_ = state.config; queue_ = state.queue; volume_ = state.playback.volume; shuffle_ = state.playback.shuffle; repeat_ = state.playback.repeat; // Rebuild shuffle state if shuffle is enabled if (shuffle_ && !queue_.empty()) { rebuildShuffledIndices(); } ECHOION_LOG_INFO( 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) { ECHOION_LOG_INFO( 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(); ECHOION_LOG_INFO("Playback restored successfully"); } else { ECHOION_LOG_ERROR( std::format("Failed to seek to position {}ms: {}", state.playbackPosition.count(), seekResult.error().message)); } } else { ECHOION_LOG_ERROR(std::format("Failed to open stream URL: {}", openResult.error().message)); } } else { ECHOION_LOG_INFO( 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() && !queue_.empty() && hasOnlineSubscribers()) { ECHOION_LOG_INFO( "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 && !queue_.empty()) { isPaused_ = true; isPlaying_ = true; currentTrack_.reset(); } ECHOION_LOG_INFO("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() { ECHOION_LOG_DEBUG("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 localAudioBuffer; auto next = std::chrono::steady_clock::now(); int chunksSent = 0; while (true) { { std::unique_lock lock(mutex_); cv_.wait(lock, [this] { return !isPlaying_ || !isPaused_ || (hasOnlineSubscribers() && !queue_.empty() && !currentTrack_.has_value()); }); // Auto-start if we have ONLINE subscribers and queue but no // current track if (hasOnlineSubscribers() && !queue_.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 = queue_.front(); queue_.erase(queue_.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) { ECHOION_LOG_ERROR( std::format("Failed to open first track: {}", openResult.error().message)); lock.lock(); currentTrack_.reset(); isPlaying_ = false; continue; } lock.lock(); ECHOION_LOG_INFO(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 incomingChunk; if (audioDecoder_->getNextChunk(incomingChunk)) { localAudioBuffer.insert(localAudioBuffer.end(), incomingChunk.begin(), incomingChunk.end()); if (chunksSent == 0) { ECHOION_LOG_DEBUG( std::format("First chunk received: {} samples", incomingChunk.size())); } } } // Update current position periodically (every ~2 seconds) if (chunksSent == 0 && currentTrack_.has_value()) { std::shared_lock 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(position.count()) / static_cast(streamInfo->duration.count())) * 100.0f; } Api::GlobalEventBus::instance().publish( 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 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(localAudioBuffer[i]))); } ECHOION_LOG_DEBUG(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(localAudioBuffer[i] * volMult); audioChunk[i] = static_cast(std::clamp(sample, -32768, 32767)); } localAudioBuffer.erase(localAudioBuffer.begin(), localAudioBuffer.begin() + SHORTS_PER_CHUNK); // Send audio to callback if (audioCallback_) { audioCallback_(std::span(audioChunk.data(), audioChunk.size())); chunksSent++; if (chunksSent == 1 || chunksSent % 100 == 0) { ECHOION_LOG_DEBUG( std::format("Sent {} chunks, buffer: {}", chunksSent, localAudioBuffer.size())); } } else if (chunksSent == 0) { ECHOION_LOG_WARNING("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) { ECHOION_LOG_DEBUG(std::format("Waiting for data: {} < {}", localAudioBuffer.size(), SHORTS_PER_CHUNK)); } std::vector 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 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(localAudioBuffer[i] * volMult); // Soft limiting to prevent clipping audioChunk[i] = static_cast( std::clamp(sample, -32768, 32767)); } if (audioCallback_) { audioCallback_(std::span( 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) { ECHOION_LOG_INFO( std::format("Playback finished with last flush, " "sent {} chunks, flushed {} samples", chunksSent, totalFlushed)); } else { ECHOION_LOG_INFO(std::format( "Playback finished, sent {} chunks", chunksSent)); } onTrackFinished(); // Send low-level white noise during track transition to // prevent audio glitch and keep microphone active ECHOION_LOG_DEBUG( "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 noiseDist(-20, 20); while (std::chrono::steady_clock::now() - transitionStart < MAX_TRANSITION_TIME) { // Check if next track is ready std::vector incoming; if (audioDecoder_->getNextChunk(incoming, false)) { // Next track is ready, add to buffer and break localAudioBuffer.insert(localAudioBuffer.end(), incoming.begin(), incoming.end()); ECHOION_LOG_DEBUG( "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 noiseChunk(SHORTS_PER_CHUNK); for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) { noiseChunk[i] = static_cast(noiseDist(gen)); } audioCallback_(std::span( 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 lock(mutex_); if (!isPlaying_) { ECHOION_LOG_INFO( "Playback stopped during transition"); break; } } } // Check if playback should continue (more tracks available) { std::shared_lock lock(mutex_); ECHOION_LOG_DEBUG(std::format( "Playback thread: isPlaying_={}, queue_size={}, " "currentTrack.has_value={}", isPlaying_.load(), queue_.size(), currentTrack_.has_value())); if (!isPlaying_) { ECHOION_LOG_INFO( "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(); ECHOION_LOG_DEBUG("Continuing to next track..."); continue; } } } ECHOION_LOG_DEBUG("Playback thread exiting"); playbackThreadRunning_ = false; } Api::Result MusicManager::resolveQuery(const std::string& query) { if (YouTubeClient::isYouTubeUrl(query)) { ECHOION_LOG_DEBUG( std::format("Extracting video ID from URL: {}", query)); auto videoId = youTubeClient_->extractVideoId(query); if (videoId) { ECHOION_LOG_DEBUG( std::format("Extracted video ID: '{}'", *videoId)); return youTubeClient_->getVideoInfo(*videoId); } else { ECHOION_LOG_WARNING("Failed to extract video ID from URL"); } auto playlistId = youTubeClient_->extractPlaylistId(query); if (playlistId) { ECHOION_LOG_DEBUG( 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 std::unexpected( Api::Error(Api::ErrorCode::NotFound, "No results found")); } return searchResult->tracks[0]; } Api::Result MusicManager::getStreamUrl(const Api::TrackInfo& track) { if (track.streamUrl) { ECHOION_LOG_DEBUG("Using pre-resolved stream URL"); return *track.streamUrl; } if (track.source == Api::TrackSource::YouTube) { auto videoId = youTubeClient_->extractVideoId(track.originalUrl); if (videoId) { ECHOION_LOG_DEBUG(std::format( "Extracting stream URL for YouTube video: {}", *videoId)); auto url = youTubeClient_->getStreamUrl(*videoId); if (url) { ECHOION_LOG_DEBUG( std::format("Got stream URL: {}", url->c_str())); } else { ECHOION_LOG_ERROR(std::format( "Failed to get stream URL: {}", url.error().message)); } return url; } ECHOION_LOG_WARNING("Could not extract video ID from URL"); } return std::unexpected( Api::Error(Api::ErrorCode::NotFound, "Could not get stream URL")); } void MusicManager::onTrackFinished() { std::shared_lock lock(mutex_); // Publish track finished event if (currentTrack_.has_value()) { Api::GlobalEventBus::instance().publish(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 (queue_.empty()) { // Queue is empty - stop playback but keep thread running for next // track isPlaying_ = false; currentTrack_.reset(); audioDecoder_->closeSource(); ECHOION_LOG_INFO("Queue empty, playback stopped"); return; } // Play next track from queue auto nextTrack = getNextTrack(); ECHOION_LOG_INFO(std::format("Playing next track: {} - {}", nextTrack.title, nextTrack.artist)); currentTrack_ = Api::QueueEntry{.queueId = 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 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) { ECHOION_LOG_INFO( "Using prefetched stream URL for seamless transition"); streamUrl = *result; } } } // If prefetch not ready or failed, fetch synchronously if (!streamUrl) { if (prefetchState_.isPrefetching) { ECHOION_LOG_INFO("Waiting for prefetch to complete..."); auto result = prefetchState_.streamUrlFuture.get(); if (result) { streamUrl = *result; } } if (!streamUrl) { ECHOION_LOG_DEBUG( "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) { ECHOION_LOG_ERROR(std::format("Failed to open next track: {}", result.error().message)); // Remove the failed track and try next queue_.erase(queue_.begin()); onTrackFinished(); } } else { ECHOION_LOG_ERROR("Failed to get stream URL for next track"); queue_.erase(queue_.begin()); onTrackFinished(); } } Api::TrackInfo MusicManager::getNextTrack() { if (queue_.empty()) { return Api::TrackInfo{}; } if (shuffle_ && !shuffledIndices_.empty()) { // Use shuffled order size_t queueIndex = shuffledIndices_[shuffleIndex_]; auto track = queue_[queueIndex].track; // Remove the track from queue and rebuild shuffled indices queue_.erase(queue_.begin() + queueIndex); shuffleIndex_++; // If we've played all tracks, rebuild for next cycle if (shuffleIndex_ >= shuffledIndices_.size()) { rebuildShuffledIndices(); } else { // Rebuild indices to account for the removed track // Decrement indices that were after the removed track for (size_t i = shuffleIndex_; i < shuffledIndices_.size(); ++i) { if (shuffledIndices_[i] > queueIndex) { shuffledIndices_[i]--; } } } return track; } auto track = queue_.front().track; queue_.erase(queue_.begin()); return track; } Api::Result MusicManager::shuffleQueue() { std::shuffle(queue_.begin(), queue_.end(), rng_); return {}; } std::string MusicManager::getHelpText() const { return R"(Echoion Music Bot Commands: !play - 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 - 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 MusicManager::subscribe(uint64_t clientId) { if (!subscriptionManager_) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized")); } // Get client info (UID and nickname) from the callback if (!clientInfoCallback_) { return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized, "Client info callback not set")); } auto clientInfo = clientInfoCallback_(clientId); if (!clientInfo) { return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "Could not get client info")); } const auto& [uid, nickname] = *clientInfo; bool added = subscriptionManager_->subscribe(uid, nickname); ECHOION_LOG_INFO(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_) { ECHOION_LOG_INFO( "Subscribe: triggering subscriptionChangeCallback"); subscriptionChangeCallback_(); } // Publish subscription event Api::GlobalEventBus::instance().publish(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 MusicManager::unsubscribe(uint64_t clientId) { if (!subscriptionManager_) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized")); } // Get client UID from the callback if (!clientInfoCallback_) { return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized, "Client info callback not set")); } auto clientInfo = clientInfoCallback_(clientId); if (!clientInfo) { return std::unexpected(Api::Error(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_) { ECHOION_LOG_INFO("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) { Api::GlobalEventBus::instance().publish( 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 MusicManager::unsubscribeByUid(const std::string& uid) { if (!subscriptionManager_) { return std::unexpected( Api::Error(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_) { ECHOION_LOG_INFO("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 MusicManager::clearAllSubscriptions() { if (!subscriptionManager_) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized")); } bool cleared = subscriptionManager_->clearAll(); // Pause playback if no subscribers if (cleared && isPlaying_ && !isPaused_) { ECHOION_LOG_INFO("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 MusicManager::getOnlineSubscriberUids() const { std::set 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 MusicManager::getSubscribedClients() const { if (!subscriptionManager_ || !uidToClientIdCallback_) { return {}; } // Resolve UIDs to current session client IDs std::set clientIds; auto uids = subscriptionManager_->getSubscribedUids(); for (const auto& uid : uids) { auto clientId = uidToClientIdCallback_(uid); if (clientId) { clientIds.insert(*clientId); } } return clientIds; } std::vector 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) { ECHOION_LOG_INFO(std::format("onClientConnected: client {}", clientId)); if (!subscriptionManager_ || !clientInfoCallback_) { ECHOION_LOG_WARNING("onClientConnected: subscriptionManager or " "clientInfoCallback not set"); return; } // Get the client's UID auto clientInfo = clientInfoCallback_(clientId); if (!clientInfo) { ECHOION_LOG_WARNING(std::format( "onClientConnected: could not get client info for {}", clientId)); return; } const auto& [uid, nickname] = *clientInfo; ECHOION_LOG_INFO(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)) { ECHOION_LOG_INFO(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_) { ECHOION_LOG_INFO( "onClientConnected: triggering subscriptionChangeCallback"); subscriptionChangeCallback_(); } // If we were paused due to no online subscribers, resume playback if (wasPausedForNoSubscribers_ && isPlaying_ && isPaused_) { ECHOION_LOG_INFO( "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() && !queue_.empty()) { ECHOION_LOG_INFO("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 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)) { ECHOION_LOG_INFO(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_) { ECHOION_LOG_INFO( "No online subscribers left, pausing playback"); auto result = pause(); if (result) { wasPausedForNoSubscribers_ = true; } } } } Api::Result MusicManager::downloadAudioForPlayback(const std::string& url) { if (!networkClient_) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "NetworkClient not available")); } // Create temp file path auto cacheDir = std::filesystem::temp_directory_path() / "echoion_audio"; std::error_code ec; std::filesystem::create_directories(cacheDir, ec); auto timestamp = std::chrono::system_clock::now().time_since_epoch().count(); auto tempPath = cacheDir / std::format("audio_{}.tmp", timestamp); // Download the file ECHOION_LOG_INFO( std::format("Downloading audio from: {}...", url.substr(0, 60))); auto response = networkClient_->get(url); if (!response) { return std::unexpected( Api::Error(Api::ErrorCode::NetworkError, std::format("Failed to download audio: {}", response.error().message))); } if (response->statusCode != 200) { return std::unexpected(Api::Error( Api::ErrorCode::NetworkError, std::format("HTTP error {}: {}", response->statusCode, response->body.substr(0, 100)))); } // Write to temp file std::ofstream file(tempPath, std::ios::binary); if (!file) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Failed to create temp file")); } file.write(response->body.data(), response->body.size()); file.close(); ECHOION_LOG_INFO(std::format("Downloaded {} bytes to {}", response->body.size(), tempPath.string())); return tempPath.string(); } void MusicManager::cleanupTempFile(const std::string& filepath) { std::unique_lock lock(tempFilesMutex_); tempFiles_.erase(filepath); std::error_code ec; std::filesystem::remove(filepath, ec); if (ec) { ECHOION_LOG_WARNING(std::format("Failed to remove temp file {}: {}", filepath, ec.message())); } else { ECHOION_LOG_DEBUG( std::format("Cleaned up temp file: {}", filepath)); } } bool MusicManager::shouldPrefetch() const { std::shared_lock lock(mutex_); // Don't prefetch if not playing, no current track, or queue is empty if (!isPlaying_ || !currentTrack_.has_value() || queue_.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) { ECHOION_LOG_DEBUG("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) { ECHOION_LOG_DEBUG(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)) { ECHOION_LOG_DEBUG(std::format( "Prefetch: Time remaining {}s, threshold {}s - {}", std::chrono::duration_cast(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 } ECHOION_LOG_INFO("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 lock(mutex_); if (queue_.empty()) { prefetchState_.isPrefetching = false; return; } // Use shuffled order if shuffle is enabled if (shuffle_ && !shuffledIndices_.empty() && shuffleIndex_ < shuffledIndices_.size()) { nextTrack = queue_[shuffledIndices_[shuffleIndex_]].track; } else { nextTrack = queue_[0].track; } } // Start async prefetch prefetchState_.streamUrlFuture = std::async( std::launch::async, [this, nextTrack]() -> Api::Result { auto result = getStreamUrl(nextTrack); if (result) { ECHOION_LOG_INFO("Prefetch completed successfully"); } else { ECHOION_LOG_WARNING(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 silenceChunk(SHORTS_PER_CHUNK, 0); ECHOION_LOG_DEBUG( std::format("Generating {}ms of transition silence ({} chunks)", duration.count(), chunksNeeded)); for (int i = 0; i < chunksNeeded; ++i) { audioCallback_(std::span(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 silenceChunk(SHORTS_PER_CHUNK, 0); audioCallback_( std::span(silenceChunk.data(), silenceChunk.size())); } } // namespace Echoion::Core