Skip to main content

egui_pop_views/timeline/
scale.rs

1//! [`TimeScale`]: how a timeline counts time (seconds, frames with a
2//! timecode, bars and beats), converts it, writes it and spaces its ruler.
3//!
4//! Time itself is always an `f64` in seconds; a scale only reads it in its
5//! own units.
6
7use serde::{Deserialize, Serialize};
8
9/// A frame rate, `num / den` frames per second: `25 / 1`, `30000 / 1001`
10/// (29.97).
11#[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    /// Cinema, 24 frames per second.
19    pub const FILM: FrameRate = FrameRate::whole(24);
20    /// 25 frames per second.
21    pub const PAL: FrameRate = FrameRate::whole(25);
22    /// 29.97 frames per second (its timecode is counted without dropping
23    /// frames).
24    pub const NTSC: FrameRate = FrameRate::new(30000, 1001);
25
26    /// `num / den` frames per second; neither may be 0 (1 is taken).
27    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    /// A whole number of frames per second.
35    pub const fn whole(fps: u32) -> Self {
36        Self::new(fps, 1)
37    }
38
39    /// Frames per second.
40    pub fn fps(self) -> f64 {
41        f64::from(self.num.max(1)) / f64::from(self.den.max(1))
42    }
43
44    /// One frame, in seconds.
45    pub fn frame(self) -> f64 {
46        1.0 / self.fps()
47    }
48
49    /// The frames a timecode's second counts: the rate rounded (30 for
50    /// 29.97; the timecode does not drop frames).
51    pub fn nominal(self) -> u32 {
52        (self.fps().round() as u32).max(1)
53    }
54}
55
56/// A tempo and a time signature, for a timeline counted in bars and beats.
57#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
58pub struct Tempo {
59    /// Beats per minute.
60    pub bpm: f64,
61    /// The signature's upper number: beats in a bar.
62    pub beats_per_bar: u32,
63    /// The signature's lower number: the note a beat is (4, a quarter).
64    pub beat_unit: u32,
65    /// How finely a beat is divided in the text (`bar.beat.tick`).
66    pub ticks_per_beat: u32,
67    /// Where bar 1 starts, in seconds (a track's first downbeat).
68    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    /// `bpm` beats per minute, `beats_per_bar / beat_unit`, 960 ticks to a
79    /// beat, bar 1 at 0.
80    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    /// Bar 1 starts at `seconds`.
91    pub fn offset(mut self, seconds: f64) -> Self {
92        self.offset = seconds;
93        self
94    }
95
96    /// A beat divided in `ticks` in the text.
97    pub fn ticks_per_beat(mut self, ticks: u32) -> Self {
98        self.ticks_per_beat = ticks.max(1);
99        self
100    }
101
102    /// One beat, in seconds.
103    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    /// One bar, in seconds.
112    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/// How a timeline counts time: its ruler, its text, its steps and its grid.
126#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
127#[serde(rename_all = "snake_case")]
128pub enum TimeScale {
129    /// Seconds, written `1:02.500` (hours when there are some).
130    #[default]
131    Seconds,
132    /// Frames at a rate, written as a timecode `HH:MM:SS:FF`; a time on
133    /// this scale is always a whole frame.
134    Frames(FrameRate),
135    /// Bars and beats at a tempo, written `bar.beat.tick` from `1.1.000`.
136    Beats(Tempo),
137}
138
139/// Seconds' ruler steps up to an hour, then whole hours and days.
140const 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
145/// Whole seconds and above, for frames past a second.
146const 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    /// Frames at `fps` frames per second.
153    pub fn frames(fps: u32) -> Self {
154        TimeScale::Frames(FrameRate::whole(fps))
155    }
156
157    /// Bars of four beats at `bpm`.
158    pub fn beats(bpm: f64) -> Self {
159        TimeScale::Beats(Tempo::new(bpm, 4, 4))
160    }
161
162    /// Its name, for agents: `seconds`, `frames` or `beats`.
163    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    /// One of its units in seconds: a second, a frame, a beat.
172    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    /// A time in its units: seconds, frames, beats from bar 1.
181    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    /// A time given in its units, in seconds.
190    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    /// Where its grid starts: bar 1 for beats, 0 otherwise.
199    pub fn origin(&self) -> f64 {
200        match self {
201            TimeScale::Beats(t) => t.offset,
202            _ => 0.0,
203        }
204    }
205
206    /// What Left and Right move by: a second, a frame, a beat; with Shift
207    /// (`big`), ten seconds, a timecode second, a bar.
208    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    /// The time it can hold nearest to `seconds`: the nearest whole frame on
220    /// frames, the time itself otherwise.
221    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    /// The line of a grid `step` apart nearest to `seconds` (the grid starts
229    /// at [`origin`](Self::origin)).
230    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    /// The ruler's steps from the finest to the coarsest, in seconds; each
239    /// lands on the scale's units (whole frames, divisions of a beat, bars).
240    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                // A timecode second is `nominal` frames.
252                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    /// The full text of a time: `1:02.500`, `00:01:02:12`, `17.2.480`.
277    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    /// A ruler's label for a time on a grid `step` apart: no more digits
286    /// than the step needs (`0:05`, `0:05.5`; `17`, `17.2`).
287    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    /// Reads a time written as [`format`](Self::format) writes it (fewer
306    /// fields too: `1:02`, `12.5` seconds; `17.2` for bar 17, beat 2).
307    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/// How finely `bar.beat.tick` is written.
353#[derive(Clone, Copy, PartialEq, Eq)]
354enum Precision {
355    Bar,
356    Beat,
357    Tick,
358}
359
360/// The decimals a grid `step` seconds apart needs: 0 from a second, 1 for
361/// 0.5 or 0.1, 2 for 0.05.
362fn 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
369/// Seconds as a clock, `m:ss` or `h:mm:ss`, with `decimals` after the
370/// seconds.
371fn 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
392/// `h:m:s.f`, `m:s.f` or `s.f`, in seconds.
393fn 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
414/// A timecode, `HH:MM:SS:FF`, counted in nominal frames per second.
415fn 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
430/// `bar.beat.tick` from 1, as finely as `precision`.
431fn 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        // 29.97 counts 30 frames to its timecode's second.
482        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        // 128 BPM: a beat is 0.46875 s, a bar of four 1.875 s.
490        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        // A first downbeat later in the track moves bar 1 there.
501        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}