alpha2-engine 0.10.0

Player and exporter facade for alpha2.
Documentation
//! Effect parameters that change over time: which chain nodes they retune, and their values at
//! the control points a block touches.

use alpha2_audio::{CONTROL_INTERVAL, ControlLane, Controls, Processor, ProcessorChain};
use alpha2_eval::{SampleContext, sample_scalar};
use alpha2_model::{Animated, Domain, Extrapolation, Interpolation};
use alpha2_time::MediaTime;

use super::{constant_value, ticks_at};

pub(super) struct Param {
    value: Animated<f32>,
    domain: Domain,
}

impl Param {
    pub(super) fn new(value: &Animated<f32>, domain: Domain) -> Self {
        Self {
            value: value.clone(),
            domain,
        }
    }

    fn reach(&self) -> [f32; 2] {
        if let Some(value) = constant_value(&self.value) {
            return [value, value];
        }
        let whole = [self.domain.min.max(f32::MIN), self.domain.max.min(f32::MAX)];
        let Animated::Keyframes {
            keyframes,
            before,
            after,
        } = &self.value
        else {
            return whole;
        };
        let stays_between_keys = |end: &Extrapolation| {
            matches!(
                end,
                Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong
            )
        };
        if !(stays_between_keys(before) && stays_between_keys(after)) {
            return whole;
        }
        let mut reach = [f64::INFINITY, f64::NEG_INFINITY];
        let mut widen = |value: f64| reach = [reach[0].min(value), reach[1].max(value)];
        for (index, keyframe) in keyframes.iter().enumerate() {
            widen(f64::from(keyframe.value));
            let Some(next) = keyframes.get(index + 1) else {
                break;
            };
            match &keyframe.interpolation {
                Interpolation::Hold | Interpolation::Linear | Interpolation::Steps(_) => {}
                Interpolation::ValueBezier(curve) => {
                    for end in curve.range(keyframe.value, next.value) {
                        widen(end);
                    }
                }
                Interpolation::CubicBezier(_) | Interpolation::Points { .. } => return whole,
            }
        }
        #[expect(
            clippy::cast_possible_truncation,
            reason = "the ends are clamped to the domain's f32 ends"
        )]
        let reach = reach.map(|end| self.domain.clamp(end as f32));
        reach
    }

    fn at(&self, sample: i64, sample_rate: u32, context: &SampleContext<'_>) -> f32 {
        let time = MediaTime::from_ticks(ticks_at(sample, sample_rate));
        self.domain.clamp(sample_scalar(&self.value, time, context))
    }
}

pub(super) struct Retuned {
    pub(super) processor: usize,
    pub(super) params: Vec<Param>,
}

pub(super) fn varies(params: &[Param]) -> bool {
    params
        .iter()
        .any(|param| constant_value(&param.value).is_none())
}

pub(super) fn slowest_to_settle<P: Processor>(
    params: &[Param],
    sample_rate: u32,
    make: impl Fn(&[f32]) -> P,
) -> P {
    let reaches: Vec<[f32; 2]> = params.iter().map(Param::reach).collect();
    let moving: Vec<usize> = (0..params.len())
        .filter(|&param| reaches[param][0].to_bits() != reaches[param][1].to_bits())
        .collect();
    let mut values: Vec<f32> = reaches.iter().map(|reach| reach[0]).collect();
    let mut slowest: Option<(u32, Vec<f32>)> = None;
    for corner in 0..1_usize << moving.len() {
        for (bit, &param) in moving.iter().enumerate() {
            values[param] = reaches[param][(corner >> bit) & 1];
        }
        let mut processor = make(&values);
        processor.prepare(sample_rate, 1);
        let history = processor.history_samples();
        if slowest.as_ref().is_none_or(|(most, _)| history > *most) {
            slowest = Some((history, values.clone()));
        }
    }
    make(&slowest.map_or(values, |(_, values)| values))
}

struct RetunedNode {
    params: Vec<Param>,
    latency_before: i64,
}

pub(super) struct ChainControl {
    nodes: Vec<RetunedNode>,
    lanes: Vec<ControlLane>,
    values: Vec<f32>,
    points_per_lane: usize,
}

impl ChainControl {
    pub(super) fn new(retuned: Vec<Retuned>, chain: &ProcessorChain, max_block: usize) -> Self {
        let interval = usize::try_from(CONTROL_INTERVAL).unwrap_or(usize::MAX);
        let points_per_lane = max_block / interval + 3;
        let mut offset = 0;
        let mut lanes = Vec::with_capacity(retuned.len());
        let mut nodes = Vec::with_capacity(retuned.len());
        for Retuned { processor, params } in retuned {
            lanes.push(ControlLane {
                node: processor,
                first_point: 0,
                points: 0,
                offset,
            });
            offset += points_per_lane * params.len();
            let latency_before = chain.latency_samples() - chain.latency_from(processor);
            nodes.push(RetunedNode {
                params,
                latency_before: i64::from(latency_before),
            });
        }
        Self {
            nodes,
            lanes,
            values: vec![0.0; offset],
            points_per_lane,
        }
    }

    pub(super) fn none() -> Self {
        Self {
            nodes: Vec::new(),
            lanes: Vec::new(),
            values: Vec::new(),
            points_per_lane: 0,
        }
    }

    pub(super) fn fill(
        &mut self,
        input: i64,
        frames: usize,
        sample_rate: u32,
        context: &SampleContext<'_>,
    ) -> Controls<'_> {
        if self.nodes.is_empty() || frames == 0 {
            return Controls::default();
        }
        #[cfg(test)]
        super::LANES_FILLED.set(super::LANES_FILLED.get() + self.nodes.len());
        let last_offset = i64::try_from(frames - 1).unwrap_or(i64::MAX);
        for (node, lane) in self.nodes.iter().zip(&mut self.lanes) {
            let first_sample = input - node.latency_before;
            let first_point = first_sample.div_euclid(CONTROL_INTERVAL);
            let point_after_the_block = first_sample
                .saturating_add(last_offset)
                .div_euclid(CONTROL_INTERVAL)
                + 1;
            let params = node.params.len();
            let points = usize::try_from(point_after_the_block - first_point + 1)
                .unwrap_or(self.points_per_lane)
                .min(self.points_per_lane);
            lane.first_point = first_point;
            lane.points = points;
            let values = &mut self.values[lane.offset..lane.offset + points * params];
            for (point, values) in (first_point..).zip(values.chunks_exact_mut(params)) {
                let sample = point.saturating_mul(CONTROL_INTERVAL);
                for (value, param) in values.iter_mut().zip(&node.params) {
                    *value = param.at(sample, sample_rate, context);
                }
            }
        }
        Controls {
            lanes: &self.lanes,
            values: &self.values,
        }
    }
}