qualia_audio/midi/sequencer/quantize.rs
1//! Snap an event tick to a musical grid, with optional strength.
2//!
3//! `quantize_tick(tick, grid_ticks, strength)` rounds `tick` to the nearest
4//! multiple of `grid_ticks` (the grid), then moves the event only a fraction of
5//! the way there when `strength < 1.0`:
6//!
7//! ```text
8//! snapped = round(tick / grid) * grid
9//! result = round(tick + strength * (snapped - tick))
10//! ```
11//!
12//! `strength` is clamped to `[0, 1]`: `1.0` snaps fully to the grid, `0.0`
13//! leaves the tick untouched, and intermediate values "humanize" by partially
14//! pulling toward the grid. Pure and allocation-free.
15
16use crate::types::AudioError;
17
18/// Snap `tick` toward the nearest multiple of `grid_ticks` by `strength`.
19///
20/// `grid_ticks` is the grid spacing in ticks (e.g. a 1/16 note = `ppq/4`).
21/// `strength` in `[0, 1]` is clamped. Returns [`AudioError::InvalidParameter`]
22/// if `grid_ticks == 0` or `strength` is not finite.
23pub fn quantize_tick(tick: u64, grid_ticks: u32, strength: f64) -> Result<u64, AudioError> {
24 if grid_ticks == 0 || !strength.is_finite() {
25 return Err(AudioError::InvalidParameter);
26 }
27 let strength = strength.clamp(0.0, 1.0);
28 let grid = grid_ticks as u64;
29
30 // Nearest grid multiple via integer rounding (round half up).
31 let snapped = ((tick + grid / 2) / grid) * grid;
32
33 if strength >= 1.0 {
34 return Ok(snapped);
35 }
36 let t = tick as f64;
37 let moved = t + strength * (snapped as f64 - t);
38 // Round to nearest whole tick, never negative.
39 Ok(moved.round().max(0.0) as u64)
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn golden_119_snaps_to_120_on_sixteenth_grid() {
48 // 1/16 note at 480 PPQ = 120 ticks.
49 let q = quantize_tick(119, 120, 1.0).unwrap();
50 assert_eq!(q, 120);
51 }
52
53 #[test]
54 fn rounds_down_below_half() {
55 // 55 is closer to 0 than to 120 -> 0 at full strength.
56 assert_eq!(quantize_tick(55, 120, 1.0).unwrap(), 0);
57 // 65 is past the halfway point -> 120.
58 assert_eq!(quantize_tick(65, 120, 1.0).unwrap(), 120);
59 }
60
61 #[test]
62 fn partial_strength_pulls_halfway() {
63 // tick 100, grid 120 -> snapped 120; at 0.5 strength -> 110.
64 assert_eq!(quantize_tick(100, 120, 0.5).unwrap(), 110);
65 // Zero strength leaves it untouched.
66 assert_eq!(quantize_tick(100, 120, 0.0).unwrap(), 100);
67 }
68
69 #[test]
70 fn rejects_zero_grid() {
71 assert_eq!(quantize_tick(10, 0, 1.0), Err(AudioError::InvalidParameter));
72 }
73}