1 //! The clip: the frame size, the rate, the frame count, and the frame range.2 //!3 //! A job names a time range, not a frame range. The conversion belongs here so4 //! that every plugin cuts the range at the same frame.5 6 use std::time::Duration;7 8 use crate::VideoError;9 use crate::time::{NANOS_PER_SEC, Rational, Timebase, duration_from_nanos};10 11 /// The largest side that any codec in the deploy carries.12 pub const MAX_SIDE: u32 = 16384;13 14 /// A clip as a client describes it: no pixels, only the shape and the rate.15 #[derive(Clone, Copy, PartialEq, Eq, Debug)]16 pub struct Clip {17 /// Frame width in pixels.18 pub width: u32,19 /// Frame height in pixels.20 pub height: u32,21 /// Frames per second.22 pub fps: Rational,23 /// Number of frames in the clip.24 pub frames: u64,25 }26 27 impl Clip {28 /// A clip that a container and an encoder can carry.29 pub fn new(width: u32, height: u32, fps: Rational, frames: u64) -> Result<Clip, VideoError> {30 if width == 0 || height == 0 || frames == 0 {31 return Err(VideoError::Empty);32 }33 if width > MAX_SIDE || height > MAX_SIDE {34 return Err(VideoError::TooLarge);35 }36 if fps.num == 0 {37 return Err(VideoError::Division);38 }39 Ok(Clip {40 width,41 height,42 fps,43 frames,44 })45 }46 47 /// The wall time of the whole clip.48 pub fn duration(&self) -> Duration {49 if self.fps.num == 0 {50 return Duration::ZERO;51 }52 let numerator = u128::from(self.frames)53 .saturating_mul(u128::from(self.fps.den))54 .saturating_mul(NANOS_PER_SEC);55 duration_from_nanos(numerator / u128::from(self.fps.num))56 }57 58 /// The frames that a range covers: `[from, to)` in time, clipped to the59 /// clip, rounding each edge down to the frame that contains it.60 pub fn range(&self, from: Duration, to: Duration) -> (u64, u64) {61 let end = self.duration();62 let from = from.min(end);63 let to = to.min(end);64 let start = self.frame_at(from, end);65 if to <= from {66 return (start, start);67 }68 (start, self.frame_at(to, end))69 }70 71 /// The timebase of the track. One tick is one frame period.72 pub fn timebase(&self) -> Timebase {73 Timebase(Rational {74 num: self.fps.den,75 den: self.fps.num,76 })77 }78 79 /// The frame that contains `at`, clamped to the frame count.80 fn frame_at(&self, at: Duration, end: Duration) -> u64 {81 if self.fps.num == 0 {82 return 0;83 }84 let at = at.min(end);85 let numerator = at.as_nanos().saturating_mul(u128::from(self.fps.num));86 let denominator = u128::from(self.fps.den).saturating_mul(NANOS_PER_SEC);87 let frame = numerator / denominator;88 u64::try_from(frame.min(u128::from(self.frames))).unwrap_or(self.frames)89 }90 }