Skip to main content

broadcast_common/
clock33.rs

1//! Generic 33-bit wrapping-clock helpers.
2//!
3//! ISO/IEC 13818-1 §2.4.3.7 samples a 90 kHz clock into a 33-bit PTS/DTS
4//! field; ANSI/SCTE 35 §9.2 `pts_time` reuses the identical 2^33 modulus so a
5//! splice cue can be compared against the same clock. Both wrap roughly every
6//! 26.5 hours, and any long-lived consumer that needs an ever-growing
7//! timeline, or just needs to compare two nearby samples correctly across a
8//! wrap boundary, needs the same handful of primitives. Before this module
9//! existed, four crates (`timed-metadata`, `transmux`, `media-doctor`,
10//! `compliance-probe`) each hand-rolled their own copy; an overrun or
11//! wrap-direction fix in one reached none of the others. This module is now
12//! the single owner both algorithms live in.
13//!
14//! `transmux` (a container-muxing hub) cannot take a dependency on
15//! `timed-metadata` (a DPI/timed-metadata *signalling* conversion crate several
16//! layers up the stack, pulling in `scte35-splice`/`mp4-emsg`) without an
17//! inverted, heavy dependency edge, and the primitive itself has no
18//! dependencies of its own — so it lives here, in the crate every one of the
19//! four already depends on, rather than promoting one sibling to depend on
20//! another.
21//!
22//! The values themselves are [`Clock33`] (a validated 33-bit 90 kHz sample) and
23//! [`Clock27`] (a validated 27 MHz `base * 300 + ext`), so `mpeg-ts`'s `Pcr`,
24//! `mpeg-ps`'s `Scr` and `mpeg-pes`'s `Pts`/`Dts` are all this one pair rather
25//! than separate unchecked copies.
26//!
27//! Beyond the two validated types, two independent operations live here,
28//! because they answer different questions and must not be collapsed into
29//! one:
30//!
31//! - [`unwrap_delta`] — extend a running **unwrapped** (ever-growing, signed)
32//!   accumulator by the next raw sample, correcting for exactly one wrap in
33//!   *either* direction. Used to turn a repeating hardware counter into an
34//!   absolute timeline (PTS/DTS unrolling across a capture, including
35//!   B-frame reordering that dips slightly backward without crossing a
36//!   wrap).
37//! - [`pcr_forward_distance`] / [`pcr_signed_distance`] / [`pcr_from_parts`] /
38//!   [`pcr_split`] — the same modular arithmetic for the 27 MHz PCR clock
39//!   (`base * 300 + extension`, wrapping at `2^33 * 300`, which is *not* a power
40//!   of two, so `wrapping_sub(..) % M` is wrong across a wrap).
41//! - [`wrapping_forward_distance`] — the modular forward distance from one
42//!   already-comparable raw value to another, with no accumulator or history
43//!   at all. Used to classify a single pair of values as "in order" vs
44//!   "wrapped/out of order" when the caller already knows the two are
45//!   supposed to be close in time (e.g. a decode-order monotonicity check,
46//!   or a splice cue's `pts_time` judged against a reference "now").
47
48/// The 33-bit modulus (2^33) shared by MPEG-2 Systems PTS/DTS (ISO/IEC
49/// 13818-1 §2.4.3.7) and SCTE-35 `pts_time` (ANSI/SCTE 35 §9.2) — both a
50/// 90 kHz clock sampled into a 33-bit field.
51pub const WRAP_33BIT: u64 = 1 << 33;
52
53/// Half of [`WRAP_33BIT`] — the threshold distinguishing a genuine backward
54/// step from a legal wrap.
55pub const WRAP_33BIT_HALF: u64 = WRAP_33BIT / 2;
56
57/// Extend a running unwrapped 33-bit clock by the delta to the next raw
58/// value, correcting for a single wrap in either direction.
59///
60/// The delta is computed on the wrapped clock (a signed value in
61/// `(-2^32, 2^32]`; a step of exactly half the range resolves forward, the
62/// same tie rule as [`signed_distance`]), then applied to the unwrapped accumulator — so an
63/// ordinary small backward step (e.g. B-frame PTS reordering) is preserved
64/// as-is, and only a near-full-range jump is treated as a wrap.
65/// `prev_unwrapped` need not itself be in `[0, 2^33)`; after the first wrap
66/// it grows (or, in a reorder that dips across the origin before any wrap
67/// has happened, can go slightly negative) without bound.
68///
69/// This is deliberately **bidirectional**: a naive "epoch counter that only
70/// ever increments" unroller (which is what this replaced in
71/// `timed-metadata`) gets a rare-but-real case wrong — a small backward
72/// reorder that happens to straddle the wrap boundary (e.g. previous raw `2`,
73/// next raw `2^33 - 3`, a legitimate 5-tick backward step) is
74/// indistinguishable, from an epoch-counter's point of view, from a huge
75/// forward jump, and it reports the latter. Computing the delta first and
76/// only then deciding whether it wrapped gets both directions right.
77#[must_use]
78pub fn unwrap_delta(prev_unwrapped: i128, prev_raw: u64, raw: u64) -> i128 {
79    let mut delta = raw as i128 - prev_raw as i128;
80    if delta > WRAP_33BIT_HALF as i128 {
81        delta -= WRAP_33BIT as i128; // wrapped backward across 2^33
82    } else if delta <= -(WRAP_33BIT_HALF as i128) {
83        delta += WRAP_33BIT as i128; // wrapped forward across 2^33
84    }
85    prev_unwrapped + delta
86}
87
88/// The modular forward distance from `from` to `to` on the 33-bit clock:
89/// `(to - from) mod 2^33`, always in `[0, 2^33)`.
90///
91/// A distance greater than [`WRAP_33BIT_HALF`] means `to` is "behind" `from`
92/// on the wrapped clock, not genuinely more than `2^32` ticks ahead — the
93/// same wrap-vs-past ambiguity [`unwrap_delta`] resolves using history; this
94/// function resolves it using only the half-range convention (no state),
95/// which is enough when the caller already knows the two values are
96/// supposed to be close in time.
97#[must_use]
98pub fn wrapping_forward_distance(from: u64, to: u64) -> u64 {
99    to.wrapping_sub(from) % WRAP_33BIT
100}
101
102/// `(a + b) mod 2^33` — e.g. an SCTE-35 `pts_time` shifted by its
103/// `pts_adjustment`: `add(WRAP_33BIT - 1, 1) == 0`, and inputs at or above
104/// the modulus are reduced first, so `add(WRAP_33BIT + 3, 0) == 3`.
105#[must_use]
106pub fn add(a: u64, b: u64) -> u64 {
107    let a = a % WRAP_33BIT;
108    let b = b % WRAP_33BIT;
109    // Each reduced operand is < 2^33, so the sum cannot overflow a u64.
110    (a + b) % WRAP_33BIT
111}
112
113/// `(a + delta) mod 2^33` where `delta` may be negative; the result is always
114/// in `[0, 2^33)` — e.g. stepping five ticks back past zero wraps forward:
115/// `add_signed(5, -10) == WRAP_33BIT - 5`.
116#[must_use]
117pub fn add_signed(a: u64, delta: i64) -> u64 {
118    // i128 intermediates: `delta` alone can be `i64::MIN`, and the sum must
119    // not wrap before the Euclidean reduction.
120    let sum = i128::from(a % WRAP_33BIT) + i128::from(delta);
121    let reduced = sum.rem_euclid(i128::from(WRAP_33BIT));
122    // `rem_euclid` by 2^33 is in `[0, 2^33)`, so the cast is lossless.
123    reduced as u64
124}
125
126/// The shortest signed distance from `from` to `to` on the 2^33 circle, in
127/// `(-2^32, 2^32]` — e.g. crossing the wrap forward reads as a small positive
128/// step, `signed_distance(WRAP_33BIT - 10, 5) == 15`, while stepping back
129/// across it reads negative, `signed_distance(5, WRAP_33BIT - 10) == -15`.
130#[must_use]
131pub fn signed_distance(from: u64, to: u64) -> i64 {
132    let forward = wrapping_forward_distance(from % WRAP_33BIT, to % WRAP_33BIT);
133    if forward <= WRAP_33BIT_HALF {
134        forward as i64 // `forward <= 2^32`: lossless
135    } else {
136        let back = WRAP_33BIT - forward;
137        // `back` is in `[1, 2^32)` here, so the negation cannot overflow.
138        -(back as i64)
139    }
140}
141
142// ── 27 MHz PCR clock (ISO/IEC 13818-1 §2.4.3.5) ─────────────────────────────
143
144/// MPEG-2 Systems 90 kHz system-clock rate: the unit of PTS/DTS and of the
145/// 33-bit PCR/ESCR/SCR *base* (ISO/IEC 13818-1 §2.4.3.5 / §2.4.3.7).
146pub const PTS_HZ: u64 = PTS_TIMESCALE.as_u64();
147
148/// [`PTS_HZ`] as a [`Timescale`](crate::timescale::Timescale).
149pub const PTS_TIMESCALE: crate::timescale::Timescale = crate::timescale!(90_000);
150
151/// The 27 MHz system-clock rate: the unit of a full `PCR` (`base * 300 +
152/// extension`), ESCR and SCR value (ISO/IEC 13818-1 §2.4.2.1 / §2.4.3.5).
153pub const PCR_HZ: u64 = PCR_TIMESCALE.as_u64();
154
155/// [`PCR_HZ`] as a [`Timescale`](crate::timescale::Timescale).
156pub const PCR_TIMESCALE: crate::timescale::Timescale = crate::timescale!(27_000_000);
157
158/// `base * 300 + extension`: how many 27 MHz ticks one 90 kHz base tick spans
159/// (`PCR_HZ / PTS_HZ`), and the modulus of the 9-bit `extension`.
160pub const PCR_EXT_MODULUS: u64 = PCR_HZ / PTS_HZ;
161
162/// The wrap period of a full PCR on the 27 MHz clock: `2^33 * 300` ticks
163/// (~26.5 h). It is NOT a power of two, so a wrapped difference computed with
164/// `u64::wrapping_sub(..) % PCR_WRAP_27MHZ` is wrong whenever the PCR wraps or
165/// steps backward (2^64 is not a multiple of this modulus, so the u64 wrap
166/// contributes a bogus `2^64 mod PCR_WRAP_27MHZ` offset): use
167/// [`pcr_forward_distance`] / [`pcr_signed_distance`].
168pub const PCR_WRAP_27MHZ: u64 = WRAP_33BIT * PCR_EXT_MODULUS;
169
170/// A full 27 MHz clock value from its parts: `base * 300 + extension`
171/// (ISO/IEC 13818-1 §2.4.3.5; the same arithmetic as ESCR §2.4.3.7 and the
172/// program-stream SCR §2.5.3.4). Wrapping arithmetic: an out-of-range `base`
173/// (wider than 33 bits) yields a meaningless value rather than a panic, like
174/// every parser-fed helper in this crate.
175#[must_use]
176pub const fn pcr_from_parts(base: u64, extension: u16) -> u64 {
177    base.wrapping_mul(PCR_EXT_MODULUS)
178        .wrapping_add(extension as u64)
179}
180
181/// Split a 27 MHz clock value into `(base, extension)`: `base = ticks / 300`
182/// truncated to its 33-bit wire width, `extension = ticks % 300` (always < 300,
183/// so it fits the 9-bit field). Round-trips with [`pcr_from_parts`] for any
184/// `ticks < PCR_WRAP_27MHZ`.
185#[must_use]
186pub const fn pcr_split(ticks: u64) -> (u64, u16) {
187    (
188        (ticks / PCR_EXT_MODULUS) & (WRAP_33BIT - 1),
189        (ticks % PCR_EXT_MODULUS) as u16,
190    )
191}
192
193/// The modular forward distance from `from` to `to` on the 27 MHz PCR clock:
194/// `(to - from) mod 2^33*300`, always in `[0, PCR_WRAP_27MHZ)`. Inputs at or
195/// above the modulus are reduced first. This is the PCR analogue of
196/// [`wrapping_forward_distance`] and the only correct way to take a PCR delta
197/// across a wrap (see [`PCR_WRAP_27MHZ`] for why `wrapping_sub` is not).
198#[must_use]
199pub fn pcr_forward_distance(from: u64, to: u64) -> u64 {
200    // Both reduced operands are < M < 2^42, so `to + M - from` cannot overflow.
201    (to % PCR_WRAP_27MHZ + PCR_WRAP_27MHZ - from % PCR_WRAP_27MHZ) % PCR_WRAP_27MHZ
202}
203
204/// The shortest signed distance from `from` to `to` on the PCR circle, in
205/// `(-PCR_WRAP_27MHZ/2, PCR_WRAP_27MHZ/2]`: a forward wrap reads as a small
206/// positive step, a small backward step (also across the wrap) as negative.
207#[must_use]
208pub fn pcr_signed_distance(from: u64, to: u64) -> i64 {
209    let forward = pcr_forward_distance(from, to);
210    if forward <= PCR_WRAP_27MHZ / 2 {
211        forward as i64 // `forward <= M/2 < 2^41`: lossless
212    } else {
213        -((PCR_WRAP_27MHZ - forward) as i64) // in `[1, M/2)`: lossless
214    }
215}
216
217// ── 5-byte marker-bit timestamp (PTS / DTS / DTS_next_AU) ───────────────────
218
219/// All three `marker_bit`s of a 5-byte marked timestamp set to `1` (the value
220/// every PES `PTS`/`DTS` must carry, ISO/IEC 13818-1 §2.4.3.7).
221pub const MARKERS_ALL_SET: u8 = 0b111;
222
223/// A decoded 5-byte marker-bit timestamp field.
224///
225/// Wire layout (ISO/IEC 13818-1 §2.4.3.7 Table 2-21 `PTS`/`DTS`; §2.4.3.5
226/// `DTS_next_AU` uses the same shape): `prefix(4) ts[32:30](3) marker(1)
227/// ts[29:15](15) marker(1) ts[14:0](15) marker(1)`.
228#[derive(Clone, Copy, Debug, PartialEq, Eq)]
229pub struct Marked {
230    /// The leading 4 bits (`0b0010` PTS-only, `0b0011` PTS-with-DTS, `0b0001`
231    /// DTS, or a seamless-splice `splice_type`).
232    pub prefix: u8,
233    /// The 33-bit timestamp.
234    pub timestamp: u64,
235    /// The three `marker_bit`s: bit 2 = byte 0 bit 0, bit 1 = byte 2 bit 0,
236    /// bit 0 = byte 4 bit 0. A conformant field is [`MARKERS_ALL_SET`].
237    pub markers: u8,
238}
239
240/// Decode a 5-byte marker-bit timestamp field. Never fails: the caller
241/// validates `prefix` and `markers` against its own spec clause and maps a
242/// mismatch into its own error type.
243#[must_use]
244pub fn unpack_marked(b: &[u8; 5]) -> Marked {
245    let hi = u64::from((b[0] >> 1) & 0x07); // [32:30]
246    let mid = (u64::from(b[1]) << 7) | u64::from(b[2] >> 1); // [29:15]
247    let lo = (u64::from(b[3]) << 7) | u64::from(b[4] >> 1); // [14:0]
248    Marked {
249        prefix: b[0] >> 4,
250        timestamp: (hi << 30) | (mid << 15) | lo,
251        markers: ((b[0] & 1) << 2) | ((b[2] & 1) << 1) | (b[4] & 1),
252    }
253}
254
255/// Encode a 5-byte marker-bit timestamp field with explicit marker bits (see
256/// [`Marked::markers`]); `timestamp` is reduced modulo 2^33 and only the low
257/// nibble of `prefix` / low 3 bits of `markers` are used (the wire widths).
258#[must_use]
259pub fn pack_marked_with(timestamp: u64, prefix: u8, markers: u8) -> [u8; 5] {
260    let ts = timestamp & (WRAP_33BIT - 1);
261    [
262        ((prefix & 0x0F) << 4) | ((((ts >> 30) & 0x07) as u8) << 1) | ((markers >> 2) & 1),
263        ((ts >> 22) & 0xFF) as u8,
264        ((((ts >> 15) & 0x7F) as u8) << 1) | ((markers >> 1) & 1),
265        ((ts >> 7) & 0xFF) as u8,
266        (((ts & 0x7F) as u8) << 1) | (markers & 1),
267    ]
268}
269
270/// Encode a conformant PTS/DTS field: every `marker_bit` set to `1`.
271#[must_use]
272pub fn pack_marked(timestamp: u64, prefix: u8) -> [u8; 5] {
273    pack_marked_with(timestamp, prefix, MARKERS_ALL_SET)
274}
275
276// ── Validated clock values ──────────────────────────────────────────────────
277
278/// A clock reading that does not fit the field it is carried in: a 33-bit
279/// PTS/DTS/`pts_time` sample, or a 27 MHz PCR/ESCR/SCR base (beyond the
280/// `2^33 * 300` wrap) or extension (`>= 300`).
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282#[non_exhaustive]
283pub struct ClockOutOfRange {
284    /// Which field was rejected: `"33-bit ticks"`, `"27 MHz base"`,
285    /// `"27 MHz extension"` or `"27 MHz ticks"`.
286    pub field: &'static str,
287    /// The rejected value, widened to `u64` for reporting.
288    pub value: u64,
289}
290
291impl core::fmt::Display for ClockOutOfRange {
292    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
293        write!(f, "{} value {} is out of range", self.field, self.value)
294    }
295}
296
297impl core::error::Error for ClockOutOfRange {}
298
299impl ClockOutOfRange {
300    /// A rejected 27 MHz base: a value at or above the 33-bit wire width.
301    ///
302    /// The constructors here never produce one (a base is either already a
303    /// [`Clock33`] or checked by [`Clock27::from_parts`]); a type that kept
304    /// wire parts unvalidated reports an over-wide base with this.
305    #[must_use]
306    pub const fn base(value: u64) -> Self {
307        Self {
308            field: "27 MHz base",
309            value,
310        }
311    }
312}
313
314/// A validated 33-bit 90 kHz clock sample (PTS, DTS, SCTE-35 `pts_time`).
315///
316/// ISO/IEC 13818-1 §2.4.3.7 samples the 90 kHz system clock into a 33-bit
317/// field. This type is that value *after* the wire: always in `[0, 2^33)`, so
318/// the modular helpers here never have to reduce their input and a caller
319/// cannot hand them a value that silently wraps somewhere else. `mpeg-pes`'s
320/// `Pts`/`Dts`, SCTE-35's `pts_time`/`pts_adjustment` and `timed-metadata`'s
321/// timeline all carry this type.
322///
323/// `Default` is the origin (`0`). [`From<Clock33> for u64`], [`TryFrom<u64>`]
324/// and [`TryFrom<i64>`] convert.
325#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
326#[cfg_attr(feature = "serde", derive(serde::Serialize))]
327#[cfg_attr(feature = "serde", serde(transparent))]
328pub struct Clock33(u64);
329
330impl Clock33 {
331    /// The origin of the clock (`0`).
332    pub const ZERO: Self = Self(0);
333
334    /// Construct from a raw tick count, rejecting any value at or above
335    /// [`WRAP_33BIT`].
336    ///
337    /// # Errors
338    /// [`ClockOutOfRange`] (`field: "33-bit ticks"`) when `ticks >= 2^33`.
339    pub const fn try_new(ticks: u64) -> Result<Self, ClockOutOfRange> {
340        if ticks >= WRAP_33BIT {
341            Err(ClockOutOfRange {
342                field: "33-bit ticks",
343                value: ticks,
344            })
345        } else {
346            Ok(Self(ticks))
347        }
348    }
349
350    /// The raw tick count, always in `[0, 2^33)`.
351    #[must_use]
352    pub const fn ticks(self) -> u64 {
353        self.0
354    }
355
356    /// `(self + b) mod 2^33` — see [`add`].
357    #[must_use]
358    pub const fn wrapping_add(self, b: Self) -> Self {
359        // Both operands are < 2^33, so the sum cannot overflow a u64.
360        Self((self.0 + b.0) % WRAP_33BIT)
361    }
362
363    /// `(self + delta) mod 2^33` for a possibly negative step — see
364    /// [`add_signed`].
365    #[must_use]
366    pub fn wrapping_add_signed(self, delta: i64) -> Self {
367        Self(add_signed(self.0, delta))
368    }
369
370    /// The shortest signed distance from `self` to `to` — see
371    /// [`signed_distance`].
372    #[must_use]
373    pub fn signed_distance_to(self, to: Self) -> i64 {
374        signed_distance(self.0, to.0)
375    }
376}
377
378impl From<Clock33> for u64 {
379    fn from(c: Clock33) -> Self {
380        c.0
381    }
382}
383
384impl TryFrom<u64> for Clock33 {
385    type Error = ClockOutOfRange;
386    fn try_from(ticks: u64) -> Result<Self, Self::Error> {
387        Self::try_new(ticks)
388    }
389}
390
391impl TryFrom<i64> for Clock33 {
392    type Error = ClockOutOfRange;
393    fn try_from(ticks: i64) -> Result<Self, Self::Error> {
394        // A negative sample cannot name a position on the clock: report the
395        // magnitude, which is the width that matters.
396        Self::try_new(ticks.unsigned_abs())
397    }
398}
399
400impl core::fmt::Debug for Clock33 {
401    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
402        write!(f, "Clock33({})", self.0)
403    }
404}
405
406impl core::fmt::Display for Clock33 {
407    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
408        write!(f, "{}", self.0)
409    }
410}
411
412/// A validated 27 MHz clock value: `base * 300 + ext` (ISO/IEC 13818-1
413/// §2.4.3.5 PCR, §2.4.3.7 ESCR, §2.5.3.4 program-stream SCR).
414///
415/// Construction ([`from_parts`](Self::from_parts),
416/// [`from_27mhz`](Self::from_27mhz)) keeps `ext < 300`, so a value built that
417/// way is always in `[0, PCR_WRAP_27MHZ)`. A *parsed* field may carry a 9-bit
418/// extension in `300..=511` (off the clock): [`from_wire_parts`](Self::from_wire_parts)
419/// keeps it losslessly and [`to_clock27`](Self::to_clock27) is the checked way
420/// to use it. This is the one representation of a PCR/ESCR/SCR: `mpeg-ts`'s
421/// `Pcr` and `mpeg-ps`'s `Scr` wrap it and add only their wire codecs.
422#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
423pub struct Clock27 {
424    /// The 33-bit base (27 MHz ticks / 300).
425    pub base: Clock33,
426    /// The 9-bit extension (27 MHz ticks within the current base tick).
427    pub ext: u16,
428}
429
430/// Serializes as the 27 MHz tick count: a PCR is stored as the one number
431/// its wire fields code, so a snapshot survives the lossless `from_wire_parts`
432/// round trip.
433#[cfg(feature = "serde")]
434impl serde::Serialize for Clock27 {
435    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
436        s.serialize_u64(self.ticks())
437    }
438}
439
440impl Clock27 {
441    /// Construct from the two wire parts, checking both widths.
442    ///
443    /// # Errors
444    /// [`ClockOutOfRange`] when `base >= 2^33` (`field: "27 MHz base"`) or
445    /// `ext >= 300` (`field: "27 MHz extension"`).
446    pub const fn from_parts(base: u64, ext: u16) -> Result<Self, ClockOutOfRange> {
447        let base = match Clock33::try_new(base) {
448            Ok(base) => base,
449            Err(_) => {
450                return Err(ClockOutOfRange {
451                    field: "27 MHz base",
452                    value: base,
453                });
454            }
455        };
456        if ext >= PCR_EXT_MODULUS as u16 {
457            return Err(ClockOutOfRange {
458                field: "27 MHz extension",
459                value: ext as u64,
460            });
461        }
462        Ok(Self { base, ext })
463    }
464
465    /// Split an absolute 27 MHz value into its two wire parts, the inverse of
466    /// [`from_parts`](Self::from_parts) for any `ticks < PCR_WRAP_27MHZ`.
467    ///
468    /// # Errors
469    /// [`ClockOutOfRange`] (`field: "27 MHz ticks"`) when
470    /// `ticks >= PCR_WRAP_27MHZ`.
471    pub fn from_27mhz(ticks: u64) -> Result<Self, ClockOutOfRange> {
472        if ticks >= PCR_WRAP_27MHZ {
473            return Err(ClockOutOfRange {
474                field: "27 MHz ticks",
475                value: ticks,
476            });
477        }
478        let (base, ext) = pcr_split(ticks);
479        // `ticks < PCR_WRAP_27MHZ` puts both parts in range by construction.
480        Self::from_parts(base, ext)
481    }
482
483    /// The position `ticks` names on the 27 MHz clock, taking any count:
484    /// `ticks` itself when it is below [`PCR_WRAP_27MHZ`], and `ticks`
485    /// reduced modulo the wrap otherwise (a reading from a free-running counter
486    /// that has passed the wrap).
487    ///
488    /// Infallible: the reduction puts both wire parts in range, so this is the
489    /// constructor for a raw count that may be past the wrap, and
490    /// [`from_27mhz`](Self::from_27mhz) the checked one that reports it.
491    #[must_use]
492    pub const fn from_27mhz_wrapping(ticks: u64) -> Self {
493        let (base, ext) = pcr_split(ticks % PCR_WRAP_27MHZ);
494        Self {
495            // `ticks % PCR_WRAP_27MHZ` is 33 bits (base) times 300 (ext), so
496            // both parts are in range by construction.
497            base: Clock33(base),
498            ext,
499        }
500    }
501
502    /// The full value on the 27 MHz clock: `base * 300 + ext`.
503    ///
504    /// A constructed value is a real time reading. For a value from
505    /// [`from_wire_parts`](Self::from_wire_parts) with an extension at or above
506    /// 300 this is not a time on the clock, so callers check
507    /// [`is_valid`](Self::is_valid) or [`to_clock27`](Self::to_clock27) first.
508    #[must_use]
509    pub const fn ticks(self) -> u64 {
510        pcr_from_parts(self.base.ticks(), self.ext)
511    }
512
513    /// The value in seconds.
514    #[must_use]
515    pub fn seconds(self) -> f64 {
516        self.ticks() as f64 / PCR_HZ as f64
517    }
518
519    /// The shortest signed distance from `self` to `to` — see
520    /// [`pcr_signed_distance`].
521    #[must_use]
522    pub fn signed_distance_to(self, to: Self) -> i64 {
523        pcr_signed_distance(self.ticks(), to.ticks())
524    }
525
526    /// Wrap the two parts exactly as the **wire** carried them, without
527    /// validating.
528    ///
529    /// A PCR/ESCR/SCR field is 33-bit base + 9-bit extension, so real
530    /// captures do carry extensions in `300..=511` — a value off the 27 MHz
531    /// clock that this type cannot hold. Parsing must stay lossless (the
532    /// workspace's byte-exact round-trip invariant), so a parser uses this to
533    /// keep the wire bytes, and a caller that needs a real clock reading asks
534    /// [`to_clock27`](Self::to_clock27) for the checked view.
535    ///
536    /// Code that *constructs* a clock value uses [`from_parts`](Self::from_parts)
537    /// instead, which rejects those parts.
538    #[must_use]
539    pub const fn from_wire_parts(base: u64, ext: u16) -> Self {
540        Self {
541            // The 33-bit field cannot exceed the clock's range; the wire
542            // width, not validation, decides here.
543            base: Clock33(base & (WRAP_33BIT - 1)),
544            ext,
545        }
546    }
547
548    /// The checked view of these parts: `Ok` when they name a position on the
549    /// 27 MHz clock.
550    ///
551    /// # Errors
552    /// [`ClockOutOfRange`] when `ext >= 300`. The base is always a [`Clock33`],
553    /// so it cannot be out of range.
554    pub const fn to_clock27(self) -> Result<Self, ClockOutOfRange> {
555        if self.ext >= PCR_EXT_MODULUS as u16 {
556            Err(ClockOutOfRange {
557                field: "27 MHz extension",
558                value: self.ext as u64,
559            })
560        } else {
561            Ok(self)
562        }
563    }
564
565    /// Whether [`ticks`](Self::ticks) is `base * 300 + ext` (an extension
566    /// below 300) rather than a wire value off the 27 MHz clock.
567    #[must_use]
568    pub const fn is_valid(self) -> bool {
569        self.ext < PCR_EXT_MODULUS as u16
570    }
571}
572
573impl From<Clock27> for u64 {
574    fn from(c: Clock27) -> Self {
575        c.ticks()
576    }
577}
578
579impl core::fmt::Debug for Clock27 {
580    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
581        write!(f, "Clock27({})", self.ticks())
582    }
583}
584
585impl core::fmt::Display for Clock27 {
586    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
587        write!(f, "{}", self.ticks())
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    #[test]
596    fn unwrap_delta_half_range_step_agrees_with_signed_distance() {
597        let step = signed_distance(WRAP_33BIT_HALF, 0);
598        assert_eq!(step, WRAP_33BIT_HALF as i64);
599        assert_eq!(unwrap_delta(0, WRAP_33BIT_HALF, 0), i128::from(step));
600        assert_eq!(unwrap_delta(0, 0, WRAP_33BIT_HALF), i128::from(step));
601    }
602
603    #[test]
604    fn unwrap_delta_forward_wrap_advances_by_one_modulus() {
605        // prev near the top of the range, next small: a legitimate forward
606        // wrap of +8 ticks, not a ~2^33-tick backward jump.
607        let prev_unwrapped = (WRAP_33BIT - 10) as i128;
608        let got = unwrap_delta(prev_unwrapped, WRAP_33BIT - 10, 5);
609        assert_eq!(got, prev_unwrapped + 15);
610        assert_eq!(got, 5 + WRAP_33BIT as i128);
611    }
612
613    #[test]
614    fn unwrap_delta_small_forward_step_is_identity_shift() {
615        assert_eq!(unwrap_delta(1_000, 1_000, 2_000), 2_000);
616    }
617
618    #[test]
619    fn unwrap_delta_small_backward_step_is_preserved_not_wrapped() {
620        // Ordinary B-frame reordering: a small backward step within an
621        // epoch must NOT be treated as a wrap.
622        assert_eq!(unwrap_delta(2_000, 2_000, 1_995), 1_995);
623    }
624
625    /// MUTATION-PROOF: a reorder that straddles the origin (previous raw
626    /// value small, next raw value near the top of the range, representing a
627    /// genuine small *backward* step across 0) must unwrap to a small
628    /// negative delta, not a huge forward jump. This is exactly the case a
629    /// naive forward-only epoch counter (what `timed_metadata::Timeline`
630    /// used before this module existed) gets wrong. Verified by temporarily
631    /// deleting the `delta > WRAP_33BIT_HALF` branch below (so only forward
632    /// wraps are corrected): this test then fails with `got = 2^33 - 3`
633    /// instead of `-3`, confirming the branch is load-bearing. Restored.
634    #[test]
635    fn unwrap_delta_backward_reorder_across_origin_stays_small_and_negative() {
636        let got = unwrap_delta(2, 2, WRAP_33BIT - 3);
637        assert_eq!(got, -3);
638    }
639
640    #[test]
641    fn wrapping_forward_distance_small_forward_is_small() {
642        assert_eq!(wrapping_forward_distance(100, 105), 5);
643    }
644
645    #[test]
646    fn wrapping_forward_distance_wraps_at_modulus() {
647        assert_eq!(wrapping_forward_distance(WRAP_33BIT - 1, 0), 1);
648    }
649
650    #[test]
651    fn wrapping_forward_distance_backward_step_is_large() {
652        // A backward step of 5 reports as (modulus - 5): a huge forward
653        // distance, which callers threshold against `WRAP_33BIT_HALF` to
654        // classify as "actually behind", not "far ahead".
655        let d = wrapping_forward_distance(105, 100);
656        assert_eq!(d, WRAP_33BIT - 5);
657        assert!(d > WRAP_33BIT_HALF);
658    }
659
660    #[test]
661    fn add_wraps_at_modulus() {
662        assert_eq!(add(WRAP_33BIT - 1, 1), 0);
663        assert_eq!(add(WRAP_33BIT - 10, 20), 10);
664    }
665
666    #[test]
667    fn add_reduces_inputs_at_or_above_the_modulus() {
668        assert_eq!(add(WRAP_33BIT + 3, 0), 3);
669    }
670
671    #[test]
672    fn add_signed_negative_delta_wraps_below_zero() {
673        assert_eq!(add_signed(5, -10), WRAP_33BIT - 5);
674    }
675
676    #[test]
677    fn add_signed_extreme_deltas_stay_in_range() {
678        for delta in [i64::MIN, i64::MAX] {
679            let got = add_signed(0, delta);
680            assert!(
681                got < WRAP_33BIT,
682                "add_signed(0, {delta}) = {got} escaped [0, 2^33)"
683            );
684        }
685    }
686
687    #[test]
688    fn signed_distance_matches_doc_examples() {
689        assert_eq!(signed_distance(WRAP_33BIT - 10, 5), 15);
690        assert_eq!(signed_distance(5, WRAP_33BIT - 10), -15);
691    }
692
693    #[test]
694    fn signed_distance_half_range_boundary_is_positive() {
695        // The range is (-2^32, 2^32]: exactly half the modulus reads as +2^32,
696        // one tick past it flips to the negative shortest path.
697        assert_eq!(signed_distance(0, WRAP_33BIT_HALF), WRAP_33BIT_HALF as i64);
698        assert_eq!(
699            signed_distance(0, WRAP_33BIT_HALF + 1),
700            -((WRAP_33BIT_HALF - 1) as i64)
701        );
702    }
703
704    #[test]
705    fn signed_distance_reduces_inputs_at_or_above_the_modulus() {
706        assert_eq!(signed_distance(WRAP_33BIT + 5, WRAP_33BIT + 8), 3);
707    }
708    #[test]
709    fn clock33_rejects_every_out_of_width_value() {
710        assert_eq!(
711            Clock33::try_new(WRAP_33BIT - 1),
712            Ok(Clock33(WRAP_33BIT - 1))
713        );
714        for bad in [WRAP_33BIT, WRAP_33BIT + 1, u64::MAX] {
715            let err = Clock33::try_new(bad).unwrap_err();
716            assert_eq!((err.field, err.value), ("33-bit ticks", bad));
717            assert_eq!(Clock33::try_from(bad).unwrap_err(), err);
718        }
719        assert_eq!(Clock33::try_from(7u64), Ok(Clock33(7)));
720        assert_eq!(Clock33::try_from(0u64), Ok(Clock33::ZERO));
721    }
722
723    #[test]
724    fn clock33_arithmetic_wraps_and_agrees_with_the_free_functions() {
725        let top = Clock33::try_new(WRAP_33BIT - 1).expect("in range");
726        let one = Clock33::try_new(1).expect("in range");
727        assert_eq!(top.wrapping_add(one), Clock33::ZERO);
728        assert_eq!(top.wrapping_add_signed(1), Clock33::ZERO);
729        assert_eq!(top.wrapping_add_signed(2), one);
730        let five = Clock33::try_new(5).expect("in range");
731        assert_eq!(five.signed_distance_to(top), -6);
732        assert_eq!(top.signed_distance_to(five), 6);
733        assert_eq!(u64::from(top), WRAP_33BIT - 1);
734    }
735
736    #[test]
737    fn clock27_validates_both_wire_widths() {
738        assert_eq!(
739            Clock27::from_parts(WRAP_33BIT, 0).unwrap_err().field,
740            "27 MHz base"
741        );
742        assert_eq!(
743            Clock27::from_27mhz(PCR_WRAP_27MHZ).unwrap_err(),
744            ClockOutOfRange {
745                field: "27 MHz ticks",
746                value: PCR_WRAP_27MHZ
747            }
748        );
749        // 300..=511 fits the 9-bit wire field but not the clock.
750        assert_eq!(
751            Clock27::from_parts(0, 300).unwrap_err(),
752            ClockOutOfRange {
753                field: "27 MHz extension",
754                value: 300
755            }
756        );
757        assert!(Clock27::from_parts(WRAP_33BIT - 1, 299).is_ok());
758    }
759
760    #[test]
761    fn clock27_wire_parts_keep_off_clock_values_and_report_them() {
762        for ext in [0u16, 1, 299, 300, 408, 511] {
763            let c = Clock27::from_wire_parts(0x1_2345_6789, ext);
764            assert_eq!((c.base.ticks(), c.ext), (0x1_2345_6789, ext));
765            assert_eq!(c.is_valid(), ext < 300);
766            match c.to_clock27() {
767                Ok(checked) => {
768                    assert!(ext < 300);
769                    assert_eq!(checked, c);
770                }
771                Err(err) => {
772                    assert!(ext >= 300);
773                    assert_eq!((err.field, err.value), ("27 MHz extension", u64::from(ext)));
774                }
775            }
776        }
777        // The base is a 33-bit wire field, kept as its low 33 bits.
778        assert_eq!(Clock27::from_wire_parts(WRAP_33BIT | 5, 0).base.ticks(), 5);
779        assert_eq!(ClockOutOfRange::base(WRAP_33BIT).field, "27 MHz base");
780    }
781
782    #[test]
783    fn clock27_round_trips_a_full_revolution() {
784        for ticks in [0, 1, 299, 300, 27_000_000, PCR_WRAP_27MHZ - 1] {
785            let c = Clock27::from_27mhz(ticks).expect("in range");
786            assert_eq!(c.ticks(), ticks);
787            assert_eq!(u64::from(c), ticks);
788            assert_eq!(Clock27::from_parts(c.base.ticks(), c.ext), Ok(c));
789        }
790        let a = Clock27::from_27mhz(PCR_WRAP_27MHZ - 5).expect("in range");
791        let b = Clock27::from_27mhz(10).expect("in range");
792        assert_eq!(a.signed_distance_to(b), 15);
793    }
794
795    #[test]
796    fn pcr_constants_are_the_spec_values() {
797        assert_eq!(PCR_EXT_MODULUS, 300);
798        assert_eq!(PCR_WRAP_27MHZ, (1u64 << 33) * 300);
799        assert_eq!(PCR_WRAP_27MHZ, 2_576_980_377_600);
800        assert_eq!(PCR_HZ, PTS_HZ * PCR_EXT_MODULUS);
801    }
802
803    /// A count past the wrap is reduced onto the clock, a count below it is
804    /// taken as it is, and the result is always a real position.
805    #[test]
806    fn a_wrapping_27mhz_constructor_reduces_onto_the_clock() {
807        for ticks in [0, 1, 299, 300, 27_000_000, PCR_WRAP_27MHZ - 1] {
808            let c = Clock27::from_27mhz_wrapping(ticks);
809            assert_eq!(c.ticks(), ticks);
810            assert!(c.is_valid());
811        }
812        let wrapped = Clock27::from_27mhz_wrapping(PCR_WRAP_27MHZ + 300);
813        assert_eq!(wrapped.ticks(), 300);
814        assert!(wrapped.is_valid());
815        assert_eq!(
816            Clock27::from_27mhz_wrapping(u64::MAX).ticks(),
817            u64::MAX % PCR_WRAP_27MHZ
818        );
819    }
820
821    #[test]
822    fn pcr_parts_round_trip() {
823        for ticks in [0, 1, 299, 300, 301, 27_000_000, PCR_WRAP_27MHZ - 1] {
824            let (base, ext) = pcr_split(ticks);
825            assert!(ext < 300 && base < WRAP_33BIT);
826            assert_eq!(pcr_from_parts(base, ext), ticks);
827        }
828        // An over-wide base wraps instead of panicking.
829        let _ = pcr_from_parts(u64::MAX, 299);
830    }
831
832    #[test]
833    fn pcr_forward_distance_across_the_wrap() {
834        let m = PCR_WRAP_27MHZ;
835        assert_eq!(pcr_forward_distance(m - 5, 10), 15);
836        assert_eq!(pcr_forward_distance(10, m - 5), m - 15);
837        assert_eq!(pcr_forward_distance(7, 7), 0);
838        assert_eq!(pcr_forward_distance(0, m - 1), m - 1);
839        // Inputs at or above the modulus are reduced first.
840        assert_eq!(pcr_forward_distance(m + 3, 5), 2);
841    }
842
843    /// The bug this exists to prevent: `to.wrapping_sub(from) % M` is wrong
844    /// whenever `to < from`, because 2^64 mod M != 0.
845    #[test]
846    fn pcr_forward_distance_is_not_wrapping_sub_mod_m() {
847        let m = PCR_WRAP_27MHZ;
848        let (from, to) = (m - 5, 10u64);
849        let naive = to.wrapping_sub(from) % m;
850        assert_ne!(naive, 15, "the naive form is wrong across a wrap");
851        assert_eq!(pcr_forward_distance(from, to), 15);
852    }
853
854    #[test]
855    fn pcr_signed_distance_is_the_shortest_path() {
856        let m = PCR_WRAP_27MHZ;
857        assert_eq!(pcr_signed_distance(m - 10, 5), 15);
858        assert_eq!(pcr_signed_distance(5, m - 10), -15);
859        assert_eq!(pcr_signed_distance(0, m / 2), (m / 2) as i64);
860        assert_eq!(pcr_signed_distance(0, m / 2 + 1), -((m / 2 - 1) as i64));
861        assert_eq!(pcr_signed_distance(100, 100), 0);
862    }
863    /// A REAL 5-byte PTS field: the first PES of `fixtures/ts/m6-single.ts`
864    /// (private_stream_1, `PTS_DTS_flags = 10`). The expected value was decoded
865    /// independently by slicing the 40-bit string as
866    /// `prefix(4) ts[32:30](3) '1' ts[29:15](15) '1' ts[14:0](15) '1'`.
867    #[test]
868    fn marked_decodes_and_re_encodes_a_real_capture_pts_field() {
869        let real = [0x29, 0xFD, 0x91, 0xD2, 0x29];
870        let m = unpack_marked(&real);
871        assert_eq!(
872            m,
873            Marked {
874                prefix: 0b0010,
875                timestamp: 5_358_512_404,
876                markers: MARKERS_ALL_SET
877            }
878        );
879        assert_eq!(pack_marked(m.timestamp, m.prefix), real);
880    }
881
882    #[test]
883    fn marked_round_trips_every_boundary_and_marker_combination() {
884        for ts in [0, 1, 90_000, 0x1_2345_6789, WRAP_33BIT - 1] {
885            for prefix in [0b0001, 0b0010, 0b0011, 0x0F, 0] {
886                for markers in 0..8u8 {
887                    let b = pack_marked_with(ts, prefix, markers);
888                    let m = unpack_marked(&b);
889                    assert_eq!(
890                        (m.prefix, m.timestamp, m.markers),
891                        (prefix, ts, markers),
892                        "ts={ts:#x} prefix={prefix:#x} markers={markers:#05b}"
893                    );
894                }
895            }
896        }
897    }
898
899    #[test]
900    fn marked_pack_reduces_modulo_2_pow_33_and_masks_the_prefix() {
901        assert_eq!(pack_marked(WRAP_33BIT + 5, 0b0010), pack_marked(5, 0b0010));
902        // Only the low nibble of the prefix is on the wire.
903        assert_eq!(pack_marked(7, 0xF2), pack_marked(7, 0x02));
904    }
905
906    #[test]
907    fn marked_a_cleared_marker_is_visible_to_the_caller() {
908        let mut b = pack_marked(0x1234, 0b0010);
909        b[2] &= !1; // clear the middle marker bit
910        assert_eq!(unpack_marked(&b).markers, 0b101);
911    }
912}