Skip to content

Commit

Permalink
Using SmallRng for white noise generation
Browse files Browse the repository at this point in the history
This resolves a PR code review note and should make the source run
much faster.
  • Loading branch information
iluvcapra committed Aug 13, 2024
1 parent 84a008d commit a015eb4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ minimp3_fixed = { version = "0.5.4", optional = true}
symphonia = { version = "0.5.4", optional = true, default-features = false }
crossbeam-channel = { version = "0.5.8", optional = true }
thiserror = "1.0.49"
rand = "0.8.5"
rand = {version = "0.8.5", features = ["small_rng"]}

[features]
default = ["flac", "vorbis", "wav", "mp3"]
Expand Down
11 changes: 9 additions & 2 deletions src/source/noise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ use crate::Source;

use super::SeekError;

use rand::rngs::SmallRng;
use rand::{RngCore, SeedableRng};

/// Create a new white noise source.
#[inline]
pub fn white(sample_rate: cpal::SampleRate) -> WhiteNoise {
Expand All @@ -18,12 +21,16 @@ pub fn pink(sample_rate: cpal::SampleRate) -> PinkNoise {
#[derive(Clone, Debug)]
pub struct WhiteNoise {
sample_rate: cpal::SampleRate,
rng: SmallRng,
}

impl WhiteNoise {
/// Create a new white noise generator.
pub fn new(sample_rate: cpal::SampleRate) -> Self {
Self { sample_rate }
Self {
sample_rate,
rng: SmallRng::from_entropy(),
}
}
}

Expand All @@ -32,7 +39,7 @@ impl Iterator for WhiteNoise {

#[inline]
fn next(&mut self) -> Option<Self::Item> {
let randf = rand::random::<f32>();
let randf = self.rng.next_u32() as f32 / u32::MAX as f32;
let scaled = randf * 2.0 - 1.0;
Some(scaled)
}
Expand Down

0 comments on commit a015eb4

Please sign in to comment.