From 0bbf6435b4fc329eed16e7d1f89986ed28dc490d Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 19 Jan 2026 18:03:23 -0600 Subject: [PATCH] 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 --- src-tauri/Cargo.toml | 3 +++ src-tauri/src/queue/mod.rs | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index f369abee4..675943d57 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -45,6 +45,9 @@ anyhow = "1" log = "0.4" env_logger = "0.11" +# Random number generation (for shuffle) +rand = "0.8" + # Audio playback rodio = { version = "0.19", features = ["symphonia-all"] } symphonia = { version = "0.5", features = ["all"] } diff --git a/src-tauri/src/queue/mod.rs b/src-tauri/src/queue/mod.rs index 4aac2f88d..c0c9df9fe 100644 --- a/src-tauri/src/queue/mod.rs +++ b/src-tauri/src/queue/mod.rs @@ -508,15 +508,20 @@ impl QueueManager { fn regenerate_shuffle_order_internal(state: &mut InternalState) { let mut order: Vec = (0..state.tracks.len()).collect(); - // Fisher-Yates shuffle + // Fisher-Yates shuffle with proper PRNG + use rand::{Rng, SeedableRng}; use std::time::{SystemTime, UNIX_EPOCH}; + + // Create seeded RNG from current timestamp let seed = SystemTime::now() .duration_since(UNIX_EPOCH) .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() { - let j = (seed.wrapping_mul(i + 1)) % (i + 1); + let j = rng.gen_range(0..=i); order.swap(i, j); }