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

+9 -8
View File
@@ -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<std::vector<Api::PlaylistInfo>>
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<Api::TrackInfo>
resolveQuery(const std::string& query);
[[nodiscard]] Api::Result<std::string>
@@ -218,13 +221,11 @@ namespace Echoion::Core
std::optional<std::string> prefetchedUrl;
} prefetchState_;
// Async playlist loading state
std::thread playlistLoadThread_;
std::atomic<bool> playlistLoading_{false};
std::atomic<size_t> playlistLoadedCount_{0};
std::atomic<size_t> playlistTotalCount_{0};
// Async playlist loading (background thread owned by the loader).
std::unique_ptr<PlaylistLoader> 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> networkClient_;
+75
View File
@@ -0,0 +1,75 @@
#pragma once
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <Void/Async/EventBus.hpp>
#include <atomic>
#include <cstdint>
#include <functional>
#include <string>
#include <thread>
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<bool(const Api::TrackInfo&, uint64_t)>;
using PlaybackStartFn = std::function<void()>;
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<void>
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 <typename T> void emit(T event)
{
if (bus_) {
bus_->publish<T>(std::move(event));
}
}
YouTubeClient* yt_;
Void::EventBus::EventBus* bus_;
EnqueueFn enqueue_;
PlaybackStartFn requestStart_;
std::thread loadThread_;
std::atomic<bool> loading_{false};
std::atomic<std::size_t> loadedCount_{0};
std::atomic<std::size_t> totalCount_{0};
};
} // namespace Echoion::Core
+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>>
+129
View File
@@ -0,0 +1,129 @@
#include "echoion/core/PlaylistLoader.hpp"
#include "echoion/core/YouTubeClient.hpp"
#include <Events.hpp>
#include <Void/Log/Log.hpp>
#include <format>
#include <mutex>
namespace Echoion::Core
{
Api::Result<void> 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<uint32_t> added{0};
std::atomic<bool> 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<std::mutex> 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<uint32_t>(loadedCount_.load()),
.totalCount =
static_cast<uint32_t>(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