1mod session;
5mod stream;
6mod timeline;
7pub use session::{RenderSession, SessionState};
8pub use timeline::{AutomationRamp, RenderSchedule, TransportChange};
9
10use crate::errors::RenderError;
11use crate::event::{Events, events_fit};
12use crate::sample::Sample;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum Tail {
18 Samples(u32),
20 Infinite,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq)]
26#[non_exhaustive]
27pub enum TailPolicy {
28 Reported,
31 UntilSilence {
38 threshold: f64,
40 hold_seconds: f64,
42 },
43}
44
45#[derive(Clone, Copy, Debug, PartialEq)]
50#[non_exhaustive]
51pub struct RenderOptions {
52 pub tail: TailPolicy,
54 pub max_tail_seconds: f64,
56}
57
58impl Default for RenderOptions {
59 fn default() -> RenderOptions {
60 RenderOptions {
61 tail: TailPolicy::UntilSilence {
62 threshold: 1.585e-5,
64 hold_seconds: 1.0,
65 },
66 max_tail_seconds: 30.0,
67 }
68 }
69}
70
71impl RenderOptions {
72 #[must_use]
74 pub const fn new(tail: TailPolicy, max_tail_seconds: f64) -> RenderOptions {
75 RenderOptions {
76 tail,
77 max_tail_seconds,
78 }
79 }
80
81 fn validate(&self) -> Result<(), RenderError> {
82 if !self.max_tail_seconds.is_finite() || self.max_tail_seconds < 0.0 {
83 return Err(RenderError::TailDuration);
84 }
85 if let TailPolicy::UntilSilence {
86 threshold,
87 hold_seconds,
88 } = self.tail
89 {
90 if !threshold.is_finite() || threshold < 0.0 {
91 return Err(RenderError::SilenceThreshold);
92 }
93 if !hold_seconds.is_finite() || hold_seconds < 0.0 {
94 return Err(RenderError::SilenceHold);
95 }
96 }
97 Ok(())
98 }
99}
100
101pub trait Process<S: Sample> {
103 type Error: From<RenderError>;
105
106 fn sample_rate(&self) -> f64;
108 fn max_block_size(&self) -> usize;
110 fn input_channels(&self) -> usize;
112 fn output_channels(&self) -> usize;
114 fn latency(&self) -> Result<u32, Self::Error>;
118 fn tail(&self) -> Result<Tail, Self::Error>;
120 fn begin_render(&mut self) -> Result<(), Self::Error> {
125 Ok(())
126 }
127 fn validate_automation(
130 &mut self,
131 automation: &[crate::AutomationEvent],
132 ) -> Result<(), Self::Error> {
133 if automation.is_empty() {
134 Ok(())
135 } else {
136 Err(RenderError::Input(crate::InputError::Automation).into())
137 }
138 }
139 fn validate_events(&mut self, _events: &Events) -> Result<(), Self::Error> {
144 Ok(())
145 }
146 fn process(
153 &mut self,
154 context: &crate::BlockContext,
155 input: &[&[S]],
156 output: &mut [&mut [S]],
157 automation: &[crate::AutomationEvent],
158 events: &Events,
159 produced: &mut Events,
160 ) -> Result<(), Self::Error>;
161}
162
163#[derive(Clone, Copy, Debug)]
167#[non_exhaustive]
168pub struct Delivery<'a, S> {
169 pub audio: &'a [&'a [S]],
171 pub events: &'a Events,
173}
174
175#[derive(Clone, Debug, PartialEq)]
177#[non_exhaustive]
178pub struct Rendered<S> {
179 pub channels: Vec<Vec<S>>,
181 pub events: Events,
184 pub latency: u32,
186 pub tail: usize,
188 pub status: RenderStatus,
191}
192
193pub fn render<S: Sample, P: Process<S>>(
205 processor: &mut P,
206 input: &[&[S]],
207 frames: usize,
208 events: &Events,
209 options: &RenderOptions,
210) -> Result<Rendered<S>, P::Error> {
211 render_with_schedule(
212 processor,
213 input,
214 frames,
215 events,
216 options,
217 &RenderSchedule::default(),
218 )
219}
220
221pub fn render_with_schedule<S: Sample, P: Process<S>>(
226 processor: &mut P,
227 input: &[&[S]],
228 frames: usize,
229 events: &Events,
230 options: &RenderOptions,
231 schedule: &RenderSchedule<'_>,
232) -> Result<Rendered<S>, P::Error> {
233 let mut channels = vec![Vec::new(); processor.output_channels()];
234 let mut produced = Events::new();
235 let result = render_stream(
236 processor,
237 RenderInput {
238 audio: input,
239 frames,
240 events,
241 schedule: *schedule,
242 },
243 options,
244 |delivery| {
245 for (channel, samples) in channels.iter_mut().zip(delivery.audio) {
246 channel.extend_from_slice(samples);
247 }
248 produced.extend_from(delivery.events);
249 },
250 || false,
251 )?;
252 Ok(Rendered {
253 channels,
254 events: produced,
255 latency: result.latency,
256 tail: result.tail,
257 status: result.status,
258 })
259}
260
261#[derive(Clone, Copy, Debug)]
263#[non_exhaustive]
264pub struct RenderInput<'a, S> {
265 pub audio: &'a [&'a [S]],
267 pub frames: usize,
269 pub events: &'a Events,
271 pub schedule: RenderSchedule<'a>,
273}
274
275impl<'a, S> RenderInput<'a, S> {
276 #[must_use]
278 pub fn new(audio: &'a [&'a [S]], frames: usize, events: &'a Events) -> RenderInput<'a, S> {
279 RenderInput {
280 audio,
281 frames,
282 events,
283 schedule: RenderSchedule::default(),
284 }
285 }
286
287 #[must_use]
289 pub fn with_schedule(mut self, schedule: RenderSchedule<'a>) -> RenderInput<'a, S> {
290 self.schedule = schedule;
291 self
292 }
293}
294
295#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298#[non_exhaustive]
299pub enum RenderStatus {
300 Complete,
302 Cancelled,
304 TailLimit,
308}
309
310#[derive(Clone, Copy, Debug, PartialEq, Eq)]
312#[non_exhaustive]
313pub struct RenderProgress {
314 pub status: RenderStatus,
316 pub processed_frames: usize,
318 pub output_frames: usize,
320 pub latency: u32,
322 pub tail: usize,
324}
325
326pub fn render_stream<S: Sample, P: Process<S>>(
337 processor: &mut P,
338 request: RenderInput<'_, S>,
339 options: &RenderOptions,
340 consume: impl FnMut(Delivery<'_, S>),
341 cancelled: impl FnMut() -> bool,
342) -> Result<RenderProgress, P::Error> {
343 render_reusing(
344 processor,
345 request,
346 options,
347 None,
348 &mut Scratch::default(),
349 consume,
350 cancelled,
351 )
352}
353
354struct Scratch<S> {
356 input: Vec<Vec<S>>,
357 output: Vec<Vec<S>>,
358 stage: stream::Output<S>,
359 events: Events,
360 automation: Vec<crate::AutomationEvent>,
361 produced: Events,
362 produced_since: Events,
363 targets: Vec<crate::AutomationEvent>,
364 timeline: timeline::Storage,
365}
366
367impl<S: Sample> Default for Scratch<S> {
368 fn default() -> Scratch<S> {
369 Scratch {
370 input: Vec::new(),
371 output: Vec::new(),
372 stage: stream::Output::default(),
373 events: Events::for_block(),
374 automation: Vec::new(),
375 produced: Events::for_block(),
376 produced_since: Events::new(),
377 targets: Vec::new(),
378 timeline: timeline::Storage::default(),
379 }
380 }
381}
382
383fn size<S: Sample>(buffers: &mut Vec<Vec<S>>, channels: usize, frames: usize) {
386 buffers.resize_with(channels, Vec::new);
387 for buffer in buffers {
388 buffer.resize(frames, S::default());
389 }
390}
391
392fn render_reusing<S: Sample, P: Process<S>>(
395 processor: &mut P,
396 request: RenderInput<'_, S>,
397 options: &RenderOptions,
398 skip: Option<usize>,
399 scratch: &mut Scratch<S>,
400 mut consume: impl FnMut(Delivery<'_, S>),
401 mut cancelled: impl FnMut() -> bool,
402) -> Result<RenderProgress, P::Error> {
403 let RenderInput {
404 audio: input,
405 frames,
406 events,
407 schedule,
408 } = request;
409 let Scratch {
410 input: input_block,
411 output: output_block,
412 stage: output,
413 events: block_events,
414 automation,
415 produced,
416 produced_since,
417 targets,
418 timeline: storage,
419 } = scratch;
420 processor.begin_render()?;
421 let expected = processor.input_channels();
422 if input.len() != expected || input.iter().any(|channel| channel.len() != frames) {
423 return Err(RenderError::Input(crate::InputError::AudioBuffers).into());
424 }
425 if !events_fit(events, frames) {
426 return Err(RenderError::Input(crate::InputError::Events).into());
427 }
428
429 processor.validate_events(events)?;
430 let latency = processor.latency()?;
431 let sample_rate = processor.sample_rate();
432 let block = processor.max_block_size();
433 crate::config::validate_processing(sample_rate, block).map_err(RenderError::Input)?;
434 options.validate()?;
435 let max_tail = seconds_to_samples(options.max_tail_seconds, sample_rate)?;
436 let body = frames
437 .checked_add(latency as usize)
438 .ok_or(RenderError::LengthOverflow)?;
439 let reported = matches!(options.tail, TailPolicy::Reported);
440 let reported_tail = |tail: Tail| match tail {
441 Tail::Samples(samples) => (samples as usize).min(max_tail),
442 Tail::Infinite => max_tail,
443 };
444 let tail = if reported {
445 reported_tail(processor.tail()?)
446 } else {
447 max_tail
448 };
449 let end = body.checked_add(tail).ok_or(RenderError::LengthOverflow)?;
450 std::alloc::Layout::array::<S>(end).map_err(|_| RenderError::LengthOverflow)?;
451 schedule
452 .validate(frames, end, sample_rate)
453 .map_err(RenderError::Input)?;
454 let mut timeline = timeline::Timeline::new(schedule, storage);
455 timeline
456 .validate_capacity(events)
457 .map_err(RenderError::Input)?;
458 targets.clear();
459 targets.extend(
460 schedule
461 .automation
462 .iter()
463 .copied()
464 .chain(schedule.ramps.iter().map(|ramp| crate::AutomationEvent {
465 slot: ramp.slot,
466 change: crate::ParameterChange {
467 id: ramp.id,
468 offset: ramp.start,
469 value: ramp.from,
470 },
471 })),
472 );
473 processor.validate_automation(targets)?;
474 let silence = match options.tail {
475 TailPolicy::UntilSilence {
476 threshold,
477 hold_seconds,
478 } => Some((threshold, seconds_to_samples(hold_seconds, sample_rate)?)),
479 TailPolicy::Reported => None,
480 };
481
482 let skip = skip.unwrap_or(latency as usize);
483 size(input_block, input.len(), block);
484 size(output_block, processor.output_channels(), block);
485 output.start(output_block.len(), silence);
486 let mut status = RenderStatus::Complete;
487 let mut silent = false;
489 let mut position = 0;
490 let mut pending = 0;
492 block_events.clear();
493 automation.clear();
494 produced.clear();
495 produced_since.clear();
496 automation.reserve(crate::MAX_BLOCK_EVENTS);
497
498 while position < end {
499 if cancelled() {
500 status = RenderStatus::Cancelled;
501 break;
502 }
503 let boundary = schedule.next_transport(position).unwrap_or(end).min(end);
504 let limit = position + block.min(boundary - position);
505 let block_end = timeline.fill_block(position, limit, events, pending, automation);
506 let count = block_end - position;
507 let start = position.min(frames);
508 let available = count.min(frames - start);
509 for (buffer, source) in input_block.iter_mut().zip(input) {
510 buffer[..available].copy_from_slice(&source[start..start + available]);
511 buffer[available..count].fill(S::default());
512 }
513 for buffer in output_block.iter_mut() {
514 buffer[..count].fill(S::default());
515 }
516 let inputs: Vec<&[S]> = input_block.iter().map(|b| &b[..count]).collect();
517 let mut outputs: Vec<&mut [S]> = output_block.iter_mut().map(|b| &mut b[..count]).collect();
518 let due = events.partition_point(|offset| offset < position + count);
519 block_events.clear();
520 for event in events.iter().skip(pending).take(due - pending) {
521 block_events
523 .push(event.at(event.offset - position))
524 .map_err(RenderError::Input)?;
525 }
526 pending = due;
527 let context = crate::BlockContext {
528 frames: count,
529 transport: schedule
530 .transport_at(position, sample_rate)
531 .map_err(RenderError::Input)?,
532 };
533 processor.process(
534 &context,
535 &inputs,
536 &mut outputs,
537 automation,
538 block_events,
539 produced,
540 )?;
541 for event in produced.iter() {
542 produced_since
543 .push(event.at(event.offset + position))
544 .map_err(RenderError::Input)?;
545 }
546 let now = processor.latency()?;
547 if now != latency {
548 return Err(RenderError::LatencyChanged {
549 before: latency,
550 after: now,
551 }
552 .into());
553 }
554 let silenced = output.accept(output_block, count, position, skip, body);
555 let first = skip.saturating_sub(position).min(count);
557 let last = silenced.unwrap_or(count);
558 if let Some(frame) = crate::sample::level(output_block, first..last).non_finite {
559 return Err(RenderError::NonFiniteOutput {
560 frame: position + frame - skip,
561 }
562 .into());
563 }
564 position += count;
565 output.deliver(produced_since, &mut consume);
566 if silenced.is_some() {
567 silent = true;
568 break;
569 }
570 }
571 output.deliver(produced_since, &mut consume);
572 if status == RenderStatus::Complete && silence.is_some() && !silent {
573 status = RenderStatus::TailLimit;
574 }
575 Ok(RenderProgress {
576 status,
577 processed_frames: position,
578 output_frames: output.emitted,
579 latency,
580 tail: output.emitted.saturating_sub(body.saturating_sub(skip)),
582 })
583}
584
585fn seconds_to_samples(seconds: f64, sample_rate: f64) -> Result<usize, RenderError> {
586 let samples = (seconds * sample_rate).round();
587 let upper_bound = (usize::MAX as u128 + 1) as f64;
589 if !samples.is_finite() || samples >= upper_bound {
590 return Err(RenderError::LengthOverflow);
591 }
592 Ok(samples as usize)
593}
594
595#[cfg(test)]
596mod tests;