plughost 0.2.2

Load and run VST3, Audio Unit, and CLAP plugins from Rust, isolated in helper processes
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
597
598
599
600
601
602
603
604
605
606
//! The endpoint's callback. Each call submits the callback's quantum and plays the output of the
//! quantum submitted `latency` callbacks before, or the fallback when it is missing. The call
//! allocates nothing, takes no lock and waits for nothing: it copies into and out of the ring,
//! rings the doorbell, updates atomic counters, and keeps track of the notes it delivered.

use std::io;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;

use plughost_core::internal::level;
use plughost_core::ipc::shared::clock;
use plughost_core::ipc::shared::realtime::{MAX_LANES, Outcome, Ring};
use plughost_core::{
    AutomationEvent, BlockContext, Events, FailureKind, InputError, RoutedChainConfig, Sample,
    SampleFormat,
};

use super::dry::DryDelay;
use super::notes::Notes;
use super::{Fallback, RealtimeConfig, State};
use crate::Error;

/// What a callback played.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RealtimeOutput {
    /// The chain's output for the quantum submitted `latency` callbacks before.
    Processed,
    /// The fallback.
    Fallback(FallbackReason),
}

/// Why a callback played the fallback.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FallbackReason {
    /// The endpoint is not running.
    Stopped,
    /// The endpoint started less than `latency` callbacks ago, so no output is due yet. The first
    /// output plays as is, without a crossfade from this fallback.
    Priming,
    /// The helper had not completed the output in time. Its events go out, at offset 0, with
    /// the first callback after the helper completed it.
    Missed,
    /// The endpoint waits for [`crate::Chain::resync_realtime`], to be stopped, the chain reset
    /// and the endpoint started again, or to be recovered; or a resync or recovery is under way.
    /// The first output of the new generation plays as is, as after a start.
    Resync,
}

/// The audio callback's side of a chain's realtime endpoint, from [`crate::Chain::realtime_endpoint`].
/// Move it to the callback's thread and call `process_audio_f32` or `process_audio_f64` there,
/// in the chain's prepared precision, once per callback. Drop it on a control thread: dropping
/// releases shared memory. [`crate::Chain::recover_realtime`] moves the endpoint to the chain it
/// recovers in a new helper, while the callback keeps this value.
///
/// Call it once per quantum's worth of time, as an audio device calls back: the helper works on
/// a quantum until the call `latency` quanta later, so quanta processed in a burst find the
/// previous ones unfinished and play the fallback ([`FallbackReason::Missed`]). Ask the device
/// for callbacks of one quantum; an application that cuts each device callback into several
/// quanta needs a latency of as many quanta as a callback holds.
pub struct RealtimeEndpoint {
    /// Boxed so that recovery can hand the callback another chain's ring without allocating.
    ring: Box<Ring>,
    state: Arc<State>,
    quantum: usize,
    latency: u64,
    fallback: Fallback,
    format: SampleFormat,
    sample_rate: f64,
    input_channels: usize,
    output_channels: usize,
    event_inputs: usize,
    event_outputs: usize,
    slots: usize,
    generation: u64,
    sequence: u64,
    /// The previous callback played the chain's output.
    wet: bool,
    /// The previous callback played the fallback for a missed output, which the next output
    /// crossfades from. The first output after a start plays as is.
    crossfade: bool,
    /// Each output channel's last played sample, which a fallback ramps from.
    last: Vec<f64>,
    /// Ticks from submission to completion of the output the last callback played.
    completion: Option<u64>,
    dry: Option<Box<DryDelay>>,
    /// The chain latency of the generation's first output. A replacement that changes it waits
    /// for a new generation rather than go on in this one's timeline.
    planned: Option<u32>,
    notes: Notes,
    /// The notes earlier outputs started wait for the new generation's first callback that
    /// returns `Ok` to end them.
    ending: bool,
    /// The quanta of this generation the callback played the fallback for, oldest first, whose
    /// events it delivers once the helper has completed them.
    missed: [u64; MAX_LANES],
    missed_len: usize,
    /// The events of those quanta that this call delivers, at the start of its output.
    late: Events,
    /// Room to read one quantum's events, and to set aside this call's output's.
    scratch: Events,
}

impl std::fmt::Debug for RealtimeEndpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RealtimeEndpoint")
            .field("quantum", &self.quantum)
            .field("latency", &self.latency)
            .field("fallback", &self.fallback)
            .field("generation", &self.generation)
            .field("sequence", &self.sequence)
            .finish_non_exhaustive()
    }
}

/// The samples the ring carries.
trait Wire: Sample {
    fn from_f64(value: f64) -> Self;
    fn submit(
        ring: &mut Ring,
        generation: u64,
        sequence: u64,
        context: &BlockContext,
        input: &[&[Self]],
        automation: &[AutomationEvent],
        events: &Events,
    ) -> io::Result<()>;
    fn read(
        ring: &mut Ring,
        generation: u64,
        sequence: u64,
        output: &mut [&mut [Self]],
        event_ports: usize,
        produced: &mut Events,
    ) -> io::Result<Option<(Outcome, usize)>>;
}

macro_rules! wire {
    ($sample:ty, $submit:ident, $read:ident) => {
        impl Wire for $sample {
            fn from_f64(value: f64) -> Self {
                value as $sample
            }
            fn submit(
                ring: &mut Ring,
                generation: u64,
                sequence: u64,
                context: &BlockContext,
                input: &[&[Self]],
                automation: &[AutomationEvent],
                events: &Events,
            ) -> io::Result<()> {
                ring.$submit(generation, sequence, context, input, automation, events)
            }
            fn read(
                ring: &mut Ring,
                generation: u64,
                sequence: u64,
                output: &mut [&mut [Self]],
                event_ports: usize,
                produced: &mut Events,
            ) -> io::Result<Option<(Outcome, usize)>> {
                ring.$read(generation, sequence, output, event_ports, produced)
            }
        }
    };
}
wire!(f32, submit_f32, read_f32);
wire!(f64, submit_f64, read_f64);

impl RealtimeEndpoint {
    pub(crate) fn new(
        ring: Ring,
        state: Arc<State>,
        config: &RealtimeConfig,
        chain: &RoutedChainConfig,
        dry: Option<Box<DryDelay>>,
    ) -> RealtimeEndpoint {
        let output_channels = chain.output_channels();
        RealtimeEndpoint {
            ring: Box::new(ring),
            state,
            quantum: config.quantum,
            latency: config.latency as u64,
            fallback: config.fallback,
            format: chain.sample_format,
            sample_rate: chain.sample_rate,
            input_channels: chain.input_channels(),
            output_channels,
            event_inputs: chain.event_inputs,
            event_outputs: chain.event_outputs(),
            slots: chain.slots.len(),
            generation: 0,
            sequence: 0,
            wet: false,
            crossfade: false,
            last: vec![0.0; output_channels],
            completion: None,
            dry,
            planned: None,
            notes: Notes::new(),
            ending: false,
            missed: [0; MAX_LANES],
            missed_len: 0,
            late: Events::for_block(),
            scratch: Events::for_block(),
        }
    }

    /// The ring, for a test to play the helper's part in it.
    #[cfg(test)]
    pub(super) fn ring(&mut self) -> &mut Ring {
        &mut self.ring
    }

    /// Validates the callback's events and automation as a chain block, without allocating.
    fn validate(
        &self,
        context: &BlockContext,
        automation: &[AutomationEvent],
        events: &Events,
    ) -> Result<(), InputError> {
        context.validate()?;
        if let Some(transport) = context.transport {
            transport.validate_at_rate(self.sample_rate)?;
        }
        plughost_core::internal::validate_event_budget(automation.len(), events)?;
        if let Some(event) = events.iter().find(|event| event.port >= self.event_inputs) {
            return Err(InputError::EventPort { port: event.port });
        }
        if !plughost_core::internal::events_fit(events, context.frames) {
            return Err(InputError::Events);
        }
        if automation.iter().any(|event| {
            event.slot >= self.slots
                || !plughost_core::internal::changes_fit(&[event.change], context.frames)
        }) || automation
            .windows(2)
            .any(|pair| pair[0].change.offset > pair[1].change.offset)
        {
            return Err(InputError::Automation);
        }
        Ok(())
    }

    fn process<S: Wire>(
        &mut self,
        context: &BlockContext,
        input: &[&[S]],
        output: &mut [&mut [S]],
        automation: &[AutomationEvent],
        events: &Events,
        produced: &mut Events,
    ) -> Result<RealtimeOutput, Error> {
        let _audit = plughost_core::audit::processing();
        let state = Arc::clone(&self.state);
        let _call = state.enter();
        let played = self.serve(context, input, output, automation, events, produced);
        // The new generation's plugins will not end the notes earlier outputs started. A
        // generation's first `latency` callbacks play no output, and a callback that fails sets
        // `resync` until the next generation, so no output of this one has added notes yet.
        if played.is_ok() && std::mem::take(&mut self.ending) {
            let dropped = self.notes.end_all(produced);
            self.state
                .dropped_events
                .fetch_add(dropped, Ordering::Relaxed);
        }
        if !self.late.is_empty() {
            self.deliver_late(produced);
        }
        played
    }

    /// Reads the events of the missed quanta the helper has completed since. A missed quantum's
    /// lane is reused only once it completed, as an overflow otherwise starts a resync, so each
    /// is read before its lane is.
    fn take_late(&mut self, generation: u64) {
        let mut kept = 0;
        let mut dropped = 0;
        for index in 0..self.missed_len {
            let sequence = self.missed[index];
            match self
                .ring
                .read_events(generation, sequence, self.event_outputs, &mut self.scratch)
            {
                Ok(None) => {
                    self.missed[kept] = sequence;
                    kept += 1;
                }
                Ok(Some(skipped)) => {
                    dropped += skipped as u64;
                    for event in self.scratch.iter() {
                        if !self.late.push_within_capacity(event.at(0)) {
                            dropped += 1;
                        }
                    }
                }
                // A lane the helper rewrote out of turn; its events are lost.
                Err(_) => {}
            }
        }
        self.missed_len = kept;
        self.notes.record(&self.late);
        self.state
            .dropped_events
            .fetch_add(dropped, Ordering::Relaxed);
    }

    /// Puts the late events at offset 0 before the output's own, within the room `produced` has
    /// reserved.
    fn deliver_late(&mut self, produced: &mut Events) {
        self.scratch.clear();
        let mut dropped = 0;
        for event in produced.iter() {
            if !self.scratch.push_within_capacity(event) {
                dropped += 1;
            }
        }
        produced.clear();
        for event in self.late.iter().chain(self.scratch.iter()) {
            if !produced.push_within_capacity(event) {
                dropped += 1;
            }
        }
        self.late.clear();
        self.state
            .dropped_events
            .fetch_add(dropped, Ordering::Relaxed);
    }

    fn serve<S: Wire>(
        &mut self,
        context: &BlockContext,
        input: &[&[S]],
        output: &mut [&mut [S]],
        automation: &[AutomationEvent],
        events: &Events,
        produced: &mut Events,
    ) -> Result<RealtimeOutput, Error> {
        produced.clear();
        if S::FORMAT != self.format {
            return Err(Error::Input {
                slot: None,
                error: InputError::AudioSampleFormat,
            });
        }
        let frames = context.frames;
        if output.len() != self.output_channels
            || output.iter().any(|channel| channel.len() != frames)
        {
            return Err(Error::Input {
                slot: None,
                error: InputError::AudioBuffers,
            });
        }
        State::count(&self.state.callbacks);
        // A new generation's dry delay line holds this callback's input already.
        let generation = self.state.generation.load(Ordering::Acquire);
        if generation != self.generation {
            self.begin(generation);
        }
        let input_fits = input.len() == self.input_channels
            && input.iter().all(|channel| channel.len() == frames);
        if let Some(dry) = &mut self.dry {
            dry.push(input_fits.then_some(input), frames);
        }
        if self.state.closed.load(Ordering::Acquire) {
            return Ok(self.fallback(output, FallbackReason::Stopped));
        }
        if !self.state.running.load(Ordering::Acquire) {
            return Ok(self.fallback(output, FallbackReason::Stopped));
        }
        if self.state.resync.load(Ordering::Relaxed) || self.state.halted(self.generation) {
            return Ok(self.fallback(output, FallbackReason::Resync));
        }
        if frames != self.quantum {
            State::count(&self.state.size_mismatches);
            self.state.resync.store(true, Ordering::Relaxed);
            return Ok(self.fallback(output, FallbackReason::Resync));
        }
        let invalid = if input_fits {
            self.validate(context, automation, events)
                .map_err(|error| Error::Input { slot: None, error })
        } else {
            Err(Error::Input {
                slot: None,
                error: InputError::AudioBuffers,
            })
        };
        if let Err(error) = invalid {
            // A quantum that is not submitted breaks the pipeline like an overflow.
            self.state.resync.store(true, Ordering::Relaxed);
            self.fallback(output, FallbackReason::Resync);
            return Err(error);
        }
        let sequence = self.sequence + 1;
        if !self.ring.lane_free(sequence) {
            State::count(&self.state.overflows);
            self.state.resync.store(true, Ordering::Relaxed);
            return Ok(self.fallback(output, FallbackReason::Resync));
        }
        // Before this quantum's submission reuses a missed quantum's lane. Every return from
        // here on is `Ok`, which delivers them.
        if self.missed_len > 0 {
            self.take_late(generation);
        }
        let submitted = S::submit(
            &mut self.ring,
            generation,
            sequence,
            context,
            input,
            automation,
            events,
        );
        if submitted.is_err() {
            self.state.fail(None, FailureKind::Protocol);
            return Ok(self.fallback(output, FallbackReason::Resync));
        }
        self.sequence = sequence;
        if sequence <= self.latency {
            return Ok(self.fallback(output, FallbackReason::Priming));
        }
        let read = S::read(
            &mut self.ring,
            generation,
            sequence - self.latency,
            output,
            self.event_outputs,
            produced,
        );
        match read {
            Ok(Some((
                Outcome::Done {
                    latency, elapsed, ..
                },
                dropped,
            ))) => {
                if *self.planned.get_or_insert(latency) != latency {
                    produced.clear();
                    self.state.resync.store(true, Ordering::Relaxed);
                    return Ok(self.fallback(output, FallbackReason::Resync));
                }
                State::count(&self.state.processed);
                self.notes.record(produced);
                self.completion = Some(elapsed);
                self.state
                    .dropped_events
                    .fetch_add(dropped as u64, Ordering::Relaxed);
                self.state.latency.store(latency, Ordering::Relaxed);
                self.play(output);
                if level(output, 0..frames).non_finite.is_some() {
                    State::count(&self.state.non_finite_outputs);
                }
                Ok(RealtimeOutput::Processed)
            }
            Ok(Some((Outcome::Failed { slot, kind }, _))) => {
                produced.clear();
                // A slot the chain does not have is the helper's fault, not the slot's.
                match slot {
                    Some(slot) if slot >= self.slots => {
                        self.state.fail(None, FailureKind::Protocol);
                    }
                    _ => self.state.fail(slot, kind),
                }
                Ok(self.fallback(output, FallbackReason::Resync))
            }
            Ok(None) => {
                produced.clear();
                State::count(&self.state.missed);
                if let Some(missed) = self.missed.get_mut(self.missed_len) {
                    *missed = sequence - self.latency;
                    self.missed_len += 1;
                }
                Ok(self.fallback(output, FallbackReason::Missed))
            }
            Err(_) => {
                produced.clear();
                self.state.fail(None, FailureKind::Protocol);
                Ok(self.fallback(output, FallbackReason::Resync))
            }
        }
    }

    /// How long the helper took to complete the output the last callback played, from its
    /// submission; `None` when the callback played the fallback. Call it outside the callback, or
    /// keep the value for later: the conversion reads the system's timebase.
    pub fn last_completion(&self) -> Option<Duration> {
        self.completion.map(clock::duration)
    }

    /// Follows a new generation, whose quanta start again from 1, in the ring of the chain that
    /// recovered the endpoint when recovery started it.
    fn begin(&mut self, generation: u64) {
        self.generation = generation;
        self.sequence = 0;
        self.planned = None;
        self.ending = true;
        self.missed_len = 0;
        self.state.ring.receive(&mut self.ring);
        if let Some(dry) = &mut self.dry {
            self.state.dry.receive(dry);
            dry.set_delay(self.state.dry_delay.load(Ordering::Relaxed) as usize);
        }
    }

    /// The fallback's sample at `frame` of a callback `frames` long.
    fn fallback_sample(&self, channel: usize, frame: usize, frames: usize) -> f64 {
        match (&self.dry, self.fallback) {
            (Some(dry), Fallback::Dry) => dry.delayed(channel, frame, frames),
            _ => 0.0,
        }
    }

    /// Plays the fallback, ramping over the callback from the last sample played, or 0 when it
    /// was not finite, when the previous callback played the chain's output.
    fn fallback<S: Wire>(
        &mut self,
        output: &mut [&mut [S]],
        reason: FallbackReason,
    ) -> RealtimeOutput {
        for (index, channel) in output.iter_mut().enumerate() {
            let frames = channel.len();
            let start = self.fallback_sample(index, 0, frames);
            let held = if self.last[index].is_finite() {
                self.last[index]
            } else {
                0.0
            };
            for (frame, sample) in channel.iter_mut().enumerate() {
                let mut value = self.fallback_sample(index, frame, frames);
                if self.wet {
                    let remaining = 1.0 - (frame + 1) as f64 / frames as f64;
                    value += (held - start) * remaining;
                }
                *sample = S::from_f64(value);
            }
            if let Some(&last) = channel.last() {
                self.last[index] = last.to_f64();
            }
        }
        self.wet = false;
        self.crossfade = reason == FallbackReason::Missed;
        self.completion = None;
        RealtimeOutput::Fallback(reason)
    }

    /// Plays the chain's output, which the ring wrote into `output`, crossfading from the
    /// fallback when the previous callback played it for a missed output.
    fn play<S: Wire>(&mut self, output: &mut [&mut [S]]) {
        for (index, channel) in output.iter_mut().enumerate() {
            let frames = channel.len();
            if self.crossfade {
                for frame in 0..frames {
                    let gain = (frame + 1) as f64 / frames as f64;
                    let fallback = self.fallback_sample(index, frame, frames);
                    channel[frame] =
                        S::from_f64(fallback * (1.0 - gain) + channel[frame].to_f64() * gain);
                }
            }
            if let Some(&last) = channel.last() {
                self.last[index] = last.to_f64();
            }
        }
        self.wet = true;
        self.crossfade = false;
    }
}

macro_rules! endpoint_process {
    ($sample:ty, $method:ident) => {
        impl RealtimeEndpoint {
            /// Serves one audio callback in the chain's prepared precision: submits `input`,
            /// `automation` and `events`, which address the chain as in
            /// [`crate::Chain::process_audio_f32`], and plays into `output` the chain's output
            /// for the quantum submitted `latency` callbacks before, or the fallback. Each slice
            /// is the callback's frames long, which must be the quantum. `produced` is replaced
            /// with that output's events, system exclusive ones included, up to the room it has
            /// reserved: pass [`crate::Events::for_block`] to receive them all without
            /// allocating. The events of outputs the callback missed come first, at offset 0,
            /// once the helper has completed them. The first callback that returns `Ok` after a
            /// start, a resync or a recovery puts there instead a note off at offset 0 for each
            /// note earlier outputs started and did not end, in the form it started in: a MIDI
            /// note off, or a note off with the note's ID.
            ///
            /// Invalid input is an error and starts a resync, like a callback of another size;
            /// the fallback then plays. Wrong output buffers or precision are an error and leave
            /// `output` unchanged.
            pub fn $method(
                &mut self,
                context: &BlockContext,
                input: &[&[$sample]],
                output: &mut [&mut [$sample]],
                automation: &[AutomationEvent],
                events: &Events,
                produced: &mut Events,
            ) -> Result<RealtimeOutput, Error> {
                self.process(context, input, output, automation, events, produced)
            }
        }
    };
}
endpoint_process!(f32, process_audio_f32);
endpoint_process!(f64, process_audio_f64);