Files
prometeu-runtime/crates/console/prometeu-drivers/src/audio/engine.rs
T
bquarkz f480b755ed
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
fix(runtime): restore tooling coverage and allow atomic release ordering
2026-11-21 15:38:33 +00:00

925 lines
34 KiB
Rust

//! Host-independent bounded PCM engine. Construct resources off the render lane.
use super::{
AudioCommand, AudioDelivery, AudioTransport, Channel, LoopMode, MAX_CHANNELS,
MAX_COMMANDS_PER_FRAME, SFX_CHANNELS, SFX_START,
};
use prometeu_hal::{
audio_bridge::AudioControl,
music_bank::{Instrument, MAX_MUSIC_TRACKS, MusicBank, MusicEvent},
sample::Sample,
};
use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
pub const RETIRED_CAPACITY: usize = 2 * (3 * MAX_COMMANDS_PER_FRAME + MAX_CHANNELS + 2);
/// Owning resources leave the real-time lane in a preallocated packet.
#[allow(dead_code)]
enum Retired {
Sample(Arc<Sample>),
Bank(Arc<MusicBank>),
Token(Arc<AtomicBool>),
}
pub struct Packet {
retired: Vec<Retired>,
pub batches: [Option<Vec<AudioCommand>>; 2],
}
impl Default for Packet {
fn default() -> Self {
Self::new()
}
}
impl Packet {
pub fn new() -> Self {
Self { retired: Vec::with_capacity(RETIRED_CAPACITY), batches: [None, None] }
}
fn push(&mut self, owner: Retired) {
assert!(self.retired.len() < RETIRED_CAPACITY, "audio retirement bound");
self.retired.push(owner);
}
fn voice(&mut self, voice: &mut Channel) {
if let Some(s) = voice.sample.take() {
self.push(Retired::Sample(s));
}
if let Some(t) = voice.alive.take() {
self.push(Retired::Token(t));
}
voice.active = false;
}
pub fn recycle(&mut self, transport: &AudioTransport) {
self.retired.clear();
for batch in &mut self.batches {
if let Some(batch) = batch.take() {
transport.recycle_commands(batch);
}
}
}
/// Service thread only: count distinct retired PCM payloads, excluding Arc overhead.
pub fn retained_pcm_bytes(&self) -> usize {
let mut seen = std::collections::HashSet::new();
let mut bytes = 0;
let mut add = |sample: &Arc<Sample>| {
if seen.insert(Arc::as_ptr(sample)) {
bytes += sample.data.capacity() * 2;
}
};
for owner in &self.retired {
match owner {
Retired::Sample(sample) => add(sample),
Retired::Bank(bank) => {
for sample in bank.samples.iter() {
add(sample);
}
}
Retired::Token(_) => {}
}
}
for batch in self.batches.iter().flatten() {
for command in batch {
match command {
AudioCommand::Play { sample, .. } => add(sample),
AudioCommand::MusicPlay { bank, .. } => {
for sample in bank.samples.iter() {
add(sample);
}
}
_ => {}
}
}
}
bytes
}
pub fn is_empty(&self) -> bool {
self.retired.is_empty() && self.batches.iter().all(Option::is_none)
}
pub fn capacity(&self) -> usize {
self.retired.capacity()
}
}
#[derive(Clone, Copy)]
struct Ramp {
from: f64,
to: f64,
start: u64,
duration: u32,
smooth: bool,
}
impl Ramp {
fn constant(value: f64) -> Self {
Self { from: value, to: value, start: 0, duration: 0, smooth: false }
}
fn at(self, now: u64) -> f64 {
if self.duration == 0 {
return self.to;
}
let elapsed = now.saturating_sub(self.start);
if elapsed >= self.duration as u64 {
return self.to;
}
let x = elapsed as f64 / self.duration as f64;
let x = if self.smooth { x * x * (3.0 - 2.0 * x) } else { x };
self.from + (self.to - self.from) * x
}
fn set(&mut self, value: f64, now: u64, duration: u32, smooth: bool) {
*self = Self { from: self.at(now), to: value, start: now, duration, smooth };
}
fn done(self, now: u64) -> bool {
now.saturating_sub(self.start) >= self.duration as u64
}
}
#[derive(Clone, Copy)]
struct SendRamp {
base: Ramp,
scale: Ramp,
}
impl Default for SendRamp {
fn default() -> Self {
Self { base: Ramp::constant(0.0), scale: Ramp::constant(1.0) }
}
}
impl SendRamp {
fn at(self, now: u64, instrument_default: f64) -> f64 {
self.base.at(now) + self.scale.at(now) * instrument_default
}
fn set(&mut self, to: f64, now: u64, frames: u32, smooth: bool) {
self.base.set(to, now, frames, smooth);
self.scale.set(0.0, now, frames, smooth);
}
}
#[derive(Clone, Copy)]
struct Track {
gain: Ramp,
pan: Ramp,
pitch: Ramp,
send: SendRamp,
vibrato: Option<(u32, f64)>,
tremolo: Option<(u32, f64)>,
}
impl Default for Track {
fn default() -> Self {
Self {
gain: Ramp::constant(1.0),
pan: Ramp::constant(128.0),
pitch: Ramp::constant(0.0),
send: SendRamp::default(),
vibrato: None,
tremolo: None,
}
}
}
struct MusicGroup {
bank: Option<Arc<MusicBank>>,
active: bool,
paused: bool,
looping: bool,
time: u128,
cursor: usize,
frame: u64,
iteration: u64,
tracks: [Track; MAX_MUSIC_TRACKS],
gain: Ramp,
stop_after_fade: bool,
}
impl Default for MusicGroup {
fn default() -> Self {
Self {
bank: None,
active: false,
paused: false,
looping: false,
time: 0,
cursor: 0,
frame: 0,
iteration: 0,
tracks: [Track::default(); MAX_MUSIC_TRACKS],
gain: Ramp::constant(1.0),
stop_after_fade: false,
}
}
}
#[derive(Clone, Copy)]
struct VoiceState {
inst: Instrument,
track: usize,
note_id: u32,
iteration: u64,
born: u64,
age: u64,
release_age: Option<u64>,
release_level: f64,
release_order: Option<u64>,
level: f64,
cached_cents: f64,
pitch_factor: f64,
glide: Ramp,
send: f64,
zone: usize,
}
impl Default for VoiceState {
fn default() -> Self {
Self {
inst: Instrument::default(),
track: 0,
note_id: 0,
iteration: 0,
born: 0,
age: 0,
release_age: None,
release_level: 0.0,
release_order: None,
level: 1.0,
cached_cents: f64::INFINITY,
pitch_factor: 1.0,
glide: Ramp::constant(0.0),
send: 0.0,
zone: 0,
}
}
}
struct Effect {
delay: Vec<[f32; 2]>,
write: usize,
history: usize,
frames: usize,
feedback: f32,
wet: f32,
dry: f32,
coefficient: f32,
filter: [f32; 2],
}
impl Effect {
fn new() -> Self {
Self {
delay: vec![[0.0; 2]; 96_000],
write: 0,
history: 0,
frames: 0,
feedback: 0.0,
wet: 0.0,
dry: 1.0,
coefficient: 1.0,
filter: [0.0; 2],
}
}
fn reset(&mut self) {
self.write = 0;
self.history = 0;
self.filter = [0.0; 2];
}
fn process(&mut self, input: [f32; 2], send: [f32; 2]) -> [f32; 2] {
if self.frames == 0 && self.coefficient == 1.0 {
self.filter = input;
return [input[0] * self.dry, input[1] * self.dry];
}
let mut out = [0.0; 2];
for c in 0..2 {
self.filter[c] += self.coefficient * (input[c] - self.filter[c]);
// Flush subnormals without denormal-sensitive host settings.
if self.filter[c].abs() < 1e-20 {
self.filter[c] = 0.0;
}
let echo = if self.frames != 0 && self.history >= self.frames {
self.delay[(self.write + 96_000 - self.frames) % 96_000][c]
} else {
0.0
};
out[c] = self.filter[c] * self.dry + echo * self.wet;
self.delay[self.write][c] = send[c] + echo * self.feedback;
if self.delay[self.write][c].abs() < 1e-20 {
self.delay[self.write][c] = 0.0;
}
}
self.write = (self.write + 1) % 96_000;
self.history = (self.history + 1).min(96_000);
out
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct AudioDiagnostics {
pub frames: u64,
pub active_voices: usize,
pub maximum_voices: usize,
pub last_render_us: u64,
pub maximum_render_us: u64,
}
pub struct AudioMixer {
pub voices: [Channel; MAX_CHANNELS],
states: [VoiceState; MAX_CHANNELS],
groups: [MusicGroup; 2],
effects: [Effect; 3],
bus: [f32; 3],
sfx_gain: f32,
exponential: [f64; 1025],
sine: [f64; 4097],
pub last_processing_time: Duration,
paused: bool,
epoch: u64,
pub diagnostics: AudioDiagnostics,
note_serial: u64,
}
impl Default for AudioMixer {
fn default() -> Self {
Self::new()
}
}
impl AudioMixer {
pub fn new() -> Self {
Self {
voices: std::array::from_fn(|_| Channel::default()),
states: [VoiceState::default(); MAX_CHANNELS],
groups: std::array::from_fn(|_| MusicGroup::default()),
effects: std::array::from_fn(|_| Effect::new()),
bus: [1.0; 3],
sfx_gain: 1.0,
exponential: std::array::from_fn(|i| {
((-6.0 * i as f64 / 1024.0).exp() - (-6.0f64).exp()) / (1.0 - (-6.0f64).exp())
}),
sine: std::array::from_fn(|i| (std::f64::consts::TAU * i as f64 / 4096.0).sin()),
last_processing_time: Duration::ZERO,
paused: false,
epoch: 0,
diagnostics: AudioDiagnostics::default(),
note_serial: 0,
}
}
pub fn prepared_bytes(&self) -> usize {
std::mem::size_of::<Self>()
+ self
.effects
.iter()
.map(|e| e.delay.capacity() * std::mem::size_of::<[f32; 2]>())
.sum::<usize>()
}
fn stop_group(&mut self, group: usize, packet: &mut Packet) {
for v in &mut self.voices[group * 12..group * 12 + 12] {
packet.voice(v);
}
if let Some(bank) = self.groups[group].bank.take() {
packet.push(Retired::Bank(bank));
}
let gain = self.groups[group].gain.at(self.groups[group].frame);
self.groups[group] = MusicGroup::default();
self.groups[group].gain = Ramp::constant(gain);
self.effects[group].reset();
}
pub fn retire_inactive(&mut self, packet: &mut Packet) {
for g in 0..2 {
if self.groups[g].bank.as_ref().is_some_and(|b| !b.alive.load(Ordering::Acquire))
|| (self.groups[g].stop_after_fade && !self.groups[g].active)
{
self.stop_group(g, packet);
}
}
for v in &mut self.voices {
if !v.active || v.alive.as_ref().is_some_and(|a| !a.load(Ordering::Acquire)) {
packet.voice(v);
}
}
}
pub fn apply_delivery_into(&mut self, delivery: AudioDelivery, packet: &mut Packet) {
if delivery.epoch < self.epoch {
packet.batches = [delivery.frame, delivery.lifecycle];
return;
}
if delivery.epoch != self.epoch {
for group in 0..2 {
self.stop_group(group, packet);
}
for voice in &mut self.voices {
packet.voice(voice);
*voice = Channel::default();
}
for group in &mut self.groups {
group.gain = Ramp::constant(1.0);
}
for effect in &mut self.effects {
effect.reset();
effect.frames = 0;
effect.feedback = 0.0;
effect.wet = 0.0;
effect.dry = 1.0;
effect.coefficient = 1.0;
}
self.bus = [1.0; 3];
self.sfx_gain = 1.0;
self.epoch = delivery.epoch;
}
packet.batches = [delivery.frame, delivery.lifecycle];
for index in 0..2 {
if let Some(mut batch) = packet.batches[index].take() {
for command in &mut batch {
let command =
std::mem::replace(command, AudioCommand::Stop { voice_id: SFX_CHANNELS });
self.process_command(command, packet);
}
packet.batches[index] = Some(batch);
}
}
self.paused = delivery.paused;
}
/// Convenience for non-real-time signal tests/offline owners.
pub fn apply_delivery(&mut self, delivery: AudioDelivery) {
self.apply_delivery_into(delivery, &mut Packet::new());
}
pub fn fill_buffer(&mut self, buffer: &mut [f32]) {
self.mix(buffer);
self.retire_inactive(&mut Packet::new());
}
fn process_command(&mut self, command: AudioCommand, packet: &mut Packet) {
match command {
AudioCommand::Play {
sample,
alive,
voice_id,
volume,
pan,
pitch,
priority,
loop_mode,
} => {
if voice_id >= SFX_CHANNELS
|| alive.as_ref().is_some_and(|a| !a.load(Ordering::Acquire))
{
packet.push(Retired::Sample(sample));
if let Some(t) = alive {
packet.push(Retired::Token(t));
}
return;
}
let index = SFX_START + voice_id;
packet.voice(&mut self.voices[index]);
self.voices[index] = Channel {
sample: Some(sample),
alive,
active: true,
pos: 0.0,
pitch,
volume,
pan,
loop_mode,
priority,
};
self.states[index] = VoiceState::default();
}
AudioCommand::Stop { voice_id } => {
if voice_id < SFX_CHANNELS {
packet.voice(&mut self.voices[SFX_START + voice_id]);
}
}
AudioCommand::SetVolume { voice_id, volume } => {
if voice_id < SFX_CHANNELS {
self.voices[SFX_START + voice_id].volume = volume;
}
}
AudioCommand::SetPan { voice_id, pan } => {
if voice_id < SFX_CHANNELS {
self.voices[SFX_START + voice_id].pan = pan;
}
}
AudioCommand::SetPitch { voice_id, pitch } => {
if voice_id < SFX_CHANNELS {
self.voices[SFX_START + voice_id].pitch = pitch;
}
}
AudioCommand::MusicPlay { group, bank, looping } => {
if group >= 2 || !bank.alive.load(Ordering::Acquire) {
packet.push(Retired::Bank(bank));
return;
}
self.stop_group(group, packet);
self.groups[group].bank = Some(bank);
self.groups[group].active = true;
self.groups[group].looping = looping;
}
AudioCommand::Control(control) => match control {
AudioControl::GroupVolume { group, gain } => {
if group == 2 {
self.sfx_gain = gain as f32 / 255.0;
} else {
self.groups[group].gain = Ramp::constant(gain as f64 / 255.0);
self.groups[group].stop_after_fade = false;
}
}
AudioControl::MusicStop { group } => self.stop_group(group, packet),
AudioControl::MusicPause { group, paused } => self.groups[group].paused = paused,
AudioControl::MusicVolume { group, gain } => {
self.groups[group].gain = Ramp::constant(gain as f64 / 255.0);
self.groups[group].stop_after_fade = false;
}
AudioControl::MusicFade { group, gain, frames, smooth } => {
let g = &mut self.groups[group];
g.gain.set(gain as f64 / 255.0, g.frame, frames, smooth);
g.stop_after_fade = false;
}
AudioControl::Crossfade { source, target, frames, smooth } => {
if !self.groups[source].active || !self.groups[target].active {
return;
}
for (g, value) in [(source, 0.0), (target, 1.0)] {
let group = &mut self.groups[g];
group.gain.set(value, group.frame, frames, smooth);
group.stop_after_fade = g == source;
}
}
AudioControl::BusVolume { bus, gain } => self.bus[bus] = gain as f32 / 255.0,
AudioControl::SfxSend { voice, gain } => {
self.states[SFX_START + voice].send = gain as f64 / 255.0
}
AudioControl::Effect { group, cutoff_hz, delay_frames, feedback, wet, dry } => {
let effect = &mut self.effects[group];
effect.coefficient = if cutoff_hz == 0 {
1.0
} else {
(1.0 - (-std::f32::consts::TAU * cutoff_hz as f32 / 48_000.0).exp())
.clamp(0.0, 1.0)
};
if effect.frames != delay_frames as usize {
effect.reset();
}
effect.frames = delay_frames as usize;
effect.feedback = feedback;
effect.wet = wet;
effect.dry = dry;
}
},
}
}
fn begin_note_release(&mut self, index: usize) {
let state = &mut self.states[index];
if state.release_age.is_none() {
let level = envelope(state, &self.exponential);
state.release_age = Some(state.age);
state.release_order = Some(self.note_serial);
self.note_serial = self.note_serial.wrapping_add(1);
state.release_level = level;
}
}
fn event(&mut self, group: usize, event: MusicEvent, zone: usize) {
let frame = self.groups[group].frame;
let track = event.track as usize;
if event.kind == 1 {
let bank = self.groups[group].bank.as_ref().unwrap();
let inst = bank.instruments[zone];
let cents = (event.c - inst.root as i32) as f64 * 100.0 + inst.tuning_cents as f64;
let range = group * 12..group * 12 + 12;
self.note_serial = self.note_serial.wrapping_add(1);
let legato = if event.flags & 1 != 0 {
range
.clone()
.filter(|&i| {
self.voices[i].active
&& self.states[i].track == track
&& self.states[i].release_age.is_none()
})
.max_by_key(|&i| (self.states[i].born, i))
} else {
None
};
if let Some(index) = legato.filter(|&i| self.states[i].zone == zone) {
let state = &mut self.states[index];
state.glide.set(cents, frame, event.duration_frames, event.curve == 1);
state.note_id = event.a;
state.born = self.note_serial;
state.iteration = self.groups[group].iteration;
self.voices[index].volume = ((inst.gain as u16 * event.d as u16 + 127) / 255) as u8;
return;
}
let index = legato.unwrap_or_else(|| {
range.clone().find(|&i| !self.voices[i].active).unwrap_or_else(|| {
range
.min_by_key(|&i| {
(
self.states[i].release_age.is_none(),
self.states[i].release_order.unwrap_or(self.states[i].born),
i,
)
})
.unwrap()
})
});
// Music samples always have an owner in this group's retained bank.
self.voices[index] = Channel {
sample: Some(bank.samples[inst.sample as usize].clone()),
alive: None,
active: true,
pos: 0.0,
pitch: 1.0,
volume: ((inst.gain as u16 * event.d as u16 + 127) / 255) as u8,
pan: inst.pan,
loop_mode: if inst.looping { LoopMode::On } else { LoopMode::Off },
priority: 0,
};
self.states[index] = VoiceState {
inst,
track,
note_id: event.a,
iteration: self.groups[group].iteration,
born: self.note_serial,
glide: Ramp::constant(cents),
send: inst.send as f64 / 65535.0,
zone,
..VoiceState::default()
};
} else if event.kind == 2 {
for index in group * 12..group * 12 + 12 {
let state = &self.states[index];
if self.voices[index].active
&& state.track == track
&& state.note_id == event.a
&& state.iteration == self.groups[group].iteration
{
self.begin_note_release(index);
}
}
} else {
let t = &mut self.groups[group].tracks[track];
let smooth = event.curve == 1;
match event.kind {
4 => t.gain.set(event.c as f64 / 65535.0, frame, event.duration_frames, smooth),
5 => t.pan.set(event.c as f64, frame, event.duration_frames, smooth),
6 => t.pitch.set(event.c as f64, frame, event.duration_frames, smooth),
7 => t.vibrato = Some((event.a, event.c as f64)),
8 => t.tremolo = Some((event.a, event.c as f64 / 65535.0)),
9 => t.send.set(event.c as f64 / 65535.0, frame, event.duration_frames, smooth),
_ => {} // Tempo/instrument selection were resolved during compilation.
}
}
}
fn sequence(&mut self, group: usize) {
if !self.groups[group].active || self.groups[group].paused {
return;
}
loop {
let g = &self.groups[group];
let bank = g.bank.as_ref().unwrap();
if let Some(event) = bank.events.get(g.cursor).filter(|e| e.time <= g.time) {
let event = *event;
self.groups[group].cursor += 1;
self.event(group, event.event, event.zone);
continue;
}
if g.time < bank.end_time {
break;
}
let loop_start = bank.loop_time.unwrap_or(0);
let loop_event = if bank.loop_time.is_some() { bank.loop_event } else { 0 };
let loop_length = bank.end_time - loop_start;
for index in group * 12..group * 12 + 12 {
self.begin_note_release(index);
}
let g = &mut self.groups[group];
if !g.looping {
g.active = false;
break;
}
g.time -= loop_length;
g.cursor = loop_event;
g.iteration = g.iteration.wrapping_add(1);
}
}
pub fn mix(&mut self, buffer: &mut [f32]) {
let start = Instant::now();
buffer.fill(0.0);
if self.paused {
self.last_processing_time = start.elapsed();
return;
}
for frame in buffer.as_chunks_mut::<2>().0 {
// Invalidated resources stay owned until a reclamation packet is available.
for g in 0..2 {
if self.groups[g].bank.as_ref().is_some_and(|b| !b.alive.load(Ordering::Acquire)) {
self.groups[g].active = false;
for v in &mut self.voices[g * 12..g * 12 + 12] {
v.active = false;
}
self.effects[g].reset();
}
self.sequence(g);
}
let mut dry = [[0.0f32; 2]; 3];
let mut send = [[0.0f32; 2]; 3];
let mut active = 0;
for index in 0..MAX_CHANNELS {
let group = if index < 12 {
0
} else if index < 24 {
1
} else {
2
};
if group < 2 && self.groups[group].paused {
continue;
}
let voice = &mut self.voices[index];
if !voice.active {
continue;
}
if voice.alive.as_ref().is_some_and(|a| !a.load(Ordering::Acquire)) {
voice.active = false;
continue;
}
let Some(sample) = &voice.sample else {
continue;
};
let len = sample.frames_len();
if len == 0 {
voice.active = false;
continue;
}
active += 1;
let state = &mut self.states[index];
let mut volume = voice.volume as f64 / 255.0;
let mut pan = voice.pan as f64;
let mut pitch = voice.pitch;
let mut amount = state.send;
if group < 2 {
let g = &self.groups[group];
let track = g.tracks[state.track];
state.level = envelope(state, &self.exponential);
if state.release_age.is_some() && state.level <= 0.0 {
voice.active = false;
continue;
}
let vib = track
.vibrato
.unwrap_or((state.inst.vibrato_millihz, state.inst.vibrato_cents as f64));
let trem = track.tremolo.unwrap_or((
state.inst.tremolo_millihz,
state.inst.tremolo_depth as f64 / 65535.0,
));
let cents = state.glide.at(g.frame)
+ track.pitch.at(g.frame)
+ lfo(&self.sine, state.age, vib.0) * vib.1;
if cents != state.cached_cents {
state.pitch_factor = (cents / 1200.0).exp2();
state.cached_cents = cents;
}
pitch *= state.pitch_factor;
volume *= state.level
* track.gain.at(g.frame)
* (1.0 - trem.1 * (lfo(&self.sine, state.age, trem.0) + 1.0) * 0.5);
pan = (pan + track.pan.at(g.frame) - 128.0).clamp(0.0, 255.0);
amount = track.send.at(g.frame, state.send);
state.age = state.age.wrapping_add(1);
}
let channels = sample.channels as usize;
let (loop_start, end) = match (voice.loop_mode, sample.loop_start, sample.loop_end)
{
(LoopMode::On, Some(a), Some(b)) if a < b && b as usize <= len => {
(a as f64, b as f64)
}
_ => (0.0, len as f64),
};
let pos = voice.pos as usize;
if pos >= len {
voice.active = false;
continue;
}
let next = if voice.loop_mode == LoopMode::On && (pos + 1) as f64 >= end {
loop_start as usize
} else {
pos + 1
};
let frac = (voice.pos - pos as f64) as f32;
let value = |c: usize| {
let a = sample.data[pos * channels + c] as f32 / 32768.0;
let b =
sample.data.get(next * channels + c).copied().unwrap_or(0) as f32 / 32768.0;
a + (b - a) * frac
};
if volume != 0.0 {
let normalized_pan =
if pan <= 128.0 { pan / 256.0 } else { 0.5 + (pan - 128.0) / 254.0 };
let gains = if channels == 1 {
[(1.0 - normalized_pan).sqrt(), normalized_pan.sqrt()]
} else {
[
if pan <= 128.0 { 1.0 } else { (255.0 - pan) / 127.0 },
if pan >= 128.0 { 1.0 } else { pan / 128.0 },
]
};
for c in 0..2 {
let v =
value(if channels == 1 { 0 } else { c }) * (volume * gains[c]) as f32;
dry[group][c] += v;
send[group][c] += v * amount as f32;
}
}
let ratio = sample.sample_rate as f64 / 48_000.0;
if ratio > 0.0 {
if pitch >= (end - voice.pos) / ratio {
if voice.loop_mode == LoopMode::Off {
voice.active = false;
} else {
let length = end - loop_start;
let step = (pitch % (length / ratio)) * ratio;
voice.pos =
loop_start + (voice.pos - loop_start + step).rem_euclid(length);
if voice.pos >= end {
voice.pos = loop_start;
}
}
} else {
voice.pos += pitch * ratio;
}
}
}
self.diagnostics.active_voices = active;
self.diagnostics.maximum_voices = self.diagnostics.maximum_voices.max(active);
for group in 0..3 {
if group < 2 && self.groups[group].paused {
continue;
}
let gain = if group < 2 {
self.groups[group].gain.at(self.groups[group].frame) as f32 * self.bus[0]
} else {
self.bus[1] * self.sfx_gain
};
let values = self.effects[group].process(dry[group], send[group]);
for c in 0..2 {
frame[c] += values[c] * gain;
}
}
for value in frame {
*value = (*value * self.bus[2]).clamp(-1.0, 1.0);
}
for group in &mut self.groups {
if !group.paused
&& let Some(bank) = &group.bank
{
group.frame = group.frame.wrapping_add(1);
if group.active {
group.time += bank.denominator;
}
if group.stop_after_fade && group.gain.done(group.frame) {
group.active = false;
}
}
}
// Crossfade completion silences/relinquishes notes; bank reclamation is deferred.
for g in 0..2 {
if self.groups[g].stop_after_fade && !self.groups[g].active {
for voice in &mut self.voices[g * 12..g * 12 + 12] {
voice.active = false;
}
self.effects[g].reset();
}
}
self.diagnostics.frames += 1;
}
self.last_processing_time = start.elapsed();
self.diagnostics.last_render_us = self.last_processing_time.as_micros() as u64;
self.diagnostics.maximum_render_us =
self.diagnostics.maximum_render_us.max(self.diagnostics.last_render_us);
}
}
fn lfo(table: &[f64; 4097], age: u64, millihz: u32) -> f64 {
let phase = ((age % 48_000_000) * millihz as u64 % 48_000_000) as f64 / 48_000_000.0 * 4096.0;
let index = phase as usize;
table[index] + (table[index + 1] - table[index]) * (phase - index as f64)
}
fn micros_frames(value: u32) -> u64 {
(value as u64 * 48_000).div_ceil(1_000_000)
}
fn envelope(state: &VoiceState, table: &[f64; 1025]) -> f64 {
let curve = |x: f64| {
if state.inst.curve == 0 {
1.0 - x
} else {
let p = x.clamp(0.0, 1.0) * 1024.0;
let i = (p as usize).min(1023);
table[i] + (table[i + 1] - table[i]) * (p - i as f64)
}
};
if let Some(start) = state.release_age {
let duration = micros_frames(state.inst.release_us);
let elapsed = state.age - start;
return if duration == 0 || elapsed >= duration {
0.0
} else {
state.release_level * curve(elapsed as f64 / duration as f64)
};
}
let attack = micros_frames(state.inst.attack_us);
let decay = micros_frames(state.inst.decay_us);
if state.age < attack {
return state.age as f64 / attack as f64;
}
let sustain = state.inst.sustain as f64 / 65535.0;
if state.age - attack < decay {
sustain + (1.0 - sustain) * curve((state.age - attack) as f64 / decay as f64)
} else {
sustain
}
}
#[cfg(test)]
#[path = "engine_tests.rs"]
mod tests;