#pragma once #include #include #include #include #include #include #include namespace Echoion::Core { // Owns the playback queue, shuffle order and repeat flag. Self-locking: // every public method takes the internal mutex, so callers never manage // queue locks (the old QueueManager exposed raw references and relied on // MusicManager's shared_mutex, which several writers acquired shared). // // Shuffle model: shuffledIndices_ is a permutation of positions into // entries_; shuffleIndex_ is the cursor of the next shuffled pick. // Removing/moving/adding entries fixes the permutation up in place, so // already-played order is preserved. class QueueService { public: using Entry = Api::QueueEntry; // ---- mutation ------------------------------------------------- // Appends a track. Fails when the queue is at maxSize. Api::Result enqueue(const Api::TrackInfo& track, std::string addedBy, std::size_t maxSize); // Removes the entry at `position`; returns it for event payloads. Api::Result removeAt(uint32_t position); // Returns the number of entries removed. uint32_t clear(); // Moves an entry; returns its queueId for event payloads. Api::Result move(uint32_t from, uint32_t to); // Pops the next entry honouring shuffle order. std::optional popNext(); // Pops the next entry only if it is still the given one — the // gapless engine peeks, warms a decoder, and commits at the swap; // queue edits in between invalidate the warm slot. std::optional popIfNext(uint64_t queueId); // Replace the whole queue (hot-reload restore). void replaceAll(std::vector entries); // In-place random shuffle of the raw order (legacy !shufflequeue). void shuffleInPlace(); // ---- shuffle / repeat ----------------------------------------- bool toggleShuffle(); void setShuffle(bool enabled); [[nodiscard]] bool shuffleEnabled() const; bool toggleRepeat(); void setRepeat(bool enabled); [[nodiscard]] bool repeatEnabled() const; // ---- inspection ----------------------------------------------- [[nodiscard]] std::optional peekNext() const; [[nodiscard]] std::vector snapshot() const; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool empty() const; // Allocate a queue id for entries created outside the queue (the // immediately-played track in play()). [[nodiscard]] uint64_t allocateQueueId(); private: // All *Locked helpers assume mutex_ is held. void rebuildShuffledIndicesLocked(); [[nodiscard]] std::optional nextPositionLocked() const; std::optional popNextLocked(); mutable std::mutex mutex_; std::vector entries_; std::vector shuffledIndices_; std::size_t shuffleIndex_ = 0; uint64_t nextQueueId_ = 1; bool shuffle_ = false; bool repeat_ = false; std::mt19937 rng_{std::random_device{}()}; }; } // namespace Echoion::Core