use crate::error::{Error, Result};
use crate::event::MediaTime;
use alloc::string::String;
use jiff::SignedDuration;
use jiff::civil::{DateTime, date};
use jiff::fmt::temporal::DateTimePrinter;
const PRINTER: DateTimePrinter = DateTimePrinter::new().precision(Some(3));
#[cfg(test)]
const MIN_EPOCH_MS: i64 = -377_705_116_800_000;
#[cfg(test)]
const MAX_EPOCH_MS: i64 = 253_402_300_799_999;
fn civil_from_epoch_ms(epoch_ms: i64) -> Option<DateTime> {
date(1970, 1, 1)
.at(0, 0, 0, 0)
.checked_add(SignedDuration::from_millis(epoch_ms))
.ok()
}
fn render(dt: &DateTime) -> String {
let printed = PRINTER.datetime_to_string(dt);
let mut out = match printed.strip_prefix('-') {
Some(rest) => {
let (year6, tail) = rest.split_at(6);
let digits = year6.trim_start_matches('0');
alloc::format!("-{digits:0>3}{tail}")
}
None => printed,
};
out.push('Z');
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TimeAnchor {
pub pts_90k: u64,
pub utc_epoch_ms: i64,
}
impl TimeAnchor {
pub fn media_to_epoch_ms(&self, t: MediaTime) -> i64 {
let delta_ticks = i128::from(t.0) - i128::from(self.pts_90k);
let ms = i128::from(self.utc_epoch_ms)
+ delta_ticks
.saturating_mul(1000)
.div_euclid(i128::from(crate::PTS_HZ));
ms.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
}
pub fn try_rfc3339(&self, t: MediaTime) -> Result<String> {
try_format_rfc3339_ms(self.media_to_epoch_ms(t))
}
}
pub fn try_format_rfc3339_ms(epoch_ms: i64) -> Result<String> {
let dt = civil_from_epoch_ms(epoch_ms).ok_or(Error::TimestampOutOfRange(epoch_ms))?;
Ok(render(&dt))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event::MediaTime;
#[test]
fn epoch_zero_formats_unix_epoch() {
assert_eq!(
try_format_rfc3339_ms(0).unwrap(),
"1970-01-01T00:00:00.000Z"
);
assert_eq!(
try_format_rfc3339_ms(86_400_000).unwrap(),
"1970-01-02T00:00:00.000Z"
);
assert_eq!(
try_format_rfc3339_ms(1_000).unwrap(),
"1970-01-01T00:00:01.000Z"
);
}
#[test]
fn anchor_maps_media_to_wallclock() {
let a = TimeAnchor {
pts_90k: 0,
utc_epoch_ms: 1_000,
};
assert_eq!(a.media_to_epoch_ms(MediaTime(90_000)), 2_000);
assert_eq!(
a.try_rfc3339(MediaTime(0)).unwrap(),
"1970-01-01T00:00:01.000Z"
);
}
#[test]
fn sub_millisecond_offsets_floor_on_both_sides_of_the_anchor() {
let a = TimeAnchor {
pts_90k: 900_000,
utc_epoch_ms: 1_000,
};
assert_eq!(a.media_to_epoch_ms(MediaTime(900_001)), 1_000);
assert_eq!(a.media_to_epoch_ms(MediaTime(899_999)), 999);
assert_eq!(a.media_to_epoch_ms(MediaTime(899_911)), 999);
assert_eq!(a.media_to_epoch_ms(MediaTime(899_910)), 999);
assert_eq!(a.media_to_epoch_ms(MediaTime(899_909)), 998);
}
#[test]
fn range_constants_are_exactly_the_civil_range() {
assert!(civil_from_epoch_ms(MIN_EPOCH_MS).is_some());
assert!(civil_from_epoch_ms(MIN_EPOCH_MS - 1).is_none());
assert!(civil_from_epoch_ms(MAX_EPOCH_MS).is_some());
assert!(civil_from_epoch_ms(MAX_EPOCH_MS + 1).is_none());
assert_eq!(
try_format_rfc3339_ms(MAX_EPOCH_MS).unwrap(),
"9999-12-31T23:59:59.999Z"
);
}
#[test]
fn negative_years_keep_the_historical_four_wide_signed_form() {
assert_eq!(
try_format_rfc3339_ms(-62_167_219_200_000).unwrap(),
"0000-01-01T00:00:00.000Z"
);
assert_eq!(
try_format_rfc3339_ms(-62_167_219_200_001).unwrap(),
"-001-12-31T23:59:59.999Z"
);
assert_eq!(
try_format_rfc3339_ms(-62_798_785_600_000).unwrap(),
"-021-12-27T04:53:20.000Z"
);
assert_eq!(
try_format_rfc3339_ms(MIN_EPOCH_MS).unwrap(),
"-9999-01-01T00:00:00.000Z"
);
}
}