Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ir/src/time.rs3//! Description: Exact musical time (rationals in whole notes), the tempo map and the single4//! musical-time to seconds to samples conversion rule shared by the compiler, runtime and studio.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use serde::{Deserialize, Serialize};10use std::cmp::Ordering;11use std::fmt;1213/// An exact rational number, always normalised (gcd 1, positive denominator).14///15/// Musical positions and durations are expressed in **whole notes**: `1/4` is a quarter note.16/// Arithmetic is checked: an overflow of `i64` returns `None` instead of wrapping.17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]18pub struct Rational {19 num: i64,20 den: i64,21}2223/// Deserialisation goes through [`Rational::new`]: untrusted JSON can never produce a zero24/// denominator or a non-normalised value.25impl<'de> Deserialize<'de> for Rational {26 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Rational, D::Error> {27 #[derive(Deserialize)]28 struct Raw {29 num: i64,30 den: i64,31 }32 let raw = Raw::deserialize(d)?;33 Rational::new(raw.num, raw.den).ok_or_else(|| serde::de::Error::custom("rational with a zero denominator or out of range"))34 }35}3637fn gcd(a: i128, b: i128) -> i128 {38 let (mut a, mut b) = (a.abs(), b.abs());39 while b != 0 {40 let t = a % b;41 a = b;42 b = t;43 }44 a45}4647impl Rational {48 pub const ZERO: Rational = Rational { num: 0, den: 1 };49 pub const ONE: Rational = Rational { num: 1, den: 1 };5051 /// Builds `num/den`. Returns `None` when `den == 0` or the reduced value does not fit `i64`.52 pub fn new(num: i64, den: i64) -> Option<Rational> {53 Self::from_i128(num as i128, den as i128)54 }5556 fn from_i128(num: i128, den: i128) -> Option<Rational> {57 if den == 0 {58 return None;59 }60 let g = gcd(num, den).max(1);61 let (mut n, mut d) = (num / g, den / g);62 if d < 0 {63 n = -n;64 d = -d;65 }66 if n > i64::MAX as i128 || n < i64::MIN as i128 || d > i64::MAX as i128 {67 return None;68 }69 Some(Rational { num: n as i64, den: d as i64 })70 }7172 pub const fn from_int(n: i64) -> Rational {73 Rational { num: n, den: 1 }74 }7576 pub fn num(self) -> i64 {77 self.num78 }79 pub fn den(self) -> i64 {80 self.den81 }82 pub fn is_zero(self) -> bool {83 self.num == 084 }85 pub fn is_negative(self) -> bool {86 self.num < 087 }88 pub fn is_integer(self) -> bool {89 self.den == 190 }91 pub fn to_f64(self) -> f64 {92 self.num as f64 / self.den as f6493 }9495 pub fn checked_add(self, o: Rational) -> Option<Rational> {96 let n = (self.num as i128) * (o.den as i128) + (o.num as i128) * (self.den as i128);97 Self::from_i128(n, (self.den as i128) * (o.den as i128))98 }99 pub fn checked_sub(self, o: Rational) -> Option<Rational> {100 self.checked_add(Rational { num: o.num.checked_neg()?, den: o.den })101 }102 pub fn checked_mul(self, o: Rational) -> Option<Rational> {103 Self::from_i128((self.num as i128) * (o.num as i128), (self.den as i128) * (o.den as i128))104 }105 pub fn checked_div(self, o: Rational) -> Option<Rational> {106 if o.num == 0 {107 return None;108 }109 Self::from_i128((self.num as i128) * (o.den as i128), (self.den as i128) * (o.num as i128))110 }111112 /// Best rational approximation of a finite float with a denominator no larger than `max_den`113 /// (continued fractions). Used only where the language explicitly converts a float to musical time.114 pub fn approximate(x: f64, max_den: i64) -> Option<Rational> {115 if !x.is_finite() || x.abs() > 1e12 {116 return None;117 }118 let neg = x < 0.0;119 let mut v = x.abs();120 let (mut p0, mut q0, mut p1, mut q1) = (0i128, 1i128, 1i128, 0i128);121 for _ in 0..64 {122 let a = v.floor() as i128;123 let (p2, q2) = (a * p1 + p0, a * q1 + q0);124 if q2 > max_den as i128 {125 break;126 }127 p0 = p1;128 q0 = q1;129 p1 = p2;130 q1 = q2;131 let frac = v - a as f64;132 if frac < 1e-12 {133 break;134 }135 v = 1.0 / frac;136 }137 if q1 == 0 {138 return None;139 }140 Self::from_i128(if neg { -p1 } else { p1 }, q1)141 }142}143144impl PartialOrd for Rational {145 fn partial_cmp(&self, o: &Rational) -> Option<Ordering> {146 Some(self.cmp(o))147 }148}149impl Ord for Rational {150 fn cmp(&self, o: &Rational) -> Ordering {151 ((self.num as i128) * (o.den as i128)).cmp(&((o.num as i128) * (self.den as i128)))152 }153}154impl fmt::Display for Rational {155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {156 if self.den == 1 {157 write!(f, "{}", self.num)158 } else {159 write!(f, "{}/{}", self.num, self.den)160 }161 }162}163164/// A tempo that takes effect at a musical position and holds until the next point.165///166/// `bpm` counts `beat_unit` notes per minute (`beat_unit` = 1/4 means quarter notes per minute).167/// When `ramp` is true the tempo moves linearly **in musical position** from this point's `bpm`168/// to the next point's `bpm`; otherwise it is constant.169#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]170pub struct TempoPoint {171 pub at: Rational,172 pub bpm: f64,173 pub beat_unit: Rational,174 pub ramp: bool,175}176177impl TempoPoint {178 /// Seconds taken by one whole note at this point's tempo.179 pub fn seconds_per_whole(&self) -> f64 {180 60.0 / (self.bpm * self.beat_unit.to_f64())181 }182}183184/// A time signature taking effect at a musical position (always a bar line).185#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]186pub struct SignaturePoint {187 pub at: Rational,188 pub numerator: u32,189 pub denominator: u32,190}191192impl SignaturePoint {193 pub fn bar_length(&self) -> Rational {194 Rational::new(self.numerator as i64, self.denominator as i64).unwrap_or(Rational::ONE)195 }196 pub fn beat_length(&self) -> Rational {197 Rational::new(1, self.denominator as i64).unwrap_or(Rational::ONE)198 }199}200201/// The tempo map of a composition. Invariants (checked by [`TempoMap::validate`]): at least one202/// point, the first one at position 0, positions strictly increasing, finite `bpm` in [1, 1000].203#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]204pub struct TempoMap {205 pub points: Vec<TempoPoint>,206}207208impl Default for TempoMap {209 fn default() -> Self {210 TempoMap { points: vec![TempoPoint { at: Rational::ZERO, bpm: 120.0, beat_unit: Rational::new(1, 4).unwrap(), ramp: false }] }211 }212}213214impl TempoMap {215 pub fn constant(bpm: f64) -> TempoMap {216 TempoMap { points: vec![TempoPoint { at: Rational::ZERO, bpm, beat_unit: Rational::new(1, 4).unwrap(), ramp: false }] }217 }218219 pub fn validate(&self) -> Result<(), String> {220 let first = self.points.first().ok_or("tempo map is empty")?;221 if !first.at.is_zero() {222 return Err("first tempo point must be at position 0".into());223 }224 for w in self.points.windows(2) {225 if w[1].at <= w[0].at {226 return Err("tempo points must be strictly increasing".into());227 }228 }229 for p in &self.points {230 if !(p.bpm.is_finite() && (1.0..=1000.0).contains(&p.bpm)) {231 return Err(format!("tempo {} bpm is outside [1, 1000]", p.bpm));232 }233 if p.beat_unit <= Rational::ZERO {234 return Err("beat unit must be positive".into());235 }236 }237 Ok(())238 }239240 /// Seconds elapsed from position 0 to `pos` (whole notes). Positions before 0 clamp to 0.241 ///242 /// Constant segments integrate exactly; a ramp from s0 to s1 seconds-per-whole over a span L243 /// integrates as the trapezoid of the linearly interpolated seconds-per-whole.244 pub fn seconds_at(&self, pos: Rational) -> f64 {245 if pos <= Rational::ZERO || self.points.is_empty() {246 return 0.0;247 }248 let mut secs = 0.0f64;249 for (i, p) in self.points.iter().enumerate() {250 if pos <= p.at {251 break;252 }253 let next = self.points.get(i + 1);254 let seg_end = match next {255 Some(n) if n.at < pos => n.at,256 _ => pos,257 };258 let len = (seg_end.to_f64() - p.at.to_f64()).max(0.0);259 let s0 = p.seconds_per_whole();260 match (p.ramp, next) {261 (true, Some(n)) => {262 let full = n.at.to_f64() - p.at.to_f64();263 let s1 = n.seconds_per_whole();264 let s_end = s0 + (s1 - s0) * (len / full);265 secs += 0.5 * (s0 + s_end) * len;266 }267 _ => secs += s0 * len,268 }269 }270 secs271 }272273 /// Inverse of [`seconds_at`]: the musical position (as a float, whole notes) reached at `secs`.274 pub fn position_at_seconds(&self, secs: f64) -> f64 {275 if secs <= 0.0 || self.points.is_empty() {276 return 0.0;277 }278 let mut acc = 0.0f64;279 for (i, p) in self.points.iter().enumerate() {280 let s0 = p.seconds_per_whole();281 let next = self.points.get(i + 1);282 match next {283 None => return p.at.to_f64() + (secs - acc) / s0,284 Some(n) => {285 let full = n.at.to_f64() - p.at.to_f64();286 let s1 = if p.ramp { n.seconds_per_whole() } else { s0 };287 let seg = 0.5 * (s0 + s1) * full;288 if secs < acc + seg {289 let t = secs - acc;290 if !p.ramp || (s1 - s0).abs() < 1e-15 {291 return p.at.to_f64() + t / s0;292 }293 // t = s0*x + 0.5*k*x^2 with k = (s1-s0)/full; solve for x >= 0.294 let k = (s1 - s0) / full;295 let disc = (s0 * s0 + 2.0 * k * t).max(0.0);296 return p.at.to_f64() + (-s0 + disc.sqrt()) / k;297 }298 acc += seg;299 }300 }301 }302 0.0303 }304305 /// The tempo point in effect at `pos`.306 pub fn point_at(&self, pos: Rational) -> &TempoPoint {307 let mut cur = &self.points[0];308 for p in &self.points {309 if p.at <= pos {310 cur = p;311 } else {312 break;313 }314 }315 cur316 }317}318319/// THE rounding rule from seconds to a sample index: round half up, `floor(secs * rate + 0.5)`.320/// Every component (offline render, real-time engine, studio rulers) must use this function.321pub fn seconds_to_samples(secs: f64, sample_rate: u32) -> u64 {322 if secs.is_nan() || secs <= 0.0 {323 return 0;324 }325 (secs * sample_rate as f64 + 0.5).floor() as u64326}327328pub fn samples_to_seconds(samples: u64, sample_rate: u32) -> f64 {329 samples as f64 / sample_rate as f64330}331332#[cfg(test)]333mod tests {334 use super::*;335336 fn r(n: i64, d: i64) -> Rational {337 Rational::new(n, d).unwrap()338 }339340 #[test]341 fn normalises_and_orders() {342 assert_eq!(r(2, 4), r(1, 2));343 assert_eq!(r(1, -2), r(-1, 2));344 assert!(r(1, 3) < r(1, 2));345 assert_eq!(r(1, 3).checked_add(r(1, 6)), Some(r(1, 2)));346 assert_eq!(r(1, 2).checked_div(Rational::ZERO), None);347 assert_eq!(Rational::new(1, 0), None);348 assert_eq!(format!("{}", r(3, 4)), "3/4");349 }350351 #[test]352 fn deserialisation_validates() {353 assert_eq!(serde_json::from_str::<Rational>(r#"{"num":2,"den":-4}"#).unwrap(), r(-1, 2));354 assert!(serde_json::from_str::<Rational>(r#"{"num":1,"den":0}"#).is_err());355 assert_eq!(serde_json::to_string(&r(3, 4)).unwrap(), r#"{"num":3,"den":4}"#);356 }357358 #[test]359 fn overflow_is_reported() {360 let big = Rational::from_int(i64::MAX);361 assert_eq!(big.checked_add(Rational::ONE), None);362 assert_eq!(big.checked_mul(Rational::from_int(2)), None);363 }364365 #[test]366 fn approximation() {367 assert_eq!(Rational::approximate(0.75, 1000), Some(r(3, 4)));368 assert_eq!(Rational::approximate(1.0 / 3.0, 1000), Some(r(1, 3)));369 assert_eq!(Rational::approximate(f64::NAN, 1000), None);370 }371372 #[test]373 fn constant_tempo_seconds() {374 let m = TempoMap::constant(120.0);375 // One whole note = 4 quarter notes = 2 s at 120 bpm.376 assert!((m.seconds_at(Rational::ONE) - 2.0).abs() < 1e-12);377 assert!((m.position_at_seconds(2.0) - 1.0).abs() < 1e-12);378 assert_eq!(seconds_to_samples(m.seconds_at(r(1, 4)), 48_000), 24_000);379 }380381 #[test]382 fn tempo_change_and_ramp_round_trip() {383 let q = r(1, 4);384 let m = TempoMap {385 points: vec![386 TempoPoint { at: Rational::ZERO, bpm: 120.0, beat_unit: q, ramp: false },387 TempoPoint { at: Rational::ONE, bpm: 60.0, beat_unit: q, ramp: true },388 TempoPoint { at: r(2, 1), bpm: 120.0, beat_unit: q, ramp: false },389 ],390 };391 m.validate().unwrap();392 // Bar 1: 2 s. Bar 2: ramp 4 s/whole -> 2 s/whole, mean 3 s. Then 2 s/whole.393 assert!((m.seconds_at(r(2, 1)) - 5.0).abs() < 1e-12);394 assert!((m.seconds_at(r(3, 1)) - 7.0).abs() < 1e-12);395 for i in 0..=60 {396 let pos = i as f64 / 20.0;397 let secs = m.seconds_at(Rational::approximate(pos, 1000).unwrap());398 assert!((m.position_at_seconds(secs) - pos).abs() < 1e-9, "pos {pos}");399 }400 }401402 #[test]403 fn rounding_rule_is_half_up() {404 assert_eq!(seconds_to_samples(0.5 / 48_000.0, 48_000), 1);405 assert_eq!(seconds_to_samples(0.49 / 48_000.0, 48_000), 0);406 assert_eq!(seconds_to_samples(-1.0, 48_000), 0);407 assert_eq!(seconds_to_samples(f64::NAN, 48_000), 0);408 }409}410