forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

transport.rs406 lines, 17.6 KiBHistoryRawDownload
1//! Where the transport is, how loud it is, and the seek rate limits.
2
3use crate::*;
4
5/// What the header says with no timeline open, and what the window title reads
6/// as a program name rather than as a file name.
7pub(crate) const NO_FILE: &str = "no file open";
8
9/// What a press of play says when there is nothing to play: no timeline at all
10/// and an emptied one are the same answer to the user, so they are one line.
11pub(crate) const NOTHING_TO_PLAY: &str = "Nothing to play: the timeline is empty";
12
13/// Whether a press of play would have anything to play. No timeline at all and
14/// one every clip has been taken off are the same state to a transport, and the
15/// button and the key both have to give the same answer to it -- so there is
16/// one of them, and it is free of the window so it can be checked without one.
17pub(crate) fn nothing_to_play(session: Option<&PlaybackSession>) -> bool {
18 session.is_none_or(PlaybackSession::is_empty)
19}
20
21/// What the monitoring output is set to. Two things, not one: the level the
22/// user picked, and whether it is being held silent -- so unmuting comes back
23/// to the level rather than to a guess.
24///
25/// The level counts steps rather than carrying an `f32`, because 5% at a time
26/// down and back up again through a float would not land on the number it
27/// started from, and the label would eventually read `79%`.
28///
29/// Volume and mute stay independent on purpose: turning the level down while
30/// muted must not be what makes sound come out. Only the mute key unmutes, and
31/// the button says both things at once ("Muted 80%") so neither is a surprise.
32#[derive(Clone, Copy, PartialEq, Eq, Debug)]
33pub(crate) struct Volume {
34 pub(crate) steps: u8,
35 pub(crate) muted: bool,
36}
37
38impl Volume {
39 /// One step is one percent: fine enough that a drag along the slider reads
40 /// as continuous, and still a count rather than a float.
41 pub(crate) const MAX_STEPS: u8 = 100;
42
43 /// 5% a press: twenty presses across the range, which is what the keys have
44 /// always moved. The slider is what the finer grid is for.
45 pub(crate) const KEY_STEP: u8 = 5;
46
47 /// What the device is set to: mute wins, and the level is what it returns
48 /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts.
49 pub(crate) fn gain(self) -> f32 {
50 if self.muted { 0. } else { self.along() }
51 }
52
53 /// One press up or down, clamped at both ends -- saturating, so the count
54 /// cannot wrap past silence into full volume.
55 pub(crate) fn step(&mut self, up: bool) {
56 self.steps = if up {
57 self.steps
58 .saturating_add(Self::KEY_STEP)
59 .min(Self::MAX_STEPS)
60 } else {
61 self.steps.saturating_sub(Self::KEY_STEP)
62 };
63 }
64
65 /// Where the hand let go along the slider, 0..1 from silence to full. The
66 /// grid is the same one the keys land on, so a drag to the top and a key
67 /// held up reach the very same number -- and a drag never touches mute:
68 /// asking for a level while muted is not asking for sound.
69 pub(crate) fn set_along(&mut self, frac: f32) {
70 self.steps = (frac.clamp(0., 1.) * f32::from(Self::MAX_STEPS)).round() as u8;
71 }
72
73 /// How full the slider is drawn, 0..1. The level and not the gain: a muted
74 /// slider still shows what unmuting comes back to, exactly as the label
75 /// does.
76 pub(crate) fn along(self) -> f32 {
77 f32::from(self.steps) / f32::from(Self::MAX_STEPS)
78 }
79
80 /// The level as a number to read out, 0..=100 -- what the settings page's
81 /// Level row says (`100%`), the one place the level is written since the
82 /// time band lost its slider.
83 pub(crate) fn percent(self) -> u32 {
84 u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS)
85 }
86
87 /// What the button read before the mute state became a glyph and a colour
88 /// ([`Player::toolbar`]): the guards still hold the wording to it, so it
89 /// sits with them rather than in the binary.
90 #[cfg(test)]
91 pub(crate) fn label(self) -> String {
92 let percent = self.percent();
93 if self.muted {
94 format!("Muted {percent}%")
95 } else {
96 format!("Vol {percent}%")
97 }
98 }
99}
100
101impl Default for Volume {
102 fn default() -> Self {
103 Self {
104 steps: Self::MAX_STEPS,
105 muted: false,
106 }
107 }
108}
109
110/// Where the transport is. The one answer the button's glyph, its label, its
111/// enablement, the play key and the repaint loop all read -- there is no play
112/// flag anywhere else, because a second one is a second answer.
113#[derive(Clone, Copy, PartialEq, Eq, Debug)]
114pub(crate) enum Transport {
115 /// No timeline open. Nothing to play and the transport is dimmed.
116 Stopped,
117 Playing,
118 Paused,
119 /// Played out: the last frame is on screen, the decoder is finished, and the
120 /// clock is still running past it -- which is exactly why "is the clock
121 /// going" is not the same question as "is this playing".
122 Ended,
123}
124
125impl Transport {
126 /// The timeline is in motion: two bars on the button, and a repaint owed
127 /// every vsync.
128 pub(crate) fn is_playing(self) -> bool {
129 matches!(self, Transport::Playing)
130 }
131
132 /// The play key and the transport button start over from the top rather
133 /// than toggling -- the end of a timeline is where every NLE does this, and
134 /// the button does it because the key already did.
135 pub(crate) fn restarts(self) -> bool {
136 matches!(self, Transport::Ended)
137 }
138}
139
140/// What a session's own two answers mean: the clock, unless the timeline has
141/// been played out -- `played_out` is the engine's end of stream with no frame
142/// still waiting on the pump, and it wins, because past the end a running clock
143/// is measuring wall time and not a picture.
144pub(crate) fn transport(playing: bool, played_out: bool) -> Transport {
145 match (played_out, playing) {
146 (true, _) => Transport::Ended,
147 (_, true) => Transport::Playing,
148 (_, false) => Transport::Paused,
149 }
150}
151
152/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the
153/// hardware path for the small files it was measured on (215 ms in software), so
154/// one seek per mouse move would only queue workers that are cancelled before
155/// they decode anything.
156///
157/// It is a *floor*, not a bound: the reopen is a demux open
158/// ([`engine::decode::open_worker`]), and on a 25 GB film that is 550-750 ms --
159/// five to seven times this gap, which therefore gates nothing there. Where the
160/// cost had to be bounded rather than thinned -- the colour and speed drags --
161/// the gate is the frame the worker delivers ([`Player::flush_drag`]) and no
162/// timer at all. The ruler keeps this one: a scrub has no value to hold back,
163/// only a position that the next mouse move replaces anyway.
164pub(crate) const SCRUB_GAP: Duration = Duration::from_millis(100);
165
166pub(crate) fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool {
167 target != last_target && since >= SCRUB_GAP
168}
169
170/// How far the picture may fall behind the sound before it is restarted at the
171/// clock instead of left to crawl after it. Past what an eye reads as lip sync
172/// (a tenth of a second or so) and above what a single reopen costs to fix, so a
173/// picture that is merely a reopen behind is not answered with another one.
174pub(crate) const LATE_RESYNC: f64 = 0.4;
175/// The least time between two such restarts: the decoder that cannot keep up is
176/// the one this fires for, and it will still be behind straight afterwards.
177pub(crate) const RESYNC_GAP: Duration = Duration::from_secs(2);
178
179/// Whether a picture `late` seconds behind the master clock is restarted at it,
180/// given when the last restart was ([`Player::pump`]).
181pub(crate) fn should_resync(late: f64, last: Option<Instant>) -> bool {
182 late > LATE_RESYNC && last.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
183}
184
185/// The gate a live drag sample goes through. With the worker still owing a
186/// frame (`busy`), writing now would only cancel the open the picture is already
187/// waiting for -- the sample is held in `stash` instead, and the frame that
188/// lands writes it ([`Player::flush_drag`]). Returns what to write, if anything.
189///
190/// The press (`first`) never waits: it is the undo step the whole gesture rolls
191/// back to, so it has to be taken against the state the hand picked up.
192pub(crate) fn stash_or_write<T: Copy>(
193 stash: &mut Option<T>,
194 value: T,
195 first: bool,
196 busy: bool,
197) -> Option<T> {
198 match busy && !first {
199 true => {
200 *stash = Some(value);
201 None
202 }
203 false => Some(value),
204 }
205}
206
207/// Which of a visualizer's two inks a look control acts on: the clip's own
208/// colour, or the second half of a dual-strand ring. Zero -- the clip's own --
209/// is what every control meant before there was a second, so it is also what
210/// the Clip tab opens on ([`Player::viz_slot`]).
211///
212/// Both inks are read and written through the same three methods, so the
213/// wheel, the hex field and the drag that holds a sample between them cannot
214/// disagree about which one a gesture is on.
215#[derive(Clone, Copy, PartialEq, Eq, Debug)]
216pub(crate) enum VizSlot {
217 /// The clip's own hue and saturation -- the paint field's low bytes.
218 Main,
219 /// The ring's dual half. Only a clip that chose one wears it; otherwise
220 /// the painter draws the automatic complement (`visualizer_i420`).
221 Strand,
222}
223
224impl VizSlot {
225 /// The ink with a picture behind it. A one-strand ring has no dual half,
226 /// so a wheel on the strand colour there would move a mark and nothing
227 /// else: every control reads the slot through here and lands on the clip's
228 /// own colour instead while that is the case -- which is also why the
229 /// Strand chip is dead then.
230 pub(crate) fn picked(self, paint: u64) -> VizSlot {
231 match self {
232 VizSlot::Strand if engine::decode::viz_strands_of(paint) < 2 => VizSlot::Main,
233 slot => slot,
234 }
235 }
236
237 /// What this ink is showing: the clip's hue and saturation, or -- for a
238 /// strand the clip has not chosen -- the automatic complement the painter
239 /// draws there, so a hand picking the strand up starts where the picture
240 /// already is and the first write only says "this one, then".
241 pub(crate) fn hue_sat(self, paint: u64) -> (u8, u8) {
242 match self {
243 VizSlot::Main => (
244 engine::decode::viz_hue_ui(paint),
245 engine::decode::viz_sat_ui(paint),
246 ),
247 VizSlot::Strand if engine::decode::viz_strand_set(paint) => (
248 engine::decode::viz_strand_hue_ui(paint),
249 engine::decode::viz_strand_sat_ui(paint),
250 ),
251 VizSlot::Strand => (
252 engine::decode::viz_hue_ui(paint).wrapping_add(128),
253 engine::decode::viz_sat_ui(paint),
254 ),
255 }
256 }
257
258 /// Sets this ink's hue and saturation, raising the strand's chosen flag on
259 /// the way -- the engine's strand setters do that, which is what makes the
260 /// wheel's first sample on the slot the write that chooses it.
261 pub(crate) fn set_hue_sat(self, paint: u64, hue: u8, sat: u8) -> u64 {
262 match self {
263 VizSlot::Main => engine::decode::with_viz_paint_sat(
264 engine::decode::with_viz_paint_hue(paint, hue),
265 sat,
266 ),
267 VizSlot::Strand => engine::decode::with_viz_paint_strand_sat(
268 engine::decode::with_viz_paint_strand_hue(paint, hue),
269 sat,
270 ),
271 }
272 }
273}
274
275/// What the wheel draws: the clip's own ink, or the sample a drag is holding
276/// while the worker is still behind ([`stash_or_write`]). The wheel is a
277/// picker with no table of its own, so a held sample would otherwise be
278/// invisible -- the clip carries the sample *before* it until the holding
279/// frame lands -- and the mark would sit still under a moving hand.
280/// [`Player::color_params`] holds exactly this rule for the card's sliders.
281///
282/// The held sample carries its slot, so a drag on the strand colour draws the
283/// strand colour even before the clip has one of its own.
284pub(crate) fn viz_held_paint(paint: u64, held: Option<(VizSlot, u8, u8)>) -> u64 {
285 match held {
286 Some((slot, hue, sat)) => slot.set_hue_sat(paint, hue, sat),
287 None => paint,
288 }
289}
290
291/// How long an open may stand before the window says so in words. Well past an
292/// ordinary seek (a warm reopen is under a tenth of this) and well under what a
293/// cold read of a big film takes, which is the only case worth a line.
294pub(crate) const SEEK_STALL: Duration = Duration::from_secs(2);
295
296/// How long before the line counts the seconds.
297pub(crate) const SEEK_COUNT: Duration = Duration::from_secs(3);
298
299/// How long a picture may stand unopened before the line stops saying it is opening and says
300/// why it cannot be shown. A slow read still lands inside this; a compound or a missing file
301/// never does, and a running timer over it would be a lie.
302pub(crate) const SEEK_GIVE_UP: Duration = Duration::from_secs(8);
303
304/// What a seek that has stood past [`SEEK_STALL`] says, and nothing at all
305/// before that: a line on every click of the ruler would be a flicker, and the
306/// picture holding still for a tenth of a second is not something to explain.
307/// Short and plain; the seconds only once they say something (a window that
308/// cannot move and a window that has hung look identical, so this one counts).
309/// A picture whose file is off the disk is the banner's to say (`missing_clip_note`), so this
310/// line is only for a read that failed.
311pub(crate) fn seek_line(standing: Option<Duration>) -> Option<String> {
312 let since = standing.filter(|d| *d >= SEEK_STALL)?;
313 if since >= SEEK_GIVE_UP {
314 return Some("Can't show this frame: nothing could be read at the playhead.".to_string());
315 }
316 Some(match since >= SEEK_COUNT {
317 true => format!("Opening the picture\u{2026} {} s", since.as_secs()),
318 false => "Opening the picture\u{2026}".to_string(),
319 })
320}
321
322/// Where along the preview's own seek bar a click landed, in seconds from
323/// the start: [`frac_along`]'s fraction of `duration`, since the bar spans
324/// the preview's whole length rather than a zoomed timeline `Scale` -- a
325/// preview does not zoom, so there is no bed narrower than the file to map
326/// into.
327pub(crate) fn preview_seek_seconds(x: Pixels, bar: Bounds<Pixels>, duration: f64) -> f64 {
328 f64::from(frac_along(x, bar)) * duration.max(0.)
329}
330
331/// How full the preview's seek bar is drawn, 0..1: the played share of the
332/// duration, clamped for the same reason [`frac_along`] clamps a click -- a
333/// clock a frame past the end must not overhang the track it is drawn on.
334/// Zero for a duration of nothing, rather than a NaN from dividing by it.
335pub(crate) fn preview_progress_along(now: f64, duration: f64) -> f32 {
336 if duration <= 0. {
337 return 0.;
338 }
339 (now / duration).clamp(0., 1.) as f32
340}
341
342/// Where the ruler draws the playhead, given whether *the timeline's own*
343/// session ([`Player::session`]) has played out. `ended` must answer for
344/// `session` specifically, never for [`Player::active_session`] -- a preview
345/// reaching *its* end is not the timeline's own playhead running out, and
346/// must not snap the ruler to `duration` while the timeline sits wherever it
347/// was left (a seek, mid-scrub, anywhere). `now` is `session`'s own clock,
348/// which a preview never touches.
349pub(crate) fn playhead_position(now: f64, ended: bool, duration: f64) -> f64 {
350 if ended {
351 duration
352 } else {
353 now.clamp(0., duration)
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360
361 /// A click at either end of the bar lands exactly on the file's own
362 /// ends, the middle lands at half the duration, and a click past either
363 /// edge clamps to it rather than reading negative or past the end --
364 /// `frac_along`'s own clamp, carried through.
365 #[test]
366 fn preview_seek_seconds_maps_the_bar_to_the_file() {
367 let bar = Bounds {
368 origin: point(px(100.), px(0.)),
369 size: size(px(200.), px(HIT_MIN)),
370 };
371 assert_eq!(preview_seek_seconds(px(100.), bar, 60.), 0.);
372 assert_eq!(preview_seek_seconds(px(300.), bar, 60.), 60.);
373 assert_eq!(preview_seek_seconds(px(200.), bar, 60.), 30.);
374 // Off both ends -- the pointer left the bar, and the seek clamps to
375 // the end it left through.
376 assert_eq!(preview_seek_seconds(px(0.), bar, 60.), 0.);
377 assert_eq!(preview_seek_seconds(px(500.), bar, 60.), 60.);
378 }
379
380 /// Ended pins the ruler to the out point; short of that it tracks the
381 /// clock, clamped -- a tail dragged past the end must not walk the ruler
382 /// off the bed.
383 #[test]
384 fn playhead_position_pins_only_on_the_sessions_own_end() {
385 assert_eq!(playhead_position(8., false, 35.), 8.);
386 assert_eq!(playhead_position(35., true, 35.), 35.);
387 assert_eq!(playhead_position(40., false, 35.), 35.);
388 // A preview ending must not read as `ended` for this call at all --
389 // it is the caller's job to pass `false` while one is up, which is
390 // exactly what leaves the ruler on the timeline's own clock.
391 assert_eq!(playhead_position(8., false, 35.), 8.);
392 }
393
394 /// The fill tracks the played share exactly, and a duration of nothing
395 /// -- no file open yet -- reads as an empty bar rather than a divide by
396 /// zero.
397 #[test]
398 fn preview_progress_along_is_the_played_share() {
399 assert_eq!(preview_progress_along(0., 60.), 0.);
400 assert_eq!(preview_progress_along(30., 60.), 0.5);
401 assert_eq!(preview_progress_along(60., 60.), 1.);
402 // Past the end clamps rather than overhanging the track.
403 assert_eq!(preview_progress_along(61., 60.), 1.);
404 assert_eq!(preview_progress_along(5., 0.), 0.);
405 }
406}