use std::sync::Arc;
use super::gain::Gain;
use super::ClipId;
pub(super) struct ClipVoice {
pub(super) id: ClipId,
pub(super) data: Arc<[[f32; 2]]>,
pos: f64,
step: f64,
left: f32,
right: f32,
pub(super) gain: Gain,
pub(super) bus: u8,
looping: bool,
pub(super) order: u64,
}
pub(super) fn balance(pan: f32) -> (f32, f32) {
let p = if pan.is_finite() {
pan.clamp(-1.0, 1.0)
} else {
0.0
};
((1.0 - p).min(1.0), (1.0 + p).min(1.0))
}
impl ClipVoice {
#[allow(clippy::too_many_arguments)]
pub(super) fn new(
id: ClipId,
data: Arc<[[f32; 2]]>,
step: f64,
pan: f32,
volume: f32,
bus: u8,
looping: bool,
order: u64,
) -> ClipVoice {
let (left, right) = balance(pan);
ClipVoice {
id,
data,
pos: 0.0,
step,
left,
right,
gain: Gain::at(volume),
bus,
looping,
order,
}
}
pub(super) fn mix(&mut self, out: &mut [[f32; 2]]) -> bool {
let len = self.data.len();
if len == 0 {
return true;
}
let lenf = len as f64;
for o in out.iter_mut() {
if self.pos >= lenf {
if self.looping {
self.pos %= lenf;
} else {
return true;
}
}
let i = self.pos as usize;
let frac = (self.pos - i as f64) as f32;
let a = self.data[i];
let s = if frac == 0.0 {
a
} else {
let b = if i + 1 < len {
self.data[i + 1]
} else if self.looping {
self.data[0]
} else {
[0.0, 0.0]
};
[a[0] + (b[0] - a[0]) * frac, a[1] + (b[1] - a[1]) * frac]
};
let g = self.gain.next();
o[0] += s[0] * self.left * g;
o[1] += s[1] * self.right * g;
self.pos += self.step;
if self.gain.is_done() {
return true;
}
}
!self.looping && self.pos >= lenf
}
}