Extract PlaylistLoader from MusicManager

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 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-24 01:07:00 +03:00
1 parent 0e090168e8
commit 622335260f
4 files changed
+243 -145

No files matched your search

+30 -137
View File
@@ -1,6 +1,7 @@
#include "ConfigManager.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/PlaylistLoader.hpp"
#include <Events.hpp>
#include <algorithm>
#include <execution>
@@ -42,6 +43,15 @@ namespace Echoion::Core
youTubeClient_ = std::make_unique<YouTubeClient>(networkClient_);
// Playlist loading runs off the audio path: it enqueues resolved
// tracks via queueTrack and pokes the playback loop on the first one.
playlistLoader_ = std::make_unique<PlaylistLoader>(
youTubeClient_.get(), eventBus_,
[this](const Api::TrackInfo& track, uint64_t clientId) {
return queueTrack(track, clientId).has_value();
},
[this]() { requestPlaybackStart(); });
// Configure YouTube cookies if provided
if (youtubeConfig.youtubeCookiesPath.has_value()) {
youTubeClient_->setCookiesPath(*youtubeConfig.youtubeCookiesPath);
@@ -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<std::shared_mutex> 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<uint32_t> added{0};
std::atomic<bool> 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<std::mutex> 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<uint32_t>(
playlistLoadedCount_.load()),
.totalCount = static_cast<uint32_t>(
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<std::shared_mutex> 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<std::vector<Api::PlaylistInfo>>