//! Where the transport is, how loud it is, and the seek rate limits. use crate::*; /// What the header says with no timeline open, and what the window title reads /// as a program name rather than as a file name. pub(crate) const NO_FILE: &str = "no file open"; /// What a press of play says when there is nothing to play: no timeline at all /// and an emptied one are the same answer to the user, so they are one line. pub(crate) const NOTHING_TO_PLAY: &str = "Nothing to play: the timeline is empty"; /// Whether a press of play would have anything to play. No timeline at all and /// one every clip has been taken off are the same state to a transport, and the /// button and the key both have to give the same answer to it -- so there is /// one of them, and it is free of the window so it can be checked without one. pub(crate) fn nothing_to_play(session: Option<&PlaybackSession>) -> bool { session.is_none_or(PlaybackSession::is_empty) } /// What the monitoring output is set to. Two things, not one: the level the /// user picked, and whether it is being held silent -- so unmuting comes back /// to the level rather than to a guess. /// /// The level counts steps rather than carrying an `f32`, because 5% at a time /// down and back up again through a float would not land on the number it /// started from, and the label would eventually read `79%`. /// /// Volume and mute stay independent on purpose: turning the level down while /// muted must not be what makes sound come out. Only the mute key unmutes, and /// the button says both things at once ("Muted 80%") so neither is a surprise. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) struct Volume { pub(crate) steps: u8, pub(crate) muted: bool, } impl Volume { /// One step is one percent: fine enough that a drag along the slider reads /// as continuous, and still a count rather than a float. pub(crate) const MAX_STEPS: u8 = 100; /// 5% a press: twenty presses across the range, which is what the keys have /// always moved. The slider is what the finer grid is for. pub(crate) const KEY_STEP: u8 = 5; /// What the device is set to: mute wins, and the level is what it returns /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts. pub(crate) fn gain(self) -> f32 { if self.muted { 0. } else { self.along() } } /// One press up or down, clamped at both ends -- saturating, so the count /// cannot wrap past silence into full volume. pub(crate) fn step(&mut self, up: bool) { self.steps = if up { self.steps .saturating_add(Self::KEY_STEP) .min(Self::MAX_STEPS) } else { self.steps.saturating_sub(Self::KEY_STEP) }; } /// Where the hand let go along the slider, 0..1 from silence to full. The /// grid is the same one the keys land on, so a drag to the top and a key /// held up reach the very same number -- and a drag never touches mute: /// asking for a level while muted is not asking for sound. pub(crate) fn set_along(&mut self, frac: f32) { self.steps = (frac.clamp(0., 1.) * f32::from(Self::MAX_STEPS)).round() as u8; } /// How full the slider is drawn, 0..1. The level and not the gain: a muted /// slider still shows what unmuting comes back to, exactly as the label /// does. pub(crate) fn along(self) -> f32 { f32::from(self.steps) / f32::from(Self::MAX_STEPS) } /// The level as a number to read out, 0..=100 -- what the settings page's /// Level row says (`100%`), the one place the level is written since the /// time band lost its slider. pub(crate) fn percent(self) -> u32 { u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS) } /// What the button read before the mute state became a glyph and a colour /// ([`Player::toolbar`]): the guards still hold the wording to it, so it /// sits with them rather than in the binary. #[cfg(test)] pub(crate) fn label(self) -> String { let percent = self.percent(); if self.muted { format!("Muted {percent}%") } else { format!("Vol {percent}%") } } } impl Default for Volume { fn default() -> Self { Self { steps: Self::MAX_STEPS, muted: false, } } } /// Where the transport is. The one answer the button's glyph, its label, its /// enablement, the play key and the repaint loop all read -- there is no play /// flag anywhere else, because a second one is a second answer. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Transport { /// No timeline open. Nothing to play and the transport is dimmed. Stopped, Playing, Paused, /// Played out: the last frame is on screen, the decoder is finished, and the /// clock is still running past it -- which is exactly why "is the clock /// going" is not the same question as "is this playing". Ended, } impl Transport { /// The timeline is in motion: two bars on the button, and a repaint owed /// every vsync. pub(crate) fn is_playing(self) -> bool { matches!(self, Transport::Playing) } /// The play key and the transport button start over from the top rather /// than toggling -- the end of a timeline is where every NLE does this, and /// the button does it because the key already did. pub(crate) fn restarts(self) -> bool { matches!(self, Transport::Ended) } } /// What a session's own two answers mean: the clock, unless the timeline has /// been played out -- `played_out` is the engine's end of stream with no frame /// still waiting on the pump, and it wins, because past the end a running clock /// is measuring wall time and not a picture. pub(crate) fn transport(playing: bool, played_out: bool) -> Transport { match (played_out, playing) { (true, _) => Transport::Ended, (_, true) => Transport::Playing, (_, false) => Transport::Paused, } } /// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the /// hardware path for the small files it was measured on (215 ms in software), so /// one seek per mouse move would only queue workers that are cancelled before /// they decode anything. /// /// It is a *floor*, not a bound: the reopen is a demux open /// ([`engine::decode::open_worker`]), and on a 25 GB film that is 550-750 ms -- /// five to seven times this gap, which therefore gates nothing there. Where the /// cost had to be bounded rather than thinned -- the colour and speed drags -- /// the gate is the frame the worker delivers ([`Player::flush_drag`]) and no /// timer at all. The ruler keeps this one: a scrub has no value to hold back, /// only a position that the next mouse move replaces anyway. pub(crate) const SCRUB_GAP: Duration = Duration::from_millis(100); pub(crate) fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool { target != last_target && since >= SCRUB_GAP } /// How far the picture may fall behind the sound before it is restarted at the /// clock instead of left to crawl after it. Past what an eye reads as lip sync /// (a tenth of a second or so) and above what a single reopen costs to fix, so a /// picture that is merely a reopen behind is not answered with another one. pub(crate) const LATE_RESYNC: f64 = 0.4; /// The least time between two such restarts: the decoder that cannot keep up is /// the one this fires for, and it will still be behind straight afterwards. pub(crate) const RESYNC_GAP: Duration = Duration::from_secs(2); /// Whether a picture `late` seconds behind the master clock is restarted at it, /// given when the last restart was ([`Player::pump`]). pub(crate) fn should_resync(late: f64, last: Option) -> bool { late > LATE_RESYNC && last.is_none_or(|t| t.elapsed() >= RESYNC_GAP) } /// The gate a live drag sample goes through. With the worker still owing a /// frame (`busy`), writing now would only cancel the open the picture is already /// waiting for -- the sample is held in `stash` instead, and the frame that /// lands writes it ([`Player::flush_drag`]). Returns what to write, if anything. /// /// The press (`first`) never waits: it is the undo step the whole gesture rolls /// back to, so it has to be taken against the state the hand picked up. pub(crate) fn stash_or_write( stash: &mut Option, value: T, first: bool, busy: bool, ) -> Option { match busy && !first { true => { *stash = Some(value); None } false => Some(value), } } /// Which of a visualizer's two inks a look control acts on: the clip's own /// colour, or the second half of a dual-strand ring. Zero -- the clip's own -- /// is what every control meant before there was a second, so it is also what /// the Clip tab opens on ([`Player::viz_slot`]). /// /// Both inks are read and written through the same three methods, so the /// wheel, the hex field and the drag that holds a sample between them cannot /// disagree about which one a gesture is on. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum VizSlot { /// The clip's own hue and saturation -- the paint field's low bytes. Main, /// The ring's dual half. Only a clip that chose one wears it; otherwise /// the painter draws the automatic complement (`visualizer_i420`). Strand, } impl VizSlot { /// The ink with a picture behind it. A one-strand ring has no dual half, /// so a wheel on the strand colour there would move a mark and nothing /// else: every control reads the slot through here and lands on the clip's /// own colour instead while that is the case -- which is also why the /// Strand chip is dead then. pub(crate) fn picked(self, paint: u64) -> VizSlot { match self { VizSlot::Strand if engine::decode::viz_strands_of(paint) < 2 => VizSlot::Main, slot => slot, } } /// What this ink is showing: the clip's hue and saturation, or -- for a /// strand the clip has not chosen -- the automatic complement the painter /// draws there, so a hand picking the strand up starts where the picture /// already is and the first write only says "this one, then". pub(crate) fn hue_sat(self, paint: u64) -> (u8, u8) { match self { VizSlot::Main => ( engine::decode::viz_hue_ui(paint), engine::decode::viz_sat_ui(paint), ), VizSlot::Strand if engine::decode::viz_strand_set(paint) => ( engine::decode::viz_strand_hue_ui(paint), engine::decode::viz_strand_sat_ui(paint), ), VizSlot::Strand => ( engine::decode::viz_hue_ui(paint).wrapping_add(128), engine::decode::viz_sat_ui(paint), ), } } /// Sets this ink's hue and saturation, raising the strand's chosen flag on /// the way -- the engine's strand setters do that, which is what makes the /// wheel's first sample on the slot the write that chooses it. pub(crate) fn set_hue_sat(self, paint: u64, hue: u8, sat: u8) -> u64 { match self { VizSlot::Main => engine::decode::with_viz_paint_sat( engine::decode::with_viz_paint_hue(paint, hue), sat, ), VizSlot::Strand => engine::decode::with_viz_paint_strand_sat( engine::decode::with_viz_paint_strand_hue(paint, hue), sat, ), } } } /// What the wheel draws: the clip's own ink, or the sample a drag is holding /// while the worker is still behind ([`stash_or_write`]). The wheel is a /// picker with no table of its own, so a held sample would otherwise be /// invisible -- the clip carries the sample *before* it until the holding /// frame lands -- and the mark would sit still under a moving hand. /// [`Player::color_params`] holds exactly this rule for the card's sliders. /// /// The held sample carries its slot, so a drag on the strand colour draws the /// strand colour even before the clip has one of its own. pub(crate) fn viz_held_paint(paint: u64, held: Option<(VizSlot, u8, u8)>) -> u64 { match held { Some((slot, hue, sat)) => slot.set_hue_sat(paint, hue, sat), None => paint, } } /// How long an open may stand before the window says so in words. Well past an /// ordinary seek (a warm reopen is under a tenth of this) and well under what a /// cold read of a big film takes, which is the only case worth a line. pub(crate) const SEEK_STALL: Duration = Duration::from_secs(2); /// How long before the line counts the seconds. pub(crate) const SEEK_COUNT: Duration = Duration::from_secs(3); /// How long a picture may stand unopened before the line stops saying it is opening and says /// why it cannot be shown. A slow read still lands inside this; a compound or a missing file /// never does, and a running timer over it would be a lie. pub(crate) const SEEK_GIVE_UP: Duration = Duration::from_secs(8); /// What a seek that has stood past [`SEEK_STALL`] says, and nothing at all /// before that: a line on every click of the ruler would be a flicker, and the /// picture holding still for a tenth of a second is not something to explain. /// Short and plain; the seconds only once they say something (a window that /// cannot move and a window that has hung look identical, so this one counts). /// A picture whose file is off the disk is the banner's to say (`missing_clip_note`), so this /// line is only for a read that failed. pub(crate) fn seek_line(standing: Option) -> Option { let since = standing.filter(|d| *d >= SEEK_STALL)?; if since >= SEEK_GIVE_UP { return Some("Can't show this frame: nothing could be read at the playhead.".to_string()); } Some(match since >= SEEK_COUNT { true => format!("Opening the picture\u{2026} {} s", since.as_secs()), false => "Opening the picture\u{2026}".to_string(), }) } /// Where along the preview's own seek bar a click landed, in seconds from /// the start: [`frac_along`]'s fraction of `duration`, since the bar spans /// the preview's whole length rather than a zoomed timeline `Scale` -- a /// preview does not zoom, so there is no bed narrower than the file to map /// into. pub(crate) fn preview_seek_seconds(x: Pixels, bar: Bounds, duration: f64) -> f64 { f64::from(frac_along(x, bar)) * duration.max(0.) } /// How full the preview's seek bar is drawn, 0..1: the played share of the /// duration, clamped for the same reason [`frac_along`] clamps a click -- a /// clock a frame past the end must not overhang the track it is drawn on. /// Zero for a duration of nothing, rather than a NaN from dividing by it. pub(crate) fn preview_progress_along(now: f64, duration: f64) -> f32 { if duration <= 0. { return 0.; } (now / duration).clamp(0., 1.) as f32 } /// Where the ruler draws the playhead, given whether *the timeline's own* /// session ([`Player::session`]) has played out. `ended` must answer for /// `session` specifically, never for [`Player::active_session`] -- a preview /// reaching *its* end is not the timeline's own playhead running out, and /// must not snap the ruler to `duration` while the timeline sits wherever it /// was left (a seek, mid-scrub, anywhere). `now` is `session`'s own clock, /// which a preview never touches. pub(crate) fn playhead_position(now: f64, ended: bool, duration: f64) -> f64 { if ended { duration } else { now.clamp(0., duration) } } #[cfg(test)] mod tests { use super::*; /// A click at either end of the bar lands exactly on the file's own /// ends, the middle lands at half the duration, and a click past either /// edge clamps to it rather than reading negative or past the end -- /// `frac_along`'s own clamp, carried through. #[test] fn preview_seek_seconds_maps_the_bar_to_the_file() { let bar = Bounds { origin: point(px(100.), px(0.)), size: size(px(200.), px(HIT_MIN)), }; assert_eq!(preview_seek_seconds(px(100.), bar, 60.), 0.); assert_eq!(preview_seek_seconds(px(300.), bar, 60.), 60.); assert_eq!(preview_seek_seconds(px(200.), bar, 60.), 30.); // Off both ends -- the pointer left the bar, and the seek clamps to // the end it left through. assert_eq!(preview_seek_seconds(px(0.), bar, 60.), 0.); assert_eq!(preview_seek_seconds(px(500.), bar, 60.), 60.); } /// Ended pins the ruler to the out point; short of that it tracks the /// clock, clamped -- a tail dragged past the end must not walk the ruler /// off the bed. #[test] fn playhead_position_pins_only_on_the_sessions_own_end() { assert_eq!(playhead_position(8., false, 35.), 8.); assert_eq!(playhead_position(35., true, 35.), 35.); assert_eq!(playhead_position(40., false, 35.), 35.); // A preview ending must not read as `ended` for this call at all -- // it is the caller's job to pass `false` while one is up, which is // exactly what leaves the ruler on the timeline's own clock. assert_eq!(playhead_position(8., false, 35.), 8.); } /// The fill tracks the played share exactly, and a duration of nothing /// -- no file open yet -- reads as an empty bar rather than a divide by /// zero. #[test] fn preview_progress_along_is_the_played_share() { assert_eq!(preview_progress_along(0., 60.), 0.); assert_eq!(preview_progress_along(30., 60.), 0.5); assert_eq!(preview_progress_along(60., 60.), 1.); // Past the end clamps rather than overhanging the track. assert_eq!(preview_progress_along(61., 60.), 1.); assert_eq!(preview_progress_along(5., 0.), 0.); } }