use alpha2_audio::DelayLine;
use alpha2_eval::{SampleContext, next_knot, sample_scalar};
use alpha2_model::{Animated, MAX_CHAIN_EFFECTS, MAX_GAIN, SendTap};
use super::{MixNode, Stages, constant_value, earliest, fill_envelope, pan_gains};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Sink {
Master,
Node(usize),
HostTap,
}
pub(super) enum EdgeSignal {
Output,
Send { gain: Animated<f32>, tap: SendTap },
Key,
BeforeFader,
}
impl EdgeSignal {
pub(super) const fn reads_after_fader(&self) -> bool {
matches!(
self,
Self::Output
| Self::Send {
tap: SendTap::PostFader,
..
}
)
}
const fn send_gain(&self) -> Option<&Animated<f32>> {
match self {
Self::Output | Self::Key | Self::BeforeFader => None,
Self::Send { gain, .. } => Some(gain),
}
}
}
pub(super) struct Edge {
pub(super) to: Sink,
pub(super) signal: EdgeSignal,
pub(super) live: bool,
pub(super) waits: usize,
}
#[derive(Clone, Copy)]
pub(super) struct Input {
pub(super) edge: usize,
pub(super) from: usize,
pub(super) delayed_tap: Option<usize>,
}
pub(super) struct KeyInput {
pub(super) input: Input,
pub(super) slot: usize,
}
pub(super) struct DelayedTap {
line: DelayLine,
delayed_before_fader: [Vec<f32>; 2],
pub(super) delayed_this_block: bool,
pub(super) settling_lead: i64,
}
impl DelayedTap {
pub(super) fn new(samples: usize, channels: usize, max_block: usize) -> Self {
Self {
line: DelayLine::new(samples, channels),
delayed_before_fader: super::buffers(max_block),
delayed_this_block: false,
settling_lead: 0,
}
}
pub(super) fn samples(&self) -> usize {
self.line.samples()
}
pub(super) fn reset(&mut self) {
self.line.reset();
self.delayed_this_block = false;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum AfterFader {
AppliedByEachReader,
BufferedForUndelayedReaders,
}
pub(super) const ENVELOPE_PLANES: usize = 4;
const SEND_PLANE: usize = 3;
pub(super) struct BlockRun<'a, 'c> {
pub(super) start: i64,
pub(super) frames: usize,
pub(super) channels: usize,
pub(super) sample_rate: u32,
pub(super) envelope: &'a mut [Vec<f32>; ENVELOPE_PLANES],
pub(super) context: &'a SampleContext<'c>,
}
struct Signal<'a> {
planes: &'a [Vec<f32>; 2],
first_sample: i64,
}
fn add(output: &mut f32, value: f32) {
*output += value;
}
fn set(output: &mut f32, value: f32) {
*output = value;
}
fn constant_fader(node: &MixNode, channels: usize) -> Option<(f32, [f32; 2])> {
let gain = constant_value(&node.gain)?.clamp(0.0, MAX_GAIN);
let pan = constant_value(&node.pan)?.clamp(-1.0, 1.0);
Some((gain, pan_gains(pan, channels)))
}
fn fill_fader_planes(node: &MixNode, first: i64, run: &mut BlockRun<'_, '_>) {
let (channels, context) = (run.channels, run.context);
fill_envelope(
&mut run.envelope[..SEND_PLANE],
first,
run.frames,
run.sample_rate,
|ticks| {
earliest(
next_knot(&node.gain, ticks, context),
next_knot(&node.pan, ticks, context),
)
},
|time| {
let gain = sample_scalar(&node.gain, time, context).clamp(0.0, MAX_GAIN);
let [left, right] = pan_gains(sample_scalar(&node.pan, time, context), channels);
[gain, left, right]
},
);
}
fn fill_send_plane(gain: &Animated<f32>, first: i64, run: &mut BlockRun<'_, '_>) {
let context = run.context;
fill_envelope(
&mut run.envelope[SEND_PLANE..],
first,
run.frames,
run.sample_rate,
|ticks| next_knot(gain, ticks, context),
|time| [sample_scalar(gain, time, context).clamp(0.0, MAX_GAIN)],
);
}
fn through_fader(
node: &MixNode,
before_fader: &Signal<'_>,
target: &mut [Vec<f32>; 2],
run: &mut BlockRun<'_, '_>,
combine: impl Fn(&mut f32, f32) + Copy,
) {
let (channels, frames) = (run.channels, run.frames);
if let Some((gain, weights)) = constant_fader(node, channels) {
for (channel, weight) in weights.iter().enumerate().take(channels) {
let input = &before_fader.planes[channel][..frames];
let output = &mut target[channel][..frames];
for (output, sample) in output.iter_mut().zip(input) {
combine(output, sample * gain * weight);
}
}
return;
}
fill_fader_planes(node, before_fader.first_sample, run);
let [gains, left, right, _] = &*run.envelope;
for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
let input = &before_fader.planes[channel][..frames];
let output = &mut target[channel][..frames];
for (((output, sample), gain), weight) in
output.iter_mut().zip(input).zip(gains).zip(weights)
{
combine(output, sample * gain * weight);
}
}
}
fn through_send(
gain: &Animated<f32>,
signal: &Signal<'_>,
target: &mut [Vec<f32>; 2],
run: &mut BlockRun<'_, '_>,
) {
let (channels, frames) = (run.channels, run.frames);
if let Some(gain) = constant_value(gain) {
let gain = gain.clamp(0.0, MAX_GAIN);
for (output, input) in target.iter_mut().zip(signal.planes).take(channels) {
for (output, sample) in output[..frames].iter_mut().zip(&input[..frames]) {
*output += sample * gain;
}
}
return;
}
fill_send_plane(gain, signal.first_sample, run);
let gains = &run.envelope[SEND_PLANE][..frames];
for (output, input) in target.iter_mut().zip(signal.planes).take(channels) {
let samples = output[..frames].iter_mut().zip(&input[..frames]);
for ((output, sample), gain) in samples.zip(gains) {
*output += sample * gain;
}
}
}
fn through_fader_and_send(
node: &MixNode,
send: &Animated<f32>,
before_fader: &Signal<'_>,
target: &mut [Vec<f32>; 2],
run: &mut BlockRun<'_, '_>,
) {
let (channels, frames) = (run.channels, run.frames);
let fader = constant_fader(node, channels);
let send_gain = constant_value(send).map(|gain| gain.clamp(0.0, MAX_GAIN));
if let (Some((gain, weights)), Some(send_gain)) = (fader, send_gain) {
for (channel, weight) in weights.iter().enumerate().take(channels) {
let input = &before_fader.planes[channel][..frames];
for (output, sample) in target[channel][..frames].iter_mut().zip(input) {
*output += sample * gain * weight * send_gain;
}
}
return;
}
match fader {
Some((gain, [left, right])) => {
let [gains, lefts, rights, _] = &mut *run.envelope;
gains[..frames].fill(gain);
lefts[..frames].fill(left);
rights[..frames].fill(right);
}
None => fill_fader_planes(node, before_fader.first_sample, run),
}
match send_gain {
Some(gain) => run.envelope[SEND_PLANE][..frames].fill(gain),
None => fill_send_plane(send, before_fader.first_sample, run),
}
let [gains, left, right, sends] = &*run.envelope;
for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
let input = &before_fader.planes[channel][..frames];
let output = &mut target[channel][..frames];
for ((((output, sample), gain), weight), send) in output
.iter_mut()
.zip(input)
.zip(gains)
.zip(weights)
.zip(sends)
{
*output += sample * gain * weight * send;
}
}
}
fn add_planes(source: &[Vec<f32>; 2], target: &mut [Vec<f32>; 2], run: &BlockRun<'_, '_>) {
for channel in 0..run.channels {
let input = &source[channel][..run.frames];
for (output, sample) in target[channel][..run.frames].iter_mut().zip(input) {
*output += sample;
}
}
}
pub(super) fn carries(input: Input, nodes: &[MixNode]) -> bool {
let node = &nodes[input.from];
match input.delayed_tap {
Some(tap) => node.delayed_taps[tap].delayed_this_block,
None => node.live,
}
}
fn before_fader(input: Input, nodes: &[MixNode]) -> &[Vec<f32>; 2] {
let node = &nodes[input.from];
match input.delayed_tap {
Some(tap) => &node.delayed_taps[tap].delayed_before_fader,
None => &node.output,
}
}
pub(super) fn key_planes<'a>(
keys: &[KeyInput],
nodes: &'a [MixNode],
frames: usize,
) -> [[&'a [f32]; 2]; MAX_CHAIN_EFFECTS] {
let mut planes = [[&[][..]; 2]; MAX_CHAIN_EFFECTS];
for key in keys {
if !carries(key.input, nodes) {
continue;
}
let source = before_fader(key.input, nodes);
if let Some(planes) = planes.get_mut(key.slot) {
*planes = [&source[0][..frames], &source[1][..frames]];
}
}
planes
}
pub(super) fn add_inputs(
inputs: &[Input],
edges: &[Edge],
nodes: &[MixNode],
target: &mut [Vec<f32>; 2],
run: &mut BlockRun<'_, '_>,
) {
for &input in inputs {
if !carries(input, nodes) {
continue;
}
#[cfg(test)]
super::BUS_PLANES_SUMMED.set(super::BUS_PLANES_SUMMED.get() + run.channels);
let edge = &edges[input.edge];
let node = &nodes[input.from];
let waits = i64::try_from(edge.waits).unwrap_or(i64::MAX);
let first_sample = run.start + node.ahead_of_output - waits;
let before_fader = Signal {
planes: before_fader(input, nodes),
first_sample,
};
let buffered = (input.delayed_tap.is_none()
&& node.after_fader_use == AfterFader::BufferedForUndelayedReaders)
.then_some(Signal {
planes: &node.after_fader,
first_sample,
});
match (edge.signal.send_gain(), edge.signal.reads_after_fader()) {
(None, true) => match buffered {
Some(after_fader) => add_planes(after_fader.planes, target, run),
None => through_fader(node, &before_fader, target, run, add),
},
(None, false) => add_planes(before_fader.planes, target, run),
(Some(gain), true) => match buffered {
Some(after_fader) => through_send(gain, &after_fader, target, run),
None => through_fader_and_send(node, gain, &before_fader, target, run),
},
(Some(gain), false) => through_send(gain, &before_fader, target, run),
}
}
}
pub(super) fn feed_delayed_taps(node: &mut MixNode, run: &mut BlockRun<'_, '_>, stages: Stages) {
if node.live && node.after_fader_use == AfterFader::BufferedForUndelayedReaders {
let mut after_fader = std::mem::take(&mut node.after_fader);
let before_fader = Signal {
planes: &node.output,
first_sample: run.start + node.ahead_of_output,
};
through_fader(node, &before_fader, &mut after_fader, run, set);
node.after_fader = after_fader;
}
let mut taps = std::mem::take(&mut node.delayed_taps);
for tap in &mut taps {
if !stages.run(tap.settling_lead) {
continue;
}
let planes = node.output.iter().zip(&mut tap.delayed_before_fader);
for (channel, (output, delayed)) in planes.enumerate().take(run.channels) {
let delayed = &mut delayed[..run.frames];
if node.live {
tap.line.process(channel, &output[..run.frames], delayed);
} else {
delayed.fill(0.0);
tap.line.process_in_place(channel, delayed);
}
}
tap.line.advance(run.frames);
tap.delayed_this_block = true;
}
node.delayed_taps = taps;
}
pub(super) struct Measured {
pub(super) peak: [f32; 2],
pub(super) sum_of_squares: [f32; 2],
}
pub(super) const LEVEL_LANES: usize = 16;
struct LevelLanes {
peaks: [f32; LEVEL_LANES],
sums: [f32; LEVEL_LANES],
}
impl LevelLanes {
const EMPTY: Self = Self {
peaks: [0.0; LEVEL_LANES],
sums: [0.0; LEVEL_LANES],
};
#[inline]
fn take(&mut self, lane: usize, sample: f32) {
let magnitude = sample.abs();
if magnitude > self.peaks[lane] {
self.peaks[lane] = magnitude;
}
self.sums[lane] += sample * sample;
}
#[inline]
fn take_chunk(&mut self, chunk: [f32; LEVEL_LANES]) {
for (peak, sample) in self.peaks.iter_mut().zip(chunk) {
let magnitude = sample.abs();
*peak = if magnitude > *peak { magnitude } else { *peak };
}
for (sum, sample) in self.sums.iter_mut().zip(chunk) {
*sum += sample * sample;
}
}
fn peak_and_sum(mut self) -> (f32, f32) {
let mut width = LEVEL_LANES;
while width > 1 {
width /= 2;
for lane in 0..width {
self.sums[lane] = self.sums[2 * lane] + self.sums[2 * lane + 1];
}
}
(self.peaks.into_iter().fold(0.0, f32::max), self.sums[0])
}
}
pub(super) fn peak_and_sum_of_squares(samples: &[f32]) -> (f32, f32) {
peak_and_sum_of_squares_at(samples, 1.0, 1.0)
}
fn peak_and_sum_of_squares_at(samples: &[f32], gain: f32, weight: f32) -> (f32, f32) {
let mut lanes = LevelLanes::EMPTY;
let (chunks, rest) = samples.as_chunks::<LEVEL_LANES>();
for chunk in chunks {
lanes.take_chunk(chunk.map(|sample| sample * gain * weight));
}
for (lane, sample) in rest.iter().enumerate() {
lanes.take(lane, sample * gain * weight);
}
lanes.peak_and_sum()
}
fn peak_and_sum_of_squares_through(samples: &[f32], gains: &[f32], weights: &[f32]) -> (f32, f32) {
let mut lanes = LevelLanes::EMPTY;
let faded = samples.iter().zip(gains).zip(weights);
for (index, ((sample, gain), weight)) in faded.enumerate() {
lanes.take(index % LEVEL_LANES, sample * gain * weight);
}
lanes.peak_and_sum()
}
pub(super) fn measure_after_fader(node: &MixNode, run: &mut BlockRun<'_, '_>) -> Measured {
let (channels, frames) = (run.channels, run.frames);
let mut measured = Measured {
peak: [0.0; 2],
sum_of_squares: [0.0; 2],
};
if !node.live {
return measured;
}
let constant = constant_fader(node, channels);
if constant.is_none() {
fill_fader_planes(node, run.start + node.ahead_of_output, run);
}
let [gains, left, right, _] = &*run.envelope;
for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
let samples = &node.output[channel][..frames];
(measured.peak[channel], measured.sum_of_squares[channel]) = match constant {
Some((gain, weight)) => peak_and_sum_of_squares_at(samples, gain, weight[channel]),
None => peak_and_sum_of_squares_through(samples, &gains[..frames], &weights[..frames]),
};
}
measured
}