Skip to main content

buffering_runtime/
time.rs

1//! Time on the public surface: a span is a [`Duration`], a position is a
2//! [`Clock27`].
3//!
4//! The controller keeps **two clocks**: the host's monotonic clock (arrival
5//! instants, ticks, timeouts) and the playback (PTS) domain (27 MHz tick
6//! positions, `PTS90k x 300`). The workspace has one type for each
7//! (`docs/API-CONVENTIONS.md`): a *span* of host time is
8//! [`core::time::Duration`], and a *position* in the playback domain is
9//! [`broadcast_common::clock33::Clock27`], the validated 27 MHz clock value
10//! that cannot hold a PCR extension or a wrap outside the clock. The
11//! controller itself computes host spans in whole microseconds, so it converts
12//! at its edge with [`instant_micros`] (or [`window_micros`] for a configured
13//! window) and back with [`micros_as_duration`].
14//!
15//! # Rounding
16//!
17//! One placeholder. A *reading* (a clock instant) or a *difference* of two is
18//! truncated to the microsecond it is in ([`instant_micros`]): rounding a
19//! reading up makes a logged "now" replay a microsecond in the future, and
20//! makes `ceil(a) - ceil(b)` disagree with `ceil(a - b)` by
21//! [`MAX_DIFFERENCE_ERROR`]. A *configured* window that must not become zero
22//! (a jitter window, a hold, a bucket) rounds up ([`window_micros`]), so a
23//! sub-microsecond setting is one microsecond rather than an empty window.
24//! This is the workspace's rule: floor a reading, raise only what a zero would
25//! make meaningless.
26
27use core::time::Duration;
28
29pub use broadcast_common::clock33::Clock27;
30
31/// Nanoseconds in a microsecond: a span is carried in whole microseconds.
32const NANOS_PER_MICRO: u128 = 1_000;
33const NANOS_PER_MICRO_U64: u64 = 1_000;
34
35/// The microsecond an instant names, truncated: the whole microsecond it falls
36/// in. A span too long for the microsecond range clamps to [`u64::MAX`].
37#[must_use]
38pub fn instant_micros(span: Duration) -> u64 {
39    let micros = span.as_nanos() / NANOS_PER_MICRO;
40    u64::try_from(micros).unwrap_or(u64::MAX)
41}
42
43/// The microseconds a configured window spans, rounded **up**.
44///
45/// This is the only rounding-up conversion: a sub-microsecond window is one
46/// microsecond, never zero, so a caller that set a 500 ns window cannot end up
47/// with a zero-length one. A span too long for the microsecond range clamps to
48/// [`u64::MAX`].
49#[must_use]
50pub fn window_micros(span: Duration) -> u64 {
51    let micros = span.as_nanos().div_ceil(NANOS_PER_MICRO);
52    u64::try_from(micros).unwrap_or(u64::MAX)
53}
54
55/// Whole microseconds as a [`Duration`].
56#[must_use]
57pub fn micros_as_duration(micros: u64) -> Duration {
58    Duration::from_micros(micros)
59}
60
61/// The most a difference of two truncated readings can understate the real one:
62/// each reading is floored by up to one microsecond less than it, and the two
63/// roundings cannot exceed this together.
64pub const MAX_DIFFERENCE_ERROR: Duration = Duration::from_nanos(NANOS_PER_MICRO_U64 - 1);
65
66/// `a + b` in whole microseconds, saturating at the end of the microsecond
67/// range rather than panicking on an overflow.
68#[must_use]
69pub fn duration_add(a: Duration, b: Duration) -> Duration {
70    micros_as_duration(instant_micros(a).saturating_add(instant_micros(b)))
71}
72
73/// The span from `earlier` to `later`, the whole microsecond it is in, zero
74/// when `later` is not after it (a span never goes backwards).
75#[must_use]
76pub fn duration_between(earlier: Duration, later: Duration) -> Duration {
77    micros_as_duration(instant_micros(later).saturating_sub(instant_micros(earlier)))
78}
79
80#[cfg(test)]
81mod tests {
82    use super::{
83        MAX_DIFFERENCE_ERROR, duration_between, instant_micros, micros_as_duration, window_micros,
84    };
85    use core::time::Duration;
86
87    #[test]
88    fn a_reading_is_the_microsecond_it_is_in() {
89        assert_eq!(instant_micros(Duration::ZERO), 0);
90        assert_eq!(instant_micros(Duration::from_nanos(1)), 0);
91        assert_eq!(instant_micros(Duration::from_nanos(999)), 0);
92        assert_eq!(instant_micros(Duration::from_nanos(1_000)), 1);
93        assert_eq!(instant_micros(Duration::from_nanos(1_999)), 1);
94        assert_eq!(instant_micros(Duration::from_secs(2)), 2_000_000);
95        assert_eq!(instant_micros(Duration::MAX), u64::MAX);
96        assert_eq!(micros_as_duration(1_800_000), Duration::from_millis(1_800));
97    }
98
99    #[test]
100    fn a_configured_window_rounds_up_to_whole_microseconds() {
101        assert_eq!(window_micros(Duration::ZERO), 0);
102        assert_eq!(window_micros(Duration::from_nanos(1)), 1);
103        assert_eq!(window_micros(Duration::from_nanos(999)), 1);
104        assert_eq!(window_micros(Duration::from_nanos(1_000)), 1);
105        assert_eq!(window_micros(Duration::from_secs(2)), 2_000_000);
106        assert_eq!(window_micros(Duration::MAX), u64::MAX);
107    }
108
109    #[test]
110    fn a_difference_is_the_whole_microsecond_between_two_readings() {
111        assert_eq!(
112            duration_between(Duration::from_nanos(1_500), Duration::from_nanos(3_500)),
113            Duration::from_micros(2),
114            "1 us to 3 us, not 2 us to 4 us"
115        );
116        assert!(
117            duration_between(Duration::from_nanos(1_500), Duration::from_nanos(3_500))
118                >= Duration::from_nanos(3_500) - Duration::from_nanos(1_500) - MAX_DIFFERENCE_ERROR
119        );
120    }
121
122    #[test]
123    fn a_backwards_span_is_zero_not_a_negative_duration() {
124        assert_eq!(
125            duration_between(Duration::from_millis(5), Duration::from_millis(2)),
126            Duration::ZERO
127        );
128    }
129
130    #[test]
131    fn a_position_is_a_checked_27mhz_clock_value() {
132        let p = super::Clock27::from_27mhz(27_000_000).expect("one second");
133        assert_eq!(p.ticks(), 27_000_000);
134    }
135}