use std::collections::HashMap;
use alpha2_audio::{Interpolator, Stretch, StretchReader, StretchSignal};
use alpha2_eval::{ActiveAudioClip, TimeCurve};
use alpha2_media::{AudioBlock, AudioBlockProvider, SourceId};
use alpha2_model::{AudioRead, ClipId, TimeMap};
use alpha2_time::{TICKS_PER_SECOND, TimeRange};
use super::{AudioRenderer, Fill, SourceMap, filtered, mixed_sample, sample_at_or_after};
use crate::downmix::Downmix;
pub(super) fn read_of(clip: &ActiveAudioClip) -> AudioRead {
clip.audio
.read(clip.time_map, clip.timeline_range, clip.source_range)
}
pub(super) fn stretches(clip: &ActiveAudioClip) -> bool {
read_of(clip).stretches()
}
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)
}
#[expect(
clippy::cast_precision_loss,
reason = "sample counts stay far below 2^53"
)]
const fn real(sample: i64) -> f64 {
sample as f64
}
struct ReadLine {
whole: i64,
fraction: f64,
step: f64,
}
impl ReadLine {
fn floor_at(&self, stretched_sample: i64) -> Option<i64> {
self.whole
.checked_add(floored(self.fraction + real(stretched_sample) * self.step)?)
}
}
struct Tap {
at: i64,
fraction: f64,
interpolator: Interpolator,
}
impl Tap {
fn first(&self) -> Option<i64> {
self.at.checked_sub(self.interpolator.half_taps() - 1)
}
fn end(&self) -> Option<i64> {
self.at.checked_add(self.interpolator.half_taps() + 1)
}
}
enum Resampling {
Constant {
pitch: f64,
interpolator: Interpolator,
},
Along(Vec<Tap>),
}
impl Resampling {
fn new(pitch: f64) -> Option<Self> {
(pitch.is_finite() && pitch > 0.0).then(|| Self::Constant {
pitch,
interpolator: Interpolator::new(pitch),
})
}
fn along(path: &CurvePath, ratio: f64, clip_first: i64, clip_end: i64) -> Option<Self> {
if !(ratio.is_finite() && ratio > 0.0) {
return None;
}
let start = path.ends[0].0;
(clip_first..clip_end)
.map(|clip_sample| {
let (position, speed) = path.inside(real(clip_sample));
let stretched = ratio * (position - start);
Some(Tap {
at: floored(stretched)?,
fraction: stretched - libm::floor(stretched),
interpolator: Interpolator::new(ratio * speed.abs()),
})
})
.collect::<Option<Vec<Tap>>>()
.map(Self::Along)
}
fn tap(&self, clip_sample: i64) -> Option<Tap> {
let Self::Constant {
pitch,
interpolator,
} = self
else {
return None;
};
let position = real(clip_sample) * pitch;
Some(Tap {
at: floored(position)?,
fraction: position - libm::floor(position),
interpolator: *interpolator,
})
}
fn resample(
&self,
stretched: &[Vec<f32>],
stretched_first: i64,
clip_first: i64,
outputs: &mut [&mut [f32]],
weights: &mut Vec<f64>,
) {
let count = outputs.first().map_or(0, |output| output.len());
for (index, clip_sample) in (clip_first..).take(count).enumerate() {
let constant = self.tap(clip_sample);
let tap = match self {
Self::Constant { .. } => constant.as_ref(),
Self::Along(taps) => taps.get(index),
};
let Some(tap) = tap else {
continue;
};
let Some(first_tap) = tap.first().and_then(|tap| tap.checked_sub(stretched_first))
else {
continue;
};
tap.interpolator.weights(tap.fraction, weights);
for (output, plane) in outputs.iter_mut().zip(stretched) {
output[index] = filtered(plane, first_tap, weights);
}
}
}
fn stretched_span(&self, clip_first: i64, clip_end: i64) -> Option<(i64, i64)> {
match self {
Self::Constant { .. } => Some((
self.tap(clip_first)?.first()?,
self.tap(clip_end.checked_sub(1)?)?.end()?,
)),
Self::Along(taps) => {
let mut span = (i64::MAX, i64::MIN);
for tap in taps {
span = (span.0.min(tap.first()?), span.1.max(tap.end()?));
}
(span.0 < span.1).then_some(span)
}
}
}
}
pub(super) struct CurveRun<'a> {
pub(super) curve: TimeCurve<'a>,
pub(super) number: usize,
pub(super) falling: bool,
pub(super) origin: i64,
pub(super) end: i64,
}
struct CurvePath<'a> {
curve: TimeCurve<'a>,
rate: u32,
falling: bool,
origin: i64,
last: f64,
clip_samples_per_stretched: f64,
ends: [(f64, f64); 2],
}
impl<'a> CurvePath<'a> {
fn new(run: &CurveRun<'a>, rate: u32, read: AudioRead) -> Option<Self> {
let clip_samples_per_stretched = match read {
AudioRead::PitchedAlong {
ratio,
preserve: true,
} => 1.0 / ratio,
_ => 1.0,
};
if !(clip_samples_per_stretched.is_finite() && clip_samples_per_stretched > 0.0) {
return None;
}
let mut path = Self {
curve: run.curve,
rate,
falling: run.falling,
origin: run.origin,
last: real(run.end.checked_sub(run.origin)?.checked_sub(1)?.max(0)),
clip_samples_per_stretched,
ends: [(0.0, 0.0); 2],
};
path.ends = [path.inside(0.0), path.inside(path.last)];
Some(path)
}
fn inside(&self, clip_sample: f64) -> (f64, f64) {
let time =
(real(self.origin) + clip_sample) * real(TICKS_PER_SECOND) / f64::from(self.rate);
let (value, speed) = self.curve.position(time);
let position = value * f64::from(self.rate) / real(TICKS_PER_SECOND);
if self.falling {
(-position, -speed)
} else {
(position, speed)
}
}
fn at(&self, clip_sample: f64) -> f64 {
let continued =
|(position, speed): (f64, f64), beyond: f64| position + beyond * speed.max(0.0);
if clip_sample < 0.0 {
continued(self.ends[0], clip_sample)
} else if clip_sample > self.last {
continued(self.ends[1], clip_sample - self.last)
} else {
self.inside(clip_sample).0
}
}
}
enum Along<'a> {
Clip(SourceMap),
Curve(CurvePath<'a>),
}
struct GrainMap<'a> {
along: Along<'a>,
reversed: bool,
origin: i64,
hop: i64,
bounds: (i64, i64),
pitched: Option<ReadLine>,
}
impl<'a> GrainMap<'a> {
fn new(
clip: &ActiveAudioClip,
run: Option<&CurveRun<'a>>,
rate: u32,
hop: i64,
read: AudioRead,
) -> Option<Self> {
let (along, reversed, origin) = if let Some(run) = run {
(
Along::Curve(CurvePath::new(run, rate, read)?),
run.falling,
run.origin,
)
} else {
let reversed = *clip.time_map == TimeMap::Reverse;
(
Along::Clip(SourceMap::stretched(clip, reversed, rate)?),
reversed,
sample_at_or_after(clip.timeline_range.start().ticks(), rate),
)
};
let low = sample_at_or_after(clip.source_range.start().ticks(), rate);
let high = sample_at_or_after(clip.source_range.end().ticks(), rate);
let mut grains = Self {
along,
reversed,
origin,
hop,
bounds: if reversed {
(1 - high, 1 - low)
} else {
(low, high)
},
pitched: None,
};
let step = match read {
AudioRead::Pitched { stretch, .. } => stretch,
AudioRead::PitchedAlong {
ratio,
preserve: false,
} => 1.0 / ratio,
_ => return Some(grains),
};
if !(step.is_finite() && step > 0.0) {
return None;
}
let (whole, fraction) = grains.read_position(grains.origin)?;
grains.pitched = Some(ReadLine {
whole,
fraction,
step,
});
Some(grains)
}
fn read_position(&self, sample: i64) -> Option<(i64, f64)> {
let map = match &self.along {
Along::Clip(map) => map,
Along::Curve(path) => {
let position = path.at(real(sample.checked_sub(self.origin)?));
return Some((floored(position)?, position - libm::floor(position)));
}
};
let (whole, fraction) = map.position(sample)?;
if !self.reversed {
return Some((whole, fraction));
}
if fraction > 0.0 {
Some((whole.checked_add(1)?.checked_neg()?, 1.0 - fraction))
} else {
Some((whole.checked_neg()?, 0.0))
}
}
fn position(&self, grain: i64) -> Option<i64> {
let centre = grain.checked_add(1)?.checked_mul(self.hop)?;
let at = match (&self.pitched, &self.along) {
(Some(line), _) => line.floor_at(centre)?,
(None, Along::Curve(path)) => {
floored(path.at(real(centre) * path.clip_samples_per_stretched))?
}
(None, Along::Clip(_)) => self.read_position(self.origin.checked_add(centre)?)?.0,
};
at.checked_sub(self.hop)
}
const fn source(&self, at: i64) -> i64 {
if self.reversed { -at } else { at }
}
fn folded(
&self,
(from, to): (i64, i64),
downmix: &Downmix,
source: &AudioBlock,
channels: usize,
) -> Vec<Vec<f32>> {
(0..channels)
.map(|channel| {
let mix = downmix.channel(channel);
(from..to)
.map(|at| {
if at < self.bounds.0 || at >= self.bounds.1 {
0.0
} else {
mixed_sample(
mix,
&source.channels,
self.source(at) - source.start_sample,
)
}
})
.collect()
})
.collect()
}
fn source_window(&self, from: i64, to: i64) -> Option<(i64, i64)> {
let (from, to) = (from.max(self.bounds.0), to.min(self.bounds.1));
if from >= to {
return None;
}
Some(if self.reversed {
(1 - to, 1 - from)
} else {
(from, to)
})
}
}
struct Window<'a> {
grains: GrainMap<'a>,
first: i64,
stretched_frames: usize,
read: (i64, i64),
source: Option<(i64, i64)>,
clip_first: i64,
resampling: Option<Resampling>,
}
fn window<'a>(
stretch: &Stretch,
clip: &ActiveAudioClip,
run: Option<&CurveRun<'a>>,
first_sample: i64,
count: usize,
rate: u32,
) -> Option<Window<'a>> {
let read = read_of(clip);
let grains = GrainMap::new(clip, run, rate, stretch.hop(), read)?;
let clip_first = first_sample.checked_sub(grains.origin)?;
let clip_end = clip_first.checked_add(i64::try_from(count).ok()?)?;
let resampling = match (read, &grains.along) {
(AudioRead::Pitched { pitch, .. }, _) => Some(Resampling::new(pitch)?),
(
AudioRead::PitchedAlong {
ratio,
preserve: true,
},
_,
) => Some(Resampling::new(ratio)?),
(
AudioRead::PitchedAlong {
ratio,
preserve: false,
},
Along::Curve(path),
) => Some(Resampling::along(path, ratio, clip_first, clip_end)?),
_ => None,
};
let (first, end) = match &resampling {
Some(resampling) => resampling.stretched_span(clip_first, clip_end)?,
None => (clip_first, clip_end),
};
let (low, high) = stretch.grains(first, end);
grains.position(Stretch::chain(Stretch::segment(low)).0)?;
grains.position(Stretch::chain(Stretch::segment(high)).1)?;
let read = stretch.reach_output(first, end, |grain| grains.position(grain).unwrap_or(0));
let source = grains.source_window(read.0, read.1);
Some(Window {
grains,
first,
stretched_frames: usize::try_from(end.checked_sub(first)?).ok()?,
read,
source,
clip_first,
resampling,
})
}
pub(super) fn stretched_request(
stretch: &Stretch,
clip: &ActiveAudioClip,
run: Option<&CurveRun<'_>>,
first_sample: i64,
count: usize,
rate: u32,
) -> Option<(i64, i64)> {
window(stretch, clip, run, first_sample, count, rate)?.source
}
pub(super) struct StretchSlot {
source: SourceId,
stream: Option<u32>,
channel_map: Option<alpha2_model::ChannelMap>,
timeline_range: TimeRange,
source_range: TimeRange,
time_map: TimeMap,
read: AudioRead,
reader: StretchReader,
pub(super) used_in: u64,
}
fn reader_for<'a>(
slots: &'a mut HashMap<(ClipId, usize), StretchSlot>,
clip: &ActiveAudioClip,
run: usize,
rate: u32,
block: u64,
) -> &'a mut StretchReader {
let fresh = || StretchSlot {
source: clip.source_id.clone(),
stream: clip.audio.stream,
channel_map: clip.audio.channel_map.clone(),
timeline_range: clip.timeline_range,
source_range: clip.source_range,
time_map: clip.time_map.clone(),
read: read_of(clip),
reader: StretchReader::new(rate),
used_in: block,
};
let slot = slots
.entry((clip.clip_id.clone(), run))
.or_insert_with(fresh);
if slot.source != *clip.source_id
|| slot.stream != clip.audio.stream
|| slot.channel_map != clip.audio.channel_map
|| slot.timeline_range != clip.timeline_range
|| slot.source_range != clip.source_range
|| slot.time_map != *clip.time_map
|| slot.read != read_of(clip)
{
*slot = fresh();
}
slot.used_in = block;
&mut slot.reader
}
impl AudioRenderer {
#[expect(
clippy::too_many_arguments,
reason = "a read is a clip, a span of it, where it goes and where it comes from"
)]
pub(super) fn read_stretched(
&mut self,
clip: &ActiveAudioClip,
run: Option<&CurveRun<'_>>,
first_sample: i64,
offset: usize,
count: usize,
provider: &dyn AudioBlockProvider,
fill: Fill,
) -> bool {
let rate = self.sample_rate;
let Some(window) = window(&self.stretch, clip, run, first_sample, count, rate) else {
return false;
};
let Some((source_from, source_to)) = window.source else {
return true;
};
let frames = usize::try_from(source_to - source_from).unwrap_or(0);
let Some(span) = provider.block(clip.source_id, clip.audio.stream, source_from, frames)
else {
return false;
};
if !span.covers(source_from, source_to) {
return false;
}
let source = span.block;
if source.sample_rate != rate {
return false;
}
let Some(downmix) = super::clip_downmix(clip, source, self.layout) else {
return false;
};
if fill == Fill::Presence {
return true;
}
#[cfg(test)]
{
self.samples_read += count;
}
let grains = &window.grains;
let (from, _) = window.read;
let channels = self.layout.channels();
let planes = grains.folded(window.read, &downmix, source, channels);
#[allow(clippy::cast_precision_loss)]
let scale = 1.0 / channels as f32;
let mono: Vec<f32> = (0..planes[0].len())
.map(|index| planes.iter().map(|plane| plane[index]).sum::<f32>() * scale)
.collect();
let signals: Vec<StretchSignal<'_>> = planes
.iter()
.map(|plane| StretchSignal {
start: from,
samples: plane,
})
.collect();
let reader = reader_for(
&mut self.stretch_slots,
clip,
run.map_or(0, |run| run.number),
rate,
self.blocks_mixed,
);
let mut stretched = match window.resampling {
Some(_) => vec![vec![0.0; window.stretched_frames]; channels],
None => Vec::new(),
};
let mut outputs: Vec<&mut [f32]> = if window.resampling.is_some() {
stretched.iter_mut().map(Vec::as_mut_slice).collect()
} else {
self.clip_a
.iter_mut()
.take(channels)
.map(|plane| &mut plane[offset..offset + count])
.collect()
};
reader.render(
window.first,
&mut outputs,
|grain| grains.position(grain).unwrap_or(0),
&signals,
StretchSignal {
start: from,
samples: &mono,
},
);
let Some(resampling) = &window.resampling else {
return true;
};
let mut outputs: Vec<&mut [f32]> = self
.clip_a
.iter_mut()
.take(channels)
.map(|plane| &mut plane[offset..offset + count])
.collect();
resampling.resample(
&stretched,
window.first,
window.clip_first,
&mut outputs,
&mut self.weights,
);
true
}
}