diff --git a/native/shared/src/audio/mod.rs b/native/shared/src/audio/mod.rs index 2ddd4499..7d2bf19a 100644 --- a/native/shared/src/audio/mod.rs +++ b/native/shared/src/audio/mod.rs @@ -63,6 +63,7 @@ enum MusicSource { kind: stream::StreamKind, bytes: Arc>, channels: u16, + sample_rate: u32, }, } @@ -157,11 +158,30 @@ impl AudioMixer { ref_dist: f32, max_dist: f32, rolloff: f32, + ) -> f64 { + self.send_play_with(handle, spatial, looping, ref_dist, max_dist, rolloff, 1.0, 1.0, 0.0) + } + + /// `send_play` with a per-voice volume (multiplied onto the sound's own), + /// pitch and stereo pan from the start, so the first block is already + /// right (a volume set after the play would ramp in from the old level). + #[allow(clippy::too_many_arguments)] + fn send_play_with( + &mut self, + handle: f64, + spatial: Option<[f32; 3]>, + looping: bool, + ref_dist: f32, + max_dist: f32, + rolloff: f32, + gain: f32, + pitch: f32, + pan: f32, ) -> f64 { let Some(data) = self.sounds.get(handle).cloned() else { return 0.0; }; - let volume = self.get_sound_volume(handle); + let volume = self.get_sound_volume(handle) * gain.max(0.0); let (bus, send, lowpass) = self.routing(handle); self.next_voice += 1; let voice_id = self.next_voice; @@ -175,7 +195,8 @@ impl AudioMixer { ref_dist, max_dist, rolloff, - pitch: 1.0, + pitch, + pan, bus, send, lowpass, @@ -223,6 +244,22 @@ impl AudioMixer { ) } + /// Play a non-spatial voice and return its id (0.0 = unknown sound): the + /// handle a Web Audio source node needs to change its gain, rate and pan + /// while it plays, and to stop it. `looping` voices play until + /// [`Self::stop_voice`]. `pan` is a stereo balance, -1 (left) .. 1 (right). + pub fn play_sound_ex(&mut self, handle: f64, looping: bool, volume: f32, pitch: f32, pan: f32) -> f64 { + self.send_play_with(handle, None, looping, 1.0, 1.0e9, 1.0, volume, pitch, pan) + } + + /// Stereo balance of a non-spatial voice, -1..1. + pub fn set_voice_pan(&mut self, voice: f64, pan: f32) { + self.send(Cmd::SetVoicePan { + voice_id: voice as u64, + pan, + }); + } + pub fn set_voice_position(&mut self, voice: f64, x: f32, y: f32, z: f32) { self.send(Cmd::SetVoicePosition { voice_id: voice as u64, @@ -399,11 +436,12 @@ impl AudioMixer { None }; if let Some(kind) = kind { - if let Some((_rate, channels)) = stream::probe(kind, &data) { + if let Some((sample_rate, channels)) = stream::probe(kind, &data) { return self.alloc_music(MusicSource::Streamed { kind, bytes: Arc::new(data), channels, + sample_rate, }); } // Mislabelled file — fall through to sniffing decode. @@ -428,9 +466,28 @@ impl AudioMixer { } pub fn play_music(&mut self, handle: f64) { + self.play_music_from(handle, 0.0); + } + + /// Play a track from `seconds` into it (0 = the start). A streamed track + /// decodes and drops what comes before, so a seek costs decode time, + /// done on the decode worker. + pub fn play_music_from(&mut self, handle: f64, seconds: f64) { let Some(m) = self.music.get(handle) else { return; }; + let (rate, channels) = match &m.source { + MusicSource::Full(d) => (d.sample_rate, d.channels), + #[cfg(not(target_arch = "wasm32"))] + MusicSource::Streamed { + sample_rate, + channels, + .. + } => (*sample_rate, *channels), + }; + let start = (seconds.max(0.0) * rate as f64) as usize * channels.max(1) as usize; + // what music_time reports until the render thread confirms + m.shared.position.store(start, Ordering::Relaxed); // Optimistically flip the flag so is_music_playing is true the // moment play_music returns (the render thread confirms on its // next callback). @@ -442,8 +499,9 @@ impl AudioMixer { kind, bytes, channels, + .. } => render::MusicPayload::Stream { - consumer: stream::start(*kind, bytes.clone(), m.looping), + consumer: stream::start_at(*kind, bytes.clone(), m.looping, start), channels: *channels, }, }; @@ -453,6 +511,7 @@ impl AudioMixer { shared: m.shared.clone(), volume: m.volume, looping: m.looping, + start, }; self.send(cmd); } @@ -476,6 +535,51 @@ impl AudioMixer { }); } + /// Loop the track (the default) or play it once. Applies to the next + /// play and to the playback already running. + pub fn set_music_looping(&mut self, handle: f64, looping: bool) { + if let Some(m) = self.music.get_mut(handle) { + m.looping = looping; + } + self.send(Cmd::SetMusicLooping { + music_id: handle.to_bits(), + looping, + }); + } + + /// Seconds of the track played since its last play_music. A looping + /// streamed track keeps counting past its end (take it modulo the + /// track's length); a looping decoded one starts again from 0. + pub fn music_time(&self, handle: f64) -> f64 { + let Some(m) = self.music.get(handle) else { + return 0.0; + }; + let (rate, channels) = match &m.source { + MusicSource::Full(d) => (d.sample_rate, d.channels), + #[cfg(not(target_arch = "wasm32"))] + MusicSource::Streamed { + sample_rate, + channels, + .. + } => (*sample_rate, *channels), + }; + let consumed = m.shared.position.load(Ordering::Relaxed) as f64; + // Decoded mono advances one sample per frame, decoded stereo two; + // the streamed path counts samples the same way. + consumed / channels.max(1) as f64 / rate.max(1) as f64 + } + + /// Length of a fully decoded track in seconds; 0 for a streamed one + /// (its length is not known without decoding it all). + pub fn music_length(&self, handle: f64) -> f64 { + match self.music.get(handle).map(|m| &m.source) { + Some(MusicSource::Full(d)) => { + d.samples.len() as f64 / d.channels.max(1) as f64 / d.sample_rate.max(1) as f64 + } + _ => 0.0, + } + } + pub fn is_music_playing(&self, handle: f64) -> bool { self.music .get(handle) @@ -557,6 +661,89 @@ mod tests { buf.iter().fold(0.0f32, |m, s| m.max(s.abs())) } + // ---- Web Audio bridge ---------------------------------------------- + + fn stereo_peaks(buf: &[f32]) -> (f32, f32) { + let mut l = 0.0f32; + let mut r = 0.0f32; + for f in buf.chunks(2) { + l = l.max(f[0].abs()); + r = r.max(f[1].abs()); + } + (l, r) + } + + #[test] + fn play_sound_ex_returns_a_voice_with_its_volume() { + let mut a = AudioMixer::new(); + let h = a.load_sound(tone(4096)); + let v = a.play_sound_ex(h, false, 0.25, 1.0, 0.0); + assert!(v > 0.0, "no voice id"); + assert_eq!(a.play_sound_ex(999.0, false, 1.0, 1.0, 0.0), 0.0, "unknown sound must give 0"); + let mut out = [0.0f32; 256]; + a.mix_output(&mut out); + let (l, r) = stereo_peaks(&out); + assert!((l - 0.125).abs() < 1e-3 && (r - 0.125).abs() < 1e-3, "volume 0.25 of a 0.5 tone: {l} {r}"); + } + + #[test] + fn pan_moves_a_voice_between_channels() { + let mut a = AudioMixer::new(); + let h = a.load_sound(tone(1 << 14)); + let v = a.play_sound_ex(h, true, 1.0, 1.0, -1.0); + let mut out = [0.0f32; 256]; + a.mix_output(&mut out); + let (l, r) = stereo_peaks(&out); + assert!(l > 0.4 && r < 1e-4, "hard left: {l} {r}"); + a.set_voice_pan(v, 1.0); + a.mix_output(&mut out); // ramps across this block + a.mix_output(&mut out); + let (l, r) = stereo_peaks(&out); + assert!(r > 0.4 && l < 1e-4, "hard right: {l} {r}"); + } + + #[test] + fn music_once_ends_and_reports_time() { + let mut a = AudioMixer::new(); + // 0.5 s of mono at 44.1 kHz + let m = a.load_music(tone(22_050)); + assert!((a.music_length(m) - 0.5).abs() < 1e-6); + a.set_music_looping(m, false); + a.play_music(m); + let mut out = vec![0.0f32; 2 * 11_025]; // 0.25 s + a.mix_output(&mut out); + assert!((a.music_time(m) - 0.25).abs() < 1e-3, "time {}", a.music_time(m)); + a.mix_output(&mut out); + a.mix_output(&mut out); + assert!(!a.is_music_playing(m), "a track played once must stop at its end"); + } + + #[test] + fn music_plays_from_an_offset() { + let mut a = AudioMixer::new(); + let m = a.load_music(tone(44_100)); // 1 s + a.set_music_looping(m, false); + a.play_music_from(m, 0.75); + assert!((a.music_time(m) - 0.75).abs() < 1e-3, "starts at the offset: {}", a.music_time(m)); + let mut out = vec![0.0f32; 2 * 22_050]; // 0.5 s: past the end + a.mix_output(&mut out); + assert!(!a.is_music_playing(m), "0.25 s left, so 0.5 s of mixing ends it"); + } + + #[test] + fn music_volume_ramps_instead_of_jumping() { + let mut a = AudioMixer::new(); + let m = a.load_music(tone(1 << 16)); + a.play_music(m); + let mut out = [0.0f32; 512]; + a.mix_output(&mut out); + a.set_music_volume(m, 0.0); + a.mix_output(&mut out); + // the first frame of the block is still at the old level, the last near 0 + assert!(out[0].abs() > 0.4, "ramp starts at the old gain: {}", out[0]); + assert!(out[510].abs() < 0.01, "ramp ends at the new gain: {}", out[510]); + } + #[test] fn bus_gain_scales_only_its_own_bus() { let mut a = AudioMixer::new(); diff --git a/native/shared/src/audio/render.rs b/native/shared/src/audio/render.rs index 027db171..3f60fc28 100644 --- a/native/shared/src/audio/render.rs +++ b/native/shared/src/audio/render.rs @@ -73,6 +73,8 @@ pub enum Cmd { rolloff: f32, /// EN-062 — playback-rate multiplier (doppler multiplies on top). pitch: f32, + /// Stereo balance of a non-spatial voice, -1 (left) .. 1 (right). + pan: f32, /// EN-029 — mix bus (see [`bus`]), reverb send (0..1) and low-pass /// cutoff in Hz (<= 0 or >= NYQUIST = bypass). bus: u8, @@ -92,6 +94,9 @@ pub enum Cmd { shared: Arc, volume: f32, looping: bool, + /// Interleaved samples into the track to start at (a seek). A streamed + /// track's worker already skipped them; this only seeds the position. + start: usize, }, StopMusic { music_id: u64, @@ -160,6 +165,16 @@ pub enum Cmd { voice_id: u64, cutoff: f32, }, + /// Stereo balance of a non-spatial voice (spatial voices pan from + /// their position and ignore it). + SetVoicePan { + voice_id: u64, + pan: f32, + }, + SetMusicLooping { + music_id: u64, + looping: bool, + }, } /// Mix buses. Kept tiny and fixed: a general submix graph is a lot of @@ -257,6 +272,8 @@ struct Voice { rolloff: f32, /// Game-set playback rate. Doppler multiplies on top of it. pitch: f32, + /// Stereo balance when not spatial, -1..1. + pan: f32, /// Smoothed doppler rate. doppler: f32, /// Listener distance last block; < 0 = not yet seeded. @@ -326,6 +343,10 @@ struct MusicVoice { looping: bool, /// Total samples consumed (drives the shared position mirror). consumed: usize, + /// Gain applied in the last block; the next block ramps from it to its + /// target, so per-frame fades (crossfades, ducking) never zipper. + gain: f32, + seeded: bool, } /// EN-029 — a Schroeder reverb: parallel comb filters (the density) into @@ -463,6 +484,7 @@ impl AudioRenderer { max_dist, rolloff, pitch, + pan, bus, send, lowpass, @@ -498,6 +520,7 @@ impl AudioRenderer { max_dist: max_dist.max(0.0), rolloff: rolloff.max(0.0), pitch: pitch.clamp(0.25, 4.0), + pan: pan.clamp(-1.0, 1.0), doppler: 1.0, prev_dist: -1.0, g_l: 0.0, @@ -526,13 +549,17 @@ impl AudioRenderer { shared, volume, looping, + start, } => { - // Restart-from-zero semantics (matches the old mixer). + // Restart semantics (matches the old mixer), from `start`. self.music.retain(|m| m.music_id != music_id); shared.playing.store(true, Ordering::Relaxed); - shared.position.store(0, Ordering::Relaxed); + shared.position.store(start, Ordering::Relaxed); let samples = match payload { - MusicPayload::Full(data) => MusicSamples::Full { data, position: 0 }, + MusicPayload::Full(data) => { + let position = start.min(data.samples.len()); + MusicSamples::Full { data, position } + } #[cfg(not(target_arch = "wasm32"))] MusicPayload::Stream { consumer, channels } => MusicSamples::Stream { consumer, @@ -555,7 +582,9 @@ impl AudioRenderer { shared, volume, looping, - consumed: 0, + consumed: start, + gain: 0.0, + seeded: false, }); } Cmd::StopMusic { music_id } => { @@ -649,6 +678,20 @@ impl AudioRenderer { } } } + Cmd::SetVoicePan { voice_id, pan } => { + for v in &mut self.voices { + if v.voice_id == voice_id { + v.pan = pan.clamp(-1.0, 1.0); + } + } + } + Cmd::SetMusicLooping { music_id, looping } => { + for m in &mut self.music { + if m.music_id == music_id { + m.looping = looping; + } + } + } } } @@ -760,6 +803,10 @@ impl AudioRenderer { } } (gl, gr, dist) + } else if v.pan != 0.0 { + // Balance, not equal-power: centred stays at unity, so a + // voice that never pans is as loud as before. + ((1.0 - v.pan).min(1.0), (1.0 + v.pan).min(1.0), -1.0) } else { (1.0, 1.0, -1.0) }; @@ -912,15 +959,23 @@ impl AudioRenderer { // when the player takes a hit" is the single most-used mix move in the // genre and it needs music to be separable from SFX. let music_gain = bus_gain[bus::MUSIC as usize]; + let music_frames = (output.len() / 2).max(1) as f32; music.retain_mut(|m| { - let vol = m.volume * master * music_gain; + let target = m.volume * master * music_gain; + if !m.seeded { + m.gain = target; + m.seeded = true; + } + let g0 = m.gain; + let dg = (target - g0) / music_frames; + m.gain = target; let mut i = 0; let mut finished = false; match &mut m.samples { MusicSamples::Full { data, position } => { while i < output.len() && *position < data.samples.len() { if data.channels == 1 { - let sample = data.samples[*position] * vol; + let sample = data.samples[*position] * (g0 + dg * (i / 2) as f32); output[i] += sample; if i + 1 < output.len() { output[i + 1] += sample; @@ -928,7 +983,7 @@ impl AudioRenderer { *position += 1; i += 2; } else { - output[i] += data.samples[*position] * vol; + output[i] += data.samples[*position] * (g0 + dg * (i / 2) as f32); *position += 1; i += 1; } @@ -970,7 +1025,7 @@ impl AudioRenderer { } } if mono { - let sample = current[*offset] * vol; + let sample = current[*offset] * (g0 + dg * (i / 2) as f32); output[i] += sample; if i + 1 < output.len() { output[i + 1] += sample; @@ -979,7 +1034,7 @@ impl AudioRenderer { m.consumed += 1; i += 2; } else { - output[i] += current[*offset] * vol; + output[i] += current[*offset] * (g0 + dg * (i / 2) as f32); *offset += 1; m.consumed += 1; i += 1; @@ -1026,6 +1081,7 @@ mod tests { max_dist: 0.0, rolloff: 1.0, pitch: 1.0, + pan: 0.0, bus: bus::SFX, send: 0.0, lowpass: 0.0, diff --git a/native/shared/src/audio/stream.rs b/native/shared/src/audio/stream.rs index e38fdc34..6e18d15c 100644 --- a/native/shared/src/audio/stream.rs +++ b/native/shared/src/audio/stream.rs @@ -80,12 +80,19 @@ pub fn probe(kind: StreamKind, bytes: &[u8]) -> Option<(u32, u16)> { /// Spawn the decode worker for one playback of a streamed track. #[cfg(not(target_arch = "wasm32"))] pub fn start(kind: StreamKind, bytes: Arc>, looping: bool) -> StreamConsumer { + start_at(kind, bytes, looping, 0) +} + +/// Like [`start`], from `skip` interleaved samples into the track (a seek): +/// the worker decodes and drops them before it pushes anything. +#[cfg(not(target_arch = "wasm32"))] +pub fn start_at(kind: StreamKind, bytes: Arc>, looping: bool, skip: usize) -> StreamConsumer { let (tx, rx) = spsc::channel(RING_CHUNKS + 1); let stop = Arc::new(AtomicBool::new(false)); let stop_worker = stop.clone(); std::thread::Builder::new() .name("bloom-music-decode".into()) - .spawn(move || run_worker(kind, &bytes, looping, tx, &stop_worker)) + .spawn(move || run_worker(kind, &bytes, looping, skip, tx, &stop_worker)) .expect("spawn music decode worker"); StreamConsumer { rx, stop } } @@ -95,6 +102,7 @@ fn run_worker( kind: StreamKind, bytes: &[u8], looping: bool, + mut skip: usize, mut tx: Producer, stop: &AtomicBool, ) { @@ -118,9 +126,9 @@ fn run_worker( loop { let completed = match kind { - StreamKind::Ogg => decode_ogg(bytes, stop, &mut push), + StreamKind::Ogg => decode_ogg(bytes, stop, &mut skip, &mut push), #[cfg(feature = "mp3")] - StreamKind::Mp3 => decode_mp3(bytes, stop, &mut push), + StreamKind::Mp3 => decode_mp3(bytes, stop, &mut skip, &mut push), }; if !completed || !looping { break; @@ -133,7 +141,7 @@ fn run_worker( /// Decode one full pass of the track, pushing chunks. Returns false if /// stopped early (stop flag / consumer gone). #[cfg(not(target_arch = "wasm32"))] -fn decode_ogg(bytes: &[u8], stop: &AtomicBool, push: &mut dyn FnMut(StreamMsg) -> bool) -> bool { +fn decode_ogg(bytes: &[u8], stop: &AtomicBool, skip: &mut usize, push: &mut dyn FnMut(StreamMsg) -> bool) -> bool { let Ok(mut reader) = lewton::inside_ogg::OggStreamReader::new(std::io::Cursor::new(bytes)) else { return false; @@ -144,6 +152,10 @@ fn decode_ogg(bytes: &[u8], stop: &AtomicBool, push: &mut dyn FnMut(StreamMsg) - return false; } for &s in &packet { + if *skip > 0 { + *skip -= 1; + continue; + } chunk.push(s as f32 / 32768.0); } if chunk.len() >= CHUNK_SAMPLES { @@ -160,7 +172,7 @@ fn decode_ogg(bytes: &[u8], stop: &AtomicBool, push: &mut dyn FnMut(StreamMsg) - } #[cfg(all(feature = "mp3", not(target_arch = "wasm32")))] -fn decode_mp3(bytes: &[u8], stop: &AtomicBool, push: &mut dyn FnMut(StreamMsg) -> bool) -> bool { +fn decode_mp3(bytes: &[u8], stop: &AtomicBool, skip: &mut usize, push: &mut dyn FnMut(StreamMsg) -> bool) -> bool { let mut decoder = minimp3::Decoder::new(std::io::Cursor::new(bytes)); let mut chunk: Vec = Vec::with_capacity(CHUNK_SAMPLES); loop { @@ -170,6 +182,10 @@ fn decode_mp3(bytes: &[u8], stop: &AtomicBool, push: &mut dyn FnMut(StreamMsg) - match decoder.next_frame() { Ok(frame) => { for &s in &frame.data { + if *skip > 0 { + *skip -= 1; + continue; + } chunk.push(s as f32 / 32768.0); } if chunk.len() >= CHUNK_SAMPLES { diff --git a/native/shared/src/ffi_core/audio_ffi.rs b/native/shared/src/ffi_core/audio_ffi.rs index c805b6d2..c0c49430 100644 --- a/native/shared/src/ffi_core/audio_ffi.rs +++ b/native/shared/src/ffi_core/audio_ffi.rs @@ -212,5 +212,69 @@ macro_rules! __bloom_ffi_audio_ffi { engine().audio.set_voice_lowpass(voice, cutoff as f32); }) } + + // ---- Web Audio bridge: non-spatial voices, music position -------- + // + // A Web Audio source node is a voice that changes gain, rate and pan + // while it plays; an