Extract QueueManager from MusicManager

Move the playback queue + shuffle state (the queue vector, shuffled-index
list, shuffle cursor, next-queue-id counter, and RNG) into a QueueManager
class. To preserve the real-time playback loop's exact behavior, the design
is deliberately minimal: QueueManager is a non-thread-safe data holder that
exposes its containers by reference, and MusicManager keeps its single
playback mutex_/cv_ and drives QueueManager under it. Every former queue_/
shuffledIndices_/shuffleIndex_/nextQueueId_/rng_ site is a 1:1 rename to the
accessor with identical semantics — no logic, locking, or ordering change.

Build green. Runtime behavior in the live playback loop is unverified here
(no audio/TeamSpeak); this is an isolated, revertible commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-24 01:25:07 +03:00
1 parent 622335260f
commit 1efdbe0771
3 files changed
+150 -100

No files matched your search

+3 -6
View File
@@ -4,6 +4,7 @@
#include "Database.hpp" #include "Database.hpp"
#include "NetworkClient.hpp" #include "NetworkClient.hpp"
#include "PlaylistLoader.hpp" #include "PlaylistLoader.hpp"
#include "QueueManager.hpp"
#include "RpcTypes.hpp" #include "RpcTypes.hpp"
#include "SubscriptionManager.hpp" #include "SubscriptionManager.hpp"
#include "YouTubeClient.hpp" #include "YouTubeClient.hpp"
@@ -238,7 +239,8 @@ namespace Echoion::Core
std::unique_ptr<SubscriptionManager> subscriptionManager_; std::unique_ptr<SubscriptionManager> subscriptionManager_;
Api::BotConfig config_; Api::BotConfig config_;
std::vector<Api::QueueEntry> queue_; // Playback queue + shuffle state (driven under mutex_).
QueueManager queueMgr_;
std::optional<Api::QueueEntry> currentTrack_; std::optional<Api::QueueEntry> currentTrack_;
std::atomic<bool> isPlaying_{false}; std::atomic<bool> isPlaying_{false};
std::atomic<bool> isPaused_{false}; std::atomic<bool> isPaused_{false};
@@ -254,11 +256,7 @@ namespace Echoion::Core
std::atomic<float> volume_{0.5f}; std::atomic<float> volume_{0.5f};
std::atomic<bool> shuffle_{false}; std::atomic<bool> shuffle_{false};
std::atomic<bool> repeat_{false}; std::atomic<bool> repeat_{false};
uint64_t nextQueueId_ = 1;
// Shuffle state - maintains shuffled order of queue indices
std::vector<size_t> shuffledIndices_;
size_t shuffleIndex_ = 0;
void rebuildShuffledIndices(); void rebuildShuffledIndices();
void reshuffleRemaining(); void reshuffleRemaining();
@@ -279,7 +277,6 @@ namespace Echoion::Core
ClientInfoCallback clientInfoCallback_; ClientInfoCallback clientInfoCallback_;
UidToClientIdCallback uidToClientIdCallback_; UidToClientIdCallback uidToClientIdCallback_;
NicknameCallback nicknameCallback_; NicknameCallback nicknameCallback_;
std::mt19937 rng_{std::random_device{}()};
// Position tracking for periodic event updates // Position tracking for periodic event updates
std::chrono::steady_clock::time_point lastPositionUpdate_{}; std::chrono::steady_clock::time_point lastPositionUpdate_{};
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <TrackTypes.hpp>
#include <cstddef>
#include <cstdint>
#include <random>
#include <vector>
namespace Echoion::Core
{
// Owns the playback queue and its shuffle state. NOT thread-safe by
// design: the owning MusicManager serializes every access under its
// playback mutex_, so the single-lock model of the real-time loop is
// preserved. The containers are exposed by reference so the playback loop
// keeps operating on them with identical semantics.
class QueueManager
{
public:
using Entry = Api::QueueEntry;
[[nodiscard]] std::vector<Entry>& entries() noexcept
{
return entries_;
}
[[nodiscard]] const std::vector<Entry>& entries() const noexcept
{
return entries_;
}
[[nodiscard]] std::vector<std::size_t>& shuffledIndices() noexcept
{
return shuffledIndices_;
}
[[nodiscard]] std::size_t& shuffleIndex() noexcept
{
return shuffleIndex_;
}
[[nodiscard]] std::uint64_t& nextQueueId() noexcept
{
return nextQueueId_;
}
[[nodiscard]] std::mt19937& rng() noexcept { return rng_; }
private:
std::vector<Entry> entries_;
std::vector<std::size_t> shuffledIndices_;
std::size_t shuffleIndex_ = 0;
std::uint64_t nextQueueId_ = 1;
std::mt19937 rng_{std::random_device{}()};
};
} // namespace Echoion::Core
+94 -94
View File
@@ -210,7 +210,7 @@ namespace Echoion::Core
if (!isPlaying_ && !currentTrack_.has_value()) { if (!isPlaying_ && !currentTrack_.has_value()) {
currentTrack_ = currentTrack_ =
Api::QueueEntry{.queueId = nextQueueId_++, Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++,
.track = *track, .track = *track,
.addedAt = std::chrono::system_clock::now(), .addedAt = std::chrono::system_clock::now(),
.addedBy = nickname, .addedBy = nickname,
@@ -360,7 +360,7 @@ namespace Echoion::Core
if (needToStartThread || if (needToStartThread ||
(!playbackThreadRunning_ && (!playbackThreadRunning_ &&
(!queue_.empty() || currentTrack_.has_value()))) { (!queueMgr_.entries().empty() || currentTrack_.has_value()))) {
// Start the playback thread // Start the playback thread
isPlaying_ = true; isPlaying_ = true;
isPaused_ = false; isPaused_ = false;
@@ -394,7 +394,7 @@ namespace Echoion::Core
isPlaying_ = false; isPlaying_ = false;
isPaused_ = false; isPaused_ = false;
currentTrack_.reset(); currentTrack_.reset();
queue_.clear(); queueMgr_.entries().clear();
if (audioDecoder_) { if (audioDecoder_) {
audioDecoder_->closeSource(); audioDecoder_->closeSource();
@@ -422,7 +422,7 @@ namespace Echoion::Core
} }
for (uint32_t i = 0; i < count; ++i) { for (uint32_t i = 0; i < count; ++i) {
if (queue_.empty()) { if (queueMgr_.entries().empty()) {
if (repeat_ && currentTrack_.has_value()) { if (repeat_ && currentTrack_.has_value()) {
continue; continue;
} }
@@ -434,7 +434,7 @@ namespace Echoion::Core
auto nextTrack = getNextTrack(); auto nextTrack = getNextTrack();
currentTrack_ = currentTrack_ =
Api::QueueEntry{.queueId = nextQueueId_++, Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++,
.track = nextTrack, .track = nextTrack,
.addedAt = std::chrono::system_clock::now(), .addedAt = std::chrono::system_clock::now(),
.addedBy = currentTrack_->addedBy, .addedBy = currentTrack_->addedBy,
@@ -543,13 +543,13 @@ namespace Echoion::Core
{ {
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (queue_.size() >= config_.maxQueueSize) { if (queueMgr_.entries().size() >= config_.maxQueueSize) {
return Api::fail( return Api::fail(
Api::ErrorCode::InvalidArgument, "Queue is full"); Api::ErrorCode::InvalidArgument, "Queue is full");
} }
queueId = nextQueueId_++; queueId = queueMgr_.nextQueueId()++;
queue_.push_back( queueMgr_.entries().push_back(
Api::QueueEntry{.queueId = queueId, Api::QueueEntry{.queueId = queueId,
.track = track, .track = track,
.addedAt = std::chrono::system_clock::now(), .addedAt = std::chrono::system_clock::now(),
@@ -560,15 +560,15 @@ namespace Echoion::Core
// If shuffle is enabled, add the new track to shuffled indices // If shuffle is enabled, add the new track to shuffled indices
if (shuffle_) { if (shuffle_) {
// Insert at a random position among the remaining tracks // Insert at a random position among the remaining tracks
if (shuffleIndex_ < shuffledIndices_.size()) { if (queueMgr_.shuffleIndex() < queueMgr_.shuffledIndices().size()) {
std::uniform_int_distribution<size_t> dist( std::uniform_int_distribution<size_t> dist(
shuffleIndex_, shuffledIndices_.size()); queueMgr_.shuffleIndex(), queueMgr_.shuffledIndices().size());
size_t insertPos = dist(rng_); size_t insertPos = dist(queueMgr_.rng());
shuffledIndices_.insert(shuffledIndices_.begin() + queueMgr_.shuffledIndices().insert(queueMgr_.shuffledIndices().begin() +
insertPos, insertPos,
queue_.size() - 1); queueMgr_.entries().size() - 1);
} else { } else {
shuffledIndices_.push_back(queue_.size() - 1); queueMgr_.shuffledIndices().push_back(queueMgr_.entries().size() - 1);
} }
} }
@@ -580,7 +580,7 @@ namespace Echoion::Core
// this was the first track // this was the first track
shouldStart = !isPlaying_ && !isPaused_ && shouldStart = !isPlaying_ && !isPaused_ &&
!currentTrack_.has_value() && !currentTrack_.has_value() &&
hasOnlineSubscribers() && queue_.size() > 0; hasOnlineSubscribers() && queueMgr_.entries().size() > 0;
needToStartThread = needToStartThread =
!playbackThread_.joinable() && !playbackThreadRunning_; !playbackThread_.joinable() && !playbackThreadRunning_;
@@ -590,7 +590,7 @@ namespace Echoion::Core
"thread_joinable={}, thread_running={}, queue_size={}", "thread_joinable={}, thread_running={}, queue_size={}",
shouldStart, needToStartThread, isPlaying_.load(), shouldStart, needToStartThread, isPlaying_.load(),
playbackThread_.joinable(), playbackThreadRunning_.load(), playbackThread_.joinable(), playbackThreadRunning_.load(),
queue_.size())); queueMgr_.entries().size()));
} }
if (shouldStart) { if (shouldStart) {
@@ -637,31 +637,31 @@ namespace Echoion::Core
{ {
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (position >= queue_.size()) { if (position >= queueMgr_.entries().size()) {
return Api::fail(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid position"); "Invalid position");
} }
auto removedTrack = queue_[position]; auto removedTrack = queueMgr_.entries()[position];
queue_.erase(queue_.begin() + position); queueMgr_.entries().erase(queueMgr_.entries().begin() + position);
// Update shuffled indices if shuffle is enabled // Update shuffled indices if shuffle is enabled
if (shuffle_ && !shuffledIndices_.empty()) { if (shuffle_ && !queueMgr_.shuffledIndices().empty()) {
// Remove the index from shuffledIndices // Remove the index from shuffledIndices
auto it = std::find(shuffledIndices_.begin(), auto it = std::find(queueMgr_.shuffledIndices().begin(),
shuffledIndices_.end(), position); queueMgr_.shuffledIndices().end(), position);
if (it != shuffledIndices_.end()) { if (it != queueMgr_.shuffledIndices().end()) {
size_t removedShuffleIndex = size_t removedShuffleIndex =
std::distance(shuffledIndices_.begin(), it); std::distance(queueMgr_.shuffledIndices().begin(), it);
shuffledIndices_.erase(it); queueMgr_.shuffledIndices().erase(it);
// If we removed an index before the current shuffle position, // If we removed an index before the current shuffle position,
// decrement it // decrement it
if (removedShuffleIndex < shuffleIndex_) { if (removedShuffleIndex < queueMgr_.shuffleIndex()) {
shuffleIndex_--; queueMgr_.shuffleIndex()--;
} }
} }
// Decrement indices that were after the removed position // Decrement indices that were after the removed position
for (auto& idx : shuffledIndices_) { for (auto& idx : queueMgr_.shuffledIndices()) {
if (idx > position) { if (idx > position) {
idx--; idx--;
} }
@@ -675,7 +675,7 @@ namespace Echoion::Core
.track = removedTrack.track, .track = removedTrack.track,
.queueId = removedTrack.queueId, .queueId = removedTrack.queueId,
.removedByClientId = 0, .removedByClientId = 0,
.queueLength = static_cast<uint32_t>(queue_.size())}); .queueLength = static_cast<uint32_t>(queueMgr_.entries().size())});
return {}; return {};
} }
@@ -683,13 +683,13 @@ namespace Echoion::Core
Api::Result<void> MusicManager::clearQueue() Api::Result<void> MusicManager::clearQueue()
{ {
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
uint32_t previousLength = static_cast<uint32_t>(queue_.size()); uint32_t previousLength = static_cast<uint32_t>(queueMgr_.entries().size());
queue_.clear(); queueMgr_.entries().clear();
// Clear shuffle state // Clear shuffle state
if (shuffle_) { if (shuffle_) {
shuffledIndices_.clear(); queueMgr_.shuffledIndices().clear();
shuffleIndex_ = 0; queueMgr_.shuffleIndex() = 0;
} }
Void::Log::info("MusicManager", "{}", "Queue cleared"); Void::Log::info("MusicManager", "{}", "Queue cleared");
@@ -704,26 +704,26 @@ namespace Echoion::Core
Api::Result<std::vector<Api::QueueEntry>> MusicManager::getQueue() const Api::Result<std::vector<Api::QueueEntry>> MusicManager::getQueue() const
{ {
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
return queue_; return queueMgr_.entries();
} }
Api::Result<void> MusicManager::moveInQueue(uint32_t from, uint32_t to) Api::Result<void> MusicManager::moveInQueue(uint32_t from, uint32_t to)
{ {
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (from >= queue_.size() || to >= queue_.size()) { if (from >= queueMgr_.entries().size() || to >= queueMgr_.entries().size()) {
return Api::fail(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid position"); "Invalid position");
} }
auto entry = queue_[from]; auto entry = queueMgr_.entries()[from];
queue_.erase(queue_.begin() + from); queueMgr_.entries().erase(queueMgr_.entries().begin() + from);
queue_.insert(queue_.begin() + to, entry); queueMgr_.entries().insert(queueMgr_.entries().begin() + to, entry);
// Update shuffled indices if shuffle is enabled // Update shuffled indices if shuffle is enabled
if (shuffle_ && !shuffledIndices_.empty()) { if (shuffle_ && !queueMgr_.shuffledIndices().empty()) {
// Find and update indices that are affected by the move // Find and update indices that are affected by the move
for (auto& idx : shuffledIndices_) { for (auto& idx : queueMgr_.shuffledIndices()) {
if (from < to) { if (from < to) {
// Moving forward: indices in (from, to] decrement // Moving forward: indices in (from, to] decrement
if (idx > from && idx <= to) { if (idx > from && idx <= to) {
@@ -764,14 +764,14 @@ namespace Echoion::Core
if (shuffle_) { if (shuffle_) {
// Build shuffled indices for current queue // Build shuffled indices for current queue
rebuildShuffledIndices(); rebuildShuffledIndices();
shuffleIndex_ = 0; queueMgr_.shuffleIndex() = 0;
Void::Log::info("MusicManager", "{}", Void::Log::info("MusicManager", "{}",
std::format("Shuffle enabled - queue shuffled with {} tracks", std::format("Shuffle enabled - queue shuffled with {} tracks",
shuffledIndices_.size())); queueMgr_.shuffledIndices().size()));
} else { } else {
// Clear shuffle state // Clear shuffle state
shuffledIndices_.clear(); queueMgr_.shuffledIndices().clear();
shuffleIndex_ = 0; queueMgr_.shuffleIndex() = 0;
Void::Log::info("MusicManager", "{}", "Shuffle disabled"); Void::Log::info("MusicManager", "{}", "Shuffle disabled");
} }
@@ -784,37 +784,37 @@ namespace Echoion::Core
void MusicManager::rebuildShuffledIndices() void MusicManager::rebuildShuffledIndices()
{ {
shuffledIndices_.clear(); queueMgr_.shuffledIndices().clear();
shuffledIndices_.reserve(queue_.size()); queueMgr_.shuffledIndices().reserve(queueMgr_.entries().size());
// Create indices 0 to queue_size-1 // Create indices 0 to queue_size-1
for (size_t i = 0; i < queue_.size(); ++i) { for (size_t i = 0; i < queueMgr_.entries().size(); ++i) {
shuffledIndices_.push_back(i); queueMgr_.shuffledIndices().push_back(i);
} }
// Shuffle the indices using Fisher-Yates algorithm // Shuffle the indices using Fisher-Yates algorithm
std::shuffle(shuffledIndices_.begin(), shuffledIndices_.end(), rng_); std::shuffle(queueMgr_.shuffledIndices().begin(), queueMgr_.shuffledIndices().end(), queueMgr_.rng());
shuffleIndex_ = 0; queueMgr_.shuffleIndex() = 0;
Void::Log::debug("MusicManager", "{}", std::format("Rebuilt shuffled indices: {} tracks", Void::Log::debug("MusicManager", "{}", std::format("Rebuilt shuffled indices: {} tracks",
shuffledIndices_.size())); queueMgr_.shuffledIndices().size()));
} }
void MusicManager::reshuffleRemaining() void MusicManager::reshuffleRemaining()
{ {
if (shuffledIndices_.empty() || if (queueMgr_.shuffledIndices().empty() ||
shuffleIndex_ >= shuffledIndices_.size()) { queueMgr_.shuffleIndex() >= queueMgr_.shuffledIndices().size()) {
return; return;
} }
// Only reshuffle the remaining indices (from shuffleIndex_ onwards) // Only reshuffle the remaining indices (from queueMgr_.shuffleIndex() onwards)
// This preserves the already-played tracks order but reshuffles what's // This preserves the already-played tracks order but reshuffles what's
// left // left
std::shuffle(shuffledIndices_.begin() + shuffleIndex_, std::shuffle(queueMgr_.shuffledIndices().begin() + queueMgr_.shuffleIndex(),
shuffledIndices_.end(), rng_); queueMgr_.shuffledIndices().end(), queueMgr_.rng());
Void::Log::debug("MusicManager", "{}", std::format("Reshuffled remaining {} tracks", Void::Log::debug("MusicManager", "{}", std::format("Reshuffled remaining {} tracks",
shuffledIndices_.size() - shuffleIndex_)); queueMgr_.shuffledIndices().size() - queueMgr_.shuffleIndex()));
} }
Api::Result<bool> MusicManager::toggleRepeat() Api::Result<bool> MusicManager::toggleRepeat()
@@ -851,7 +851,7 @@ namespace Echoion::Core
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_ && !queue_.empty()) { if (!isPlaying_ && !queueMgr_.entries().empty()) {
cv_.notify_one(); cv_.notify_one();
Void::Log::info("MusicManager", "{}", Void::Log::info("MusicManager", "{}",
"Playback started from playlist"); "Playback started from playlist");
@@ -914,7 +914,7 @@ namespace Echoion::Core
Api::PlaybackState state; Api::PlaybackState state;
state.currentTrack = currentTrack_; state.currentTrack = currentTrack_;
state.queue = queue_; state.queue = queueMgr_.entries();
state.isPlaying = isPlaying_; state.isPlaying = isPlaying_;
state.isPaused = isPaused_; state.isPaused = isPaused_;
state.position = getPlaybackPosition(); state.position = getPlaybackPosition();
@@ -1011,7 +1011,7 @@ namespace Echoion::Core
// Build playback state directly (don't call getPlaybackState to avoid // Build playback state directly (don't call getPlaybackState to avoid
// double-lock) // double-lock)
state.playback.currentTrack = currentTrack_; state.playback.currentTrack = currentTrack_;
state.playback.queue = queue_; state.playback.queue = queueMgr_.entries();
state.playback.isPlaying = isPlaying_; state.playback.isPlaying = isPlaying_;
state.playback.isPaused = isPaused_; state.playback.isPaused = isPaused_;
// Calculate position directly using time-based tracking // Calculate position directly using time-based tracking
@@ -1029,7 +1029,7 @@ namespace Echoion::Core
state.playback.shuffle = shuffle_; state.playback.shuffle = shuffle_;
state.playback.lastUpdate = std::chrono::system_clock::now(); state.playback.lastUpdate = std::chrono::system_clock::now();
state.queue = queue_; state.queue = queueMgr_.entries();
if (currentTrack_ && currentTrack_->track.streamUrl) { if (currentTrack_ && currentTrack_->track.streamUrl) {
state.currentStreamUrl = currentTrack_->track.streamUrl; state.currentStreamUrl = currentTrack_->track.streamUrl;
@@ -1045,13 +1045,13 @@ namespace Echoion::Core
MusicManager::restoreFromHotReload(const Api::HotReloadState& state) MusicManager::restoreFromHotReload(const Api::HotReloadState& state)
{ {
config_ = state.config; config_ = state.config;
queue_ = state.queue; queueMgr_.entries() = state.queue;
volume_ = state.playback.volume; volume_ = state.playback.volume;
shuffle_ = state.playback.shuffle; shuffle_ = state.playback.shuffle;
repeat_ = state.playback.repeat; repeat_ = state.playback.repeat;
// Rebuild shuffle state if shuffle is enabled // Rebuild shuffle state if shuffle is enabled
if (shuffle_ && !queue_.empty()) { if (shuffle_ && !queueMgr_.entries().empty()) {
rebuildShuffledIndices(); rebuildShuffledIndices();
} }
@@ -1114,7 +1114,7 @@ namespace Echoion::Core
state.playback.currentTrack.has_value(), state.playback.currentTrack.has_value(),
state.currentStreamUrl.has_value())); state.currentStreamUrl.has_value()));
} }
if (!currentTrack_.has_value() && !queue_.empty() && if (!currentTrack_.has_value() && !queueMgr_.entries().empty() &&
hasOnlineSubscribers()) { hasOnlineSubscribers()) {
Void::Log::info("MusicManager", "{}", Void::Log::info("MusicManager", "{}",
"Playback not restored but queue has items, starting " "Playback not restored but queue has items, starting "
@@ -1142,7 +1142,7 @@ namespace Echoion::Core
std::jthread(&MusicManager::playbackThread, this); std::jthread(&MusicManager::playbackThread, this);
} }
cv_.notify_one(); cv_.notify_one();
} else if (state.playback.isPlaying && !queue_.empty()) { } else if (state.playback.isPlaying && !queueMgr_.entries().empty()) {
isPaused_ = true; isPaused_ = true;
isPlaying_ = true; isPlaying_ = true;
currentTrack_.reset(); currentTrack_.reset();
@@ -1205,13 +1205,13 @@ namespace Echoion::Core
std::unique_lock<std::shared_mutex> lock(mutex_); std::unique_lock<std::shared_mutex> lock(mutex_);
cv_.wait(lock, [this] { cv_.wait(lock, [this] {
return !isPlaying_ || !isPaused_ || return !isPlaying_ || !isPaused_ ||
(hasOnlineSubscribers() && !queue_.empty() && (hasOnlineSubscribers() && !queueMgr_.entries().empty() &&
!currentTrack_.has_value()); !currentTrack_.has_value());
}); });
// Auto-start if we have ONLINE subscribers and queue but no // Auto-start if we have ONLINE subscribers and queue but no
// current track // current track
if (hasOnlineSubscribers() && !queue_.empty() && if (hasOnlineSubscribers() && !queueMgr_.entries().empty() &&
!currentTrack_.has_value() && !wasPausedForNoSubscribers_) { !currentTrack_.has_value() && !wasPausedForNoSubscribers_) {
if (!isPlaying_) { if (!isPlaying_) {
isPlaying_ = true; isPlaying_ = true;
@@ -1229,8 +1229,8 @@ namespace Echoion::Core
} }
} }
// Start first track from queue // Start first track from queue
auto firstTrack = queue_.front(); auto firstTrack = queueMgr_.entries().front();
queue_.erase(queue_.begin()); queueMgr_.entries().erase(queueMgr_.entries().begin());
auto streamUrl = getStreamUrl(firstTrack.track); auto streamUrl = getStreamUrl(firstTrack.track);
if (streamUrl) { if (streamUrl) {
@@ -1521,7 +1521,7 @@ namespace Echoion::Core
Void::Log::debug("MusicManager", "{}", std::format( Void::Log::debug("MusicManager", "{}", std::format(
"Playback thread: isPlaying_={}, queue_size={}, " "Playback thread: isPlaying_={}, queue_size={}, "
"currentTrack.has_value={}", "currentTrack.has_value={}",
isPlaying_.load(), queue_.size(), isPlaying_.load(), queueMgr_.entries().size(),
currentTrack_.has_value())); currentTrack_.has_value()));
if (!isPlaying_) { if (!isPlaying_) {
Void::Log::info("MusicManager", "{}", Void::Log::info("MusicManager", "{}",
@@ -1634,7 +1634,7 @@ namespace Echoion::Core
return; return;
} }
if (queue_.empty()) { if (queueMgr_.entries().empty()) {
// Queue is empty - stop playback but keep thread running for next // Queue is empty - stop playback but keep thread running for next
// track // track
isPlaying_ = false; isPlaying_ = false;
@@ -1650,7 +1650,7 @@ namespace Echoion::Core
nextTrack.title, nextTrack.artist)); nextTrack.title, nextTrack.artist));
currentTrack_ = currentTrack_ =
Api::QueueEntry{.queueId = nextQueueId_++, Api::QueueEntry{.queueId = queueMgr_.nextQueueId()++,
.track = nextTrack, .track = nextTrack,
.addedAt = std::chrono::system_clock::now(), .addedAt = std::chrono::system_clock::now(),
.addedBy = currentTrack_->addedBy, .addedBy = currentTrack_->addedBy,
@@ -1704,41 +1704,41 @@ namespace Echoion::Core
Void::Log::error("MusicManager", "{}", std::format("Failed to open next track: {}", Void::Log::error("MusicManager", "{}", std::format("Failed to open next track: {}",
result.error().message)); result.error().message));
// Remove the failed track and try next // Remove the failed track and try next
queue_.erase(queue_.begin()); queueMgr_.entries().erase(queueMgr_.entries().begin());
onTrackFinished(); onTrackFinished();
} }
} else { } else {
Void::Log::error("MusicManager", "{}", "Failed to get stream URL for next track"); Void::Log::error("MusicManager", "{}", "Failed to get stream URL for next track");
queue_.erase(queue_.begin()); queueMgr_.entries().erase(queueMgr_.entries().begin());
onTrackFinished(); onTrackFinished();
} }
} }
Api::TrackInfo MusicManager::getNextTrack() Api::TrackInfo MusicManager::getNextTrack()
{ {
if (queue_.empty()) { if (queueMgr_.entries().empty()) {
return Api::TrackInfo{}; return Api::TrackInfo{};
} }
if (shuffle_ && !shuffledIndices_.empty()) { if (shuffle_ && !queueMgr_.shuffledIndices().empty()) {
// Use shuffled order // Use shuffled order
size_t queueIndex = shuffledIndices_[shuffleIndex_]; size_t queueIndex = queueMgr_.shuffledIndices()[queueMgr_.shuffleIndex()];
auto track = queue_[queueIndex].track; auto track = queueMgr_.entries()[queueIndex].track;
// Remove the track from queue and rebuild shuffled indices // Remove the track from queue and rebuild shuffled indices
queue_.erase(queue_.begin() + queueIndex); queueMgr_.entries().erase(queueMgr_.entries().begin() + queueIndex);
shuffleIndex_++; queueMgr_.shuffleIndex()++;
// If we've played all tracks, rebuild for next cycle // If we've played all tracks, rebuild for next cycle
if (shuffleIndex_ >= shuffledIndices_.size()) { if (queueMgr_.shuffleIndex() >= queueMgr_.shuffledIndices().size()) {
rebuildShuffledIndices(); rebuildShuffledIndices();
} else { } else {
// Rebuild indices to account for the removed track // Rebuild indices to account for the removed track
// Decrement indices that were after the removed track // Decrement indices that were after the removed track
for (size_t i = shuffleIndex_; i < shuffledIndices_.size(); for (size_t i = queueMgr_.shuffleIndex(); i < queueMgr_.shuffledIndices().size();
++i) { ++i) {
if (shuffledIndices_[i] > queueIndex) { if (queueMgr_.shuffledIndices()[i] > queueIndex) {
shuffledIndices_[i]--; queueMgr_.shuffledIndices()[i]--;
} }
} }
} }
@@ -1746,14 +1746,14 @@ namespace Echoion::Core
return track; return track;
} }
auto track = queue_.front().track; auto track = queueMgr_.entries().front().track;
queue_.erase(queue_.begin()); queueMgr_.entries().erase(queueMgr_.entries().begin());
return track; return track;
} }
Api::Result<void> MusicManager::shuffleQueue() Api::Result<void> MusicManager::shuffleQueue()
{ {
std::shuffle(queue_.begin(), queue_.end(), rng_); std::shuffle(queueMgr_.entries().begin(), queueMgr_.entries().end(), queueMgr_.rng());
return {}; return {};
} }
@@ -2074,7 +2074,7 @@ Subscriptions are persistent across server reconnects.)";
} }
// If we're not playing but have tracks in queue, auto-start // If we're not playing but have tracks in queue, auto-start
else if (!isPlaying_ && !currentTrack_.has_value() && else if (!isPlaying_ && !currentTrack_.has_value() &&
!queue_.empty()) { !queueMgr_.entries().empty()) {
Void::Log::info("MusicManager", "{}", "Online subscriber connected with tracks in " Void::Log::info("MusicManager", "{}", "Online subscriber connected with tracks in "
"queue, auto-starting"); "queue, auto-starting");
// Notify playback thread to start // Notify playback thread to start
@@ -2200,7 +2200,7 @@ Subscriptions are persistent across server reconnects.)";
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
// Don't prefetch if not playing, no current track, or queue is empty // Don't prefetch if not playing, no current track, or queue is empty
if (!isPlaying_ || !currentTrack_.has_value() || queue_.empty()) { if (!isPlaying_ || !currentTrack_.has_value() || queueMgr_.entries().empty()) {
return false; return false;
} }
@@ -2268,16 +2268,16 @@ Subscriptions are persistent across server reconnects.)";
Api::TrackInfo nextTrack; Api::TrackInfo nextTrack;
{ {
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (queue_.empty()) { if (queueMgr_.entries().empty()) {
prefetchState_.isPrefetching = false; prefetchState_.isPrefetching = false;
return; return;
} }
// Use shuffled order if shuffle is enabled // Use shuffled order if shuffle is enabled
if (shuffle_ && !shuffledIndices_.empty() && if (shuffle_ && !queueMgr_.shuffledIndices().empty() &&
shuffleIndex_ < shuffledIndices_.size()) { queueMgr_.shuffleIndex() < queueMgr_.shuffledIndices().size()) {
nextTrack = queue_[shuffledIndices_[shuffleIndex_]].track; nextTrack = queueMgr_.entries()[queueMgr_.shuffledIndices()[queueMgr_.shuffleIndex()]].track;
} else { } else {
nextTrack = queue_[0].track; nextTrack = queueMgr_.entries()[0].track;
} }
} }