plughost-core 0.2.2

Shared types and offline render rules for plughost
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Offline render rules shared by every processing path: the output is aligned with the input by
//! removing the reported latency, and the tail after the input is rendered as well.

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;

/// The tail length a processor reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Tail {
    /// Finite tail duration in frames.
    Samples(u32),
    /// Unbounded tail, still limited by `RenderOptions::max_tail_seconds`.
    Infinite,
}

/// Rule for determining how much post-input audio to deliver.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum TailPolicy {
    /// Render the tail length the processor reports when the render starts. An infinite tail
    /// renders up to the maximum. A tail the processor reports later does not change the plan.
    Reported,
    /// Render until the output has stayed at or below `threshold` (linear peak) for
    /// `hold_seconds`, then cut after the last sample above it. Both values must be finite and
    /// non-negative; zero is allowed, and a linear peak threshold may exceed one. Plugins often report a wrong
    /// tail, so this is the default. Only audio output counts: output events do not, and a
    /// processor without audio outputs is silent from the end of the input, so use
    /// [`TailPolicy::Reported`] for one that produces only events.
    UntilSilence {
        /// Maximum absolute sample amplitude considered silent.
        threshold: f64,
        /// Continuous silence required before stopping, in seconds.
        hold_seconds: f64,
    },
}

/// Offline tail policy and duration limit.
///
/// The default detects one second of silence below a linear peak of `1.585e-5`
/// (approximately −96 dBFS), with at most 30 seconds of tail.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct RenderOptions {
    /// How to determine the delivered tail length.
    pub tail: TailPolicy,
    /// Upper bound on the rendered tail, whatever the policy. Must be finite and non-negative.
    pub max_tail_seconds: f64,
}

impl Default for RenderOptions {
    fn default() -> RenderOptions {
        RenderOptions {
            tail: TailPolicy::UntilSilence {
                // -96 dBFS
                threshold: 1.585e-5,
                hold_seconds: 1.0,
            },
            max_tail_seconds: 30.0,
        }
    }
}

impl RenderOptions {
    /// Constructs explicit tail options, validated when rendering starts.
    #[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(())
    }
}

/// A prepared processor the render rules can drive.
pub trait Process<S: Sample> {
    /// Processor error that can also represent the render scheduler’s input and timing errors.
    type Error: From<RenderError>;

    /// Prepared sample rate in samples per second.
    fn sample_rate(&self) -> f64;
    /// Prepared maximum frames per processing call.
    fn max_block_size(&self) -> usize;
    /// Number of input channels required in planar buffer order.
    fn input_channels(&self) -> usize;
    /// Number of output channels produced in planar buffer order.
    fn output_channels(&self) -> usize;
    /// The latency the processor's output has. It must not change while a render runs, so that
    /// one alignment holds; plughost's processors keep the latency they were prepared or last
    /// reset with.
    fn latency(&self) -> Result<u32, Self::Error>;
    /// Current native tail duration at render start.
    fn tail(&self) -> Result<Tail, Self::Error>;
    /// Called once as a render starts, before validating input or reading the latency and tail.
    /// Refuse here if the processor is not prepared. A processor whose
    /// latency changed without the change being applied yet refuses here with
    /// [`RenderError::LatencyNotApplied`], since the whole render would keep the old alignment.
    fn begin_render(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
    /// Validate all scheduled targets before the render advances DSP state. Implementors with
    /// automation must check slot/parameter identity, write access and automatable metadata.
    fn validate_automation(
        &mut self,
        automation: &[crate::AutomationEvent],
    ) -> Result<(), Self::Error> {
        if automation.is_empty() {
            Ok(())
        } else {
            Err(RenderError::Input(crate::InputError::Automation).into())
        }
    }
    /// Validate the event destinations for the entire render before DSP state advances.
    /// Processors with configured input ports must override this to reject unavailable ports.
    /// Offsets, ordering and event values are already checked by the renderer. The default
    /// imposes no port restrictions, preserving processors that do not expose port metadata.
    fn validate_events(&mut self, _events: &Events) -> Result<(), Self::Error> {
        Ok(())
    }
    /// Processes one block. Every input and output slice has the same length, at most
    /// `max_block_size`; automation and MIDI are in offset order, inside the block. Points hold
    /// their values from their offsets, including equal-offset input order. Native adapters own
    /// any subdivision needed to avoid implicit interpolation between point edits. `produced`
    /// holds one block's events ([`Events::for_block`]) and is replaced with the block's output
    /// events in offset order, with block offsets.
    fn process(
        &mut self,
        context: &crate::BlockContext,
        input: &[&[S]],
        output: &mut [&mut [S]],
        automation: &[crate::AutomationEvent],
        events: &Events,
        produced: &mut Events,
    ) -> Result<(), Self::Error>;
}

/// What a stream delivers at once: aligned output audio, and the output events processed since
/// the previous delivery. Event offsets count from the start of the input, in the processing
/// timeline; they are not shifted by the latency removed from the audio.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Delivery<'a, S> {
    /// One slice per output channel, all of one length, which may be zero.
    pub audio: &'a [&'a [S]],
    /// Output events with offsets on the processing timeline, without audio latency alignment.
    pub events: &'a Events,
}

/// Owned output of a completed render, with audio aligned by removing native latency.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Rendered<S> {
    /// Output channels aligned with the input: `frames + tail` samples each.
    pub channels: Vec<Vec<S>>,
    /// Output events in offset order, counted from the start of the input without latency
    /// alignment, including events processed during the tail.
    pub events: Events,
    /// The latency that was removed, in samples.
    pub latency: u32,
    /// Samples rendered after the end of the input.
    pub tail: usize,
    /// Why the render ended: [`RenderStatus::Complete`], or [`RenderStatus::TailLimit`] when a
    /// [`TailPolicy::UntilSilence`] tail reached the maximum before the output fell silent.
    pub status: RenderStatus,
}

/// Renders `frames` samples of `input` (one slice per input channel, none for an instrument)
/// through the processor, with `events` placed by offset from the start of the input, in offset
/// order and before `frames`.
///
/// [`Process::begin_render`] runs first. The latency is read before rendering and after every
/// block; a change is an error because the alignment would no longer hold. [`TailPolicy::Reported`] plans the tail length from the tail
/// reported when the render starts; [`TailPolicy::UntilSilence`] ignores the reported tail.
/// Options, processor timing, sample conversion and buffer lengths are validated before calling
/// `process`. Durations round to the nearest sample. Invalid or unrepresentable values are errors,
/// not clamped limits. Representable lengths do not guarantee enough memory is available. A NaN
/// or infinite output sample fails the render ([`RenderError::NonFiniteOutput`]).
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(),
    )
}

/// Renders a caller-defined timeline in bounded blocks, splitting at transport changes and the
/// combined event budget. Ramps expand into exact sample points within each block. Native
/// adapters preserve point semantics, subdividing internally when required by their format.
/// Seeks change the transport only; call reset explicitly to discard DSP history.
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,
    })
}

/// Borrowed planar audio, events, and automation for a render or session segment.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct RenderInput<'a, S> {
    /// Planar input channels, each containing exactly `frames` samples.
    pub audio: &'a [&'a [S]],
    /// Input duration in frames; explicit even when the processor has no input channels.
    pub frames: usize,
    /// Input events in nondecreasing offset order, strictly before `frames`.
    pub events: &'a Events,
    /// Transport and automation offsets relative to this input segment.
    pub schedule: RenderSchedule<'a>,
}

impl<'a, S> RenderInput<'a, S> {
    /// `frames` of `audio` with `events`, without a schedule; see [`Self::with_schedule`].
    #[must_use]
    pub fn new(audio: &'a [&'a [S]], frames: usize, events: &'a Events) -> RenderInput<'a, S> {
        RenderInput {
            audio,
            frames,
            events,
            schedule: RenderSchedule::default(),
        }
    }

    /// Adds transport changes and automation.
    #[must_use]
    pub fn with_schedule(mut self, schedule: RenderSchedule<'a>) -> RenderInput<'a, S> {
        self.schedule = schedule;
        self
    }
}

/// Whether rendering completed, stopped at a caller cancellation boundary, or ended a tail at its
/// maximum.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RenderStatus {
    /// All planned audio and tail have been processed.
    Complete,
    /// The caller cancelled before the next processing block.
    Cancelled,
    /// All planned audio has been processed, but a [`TailPolicy::UntilSilence`] tail reached
    /// [`RenderOptions::max_tail_seconds`] before the output stayed silent for the hold: also
    /// when the maximum is shorter than the hold, however quiet the output was.
    TailLimit,
}

/// Output-only report of work completed and audio delivered by a streaming render.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RenderProgress {
    /// Completion, cancellation, or a tail ended at its maximum.
    pub status: RenderStatus,
    /// Native frames processed, including latency and tail. Cancellation never interrupts a call.
    pub processed_frames: usize,
    /// Aligned audio frames delivered to the consumer.
    pub output_frames: usize,
    /// Native latency removed from audio, in frames.
    pub latency: u32,
    /// Delivered frames after the input, excluding trimmed silence.
    pub tail: usize,
}

/// Delivers aligned output without retaining the whole result. Memory is bounded by the prepared
/// block size plus the configured silence hold. Cancellation is checked before each submitted block;
/// delivered samples remain valid. DSP state has advanced by `processed_frames`. Reset before a
/// new independent render. This function does not reset the caller's processor implicitly.
///
/// The prepared `max_block_size` is also the submission limit. Larger offline blocks can reduce
/// helper round trips, but increase scratch storage and the amount of processing before the next
/// cancellation check. Transport changes and the event budget may shorten a block. No subsequent
/// block is submitted ahead of that check. Silence detection trims delivered output sample by
/// sample; DSP may already have advanced through the rest of the submitted block.
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,
    )
}

/// Buffers a render reuses from block to block, and a session from segment to segment.
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(),
        }
    }
}

/// Sizes `buffers` to `channels` channels of `frames` samples, keeping their storage. The
/// render loop overwrites every frame it passes on, so earlier contents are not cleared.
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());
    }
}

/// [`render_stream`] in `scratch`, dropping the first `skip` processed frames of output, or the
/// latency when `None`.
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;
    // Whether the silence hold ended the tail.
    let mut silent = false;
    let mut position = 0;
    // The first input event not yet submitted.
    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) {
            // The timeline fitted the block's events to one block's budget.
            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);
        // Frames before `skip` are latency, and those after the silence hold are never output.
        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,
        // The input ends `body - skip` frames into the delivered output.
        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();
    // The exclusive upper bound is exactly representable as f64, unlike usize::MAX on 64-bit.
    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;