Skip to content

Commit

Permalink
frame-source: bugfix NtpTimestamp to chrono conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
astraw committed Mar 21, 2024
1 parent 94cfa75 commit 03f442e
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion media-utils/frame-source/src/ntp_timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ where
let sec_since_epoch = (since_epoch >> 32) as u32;
let frac_int = (since_epoch & 0xFFFF_FFFF) as u32;
let frac = frac_int as f64 / f64::from(u32::MAX);
let nanos = (frac * 1e9) as u32;
let nanos = (frac * 1e9).round() as u32;
let timedelta: chrono::TimeDelta =
chrono::TimeDelta::new(i64::from(sec_since_epoch), nanos).unwrap();
let date_time = chrono::DateTime::UNIX_EPOCH + timedelta;
Expand Down Expand Up @@ -113,4 +113,26 @@ mod tests {
NtpTimestamp(16824201542114736079)
);
}

fn assert_roundtrip_equal(n0: NtpTimestamp) {
let dt1 = chrono::DateTime::<chrono::Utc>::from(n0);
let n1 = NtpTimestamp::try_from(dt1).unwrap();
let dt2: chrono::DateTime<chrono::Utc> = n1.into();
assert_eq!(dt1, dt2);
}

#[test]
fn test_now() {
let dt0 = chrono::Utc::now();
let n0 = NtpTimestamp::try_from(dt0).unwrap();
assert_roundtrip_equal(n0);
}

#[test]
fn test_float_rounding() {
// This magic number was found empirically to fail when conversion to a
// floating-point fractional second did not round correctly. The bug has
// now been fixed but this test ensures it does not occur again.
assert_roundtrip_equal(NtpTimestamp(16834755242908219071));
}
}

0 comments on commit 03f442e

Please sign in to comment.