1use serde::{Deserialize, Serialize};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
12pub struct FrameRate {
13 pub num: u32,
14 pub den: u32,
15}
16
17impl FrameRate {
18 pub const FILM: FrameRate = FrameRate::whole(24);
20 pub const PAL: FrameRate = FrameRate::whole(25);
22 pub const NTSC: FrameRate = FrameRate::new(30000, 1001);
25
26 pub const fn new(num: u32, den: u32) -> Self {
28 Self {
29 num: if num == 0 { 1 } else { num },
30 den: if den == 0 { 1 } else { den },
31 }
32 }
33
34 pub const fn whole(fps: u32) -> Self {
36 Self::new(fps, 1)
37 }
38
39 pub fn fps(self) -> f64 {
41 f64::from(self.num.max(1)) / f64::from(self.den.max(1))
42 }
43
44 pub fn frame(self) -> f64 {
46 1.0 / self.fps()
47 }
48
49 pub fn nominal(self) -> u32 {
52 (self.fps().round() as u32).max(1)
53 }
54}
55
56#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
58pub struct Tempo {
59 pub bpm: f64,
61 pub beats_per_bar: u32,
63 pub beat_unit: u32,
65 pub ticks_per_beat: u32,
67 pub offset: f64,
69}
70
71impl Default for Tempo {
72 fn default() -> Self {
73 Self::new(120.0, 4, 4)
74 }
75}
76
77impl Tempo {
78 pub fn new(bpm: f64, beats_per_bar: u32, beat_unit: u32) -> Self {
81 Self {
82 bpm,
83 beats_per_bar,
84 beat_unit,
85 ticks_per_beat: 960,
86 offset: 0.0,
87 }
88 }
89
90 pub fn offset(mut self, seconds: f64) -> Self {
92 self.offset = seconds;
93 self
94 }
95
96 pub fn ticks_per_beat(mut self, ticks: u32) -> Self {
98 self.ticks_per_beat = ticks.max(1);
99 self
100 }
101
102 pub fn beat(&self) -> f64 {
104 60.0 / if self.bpm.is_finite() && self.bpm > 0.0 {
105 self.bpm
106 } else {
107 120.0
108 }
109 }
110
111 pub fn bar(&self) -> f64 {
113 self.beat() * f64::from(self.beats_per_bar.max(1))
114 }
115
116 fn tpb(&self) -> i64 {
117 i64::from(self.ticks_per_beat.max(1))
118 }
119
120 fn bpb(&self) -> i64 {
121 i64::from(self.beats_per_bar.max(1))
122 }
123}
124
125#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
127#[serde(rename_all = "snake_case")]
128pub enum TimeScale {
129 #[default]
131 Seconds,
132 Frames(FrameRate),
135 Beats(Tempo),
137}
138
139const SECOND_STEPS: &[f64] = &[
141 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 15.0, 30.0, 60.0,
142 120.0, 300.0, 600.0, 900.0, 1800.0, 3600.0, 7200.0, 10800.0, 21600.0, 43200.0, 86400.0,
143];
144
145const WHOLE_SECONDS: &[f64] = &[
147 1.0, 2.0, 5.0, 10.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 900.0, 1800.0, 3600.0, 7200.0,
148 10800.0, 21600.0, 43200.0, 86400.0,
149];
150
151impl TimeScale {
152 pub fn frames(fps: u32) -> Self {
154 TimeScale::Frames(FrameRate::whole(fps))
155 }
156
157 pub fn beats(bpm: f64) -> Self {
159 TimeScale::Beats(Tempo::new(bpm, 4, 4))
160 }
161
162 pub fn kind(&self) -> &'static str {
164 match self {
165 TimeScale::Seconds => "seconds",
166 TimeScale::Frames(_) => "frames",
167 TimeScale::Beats(_) => "beats",
168 }
169 }
170
171 pub fn unit(&self) -> f64 {
173 match self {
174 TimeScale::Seconds => 1.0,
175 TimeScale::Frames(r) => r.frame(),
176 TimeScale::Beats(t) => t.beat(),
177 }
178 }
179
180 pub fn to_units(&self, seconds: f64) -> f64 {
182 match self {
183 TimeScale::Seconds => seconds,
184 TimeScale::Frames(r) => seconds * r.fps(),
185 TimeScale::Beats(t) => (seconds - t.offset) / t.beat(),
186 }
187 }
188
189 pub fn from_units(&self, units: f64) -> f64 {
191 match self {
192 TimeScale::Seconds => units,
193 TimeScale::Frames(r) => units / r.fps(),
194 TimeScale::Beats(t) => t.offset + units * t.beat(),
195 }
196 }
197
198 pub fn origin(&self) -> f64 {
200 match self {
201 TimeScale::Beats(t) => t.offset,
202 _ => 0.0,
203 }
204 }
205
206 pub fn step(&self, big: bool) -> f64 {
209 match (self, big) {
210 (TimeScale::Seconds, false) => 1.0,
211 (TimeScale::Seconds, true) => 10.0,
212 (TimeScale::Frames(r), false) => r.frame(),
213 (TimeScale::Frames(r), true) => f64::from(r.nominal()) / r.fps(),
214 (TimeScale::Beats(t), false) => t.beat(),
215 (TimeScale::Beats(t), true) => t.bar(),
216 }
217 }
218
219 pub fn quantize(&self, seconds: f64) -> f64 {
222 match self {
223 TimeScale::Frames(r) => (seconds * r.fps()).round() / r.fps(),
224 _ => seconds,
225 }
226 }
227
228 pub fn round_to(&self, seconds: f64, step: f64) -> f64 {
231 if !step.is_finite() || step <= 0.0 {
232 return self.quantize(seconds);
233 }
234 let o = self.origin();
235 self.quantize(o + ((seconds - o) / step).round() * step)
236 }
237
238 pub fn steps(&self) -> Vec<f64> {
241 match self {
242 TimeScale::Seconds => SECOND_STEPS.to_vec(),
243 TimeScale::Frames(r) => {
244 let fps = r.fps();
245 let n = r.nominal();
246 let mut v: Vec<f64> = [1u32, 2, 5, 10]
247 .iter()
248 .filter(|k| **k < n)
249 .map(|k| f64::from(*k) / fps)
250 .collect();
251 let second = f64::from(n) / fps;
253 v.extend(WHOLE_SECONDS.iter().map(|s| s * second));
254 v
255 }
256 TimeScale::Beats(t) => {
257 let b = t.beat();
258 let mut v: Vec<f64> = [1.0 / 16.0, 1.0 / 8.0, 1.0 / 4.0, 1.0 / 2.0, 1.0]
259 .iter()
260 .map(|k| k * b)
261 .collect();
262 let bar = t.bar();
263 if t.beats_per_bar > 1 {
264 v.push(bar);
265 }
266 v.extend(
267 [2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0]
268 .iter()
269 .map(|k| k * bar),
270 );
271 v
272 }
273 }
274 }
275
276 pub fn format(&self, seconds: f64) -> String {
278 match self {
279 TimeScale::Seconds => clock(seconds, 3),
280 TimeScale::Frames(r) => timecode(seconds, *r),
281 TimeScale::Beats(t) => bars(seconds, t, Precision::Tick),
282 }
283 }
284
285 pub fn label(&self, seconds: f64, step: f64) -> String {
288 match self {
289 TimeScale::Seconds => clock(seconds, decimals(step)),
290 TimeScale::Frames(r) => timecode(seconds, *r),
291 TimeScale::Beats(t) => {
292 let eps = 1e-9;
293 let precision = if t.beats_per_bar > 1 && step >= t.bar() - eps {
294 Precision::Bar
295 } else if step >= t.beat() - eps {
296 Precision::Beat
297 } else {
298 Precision::Tick
299 };
300 bars(seconds, t, precision)
301 }
302 }
303 }
304
305 pub fn parse(&self, text: &str) -> Option<f64> {
308 let text = text.trim();
309 let (negative, body) = match text.strip_prefix('-') {
310 Some(rest) => (true, rest.trim()),
311 None => (false, text),
312 };
313 if body.is_empty() {
314 return None;
315 }
316 let sign = if negative { -1.0 } else { 1.0 };
317 match self {
318 TimeScale::Seconds => parse_clock(body).map(|s| sign * s),
319 TimeScale::Frames(r) => {
320 let parts: Vec<&str> = body.split(':').collect();
321 if parts.len() == 4 {
322 let n: Vec<u64> = parts
323 .iter()
324 .map(|p| p.trim().parse::<u64>().ok())
325 .collect::<Option<_>>()?;
326 let nominal = u64::from(r.nominal());
327 let frames = ((n[0] * 60 + n[1]) * 60 + n[2]) * nominal + n[3];
328 Some(sign * frames as f64 / r.fps())
329 } else {
330 parse_clock(body).map(|s| self.quantize(sign * s))
331 }
332 }
333 TimeScale::Beats(t) => {
334 let n: Vec<i64> = body
335 .split('.')
336 .map(|p| p.trim().parse::<i64>().ok())
337 .collect::<Option<_>>()?;
338 let (bar, beat, tick) = match n.as_slice() {
339 [bar] => (*bar, 1, 0),
340 [bar, beat] => (*bar, *beat, 0),
341 [bar, beat, tick] => (*bar, *beat, *tick),
342 _ => return None,
343 };
344 let bar = if negative { -bar } else { bar };
345 let ticks = ((bar - 1) * t.bpb() + (beat - 1)) * t.tpb() + tick;
346 Some(t.offset + ticks as f64 / t.tpb() as f64 * t.beat())
347 }
348 }
349 }
350}
351
352#[derive(Clone, Copy, PartialEq, Eq)]
354enum Precision {
355 Bar,
356 Beat,
357 Tick,
358}
359
360fn decimals(step: f64) -> u32 {
363 if step >= 1.0 - 1e-9 || step.is_nan() || step <= 0.0 {
364 return 0;
365 }
366 (-step.log10() - 1e-9).ceil().clamp(0.0, 9.0) as u32
367}
368
369fn clock(seconds: f64, decimals: u32) -> String {
372 let sign = if seconds < 0.0 && seconds.abs() >= 0.5 * 10f64.powi(-(decimals as i32)) {
373 "-"
374 } else {
375 ""
376 };
377 let scale = 10u64.pow(decimals);
378 let scaled = (seconds.abs() * scale as f64).round() as u64;
379 let (whole, frac) = (scaled / scale, scaled % scale);
380 let (h, m, s) = (whole / 3600, whole / 60 % 60, whole % 60);
381 let mut out = if h > 0 {
382 format!("{sign}{h}:{m:02}:{s:02}")
383 } else {
384 format!("{sign}{m}:{s:02}")
385 };
386 if decimals > 0 {
387 out.push_str(&format!(".{frac:0width$}", width = decimals as usize));
388 }
389 out
390}
391
392fn parse_clock(text: &str) -> Option<f64> {
394 let parts: Vec<&str> = text.split(':').collect();
395 if parts.len() > 3 {
396 return None;
397 }
398 let mut total = 0.0;
399 for (i, part) in parts.iter().enumerate() {
400 let part = part.trim();
401 let v: f64 = if i + 1 == parts.len() {
402 part.parse().ok()?
403 } else {
404 f64::from(part.parse::<u32>().ok()?)
405 };
406 if !v.is_finite() || v < 0.0 {
407 return None;
408 }
409 total = total * 60.0 + v;
410 }
411 Some(total)
412}
413
414fn timecode(seconds: f64, rate: FrameRate) -> String {
416 let frames = (seconds * rate.fps()).round() as i64;
417 let sign = if frames < 0 { "-" } else { "" };
418 let n = frames.unsigned_abs();
419 let nominal = u64::from(rate.nominal());
420 let ff = n % nominal;
421 let s = n / nominal;
422 format!(
423 "{sign}{:02}:{:02}:{:02}:{ff:02}",
424 s / 3600,
425 s / 60 % 60,
426 s % 60
427 )
428}
429
430fn bars(seconds: f64, tempo: &Tempo, precision: Precision) -> String {
432 let tpb = tempo.tpb();
433 let bpb = tempo.bpb();
434 let ticks = ((seconds - tempo.offset) / tempo.beat() * tpb as f64).round() as i64;
435 let beats = ticks.div_euclid(tpb);
436 let tick = ticks.rem_euclid(tpb);
437 let bar = beats.div_euclid(bpb) + 1;
438 let beat = beats.rem_euclid(bpb) + 1;
439 let width = (tpb - 1).max(1).to_string().len();
440 match precision {
441 Precision::Bar => format!("{bar}"),
442 Precision::Beat => format!("{bar}.{beat}"),
443 Precision::Tick => format!("{bar}.{beat}.{tick:0width$}"),
444 }
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450
451 #[test]
452 fn seconds_read_and_write_as_a_clock() {
453 let s = TimeScale::Seconds;
454 assert_eq!(s.format(0.0), "0:00.000");
455 assert_eq!(s.format(62.5), "1:02.500");
456 assert_eq!(s.format(3723.25), "1:02:03.250");
457 assert_eq!(s.format(-1.5), "-0:01.500");
458 assert_eq!(s.parse("1:02.5"), Some(62.5));
459 assert_eq!(s.parse("1:02:03.25"), Some(3723.25));
460 assert_eq!(s.parse("-12.5"), Some(-12.5));
461 assert_eq!(s.parse("nope"), None);
462 assert_eq!(s.label(5.0, 1.0), "0:05");
463 assert_eq!(s.label(5.5, 0.5), "0:05.5");
464 assert_eq!(s.label(5.25, 0.05), "0:05.25");
465 assert_eq!(s.label(59.96, 0.1), "1:00.0");
466 }
467
468 #[test]
469 fn frames_are_a_timecode_of_whole_frames() {
470 let s = TimeScale::frames(25);
471 assert_eq!(s.format(0.0), "00:00:00:00");
472 assert_eq!(s.format(62.48), "00:01:02:12");
473 assert_eq!(s.format(3600.0 + 0.04), "01:00:00:01");
474 assert_eq!(s.parse("00:01:02:12"), Some(62.48));
475 assert_eq!(s.to_units(2.0), 50.0);
476 assert_eq!(s.from_units(50.0), 2.0);
477 assert_eq!(s.quantize(1.01), 1.0);
478 assert_eq!(s.quantize(1.03), 1.04);
479 assert_eq!(s.step(false), 0.04);
480 assert_eq!(s.step(true), 1.0);
481 let ntsc = TimeScale::Frames(FrameRate::NTSC);
483 assert_eq!(ntsc.format(30.0 * 1001.0 / 30000.0), "00:00:01:00");
484 assert_eq!(FrameRate::NTSC.nominal(), 30);
485 }
486
487 #[test]
488 fn beats_count_bars_from_one() {
489 let s = TimeScale::beats(128.0);
491 assert_eq!(s.format(0.0), "1.1.000");
492 assert_eq!(s.format(1.875), "2.1.000");
493 assert_eq!(s.format(1.875 + 0.46875 * 1.5), "2.2.480");
494 assert_eq!(s.parse("2.2.480"), Some(1.875 + 0.46875 * 1.5));
495 assert_eq!(s.parse("17"), Some(16.0 * 1.875));
496 assert_eq!(s.label(1.875, 1.875), "2");
497 assert_eq!(s.label(1.875 + 0.46875, 0.46875), "2.2");
498 assert_eq!(s.to_units(0.9375), 2.0);
499 assert_eq!(s.step(true), 1.875);
500 let offset = TimeScale::Beats(Tempo::new(128.0, 4, 4).offset(0.46875));
502 assert_eq!(offset.format(0.46875), "1.1.000");
503 assert_eq!(offset.format(0.0), "0.4.000");
504 assert_eq!(offset.round_to(0.6, 0.46875), 0.46875);
505 }
506
507 #[test]
508 fn every_scale_formats_what_it_parses() {
509 for s in [
510 TimeScale::Seconds,
511 TimeScale::frames(25),
512 TimeScale::Frames(FrameRate::NTSC),
513 TimeScale::beats(128.0),
514 TimeScale::Beats(Tempo::new(90.0, 3, 4).offset(0.25)),
515 ] {
516 for t in [0.0, 0.04, 1.0, 12.48, 61.0, 3725.0] {
517 let t = s.quantize(t);
518 let back = s.parse(&s.format(t)).unwrap();
519 let tolerance = match s {
520 TimeScale::Beats(tempo) => tempo.beat() / f64::from(tempo.ticks_per_beat),
521 _ => 1e-3,
522 };
523 assert!((back - t).abs() <= tolerance, "{s:?} {t} -> {back}");
524 }
525 }
526 }
527
528 #[test]
529 fn steps_grow_and_land_on_units() {
530 for s in [
531 TimeScale::Seconds,
532 TimeScale::frames(25),
533 TimeScale::beats(128.0),
534 ] {
535 let steps = s.steps();
536 assert!(steps.windows(2).all(|w| w[0] < w[1]), "{s:?}");
537 for step in steps {
538 let units = s.to_units(s.origin() + step);
539 match s {
540 TimeScale::Frames(_) => assert!((units - units.round()).abs() < 1e-6),
541 TimeScale::Beats(_) => {
542 assert!((units * 16.0 - (units * 16.0).round()).abs() < 1e-6);
543 }
544 TimeScale::Seconds => {}
545 }
546 }
547 }
548 }
549}