1use broadcast_common::clock33::{Clock33, WRAP_33BIT};
28use broadcast_common::timescale::{self, Rounding, Timescale};
29use core::time::Duration;
30
31use crate::error::{Error, Result};
32
33const PTS_TIMESCALE: Timescale = broadcast_common::clock33::PTS_TIMESCALE;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum SnapDirection {
42 Exact,
44 Before,
46 After,
49}
50
51impl SnapDirection {
52 pub fn name(&self) -> &'static str {
54 match self {
55 SnapDirection::Exact => "exact",
56 SnapDirection::Before => "before",
57 SnapDirection::After => "after",
58 }
59 }
60}
61broadcast_common::impl_spec_display!(SnapDirection);
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct ConditionedSplicePoint {
67 pub requested_pts: Clock33,
69 pub snapped_pts: Clock33,
71 pub delta_ticks: u64,
74 pub direction: SnapDirection,
76}
77
78impl ConditionedSplicePoint {
79 pub fn is_exact(&self) -> bool {
81 self.delta_ticks == 0
82 }
83}
84
85fn tolerance_ticks(max_delta: Duration) -> u64 {
89 let nanos = i128::try_from(max_delta.as_nanos()).unwrap_or(i128::MAX);
90 let ticks = timescale::rescale(nanos, Timescale::NANOS, PTS_TIMESCALE, Rounding::Ceil);
91 u64::try_from(ticks).unwrap_or(u64::MAX)
92}
93
94pub fn condition_splice_point(
119 requested_pts: Clock33,
120 candidates: &[Clock33],
121 max_delta: Duration,
122) -> Result<ConditionedSplicePoint> {
123 let r = u128::from(requested_pts.ticks());
124 let modulus = u128::from(WRAP_33BIT);
125 let tolerance_ticks = tolerance_ticks(max_delta);
126 let mut nearest: Option<(Clock33, u64, bool)> = None;
128 for &candidate in candidates {
129 let c = u128::from(candidate.ticks());
130 let forward = (c + modulus - r) % modulus;
131 let backward = (r + modulus - c) % modulus;
132 let (delta, is_forward) = if forward <= backward {
133 (forward, true)
134 } else {
135 (backward, false)
136 };
137 let delta = u64::try_from(delta).unwrap_or(u64::MAX);
139 if nearest.is_none_or(|(_, best, best_forward)| {
143 delta < best || (delta == best && is_forward && !best_forward)
144 }) {
145 nearest = Some((candidate, delta, is_forward));
146 }
147 }
148 let (snapped_pts, delta_ticks, is_forward) = nearest.ok_or(Error::NoCandidates)?;
149 if delta_ticks > tolerance_ticks {
150 return Err(Error::NoAlignedBoundary {
151 requested_pts: requested_pts.ticks(),
152 tolerance_ticks,
153 nearest_delta_ticks: delta_ticks,
154 });
155 }
156 let direction = if delta_ticks == 0 {
157 SnapDirection::Exact
158 } else if is_forward {
159 SnapDirection::After
160 } else {
161 SnapDirection::Before
162 };
163 Ok(ConditionedSplicePoint {
164 requested_pts,
165 snapped_pts,
166 delta_ticks,
167 direction,
168 })
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 const fn pts(ticks: u64) -> Clock33 {
176 match Clock33::try_new(ticks) {
177 Ok(c) => c,
178 Err(_) => Clock33::ZERO,
179 }
180 }
181
182 fn ticks(n: u64) -> Duration {
185 Duration::from_nanos(n * 1_000_000_000 / 90_000)
186 }
187
188 const WRAP: u64 = broadcast_common::clock33::WRAP_33BIT;
190
191 #[test]
192 fn snaps_to_nearest_candidate() {
193 let result =
194 condition_splice_point(pts(1_000), &[pts(500), pts(1_050), pts(2_000)], ticks(100))
195 .unwrap();
196 assert_eq!(result.snapped_pts, pts(1_050));
197 assert_eq!(result.delta_ticks, 50);
198 assert_eq!(result.direction, SnapDirection::After);
199 assert!(!result.is_exact());
200 }
201
202 #[test]
203 fn exact_match_reports_zero_delta() {
204 let result = condition_splice_point(pts(1_000), &[pts(1_000)], Duration::ZERO).unwrap();
205 assert_eq!(result.delta_ticks, 0);
206 assert_eq!(result.direction, SnapDirection::Exact);
207 assert!(result.is_exact());
208 }
209
210 #[test]
211 fn before_direction_when_candidate_precedes_request() {
212 let result = condition_splice_point(pts(1_000), &[pts(900)], ticks(200)).unwrap();
213 assert_eq!(result.snapped_pts, pts(900));
214 assert_eq!(result.direction, SnapDirection::Before);
215 }
216
217 #[test]
218 fn rejects_a_candidate_outside_tolerance() {
219 let err = condition_splice_point(pts(1_000), &[pts(2_000)], ticks(500)).unwrap_err();
220 match err {
221 Error::NoAlignedBoundary {
222 requested_pts,
223 tolerance_ticks,
224 nearest_delta_ticks,
225 } => {
226 assert_eq!(requested_pts, 1_000);
227 assert_eq!(tolerance_ticks, 500);
228 assert_eq!(nearest_delta_ticks, 1_000);
229 }
230 other => panic!("expected NoAlignedBoundary, got {other:?}"),
231 }
232 }
233
234 #[test]
235 fn rejects_empty_candidates() {
236 let err = condition_splice_point(pts(1_000), &[], ticks(500)).unwrap_err();
237 assert!(matches!(err, Error::NoCandidates));
238 }
239
240 #[test]
245 fn snaps_across_the_33_bit_boundary() {
246 let cue = pts(WRAP - 100);
247 let r = condition_splice_point(cue, &[pts(50)], ticks(1_000)).unwrap();
248 assert_eq!(r.snapped_pts, pts(50));
249 assert_eq!(r.delta_ticks, 150);
250 assert_eq!(r.direction, SnapDirection::After);
251 }
252
253 #[test]
254 fn direction_before_across_the_wrap() {
255 let r = condition_splice_point(pts(50), &[pts(WRAP - 100)], ticks(1_000)).unwrap();
256 assert_eq!(r.delta_ticks, 150);
257 assert_eq!(r.direction, SnapDirection::Before);
258 }
259
260 #[test]
261 fn picks_nearest_among_both_sides_of_the_wrap() {
262 let cue = pts(WRAP - 100);
263 let r = condition_splice_point(cue, &[pts(WRAP - 500), pts(90), pts(4_000)], ticks(10_000))
264 .unwrap();
265 assert_eq!(r.snapped_pts, pts(90));
266 assert_eq!(r.delta_ticks, 190);
267 let r = condition_splice_point(cue, &[pts(WRAP - 150), pts(90)], ticks(10_000)).unwrap();
268 assert_eq!(r.snapped_pts, pts(WRAP - 150));
269 assert_eq!(r.delta_ticks, 50);
270 assert_eq!(r.direction, SnapDirection::Before);
271 }
272
273 #[test]
274 fn exact_and_tolerance_and_tie() {
275 let r = condition_splice_point(pts(7), &[pts(7)], Duration::ZERO).unwrap();
276 assert_eq!(r.direction, SnapDirection::Exact);
277 assert!(r.is_exact());
278 let err = condition_splice_point(pts(WRAP - 100), &[pts(50)], ticks(149)).unwrap_err();
279 assert!(matches!(
280 err,
281 Error::NoAlignedBoundary {
282 nearest_delta_ticks: 150,
283 tolerance_ticks: 149,
284 ..
285 }
286 ));
287 let r = condition_splice_point(Clock33::ZERO, &[pts(5)], ticks(5)).unwrap();
288 assert_eq!((r.delta_ticks, r.direction), (5, SnapDirection::After));
289 }
290
291 #[test]
295 fn a_duration_tolerance_is_converted_to_ticks() {
296 let r = condition_splice_point(pts(1_000), &[pts(1_001)], Duration::from_nanos(1)).unwrap();
300 assert_eq!(r.delta_ticks, 1);
301 let r = condition_splice_point(pts(1_000), &[pts(WRAP - 100)], Duration::MAX).unwrap();
304 assert_eq!(r.delta_ticks, 1_100);
305 assert_eq!(r.direction, SnapDirection::Before);
306 }
307
308 #[test]
311 fn an_equidistant_tie_prefers_after_regardless_of_order() {
312 for candidates in [[pts(900), pts(1_100)], [pts(1_100), pts(900)]] {
313 let r = condition_splice_point(pts(1_000), &candidates, ticks(200)).unwrap();
314 assert_eq!(
315 (r.snapped_pts, r.direction),
316 (pts(1_100), SnapDirection::After)
317 );
318 }
319 for candidates in [[pts(WRAP - 100), pts(100)], [pts(100), pts(WRAP - 100)]] {
321 let r = condition_splice_point(Clock33::ZERO, &candidates, ticks(200)).unwrap();
322 assert_eq!(
323 (r.snapped_pts, r.direction),
324 (pts(100), SnapDirection::After)
325 );
326 }
327 }
328
329 #[test]
330 fn direction_labels() {
331 assert_eq!(SnapDirection::Exact.name(), "exact");
332 assert_eq!(alloc::format!("{}", SnapDirection::After), "after");
333 }
334}