From 622335260f5ee0f582118c6d27006a919e7e0734 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 24 Jun 2026 01:07:00 +0300 Subject: [PATCH] Extract PlaylistLoader from MusicManager MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the async, streaming playlist-load orchestration (the background load thread, loading/loaded/total counters, and the getPlaylistStreaming wiring) into a PlaylistLoader class. It enqueues resolved tracks via an injected callback (-> queueTrack) and asks the owner to start playback on the first track via requestPlaybackStart() — the single seam back to the audio loop, which still owns the auto-start thread + cv_ poke. loadPlaylist() now just delegates. Behavior preserved; build green. Co-Authored-By: Claude Opus 4.8 --- include/echoion/core/MusicManager.hpp | 17 +-- include/echoion/core/PlaylistLoader.hpp | 75 +++++++++++ src/MusicManager.cpp | 167 +++++------------------- src/PlaylistLoader.cpp | 129 ++++++++++++++++++ 4 files changed, 243 insertions(+), 145 deletions(-) create mode 100644 include/echoion/core/PlaylistLoader.hpp create mode 100644 src/PlaylistLoader.cpp diff --git a/include/echoion/core/MusicManager.hpp b/include/echoion/core/MusicManager.hpp index 26aeb9a..3cef5d8 100644 --- a/include/echoion/core/MusicManager.hpp +++ b/include/echoion/core/MusicManager.hpp @@ -3,6 +3,7 @@ #include "AudioDecoder.hpp" #include "Database.hpp" #include "NetworkClient.hpp" +#include "PlaylistLoader.hpp" #include "RpcTypes.hpp" #include "SubscriptionManager.hpp" #include "YouTubeClient.hpp" @@ -77,11 +78,11 @@ namespace Echoion::Core uint64_t clientId); [[nodiscard]] bool isPlaylistLoading() const { - return playlistLoading_.load(); + return playlistLoader_ && playlistLoader_->isLoading(); } [[nodiscard]] size_t getPlaylistLoadProgress() const { - return playlistLoadedCount_.load(); + return playlistLoader_ ? playlistLoader_->loadedCount() : 0; } [[nodiscard]] Api::Result> getPlaylists() const; @@ -179,6 +180,8 @@ namespace Echoion::Core } void playbackThread(); + // Auto-start the playback loop when a playlist's first track lands. + void requestPlaybackStart(); [[nodiscard]] Api::Result resolveQuery(const std::string& query); [[nodiscard]] Api::Result @@ -218,13 +221,11 @@ namespace Echoion::Core std::optional prefetchedUrl; } prefetchState_; - // Async playlist loading state - std::thread playlistLoadThread_; - std::atomic playlistLoading_{false}; - std::atomic playlistLoadedCount_{0}; - std::atomic playlistTotalCount_{0}; + // Async playlist loading (background thread owned by the loader). + std::unique_ptr playlistLoader_; - // Auto-start thread for playlist (must be joined, not detached) + // Auto-start thread: pokes the playback loop when a playlist's + // first track lands. Owned here because it touches the audio loop. std::thread playlistAutoStartThread_; std::shared_ptr networkClient_; diff --git a/include/echoion/core/PlaylistLoader.hpp b/include/echoion/core/PlaylistLoader.hpp new file mode 100644 index 0000000..8a389ba --- /dev/null +++ b/include/echoion/core/PlaylistLoader.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + class YouTubeClient; + + // Drives async, streaming playlist loading off the audio path. Owns the + // background load thread; resolved tracks are handed to the owner's queue + // via the enqueue callback, and the owner is asked to start playback on the + // first track via requestStart. Event publishing goes through the bus. + class PlaylistLoader + { + public: + + // Returns true if the track was accepted into the queue. + using EnqueueFn = + std::function; + using PlaybackStartFn = std::function; + + PlaylistLoader(YouTubeClient* yt, Void::EventBus::EventBus* bus, + EnqueueFn enqueue, PlaybackStartFn requestStart) + : yt_(yt), bus_(bus), enqueue_(std::move(enqueue)), + requestStart_(std::move(requestStart)) + { + } + + ~PlaylistLoader() + { + if (loadThread_.joinable()) { + loadThread_.join(); + } + } + + PlaylistLoader(const PlaylistLoader&) = delete; + PlaylistLoader& operator=(const PlaylistLoader&) = delete; + + [[nodiscard]] Api::Result + load(const std::string& playlistIdOrUrl, uint64_t clientId); + + [[nodiscard]] bool isLoading() const { return loading_.load(); } + [[nodiscard]] std::size_t loadedCount() const + { + return loadedCount_.load(); + } + + private: + + template void emit(T event) + { + if (bus_) { + bus_->publish(std::move(event)); + } + } + + YouTubeClient* yt_; + Void::EventBus::EventBus* bus_; + EnqueueFn enqueue_; + PlaybackStartFn requestStart_; + + std::thread loadThread_; + std::atomic loading_{false}; + std::atomic loadedCount_{0}; + std::atomic totalCount_{0}; + }; + +} // namespace Echoion::Core diff --git a/src/MusicManager.cpp b/src/MusicManager.cpp index 3d24a52..2fff69c 100644 --- a/src/MusicManager.cpp +++ b/src/MusicManager.cpp @@ -1,6 +1,7 @@ #include "ConfigManager.hpp" #include #include "echoion/core/MusicManager.hpp" +#include "echoion/core/PlaylistLoader.hpp" #include #include #include @@ -42,6 +43,15 @@ namespace Echoion::Core youTubeClient_ = std::make_unique(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( + 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); @@ -127,10 +137,8 @@ namespace Echoion::Core playbackThread_.join(); } - // Join playlist loading thread if still running (don't detach - unsafe) - if (playlistLoadThread_.joinable()) { - playlistLoadThread_.join(); - } + // Stop playlist loading (the loader joins its background thread). + playlistLoader_.reset(); // Join auto-start thread if still running if (playlistAutoStartThread_.joinable()) { @@ -825,145 +833,30 @@ namespace Echoion::Core MusicManager::loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId) { - if (!youTubeClient_) { + if (!playlistLoader_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "YouTube client not available"); + "Playlist loader not available"); } + return playlistLoader_->load(playlistIdOrUrl, clientId); + } - // Check if already loading a playlist - if (playlistLoading_.load()) { - return Api::fail(Api::ErrorCode::AlreadyExists, - "Already loading a playlist, please wait"); + void MusicManager::requestPlaybackStart() + { + // Start playback in a background thread so streaming isn't blocked. + if (playlistAutoStartThread_.joinable()) { + playlistAutoStartThread_.join(); } + playlistAutoStartThread_ = std::thread([this]() { + // Small delay to ensure the queue is updated. + std::this_thread::sleep_for(std::chrono::milliseconds(100)); - // 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; - Void::Log::debug("MusicManager", "{}", std::format( - "Extracted playlist ID '{}' from URL", playlistId)); - } else { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Could not extract playlist ID from URL"); + std::shared_lock lock(mutex_); + if (!isPlaying_ && !queue_.empty()) { + cv_.notify_one(); + Void::Log::info("MusicManager", "{}", + "Playback started from playlist"); } - } - - // Join previous thread if any (don't detach - unsafe) - if (playlistLoadThread_.joinable()) { - playlistLoadThread_.join(); - } - - // Reset loading state - playlistLoading_ = true; - playlistLoadedCount_ = 0; - playlistTotalCount_ = 0; - - Void::Log::info("MusicManager", "{}", - std::format("Starting async playlist load: {}", playlistId)); - - // Publish playlist load started event - emit( - 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 - emit( - 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) { - Void::Log::info("MusicManager", "{}", - 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(); - Void::Log::info("MusicManager", "{}", - "Playback started from playlist"); - } - }); - } - } - }, - // On playlist info callback - called when total track count is - // known - [this, playlistId](size_t totalTracks) { - playlistTotalCount_ = totalTracks; - Void::Log::info("MusicManager", "{}", - std::format("Playlist '{}' has {} tracks, resolving...", - playlistId, totalTracks)); - }, - // On complete callback - [this, &added, playlistId]() { - Void::Log::info("MusicManager", "{}", std::format( - "Playlist streaming complete. Added {} tracks", - added.load())); - playlistLoading_ = false; - - // Publish playlist load completed event - emit( - 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> diff --git a/src/PlaylistLoader.cpp b/src/PlaylistLoader.cpp new file mode 100644 index 0000000..6bd6849 --- /dev/null +++ b/src/PlaylistLoader.cpp @@ -0,0 +1,129 @@ +#include "echoion/core/PlaylistLoader.hpp" +#include "echoion/core/YouTubeClient.hpp" +#include +#include +#include +#include + +namespace Echoion::Core +{ + + Api::Result PlaylistLoader::load(const std::string& playlistIdOrUrl, + uint64_t clientId) + { + if (!yt_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "YouTube client not available"); + } + + if (loading_.load()) { + return Api::fail(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 = yt_->extractPlaylistId(playlistIdOrUrl); + if (extractedId) { + playlistId = *extractedId; + Void::Log::debug( + "PlaylistLoader", "{}", + std::format("Extracted playlist ID '{}' from URL", + playlistId)); + } else { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Could not extract playlist ID from URL"); + } + } + + // Join previous load thread if any (don't detach - unsafe) + if (loadThread_.joinable()) { + loadThread_.join(); + } + + loading_ = true; + loadedCount_ = 0; + totalCount_ = 0; + + Void::Log::info("PlaylistLoader", "{}", + std::format("Starting async playlist load: {}", + playlistId)); + + emit(Api::Events::PlaylistLoadStarted{.playlistId = playlistId, + .requestedByClientId = clientId}); + + loadThread_ = std::thread([this, playlistId, clientId]() { + std::atomic added{0}; + std::atomic firstTrackAdded{false}; + std::mutex firstMutex; + + yt_->getPlaylistStreaming( + playlistId, + // Track callback — called for each track as it resolves. + [this, &added, &firstTrackAdded, &firstMutex, clientId, + playlistId](Api::TrackInfo&& track) { + loadedCount_.fetch_add(1); + + bool isFirst = false; + { + std::lock_guard lock(firstMutex); + isFirst = !firstTrackAdded.load(); + if (isFirst) { + firstTrackAdded = true; + } + } + + if (enqueue_(track, clientId)) { + added.fetch_add(1); + + emit(Api::Events::PlaylistTrackLoaded{ + .playlistId = playlistId, + .track = track, + .loadedCount = + static_cast(loadedCount_.load()), + .totalCount = + static_cast(totalCount_.load())}); + + // Start playback immediately on the first track. + if (isFirst) { + Void::Log::info( + "PlaylistLoader", "{}", + std::format("First track resolved: {} - {}. " + "Starting playback...", + track.title, track.artist)); + if (requestStart_) { + requestStart_(); + } + } + } + }, + // Total-track-count callback. + [this, playlistId](size_t totalTracks) { + totalCount_ = totalTracks; + Void::Log::info( + "PlaylistLoader", "{}", + std::format("Playlist '{}' has {} tracks, resolving...", + playlistId, totalTracks)); + }, + // Completion callback. + [this, &added, playlistId]() { + Void::Log::info( + "PlaylistLoader", "{}", + std::format( + "Playlist streaming complete. Added {} tracks", + added.load())); + loading_ = false; + + emit(Api::Events::PlaylistLoadCompleted{ + .playlistId = playlistId, + .totalTracksLoaded = added.load(), + .success = true, + .error = std::nullopt}); + }); + }); + + return {}; // Loading continues in the background. + } + +} // namespace Echoion::Core