use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use bevy::audio::{AddAudioSource, AudioPlugin, Sample as RodioSample, Source as RodioSource};
use bevy::prelude::*;
use bevy::reflect::TypePath;
use crate::world::{VoxelBroken, VoxelPlaced};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SfxEvent {
Mining,
MiningComplete,
BlockPlace,
ItemPickup,
HotbarScroll,
PauseOpen,
PauseClose,
Footstep(u8),
Custom(String),
}
impl SfxEvent {
pub fn key(&self) -> String {
match self {
SfxEvent::Mining => "Mining".to_string(),
SfxEvent::MiningComplete => "MiningComplete".to_string(),
SfxEvent::BlockPlace => "BlockPlace".to_string(),
SfxEvent::ItemPickup => "ItemPickup".to_string(),
SfxEvent::HotbarScroll => "HotbarScroll".to_string(),
SfxEvent::PauseOpen => "PauseOpen".to_string(),
SfxEvent::PauseClose => "PauseClose".to_string(),
SfxEvent::Footstep(surface) => format!("Footstep:{surface}"),
SfxEvent::Custom(s) => format!("Custom:{s}"),
}
}
}
#[derive(Message, Debug, Clone)]
pub struct SfxRequest {
pub event: SfxEvent,
pub position: Option<Vec3>,
}
#[derive(Message, Debug, Clone)]
#[non_exhaustive]
pub struct PitchedSfxRequest {
pub event: SfxEvent,
pub position: Option<Vec3>,
pub pitch: f32,
}
impl PitchedSfxRequest {
pub const MIN_PITCH: f32 = 0.1;
pub const MAX_PITCH: f32 = 8.0;
pub fn new(event: SfxEvent, pitch: f32) -> Self {
Self {
event,
position: None,
pitch,
}
}
pub fn at(mut self, position: Vec3) -> Self {
self.position = Some(position);
self
}
pub fn effective_pitch(&self) -> f32 {
if self.pitch.is_finite() && self.pitch > 0.0 {
self.pitch.clamp(Self::MIN_PITCH, Self::MAX_PITCH)
} else {
1.0
}
}
}
#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct SfxFilter {
pub low_pass_hz: Option<f32>,
}
impl SfxFilter {
pub const NONE: Self = Self { low_pass_hz: None };
pub const MIN_LOW_PASS_HZ: f32 = 20.0;
pub const MAX_LOW_PASS_HZ: f32 = 20_000.0;
pub const fn low_pass(cutoff_hz: f32) -> Self {
Self {
low_pass_hz: Some(cutoff_hz),
}
}
pub fn effective_low_pass_hz(&self) -> Option<f32> {
let hz = self.low_pass_hz?;
if hz.is_finite() && hz > 0.0 {
Some(hz.clamp(Self::MIN_LOW_PASS_HZ, Self::MAX_LOW_PASS_HZ))
} else {
None
}
}
pub fn is_active(&self) -> bool {
self.effective_low_pass_hz().is_some()
}
}
#[derive(Resource, Debug, Clone)]
pub struct SfxConfig {
pub sounds: HashMap<String, Vec<String>>,
pub volume: f32,
}
impl SfxConfig {
pub fn new() -> Self {
Self {
sounds: HashMap::new(),
volume: 1.0,
}
}
pub fn register(&mut self, event: SfxEvent, paths: Vec<&str>) {
self.sounds.insert(
event.key(),
paths.into_iter().map(|p| p.to_string()).collect(),
);
}
pub fn get_paths(&self, event: &SfxEvent) -> Option<&Vec<String>> {
self.sounds.get(&event.key())
}
pub fn pick_path(&self, event: &SfxEvent, seed: u64) -> Option<&str> {
let paths = self.get_paths(event)?;
if paths.is_empty() {
return None;
}
let index = (seed % paths.len() as u64) as usize;
Some(paths[index].as_str())
}
}
impl Default for SfxConfig {
fn default() -> Self {
Self::new()
}
}
pub fn mining_sfx_system(
mut broken_reader: MessageReader<VoxelBroken>,
mut sfx_writer: MessageWriter<SfxRequest>,
) {
for broken in broken_reader.read() {
sfx_writer.write(SfxRequest {
event: SfxEvent::MiningComplete,
position: Some(broken.world_pos),
});
}
}
pub fn placement_sfx_system(
mut placed_reader: MessageReader<VoxelPlaced>,
mut sfx_writer: MessageWriter<SfxRequest>,
) {
for placed in placed_reader.read() {
sfx_writer.write(SfxRequest {
event: SfxEvent::BlockPlace,
position: Some(placed.world_pos),
});
}
}
pub struct SfxPlugin;
impl Plugin for SfxPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<SfxConfig>();
app.add_message::<SfxRequest>();
app.add_message::<PitchedSfxRequest>();
app.add_systems(Update, (mining_sfx_system, placement_sfx_system));
}
}
#[derive(Resource, Default)]
struct SfxCounter(HashMap<String, u64>);
pub struct DefaultAudioPlugin;
impl Plugin for DefaultAudioPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<SfxCounter>();
app.init_resource::<SfxFilter>();
app.add_message::<PitchedSfxRequest>();
app.add_systems(Update, play_sfx_system);
}
fn finish(&self, app: &mut App) {
if app.is_plugin_added::<AudioPlugin>() && app.world().contains_resource::<AssetServer>() {
app.add_audio_source::<LowPassSfx>();
install_low_pass_backend(app);
}
}
}
fn install_low_pass_backend(app: &mut App) {
app.init_resource::<SfxFilterShared>()
.init_resource::<LowPassSfxCache>()
.add_systems(
Update,
(
sync_sfx_filter_system.before(play_sfx_system),
resolve_low_pass_sfx_system.after(play_sfx_system),
),
);
}
fn play_sfx_system(
mut sfx_reader: MessageReader<SfxRequest>,
mut pitched_reader: MessageReader<PitchedSfxRequest>,
config: Res<SfxConfig>,
asset_server: Res<AssetServer>,
mut counter: ResMut<SfxCounter>,
(filter, low_pass_backend): (Option<Res<SfxFilter>>, Option<Res<SfxFilterShared>>),
mut commands: Commands,
) {
let low_pass = low_pass_backend.is_some() && filter.is_some_and(|filter| filter.is_active());
let plain = sfx_reader
.read()
.map(|request| (&request.event, request.position, 1.0_f32));
let pitched = pitched_reader
.read()
.map(|request| (&request.event, request.position, request.effective_pitch()));
for (event, position, speed) in plain.chain(pitched) {
let seed = {
let c = counter.0.entry(event.key()).or_insert(0);
let s = *c;
*c = c.wrapping_add(1);
s
};
let Some(path) = config.pick_path(event, seed).map(|p| p.to_owned()) else {
continue;
};
let source: Handle<AudioSource> = asset_server.load(path);
let mut settings = PlaybackSettings::ONCE;
settings.volume = bevy::audio::Volume::Linear(config.volume);
settings.speed = speed;
let mut entity = if low_pass {
commands.spawn((PendingLowPassSfx(source), settings))
} else {
commands.spawn((AudioPlayer(source), settings))
};
if let Some(pos) = position {
entity.insert(Transform::from_translation(pos));
}
}
}
#[derive(Resource, Default)]
struct SfxFilterShared(Arc<AtomicU32>);
#[derive(Resource, Default)]
struct LowPassSfxCache(HashMap<AssetId<AudioSource>, (Handle<AudioSource>, Handle<LowPassSfx>)>);
#[derive(Component)]
struct PendingLowPassSfx(Handle<AudioSource>);
#[derive(Asset, TypePath)]
struct LowPassSfx {
source: AudioSource,
cutoff: Arc<AtomicU32>,
}
impl Decodable for LowPassSfx {
type DecoderItem = f32;
type Decoder = LowPassSource<<AudioSource as Decodable>::Decoder>;
fn decoder(&self) -> Self::Decoder {
LowPassSource::new(self.source.decoder(), self.cutoff.clone())
}
}
fn sync_sfx_filter_system(filter: Option<Res<SfxFilter>>, shared: Res<SfxFilterShared>) {
let cutoff_hz = filter
.and_then(|filter| filter.effective_low_pass_hz())
.unwrap_or(0.0);
shared.0.store(cutoff_hz.to_bits(), Ordering::Relaxed);
}
fn resolve_low_pass_sfx_system(
pending: Query<(Entity, &PendingLowPassSfx)>,
sources: Res<Assets<AudioSource>>,
mut filtered: ResMut<Assets<LowPassSfx>>,
asset_server: Res<AssetServer>,
shared: Res<SfxFilterShared>,
mut cache: ResMut<LowPassSfxCache>,
mut commands: Commands,
) {
for (entity, pending) in &pending {
let id = pending.0.id();
if let Some(source) = sources.get(id) {
let handle = match cache.0.get(&id) {
Some((_, handle)) => handle.clone(),
None => {
let handle = filtered.add(LowPassSfx {
source: source.clone(),
cutoff: shared.0.clone(),
});
cache.0.insert(id, (pending.0.clone(), handle.clone()));
handle
}
};
commands
.entity(entity)
.insert(AudioPlayer::<LowPassSfx>(handle))
.remove::<PendingLowPassSfx>();
} else if asset_server.load_state(id).is_failed() {
commands.entity(entity).despawn();
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct LowPassCoefficients {
b0: f32,
b1: f32,
b2: f32,
a1: f32,
a2: f32,
}
impl LowPassCoefficients {
fn new(cutoff_hz: f32, sample_rate: u32) -> Option<Self> {
if !cutoff_hz.is_finite() || cutoff_hz <= 0.0 || sample_rate == 0 {
return None;
}
let sample_rate = sample_rate as f32;
if cutoff_hz >= sample_rate * 0.45 {
return None;
}
let w0 = std::f32::consts::TAU * cutoff_hz / sample_rate;
let (sin, cos) = w0.sin_cos();
let alpha = sin / (2.0 * std::f32::consts::FRAC_1_SQRT_2);
let a0 = 1.0 + alpha;
Some(Self {
b0: (1.0 - cos) * 0.5 / a0,
b1: (1.0 - cos) / a0,
b2: (1.0 - cos) * 0.5 / a0,
a1: -2.0 * cos / a0,
a2: (1.0 - alpha) / a0,
})
}
}
#[derive(Debug, Clone, Copy, Default)]
struct LowPassHistory {
x1: f32,
x2: f32,
y1: f32,
y2: f32,
}
impl LowPassHistory {
fn process(&mut self, coefficients: Option<LowPassCoefficients>, input: f32) -> f32 {
let x = if input.is_finite() { input } else { 0.0 };
let filtered = coefficients.map(|c| {
let y = c.b0 * x + c.b1 * self.x1 + c.b2 * self.x2 - c.a1 * self.y1 - c.a2 * self.y2;
if y.is_finite() { y.clamp(-1.0, 1.0) } else { x }
});
let y = filtered.unwrap_or(x);
self.x2 = self.x1;
self.x1 = x;
self.y2 = self.y1;
self.y1 = y;
filtered.unwrap_or(input)
}
}
struct LowPassSource<S> {
inner: S,
cutoff: Arc<AtomicU32>,
cutoff_bits: u32,
sample_rate: u32,
coefficients: Option<LowPassCoefficients>,
history: Vec<LowPassHistory>,
channel: usize,
}
impl<S> LowPassSource<S>
where
S: RodioSource,
S::Item: RodioSample,
{
fn new(inner: S, cutoff: Arc<AtomicU32>) -> Self {
Self {
inner,
cutoff,
cutoff_bits: 0,
sample_rate: 0,
coefficients: None,
history: Vec::new(),
channel: 0,
}
}
}
impl<S> Iterator for LowPassSource<S>
where
S: RodioSource,
S::Item: RodioSample,
{
type Item = f32;
fn next(&mut self) -> Option<f32> {
let channels = usize::from(self.inner.channels().max(1));
let sample_rate = self.inner.sample_rate();
let sample = RodioSample::to_f32(self.inner.next()?);
if self.history.len() != channels {
self.history.clear();
self.history.resize(channels, LowPassHistory::default());
self.channel = 0;
}
let cutoff_bits = self.cutoff.load(Ordering::Relaxed);
if cutoff_bits != self.cutoff_bits || sample_rate != self.sample_rate {
self.cutoff_bits = cutoff_bits;
self.sample_rate = sample_rate;
self.coefficients = LowPassCoefficients::new(f32::from_bits(cutoff_bits), sample_rate);
}
let channel = self.channel;
self.channel = (channel + 1) % channels;
let coefficients = self.coefficients;
Some(self.history[channel].process(coefficients, sample))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<S> RodioSource for LowPassSource<S>
where
S: RodioSource,
S::Item: RodioSample,
{
fn current_frame_len(&self) -> Option<usize> {
self.inner.current_frame_len()
}
fn channels(&self) -> u16 {
self.inner.channels()
}
fn sample_rate(&self) -> u32 {
self.inner.sample_rate()
}
fn total_duration(&self) -> Option<Duration> {
self.inner.total_duration()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn config_with_paths() -> SfxConfig {
let mut cfg = SfxConfig::new();
cfg.register(
SfxEvent::BlockPlace,
vec![
"sounds/place1.ogg",
"sounds/place2.ogg",
"sounds/place3.ogg",
],
);
cfg
}
#[test]
fn test_sfx_config_pick_deterministic() {
let cfg = config_with_paths();
let first = cfg.pick_path(&SfxEvent::BlockPlace, 0);
let second = cfg.pick_path(&SfxEvent::BlockPlace, 0);
assert_eq!(first, second, "same seed must always produce the same path");
}
#[test]
fn test_sfx_config_pick_wraps() {
let cfg = config_with_paths();
let path = cfg.pick_path(&SfxEvent::BlockPlace, 5);
assert!(
path.is_some(),
"seed > paths.len() must still return a valid path"
);
assert_eq!(path.unwrap(), "sounds/place3.ogg");
}
#[test]
fn test_sfx_config_returns_none_for_unregistered_event() {
let cfg = SfxConfig::new();
assert!(cfg.pick_path(&SfxEvent::Mining, 0).is_none());
}
#[test]
fn test_sfx_config_get_paths() {
let cfg = config_with_paths();
let paths = cfg.get_paths(&SfxEvent::BlockPlace).unwrap();
assert_eq!(paths.len(), 3);
}
#[test]
fn test_sfx_event_key_custom() {
let event = SfxEvent::Custom("footstep".to_string());
assert_eq!(event.key(), "Custom:footstep");
}
#[test]
fn pitched_request_builder_sets_fields() {
let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5);
assert_eq!(request.event, SfxEvent::ItemPickup);
assert_eq!(request.position, None);
assert_eq!(request.effective_pitch(), 1.5);
let positioned = request.at(Vec3::new(1.0, 2.0, 3.0));
assert_eq!(positioned.position, Some(Vec3::new(1.0, 2.0, 3.0)));
}
#[test]
fn invalid_pitch_plays_at_normal_speed() {
for pitch in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -0.0, -2.0] {
let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch);
assert_eq!(request.effective_pitch(), 1.0, "pitch {pitch}");
}
}
#[test]
fn extreme_pitch_is_clamped() {
let low = PitchedSfxRequest::new(SfxEvent::ItemPickup, 0.0001);
let high = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1000.0);
assert_eq!(low.effective_pitch(), PitchedSfxRequest::MIN_PITCH);
assert_eq!(high.effective_pitch(), PitchedSfxRequest::MAX_PITCH);
}
#[test]
fn filter_is_off_by_default() {
assert_eq!(SfxFilter::default(), SfxFilter::NONE);
assert_eq!(SfxFilter::default().effective_low_pass_hz(), None);
assert!(!SfxFilter::default().is_active());
}
#[test]
fn invalid_cutoff_disables_the_filter() {
for hz in [
f32::NAN,
f32::INFINITY,
f32::NEG_INFINITY,
0.0,
-0.0,
-500.0,
] {
let filter = SfxFilter::low_pass(hz);
assert_eq!(filter.effective_low_pass_hz(), None, "cutoff {hz}");
assert!(!filter.is_active(), "cutoff {hz}");
}
}
#[test]
fn valid_cutoff_is_kept_and_clamped() {
assert_eq!(
SfxFilter::low_pass(800.0).effective_low_pass_hz(),
Some(800.0)
);
assert_eq!(
SfxFilter::low_pass(1.0).effective_low_pass_hz(),
Some(SfxFilter::MIN_LOW_PASS_HZ)
);
assert_eq!(
SfxFilter::low_pass(1.0e9).effective_low_pass_hz(),
Some(SfxFilter::MAX_LOW_PASS_HZ)
);
}
fn headless_app() -> App {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()));
app.init_asset::<AudioSource>();
app.add_message::<SfxRequest>();
let mut config = SfxConfig::new();
config.register(SfxEvent::ItemPickup, vec!["sounds/pickup.ogg"]);
config.volume = 0.5;
app.insert_resource(config);
app.add_plugins(DefaultAudioPlugin);
app
}
fn headless_app_with_low_pass() -> App {
let mut app = headless_app();
app.init_asset::<LowPassSfx>();
install_low_pass_backend(&mut app);
app
}
struct Spawned {
settings: PlaybackSettings,
plain: bool,
pending: bool,
filtered: bool,
translation: Option<Vec3>,
}
fn spawned_sounds(app: &mut App) -> Vec<Spawned> {
let world = app.world_mut();
let mut query = world.query::<(
&PlaybackSettings,
Has<AudioPlayer<AudioSource>>,
Has<PendingLowPassSfx>,
Has<AudioPlayer<LowPassSfx>>,
Option<&Transform>,
)>();
query
.iter(world)
.map(|(settings, plain, pending, filtered, transform)| Spawned {
settings: *settings,
plain,
pending,
filtered,
translation: transform.map(|transform| transform.translation),
})
.collect()
}
fn shared_cutoff(app: &App) -> f32 {
f32::from_bits(
app.world()
.resource::<SfxFilterShared>()
.0
.load(Ordering::Relaxed),
)
}
#[test]
fn sfx_plugin_registers_pitched_requests() {
let mut app = App::new();
app.add_message::<VoxelBroken>();
app.add_message::<VoxelPlaced>();
app.add_plugins(SfxPlugin);
assert!(
app.world()
.contains_resource::<bevy::ecs::message::Messages<PitchedSfxRequest>>()
);
}
#[test]
fn plain_request_plays_with_unchanged_settings() {
let mut app = headless_app_with_low_pass();
assert_eq!(*app.world().resource::<SfxFilter>(), SfxFilter::NONE);
app.world_mut().write_message(SfxRequest {
event: SfxEvent::ItemPickup,
position: Some(Vec3::new(4.0, 5.0, 6.0)),
});
app.update();
let sounds = spawned_sounds(&mut app);
assert_eq!(sounds.len(), 1);
let sound = &sounds[0];
assert!(sound.plain && !sound.pending && !sound.filtered);
assert_eq!(sound.settings.speed, 1.0);
assert_eq!(sound.settings.volume, bevy::audio::Volume::Linear(0.5));
assert!(matches!(
sound.settings.mode,
bevy::audio::PlaybackMode::Once
));
assert!(!sound.settings.spatial);
assert_eq!(sound.translation, Some(Vec3::new(4.0, 5.0, 6.0)));
}
#[test]
fn pitched_request_sets_playback_speed() {
let mut app = headless_app();
app.world_mut()
.write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5));
app.world_mut()
.write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, f32::NAN).at(Vec3::X));
app.update();
let sounds = spawned_sounds(&mut app);
assert_eq!(sounds.len(), 2);
let pitched = sounds
.iter()
.find(|sound| sound.translation.is_none())
.expect("the request without a position");
let invalid = sounds
.iter()
.find(|sound| sound.translation == Some(Vec3::X))
.expect("the request with a position");
assert!(pitched.plain);
assert_eq!(pitched.settings.speed, 1.5);
assert_eq!(pitched.settings.volume, bevy::audio::Volume::Linear(0.5));
assert!(invalid.plain);
assert_eq!(invalid.settings.speed, 1.0);
}
#[test]
fn pitched_request_for_unregistered_event_plays_nothing() {
let mut app = headless_app();
app.world_mut()
.write_message(PitchedSfxRequest::new(SfxEvent::Mining, 1.5));
app.update();
assert!(spawned_sounds(&mut app).is_empty());
}
#[test]
fn active_filter_holds_the_sound_for_the_low_pass_path() {
let mut app = headless_app_with_low_pass();
app.insert_resource(SfxFilter::low_pass(800.0));
app.world_mut()
.write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 2.0).at(Vec3::Y));
app.update();
let sounds = spawned_sounds(&mut app);
assert_eq!(sounds.len(), 1);
let sound = &sounds[0];
assert!(!sound.plain && !sound.filtered);
assert!(sound.pending);
assert_eq!(sound.settings.speed, 2.0);
assert_eq!(sound.translation, Some(Vec3::Y));
assert_eq!(shared_cutoff(&app), 800.0);
}
#[test]
fn filtered_sound_whose_source_fails_to_load_is_despawned() {
let mut app = headless_app_with_low_pass();
app.insert_resource(SfxFilter::low_pass(800.0));
app.world_mut()
.write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.0));
app.update();
assert_eq!(spawned_sounds(&mut app).len(), 1);
for _ in 0..500 {
if spawned_sounds(&mut app).is_empty() {
break;
}
std::thread::sleep(Duration::from_millis(10));
app.update();
}
assert!(
spawned_sounds(&mut app).is_empty(),
"a sound that can never be decoded must not wait forever"
);
}
#[test]
fn loaded_source_is_played_through_the_filtered_asset() {
let mut app = headless_app_with_low_pass();
let bytes: Arc<[u8]> = Arc::from(vec![1_u8, 2, 3]);
let source = app
.world_mut()
.resource_mut::<Assets<AudioSource>>()
.add(AudioSource {
bytes: bytes.clone(),
});
let settings = PlaybackSettings::ONCE.with_speed(1.5);
let first = app
.world_mut()
.spawn((PendingLowPassSfx(source.clone()), settings))
.id();
let second = app
.world_mut()
.spawn((PendingLowPassSfx(source.clone()), settings))
.id();
app.update();
let sounds = spawned_sounds(&mut app);
assert_eq!(sounds.len(), 2);
for sound in &sounds {
assert!(sound.filtered && !sound.pending && !sound.plain);
assert_eq!(sound.settings.speed, 1.5);
}
let first_handle = app
.world()
.get::<AudioPlayer<LowPassSfx>>(first)
.expect("filtered player")
.0
.clone();
let second_handle = app
.world()
.get::<AudioPlayer<LowPassSfx>>(second)
.expect("filtered player")
.0
.clone();
assert_eq!(first_handle, second_handle, "one filtered asset per source");
let shared = app.world().resource::<SfxFilterShared>().0.clone();
let filtered = app
.world()
.resource::<Assets<LowPassSfx>>()
.get(&first_handle)
.expect("filtered asset");
assert!(Arc::ptr_eq(&filtered.source.bytes, &bytes));
assert!(Arc::ptr_eq(&filtered.cutoff, &shared));
}
#[test]
fn invalid_cutoff_plays_unfiltered() {
for hz in [f32::NAN, -100.0, 0.0] {
let mut app = headless_app_with_low_pass();
app.insert_resource(SfxFilter::low_pass(hz));
app.world_mut().write_message(SfxRequest {
event: SfxEvent::ItemPickup,
position: None,
});
app.update();
let sounds = spawned_sounds(&mut app);
assert_eq!(sounds.len(), 1, "cutoff {hz}");
assert!(sounds[0].plain && !sounds[0].pending, "cutoff {hz}");
assert_eq!(shared_cutoff(&app), 0.0, "cutoff {hz}");
}
}
#[test]
fn missing_filter_resource_plays_unfiltered() {
let mut app = headless_app_with_low_pass();
app.insert_resource(SfxFilter::low_pass(800.0));
app.update();
assert_eq!(shared_cutoff(&app), 800.0);
app.world_mut().remove_resource::<SfxFilter>();
app.world_mut().write_message(SfxRequest {
event: SfxEvent::ItemPickup,
position: None,
});
app.update();
let sounds = spawned_sounds(&mut app);
assert_eq!(sounds.len(), 1);
assert!(sounds[0].plain && !sounds[0].pending);
assert_eq!(shared_cutoff(&app), 0.0);
}
#[test]
fn filter_without_audio_backend_plays_unfiltered() {
let mut app = headless_app();
app.insert_resource(SfxFilter::low_pass(800.0));
app.finish();
app.cleanup();
assert!(!app.world().contains_resource::<SfxFilterShared>());
app.world_mut().write_message(SfxRequest {
event: SfxEvent::ItemPickup,
position: None,
});
app.update();
let sounds = spawned_sounds(&mut app);
assert_eq!(sounds.len(), 1);
assert!(sounds[0].plain && !sounds[0].pending);
}
struct TestSignal {
samples: std::vec::IntoIter<f32>,
channels: u16,
sample_rate: u32,
}
impl Iterator for TestSignal {
type Item = f32;
fn next(&mut self) -> Option<f32> {
self.samples.next()
}
}
impl RodioSource for TestSignal {
fn current_frame_len(&self) -> Option<usize> {
None
}
fn channels(&self) -> u16 {
self.channels
}
fn sample_rate(&self) -> u32 {
self.sample_rate
}
fn total_duration(&self) -> Option<Duration> {
None
}
}
const TEST_RATE: u32 = 44_100;
fn sine(frequency_hz: f32, samples: usize) -> Vec<f32> {
(0..samples)
.map(|i| (std::f32::consts::TAU * frequency_hz * i as f32 / TEST_RATE as f32).sin())
.collect()
}
fn cutoff_cell(cutoff_hz: f32) -> Arc<AtomicU32> {
Arc::new(AtomicU32::new(cutoff_hz.to_bits()))
}
fn filter_mono(samples: Vec<f32>, cutoff: Arc<AtomicU32>) -> Vec<f32> {
let signal = TestSignal {
samples: samples.into_iter(),
channels: 1,
sample_rate: TEST_RATE,
};
LowPassSource::new(signal, cutoff).collect()
}
fn settled_rms(samples: &[f32]) -> f32 {
let tail = &samples[samples.len() / 2..];
(tail.iter().map(|sample| sample * sample).sum::<f32>() / tail.len() as f32).sqrt()
}
#[test]
fn low_pass_attenuates_high_frequencies_and_keeps_low_ones() {
let high = sine(8_000.0, 8_820);
let low = sine(100.0, 8_820);
let high_out = filter_mono(high.clone(), cutoff_cell(500.0));
let low_out = filter_mono(low.clone(), cutoff_cell(500.0));
assert_eq!(high_out.len(), high.len());
assert!(
settled_rms(&high_out) < 0.05 * settled_rms(&high),
"8 kHz must be strongly attenuated by a 500 Hz low-pass"
);
let low_ratio = settled_rms(&low_out) / settled_rms(&low);
assert!(
(0.9..=1.05).contains(&low_ratio),
"100 Hz must pass a 500 Hz low-pass, got ratio {low_ratio}"
);
}
#[test]
fn low_pass_without_cutoff_is_the_identity() {
let input = sine(8_000.0, 512);
assert_eq!(filter_mono(input.clone(), cutoff_cell(0.0)), input);
assert_eq!(filter_mono(input.clone(), cutoff_cell(20_000.0)), input);
assert_eq!(filter_mono(input.clone(), cutoff_cell(f32::NAN)), input);
}
#[test]
fn low_pass_follows_cutoff_changes_while_playing() {
let input = sine(8_000.0, 8_820);
let cutoff = cutoff_cell(0.0);
let signal = TestSignal {
samples: input.clone().into_iter(),
channels: 1,
sample_rate: TEST_RATE,
};
let mut source = LowPassSource::new(signal, cutoff.clone());
let unfiltered: Vec<f32> = source.by_ref().take(2_940).collect();
assert_eq!(unfiltered, input[..2_940]);
cutoff.store(500.0_f32.to_bits(), Ordering::Relaxed);
let filtered: Vec<f32> = source.by_ref().take(2_940).collect();
assert!(settled_rms(&filtered) < 0.05 * settled_rms(&input));
cutoff.store(0.0_f32.to_bits(), Ordering::Relaxed);
let restored: Vec<f32> = source.collect();
assert_eq!(restored, input[5_880..]);
}
#[test]
fn low_pass_filters_each_channel_separately() {
let frames = 4_410;
let samples: Vec<f32> = (0..frames)
.flat_map(|frame| [0.5, if frame % 2 == 0 { 1.0 } else { -1.0 }])
.collect();
let signal = TestSignal {
samples: samples.into_iter(),
channels: 2,
sample_rate: TEST_RATE,
};
let output: Vec<f32> = LowPassSource::new(signal, cutoff_cell(500.0)).collect();
assert_eq!(output.len(), frames * 2);
let left = output[output.len() - 2];
let right = output[output.len() - 1];
assert!(
(left - 0.5).abs() < 0.01,
"constant level must pass, got {left}"
);
assert!(
right.abs() < 0.01,
"alternation must be removed, got {right}"
);
}
#[test]
fn low_pass_output_stays_finite_for_bad_input() {
let mut input = sine(100.0, 256);
input[10] = f32::NAN;
input[20] = f32::INFINITY;
let output = filter_mono(input, cutoff_cell(500.0));
assert!(output.iter().all(|sample| sample.is_finite()));
assert!(output.iter().all(|sample| (-1.0..=1.0).contains(sample)));
}
#[test]
fn low_pass_reports_the_inner_format() {
let signal = TestSignal {
samples: vec![0.0; 4].into_iter(),
channels: 2,
sample_rate: 22_050,
};
let source = LowPassSource::new(signal, cutoff_cell(500.0));
assert_eq!(source.channels(), 2);
assert_eq!(source.sample_rate(), 22_050);
assert_eq!(source.current_frame_len(), None);
assert_eq!(source.total_duration(), None);
}
#[test]
fn coefficients_reject_values_that_cannot_filter() {
assert!(LowPassCoefficients::new(500.0, TEST_RATE).is_some());
assert_eq!(LowPassCoefficients::new(500.0, 0), None);
assert_eq!(LowPassCoefficients::new(0.0, TEST_RATE), None);
assert_eq!(LowPassCoefficients::new(-1.0, TEST_RATE), None);
assert_eq!(LowPassCoefficients::new(f32::NAN, TEST_RATE), None);
assert_eq!(LowPassCoefficients::new(f32::INFINITY, TEST_RATE), None);
assert_eq!(LowPassCoefficients::new(22_050.0, TEST_RATE), None);
}
}