use alloc::collections::TryReserveError;
use alloc::vec::Vec;
use core::{error, fmt};
use libm::{ceilf, fabsf, sqrtf};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TimeAxisError {
InvalidSegment,
IndexOutOfRange,
InvalidOrigin,
OutOfMemory,
}
impl fmt::Display for TimeAxisError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidSegment => "a rate of the segment is negative or NaN",
Self::IndexOutOfRange => "the index is beyond the end of the time axis",
Self::InvalidOrigin => "the origin is out of range",
Self::OutOfMemory => "out of memory",
})
}
}
impl error::Error for TimeAxisError {}
impl From<TryReserveError> for TimeAxisError {
fn from(_: TryReserveError) -> Self {
Self::OutOfMemory
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TimeSegment {
pub duration_msec: u32,
pub initial_rate: f32,
pub final_rate: f32,
}
impl TimeSegment {
#[must_use]
pub const fn new(duration_msec: u32, initial_rate: f32, final_rate: f32) -> Self {
Self {
duration_msec,
initial_rate,
final_rate,
}
}
#[must_use]
pub const fn realtime(duration_msec: u32) -> Self {
Self::new(duration_msec, 1.0, 1.0)
}
#[must_use]
pub const fn constant_rate(duration_msec: u32, rate: f32) -> Self {
Self::new(duration_msec, rate, rate)
}
#[must_use]
pub const fn slowdown_from(duration_msec: u32, initial_rate: f32) -> Self {
Self::new(duration_msec, initial_rate, 0.0)
}
#[must_use]
pub const fn slowdown_from_realtime(duration_msec: u32) -> Self {
Self::slowdown_from(duration_msec, 1.0)
}
#[must_use]
pub const fn spinup_to(duration_msec: u32, final_rate: f32) -> Self {
Self::new(duration_msec, 0.0, final_rate)
}
#[must_use]
pub const fn spinup_to_realtime(duration_msec: u32) -> Self {
Self::spinup_to(duration_msec, 1.0)
}
#[must_use]
pub fn warped(warped_duration_sec: f32, initial_rate: f32, final_rate: f32) -> Option<Self> {
if warped_duration_sec < 0.0
|| initial_rate < 0.0
|| final_rate < 0.0
|| warped_duration_sec.is_nan()
|| !initial_rate.is_finite()
|| !final_rate.is_finite()
{
return None;
}
if warped_duration_sec == 0.0 {
return Some(Self::new(0, initial_rate, final_rate));
}
let average_rate = average(initial_rate, final_rate);
if average_rate == 0.0 {
return Some(Self::new(u32::MAX, initial_rate, final_rate));
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a non-negative integer; durations beyond u32::MAX saturate to infinity"
)]
let duration_msec = ceilf(warped_duration_sec / average_rate * 1000.0) as u32;
Some(Self::new(duration_msec, initial_rate, final_rate))
}
#[must_use]
#[expect(clippy::float_cmp, reason = "a constant rate is exactly constant")]
pub fn has_constant_rate(&self) -> bool {
self.initial_rate == self.final_rate
}
#[must_use]
pub const fn is_infinite(&self) -> bool {
self.duration_msec == u32::MAX
}
#[must_use]
pub const fn duration_in_wall_clock_time_msec(&self) -> u32 {
self.duration_msec
}
#[must_use]
pub fn duration_in_wall_clock_time_sec(&self) -> f32 {
if self.is_infinite() {
f32::INFINITY
} else {
msec_to_sec(self.duration_msec)
}
}
#[must_use]
pub fn duration_in_warped_time_sec(&self) -> f32 {
let duration_sec = self.duration_in_wall_clock_time_sec();
if duration_sec.is_infinite() {
f32::INFINITY
} else {
duration_sec * average(self.initial_rate, self.final_rate)
}
}
fn validate(&self) -> Result<(), TimeAxisError> {
if self.initial_rate.is_nan()
|| self.final_rate.is_nan()
|| self.initial_rate < 0.0
|| self.final_rate < 0.0
{
Err(TimeAxisError::InvalidSegment)
} else {
Ok(())
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TimeAxis {
origin_msec: i32,
segments: Vec<TimeSegment>,
}
impl TimeAxis {
#[must_use]
pub const fn new() -> Self {
Self {
origin_msec: 0,
segments: Vec::new(),
}
}
#[must_use]
pub const fn capacity(&self) -> usize {
self.segments.capacity()
}
#[must_use]
pub const fn num_segments(&self) -> usize {
self.segments.len()
}
#[must_use]
pub fn segment(&self, index: usize) -> Option<&TimeSegment> {
self.segments.get(index)
}
#[must_use]
pub fn segments(&self) -> &[TimeSegment] {
&self.segments
}
#[must_use]
pub const fn origin_msec(&self) -> i32 {
self.origin_msec
}
#[must_use]
#[expect(
clippy::cast_precision_loss,
reason = "times in seconds are floats, as in the C library"
)]
pub fn origin_sec(&self) -> f32 {
self.origin_msec as f32 / 1000.0
}
pub const fn set_origin_msec(&mut self, origin_msec: i32) -> Result<(), TimeAxisError> {
if origin_msec < 0 {
return Err(TimeAxisError::InvalidOrigin);
}
self.origin_msec = origin_msec;
Ok(())
}
#[expect(
clippy::cast_precision_loss,
reason = "the limit is compared with a float, as in the C library"
)]
pub fn set_origin_sec(&mut self, origin_sec: f32) -> Result<(), TimeAxisError> {
if !origin_sec.is_finite() || origin_sec < 0.0 || origin_sec > (i32::MAX / 1000) as f32 {
return Err(TimeAxisError::InvalidOrigin);
}
#[expect(
clippy::cast_possible_truncation,
reason = "the origin is in the range of i32 and is truncated, as in the C library"
)]
let origin_msec = (origin_sec * 1000.0) as i32;
self.origin_msec = origin_msec;
Ok(())
}
#[must_use]
pub fn total_duration_msec(&self) -> u32 {
let mut total: u32 = 0;
for segment in &self.segments {
if segment.is_infinite() {
return u32::MAX;
}
let Some(sum) = total.checked_add(segment.duration_msec) else {
return u32::MAX;
};
total = sum;
}
total
}
#[must_use]
pub fn total_duration_sec(&self) -> f32 {
match self.total_duration_msec() {
u32::MAX => f32::INFINITY,
total => msec_to_sec(total),
}
}
#[must_use]
pub fn total_warped_duration_sec(&self) -> f32 {
self.segments
.iter()
.map(TimeSegment::duration_in_warped_time_sec)
.fold(0.0, |total, duration| total + duration)
}
pub fn clear(&mut self) {
self.segments.clear();
}
pub fn append_segment(&mut self, segment: TimeSegment) -> Result<(), TimeAxisError> {
self.insert_segment_at(self.segments.len(), segment)
}
pub fn insert_segment_at(
&mut self,
index: usize,
segment: TimeSegment,
) -> Result<(), TimeAxisError> {
if index > self.segments.len() {
return Err(TimeAxisError::IndexOutOfRange);
}
segment.validate()?;
self.segments.try_reserve(1)?;
self.segments.insert(index, segment);
Ok(())
}
pub fn remove_segment_at(&mut self, index: usize) -> Option<TimeSegment> {
(index < self.segments.len()).then(|| self.segments.remove(index))
}
#[must_use]
pub fn map(&self, wall_clock_time_msec: i32) -> f32 {
self.map_with_rate(wall_clock_time_msec).0
}
#[must_use]
#[expect(
clippy::cast_precision_loss,
reason = "times in seconds are floats, as in the C library"
)]
pub fn map_with_rate(&self, wall_clock_time_msec: i32) -> (f32, f32) {
let Ok(mut msec) =
u32::try_from(i64::from(wall_clock_time_msec) - i64::from(self.origin_msec))
else {
let msec = i64::from(wall_clock_time_msec) - i64::from(self.origin_msec);
return (msec as f32 / 1000.0, 1.0);
};
if self.segments.is_empty() {
return (msec_to_sec(msec), 1.0);
}
let mut accumulated_sec = 0.0;
for segment in &self.segments {
let duration_msec = segment.duration_msec;
if segment.is_infinite() || duration_msec > msec {
let (in_segment_sec, rate) = if segment.is_infinite() || segment.has_constant_rate()
{
(
msec_to_sec(msec) * segment.initial_rate,
segment.initial_rate,
)
} else if duration_msec > 0 {
let delta_rate = segment.final_rate - segment.initial_rate;
let relative_time = msec as f32 / duration_msec as f32;
(
(segment.initial_rate + delta_rate / 2.0 * relative_time) * msec as f32
/ 1000.0,
segment.initial_rate + delta_rate * relative_time,
)
} else {
(0.0, average(segment.initial_rate, segment.final_rate))
};
return (accumulated_sec + in_segment_sec, rate);
}
msec -= duration_msec;
accumulated_sec += segment.duration_in_warped_time_sec();
}
let final_rate = self
.segments
.last()
.map_or(1.0, |segment| segment.final_rate);
(accumulated_sec + msec_to_sec(msec) * final_rate, final_rate)
}
#[must_use]
pub fn reverse_map(&self, time_sec: f32) -> i32 {
let wall_clock_sec = if time_sec.is_nan() {
0.0
} else if time_sec.is_infinite() {
return if time_sec < 0.0 { i32::MIN } else { i32::MAX };
} else if time_sec < 0.0 || self.segments.is_empty() {
time_sec
} else {
self.reverse_map_segments(time_sec)
};
if !wall_clock_sec.is_finite() {
return if wall_clock_sec < 0.0 {
i32::MIN
} else {
i32::MAX
};
}
#[expect(
clippy::cast_possible_truncation,
reason = "truncated as in the C library; out of range values saturate"
)]
let msec = (wall_clock_sec * 1000.0) as i32;
self.origin_msec.saturating_add(msec)
}
fn reverse_map_segments(&self, time_sec: f32) -> f32 {
let mut remaining_sec = time_sec;
let mut accumulated_sec = 0.0;
for segment in &self.segments {
if remaining_sec <= 0.0 {
break;
}
let warped_duration_sec = segment.duration_in_warped_time_sec();
if remaining_sec < warped_duration_sec {
if !warped_duration_sec.is_finite() || segment.has_constant_rate() {
accumulated_sec += if segment.initial_rate != 0.0 {
remaining_sec / segment.initial_rate
} else if remaining_sec > 0.0 {
f32::INFINITY
} else {
0.0
};
} else if warped_duration_sec > 0.0 {
let roots = solve_quadratic(
(segment.final_rate - segment.initial_rate)
/ (2.0 * segment.duration_in_wall_clock_time_sec()),
segment.initial_rate,
-remaining_sec,
);
accumulated_sec += match roots {
[Some(first), Some(second)] => {
if first >= 0.0 {
first
} else {
second
}
}
[Some(root), None] => root,
_ => 0.0,
};
}
return accumulated_sec;
}
remaining_sec -= warped_duration_sec;
accumulated_sec += segment.duration_in_wall_clock_time_sec();
}
if remaining_sec > 0.0 {
let final_rate = self
.segments
.last()
.map_or(1.0, |segment| segment.final_rate);
accumulated_sec += if final_rate == 0.0 {
f32::INFINITY
} else {
remaining_sec / final_rate
};
}
accumulated_sec
}
}
#[expect(clippy::manual_midpoint, reason = "rounded like the C library")]
fn average(first: f32, second: f32) -> f32 {
(first + second) / 2.0
}
fn solve_quadratic(a: f32, b: f32, c: f32) -> [Option<f32>; 2] {
if fabsf(a) < f32::MIN_POSITIVE {
if fabsf(b) < f32::MIN_POSITIVE {
return [None, None];
}
return [Some(-c / b), None];
}
let d = b * b - 4.0 * a * c;
if fabsf(d) < f32::MIN_POSITIVE {
return [Some(-b / (2.0 * a)), None];
}
if d > 0.0 {
let d = sqrtf(d);
let (low, high) = ((-b - d) / (2.0 * a), (-b + d) / (2.0 * a));
return if a < 0.0 {
[Some(high), Some(low)]
} else {
[Some(low), Some(high)]
};
}
[None, None]
}
#[expect(
clippy::cast_precision_loss,
reason = "times in seconds are floats, as in the C library"
)]
fn msec_to_sec(msec: u32) -> f32 {
msec as f32 / 1000.0
}