fix(queue): implement proper Fisher-Yates shuffle algorithm

Previous implementation had a critical bug in the shuffle algorithm
that used the same seed value for all iterations, resulting in
weak/predictable shuffling.

Changes:
- Add rand crate dependency for proper PRNG
- Fix Fisher-Yates to use unique random value per iteration
- Use StdRng with timestamp-based seed for reproducible randomness
- Each shuffle iteration now gets a new random number from the RNG

This fixes shuffle working inconsistently across different contexts
(albums, playlists, continuous play).

cc
This commit is contained in:
vicrodh committed 2026-01-19 18:17:04 -06:00
1 parent 603b794838
commit 0bbf6435b4
2 files changed
+11 -3

No files matched your search

+3
View File
@@ -45,6 +45,9 @@ anyhow = "1"
log = "0.4" log = "0.4"
env_logger = "0.11" env_logger = "0.11"
# Random number generation (for shuffle)
rand = "0.8"
# Audio playback # Audio playback
rodio = { version = "0.19", features = ["symphonia-all"] } rodio = { version = "0.19", features = ["symphonia-all"] }
symphonia = { version = "0.5", features = ["all"] } symphonia = { version = "0.5", features = ["all"] }
+8 -3
View File
@@ -508,15 +508,20 @@ impl QueueManager {
fn regenerate_shuffle_order_internal(state: &mut InternalState) { fn regenerate_shuffle_order_internal(state: &mut InternalState) {
let mut order: Vec<usize> = (0..state.tracks.len()).collect(); let mut order: Vec<usize> = (0..state.tracks.len()).collect();
// Fisher-Yates shuffle // Fisher-Yates shuffle with proper PRNG
use rand::{Rng, SeedableRng};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
// Create seeded RNG from current timestamp
let seed = SystemTime::now() let seed = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.unwrap_or_default() .unwrap_or_default()
.as_nanos() as usize; .as_nanos() as u64;
let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
// Proper Fisher-Yates shuffle - each iteration gets a NEW random number
for i in (1..order.len()).rev() { for i in (1..order.len()).rev() {
let j = (seed.wrapping_mul(i + 1)) % (i + 1); let j = rng.gen_range(0..=i);
order.swap(i, j); order.swap(i, j);
} }