1use std::time::Duration;
4
5use crate::{
6 Error, Result,
7 video::{VideoFrameTiming, VideoTimeBase},
8};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
12pub struct MediaTimestamp(u64);
13
14impl MediaTimestamp {
15 pub const fn new_from_microseconds(value: u64) -> Self {
16 Self(value)
17 }
18
19 pub const fn as_microseconds(self) -> u64 {
20 self.0
21 }
22
23 pub fn has_reached(self, boundary: Duration) -> bool {
25 boundary <= Duration::from_micros(self.0)
26 }
27
28 pub fn frame_is_due(self, timing: VideoFrameTiming) -> Result<bool> {
33 let duration = timing.duration().ok_or_else(|| {
34 Error::missing_capability("MediaPlayer requires known video frame durations")
35 })?;
36 let next_boundary = timing
37 .presentation_timestamp()
38 .checked_add(duration)
39 .ok_or_else(|| Error::out_of_range("video presentation time overflowed"))?;
40 Ok(self.has_reached(next_boundary))
41 }
42
43 pub fn to_video_ticks(self, base: VideoTimeBase) -> Result<u64> {
45 let ticks = u128::from(self.0) * u128::from(base.denominator())
46 / (u128::from(base.numerator()) * 1_000_000);
47 u64::try_from(ticks).map_err(|_| Error::out_of_range("media timestamp exceeds video time base"))
48 }
49}
50
51#[derive(Clone, Copy)]
53pub(super) struct TrackTimeline {
54 pub start: Duration,
55 pub end: Duration,
56 media_start: Duration,
57 media_end: Option<Duration>,
58}
59
60impl TrackTimeline {
61 pub fn new(edit: crate::video::Mp4TrackEdit, raw_duration: Duration) -> Result<Self> {
62 let length = edit
63 .length
64 .unwrap_or_else(|| raw_duration.saturating_sub(edit.media_start));
65 let media_end = edit
66 .length
67 .map(|length| {
68 edit
69 .media_start
70 .checked_add(length)
71 .ok_or_else(|| Error::out_of_range("media segment end exceeds Duration"))
72 })
73 .transpose()?;
74 let end = edit
75 .movie_start
76 .checked_add(length)
77 .ok_or_else(|| Error::out_of_range("movie edit end exceeds Duration"))?;
78 Ok(Self {
79 start: edit.movie_start,
80 end,
81 media_start: edit.media_start,
82 media_end,
83 })
84 }
85
86 pub fn movie_at(&self, media: Duration) -> Duration {
87 self
88 .start
89 .saturating_add(media.saturating_sub(self.media_start))
90 }
91
92 pub fn media_at(&self, movie: Duration) -> Duration {
93 let elapsed = movie.saturating_sub(self.start);
94 let time = self.media_start.saturating_add(elapsed);
95 self.media_end.map_or(time, |end| {
96 time.min(end.saturating_sub(Duration::from_nanos(1)))
97 })
98 }
99
100 pub fn contains(&self, movie: Duration) -> bool {
101 movie >= self.start && (self.end == self.start || movie < self.end)
102 }
103
104 pub fn is_past_end(&self, media: Duration) -> bool {
105 self.media_end.is_some_and(|end| media >= end)
106 }
107}