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