1use nadir_assets::{AssetServer, Handle, LoadState};
21use nadir_audio::{Audio, AudioConfig, Mixer, Music, VoiceChange, VoiceId};
22use nadir_core::Vec2;
23use nadir_core::log::warn;
24use nadir_core::time::Frame;
25use nadir_ecs::{Component, Entity, World};
26use nadir_platform::AudioRender;
27use nadir_render::RenderFrame;
28
29use crate::{AudioEmitter, AudioListener, MusicArea, PrevTransform, Transform};
30
31const STOP_MS: u32 = 100;
33
34const MARGIN: f32 = 64.0;
38
39const EMITTERS: usize = 64;
41
42pub(crate) struct MixerOutput(pub(crate) Mixer);
44
45impl AudioRender for MixerOutput {
46 fn render(&mut self, out: &mut [f32], channels: u16, sample_rate: u32) {
47 self.0.render(out, usize::from(channels), sample_rate);
48 }
49
50 fn underrun(&mut self) {
51 self.0.count_underrun();
52 }
53}
54
55#[derive(Debug)]
59pub struct AudioState {
60 emitters: Vec<Entry>,
62 area: Option<(Entity, Handle<Music>)>,
64 failed: Vec<(Entity, MusicArea)>,
67 listener: Vec2,
69 placed: Option<Vec2>,
72 range: f32,
75}
76
77#[derive(Debug)]
79struct Entry {
80 entity: Entity,
81 emitter: AudioEmitter,
83 voice: Option<VoiceId>,
85 position: Vec2,
87}
88
89#[derive(Clone, Copy, Debug)]
92pub(crate) struct Tracked;
93
94impl Component for Tracked {}
95
96impl AudioState {
97 pub(crate) fn new(config: &AudioConfig) -> Self {
99 Self {
100 emitters: Vec::with_capacity(EMITTERS),
101 area: None,
102 failed: Vec::new(),
103 listener: Vec2::ZERO,
104 placed: None,
105 range: config.max_dist,
106 }
107 }
108
109 pub fn music_area(&self) -> Option<Entity> {
114 self.area.map(|(entity, _)| entity)
115 }
116
117 fn emitters(
120 &mut self,
121 world: &World,
122 audio: &Audio,
123 assets: &AssetServer,
124 at: &impl Fn(Entity) -> Option<Vec2>,
125 ) {
126 let emitters = world.read::<AudioEmitter>();
127 let mut tracked = world.write::<Tracked>();
128 let mut index = 0;
129 while let Some(entry) = self.emitters.get_mut(index) {
130 let emitter = emitters.get(entry.entity);
131 let keep = match entry.voice {
132 None => emitter.is_some_and(|emitter| same(emitter, &entry.emitter)),
135 Some(voice) => match emitter.zip(at(entry.entity)) {
136 Some((emitter, position)) => {
137 let far = position.distance(self.listener) > self.range + MARGIN;
138 if far || restarts(emitter, &entry.emitter) {
139 sent(audio, |audio| audio.stop(voice, STOP_MS)).is_none()
140 } else {
141 entry.follow(emitter, position, voice, audio);
142 true
143 }
144 }
145 None => sent(audio, |audio| audio.stop(voice, STOP_MS)).is_none(),
147 },
148 };
149 if keep {
150 index += 1;
151 } else {
152 tracked.remove(entry.entity);
153 self.emitters.swap_remove(index);
154 }
155 }
156 for (entity, emitter) in emitters.iter() {
157 if tracked.contains(entity) {
158 continue;
159 }
160 let Some(position) = at(entity) else {
161 continue;
162 };
163 let near = position.distance(self.listener) <= self.range;
164 if !near {
165 continue;
166 }
167 let voice = match assets.get(emitter.sound) {
168 Some(sound) => {
169 let play = |audio: &Audio| audio.play_sound_at(sound, position, emitter.params);
170 match sent(audio, play) {
171 Some(voice) => Some(voice),
172 None => continue,
174 }
175 }
176 None if assets.state(emitter.sound) == Some(LoadState::Loading) => continue,
177 None => {
178 match assets.path(emitter.sound) {
179 Some(path) => warn!(
180 "{entity:?}'s AudioEmitter plays `{path}`, which did not load: it \
181 is silent until the emitter changes"
182 ),
183 None => warn!(
184 "{entity:?}'s AudioEmitter plays a sound the asset server does not \
185 hold: it is silent until the emitter changes"
186 ),
187 }
188 None
189 }
190 };
191 self.emitters.push(Entry {
192 entity,
193 emitter: *emitter,
194 voice,
195 position,
196 });
197 tracked.insert(entity, Tracked);
198 }
199 }
200
201 fn music(
204 &mut self,
205 world: &World,
206 audio: &Audio,
207 assets: &AssetServer,
208 at: &impl Fn(Entity) -> Option<Vec2>,
209 ) {
210 let areas = world.read::<MusicArea>();
211 if self.area.is_some_and(|(entity, _)| !areas.contains(entity)) {
212 self.area = None;
213 }
214 self.failed
215 .retain(|&(entity, area)| areas.get(entity).is_some_and(|now| same_area(now, &area)));
216 let listener = self.listener;
217 let failed = &self.failed;
218 let warned = |entity: Entity| failed.iter().any(|&(warned, _)| warned == entity);
219 let holds = |entity: Entity, area: &MusicArea| {
220 at(entity).is_some_and(|centre| {
221 let offset = (listener - centre).abs();
222 offset.x <= area.half.x && offset.y <= area.half.y
223 })
224 };
225 let current = self.area.and_then(|(entity, _)| {
229 let area = areas.get(entity).filter(|area| holds(entity, area))?;
230 Some((entity, *area))
231 });
232 let first = || {
233 let (entity, area) = areas
234 .iter()
235 .find(|&(entity, area)| !warned(entity) && holds(entity, area))?;
236 Some((entity, *area))
237 };
238 let Some((entity, area)) = current.or_else(first) else {
239 self.area = None;
242 return;
243 };
244 if self.area == Some((entity, area.music)) || warned(entity) {
246 return;
247 }
248 match assets.get(area.music) {
249 Some(track) => {
250 if sent(audio, |audio| audio.play_track(track, area.crossfade_ms)).is_some() {
251 self.area = Some((entity, area.music));
252 }
253 }
254 None if assets.state(area.music) == Some(LoadState::Loading) => {}
255 None => {
256 match assets.path(area.music) {
257 Some(path) => warn!(
258 "{entity:?}'s MusicArea plays `{path}`, which did not load: the music does \
259 not change for it until the area changes"
260 ),
261 None => warn!(
262 "{entity:?}'s MusicArea plays a track the asset server does not hold: the \
263 music does not change for it until the area changes"
264 ),
265 }
266 self.failed.push((entity, area));
267 }
268 }
269 }
270}
271
272impl Entry {
273 fn follow(&mut self, emitter: &AudioEmitter, position: Vec2, voice: VoiceId, audio: &Audio) {
276 if bits(position) != bits(self.position)
277 && sent(audio, |audio| {
278 audio.set_voice(voice, VoiceChange::Position(position));
279 })
280 .is_some()
281 {
282 self.position = position;
283 }
284 let (now, then) = (emitter.params, &mut self.emitter.params);
285 if now.volume.to_bits() != then.volume.to_bits()
286 && sent(audio, |audio| {
287 audio.set_voice(voice, VoiceChange::Volume(now.volume));
288 })
289 .is_some()
290 {
291 then.volume = now.volume;
292 }
293 if now.pitch.to_bits() != then.pitch.to_bits()
294 && sent(audio, |audio| {
295 audio.set_voice(voice, VoiceChange::Pitch(now.pitch));
296 })
297 .is_some()
298 {
299 then.pitch = now.pitch;
300 }
301 }
302}
303
304pub(crate) fn sound(world: &World, frame: &Frame) {
316 let audio = world.resource::<Audio>();
317 let assets = world.resource::<AssetServer>();
318 let mut state = world.resource_mut::<AudioState>();
319 let transforms = world.read::<Transform>();
320 let previous = world.read::<PrevTransform>();
321 let at = |entity| {
323 let current = transforms.get(entity)?.position;
324 Some(previous.get(entity).map_or(current, |previous| {
325 previous.0.position.lerp(current, frame.alpha)
326 }))
327 };
328 let listener = world
329 .read::<AudioListener>()
330 .entities()
331 .iter()
332 .find_map(|&entity| at(entity))
333 .unwrap_or_else(|| world.resource::<RenderFrame>().camera.position);
334 state.listener = listener;
335 if state.placed.map(bits) != Some(bits(listener))
336 && sent(&audio, |audio| audio.set_listener(listener)).is_some()
337 {
338 state.placed = Some(listener);
339 }
340 state.emitters(world, &audio, &assets, &at);
341 state.music(world, &audio, &assets, &at);
342 audio.update();
343}
344
345fn sent<T>(audio: &Audio, send: impl FnOnce(&Audio) -> T) -> Option<T> {
348 let dropped = audio.stats().dropped;
349 let value = send(audio);
350 (audio.stats().dropped == dropped).then_some(value)
351}
352
353fn bits(position: Vec2) -> [u32; 2] {
356 [position.x, position.y].map(f32::to_bits)
357}
358
359fn restarts(now: &AudioEmitter, then: &AudioEmitter) -> bool {
362 let (a, b) = (&now.params, &then.params);
363 now.sound != then.sound
364 || a.bus != b.bus
365 || a.looped != b.looped
366 || a.priority != b.priority
367 || a.max_instances != b.max_instances
368}
369
370fn same(a: &AudioEmitter, b: &AudioEmitter) -> bool {
373 let bits = |emitter: &AudioEmitter| {
374 let params = &emitter.params;
375 [params.volume, params.pitch, params.pan].map(f32::to_bits)
376 };
377 !restarts(a, b) && bits(a) == bits(b)
378}
379
380fn same_area(a: &MusicArea, b: &MusicArea) -> bool {
382 let bits = |area: &MusicArea| [area.half.x, area.half.y].map(f32::to_bits);
383 a.music == b.music && a.crossfade_ms == b.crossfade_ms && bits(a) == bits(b)
384}
385
386#[cfg(test)]
387mod tests {
388 use std::collections::HashMap;
389 use std::f32::consts::{FRAC_PI_4, TAU};
390 use std::num::NonZeroU32;
391 use std::sync::{Arc, Mutex, PoisonError};
392 use std::time::Duration;
393
394 use nadir_assets::{AssetError, AssetPath, FinalizeCtx, OnFailure, Source};
395 use nadir_audio::{AudioStats, Bus, PlayParams, Sound, SoundData};
396 use nadir_codec::{kpcm, qoa};
397 use nadir_core::{GenIndex, log};
398
399 use super::*;
400 use crate::{App, Config, Volumes};
401
402 const TICK: Duration = Duration::from_nanos(16_666_667);
404 const RATE: u32 = 48_000;
406 const FRAME: usize = 800;
408 const STOPPED: usize = 7;
411
412 #[derive(Clone, Default)]
414 struct Files(Arc<Mutex<HashMap<String, Vec<u8>>>>);
415
416 impl Files {
417 fn insert(&self, path: &str, bytes: Vec<u8>) {
418 self.0
419 .lock()
420 .unwrap_or_else(PoisonError::into_inner)
421 .insert(path.to_string(), bytes);
422 }
423 }
424
425 impl Source for Files {
426 fn read(&self, path: &AssetPath) -> Result<Vec<u8>, AssetError> {
427 self.0
428 .lock()
429 .unwrap_or_else(PoisonError::into_inner)
430 .get(path.as_str())
431 .cloned()
432 .ok_or(AssetError::NotFound)
433 }
434 }
435
436 fn constant_file(level: f32) -> Vec<u8> {
439 let header = kpcm::Header {
440 channels: 1,
441 sample_rate: RATE,
442 frames: RATE,
443 };
444 let sample = (level * 32768.0) as i16;
445 kpcm::encode(&header, &vec![sample; RATE as usize]).expect("a sound file")
446 }
447
448 fn track_file(samples: &[i16]) -> Vec<u8> {
450 let header = qoa::Header {
451 channels: 1,
452 sample_rate: RATE,
453 samples: samples.len() as u32,
454 };
455 qoa::encode(&header, samples).expect("a QOA file")
456 }
457
458 fn tone(hz: f32, level: f32) -> Vec<i16> {
461 (0..RATE)
462 .map(|n| ((TAU * hz * n as f32 / RATE as f32).sin() * level * 32767.0) as i16)
463 .collect()
464 }
465
466 struct Game {
469 app: App,
470 mixer: Mixer,
471 files: Files,
472 }
473
474 impl Game {
475 fn new() -> Self {
476 Self::with(Config::default())
477 }
478
479 fn with(config: Config) -> Self {
480 Self::of(App::new(config))
481 }
482
483 fn of(mut app: App) -> Self {
484 let mixer = app.take_mixer().expect("no frame has run");
485 let files = Files::default();
486 let server = AssetServer::with_source(files.clone(), OnFailure::Nothing);
488 app.world_mut().insert_resource(server);
489 Self { app, mixer, files }
490 }
491
492 fn assets(&self) -> nadir_ecs::ResMut<'_, AssetServer> {
493 self.app.world().resource_mut::<AssetServer>()
494 }
495
496 fn constant(&mut self, path: &str, level: f32) -> Handle<Sound> {
498 self.files.insert(path, constant_file(level));
499 self.assets()
500 .load_now(path, &mut FinalizeCtx::new())
501 .expect("the sound loads")
502 }
503
504 fn track(&mut self, path: &str, samples: &[i16]) -> Handle<Music> {
507 self.files.insert(path, track_file(samples));
508 self.assets()
509 .load_now(path, &mut FinalizeCtx::new())
510 .expect("the track loads")
511 }
512
513 fn spawn<T: Component>(&mut self, position: Vec2, component: T) -> Entity {
515 self.app
516 .world_mut()
517 .spawn()
518 .with(Transform::at(position))
519 .with(component)
520 .id()
521 }
522
523 fn place(&self, entity: Entity, position: Vec2) {
524 let mut transforms = self.app.world().write::<Transform>();
525 transforms.get_mut(entity).expect("placed").position = position;
526 }
527
528 fn camera(&self, position: Vec2) {
529 self.app
530 .world()
531 .resource_mut::<RenderFrame>()
532 .camera
533 .position = position;
534 }
535
536 fn emitter(&self, entity: Entity) -> std::cell::RefMut<'_, AudioEmitter> {
537 std::cell::RefMut::map(self.app.world().write::<AudioEmitter>(), |emitters| {
538 emitters.get_mut(entity).expect("an emitter")
539 })
540 }
541
542 fn frame_into(&mut self, elapsed: Duration, out: &mut [f32]) {
545 self.app.update(elapsed, &[]);
546 self.mixer.render(out, 2, RATE);
547 }
548
549 fn frame(&mut self) -> Vec<f32> {
551 let mut out = vec![0.0; FRAME * 2];
552 self.frame_into(TICK, &mut out);
553 out
554 }
555
556 fn frames(&mut self, frames: usize) -> Vec<f32> {
558 let mut out = vec![0.0; FRAME * 2];
559 for _ in 0..frames {
560 self.frame_into(TICK, &mut out);
561 }
562 out
563 }
564
565 fn stats(&self) -> AudioStats {
566 self.app.world().resource::<Audio>().stats()
567 }
568
569 fn music_area(&self) -> Option<Entity> {
570 self.app.world().resource::<AudioState>().music_area()
571 }
572
573 fn fill_queue(&self) {
576 let audio = self.app.world().resource::<Audio>();
577 let dropped = audio.stats().dropped;
578 while audio.stats().dropped == dropped {
579 audio.set_bus_volume(Bus::Ui, 1.0, 0);
580 }
581 }
582 }
583
584 fn heard(level: f32, offset: Vec2) -> [f32; 2] {
589 let pan = (offset.x / 480.0).clamp(-1.0, 1.0);
590 let distance = offset.length();
591 let gain = ((800.0 - distance) / (800.0 - 64.0)).clamp(0.0, 1.0);
592 let (sin, cos) = ((pan + 1.0) * FRAC_PI_4).sin_cos();
593 [level * gain * cos, level * gain * sin]
594 }
595
596 #[track_caller]
598 fn assert_heard(out: &[f32], expected: [f32; 2]) {
599 let found = [out[out.len() - 2], out[out.len() - 1]];
600 let near = (0..2).all(|side| (found[side] - expected[side]).abs() < 1e-3);
601 assert!(near, "heard {found:?}, not {expected:?}");
602 }
603
604 fn rms(out: &[f32], from: usize, frames: usize) -> f32 {
607 let left = out[from * 2..(from + frames) * 2].iter().step_by(2);
608 (left.map(|x| x * x).sum::<f32>() / frames as f32).sqrt()
609 }
610
611 fn logged(parts: &[&str]) -> usize {
613 log::tail(log::RING_CAPACITY)
614 .iter()
615 .filter(|record| parts.iter().all(|part| record.contains(part)))
616 .count()
617 }
618
619 #[test]
620 fn the_mixer_output_renders_the_mixer_and_counts_its_underruns() {
621 let (audio, mixer) = nadir_audio::new(AudioConfig::default()).expect("the default");
622 let mut output = MixerOutput(mixer);
623 let sound = Sound::new(SoundData::new(1, RATE, vec![0.5; 4_800]).expect("a sound"));
624 audio.play_sound(&sound, PlayParams::default());
625 let mut out = vec![0.0; 480 * 2];
626 output.render(&mut out, 2, RATE);
627 assert_heard(&out, heard(0.5, Vec2::ZERO));
628 let mut mono = vec![0.0; 480];
630 output.render(&mut mono, 1, RATE);
631 assert!((mono[479] - heard(0.5, Vec2::ZERO)[0]).abs() < 1e-3);
632 output.underrun();
633 output.underrun();
634 assert_eq!((audio.stats().underruns, audio.stats().rate), (2, RATE));
635 }
636
637 #[test]
638 fn the_first_update_drops_a_mixer_not_taken_and_the_audio_does_nothing() {
639 let mut taken = App::new(Config::default());
640 assert!(taken.take_mixer().is_some());
641 assert!(taken.take_mixer().is_none(), "taken once");
642
643 let mut app = App::new(Config::default());
644 app.update(TICK, &[]);
645 assert!(app.take_mixer().is_none(), "dropped");
646 let world = app.world();
647 let audio = world.resource::<Audio>();
648 let sound = Sound::new(SoundData::new(1, RATE, vec![0.5; 480]).expect("a sound"));
649 for _ in 0..2_000 {
651 audio.play_sound(&sound, PlayParams::default());
652 audio.set_listener(Vec2::ONE);
653 }
654 let nothing = Handle::new(GenIndex::new(7, NonZeroU32::MIN));
656 audio.play(
657 &world.resource::<AssetServer>(),
658 nothing,
659 PlayParams::default(),
660 );
661 audio.update();
662 let expected = AudioStats {
663 unplayed: 1,
664 ..AudioStats::default()
665 };
666 assert_eq!(audio.stats(), expected);
667 assert_eq!(
668 Arc::strong_count(sound.data()),
669 1,
670 "nothing holds the sound"
671 );
672 }
673
674 #[test]
675 fn the_listener_is_the_first_audio_listener_where_it_is_drawn_or_else_the_camera() {
676 let mut game = Game::new();
677 let hum = game.constant("audio/hum.kpcm", 0.5);
678 game.spawn(Vec2::new(100.0, 0.0), AudioEmitter::looped(hum));
679 assert_heard(&game.frames(2), heard(0.5, Vec2::new(100.0, 0.0)));
682 game.camera(Vec2::new(300.0, 0.0));
683 assert_heard(&game.frames(2), heard(0.5, Vec2::new(-200.0, 0.0)));
684
685 game.app.world_mut().spawn().with(AudioListener);
688 let listener = game.spawn(Vec2::new(200.0, 0.0), AudioListener);
689 game.app
690 .world_mut()
691 .write::<PrevTransform>()
692 .insert(listener, PrevTransform(Transform::at(Vec2::ZERO)));
693 let mut out = vec![0.0; FRAME * 2];
694 game.frame_into(TICK / 2, &mut out);
695 assert_heard(&out, heard(0.5, Vec2::ZERO));
696 assert_heard(&game.frames(2), heard(0.5, Vec2::new(-100.0, 0.0)));
698 game.app.world_mut().despawn(listener);
700 assert_heard(&game.frames(2), heard(0.5, Vec2::new(-200.0, 0.0)));
701 }
702
703 #[test]
704 fn an_emitter_waits_for_its_sound_and_follows_its_entity() {
705 let mut game = Game::new();
706 game.files.insert("audio/later.kpcm", constant_file(0.5));
707 let later = game.assets().load::<Sound>("audio/later.kpcm");
708 let entity = game.spawn(Vec2::new(100.0, 0.0), AudioEmitter::looped(later));
709 for _ in 0..3 {
711 assert!(game.frame().iter().all(|&x| x == 0.0));
712 }
713 assert_eq!((game.stats().active_voices, game.stats().unplayed), (0, 0));
714 game.assets().finish_all_loads(&mut FinalizeCtx::new());
715 assert_heard(&game.frame(), heard(0.5, Vec2::new(100.0, 0.0)));
716 for x in [-240.0, 0.0, 400.0] {
718 game.place(entity, Vec2::new(x, 30.0));
719 assert_heard(&game.frame(), heard(0.5, Vec2::new(x, 30.0)));
720 }
721 assert_eq!(game.stats().active_voices, 1);
722 }
723
724 #[test]
725 fn an_emitter_changed_takes_a_new_volume_live_and_restarts_for_a_new_sound() {
726 let mut game = Game::new();
727 let hum = game.constant("audio/hum.kpcm", 0.5);
728 let buzz = game.constant("audio/buzz.kpcm", 0.25);
729 let entity = game.spawn(Vec2::ZERO, AudioEmitter::looped(hum));
730 assert_heard(&game.frames(2), heard(0.5, Vec2::ZERO));
731 game.emitter(entity).params.volume = 0.5;
734 game.emitter(entity).params.pitch = 0.5;
735 assert_heard(&game.frame(), heard(0.25, Vec2::ZERO));
736 assert_eq!(game.stats().active_voices, 1);
737 game.emitter(entity).params.volume = f32::NAN;
739 assert_heard(&game.frames(2), [0.0, 0.0]);
740 game.emitter(entity).params.volume = 0.5;
741 assert_heard(&game.frame(), heard(0.25, Vec2::ZERO));
742
743 game.emitter(entity).sound = buzz;
745 game.frame();
746 assert_eq!(game.stats().active_voices, 2);
747 assert_heard(&game.frames(STOPPED), heard(0.125, Vec2::ZERO));
748 assert_eq!(game.stats().active_voices, 1);
749 game.emitter(entity).params.bus = Bus::Sfx;
751 game.frame();
752 assert_eq!(game.stats().active_voices, 2);
753 game.app
754 .world_mut()
755 .write::<AudioEmitter>()
756 .insert(entity, AudioEmitter::looped(hum));
757 assert_heard(&game.frames(STOPPED * 2), heard(0.5, Vec2::ZERO));
758 assert_eq!(game.stats().active_voices, 1);
759 }
760
761 #[test]
762 fn an_emitter_stops_when_it_goes_or_is_far_and_plays_again_when_near() {
763 let mut game = Game::new();
764 let hum = game.constant("audio/hum.kpcm", 0.5);
765 let far = game.spawn(Vec2::new(100.0, 0.0), AudioEmitter::looped(hum));
766 let removed = game.spawn(Vec2::new(-100.0, 0.0), AudioEmitter::looped(hum));
767 let despawned = game.spawn(Vec2::new(0.0, 100.0), AudioEmitter::looped(hum));
768 game.frames(2);
769 assert_eq!(game.stats().active_voices, 3);
770
771 game.app.world_mut().write::<AudioEmitter>().remove(removed);
772 game.app.world_mut().despawn(despawned);
773 game.frames(STOPPED);
774 assert_eq!(game.stats().active_voices, 1);
775 assert_heard(&game.frame(), heard(0.5, Vec2::new(100.0, 0.0)));
776
777 game.place(far, Vec2::new(850.0, 0.0));
779 assert_heard(&game.frames(STOPPED), [0.0, 0.0]);
780 assert_eq!(game.stats().active_voices, 1);
781 game.place(far, Vec2::new(0.0, 870.0));
782 game.frames(STOPPED);
783 assert_eq!(game.stats().active_voices, 0);
784 game.place(far, Vec2::new(810.0, 0.0));
786 game.frames(2);
787 assert_eq!(game.stats().active_voices, 0);
788 game.place(far, Vec2::new(-200.0, 0.0));
789 assert_heard(&game.frame(), heard(0.5, Vec2::new(-200.0, 0.0)));
790 assert_eq!(game.stats().active_voices, 1);
791
792 game.app
794 .world_mut()
795 .write::<AudioEmitter>()
796 .insert(removed, AudioEmitter::looped(hum));
797 game.frame();
798 assert_eq!(game.stats().active_voices, 2);
799 game.app.world_mut().write::<Transform>().remove(removed);
801 game.frames(STOPPED);
802 assert_eq!(game.stats().active_voices, 1);
803 }
804
805 #[test]
806 fn a_sound_played_to_its_end_is_given_back_by_the_frame_after() {
807 let mut game = Game::new();
808 let blip = game.constant("audio/blip.kpcm", 0.5);
809 let held = |game: &Game| Arc::strong_count(game.assets().get(blip).expect("loaded").data());
810 game.spawn(Vec2::ZERO, AudioEmitter::new(blip, PlayParams::default()));
811 game.frames(2);
812 assert_eq!(held(&game), 2, "its voice holds it");
813 game.frames(70);
816 assert_eq!(held(&game), 1, "the asset server alone holds it");
817 }
818
819 #[test]
820 fn an_emitter_warned_of_is_warned_of_again_only_once_it_goes_or_changes() {
821 let mut game = Game::new();
822 let sound = {
823 let mut assets = game.assets();
824 let sound = assets.load::<Sound>("audio/warned-still.kpcm");
825 assets.finish_all_loads(&mut FinalizeCtx::new());
826 sound
827 };
828 let entity = game.spawn(Vec2::ZERO, AudioEmitter::looped(sound));
829 let warned = || logged(&["warned-still.kpcm", "AudioEmitter"]);
830 game.frames(2);
831 assert_eq!(warned(), 1);
832 game.app.world_mut().write::<Transform>().remove(entity);
834 game.frames(2);
835 game.app
836 .world_mut()
837 .write::<Transform>()
838 .insert(entity, Transform::at(Vec2::ZERO));
839 game.frames(2);
840 assert_eq!(warned(), 1);
841 game.app.world_mut().write::<AudioEmitter>().remove(entity);
843 game.frame();
844 game.app
845 .world_mut()
846 .write::<AudioEmitter>()
847 .insert(entity, AudioEmitter::looped(sound));
848 game.frames(2);
849 assert_eq!(warned(), 2);
850 }
851
852 #[test]
853 fn five_looped_emitters_of_one_sound_all_sound() {
854 let mut game = Game::new();
855 let hum = game.constant("audio/hum.kpcm", 0.1);
856 for _ in 0..5 {
857 game.spawn(Vec2::ZERO, AudioEmitter::looped(hum));
858 }
859 assert_heard(&game.frames(2), heard(0.5, Vec2::ZERO));
860 assert_eq!(game.stats().active_voices, 5);
861 let mut game = Game::new();
864 let hum = game.constant("audio/hum.kpcm", 0.1);
865 let looped = PlayParams {
866 looped: true,
867 ..PlayParams::default()
868 };
869 for _ in 0..5 {
870 game.spawn(Vec2::ZERO, AudioEmitter::new(hum, looped));
871 }
872 assert_heard(&game.frames(2), heard(0.4, Vec2::ZERO));
873 assert_eq!(game.stats().active_voices, 4);
874 }
875
876 #[test]
877 fn the_music_crossfades_when_the_listener_crosses_into_another_area() {
878 let mut game = Game::new();
879 let tone = game.track("audio/music/tone.qoa", &tone(400.0, 0.25));
880 let quiet = game.track("audio/music/quiet.qoa", &[0; RATE as usize]);
881 let listener = game.spawn(Vec2::ZERO, AudioListener);
882 let mut area = MusicArea::new(tone, Vec2::splat(100.0));
883 area.crossfade_ms = 600;
884 let loud = game.spawn(Vec2::ZERO, area);
885 area.music = quiet;
886 let still = game.spawn(Vec2::new(300.0, 0.0), area);
887 let out = game.frames(45);
890 let full = rms(&out, FRAME - 480, 480);
891 assert!(full > 0.17, "{full}");
892 assert_eq!(game.music_area(), Some(loud));
893
894 game.place(listener, Vec2::new(300.0, 0.0));
897 let fade = 28_800;
898 let mut out = vec![0.0; 37 * FRAME * 2];
899 for frame in out.chunks_mut(FRAME * 2) {
900 game.frame_into(TICK, frame);
901 }
902 assert_eq!(game.music_area(), Some(still));
903 let at = |from: usize| rms(&out, from, 480) / full;
904 let start = at(0);
905 let half = at(fade / 2 - 240);
906 let end = at(fade);
907 assert!(
908 (start - (1.0 - 240.0 / fade as f32)).abs() < 0.02,
909 "{start}"
910 );
911 assert!((half - 0.5).abs() < 0.02, "{half}");
912 assert!(end < 1e-3, "{end}");
914 }
915
916 #[test]
917 fn outside_every_area_the_music_plays_on_and_coming_back_carries_it_on() {
918 let mut game = Game::new();
919 let tone = game.track("audio/music/tone.qoa", &tone(400.0, 0.25));
920 let listener = game.spawn(Vec2::ZERO, AudioListener);
921 let mut area = MusicArea::new(tone, Vec2::new(100.0, 50.0));
922 area.crossfade_ms = 100;
923 let meadow = game.spawn(Vec2::ZERO, area);
924 let out = game.frames(10);
925 let full = rms(&out, FRAME - 480, 480);
926 assert_eq!(game.music_area(), Some(meadow));
927 let heard_full = |out: &[f32]| (rms(out, FRAME - 480, 480) / full - 1.0).abs() < 0.02;
928
929 game.place(listener, Vec2::new(0.0, 51.0));
931 for _ in 0..10 {
932 assert!(heard_full(&game.frame()));
933 assert_eq!(game.music_area(), None);
934 }
935 game.place(listener, Vec2::new(100.0, 50.0));
938 for _ in 0..10 {
939 assert!(heard_full(&game.frame()));
940 assert_eq!(game.music_area(), Some(meadow));
941 }
942 game.app.world_mut().write::<MusicArea>().remove(meadow);
944 assert!(heard_full(&game.frame()));
945 assert_eq!(game.music_area(), None);
946 game.app
947 .world_mut()
948 .write::<MusicArea>()
949 .insert(meadow, area);
950 game.frame();
951 assert_eq!(game.music_area(), Some(meadow));
952 game.app.world_mut().despawn(meadow);
953 assert!(heard_full(&game.frame()));
954 assert_eq!(game.music_area(), None);
955 }
956
957 #[test]
958 fn where_areas_overlap_the_music_changes_only_on_leaving_the_one_playing() {
959 let mut game = Game::new();
960 let low = game.track("audio/music/low.qoa", &tone(200.0, 0.25));
961 let high = game.track("audio/music/high.qoa", &tone(800.0, 0.25));
962 let west = game.spawn(Vec2::ZERO, MusicArea::new(low, Vec2::splat(100.0)));
964 let east = game.spawn(
965 Vec2::new(150.0, 0.0),
966 MusicArea::new(high, Vec2::splat(100.0)),
967 );
968 let mut heard_in = |x: f32| {
969 game.camera(Vec2::new(x, 0.0));
970 game.frame();
971 game.music_area()
972 };
973 assert_eq!(heard_in(0.0), Some(west));
974 assert_eq!(heard_in(80.0), Some(west));
975 assert_eq!(heard_in(200.0), Some(east));
976 assert_eq!(heard_in(80.0), Some(east));
977 assert_eq!(heard_in(-20.0), Some(west));
978 assert_eq!(heard_in(1_000.0), None);
980 assert_eq!(heard_in(80.0), Some(west));
981 }
982
983 #[test]
984 fn where_an_area_whose_track_did_not_load_overlaps_another_the_other_plays() {
985 let mut game = Game::new();
986 let tone = game.track("audio/music/tone.qoa", &tone(400.0, 0.25));
987 let missing = {
988 let mut assets = game.assets();
989 let missing = assets.load::<Music>("audio/music/skipped.qoa");
990 assets.finish_all_loads(&mut FinalizeCtx::new());
991 missing
992 };
993 game.spawn(Vec2::ZERO, MusicArea::new(missing, Vec2::splat(100.0)));
996 let meadow = game.spawn(
997 Vec2::new(50.0, 0.0),
998 MusicArea::new(tone, Vec2::splat(100.0)),
999 );
1000 game.frames(2);
1001 assert_eq!(game.music_area(), Some(meadow));
1002 assert_eq!(logged(&["skipped.qoa", "MusicArea"]), 1);
1003 }
1004
1005 #[test]
1006 fn the_area_playing_despawned_is_named_no_more_while_the_next_ones_track_loads() {
1007 let mut game = Game::new();
1008 let tone = game.track("audio/music/tone.qoa", &tone(400.0, 0.25));
1009 game.files
1010 .insert("audio/music/later.qoa", track_file(&[0; RATE as usize]));
1011 let later = game.assets().load::<Music>("audio/music/later.qoa");
1012 let west = game.spawn(Vec2::ZERO, MusicArea::new(tone, Vec2::splat(100.0)));
1014 let east = game.spawn(
1015 Vec2::new(50.0, 0.0),
1016 MusicArea::new(later, Vec2::splat(100.0)),
1017 );
1018 game.frames(2);
1019 assert_eq!(game.music_area(), Some(west));
1020 game.app.world_mut().despawn(west);
1021 game.frames(2);
1022 assert_eq!(game.music_area(), None);
1023 game.assets().finish_all_loads(&mut FinalizeCtx::new());
1025 game.frame();
1026 assert_eq!(game.music_area(), Some(east));
1027 }
1028
1029 #[test]
1030 fn a_play_a_move_and_a_track_dropped_by_a_full_queue_are_sent_again() {
1031 let mut game = Game::new();
1032 let hum = game.constant("audio/hum.kpcm", 0.5);
1033 let tone = game.track("audio/music/tone.qoa", &tone(400.0, 0.25));
1034 game.fill_queue();
1035 let entity = game.spawn(Vec2::new(100.0, 0.0), AudioEmitter::looped(hum));
1036 game.app.update(TICK, &[]);
1038 let mut out = vec![0.0; FRAME * 2];
1039 game.mixer.render(&mut out, 2, RATE);
1040 assert_eq!(game.stats().active_voices, 0);
1041 assert_heard(&game.frame(), heard(0.5, Vec2::new(100.0, 0.0)));
1042 assert_eq!(game.stats().active_voices, 1);
1043
1044 game.fill_queue();
1046 game.place(entity, Vec2::new(-100.0, 0.0));
1047 game.app.update(TICK, &[]);
1048 game.mixer.render(&mut out, 2, RATE);
1049 assert_heard(&out, heard(0.5, Vec2::new(100.0, 0.0)));
1050 assert_heard(&game.frame(), heard(0.5, Vec2::new(-100.0, 0.0)));
1051 game.fill_queue();
1053 game.camera(Vec2::new(-50.0, 0.0));
1054 game.app.update(TICK, &[]);
1055 game.mixer.render(&mut out, 2, RATE);
1056 assert_heard(&out, heard(0.5, Vec2::new(-100.0, 0.0)));
1057 assert_heard(&game.frame(), heard(0.5, Vec2::new(-50.0, 0.0)));
1058
1059 game.app.world_mut().despawn(entity);
1061 game.frames(STOPPED);
1062 game.fill_queue();
1063 let mut area = MusicArea::new(tone, Vec2::splat(100.0));
1064 area.crossfade_ms = 2;
1065 let meadow = game.spawn(Vec2::ZERO, area);
1066 game.app.update(TICK, &[]);
1067 assert_eq!(game.music_area(), None);
1068 game.mixer.render(&mut out, 2, RATE);
1069 assert_eq!(rms(&out, 0, FRAME), 0.0);
1070 let out = game.frame();
1071 assert_eq!(game.music_area(), Some(meadow));
1072 assert!(rms(&out, FRAME - 480, 480) > 0.17);
1073 }
1074
1075 #[test]
1076 fn a_frame_where_nothing_moves_sends_nothing() {
1077 let mut game = Game::new();
1079 let hum = game.constant("audio/hum.kpcm", 0.5);
1080 let tone = game.track("audio/music/tone.qoa", &tone(400.0, 0.25));
1081 game.spawn(Vec2::ZERO, MusicArea::new(tone, Vec2::splat(100.0)));
1082 let moving = game.spawn(Vec2::new(100.0, 0.0), AudioEmitter::looped(hum));
1083 for x in [-100.0, 200.0] {
1084 game.spawn(Vec2::new(x, 50.0), AudioEmitter::looped(hum));
1085 }
1086 for _ in 0..1_000 {
1089 game.app.update(TICK, &[]);
1090 }
1091 assert_eq!(game.stats().dropped, 0);
1092 for frame in 0..600 {
1097 game.place(moving, Vec2::new(frame as f32, 0.0));
1098 game.app.update(TICK, &[]);
1099 }
1100 assert_eq!(game.stats().dropped, 600 - (512 - 9));
1101 }
1102
1103 #[test]
1104 fn the_configured_volumes_scale_what_is_heard() {
1105 let volumes = Volumes {
1106 ambience: 50,
1107 sfx: 0,
1108 ..Volumes::default()
1109 };
1110 let mut game = Game::with(Config {
1111 volumes,
1112 ..Config::default()
1113 });
1114 let hum = game.constant("audio/hum.kpcm", 0.5);
1115 game.spawn(Vec2::ZERO, AudioEmitter::looped(hum));
1118 let effect = PlayParams {
1119 looped: true,
1120 ..PlayParams::default()
1121 };
1122 game.spawn(Vec2::ZERO, AudioEmitter::new(hum, effect));
1123 assert_heard(&game.frames(2), heard(0.125, Vec2::ZERO));
1124 assert_eq!(game.stats().active_voices, 2);
1125 }
1126
1127 #[test]
1128 fn a_sound_or_a_track_that_did_not_load_is_warned_of_once_until_it_changes() {
1129 let mut game = Game::new();
1130 let (sound, track) = {
1131 let mut assets = game.assets();
1132 let sound = assets.load::<Sound>("audio/warned-once.kpcm");
1133 let track = assets.load::<Music>("audio/music/warned-once.qoa");
1134 assets.finish_all_loads(&mut FinalizeCtx::new());
1135 (sound, track)
1136 };
1137 let emitter = game.spawn(Vec2::ZERO, AudioEmitter::looped(sound));
1138 let area = game.spawn(Vec2::ZERO, MusicArea::new(track, Vec2::splat(10.0)));
1139 let unknown = Handle::new(GenIndex::new(1_000, NonZeroU32::MIN));
1140 let stranger = game.spawn(Vec2::ZERO, AudioEmitter::looped(unknown));
1141 let sounds = ["warned-once.kpcm", "AudioEmitter"];
1142 let tracks = ["warned-once.qoa", "MusicArea"];
1143 let holds =
1144 format!("{stranger:?}'s AudioEmitter plays a sound the asset server does not hold");
1145 let warned = || (logged(&sounds), logged(&tracks), logged(&[&holds]));
1146 game.frames(5);
1147 assert_eq!(warned(), (1, 1, 1));
1148 assert_eq!(game.music_area(), None);
1149 assert_eq!(game.stats().unplayed, 0);
1150 game.emitter(emitter).params.volume = 0.5;
1152 game.app
1153 .world()
1154 .write::<MusicArea>()
1155 .get_mut(area)
1156 .expect("an area")
1157 .half = Vec2::splat(20.0);
1158 game.frames(5);
1159 assert_eq!(warned(), (2, 2, 1));
1160 assert_eq!(game.stats().active_voices, 0);
1161 }
1162
1163 #[test]
1164 fn the_area_playing_plays_on_when_its_music_changes_to_a_track_that_did_not_load() {
1165 let mut game = Game::new();
1166 let tone = game.track("audio/music/tone.qoa", &tone(400.0, 0.25));
1167 let quiet = game.track("audio/music/quiet.qoa", &[0; RATE as usize]);
1168 let missing = {
1169 let mut assets = game.assets();
1170 let missing = assets.load::<Music>("audio/music/plays-on.qoa");
1171 assets.finish_all_loads(&mut FinalizeCtx::new());
1172 missing
1173 };
1174 let mut area = MusicArea::new(tone, Vec2::splat(100.0));
1175 area.crossfade_ms = 100;
1176 let meadow = game.spawn(Vec2::ZERO, area);
1177 let out = game.frames(10);
1178 let full = rms(&out, FRAME - 480, 480);
1179 let play = |game: &Game, music: Handle<Music>| {
1180 let mut areas = game.app.world().write::<MusicArea>();
1181 areas.get_mut(meadow).expect("an area").music = music;
1182 };
1183 play(&game, missing);
1186 for _ in 0..10 {
1187 let out = game.frame();
1188 assert!((rms(&out, FRAME - 480, 480) / full - 1.0).abs() < 0.02);
1189 assert_eq!(game.music_area(), Some(meadow));
1190 }
1191 assert_eq!(logged(&["plays-on.qoa", "MusicArea"]), 1);
1192 play(&game, quiet);
1194 let out = game.frames(10);
1195 assert!(rms(&out, FRAME - 480, 480) < 1e-3);
1196 assert_eq!(game.music_area(), Some(meadow));
1197 }
1198
1199 #[cfg(feature = "dev")]
1202 mod steady {
1203 use nadir_core::time::Tick;
1204 use nadir_ecs::FixedStage;
1205 use nadir_platform::{AllocCounts, thread_alloc_counts};
1206
1207 use super::*;
1208
1209 const PERIOD: u64 = 120;
1211 const EMITTERS: usize = 40;
1213
1214 #[derive(Clone, Copy)]
1216 struct Path {
1217 centre: Vec2,
1218 swing: Vec2,
1219 phase: f32,
1220 }
1221
1222 impl Component for Path {}
1223
1224 fn follow(world: &World, tick: &Tick) {
1226 let turn = (tick.index % PERIOD) as f32 / PERIOD as f32 * TAU;
1227 let paths = world.read::<Path>();
1228 let mut transforms = world.write::<Transform>();
1229 for (entity, path) in paths.iter() {
1230 if let Some(transform) = transforms.get_mut(entity) {
1231 transform.position = path.centre + path.swing * (path.phase + turn).sin();
1232 }
1233 }
1234 }
1235
1236 fn scene() -> Game {
1237 let app = App::new(Config::default()).add_fixed_system(
1238 FixedStage::Gameplay,
1239 "follow",
1240 follow,
1241 );
1242 let mut game = Game::of(app);
1243 game.app.world_mut().register::<Path>();
1244 let hum = game.constant("audio/hum.kpcm", 0.01);
1245 let buzz = game.constant("audio/buzz.kpcm", 0.01);
1246 let low = game.track("audio/music/low.qoa", &tone(200.0, 0.25));
1247 let high = game.track("audio/music/high.qoa", &tone(800.0, 0.25));
1248 let listener = Path {
1251 centre: Vec2::ZERO,
1252 swing: Vec2::new(300.0, 0.0),
1253 phase: 0.0,
1254 };
1255 let start = |path: Path| path.centre + path.swing * path.phase.sin();
1256 let world = game.app.world_mut();
1257 world
1258 .spawn()
1259 .with(Transform::at(start(listener)))
1260 .with(listener)
1261 .with(AudioListener);
1262 for (x, music) in [(-200.0, low), (200.0, high)] {
1263 world
1264 .spawn()
1265 .with(Transform::at(Vec2::new(x, 0.0)))
1266 .with(MusicArea::new(music, Vec2::new(200.0, 400.0)));
1267 }
1268 for index in 0..EMITTERS {
1270 let way = Vec2::from_angle(TAU * index as f32 / EMITTERS as f32);
1271 let path = Path {
1272 centre: way * 800.0,
1273 swing: way * 250.0,
1274 phase: index as f32,
1275 };
1276 let sound = if index % 2 == 0 { hum } else { buzz };
1277 let at = Transform::at(start(path));
1278 world
1279 .spawn()
1280 .with(at)
1281 .with(PrevTransform(at))
1282 .with(path)
1283 .with(AudioEmitter::looped(sound));
1284 }
1285 game
1286 }
1287
1288 #[derive(Debug, Default, PartialEq)]
1291 struct Seen {
1292 fewest: u32,
1293 most: u32,
1294 changes: u32,
1295 }
1296
1297 fn pass(game: &mut Game, out: &mut [f32]) -> (AllocCounts, Seen) {
1299 let mut seen = Seen {
1300 fewest: u32::MAX,
1301 ..Seen::default()
1302 };
1303 let mut area = game.music_area();
1304 let before = thread_alloc_counts();
1305 for _ in 0..PERIOD {
1306 game.frame_into(TICK, out);
1307 let voices = game.stats().active_voices;
1308 seen.fewest = seen.fewest.min(voices);
1309 seen.most = seen.most.max(voices);
1310 if game.music_area() != area {
1311 seen.changes += 1;
1312 area = game.music_area();
1313 }
1314 }
1315 (thread_alloc_counts().since(before), seen)
1316 }
1317
1318 #[test]
1319 fn a_steady_frame_of_moving_emitters_a_listener_and_areas_allocates_nothing() {
1320 let mut game = scene();
1321 let mut out = vec![0.0; FRAME * 2];
1322 let (first, _) = pass(&mut game, &mut out);
1323 assert_ne!(first, AllocCounts::default(), "the first grows");
1324 let (_, second) = pass(&mut game, &mut out);
1325 let (third, seen) = pass(&mut game, &mut out);
1326 assert_eq!(third, AllocCounts::default(), "the steady pass allocated");
1327 assert_eq!(seen, second);
1330 assert!(
1331 seen.fewest < seen.most && seen.most < EMITTERS as u32,
1332 "{seen:?}"
1333 );
1334 assert_eq!(seen.changes, 2);
1335 assert_eq!(game.stats().dropped, 0);
1336 }
1337 }
1338}