broadcast-common 13.0.0

Foundation for the rust-broadcast crates: symmetric Parse/Serialize traits, CRC-32/MPEG-2, BCD + MJD time codecs, bit I/O, 33-bit/PCR clock arithmetic, checked field widths, container-mux and Stage traits. no_std + alloc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Rescaling a tick count between two timescales (ticks per second).
//!
//! One home for `ticks * to / from` so the rounding mode is explicit at every
//! call site and the edge cases are decided once:
//!
//! - A timescale is a [`Timescale`], which is non-zero by construction, so a
//!   rescale never divides by zero and there is no "treat `0` as `1`" path to
//!   inherit: a zero timescale arriving from the wire (`mdhd`/`TimeScale`, an
//!   MPD `@timescale`, a manifest) is an error at the boundary that parses it
//!   ([`Timescale::try_new`]), never a silently wrong value here.
//! - The multiply saturates instead of wrapping, so an absurd tick count
//!   clamps rather than producing a small wrong value.
//! - The `_i64` / `_u64` forms saturate to the target type; `_u64` clamps a
//!   negative result to `0`.
//!
//! [`rescale`]: self::rescale

use crate::error::InvalidValue;

/// How a fractional result is brought to a whole tick.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Rounding {
    /// Toward negative infinity.
    Floor,
    /// To the nearest tick, halves away from zero.
    Nearest,
    /// Toward positive infinity.
    Ceil,
    /// Toward zero (plain integer division).
    TowardZero,
}

impl Rounding {
    /// Label of the rounding mode.
    pub fn name(&self) -> &'static str {
        match self {
            Rounding::Floor => "floor",
            Rounding::Ceil => "ceil",
            Rounding::Nearest => "nearest",
            Rounding::TowardZero => "toward zero",
        }
    }
}

crate::impl_spec_display!(Rounding);

/// A media timescale from a literal (or a named constant) the compiler can
/// prove non-zero.
///
/// The whole check happens at compile time: the `match` sits in an inline
/// `const` block, so `timescale!(0)` is a compile error even inside a `fn` and
/// there is no runtime path that could reach the `panic!`.
///
/// ```compile_fail
/// // A zero timescale cannot be named, not even inside a function.
/// fn price() -> broadcast_common::timescale::Timescale {
///     broadcast_common::timescale!(0)
/// }
/// ```
///
/// ```
/// let t = broadcast_common::timescale!(90_000);
/// assert_eq!(t.get(), 90_000);
/// let micros = ::broadcast_common::timescale!(::broadcast_common::timescale::MICROS_PER_SECOND);
/// assert_eq!(micros, ::broadcast_common::timescale::Timescale::MICROS);
/// ```
#[macro_export]
macro_rules! timescale {
    ($value:expr) => {
        const {
            match ::core::num::NonZeroU32::new($value) {
                ::core::option::Option::Some(nz) => $crate::timescale::Timescale::from_nonzero(nz),
                ::core::option::Option::None => panic!("a timescale is never zero"),
            }
        }
    };
}

/// A media timescale (ticks per second), guaranteed non-zero.
///
/// The wire can carry a zero timescale (a parsed `mdhd`/`TimeScale` field, an
/// MPD `@timescale`, a Smooth `StreamIndex@TimeScale`); such a field is an
/// error at the parse boundary ([`Self::try_new`]), not a value to flatten to
/// `1`. Every rescale below takes a `Timescale`, so a zero can neither reach
/// the arithmetic nor become a silently wrong result.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Timescale(core::num::NonZeroU32);

impl Timescale {
    /// Ticks per second of the microsecond timescale.
    pub const MICROS: Self = crate::timescale!(MICROS_PER_SECOND);

    /// Ticks per second of the nanosecond timescale.
    pub const NANOS: Self = crate::timescale!(1_000_000_000);

    /// A timescale from a value already known non-zero, with no failure path.
    ///
    /// A literal belongs in [`timescale!`](crate::timescale!), which proves it
    /// non-zero at compile time; a runtime `u32` goes through [`Self::new`] or
    /// [`Self::try_new`], which report the zero instead of panicking.
    #[must_use]
    pub const fn from_nonzero(value: core::num::NonZeroU32) -> Self {
        Self(value)
    }

    /// Construct from a raw value, returning `None` for zero.
    #[must_use]
    pub const fn new(value: u32) -> Option<Self> {
        match core::num::NonZeroU32::new(value) {
            Some(nz) => Some(Self(nz)),
            None => None,
        }
    }

    /// Fallible constructor; zero is an error.
    ///
    /// # Errors
    /// [`InvalidValue`] (`field: "timescale"`) when `value` is zero.
    pub fn try_new(value: u32) -> Result<Self, InvalidValue> {
        core::num::NonZeroU32::new(value)
            .map(Self)
            .ok_or(InvalidValue {
                field: "timescale",
                value: u64::from(value),
                reason: "must be non-zero",
            })
    }

    /// The same timescale as a `u64` (the wire/form fields that carry it
    /// wider than 32 bits, e.g. an MPD `@timescale`).
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0.get() as u64
    }

    /// The underlying ticks-per-second value.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0.get()
    }
}

impl core::fmt::Debug for Timescale {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(&self.0.get(), f)
    }
}

impl core::fmt::Display for Timescale {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.0, f)
    }
}

impl From<core::num::NonZeroU32> for Timescale {
    fn from(v: core::num::NonZeroU32) -> Self {
        Self(v)
    }
}

impl From<Timescale> for u32 {
    fn from(t: Timescale) -> Self {
        t.0.get()
    }
}

impl From<Timescale> for u64 {
    fn from(t: Timescale) -> Self {
        t.0.get() as u64
    }
}

impl From<Timescale> for core::num::NonZeroU32 {
    fn from(t: Timescale) -> Self {
        t.0
    }
}

impl TryFrom<u32> for Timescale {
    type Error = InvalidValue;

    /// The only lossless way to convert a runtime `u32`: a `0` is the same
    /// typed error [`Timescale::try_new`] returns, never a silent `1`.
    fn try_from(v: u32) -> Result<Self, Self::Error> {
        Self::try_new(v)
    }
}

impl From<Timescale> for i128 {
    fn from(t: Timescale) -> Self {
        i128::from(t.0.get())
    }
}

impl From<Timescale> for usize {
    fn from(t: Timescale) -> Self {
        t.0.get() as usize
    }
}

/// Ticks per second of the microsecond timescale ([`Timescale::MICROS`]).
pub const MICROS_PER_SECOND: u32 = 1_000_000;

/// `ticks` rescaled from `from` to `to` ticks per second.
#[must_use]
pub fn rescale(ticks: i128, from: Timescale, to: Timescale, rounding: Rounding) -> i128 {
    let den = i128::from(from.get());
    let num = ticks.saturating_mul(i128::from(to.get()));
    match rounding {
        Rounding::Floor => num.div_euclid(den),
        Rounding::Ceil => {
            let floor = num.div_euclid(den);
            if num.rem_euclid(den) == 0 {
                floor
            } else {
                floor.saturating_add(1)
            }
        }
        Rounding::TowardZero => num / den,
        Rounding::Nearest => {
            let half = den / 2;
            if num >= 0 {
                num.saturating_add(half) / den
            } else {
                num.saturating_sub(half) / den
            }
        }
    }
}

/// `ticks` at `timescale` as microseconds.
#[must_use]
pub fn to_micros(ticks: i128, timescale: Timescale, rounding: Rounding) -> i128 {
    rescale(ticks, timescale, Timescale::MICROS, rounding)
}

/// `us` microseconds as ticks at `timescale`.
#[must_use]
pub fn from_micros(us: i128, timescale: Timescale, rounding: Rounding) -> i128 {
    rescale(us, Timescale::MICROS, timescale, rounding)
}

/// Exact comparison of `a / a_ts` with `b / b_ts` seconds, without rounding.
#[must_use]
pub fn cmp_ticks(a: i64, a_ts: Timescale, b: i64, b_ts: Timescale) -> core::cmp::Ordering {
    let a_ts = i128::from(a_ts.get());
    let b_ts = i128::from(b_ts.get());
    (i128::from(a) * b_ts).cmp(&(i128::from(b) * a_ts))
}

/// [`rescale`] on `i64` ticks, saturating to the `i64` range.
#[must_use]
pub fn rescale_i64(ticks: i64, from: Timescale, to: Timescale, rounding: Rounding) -> i64 {
    let scaled = rescale(i128::from(ticks), from, to, rounding);
    i64::try_from(scaled).unwrap_or(if scaled < 0 { i64::MIN } else { i64::MAX })
}

/// [`rescale`] on `u64` ticks, saturating to the `u64` range.
#[must_use]
pub fn rescale_u64(ticks: u64, from: Timescale, to: Timescale, rounding: Rounding) -> u64 {
    let scaled = rescale(i128::from(ticks), from, to, rounding);
    u64::try_from(scaled).unwrap_or(if scaled < 0 { 0 } else { u64::MAX })
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;

    const T1: Timescale = crate::timescale!(1);
    const T48K: Timescale = crate::timescale!(48_000);
    const T90K: Timescale = crate::timescale!(90_000);

    fn ts(value: u32) -> Timescale {
        Timescale::try_new(value).expect("a non-zero timescale")
    }

    #[test]
    fn rounding_modes_differ_on_a_half_and_a_negative() {
        let two = ts(2);
        assert_eq!(rescale(3, two, T1, Rounding::Floor), 1);
        assert_eq!(rescale(3, two, T1, Rounding::Nearest), 2);
        assert_eq!(rescale(3, two, T1, Rounding::TowardZero), 1);
        assert_eq!(rescale(-3, two, T1, Rounding::Floor), -2);
        assert_eq!(rescale(-3, two, T1, Rounding::Nearest), -2);
        assert_eq!(rescale(-3, two, T1, Rounding::TowardZero), -1);
    }

    #[test]
    fn micros_helpers_are_rescale_against_one_million() {
        let three = ts(3);
        assert_eq!(to_micros(90_000, T90K, Rounding::Floor), 1_000_000);
        assert_eq!(to_micros(1, three, Rounding::TowardZero), 333_333);
        assert_eq!(to_micros(-1, three, Rounding::Floor), -333_334);
        assert_eq!(from_micros(1_000_001, T90K, Rounding::Ceil), 90_001);
        assert_eq!(from_micros(1_000_001, T90K, Rounding::Floor), 90_000);
        assert_eq!(to_micros(5, T1, Rounding::Floor), 5_000_000);
    }

    #[test]
    fn identity_and_known_conversion() {
        assert_eq!(rescale(90_000, T90K, T90K, Rounding::Nearest), 90_000);
        assert_eq!(rescale(48_000, T48K, T90K, Rounding::Floor), 90_000);
        assert_eq!(rescale_u64(1024, T48K, T90K, Rounding::Nearest), 1920);
    }

    /// A zero timescale has no panicking constructor: a runtime `u32` goes
    /// through the fallible `try_new`/`TryFrom` and is answered with a
    /// typed error, never a `panic!` a caller cannot see in the signature.
    #[test]
    fn a_zero_timescale_is_an_error_from_every_runtime_constructor() {
        assert_eq!(
            Timescale::try_new(0).map(Timescale::get),
            Err(InvalidValue {
                field: "timescale",
                value: 0,
                reason: "must be non-zero",
            })
        );
        assert_eq!(
            Timescale::try_from(0u32).map(Timescale::get),
            Err(InvalidValue {
                field: "timescale",
                value: 0,
                reason: "must be non-zero",
            })
        );
    }

    /// The literal macro builds the value it names, in a `const` item and in an
    /// ordinary expression alike (the compile-time proof is what lets it).
    #[test]
    fn the_literal_macro_names_the_timescale_it_is_given() {
        const T: Timescale = crate::timescale!(90_000);
        assert_eq!(T.get(), 90_000);
        assert_eq!(crate::timescale!(1).get(), 1);
        assert_eq!(Timescale::from_nonzero(core::num::NonZeroU32::MIN).get(), 1);
    }

    /// A zero timescale cannot reach the arithmetic: the type has no zero
    /// value, and the boundary that reads a wire value refuses it with a
    /// typed error naming the field instead of flattening it to `1`.
    #[test]
    fn zero_timescale_is_rejected_not_flattened_to_one() {
        assert!(Timescale::try_new(0).is_err());
        let err = Timescale::try_new(0).expect_err("a zero timescale is an error");
        assert_eq!(err.field, "timescale");
        assert_eq!(err.value, 0);
        assert_eq!(err.reason, "must be non-zero");
        assert_eq!(Timescale::try_new(1).map(Timescale::get), Ok(1));
        assert_eq!(Timescale::try_new(90_000).map(Timescale::get), Ok(90_000));
        // 1 Hz is the identity timescale, never a stand-in for "unknown".
        assert_eq!(to_micros(7, T1, Rounding::Floor), 7_000_000);
    }

    /// The fallible conversion is the only way a runtime `u32` becomes a
    /// `Timescale`, so `.try_into()` on a wire zero is that same typed error
    /// — it can never be flattened to `1` Hz.
    #[test]
    fn timescale_try_from_u32_rejects_zero() {
        let err = Timescale::try_from(0u32).expect_err("a zero timescale is an error");
        assert_eq!(err.field, "timescale");
        assert_eq!(err.value, 0);
        assert_eq!(err.reason, "must be non-zero");
        let ok: Timescale = 90_000u32.try_into().expect("non-zero converts");
        assert_eq!(ok, T90K);
        assert_eq!(u32::from(ok), 90_000);
    }

    #[test]
    fn saturates_instead_of_wrapping() {
        let max = ts(u32::MAX);
        assert_eq!(rescale_i64(i64::MAX, T1, max, Rounding::Floor), i64::MAX);
        assert_eq!(rescale_i64(i64::MIN, T1, max, Rounding::Floor), i64::MIN);
        assert_eq!(rescale_u64(u64::MAX, T1, max, Rounding::Nearest), u64::MAX);
        assert_eq!(rescale_u64(0, T1, T1, Rounding::Nearest), 0);
        assert_eq!(rescale(i128::MAX, T1, ts(2), Rounding::Floor), i128::MAX);
    }

    #[test]
    fn ceil_rounds_toward_positive_infinity() {
        let two = ts(2);
        assert_eq!(rescale(3, two, T1, Rounding::Ceil), 2);
        assert_eq!(rescale(4, two, T1, Rounding::Ceil), 2);
        assert_eq!(rescale(-3, two, T1, Rounding::Ceil), -1);
        assert_eq!(rescale(-4, two, T1, Rounding::Ceil), -2);
        assert_eq!(rescale(5, T1, T1, Rounding::Ceil), 5);
        assert_eq!(
            rescale_i64(i64::MAX, T1, ts(u32::MAX), Rounding::Ceil),
            i64::MAX
        );
    }

    #[test]
    fn cmp_ticks_is_exact_across_timescales() {
        use core::cmp::Ordering::{Equal, Greater, Less};
        assert_eq!(cmp_ticks(90_000, T90K, 48_000, T48K), Equal);
        assert_eq!(cmp_ticks(1, ts(3), 1, ts(2)), Less);
        assert_eq!(cmp_ticks(i64::MAX, T1, i64::MAX, ts(2)), Greater);
        assert_eq!(cmp_ticks(5, T1, 5, T1), Equal);
    }

    #[test]
    fn labels() {
        assert_eq!(Rounding::Ceil.to_string(), "ceil");
        assert_eq!(Rounding::Nearest.name(), "nearest");
        assert_eq!(Rounding::TowardZero.to_string(), "toward zero");
    }
}