Skip to main content

plughost_core/
transport.rs

1//! Caller-owned timeline positions. Processing elapsed time belongs to the native processor.
2
3use crate::InputError;
4
5/// Musical meter; numerator must be nonzero and denominator a power of two.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7#[non_exhaustive]
8pub struct TimeSignature {
9    /// Number of denominator note units in a bar.
10    pub numerator: u16,
11    /// Note unit, such as 4 for quarter notes or 8 for eighth notes.
12    pub denominator: u16,
13}
14
15impl TimeSignature {
16    /// `numerator` beats of `denominator` note values per bar.
17    #[must_use]
18    pub const fn new(numerator: u16, denominator: u16) -> TimeSignature {
19        TimeSignature {
20            numerator,
21            denominator,
22        }
23    }
24}
25
26/// Musical positions are quarter notes, including for compound meters.
27#[derive(Clone, Copy, Debug, PartialEq)]
28#[non_exhaustive]
29pub struct LoopRegion {
30    /// Start position in quarter notes.
31    pub start: f64,
32    /// Exclusive loop end in quarter notes; greater than `start`.
33    pub end: f64,
34    /// Loop start on the caller’s absolute sample timeline.
35    pub sample_start: i64,
36    /// Exclusive loop end in samples; greater than `sample_start`.
37    pub sample_end: i64,
38}
39
40impl LoopRegion {
41    /// A loop from `start` to `end` in quarter notes, which are samples `sample_start` to
42    /// `sample_end`.
43    #[must_use]
44    pub const fn new(start: f64, end: f64, sample_start: i64, sample_end: i64) -> LoopRegion {
45        LoopRegion {
46            start,
47            end,
48            sample_start,
49            sample_end,
50        }
51    }
52}
53
54/// Caller-supplied start and numbering of the current musical bar.
55#[derive(Clone, Copy, Debug, PartialEq)]
56#[non_exhaustive]
57pub struct BarPosition {
58    /// Start position in quarter notes.
59    pub start: f64,
60    /// Caller-supplied bar number; advancement increments it at bar boundaries.
61    pub number: i32,
62}
63
64impl BarPosition {
65    /// Bar `number`, which starts at `start` quarter notes.
66    #[must_use]
67    pub const fn new(start: f64, number: i32) -> BarPosition {
68        BarPosition { start, number }
69    }
70}
71
72/// A snapshot at the first sample of a block. `None` fields are unavailable, never synthesized.
73/// A seek is a discontinuity between consecutive snapshots. Loop wrapping is caller-owned.
74#[derive(Clone, Copy, Debug, PartialEq)]
75#[non_exhaustive]
76pub struct Transport {
77    /// Signed absolute sample position of the block’s first frame.
78    pub sample_position: i64,
79    /// Absolute musical position in quarter notes, when available.
80    pub beat_position: Option<f64>,
81    /// Current bar start and number; requires an available beat position.
82    pub bar_position: Option<BarPosition>,
83    /// Finite, positive quarter notes per minute, when available.
84    pub tempo: Option<f64>,
85    /// Current musical meter, when available.
86    pub time_signature: Option<TimeSignature>,
87    /// Whether transport advances while samples are processed.
88    pub playing: bool,
89    /// Active loop boundaries, when available; wrapping remains caller-owned.
90    pub loop_region: Option<LoopRegion>,
91}
92
93impl Transport {
94    /// A position with no musical time, tempo, meter or loop.
95    #[must_use]
96    pub fn new(sample_position: i64, playing: bool) -> Transport {
97        Transport {
98            sample_position,
99            beat_position: None,
100            bar_position: None,
101            tempo: None,
102            time_signature: None,
103            playing,
104            loop_region: None,
105        }
106    }
107
108    /// Checks scalar ranges and consistency without querying a plugin.
109    /// `Transport::validate_at_rate` additionally checks sample positions at the prepared rate.
110    pub fn validate(&self) -> Result<(), InputError> {
111        // CLAP represents beats/seconds as signed 31-bit fixed point. Keep positions in the
112        // common representable range instead of silently saturating at the format boundary.
113        let beat = |v: f64| v.is_finite() && (-4_294_967_296.0..4_294_967_296.0).contains(&v);
114        if self.beat_position.is_some_and(|v| !beat(v))
115            || self.bar_position.is_some_and(|v| {
116                !beat(v.start) || self.beat_position.is_none_or(|position| v.start > position)
117            })
118            || self.tempo.is_some_and(|v| !v.is_finite() || v <= 0.0)
119            || self
120                .time_signature
121                .is_some_and(|v| v.numerator == 0 || !v.denominator.is_power_of_two())
122            || self.loop_region.is_some_and(|v| {
123                !beat(v.start)
124                    || !beat(v.end)
125                    || v.start >= v.end
126                    || v.sample_start >= v.sample_end
127                    || self.beat_position.is_none()
128            })
129        {
130            return Err(InputError::Transport);
131        }
132        Ok(())
133    }
134
135    /// Check representability at the configured rate before calling any native processor.
136    pub fn validate_at_rate(&self, sample_rate: f64) -> Result<(), InputError> {
137        crate::config::validate_processing(sample_rate, 1)?;
138        self.validate()?;
139        let valid = |position: i64| {
140            (-4_294_967_296.0..4_294_967_296.0).contains(&(position as f64 / sample_rate))
141        };
142        if !valid(self.sample_position)
143            || self
144                .loop_region
145                .is_some_and(|region| !valid(region.sample_start) || !valid(region.sample_end))
146        {
147            return Err(InputError::Transport);
148        }
149        Ok(())
150    }
151
152    /// Advance within a constant-tempo segment. Stopped transport stays in place.
153    pub fn advanced(self, frames: usize, sample_rate: f64) -> Result<Self, InputError> {
154        crate::config::validate_processing(sample_rate, 1)?;
155        self.validate_at_rate(sample_rate)?;
156        if !self.playing {
157            return Ok(self);
158        }
159        let mut next = self;
160        next.sample_position = self
161            .sample_position
162            .checked_add(i64::try_from(frames).map_err(|_| InputError::Transport)?)
163            .ok_or(InputError::Transport)?;
164        if let (Some(beat), Some(tempo)) = (self.beat_position, self.tempo) {
165            let beats = beat + frames as f64 / sample_rate * tempo / 60.0;
166            next.beat_position = Some(beats);
167            if let (Some(bar), Some(meter)) = (self.bar_position, self.time_signature) {
168                let length = f64::from(meter.numerator) * 4.0 / f64::from(meter.denominator);
169                let mut count = ((beats - bar.start) / length).floor();
170                // Just below a bar line, `beats - bar.start` can round up to it; that bar has
171                // not started yet.
172                if bar.start + count * length > beats {
173                    count -= 1.0;
174                }
175                let number = f64::from(bar.number) + count;
176                if !number.is_finite() || number < i32::MIN as f64 || number > i32::MAX as f64 {
177                    return Err(InputError::Transport);
178                }
179                next.bar_position = Some(BarPosition {
180                    start: bar.start + count * length,
181                    number: number as i32,
182                });
183            } else if frames != 0 {
184                next.bar_position = None;
185            }
186        } else if frames != 0 {
187            next.beat_position = None;
188            next.bar_position = None;
189            next.loop_region = None;
190        }
191        next.validate_at_rate(sample_rate)?;
192        Ok(next)
193    }
194}
195
196/// Explicit block duration, independent of the presence of audio channels.
197#[derive(Clone, Copy, Debug, PartialEq)]
198#[non_exhaustive]
199pub struct BlockContext {
200    /// Frames to process, independent of audio channel count; may be zero.
201    pub frames: usize,
202    /// Snapshot at the first frame, or `None` when time information is unavailable.
203    pub transport: Option<Transport>,
204}
205
206impl BlockContext {
207    /// Constructs a block duration with no transport snapshot.
208    #[must_use]
209    pub const fn new(frames: usize) -> Self {
210        Self {
211            frames,
212            transport: None,
213        }
214    }
215
216    /// The same block at `transport`.
217    #[must_use]
218    pub const fn with_transport(self, transport: Transport) -> Self {
219        Self {
220            transport: Some(transport),
221            ..self
222        }
223    }
224
225    /// Checks that the frame count fits native block lengths and validates any transport.
226    pub fn validate(&self) -> Result<(), InputError> {
227        if self.frames > i32::MAX as usize {
228            return Err(InputError::BlockSize);
229        }
230        if let Some(transport) = self.transport {
231            transport.validate()?;
232        }
233        Ok(())
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn a_beat_just_below_a_bar_boundary_stays_in_the_earlier_bar() {
243        // `beat - start` rounds to exactly nine 3/4 bars, although the beat is before the ninth
244        // bar line.
245        let start = -25.380543983444497;
246        let beat = 1.6194560165555028;
247        let mut transport = Transport::new(0, true);
248        transport.beat_position = Some(beat);
249        transport.tempo = Some(120.0);
250        transport.time_signature = Some(TimeSignature {
251            numerator: 3,
252            denominator: 4,
253        });
254        transport.bar_position = Some(BarPosition { start, number: 1 });
255        let advanced = transport.advanced(0, 48_000.0).unwrap();
256        assert_eq!(
257            advanced.bar_position,
258            Some(BarPosition {
259                start: start + 8.0 * 3.0,
260                number: 9,
261            })
262        );
263    }
264}