Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_seq/
live.rs

1//! Notes the game plays itself, over the music: an ocarina, a jingle, a
2//! voice. They go through the same note engine as the song's own notes (the
3//! instrument's envelope, vibrato, the priority allocator), but nothing in a
4//! script owns them: the game starts, bends and releases each one.
5
6use crate::engine::vel_sq_q15;
7use crate::format::NONE16;
8use crate::tables::*;
9use crate::types::*;
10use crate::Sequencer;
11use psx_sfx::hw::Hw;
12
13/// A note started by [`Sequencer::note_on`]. A stale handle (the note ended
14/// and its voice was reused) is harmless: every call on it returns `false`.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct NoteHandle(u16);
17
18impl<'a, const P: usize, const N: usize> Sequencer<'a, P, N> {
19    fn live_index(&self, h: NoteHandle) -> Option<usize> {
20        let n = (h.0 >> 8) as usize;
21        let nt = self.notes.get(n)?;
22        (nt.live && nt.live_gen == (h.0 & 0xff) as u8 && nt.list != NoteList::Disabled).then_some(n)
23    }
24
25    /// Start a note: `instrument` of the soundfont whose original id is
26    /// `font_id` (it must be in the loaded bank), at semitone `key`, with
27    /// MIDI-like `velocity` and `pan` (0 left, 64 centre, 127 right) and a
28    /// note `priority` (1 to 15, larger is more important; it takes a free
29    /// voice, then an old decaying one, then the least important sounding
30    /// note below it). Returns `None` when no voice can be had.
31    ///
32    /// ```
33    /// # use psx_seq::Sequencer;
34    /// # use psx_sfx::hw::Recorder;
35    /// let mut seq: Sequencer<'_, 1, 4> = Sequencer::new(0b1111);
36    /// let mut hw = Recorder::<8>::new();
37    /// // no bank loaded: nothing to play
38    /// assert!(seq.note_on(&mut hw, 0, 0, 60, 100, 64, 9).is_none());
39    /// ```
40    #[allow(clippy::too_many_arguments)]
41    pub fn note_on(
42        &mut self,
43        hw: &mut impl Hw,
44        font_id: u8,
45        instrument: u8,
46        key: u8,
47        velocity: u8,
48        pan: u8,
49        priority: u8,
50    ) -> Option<NoteHandle> {
51        let bank = self.bank?;
52        let font = bank.font_index(font_id)?;
53        let ins = bank.instrument(font, instrument)?;
54        let tuned = ins.for_key(key);
55        let info = bank.sample(tuned.sample)?;
56        let priority = priority.clamp(1, 15);
57        let n = self.live_voice(hw, priority)?;
58        let gen = self.notes[n].live_gen.wrapping_add(1);
59        let nt = &mut self.notes[n];
60        *nt = Note::INIT;
61        nt.live = true;
62        nt.live_gen = gen;
63        nt.live_decay = ins.decay;
64        nt.priority = priority;
65        nt.adsr.env = if ins.env == NONE16 {
66            EnvRef::Default
67        } else {
68            EnvRef::Bank(ins.env)
69        };
70        nt.adsr.state = EnvState::Initial;
71        nt.tuned = TunedRef {
72            sample: tuned.sample,
73            tuning_q16: tuned.tuning_q16,
74        };
75        nt.sample_addr = self.spu_base + info.adpcm_off;
76        nt.sample_rate = info.rate_hz;
77        nt.sample_blocks = info.blocks;
78        nt.sample_looped = info.loop_block != NONE16;
79        nt.saved_freq_q16 = mul_q16(PITCH_Q16[(key & 0x7f) as usize], tuned.tuning_q16);
80        nt.saved_vel_q15 = vel_sq_q15(velocity);
81        nt.saved_pan = pan.min(127);
82        nt.needs_key_on = true;
83        nt.list = NoteList::Active;
84        self.move_front(n);
85        Some(NoteHandle(((n as u16) << 8) | gen as u16))
86    }
87
88    /// A voice for a live note of `priority`: free, else the oldest decaying,
89    /// else the least important sounding note below `priority` (cut off at
90    /// once, which can click; it is the last resort).
91    fn live_voice(&mut self, hw: &mut impl Hw, priority: u8) -> Option<usize> {
92        let pick = self
93            .edge(NoteList::Disabled, true)
94            .or_else(|| self.edge(NoteList::Decaying, true))
95            .or_else(|| self.lowest_below(NoteList::Releasing, priority))
96            .or_else(|| self.lowest_below(NoteList::Active, priority))?;
97        if self.notes[pick].list != NoteList::Disabled {
98            let parent = self.notes[pick].parent;
99            if parent != NO_OWNER {
100                let (p, c, l) = crate::engine::unpack(parent);
101                self.players[p].channels[c].layers[l].note = NONE8;
102            }
103            self.note_disable(pick, hw);
104            self.notes[pick].wanted = NO_OWNER;
105        }
106        Some(pick)
107    }
108
109    /// Whether the note is still sounding.
110    pub fn note_alive(&self, h: NoteHandle) -> bool {
111        self.live_index(h).is_some()
112    }
113
114    /// Bend the note's pitch by `bend_q16` (65536 = none, 131072 = an octave
115    /// up). Returns whether the handle was live.
116    pub fn note_bend(&mut self, h: NoteHandle, bend_q16: u32) -> bool {
117        match self.live_index(h) {
118            Some(n) => {
119                self.notes[n].porta_freq_q16 = bend_q16.max(1);
120                true
121            }
122            None => false,
123        }
124    }
125
126    /// Give the note vibrato, with the depth and rate units of the `vibdepth`
127    /// and `vibfreq` channel opcodes (0 turns it off).
128    pub fn note_vibrato(&mut self, h: NoteHandle, depth: u8, rate: u8) -> bool {
129        match self.live_index(h) {
130            Some(n) => {
131                let v = &mut self.notes[n].vib;
132                v.live = true;
133                v.active = depth != 0;
134                v.depth = depth as u32 * 8 * 256;
135                v.rate = rate as u32 * 32 * 256;
136                v.delay = 0;
137                if depth == 0 {
138                    self.notes[n].vib_freq_q16 = 1 << 16;
139                }
140                true
141            }
142            None => false,
143        }
144    }
145
146    /// Change a held note's loudness (`velocity` as in [`note_on`](Self::note_on)).
147    pub fn note_velocity(&mut self, h: NoteHandle, velocity: u8) -> bool {
148        match self.live_index(h) {
149            Some(n) => {
150                self.notes[n].saved_vel_q15 = vel_sq_q15(velocity);
151                true
152            }
153            None => false,
154        }
155    }
156
157    /// Let the note go: it decays at its instrument's release rate.
158    pub fn note_off(&mut self, h: NoteHandle) -> bool {
159        match self.live_index(h) {
160            Some(n) => {
161                if self.notes[n].phase == 0 {
162                    let decay = self.notes[n].live_decay;
163                    let nt = &mut self.notes[n];
164                    nt.phase = 1;
165                    nt.adsr.want_decay = true;
166                    nt.adsr.fade_out = release_step_q24(decay) as i32;
167                    nt.adsr.sustain = 0;
168                    nt.list = NoteList::Decaying;
169                    self.move_front(n);
170                }
171                true
172            }
173            None => false,
174        }
175    }
176}