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
//! Caller-owned timeline positions. Processing elapsed time belongs to the native processor.
use crate::InputError;
/// Musical meter; numerator must be nonzero and denominator a power of two.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TimeSignature {
/// Number of denominator note units in a bar.
pub numerator: u16,
/// Note unit, such as 4 for quarter notes or 8 for eighth notes.
pub denominator: u16,
}
impl TimeSignature {
/// `numerator` beats of `denominator` note values per bar.
#[must_use]
pub const fn new(numerator: u16, denominator: u16) -> TimeSignature {
TimeSignature {
numerator,
denominator,
}
}
}
/// Musical positions are quarter notes, including for compound meters.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct LoopRegion {
/// Start position in quarter notes.
pub start: f64,
/// Exclusive loop end in quarter notes; greater than `start`.
pub end: f64,
/// Loop start on the caller’s absolute sample timeline.
pub sample_start: i64,
/// Exclusive loop end in samples; greater than `sample_start`.
pub sample_end: i64,
}
impl LoopRegion {
/// A loop from `start` to `end` in quarter notes, which are samples `sample_start` to
/// `sample_end`.
#[must_use]
pub const fn new(start: f64, end: f64, sample_start: i64, sample_end: i64) -> LoopRegion {
LoopRegion {
start,
end,
sample_start,
sample_end,
}
}
}
/// Caller-supplied start and numbering of the current musical bar.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct BarPosition {
/// Start position in quarter notes.
pub start: f64,
/// Caller-supplied bar number; advancement increments it at bar boundaries.
pub number: i32,
}
impl BarPosition {
/// Bar `number`, which starts at `start` quarter notes.
#[must_use]
pub const fn new(start: f64, number: i32) -> BarPosition {
BarPosition { start, number }
}
}
/// A snapshot at the first sample of a block. `None` fields are unavailable, never synthesized.
/// A seek is a discontinuity between consecutive snapshots. Loop wrapping is caller-owned.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Transport {
/// Signed absolute sample position of the block’s first frame.
pub sample_position: i64,
/// Absolute musical position in quarter notes, when available.
pub beat_position: Option<f64>,
/// Current bar start and number; requires an available beat position.
pub bar_position: Option<BarPosition>,
/// Finite, positive quarter notes per minute, when available.
pub tempo: Option<f64>,
/// Current musical meter, when available.
pub time_signature: Option<TimeSignature>,
/// Whether transport advances while samples are processed.
pub playing: bool,
/// Active loop boundaries, when available; wrapping remains caller-owned.
pub loop_region: Option<LoopRegion>,
}
impl Transport {
/// A position with no musical time, tempo, meter or loop.
#[must_use]
pub fn new(sample_position: i64, playing: bool) -> Transport {
Transport {
sample_position,
beat_position: None,
bar_position: None,
tempo: None,
time_signature: None,
playing,
loop_region: None,
}
}
/// Checks scalar ranges and consistency without querying a plugin.
/// `Transport::validate_at_rate` additionally checks sample positions at the prepared rate.
pub fn validate(&self) -> Result<(), InputError> {
// CLAP represents beats/seconds as signed 31-bit fixed point. Keep positions in the
// common representable range instead of silently saturating at the format boundary.
let beat = |v: f64| v.is_finite() && (-4_294_967_296.0..4_294_967_296.0).contains(&v);
if self.beat_position.is_some_and(|v| !beat(v))
|| self.bar_position.is_some_and(|v| {
!beat(v.start) || self.beat_position.is_none_or(|position| v.start > position)
})
|| self.tempo.is_some_and(|v| !v.is_finite() || v <= 0.0)
|| self
.time_signature
.is_some_and(|v| v.numerator == 0 || !v.denominator.is_power_of_two())
|| self.loop_region.is_some_and(|v| {
!beat(v.start)
|| !beat(v.end)
|| v.start >= v.end
|| v.sample_start >= v.sample_end
|| self.beat_position.is_none()
})
{
return Err(InputError::Transport);
}
Ok(())
}
/// Check representability at the configured rate before calling any native processor.
pub fn validate_at_rate(&self, sample_rate: f64) -> Result<(), InputError> {
crate::config::validate_processing(sample_rate, 1)?;
self.validate()?;
let valid = |position: i64| {
(-4_294_967_296.0..4_294_967_296.0).contains(&(position as f64 / sample_rate))
};
if !valid(self.sample_position)
|| self
.loop_region
.is_some_and(|region| !valid(region.sample_start) || !valid(region.sample_end))
{
return Err(InputError::Transport);
}
Ok(())
}
/// Advance within a constant-tempo segment. Stopped transport stays in place.
pub fn advanced(self, frames: usize, sample_rate: f64) -> Result<Self, InputError> {
crate::config::validate_processing(sample_rate, 1)?;
self.validate_at_rate(sample_rate)?;
if !self.playing {
return Ok(self);
}
let mut next = self;
next.sample_position = self
.sample_position
.checked_add(i64::try_from(frames).map_err(|_| InputError::Transport)?)
.ok_or(InputError::Transport)?;
if let (Some(beat), Some(tempo)) = (self.beat_position, self.tempo) {
let beats = beat + frames as f64 / sample_rate * tempo / 60.0;
next.beat_position = Some(beats);
if let (Some(bar), Some(meter)) = (self.bar_position, self.time_signature) {
let length = f64::from(meter.numerator) * 4.0 / f64::from(meter.denominator);
let mut count = ((beats - bar.start) / length).floor();
// Just below a bar line, `beats - bar.start` can round up to it; that bar has
// not started yet.
if bar.start + count * length > beats {
count -= 1.0;
}
let number = f64::from(bar.number) + count;
if !number.is_finite() || number < i32::MIN as f64 || number > i32::MAX as f64 {
return Err(InputError::Transport);
}
next.bar_position = Some(BarPosition {
start: bar.start + count * length,
number: number as i32,
});
} else if frames != 0 {
next.bar_position = None;
}
} else if frames != 0 {
next.beat_position = None;
next.bar_position = None;
next.loop_region = None;
}
next.validate_at_rate(sample_rate)?;
Ok(next)
}
}
/// Explicit block duration, independent of the presence of audio channels.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct BlockContext {
/// Frames to process, independent of audio channel count; may be zero.
pub frames: usize,
/// Snapshot at the first frame, or `None` when time information is unavailable.
pub transport: Option<Transport>,
}
impl BlockContext {
/// Constructs a block duration with no transport snapshot.
#[must_use]
pub const fn new(frames: usize) -> Self {
Self {
frames,
transport: None,
}
}
/// The same block at `transport`.
#[must_use]
pub const fn with_transport(self, transport: Transport) -> Self {
Self {
transport: Some(transport),
..self
}
}
/// Checks that the frame count fits native block lengths and validates any transport.
pub fn validate(&self) -> Result<(), InputError> {
if self.frames > i32::MAX as usize {
return Err(InputError::BlockSize);
}
if let Some(transport) = self.transport {
transport.validate()?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_beat_just_below_a_bar_boundary_stays_in_the_earlier_bar() {
// `beat - start` rounds to exactly nine 3/4 bars, although the beat is before the ninth
// bar line.
let start = -25.380543983444497;
let beat = 1.6194560165555028;
let mut transport = Transport::new(0, true);
transport.beat_position = Some(beat);
transport.tempo = Some(120.0);
transport.time_signature = Some(TimeSignature {
numerator: 3,
denominator: 4,
});
transport.bar_position = Some(BarPosition { start, number: 1 });
let advanced = transport.advanced(0, 48_000.0).unwrap();
assert_eq!(
advanced.bar_position,
Some(BarPosition {
start: start + 8.0 * 3.0,
number: 9,
})
);
}
}