use broadcast_common::clock33::{Clock33, WRAP_33BIT};
use broadcast_core::timescale::{self, Rounding, Timescale};
use core::time::Duration;
use crate::error::{Error, Result};
const PTS_TIMESCALE: Timescale = broadcast_common::clock33::PTS_TIMESCALE;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SnapDirection {
Exact,
Before,
After,
}
impl SnapDirection {
pub fn name(&self) -> &'static str {
match self {
SnapDirection::Exact => "exact",
SnapDirection::Before => "before",
SnapDirection::After => "after",
}
}
}
broadcast_core::impl_spec_display!(SnapDirection);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConditionedSplicePoint {
pub requested_pts: Clock33,
pub snapped_pts: Clock33,
pub delta_ticks: u64,
pub direction: SnapDirection,
}
impl ConditionedSplicePoint {
pub fn is_exact(&self) -> bool {
self.delta_ticks == 0
}
}
fn tolerance_ticks(max_delta: Duration) -> u64 {
let nanos = i128::try_from(max_delta.as_nanos()).unwrap_or(i128::MAX);
let ticks = timescale::rescale(nanos, Timescale::NANOS, PTS_TIMESCALE, Rounding::Ceil);
u64::try_from(ticks).unwrap_or(u64::MAX)
}
pub fn condition_splice_point(
requested_pts: Clock33,
candidates: &[Clock33],
max_delta: Duration,
) -> Result<ConditionedSplicePoint> {
let r = u128::from(requested_pts.ticks());
let modulus = u128::from(WRAP_33BIT);
let tolerance_ticks = tolerance_ticks(max_delta);
let mut nearest: Option<(Clock33, u64, bool)> = None;
for &candidate in candidates {
let c = u128::from(candidate.ticks());
let forward = (c + modulus - r) % modulus;
let backward = (r + modulus - c) % modulus;
let (delta, is_forward) = if forward <= backward {
(forward, true)
} else {
(backward, false)
};
let delta = u64::try_from(delta).unwrap_or(u64::MAX);
if nearest.is_none_or(|(_, best, best_forward)| {
delta < best || (delta == best && is_forward && !best_forward)
}) {
nearest = Some((candidate, delta, is_forward));
}
}
let (snapped_pts, delta_ticks, is_forward) = nearest.ok_or(Error::NoCandidates)?;
if delta_ticks > tolerance_ticks {
return Err(Error::NoAlignedBoundary {
requested_pts: requested_pts.ticks(),
tolerance_ticks,
nearest_delta_ticks: delta_ticks,
});
}
let direction = if delta_ticks == 0 {
SnapDirection::Exact
} else if is_forward {
SnapDirection::After
} else {
SnapDirection::Before
};
Ok(ConditionedSplicePoint {
requested_pts,
snapped_pts,
delta_ticks,
direction,
})
}
#[cfg(test)]
mod tests {
use super::*;
const fn pts(ticks: u64) -> Clock33 {
match Clock33::try_new(ticks) {
Ok(c) => c,
Err(_) => Clock33::ZERO,
}
}
fn ticks(n: u64) -> Duration {
Duration::from_nanos(n * 1_000_000_000 / 90_000)
}
const WRAP: u64 = broadcast_common::clock33::WRAP_33BIT;
#[test]
fn snaps_to_nearest_candidate() {
let result =
condition_splice_point(pts(1_000), &[pts(500), pts(1_050), pts(2_000)], ticks(100))
.unwrap();
assert_eq!(result.snapped_pts, pts(1_050));
assert_eq!(result.delta_ticks, 50);
assert_eq!(result.direction, SnapDirection::After);
assert!(!result.is_exact());
}
#[test]
fn exact_match_reports_zero_delta() {
let result = condition_splice_point(pts(1_000), &[pts(1_000)], Duration::ZERO).unwrap();
assert_eq!(result.delta_ticks, 0);
assert_eq!(result.direction, SnapDirection::Exact);
assert!(result.is_exact());
}
#[test]
fn before_direction_when_candidate_precedes_request() {
let result = condition_splice_point(pts(1_000), &[pts(900)], ticks(200)).unwrap();
assert_eq!(result.snapped_pts, pts(900));
assert_eq!(result.direction, SnapDirection::Before);
}
#[test]
fn rejects_a_candidate_outside_tolerance() {
let err = condition_splice_point(pts(1_000), &[pts(2_000)], ticks(500)).unwrap_err();
match err {
Error::NoAlignedBoundary {
requested_pts,
tolerance_ticks,
nearest_delta_ticks,
} => {
assert_eq!(requested_pts, 1_000);
assert_eq!(tolerance_ticks, 500);
assert_eq!(nearest_delta_ticks, 1_000);
}
other => panic!("expected NoAlignedBoundary, got {other:?}"),
}
}
#[test]
fn rejects_empty_candidates() {
let err = condition_splice_point(pts(1_000), &[], ticks(500)).unwrap_err();
assert!(matches!(err, Error::NoCandidates));
}
#[test]
fn snaps_across_the_33_bit_boundary() {
let cue = pts(WRAP - 100);
let r = condition_splice_point(cue, &[pts(50)], ticks(1_000)).unwrap();
assert_eq!(r.snapped_pts, pts(50));
assert_eq!(r.delta_ticks, 150);
assert_eq!(r.direction, SnapDirection::After);
}
#[test]
fn direction_before_across_the_wrap() {
let r = condition_splice_point(pts(50), &[pts(WRAP - 100)], ticks(1_000)).unwrap();
assert_eq!(r.delta_ticks, 150);
assert_eq!(r.direction, SnapDirection::Before);
}
#[test]
fn picks_nearest_among_both_sides_of_the_wrap() {
let cue = pts(WRAP - 100);
let r = condition_splice_point(cue, &[pts(WRAP - 500), pts(90), pts(4_000)], ticks(10_000))
.unwrap();
assert_eq!(r.snapped_pts, pts(90));
assert_eq!(r.delta_ticks, 190);
let r = condition_splice_point(cue, &[pts(WRAP - 150), pts(90)], ticks(10_000)).unwrap();
assert_eq!(r.snapped_pts, pts(WRAP - 150));
assert_eq!(r.delta_ticks, 50);
assert_eq!(r.direction, SnapDirection::Before);
}
#[test]
fn exact_and_tolerance_and_tie() {
let r = condition_splice_point(pts(7), &[pts(7)], Duration::ZERO).unwrap();
assert_eq!(r.direction, SnapDirection::Exact);
assert!(r.is_exact());
let err = condition_splice_point(pts(WRAP - 100), &[pts(50)], ticks(149)).unwrap_err();
assert!(matches!(
err,
Error::NoAlignedBoundary {
nearest_delta_ticks: 150,
tolerance_ticks: 149,
..
}
));
let r = condition_splice_point(Clock33::ZERO, &[pts(5)], ticks(5)).unwrap();
assert_eq!((r.delta_ticks, r.direction), (5, SnapDirection::After));
}
#[test]
fn a_duration_tolerance_is_converted_to_ticks() {
let r = condition_splice_point(pts(1_000), &[pts(1_001)], Duration::from_nanos(1)).unwrap();
assert_eq!(r.delta_ticks, 1);
let r = condition_splice_point(pts(1_000), &[pts(WRAP - 100)], Duration::MAX).unwrap();
assert_eq!(r.delta_ticks, 1_100);
assert_eq!(r.direction, SnapDirection::Before);
}
#[test]
fn an_equidistant_tie_prefers_after_regardless_of_order() {
for candidates in [[pts(900), pts(1_100)], [pts(1_100), pts(900)]] {
let r = condition_splice_point(pts(1_000), &candidates, ticks(200)).unwrap();
assert_eq!(
(r.snapped_pts, r.direction),
(pts(1_100), SnapDirection::After)
);
}
for candidates in [[pts(WRAP - 100), pts(100)], [pts(100), pts(WRAP - 100)]] {
let r = condition_splice_point(Clock33::ZERO, &candidates, ticks(200)).unwrap();
assert_eq!(
(r.snapped_pts, r.direction),
(pts(100), SnapDirection::After)
);
}
}
#[test]
fn direction_labels() {
assert_eq!(SnapDirection::Exact.name(), "exact");
assert_eq!(alloc::format!("{}", SnapDirection::After), "after");
}
}