Skip to main content

plughost_core/
changes.rs

1use crate::render::Tail;
2/// Maximum retained timing changes before consumers must resynchronize.
3pub const CHANGE_CAPACITY: usize = 128;
4
5/// A plugin's timing as its owning thread last read it. The latency is the one the plugin was
6/// activated with: it changes only when the plugin is prepared again or reset, so processing and
7/// rendering keep one alignment in between. The tail follows the plugin's reports.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9#[non_exhaustive]
10pub struct PluginTiming {
11    /// Applied processing latency in frames.
12    pub latency: u32,
13    /// Most recently observed native tail duration.
14    pub tail: Tail,
15    /// The plugin asked to be prepared again; processing is refused until it is.
16    pub restart_required: bool,
17    /// The plugin reported a new latency, which takes effect when it is prepared again or reset.
18    /// The chain keeps aligning to `latency` until then, and a render does not start.
19    pub latency_changed: bool,
20}
21
22impl PluginTiming {
23    /// The timing of a plugin with no restart or latency change pending.
24    #[must_use]
25    pub fn new(latency: u32, tail: Tail) -> PluginTiming {
26        PluginTiming {
27            latency,
28            tail,
29            restart_required: false,
30            latency_changed: false,
31        }
32    }
33}
34
35/// Latest timing observation for one plugin in a chain.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct SlotChange {
39    /// Zero-based plugin slot.
40    pub slot: usize,
41    /// Last observed timing and pending restart flags.
42    pub timing: PluginTiming,
43}
44
45/// Timing notifications coalesce by slot, retaining last-observed order. Intermediate values
46/// are not an audit trail. On overflow use `snapshot` to replace the entire consumer view.
47#[derive(Clone, Debug, Default, PartialEq, Eq)]
48#[non_exhaustive]
49#[must_use]
50pub struct ChangeBatch {
51    /// Coalesced slot changes in last-observed order.
52    pub changes: Vec<SlotChange>,
53    /// Whether overflow requires replacing the consumer view with `snapshot`.
54    pub resync_required: bool,
55    /// Last known timing per slot; `None` for a slot never observed.
56    pub snapshot: Vec<Option<PluginTiming>>,
57}
58
59/// No callbacks or I/O under the producer. The owning helper serializes access to this buffer.
60pub struct ChangeBuffer {
61    pending: Vec<SlotChange>,
62    snapshot: Vec<Option<PluginTiming>>,
63    overflow: bool,
64}
65
66impl Default for ChangeBuffer {
67    fn default() -> Self {
68        Self {
69            pending: Vec::with_capacity(CHANGE_CAPACITY),
70            snapshot: Vec::new(),
71            overflow: false,
72        }
73    }
74}
75
76impl ChangeBuffer {
77    /// Records a changed timing value, coalescing that slot and tracking overflow.
78    pub fn observe(&mut self, slot: usize, timing: PluginTiming) {
79        if self.snapshot.len() <= slot {
80            self.snapshot.resize(slot + 1, None);
81        }
82        if self.snapshot[slot] == Some(timing) {
83            return;
84        }
85        self.snapshot[slot] = Some(timing);
86        self.pending.retain(|event| event.slot != slot);
87        if self.pending.len() == CHANGE_CAPACITY {
88            self.pending.remove(0);
89            self.overflow = true;
90        }
91        self.pending.push(SlotChange { slot, timing });
92    }
93
94    /// Forgets every slot: the pending changes, the overflow and the snapshot.
95    pub fn clear(&mut self) {
96        self.pending.clear();
97        self.snapshot.clear();
98        self.overflow = false;
99    }
100
101    /// Drains pending changes and overflow, retaining and returning the latest complete snapshot.
102    pub fn take(&mut self) -> ChangeBatch {
103        // Preserve the producer's reserved storage while returning an owned batch.
104        let changes = self.pending.clone();
105        self.pending.clear();
106        ChangeBatch {
107            changes,
108            resync_required: std::mem::take(&mut self.overflow),
109            snapshot: self.snapshot.clone(),
110        }
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn change_notifications_coalesce_and_resynchronize_without_a_consumer() {
120        let mut events = ChangeBuffer::default();
121        let timing = |latency| PluginTiming {
122            latency,
123            tail: Tail::Samples(latency),
124            restart_required: false,
125            latency_changed: false,
126        };
127        for slot in 0..CHANGE_CAPACITY + 10 {
128            events.observe(slot, timing(slot as u32));
129        }
130        events.observe(0, timing(999));
131        let batch = events.take();
132        assert!(batch.resync_required);
133        assert_eq!(batch.changes.len(), CHANGE_CAPACITY);
134        assert_eq!(batch.changes.last().unwrap().slot, 0);
135        assert_eq!(batch.snapshot[0], Some(timing(999)));
136        assert_eq!(batch.snapshot.len(), CHANGE_CAPACITY + 10);
137        let empty = events.take();
138        assert!(!empty.resync_required);
139        assert!(empty.changes.is_empty());
140        assert_eq!(empty.snapshot, batch.snapshot);
141    }
142}