mod session;
mod stream;
mod timeline;
pub use session::{RenderSession, SessionState};
pub use timeline::{AutomationRamp, RenderSchedule, TransportChange};
use crate::errors::RenderError;
use crate::event::{Events, events_fit};
use crate::sample::Sample;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Tail {
Samples(u32),
Infinite,
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum TailPolicy {
Reported,
UntilSilence {
threshold: f64,
hold_seconds: f64,
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct RenderOptions {
pub tail: TailPolicy,
pub max_tail_seconds: f64,
}
impl Default for RenderOptions {
fn default() -> RenderOptions {
RenderOptions {
tail: TailPolicy::UntilSilence {
threshold: 1.585e-5,
hold_seconds: 1.0,
},
max_tail_seconds: 30.0,
}
}
}
impl RenderOptions {
#[must_use]
pub const fn new(tail: TailPolicy, max_tail_seconds: f64) -> RenderOptions {
RenderOptions {
tail,
max_tail_seconds,
}
}
fn validate(&self) -> Result<(), RenderError> {
if !self.max_tail_seconds.is_finite() || self.max_tail_seconds < 0.0 {
return Err(RenderError::TailDuration);
}
if let TailPolicy::UntilSilence {
threshold,
hold_seconds,
} = self.tail
{
if !threshold.is_finite() || threshold < 0.0 {
return Err(RenderError::SilenceThreshold);
}
if !hold_seconds.is_finite() || hold_seconds < 0.0 {
return Err(RenderError::SilenceHold);
}
}
Ok(())
}
}
pub trait Process<S: Sample> {
type Error: From<RenderError>;
fn sample_rate(&self) -> f64;
fn max_block_size(&self) -> usize;
fn input_channels(&self) -> usize;
fn output_channels(&self) -> usize;
fn latency(&self) -> Result<u32, Self::Error>;
fn tail(&self) -> Result<Tail, Self::Error>;
fn begin_render(&mut self) -> Result<(), Self::Error> {
Ok(())
}
fn validate_automation(
&mut self,
automation: &[crate::AutomationEvent],
) -> Result<(), Self::Error> {
if automation.is_empty() {
Ok(())
} else {
Err(RenderError::Input(crate::InputError::Automation).into())
}
}
fn validate_events(&mut self, _events: &Events) -> Result<(), Self::Error> {
Ok(())
}
fn process(
&mut self,
context: &crate::BlockContext,
input: &[&[S]],
output: &mut [&mut [S]],
automation: &[crate::AutomationEvent],
events: &Events,
produced: &mut Events,
) -> Result<(), Self::Error>;
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Delivery<'a, S> {
pub audio: &'a [&'a [S]],
pub events: &'a Events,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Rendered<S> {
pub channels: Vec<Vec<S>>,
pub events: Events,
pub latency: u32,
pub tail: usize,
pub status: RenderStatus,
}
pub fn render<S: Sample, P: Process<S>>(
processor: &mut P,
input: &[&[S]],
frames: usize,
events: &Events,
options: &RenderOptions,
) -> Result<Rendered<S>, P::Error> {
render_with_schedule(
processor,
input,
frames,
events,
options,
&RenderSchedule::default(),
)
}
pub fn render_with_schedule<S: Sample, P: Process<S>>(
processor: &mut P,
input: &[&[S]],
frames: usize,
events: &Events,
options: &RenderOptions,
schedule: &RenderSchedule<'_>,
) -> Result<Rendered<S>, P::Error> {
let mut channels = vec![Vec::new(); processor.output_channels()];
let mut produced = Events::new();
let result = render_stream(
processor,
RenderInput {
audio: input,
frames,
events,
schedule: *schedule,
},
options,
|delivery| {
for (channel, samples) in channels.iter_mut().zip(delivery.audio) {
channel.extend_from_slice(samples);
}
produced.extend_from(delivery.events);
},
|| false,
)?;
Ok(Rendered {
channels,
events: produced,
latency: result.latency,
tail: result.tail,
status: result.status,
})
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct RenderInput<'a, S> {
pub audio: &'a [&'a [S]],
pub frames: usize,
pub events: &'a Events,
pub schedule: RenderSchedule<'a>,
}
impl<'a, S> RenderInput<'a, S> {
#[must_use]
pub fn new(audio: &'a [&'a [S]], frames: usize, events: &'a Events) -> RenderInput<'a, S> {
RenderInput {
audio,
frames,
events,
schedule: RenderSchedule::default(),
}
}
#[must_use]
pub fn with_schedule(mut self, schedule: RenderSchedule<'a>) -> RenderInput<'a, S> {
self.schedule = schedule;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RenderStatus {
Complete,
Cancelled,
TailLimit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RenderProgress {
pub status: RenderStatus,
pub processed_frames: usize,
pub output_frames: usize,
pub latency: u32,
pub tail: usize,
}
pub fn render_stream<S: Sample, P: Process<S>>(
processor: &mut P,
request: RenderInput<'_, S>,
options: &RenderOptions,
consume: impl FnMut(Delivery<'_, S>),
cancelled: impl FnMut() -> bool,
) -> Result<RenderProgress, P::Error> {
render_reusing(
processor,
request,
options,
None,
&mut Scratch::default(),
consume,
cancelled,
)
}
struct Scratch<S> {
input: Vec<Vec<S>>,
output: Vec<Vec<S>>,
stage: stream::Output<S>,
events: Events,
automation: Vec<crate::AutomationEvent>,
produced: Events,
produced_since: Events,
targets: Vec<crate::AutomationEvent>,
timeline: timeline::Storage,
}
impl<S: Sample> Default for Scratch<S> {
fn default() -> Scratch<S> {
Scratch {
input: Vec::new(),
output: Vec::new(),
stage: stream::Output::default(),
events: Events::for_block(),
automation: Vec::new(),
produced: Events::for_block(),
produced_since: Events::new(),
targets: Vec::new(),
timeline: timeline::Storage::default(),
}
}
}
fn size<S: Sample>(buffers: &mut Vec<Vec<S>>, channels: usize, frames: usize) {
buffers.resize_with(channels, Vec::new);
for buffer in buffers {
buffer.resize(frames, S::default());
}
}
fn render_reusing<S: Sample, P: Process<S>>(
processor: &mut P,
request: RenderInput<'_, S>,
options: &RenderOptions,
skip: Option<usize>,
scratch: &mut Scratch<S>,
mut consume: impl FnMut(Delivery<'_, S>),
mut cancelled: impl FnMut() -> bool,
) -> Result<RenderProgress, P::Error> {
let RenderInput {
audio: input,
frames,
events,
schedule,
} = request;
let Scratch {
input: input_block,
output: output_block,
stage: output,
events: block_events,
automation,
produced,
produced_since,
targets,
timeline: storage,
} = scratch;
processor.begin_render()?;
let expected = processor.input_channels();
if input.len() != expected || input.iter().any(|channel| channel.len() != frames) {
return Err(RenderError::Input(crate::InputError::AudioBuffers).into());
}
if !events_fit(events, frames) {
return Err(RenderError::Input(crate::InputError::Events).into());
}
processor.validate_events(events)?;
let latency = processor.latency()?;
let sample_rate = processor.sample_rate();
let block = processor.max_block_size();
crate::config::validate_processing(sample_rate, block).map_err(RenderError::Input)?;
options.validate()?;
let max_tail = seconds_to_samples(options.max_tail_seconds, sample_rate)?;
let body = frames
.checked_add(latency as usize)
.ok_or(RenderError::LengthOverflow)?;
let reported = matches!(options.tail, TailPolicy::Reported);
let reported_tail = |tail: Tail| match tail {
Tail::Samples(samples) => (samples as usize).min(max_tail),
Tail::Infinite => max_tail,
};
let tail = if reported {
reported_tail(processor.tail()?)
} else {
max_tail
};
let end = body.checked_add(tail).ok_or(RenderError::LengthOverflow)?;
std::alloc::Layout::array::<S>(end).map_err(|_| RenderError::LengthOverflow)?;
schedule
.validate(frames, end, sample_rate)
.map_err(RenderError::Input)?;
let mut timeline = timeline::Timeline::new(schedule, storage);
timeline
.validate_capacity(events)
.map_err(RenderError::Input)?;
targets.clear();
targets.extend(
schedule
.automation
.iter()
.copied()
.chain(schedule.ramps.iter().map(|ramp| crate::AutomationEvent {
slot: ramp.slot,
change: crate::ParameterChange {
id: ramp.id,
offset: ramp.start,
value: ramp.from,
},
})),
);
processor.validate_automation(targets)?;
let silence = match options.tail {
TailPolicy::UntilSilence {
threshold,
hold_seconds,
} => Some((threshold, seconds_to_samples(hold_seconds, sample_rate)?)),
TailPolicy::Reported => None,
};
let skip = skip.unwrap_or(latency as usize);
size(input_block, input.len(), block);
size(output_block, processor.output_channels(), block);
output.start(output_block.len(), silence);
let mut status = RenderStatus::Complete;
let mut silent = false;
let mut position = 0;
let mut pending = 0;
block_events.clear();
automation.clear();
produced.clear();
produced_since.clear();
automation.reserve(crate::MAX_BLOCK_EVENTS);
while position < end {
if cancelled() {
status = RenderStatus::Cancelled;
break;
}
let boundary = schedule.next_transport(position).unwrap_or(end).min(end);
let limit = position + block.min(boundary - position);
let block_end = timeline.fill_block(position, limit, events, pending, automation);
let count = block_end - position;
let start = position.min(frames);
let available = count.min(frames - start);
for (buffer, source) in input_block.iter_mut().zip(input) {
buffer[..available].copy_from_slice(&source[start..start + available]);
buffer[available..count].fill(S::default());
}
for buffer in output_block.iter_mut() {
buffer[..count].fill(S::default());
}
let inputs: Vec<&[S]> = input_block.iter().map(|b| &b[..count]).collect();
let mut outputs: Vec<&mut [S]> = output_block.iter_mut().map(|b| &mut b[..count]).collect();
let due = events.partition_point(|offset| offset < position + count);
block_events.clear();
for event in events.iter().skip(pending).take(due - pending) {
block_events
.push(event.at(event.offset - position))
.map_err(RenderError::Input)?;
}
pending = due;
let context = crate::BlockContext {
frames: count,
transport: schedule
.transport_at(position, sample_rate)
.map_err(RenderError::Input)?,
};
processor.process(
&context,
&inputs,
&mut outputs,
automation,
block_events,
produced,
)?;
for event in produced.iter() {
produced_since
.push(event.at(event.offset + position))
.map_err(RenderError::Input)?;
}
let now = processor.latency()?;
if now != latency {
return Err(RenderError::LatencyChanged {
before: latency,
after: now,
}
.into());
}
let silenced = output.accept(output_block, count, position, skip, body);
let first = skip.saturating_sub(position).min(count);
let last = silenced.unwrap_or(count);
if let Some(frame) = crate::sample::level(output_block, first..last).non_finite {
return Err(RenderError::NonFiniteOutput {
frame: position + frame - skip,
}
.into());
}
position += count;
output.deliver(produced_since, &mut consume);
if silenced.is_some() {
silent = true;
break;
}
}
output.deliver(produced_since, &mut consume);
if status == RenderStatus::Complete && silence.is_some() && !silent {
status = RenderStatus::TailLimit;
}
Ok(RenderProgress {
status,
processed_frames: position,
output_frames: output.emitted,
latency,
tail: output.emitted.saturating_sub(body.saturating_sub(skip)),
})
}
fn seconds_to_samples(seconds: f64, sample_rate: f64) -> Result<usize, RenderError> {
let samples = (seconds * sample_rate).round();
let upper_bound = (usize::MAX as u128 + 1) as f64;
if !samples.is_finite() || samples >= upper_bound {
return Err(RenderError::LengthOverflow);
}
Ok(samples as usize)
}
#[cfg(test)]
mod tests;