use super::*;
fn step_index(v: u32) -> Option<Option<u16>> {
match v {
0 => Some(None),
v => u16::try_from(v - 1).ok().map(Some),
}
}
pub(super) fn read_detune<'a>(data: &'a [u8], pos: &mut usize) -> Option<Detune<'a>> {
let n = read_varint(data, pos)? as usize;
let l = read_varint(data, pos)?;
let r = read_varint(data, pos)?;
let end = pos.checked_add(n.checked_mul(PACKED_STEP_LEN)?)?;
let steps = data.get(*pos..end)?;
*pos = end;
Some(Detune {
steps: DetuneSteps::Packed(steps),
loop_at: step_index(l)?,
release_at: step_index(r)?,
})
}
pub(super) fn detune_at(data: &[u8], start: usize, index: u8) -> Option<Detune<'_>> {
let mut pos = start;
let mut found = None;
for _ in 0..=index {
found = read_detune(data, &mut pos);
found?;
}
found
}
pub(super) fn vibrato_at(data: &[u8], start: usize, index: u8) -> Option<Vibrato> {
let at = start.checked_add(index as usize * VIBRATO_ENTRY_LEN)?;
match data.get(at..at.checked_add(VIBRATO_ENTRY_LEN)?)? {
&[delay, speed, depth] => Some(Vibrato {
delay,
speed,
depth,
}),
_ => None,
}
}
#[derive(Clone, Copy)]
pub(super) struct Lookup<'a> {
pub(super) data: &'a [u8],
pub(super) tables: Tables,
pub(super) transpose: i8,
}
impl<'a> Lookup<'a> {
pub(super) fn env(&self, i: Option<u8>) -> Option<Envelope<'a>> {
i.and_then(|i| envelope_at(self.data, self.tables.env, i))
}
pub(super) fn vib(&self, i: Option<u8>) -> Option<Vibrato> {
i.and_then(|i| vibrato_at(self.data, self.tables.vib, i))
}
pub(super) fn det(&self, i: Option<u8>) -> Option<Detune<'a>> {
i.and_then(|i| detune_at(self.data, self.tables.det, i))
}
pub(super) fn pitch_fx(&self, c: &Cursor) -> PitchFx<'a> {
PitchFx {
vib: self.vib(c.vib_current),
detune: self.det(c.detune_current),
arp: self.arp(c.arp_current),
}
}
pub(super) fn wave(&self, i: u8) -> Option<[i8; WAVE_LEN]> {
if i >= self.tables.waves {
return None;
}
let at = self.tables.wave + i as usize * WAVE_LEN;
let bytes = self.data.get(at..at + WAVE_LEN)?;
let mut w = [0i8; WAVE_LEN];
for (d, s) in w.iter_mut().zip(bytes) {
*d = *s as i8;
}
Some(w)
}
pub(super) fn duty(&self, i: Option<u8>) -> Option<Envelope<'a>> {
i.filter(|&i| i < self.tables.duties)
.and_then(|i| envelope_at(self.data, self.tables.duty, i))
}
pub(super) fn arp(&self, i: Option<u8>) -> Option<Detune<'a>> {
i.and_then(|i| detune_at(self.data, self.tables.arp, i))
}
}
pub(super) fn read_envelope<'a>(data: &'a [u8], pos: &mut usize) -> Option<Envelope<'a>> {
let n = read_varint(data, pos)? as usize;
let l = read_varint(data, pos)?;
let r = read_varint(data, pos)?;
let end = pos.checked_add(n)?;
let steps = data.get(*pos..end)?;
*pos = end;
Some(Envelope {
steps,
loop_at: step_index(l)?,
release_at: step_index(r)?,
})
}
pub(super) fn envelope_at(data: &[u8], start: usize, index: u8) -> Option<Envelope<'_>> {
let mut pos = start;
let mut found = None;
for _ in 0..=index {
found = read_envelope(data, &mut pos);
found?;
}
found
}