use alpha2_audio::{Interpolator, MAX_FILTERED_SPEED, Stretch};
use alpha2_eval::{ActiveAudioClip, Direction, PieceMotion, Stretch as Run, TimeCurve, TimePiece};
use alpha2_media::AudioBlockProvider;
use alpha2_time::TICKS_PER_SECOND;
use super::stretch_read::{CurveRun, stretched_request, stretches};
use super::{
AudioRenderer, Fill, SourceMap, clip_downmix, filtered_sample, sample_at_or_after, ticks_at,
wrap_fade,
};
use crate::EngineProject;
const HULL_MARGIN: i64 = 1;
#[expect(
clippy::cast_precision_loss,
reason = "sample and tick counts stay far below 2^53"
)]
const fn real(value: i64) -> f64 {
value as f64
}
fn floored(value: f64) -> Option<i64> {
const I64_RANGE: f64 = 9.0e18;
#[expect(
clippy::cast_possible_truncation,
reason = "the value is whole and inside the range of an i64"
)]
(value.abs() < I64_RANGE).then(|| libm::floor(value) as i64)
}
fn time_of(sample: i64, rate: u32) -> f64 {
real(sample) * real(TICKS_PER_SECOND) / f64::from(rate)
}
fn samples_at(ticks: f64, rate: u32) -> f64 {
ticks * f64::from(rate) / real(TICKS_PER_SECOND)
}
struct Span {
sample: i64,
index: usize,
length: usize,
piece: TimePiece,
}
impl Span {
fn line(&self, rate: u32) -> Option<SourceMap> {
let PieceMotion::Line {
time,
source_time,
over,
by,
} = self.piece.motion
else {
return None;
};
SourceMap::line(
i128::from(time),
i128::from(source_time),
i128::from(over),
i128::from(by),
rate,
)
}
fn curved_request(
&self,
clip: &ActiveAudioClip,
curve: &TimeCurve,
steepest: f64,
rate: u32,
) -> Option<(i64, i64)> {
let last = self
.sample
.checked_add(i64::try_from(self.length).ok()?)?
.checked_sub(1)?;
let (low, high) = curve.hull(&self.piece, time_of(self.sample, rate), time_of(last, rate));
let (start, end) = source_ticks(clip);
let (low, high) = (low.max(start), high.min(end));
if low.is_nan() || high.is_nan() || low > high {
return None;
}
let half = Interpolator::new(steepest.min(MAX_FILTERED_SPEED)).half_taps();
let from = floored(samples_at(low, rate))?
.checked_sub(half - 1 + HULL_MARGIN)?
.max(0);
let to = floored(samples_at(high, rate))?.checked_add(half + 1 + HULL_MARGIN)?;
Some((from, to))
}
}
fn source_ticks(clip: &ActiveAudioClip) -> (f64, f64) {
(
real(clip.source_range.start().ticks()),
real(clip.source_range.end().ticks()),
)
}
fn spans(
clip: &ActiveAudioClip,
curve: &TimeCurve,
first_sample: i64,
count: usize,
rate: u32,
mut each: impl FnMut(Span),
) {
let mut index = 0;
while index < count {
let sample = first_sample.saturating_add(i64::try_from(index).unwrap_or(i64::MAX));
let piece = curve.piece(ticks_at(sample, rate), clip.source_range);
let length = usize::try_from(sample_at_or_after(piece.to, rate).saturating_sub(sample))
.unwrap_or(usize::MAX)
.clamp(1, count - index);
each(Span {
sample,
index,
length,
piece,
});
index += length;
}
}
fn runs<'a>(
curve: TimeCurve<'a>,
stretches: &[Run],
first_sample: i64,
count: usize,
rate: u32,
mut each: impl FnMut(CurveRun<'a>, i64, usize, usize),
) {
let end = first_sample.saturating_add(i64::try_from(count).unwrap_or(i64::MAX));
let first =
stretches.partition_point(|stretch| sample_at_or_after(stretch.to, rate) <= first_sample);
for (number, stretch) in stretches.iter().enumerate().skip(first) {
let origin = sample_at_or_after(stretch.from, rate);
if origin >= end {
break;
}
let run_end = sample_at_or_after(stretch.to, rate);
let (from, to) = (origin.max(first_sample), run_end.min(end));
if stretch.direction == Direction::Still || from >= to {
continue;
}
let run = CurveRun {
curve,
number,
falling: stretch.direction == Direction::Falling,
origin,
end: run_end,
};
each(
run,
from,
usize::try_from(from - first_sample).unwrap_or(0),
usize::try_from(to - from).unwrap_or(0),
);
}
}
pub(super) fn curve_requests(
snapshot: &EngineProject,
stretch: &Stretch,
clip: &ActiveAudioClip,
first_sample: i64,
count: usize,
rate: u32,
mut request: impl FnMut(i64, i64),
) {
let Some(curve) = TimeCurve::of(clip.time_map) else {
return;
};
if stretches(clip) {
let all = snapshot.curve_stretches(clip.clip_id);
runs(
curve,
all,
first_sample,
count,
rate,
|run, from, _, length| {
if let Some((from, to)) =
stretched_request(stretch, clip, Some(&run), from, length, rate)
{
request(from, to);
}
},
);
return;
}
spans(clip, &curve, first_sample, count, rate, |span| {
let window = match span.piece.motion {
PieceMotion::Level => None,
PieceMotion::Line { .. } => span
.line(rate)
.and_then(|map| map.request(span.sample, span.length)),
PieceMotion::Curved { steepest } => span.curved_request(clip, &curve, steepest, rate),
};
if let Some((from, to)) = window {
request(from, to);
}
});
}
impl AudioRenderer {
pub(super) fn fill_curve(
&mut self,
snapshot: &EngineProject,
clip: &ActiveAudioClip,
first_sample: i64,
count: usize,
provider: &dyn AudioBlockProvider,
fill: Fill,
) -> bool {
let Some(curve) = TimeCurve::of(clip.time_map) else {
return false;
};
if !stretches(clip) {
return self.fill_pieces(clip, &curve, first_sample, count, provider, fill);
}
let all = snapshot.curve_stretches(clip.clip_id);
let rate = self.sample_rate;
let mut complete = true;
runs(
curve,
all,
first_sample,
count,
rate,
|run, from, offset, length| {
complete &=
self.read_stretched(clip, Some(&run), from, offset, length, provider, fill);
},
);
if fill == Fill::Samples {
self.shape_runs(clip, &curve, all, first_sample, count);
}
complete
}
fn shape_runs(
&mut self,
clip: &ActiveAudioClip,
curve: &TimeCurve,
stretches: &[Run],
first_sample: i64,
count: usize,
) {
let rate = self.sample_rate;
let fade = wrap_fade(rate);
let (start, end) = (
clip.timeline_range.start().ticks(),
clip.timeline_range.end().ticks(),
);
let level = |tick: i64| curve.piece(tick, clip.source_range).motion == PieceMotion::Level;
spans(clip, curve, first_sample, count, rate, |span| {
if span.piece.motion == PieceMotion::Level {
for channel in 0..self.layout.channels() {
self.clip_a[channel][span.index..span.index + span.length].fill(0.0);
}
return;
}
let span_end = span
.sample
.saturating_add(i64::try_from(span.length).unwrap_or(i64::MAX));
let first = stretches
.partition_point(|stretch| sample_at_or_after(stretch.to, rate) <= span.sample);
for stretch in &stretches[first..] {
if sample_at_or_after(stretch.from, rate) >= span_end {
break;
}
let (from, to) = (
stretch.from.max(span.piece.from),
stretch.to.min(span.piece.to),
);
let (first, last) = (
sample_at_or_after(from, rate).max(span.sample),
sample_at_or_after(to, rate).min(span_end),
);
if stretch.direction == Direction::Still || first >= last {
continue;
}
let fade_in = (from > start && (from == stretch.from || level(from - 1)))
.then(|| sample_at_or_after(from, rate));
let fade_out = (to < end && (to == stretch.to || level(to)))
.then(|| sample_at_or_after(to, rate));
if fade_in.is_some() || fade_out.is_some() {
self.fade_wraps(
first,
span.index + usize::try_from(first - span.sample).unwrap_or(0),
usize::try_from(last - first).unwrap_or(0),
fade_in,
fade_out,
fade,
);
}
}
});
}
fn fill_pieces(
&mut self,
clip: &ActiveAudioClip,
curve: &TimeCurve,
first_sample: i64,
count: usize,
provider: &dyn AudioBlockProvider,
fill: Fill,
) -> bool {
let rate = self.sample_rate;
let fade = wrap_fade(rate);
let (start, end) = (
clip.timeline_range.start().ticks(),
clip.timeline_range.end().ticks(),
);
let level = |tick: i64| curve.piece(tick, clip.source_range).motion == PieceMotion::Level;
let mut complete = true;
spans(clip, curve, first_sample, count, rate, |span| {
let piece = span.piece;
complete &= match piece.motion {
PieceMotion::Level => return,
PieceMotion::Line { .. } => span.line(rate).is_some_and(|map| {
self.read_source(
clip,
&map,
span.sample,
span.index,
span.length,
provider,
fill,
)
}),
PieceMotion::Curved { steepest } => {
self.read_curved(clip, curve, &span, steepest, provider, fill)
}
};
if fill != Fill::Samples {
return;
}
let fade_in = (piece.from > start && (piece.jumps_in || level(piece.from - 1)))
.then(|| sample_at_or_after(piece.from, rate));
let fade_out = (piece.to < end && (piece.jumps_out || level(piece.to)))
.then(|| sample_at_or_after(piece.to, rate));
if fade_in.is_some() || fade_out.is_some() {
self.fade_wraps(
span.sample,
span.index,
span.length,
fade_in,
fade_out,
fade,
);
}
});
complete
}
fn read_curved(
&mut self,
clip: &ActiveAudioClip,
curve: &TimeCurve,
span: &Span,
steepest: f64,
provider: &dyn AudioBlockProvider,
fill: Fill,
) -> bool {
let rate = self.sample_rate;
let Some((from, to)) = span.curved_request(clip, curve, steepest, rate) else {
return true;
};
let frames = usize::try_from(to.saturating_sub(from)).unwrap_or(0);
let Some(block) = provider.block(clip.source_id, clip.audio.stream, from, frames) else {
return false;
};
if !block.covers(from, to) {
return false;
}
let source = block.block;
if source.sample_rate != rate {
return false;
}
let Some(downmix) = clip_downmix(clip, source, self.layout) else {
return false;
};
if fill == Fill::Presence {
return true;
}
#[cfg(test)]
{
self.samples_read += span.length;
}
let (low, high) = source_ticks(clip);
let planes = source.channels.as_slice();
let mut weights = std::mem::take(&mut self.weights);
for (index, sample) in (span.sample..).take(span.length).enumerate() {
let (value, speed) = curve.position(time_of(sample, rate));
if !(low..=high).contains(&value) {
continue;
}
let position = samples_at(value, rate);
let Some(whole) = floored(position) else {
continue;
};
let interpolator = Interpolator::new(speed.abs().min(steepest));
interpolator.weights(position - libm::floor(position), &mut weights);
let Some(first) = whole
.checked_sub(source.start_sample)
.and_then(|at| at.checked_sub(interpolator.half_taps() - 1))
else {
continue;
};
for channel in 0..self.layout.channels() {
self.clip_a[channel][span.index + index] =
filtered_sample(downmix.channel(channel), planes, first, &weights);
}
}
self.weights = weights;
true
}
}