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, thiserror::Error)]
282#[error("{field} value {value} is out of range")]
283#[non_exhaustive]
284pub struct ClockOutOfRange {
285    /// Which field was rejected: `"33-bit ticks"`, `"27 MHz base"`,
286    /// `"27 MHz extension"` or `"27 MHz ticks"`.
287    pub field: &'static str,
288    /// The rejected value, widened to `u64` for reporting.
289    pub value: u64,
290}
291
292impl ClockOutOfRange {
293    /// A rejected 27 MHz base: a value at or above the 33-bit wire width.
294    ///
295    /// The constructors here never produce one (a base is either already a
296    /// [`Clock33`] or checked by [`Clock27::from_parts`]); a type that kept
297    /// wire parts unvalidated reports an over-wide base with this.
298    #[must_use]
299    pub const fn base(value: u64) -> Self {
300        Self {
301            field: "27 MHz base",
302            value,
303        }
304    }
305}
306
307/// A validated 33-bit 90 kHz clock sample (PTS, DTS, SCTE-35 `pts_time`).
308///
309/// ISO/IEC 13818-1 §2.4.3.7 samples the 90 kHz system clock into a 33-bit
310/// field. This type is that value *after* the wire: always in `[0, 2^33)`, so
311/// the modular helpers here never have to reduce their input and a caller
312/// cannot hand them a value that silently wraps somewhere else. `mpeg-pes`'s
313/// `Pts`/`Dts`, SCTE-35's `pts_time`/`pts_adjustment` and `timed-metadata`'s
314/// timeline all carry this type.
315///
316/// `Default` is the origin (`0`). [`From<Clock33> for u64`], [`TryFrom<u64>`]
317/// and [`TryFrom<i64>`] convert.
318#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
319#[cfg_attr(feature = "serde", derive(serde::Serialize))]
320#[cfg_attr(feature = "serde", serde(transparent))]
321pub struct Clock33(u64);
322
323impl Clock33 {
324    /// The origin of the clock (`0`).
325    pub const ZERO: Self = Self(0);
326
327    /// Construct from a raw tick count, rejecting any value at or above
328    /// [`WRAP_33BIT`].
329    ///
330    /// # Errors
331    /// [`ClockOutOfRange`] (`field: "33-bit ticks"`) when `ticks >= 2^33`.
332    pub const fn try_new(ticks: u64) -> Result<Self, ClockOutOfRange> {
333        if ticks >= WRAP_33BIT {
334            Err(ClockOutOfRange {
335                field: "33-bit ticks",
336                value: ticks,
337            })
338        } else {
339            Ok(Self(ticks))
340        }
341    }
342
343    /// The raw tick count, always in `[0, 2^33)`.
344    #[must_use]
345    pub const fn ticks(self) -> u64 {
346        self.0
347    }
348
349    /// `(self + b) mod 2^33` — see [`add`].
350    #[must_use]
351    pub const fn wrapping_add(self, b: Self) -> Self {
352        // Both operands are < 2^33, so the sum cannot overflow a u64.
353        Self((self.0 + b.0) % WRAP_33BIT)
354    }
355
356    /// `(self + delta) mod 2^33` for a possibly negative step — see
357    /// [`add_signed`].
358    #[must_use]
359    pub fn wrapping_add_signed(self, delta: i64) -> Self {
360        Self(add_signed(self.0, delta))
361    }
362
363    /// The shortest signed distance from `self` to `to` — see
364    /// [`signed_distance`].
365    #[must_use]
366    pub fn signed_distance_to(self, to: Self) -> i64 {
367        signed_distance(self.0, to.0)
368    }
369}
370
371impl From<Clock33> for u64 {
372    fn from(c: Clock33) -> Self {
373        c.0
374    }
375}
376
377impl TryFrom<u64> for Clock33 {
378    type Error = ClockOutOfRange;
379    fn try_from(ticks: u64) -> Result<Self, Self::Error> {
380        Self::try_new(ticks)
381    }
382}
383
384impl TryFrom<i64> for Clock33 {
385    type Error = ClockOutOfRange;
386    fn try_from(ticks: i64) -> Result<Self, Self::Error> {
387        // A negative sample cannot name a position on the clock: report the
388        // magnitude, which is the width that matters.
389        Self::try_new(ticks.unsigned_abs())
390    }
391}
392
393impl core::fmt::Debug for Clock33 {
394    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
395        write!(f, "Clock33({})", self.0)
396    }
397}
398
399impl core::fmt::Display for Clock33 {
400    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
401        write!(f, "{}", self.0)
402    }
403}
404
405/// A validated 27 MHz clock value: `base * 300 + ext` (ISO/IEC 13818-1
406/// §2.4.3.5 PCR, §2.4.3.7 ESCR, §2.5.3.4 program-stream SCR).
407///
408/// Construction ([`from_parts`](Self::from_parts),
409/// [`from_27mhz`](Self::from_27mhz)) keeps `ext < 300`, so a value built that
410/// way is always in `[0, PCR_WRAP_27MHZ)`. A *parsed* field may carry a 9-bit
411/// extension in `300..=511` (off the clock): [`from_wire_parts`](Self::from_wire_parts)
412/// keeps it losslessly and [`to_clock27`](Self::to_clock27) is the checked way
413/// to use it. This is the one representation of a PCR/ESCR/SCR: `mpeg-ts`'s
414/// `Pcr` and `mpeg-ps`'s `Scr` wrap it and add only their wire codecs.
415#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
416pub struct Clock27 {
417    /// The 33-bit base (27 MHz ticks / 300).
418    pub base: Clock33,
419    /// The 9-bit extension (27 MHz ticks within the current base tick).
420    pub ext: u16,
421}
422
423/// Serializes as the 27 MHz tick count: a PCR is stored as the one number
424/// its wire fields code, so a snapshot survives the lossless `from_wire_parts`
425/// round trip.
426#[cfg(feature = "serde")]
427impl serde::Serialize for Clock27 {
428    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
429        s.serialize_u64(self.ticks())
430    }
431}
432
433impl Clock27 {
434    /// Construct from the two wire parts, checking both widths.
435    ///
436    /// # Errors
437    /// [`ClockOutOfRange`] when `base >= 2^33` (`field: "27 MHz base"`) or
438    /// `ext >= 300` (`field: "27 MHz extension"`).
439    pub const fn from_parts(base: u64, ext: u16) -> Result<Self, ClockOutOfRange> {
440        let base = match Clock33::try_new(base) {
441            Ok(base) => base,
442            Err(_) => {
443                return Err(ClockOutOfRange {
444                    field: "27 MHz base",
445                    value: base,
446                });
447            }
448        };
449        if ext >= PCR_EXT_MODULUS as u16 {
450            return Err(ClockOutOfRange {
451                field: "27 MHz extension",
452                value: ext as u64,
453            });
454        }
455        Ok(Self { base, ext })
456    }
457
458    /// Split an absolute 27 MHz value into its two wire parts, the inverse of
459    /// [`from_parts`](Self::from_parts) for any `ticks < PCR_WRAP_27MHZ`.
460    ///
461    /// # Errors
462    /// [`ClockOutOfRange`] (`field: "27 MHz ticks"`) when
463    /// `ticks >= PCR_WRAP_27MHZ`.
464    pub fn from_27mhz(ticks: u64) -> Result<Self, ClockOutOfRange> {
465        if ticks >= PCR_WRAP_27MHZ {
466            return Err(ClockOutOfRange {
467                field: "27 MHz ticks",
468                value: ticks,
469            });
470        }
471        let (base, ext) = pcr_split(ticks);
472        // `ticks < PCR_WRAP_27MHZ` puts both parts in range by construction.
473        Self::from_parts(base, ext)
474    }
475
476    /// The position `ticks` names on the 27 MHz clock, taking any count:
477    /// `ticks` itself when it is below [`PCR_WRAP_27MHZ`], and `ticks`
478    /// reduced modulo the wrap otherwise (a reading from a free-running counter
479    /// that has passed the wrap).
480    ///
481    /// Infallible: the reduction puts both wire parts in range, so this is the
482    /// constructor for a raw count that may be past the wrap, and
483    /// [`from_27mhz`](Self::from_27mhz) the checked one that reports it.
484    #[must_use]
485    pub const fn from_27mhz_wrapping(ticks: u64) -> Self {
486        let (base, ext) = pcr_split(ticks % PCR_WRAP_27MHZ);
487        Self {
488            // `ticks % PCR_WRAP_27MHZ` is 33 bits (base) times 300 (ext), so
489            // both parts are in range by construction.
490            base: Clock33(base),
491            ext,
492        }
493    }
494
495    /// The full value on the 27 MHz clock: `base * 300 + ext`.
496    ///
497    /// A constructed value is a real time reading. For a value from
498    /// [`from_wire_parts`](Self::from_wire_parts) with an extension at or above
499    /// 300 this is not a time on the clock, so callers check
500    /// [`is_valid`](Self::is_valid) or [`to_clock27`](Self::to_clock27) first.
501    #[must_use]
502    pub const fn ticks(self) -> u64 {
503        pcr_from_parts(self.base.ticks(), self.ext)
504    }
505
506    /// The value in seconds.
507    #[must_use]
508    pub fn seconds(self) -> f64 {
509        self.ticks() as f64 / PCR_HZ as f64
510    }
511
512    /// The shortest signed distance from `self` to `to` — see
513    /// [`pcr_signed_distance`].
514    #[must_use]
515    pub fn signed_distance_to(self, to: Self) -> i64 {
516        pcr_signed_distance(self.ticks(), to.ticks())
517    }
518
519    /// Wrap the two parts exactly as the **wire** carried them, without
520    /// validating.
521    ///
522    /// A PCR/ESCR/SCR field is 33-bit base + 9-bit extension, so real
523    /// captures do carry extensions in `300..=511` — a value off the 27 MHz
524    /// clock that this type cannot hold. Parsing must stay lossless (the
525    /// workspace's byte-exact round-trip invariant), so a parser uses this to
526    /// keep the wire bytes, and a caller that needs a real clock reading asks
527    /// [`to_clock27`](Self::to_clock27) for the checked view.
528    ///
529    /// Code that *constructs* a clock value uses [`from_parts`](Self::from_parts)
530    /// instead, which rejects those parts.
531    #[must_use]
532    pub const fn from_wire_parts(base: u64, ext: u16) -> Self {
533        Self {
534            // The 33-bit field cannot exceed the clock's range; the wire
535            // width, not validation, decides here.
536            base: Clock33(base & (WRAP_33BIT - 1)),
537            ext,
538        }
539    }
540
541    /// The checked view of these parts: `Ok` when they name a position on the
542    /// 27 MHz clock.
543    ///
544    /// # Errors
545    /// [`ClockOutOfRange`] when `ext >= 300`. The base is always a [`Clock33`],
546    /// so it cannot be out of range.
547    pub const fn to_clock27(self) -> Result<Self, ClockOutOfRange> {
548        if self.ext >= PCR_EXT_MODULUS as u16 {
549            Err(ClockOutOfRange {
550                field: "27 MHz extension",
551                value: self.ext as u64,
552            })
553        } else {
554            Ok(self)
555        }
556    }
557
558    /// Whether [`ticks`](Self::ticks) is `base * 300 + ext` (an extension
559    /// below 300) rather than a wire value off the 27 MHz clock.
560    #[must_use]
561    pub const fn is_valid(self) -> bool {
562        self.ext < PCR_EXT_MODULUS as u16
563    }
564}
565
566impl From<Clock27> for u64 {
567    fn from(c: Clock27) -> Self {
568        c.ticks()
569    }
570}
571
572impl core::fmt::Debug for Clock27 {
573    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
574        write!(f, "Clock27({})", self.ticks())
575    }
576}
577
578impl core::fmt::Display for Clock27 {
579    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
580        write!(f, "{}", self.ticks())
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587
588    #[test]
589    fn unwrap_delta_half_range_step_agrees_with_signed_distance() {
590        let step = signed_distance(WRAP_33BIT_HALF, 0);
591        assert_eq!(step, WRAP_33BIT_HALF as i64);
592        assert_eq!(unwrap_delta(0, WRAP_33BIT_HALF, 0), i128::from(step));
593        assert_eq!(unwrap_delta(0, 0, WRAP_33BIT_HALF), i128::from(step));
594    }
595
596    #[test]
597    fn unwrap_delta_forward_wrap_advances_by_one_modulus() {
598        // prev near the top of the range, next small: a legitimate forward
599        // wrap of +8 ticks, not a ~2^33-tick backward jump.
600        let prev_unwrapped = (WRAP_33BIT - 10) as i128;
601        let got = unwrap_delta(prev_unwrapped, WRAP_33BIT - 10, 5);
602        assert_eq!(got, prev_unwrapped + 15);
603        assert_eq!(got, 5 + WRAP_33BIT as i128);
604    }
605
606    #[test]
607    fn unwrap_delta_small_forward_step_is_identity_shift() {
608        assert_eq!(unwrap_delta(1_000, 1_000, 2_000), 2_000);
609    }
610
611    #[test]
612    fn unwrap_delta_small_backward_step_is_preserved_not_wrapped() {
613        // Ordinary B-frame reordering: a small backward step within an
614        // epoch must NOT be treated as a wrap.
615        assert_eq!(unwrap_delta(2_000, 2_000, 1_995), 1_995);
616    }
617
618    /// MUTATION-PROOF: a reorder that straddles the origin (previous raw
619    /// value small, next raw value near the top of the range, representing a
620    /// genuine small *backward* step across 0) must unwrap to a small
621    /// negative delta, not a huge forward jump. This is exactly the case a
622    /// naive forward-only epoch counter (what `timed_metadata::Timeline`
623    /// used before this module existed) gets wrong. Verified by temporarily
624    /// deleting the `delta > WRAP_33BIT_HALF` branch below (so only forward
625    /// wraps are corrected): this test then fails with `got = 2^33 - 3`
626    /// instead of `-3`, confirming the branch is load-bearing. Restored.
627    #[test]
628    fn unwrap_delta_backward_reorder_across_origin_stays_small_and_negative() {
629        let got = unwrap_delta(2, 2, WRAP_33BIT - 3);
630        assert_eq!(got, -3);
631    }
632
633    #[test]
634    fn wrapping_forward_distance_small_forward_is_small() {
635        assert_eq!(wrapping_forward_distance(100, 105), 5);
636    }
637
638    #[test]
639    fn wrapping_forward_distance_wraps_at_modulus() {
640        assert_eq!(wrapping_forward_distance(WRAP_33BIT - 1, 0), 1);
641    }
642
643    #[test]
644    fn wrapping_forward_distance_backward_step_is_large() {
645        // A backward step of 5 reports as (modulus - 5): a huge forward
646        // distance, which callers threshold against `WRAP_33BIT_HALF` to
647        // classify as "actually behind", not "far ahead".
648        let d = wrapping_forward_distance(105, 100);
649        assert_eq!(d, WRAP_33BIT - 5);
650        assert!(d > WRAP_33BIT_HALF);
651    }
652
653    #[test]
654    fn add_wraps_at_modulus() {
655        assert_eq!(add(WRAP_33BIT - 1, 1), 0);
656        assert_eq!(add(WRAP_33BIT - 10, 20), 10);
657    }
658
659    #[test]
660    fn add_reduces_inputs_at_or_above_the_modulus() {
661        assert_eq!(add(WRAP_33BIT + 3, 0), 3);
662    }
663
664    #[test]
665    fn add_signed_negative_delta_wraps_below_zero() {
666        assert_eq!(add_signed(5, -10), WRAP_33BIT - 5);
667    }
668
669    #[test]
670    fn add_signed_extreme_deltas_stay_in_range() {
671        for delta in [i64::MIN, i64::MAX] {
672            let got = add_signed(0, delta);
673            assert!(
674                got < WRAP_33BIT,
675                "add_signed(0, {delta}) = {got} escaped [0, 2^33)"
676            );
677        }
678    }
679
680    #[test]
681    fn signed_distance_matches_doc_examples() {
682        assert_eq!(signed_distance(WRAP_33BIT - 10, 5), 15);
683        assert_eq!(signed_distance(5, WRAP_33BIT - 10), -15);
684    }
685
686    #[test]
687    fn signed_distance_half_range_boundary_is_positive() {
688        // The range is (-2^32, 2^32]: exactly half the modulus reads as +2^32,
689        // one tick past it flips to the negative shortest path.
690        assert_eq!(signed_distance(0, WRAP_33BIT_HALF), WRAP_33BIT_HALF as i64);
691        assert_eq!(
692            signed_distance(0, WRAP_33BIT_HALF + 1),
693            -((WRAP_33BIT_HALF - 1) as i64)
694        );
695    }
696
697    #[test]
698    fn signed_distance_reduces_inputs_at_or_above_the_modulus() {
699        assert_eq!(signed_distance(WRAP_33BIT + 5, WRAP_33BIT + 8), 3);
700    }
701    #[test]
702    fn clock33_rejects_every_out_of_width_value() {
703        assert_eq!(
704            Clock33::try_new(WRAP_33BIT - 1),
705            Ok(Clock33(WRAP_33BIT - 1))
706        );
707        for bad in [WRAP_33BIT, WRAP_33BIT + 1, u64::MAX] {
708            let err = Clock33::try_new(bad).unwrap_err();
709            assert_eq!((err.field, err.value), ("33-bit ticks", bad));
710            assert_eq!(Clock33::try_from(bad).unwrap_err(), err);
711        }
712        assert_eq!(Clock33::try_from(7u64), Ok(Clock33(7)));
713        assert_eq!(Clock33::try_from(0u64), Ok(Clock33::ZERO));
714    }
715
716    #[test]
717    fn clock33_arithmetic_wraps_and_agrees_with_the_free_functions() {
718        let top = Clock33::try_new(WRAP_33BIT - 1).expect("in range");
719        let one = Clock33::try_new(1).expect("in range");
720        assert_eq!(top.wrapping_add(one), Clock33::ZERO);
721        assert_eq!(top.wrapping_add_signed(1), Clock33::ZERO);
722        assert_eq!(top.wrapping_add_signed(2), one);
723        let five = Clock33::try_new(5).expect("in range");
724        assert_eq!(five.signed_distance_to(top), -6);
725        assert_eq!(top.signed_distance_to(five), 6);
726        assert_eq!(u64::from(top), WRAP_33BIT - 1);
727    }
728
729    #[test]
730    fn clock27_validates_both_wire_widths() {
731        assert_eq!(
732            Clock27::from_parts(WRAP_33BIT, 0).unwrap_err().field,
733            "27 MHz base"
734        );
735        assert_eq!(
736            Clock27::from_27mhz(PCR_WRAP_27MHZ).unwrap_err(),
737            ClockOutOfRange {
738                field: "27 MHz ticks",
739                value: PCR_WRAP_27MHZ
740            }
741        );
742        // 300..=511 fits the 9-bit wire field but not the clock.
743        assert_eq!(
744            Clock27::from_parts(0, 300).unwrap_err(),
745            ClockOutOfRange {
746                field: "27 MHz extension",
747                value: 300
748            }
749        );
750        assert!(Clock27::from_parts(WRAP_33BIT - 1, 299).is_ok());
751    }
752
753    #[test]
754    fn clock27_wire_parts_keep_off_clock_values_and_report_them() {
755        for ext in [0u16, 1, 299, 300, 408, 511] {
756            let c = Clock27::from_wire_parts(0x1_2345_6789, ext);
757            assert_eq!((c.base.ticks(), c.ext), (0x1_2345_6789, ext));
758            assert_eq!(c.is_valid(), ext < 300);
759            match c.to_clock27() {
760                Ok(checked) => {
761                    assert!(ext < 300);
762                    assert_eq!(checked, c);
763                }
764                Err(err) => {
765                    assert!(ext >= 300);
766                    assert_eq!((err.field, err.value), ("27 MHz extension", u64::from(ext)));
767                }
768            }
769        }
770        // The base is a 33-bit wire field, kept as its low 33 bits.
771        assert_eq!(Clock27::from_wire_parts(WRAP_33BIT | 5, 0).base.ticks(), 5);
772        assert_eq!(ClockOutOfRange::base(WRAP_33BIT).field, "27 MHz base");
773    }
774
775    #[test]
776    fn clock27_round_trips_a_full_revolution() {
777        for ticks in [0, 1, 299, 300, 27_000_000, PCR_WRAP_27MHZ - 1] {
778            let c = Clock27::from_27mhz(ticks).expect("in range");
779            assert_eq!(c.ticks(), ticks);
780            assert_eq!(u64::from(c), ticks);
781            assert_eq!(Clock27::from_parts(c.base.ticks(), c.ext), Ok(c));
782        }
783        let a = Clock27::from_27mhz(PCR_WRAP_27MHZ - 5).expect("in range");
784        let b = Clock27::from_27mhz(10).expect("in range");
785        assert_eq!(a.signed_distance_to(b), 15);
786    }
787
788    #[test]
789    fn pcr_constants_are_the_spec_values() {
790        assert_eq!(PCR_EXT_MODULUS, 300);
791        assert_eq!(PCR_WRAP_27MHZ, (1u64 << 33) * 300);
792        assert_eq!(PCR_WRAP_27MHZ, 2_576_980_377_600);
793        assert_eq!(PCR_HZ, PTS_HZ * PCR_EXT_MODULUS);
794    }
795
796    /// A count past the wrap is reduced onto the clock, a count below it is
797    /// taken as it is, and the result is always a real position.
798    #[test]
799    fn a_wrapping_27mhz_constructor_reduces_onto_the_clock() {
800        for ticks in [0, 1, 299, 300, 27_000_000, PCR_WRAP_27MHZ - 1] {
801            let c = Clock27::from_27mhz_wrapping(ticks);
802            assert_eq!(c.ticks(), ticks);
803            assert!(c.is_valid());
804        }
805        let wrapped = Clock27::from_27mhz_wrapping(PCR_WRAP_27MHZ + 300);
806        assert_eq!(wrapped.ticks(), 300);
807        assert!(wrapped.is_valid());
808        assert_eq!(
809            Clock27::from_27mhz_wrapping(u64::MAX).ticks(),
810            u64::MAX % PCR_WRAP_27MHZ
811        );
812    }
813
814    #[test]
815    fn pcr_parts_round_trip() {
816        for ticks in [0, 1, 299, 300, 301, 27_000_000, PCR_WRAP_27MHZ - 1] {
817            let (base, ext) = pcr_split(ticks);
818            assert!(ext < 300 && base < WRAP_33BIT);
819            assert_eq!(pcr_from_parts(base, ext), ticks);
820        }
821        // An over-wide base wraps instead of panicking.
822        let _ = pcr_from_parts(u64::MAX, 299);
823    }
824
825    #[test]
826    fn pcr_forward_distance_across_the_wrap() {
827        let m = PCR_WRAP_27MHZ;
828        assert_eq!(pcr_forward_distance(m - 5, 10), 15);
829        assert_eq!(pcr_forward_distance(10, m - 5), m - 15);
830        assert_eq!(pcr_forward_distance(7, 7), 0);
831        assert_eq!(pcr_forward_distance(0, m - 1), m - 1);
832        // Inputs at or above the modulus are reduced first.
833        assert_eq!(pcr_forward_distance(m + 3, 5), 2);
834    }
835
836    /// The bug this exists to prevent: `to.wrapping_sub(from) % M` is wrong
837    /// whenever `to < from`, because 2^64 mod M != 0.
838    #[test]
839    fn pcr_forward_distance_is_not_wrapping_sub_mod_m() {
840        let m = PCR_WRAP_27MHZ;
841        let (from, to) = (m - 5, 10u64);
842        let naive = to.wrapping_sub(from) % m;
843        assert_ne!(naive, 15, "the naive form is wrong across a wrap");
844        assert_eq!(pcr_forward_distance(from, to), 15);
845    }
846
847    #[test]
848    fn pcr_signed_distance_is_the_shortest_path() {
849        let m = PCR_WRAP_27MHZ;
850        assert_eq!(pcr_signed_distance(m - 10, 5), 15);
851        assert_eq!(pcr_signed_distance(5, m - 10), -15);
852        assert_eq!(pcr_signed_distance(0, m / 2), (m / 2) as i64);
853        assert_eq!(pcr_signed_distance(0, m / 2 + 1), -((m / 2 - 1) as i64));
854        assert_eq!(pcr_signed_distance(100, 100), 0);
855    }
856    /// A REAL 5-byte PTS field: the first PES of `fixtures/ts/m6-single.ts`
857    /// (private_stream_1, `PTS_DTS_flags = 10`). The expected value was decoded
858    /// independently by slicing the 40-bit string as
859    /// `prefix(4) ts[32:30](3) '1' ts[29:15](15) '1' ts[14:0](15) '1'`.
860    #[test]
861    fn marked_decodes_and_re_encodes_a_real_capture_pts_field() {
862        let real = [0x29, 0xFD, 0x91, 0xD2, 0x29];
863        let m = unpack_marked(&real);
864        assert_eq!(
865            m,
866            Marked {
867                prefix: 0b0010,
868                timestamp: 5_358_512_404,
869                markers: MARKERS_ALL_SET
870            }
871        );
872        assert_eq!(pack_marked(m.timestamp, m.prefix), real);
873    }
874
875    #[test]
876    fn marked_round_trips_every_boundary_and_marker_combination() {
877        for ts in [0, 1, 90_000, 0x1_2345_6789, WRAP_33BIT - 1] {
878            for prefix in [0b0001, 0b0010, 0b0011, 0x0F, 0] {
879                for markers in 0..8u8 {
880                    let b = pack_marked_with(ts, prefix, markers);
881                    let m = unpack_marked(&b);
882                    assert_eq!(
883                        (m.prefix, m.timestamp, m.markers),
884                        (prefix, ts, markers),
885                        "ts={ts:#x} prefix={prefix:#x} markers={markers:#05b}"
886                    );
887                }
888            }
889        }
890    }
891
892    #[test]
893    fn marked_pack_reduces_modulo_2_pow_33_and_masks_the_prefix() {
894        assert_eq!(pack_marked(WRAP_33BIT + 5, 0b0010), pack_marked(5, 0b0010));
895        // Only the low nibble of the prefix is on the wire.
896        assert_eq!(pack_marked(7, 0xF2), pack_marked(7, 0x02));
897    }
898
899    #[test]
900    fn marked_a_cleared_marker_is_visible_to_the_caller() {
901        let mut b = pack_marked(0x1234, 0b0010);
902        b[2] &= !1; // clear the middle marker bit
903        assert_eq!(unpack_marked(&b).markers, 0b101);
904    }
905}