Skip to main content

openblood/
audio.rs

1//! Sound effects: SFX/RAW from SOUNDS.RFF mixed in software with 3D panning.
2
3use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
4use ob_game::game::{Game, GameEvent};
5use ob_game::resources::Resources;
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex};
8
9/// Sprite types that generate sounds.
10const SOUND_SECTOR: i16 = 709;
11const SOUND_AMBIENT: i16 = 710;
12
13pub struct Sound {
14    /// Unsigned 8-bit PCM as stored in SOUNDS.RFF (converted while mixing).
15    pub samples: Vec<u8>,
16    pub rate: u32,
17    pub loop_start: Option<usize>,
18    pub volume: f32,
19    pub pitch: f32,
20}
21
22/// Parses a Blood `.SFX` descriptor: relVol, pitch, pitchRange, format, loopStart, `rawName[9]`.
23pub fn parse_sfx(b: &[u8]) -> Option<(i32, i32, i32, i32, i32, String)> {
24    if b.len() < 21 {
25        return None;
26    }
27    let rd = |o: usize| i32::from_le_bytes(b[o..o + 4].try_into().unwrap());
28    let name_bytes = &b[20..b.len().min(29)];
29    let end = name_bytes.iter().position(|&c| c == 0).unwrap_or(name_bytes.len());
30    let name = String::from_utf8_lossy(&name_bytes[..end]).to_string();
31    Some((rd(0), rd(4), rd(8), rd(12), rd(16), name))
32}
33
34pub fn sfx_rate(format: i32) -> u32 {
35    match format {
36        f if f >= 9 => 44100,
37        5..=8 => 22050,
38        _ => 11025,
39    }
40}
41
42struct Channel {
43    sound: Arc<Sound>,
44    pos: f64,
45    step: f64,
46    vol_l: f32,
47    vol_r: f32,
48    /// World position for positional sounds.
49    at: Option<(f64, f64, f64)>,
50    radius: (f64, f64),
51    base: f32,
52    looping: bool,
53    owner: i64,
54}
55
56#[derive(Default)]
57struct Mixer {
58    channels: Vec<Channel>,
59    out_rate: f64,
60    master: f32,
61    /// Streamed interleaved stereo 44.1 kHz music.
62    music: Option<MusicStream>,
63    music_vol: f32,
64    /// A cutscene is playing: level music is silent.
65    movie: bool,
66}
67
68/// Channel owner id of cutscene soundtracks.
69pub const MOVIE_OWNER: i64 = -1000;
70
71/// Music arriving in chunks from a reader thread ([`crate::cdaudio::stream_wav`]).
72struct MusicStream {
73    rx: std::sync::mpsc::Receiver<Vec<i16>>,
74    cur: Vec<i16>,
75    /// Play position in frames within `cur`.
76    pos: f64,
77}
78
79impl Mixer {
80    fn mix(&mut self, out: &mut [f32], nch: usize) {
81        for s in out.iter_mut() {
82            *s = 0.0;
83        }
84        let frames = out.len() / nch;
85        for ch in self.channels.iter_mut() {
86            let data = &ch.sound.samples;
87            for f in 0..frames {
88                let i = ch.pos as usize;
89                if i >= data.len() {
90                    match (ch.looping, ch.sound.loop_start) {
91                        (true, Some(ls)) if ls < data.len() => ch.pos = ls as f64,
92                        (true, None) => ch.pos = 0.0,
93                        _ => break,
94                    }
95                }
96                let i = ch.pos as usize;
97                let v = (data[i.min(data.len() - 1)] as f32 - 128.0) * (1.0 / 128.0);
98                if nch >= 2 {
99                    out[f * nch] += v * ch.vol_l;
100                    out[f * nch + 1] += v * ch.vol_r;
101                } else {
102                    out[f] += v * (ch.vol_l + ch.vol_r) * 0.5;
103                }
104                ch.pos += ch.step;
105            }
106        }
107        self.channels
108            .retain(|c| (c.pos as usize) < c.sound.samples.len() || c.looping);
109        for s in out.iter_mut() {
110            *s *= self.master;
111        }
112        if let Some(ms) = self.music.as_mut().filter(|_| !self.movie) {
113            let step = 44100.0 / self.out_rate;
114            let vol = self.music_vol / 32768.0;
115            'frames: for f in 0..frames {
116                let mut i = ms.pos as usize;
117                while i * 2 + 1 >= ms.cur.len() {
118                    match ms.rx.try_recv() {
119                        Ok(next) => {
120                            ms.pos = (ms.pos - (ms.cur.len() / 2) as f64).max(0.0);
121                            ms.cur = next;
122                            i = ms.pos as usize;
123                        }
124                        // Not read yet (or stopped): silence until the next chunk arrives.
125                        Err(_) => break 'frames,
126                    }
127                }
128                let (l, r) = (ms.cur[i * 2] as f32 * vol, ms.cur[i * 2 + 1] as f32 * vol);
129                if nch >= 2 {
130                    out[f * nch] += l;
131                    out[f * nch + 1] += r;
132                } else {
133                    out[f] += (l + r) * 0.5;
134                }
135                ms.pos += step;
136            }
137        }
138        for s in out.iter_mut() {
139            *s = s.clamp(-1.0, 1.0);
140        }
141    }
142}
143
144pub struct Audio {
145    _stream: cpal::Stream,
146    mixer: Arc<Mutex<Mixer>>,
147    cache: HashMap<i32, Option<Arc<Sound>>>,
148    map_name: String,
149    rng: u32,
150    /// CD track and song of the music playing (to keep it going across reloads).
151    music: (u32, String),
152    /// AdLib timbre bank for MIDI music (GMTIMBRE.TMB), if present.
153    timbres: Option<Vec<crate::fm::Timbre>>,
154}
155
156impl Audio {
157    pub fn new(res: &Resources) -> Result<Audio, String> {
158        let host = cpal::default_host();
159        let device = host.default_output_device().ok_or("no audio device")?;
160        let supported = device.default_output_config().map_err(|e| e.to_string())?;
161        let format = supported.sample_format();
162        let config: cpal::StreamConfig = supported.into();
163        let nch = config.channels as usize;
164        let mixer = Arc::new(Mutex::new(Mixer {
165            out_rate: config.sample_rate.0 as f64,
166            master: 0.8,
167            ..Default::default()
168        }));
169        let m2 = mixer.clone();
170        let err = |e| eprintln!("audio error: {e}");
171        let stream = match format {
172            cpal::SampleFormat::F32 => device.build_output_stream(
173                &config,
174                move |data: &mut [f32], _| m2.lock().unwrap().mix(data, nch),
175                err,
176                None,
177            ),
178            cpal::SampleFormat::I16 => {
179                let mut tmp = Vec::new();
180                device.build_output_stream(
181                    &config,
182                    move |data: &mut [i16], _| {
183                        tmp.resize(data.len(), 0.0f32);
184                        m2.lock().unwrap().mix(&mut tmp, nch);
185                        for (d, s) in data.iter_mut().zip(tmp.iter()) {
186                            *d = (s * 32767.0) as i16;
187                        }
188                    },
189                    err,
190                    None,
191                )
192            }
193            other => return Err(format!("unsupported sample format {other:?}")),
194        }
195        .map_err(|e| e.to_string())?;
196        stream.play().map_err(|e| e.to_string())?;
197        let mut audio = Audio {
198            _stream: stream,
199            mixer,
200            cache: HashMap::new(),
201            map_name: String::new(),
202            rng: 12345,
203            music: (0, String::new()),
204            timbres: res
205                .sounds
206                .as_ref()
207                .and_then(|r| r.read_name("GMTIMBRE.TMB"))
208                .and_then(|b| crate::midi::parse_bank(&b)),
209        };
210        audio.preload_all(res);
211        Ok(audio)
212    }
213
214    fn rand(&mut self) -> u32 {
215        self.rng = self.rng.wrapping_mul(1103515245).wrapping_add(12345);
216        self.rng >> 16
217    }
218
219    /// Decodes every sound effect once, up front (about the size of SOUNDS.RFF in memory),
220    /// so starting a level or firing a weapon never waits for a sound to load.
221    fn preload_all(&mut self, res: &Resources) {
222        let t = std::time::Instant::now();
223        let ids: Vec<u32> = res
224            .sounds
225            .as_ref()
226            .map(|r| r.entries.iter().filter(|e| e.ext == "SFX").map(|e| e.id).collect())
227            .unwrap_or_default();
228        for id in &ids {
229            self.load(res, *id as i32);
230        }
231        if std::env::var_os("OB_PROFILE").is_some() {
232            eprintln!(
233                "preloaded {} sounds in {:.1} ms",
234                ids.len(),
235                t.elapsed().as_secs_f64() * 1e3
236            );
237        }
238    }
239
240    pub fn load(&mut self, res: &Resources, id: i32) -> Option<Arc<Sound>> {
241        if let Some(s) = self.cache.get(&id) {
242            return s.clone();
243        }
244        let snd = (|| {
245            let rff = res.sounds.as_ref()?;
246            let sfx = rff.read_id("SFX", id as u32)?;
247            let (vol, pitch, _range, format, loop_start, raw) = parse_sfx(&sfx)?;
248            let pcm = rff.read_name(&format!("{raw}.RAW"))?;
249            Some(Arc::new(Sound {
250                samples: pcm,
251                rate: sfx_rate(format),
252                loop_start: (loop_start >= 0).then_some(loop_start as usize),
253                volume: (vol as f32 / 80.0).clamp(0.0, 2.0),
254                pitch: if pitch > 0 { pitch as f32 / 65536.0 } else { 1.0 },
255            }))
256        })();
257        self.cache.insert(id, snd.clone());
258        snd
259    }
260
261    /// Plays sound `id`, optionally at a world position.
262    pub fn play(
263        &mut self,
264        res: &Resources,
265        id: i32,
266        at: Option<(f64, f64, f64)>,
267        looping: bool,
268        radius: (f64, f64),
269        owner: i64,
270    ) {
271        let Some(snd) = self.load(res, id) else { return };
272        let jitter = 1.0 + ((self.rand() % 100) as f64 - 50.0) / 2000.0;
273        let mut m = self.mixer.lock().unwrap();
274        let step = snd.rate as f64 / m.out_rate * snd.pitch as f64 * jitter;
275        let base = snd.volume;
276        m.channels.push(Channel {
277            sound: snd,
278            pos: 0.0,
279            step,
280            vol_l: base * 0.7,
281            vol_r: base * 0.7,
282            at,
283            radius,
284            base,
285            looping,
286            owner,
287        });
288    }
289
290    /// Stops game sounds (a playing cutscene soundtrack keeps going).
291    pub fn stop_all(&mut self) {
292        self.mixer.lock().unwrap().channels.retain(|c| c.owner == MOVIE_OWNER);
293    }
294
295    /// Plays a cutscene soundtrack (unsigned 8-bit mono PCM) and turns the music off until
296    /// [`Audio::stop_movie`].
297    pub fn play_movie_sound(&mut self, samples: Vec<u8>, rate: u32) {
298        let snd = Arc::new(Sound {
299            samples,
300            rate,
301            loop_start: None,
302            volume: 1.0,
303            pitch: 1.0,
304        });
305        let mut m = self.mixer.lock().unwrap();
306        m.channels.retain(|c| c.owner != MOVIE_OWNER);
307        let step = rate as f64 / m.out_rate;
308        m.channels.push(Channel {
309            sound: snd,
310            pos: 0.0,
311            step,
312            vol_l: 0.9,
313            vol_r: 0.9,
314            at: None,
315            radius: (1.0, 2.0),
316            base: 0.9,
317            looping: false,
318            owner: MOVIE_OWNER,
319        });
320        m.movie = true;
321    }
322
323    /// Stops the cutscene soundtrack and brings the music back.
324    pub fn stop_movie(&mut self) {
325        let mut m = self.mixer.lock().unwrap();
326        m.channels.retain(|c| c.owner != MOVIE_OWNER);
327        m.movie = false;
328    }
329
330    fn start_level(&mut self, res: &Resources, game: &Game) {
331        self.stop_all();
332        for (i, s) in game.world.sprites.iter().enumerate() {
333            if s.lotag == SOUND_AMBIENT {
334                if let Some(x) = game.world.xsprite(i) {
335                    if x.data3 > 0 {
336                        let r = (x.data1.max(1) as f64, x.data2.max(x.data1 + 1) as f64);
337                        self.play(
338                            res,
339                            x.data3,
340                            Some((s.x as f64, s.y as f64, s.z as f64)),
341                            true,
342                            r,
343                            i as i64,
344                        );
345                    }
346                }
347            }
348        }
349    }
350
351    pub fn on_event(&mut self, res: &Resources, game: &Game, e: &GameEvent) {
352        if let GameEvent::Sound { id, at } = *e {
353            self.play(res, id, at, false, (1500.0, 24000.0), -1);
354            return;
355        }
356        if let GameEvent::SectorSound { sector, opening, start } = *e {
357            for (i, s) in game.world.sprites.iter().enumerate() {
358                if s.lotag != SOUND_SECTOR || s.sectnum as usize != sector {
359                    continue;
360                }
361                let Some(x) = game.world.xsprite(i) else { continue };
362                let id = match (opening, start) {
363                    (true, true) => x.data1,
364                    (true, false) => x.data2,
365                    (false, true) => x.data3,
366                    (false, false) => x.data4 as i32,
367                };
368                if id > 0 {
369                    self.play(
370                        res,
371                        id,
372                        Some((s.x as f64, s.y as f64, s.z as f64)),
373                        false,
374                        (1024.0, 16384.0),
375                        -1,
376                    );
377                }
378            }
379        }
380    }
381
382    /// Updates positional volumes and panning; restarts ambience on level change.
383    pub fn update_listener(&mut self, game: &Game) {
384        if game.world.map_name != self.map_name {
385            self.map_name = game.world.map_name.clone();
386            // Needs resources; deferred to `level_changed`.
387            self.cache.retain(|_, v| v.is_some());
388        }
389        let p = &game.player;
390        let a = ob_engine::geom::ang_to_rad(p.ang);
391        let (fx, fy) = (a.cos(), a.sin());
392        let mut m = self.mixer.lock().unwrap();
393        for ch in m.channels.iter_mut() {
394            let Some((x, y, z)) = ch.at else { continue };
395            let dx = x - p.x;
396            let dy = y - p.y;
397            let dz = (z - p.z) / 16.0;
398            let d = (dx * dx + dy * dy + dz * dz).sqrt();
399            let (r0, r1) = ch.radius;
400            let att = if d <= r0 {
401                1.0
402            } else if d >= r1 {
403                0.0
404            } else {
405                1.0 - (d - r0) / (r1 - r0)
406            };
407            let side = if d > 1.0 { (-dx * fy + dy * fx) / d } else { 0.0 };
408            let pan_r = (0.5 + side * 0.4) as f32;
409            let v = ch.base * att as f32;
410            ch.vol_l = v * (1.0 - pan_r) * 1.4;
411            ch.vol_r = v * pan_r * 1.4;
412        }
413    }
414
415    pub fn level_changed(&mut self, res: &Resources, game: &Game) {
416        self.start_level(res, game);
417        let (track, song) = res
418            .ini
419            .map(&game.world.map_name)
420            .map_or((0, String::new()), |m| (m.track, m.song.clone()));
421        self.play_music(res, track, &song);
422    }
423
424    pub fn set_volumes(&mut self, sfx: f32, music: f32) {
425        let mut m = self.mixer.lock().unwrap();
426        m.master = sfx;
427        m.music_vol = music;
428    }
429
430    /// Plays CD track `n` from `music/TRACKnn.WAV` (ripped from the user's own disc). When
431    /// that file is missing, plays the MIDI `song` from SOUNDS.RFF with the FM synthesizer.
432    pub fn play_music(&mut self, res: &Resources, n: u32, song: &str) {
433        let key = (n, song.to_ascii_uppercase());
434        if key == self.music {
435            return;
436        }
437        self.music = key;
438        let mixer = self.mixer.clone();
439        mixer.lock().unwrap().music = None;
440        let candidates = [
441            res.dir.join("music").join(format!("TRACK{n:02}.WAV")),
442            res.dir.join(format!("TRACK{n:02}.WAV")),
443        ];
444        // Streamed from disk: no big allocation or conversion when a level starts.
445        let rx = (n != 0)
446            .then(|| candidates.iter().find_map(|p| crate::cdaudio::stream_wav(p)))
447            .flatten()
448            .or_else(|| self.midi_stream(res, song));
449        if let Some(rx) = rx {
450            mixer.lock().unwrap().music = Some(MusicStream {
451                rx,
452                cur: Vec::new(),
453                pos: 0.0,
454            });
455        }
456    }
457
458    /// Synthesized playback of `NAME.MID` from SOUNDS.RFF.
459    fn midi_stream(&self, res: &Resources, song: &str) -> Option<std::sync::mpsc::Receiver<Vec<i16>>> {
460        if song.is_empty() {
461            return None;
462        }
463        let bank = self.timbres.clone()?;
464        let bytes = res
465            .sounds
466            .as_ref()?
467            .read_name(&format!("{}.MID", song.to_ascii_uppercase()))?;
468        match crate::midi::Song::parse(&bytes) {
469            Ok(s) => Some(crate::midi::stream(s, bank)),
470            Err(e) => {
471                eprintln!("{song}.MID: {e}");
472                None
473            }
474        }
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481
482    #[test]
483    fn sfx_descriptor() {
484        let mut b = vec![0u8; 29];
485        b[0] = 80;
486        b[6] = 1; // pitch 0x10000
487        b[12] = 5;
488        b[16..20].copy_from_slice(&(-1i32).to_le_bytes());
489        b[20..24].copy_from_slice(b"amb3");
490        let (v, p, _, f, l, n) = parse_sfx(&b).unwrap();
491        assert_eq!((v, p, f, l, n.as_str()), (80, 0x10000, 5, -1, "amb3"));
492        assert_eq!(sfx_rate(f), 22050);
493    }
494}