From 963252a1eeb3cebe2d003b0ad434f8404ae97e84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 13 Aug 2026 10:03:12 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20chore(app):=20the=20window's=20f?= =?UTF-8?q?ile=20lets=20sixteen=20neighbourhoods=20keep=20their=20own?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main.rs was 10,529 lines with every constant, every helper and the window itself in one place. The geometry, the transport, the import state, the menus, the export card, the oracle, the library rows, the subtitles, the equalizer, the colour card, the viewport and the timeline's arithmetic each move out to the module they belong to; the Player and its two impls stay, which is what the file is for. Pure motion: every line is the line it was, with pub(crate) added only where a module boundary now stands between it and its caller. Player::enable still delegates to the one oracle. --- crates/app/src/audio_cards.rs | 187 ++ crates/app/src/color_ui.rs | 108 + crates/app/src/eq_ui.rs | 279 ++ crates/app/src/export_ui.rs | 810 +++++ crates/app/src/files.rs | 155 + crates/app/src/importing.rs | 374 +++ crates/app/src/interact.rs | 220 ++ crates/app/src/layout.rs | 291 ++ crates/app/src/library_meta.rs | 426 +++ crates/app/src/main.rs | 4924 +------------------------------ crates/app/src/menus.rs | 254 ++ crates/app/src/notices.rs | 45 + crates/app/src/oracle.rs | 293 ++ crates/app/src/subs.rs | 589 ++++ crates/app/src/timeline_math.rs | 388 +++ crates/app/src/transport.rs | 214 ++ crates/app/src/viewport.rs | 296 ++ 17 files changed, 4963 insertions(+), 4890 deletions(-) create mode 100644 crates/app/src/audio_cards.rs create mode 100644 crates/app/src/color_ui.rs create mode 100644 crates/app/src/eq_ui.rs create mode 100644 crates/app/src/export_ui.rs create mode 100644 crates/app/src/files.rs create mode 100644 crates/app/src/importing.rs create mode 100644 crates/app/src/interact.rs create mode 100644 crates/app/src/layout.rs create mode 100644 crates/app/src/library_meta.rs create mode 100644 crates/app/src/menus.rs create mode 100644 crates/app/src/notices.rs create mode 100644 crates/app/src/oracle.rs create mode 100644 crates/app/src/subs.rs create mode 100644 crates/app/src/timeline_math.rs create mode 100644 crates/app/src/transport.rs create mode 100644 crates/app/src/viewport.rs diff --git a/crates/app/src/audio_cards.rs b/crates/app/src/audio_cards.rs new file mode 100644 index 0000000..534abff --- /dev/null +++ b/crates/app/src/audio_cards.rs @@ -0,0 +1,187 @@ +//! The equalizer, speed, silence and mixer cards' numbers. + +use crate::*; + +/// How far a band may be pushed either way, in dB. The engine clamps nothing +/// here -- it will filter whatever it is given -- so this is a UI decision: +/// past about this a peaking band stops sounding like tone and starts sounding +/// like a fault. +pub(crate) const EQ_GAIN_LIMIT: f32 = 12.; + +/// One dB per keystroke, which is roughly the smallest step anyone hears on a +/// single band. +pub(crate) const EQ_STEP: f32 = 1.; + +/// A twentieth of real time per keystroke, in the thousandths a [`Speed`] is +/// held in: fine enough to creep up on a rate, coarse enough that the whole +/// range is eighty presses and not eight hundred -- and it divides 1000, so +/// stepping from anywhere lands on exactly 1.00x on the way past. +pub(crate) const SPEED_STEP: i32 = 50; + +/// The rates the card's buttons offer, so the ones people actually name are one +/// click and not a drag. Real time is among them: it is the reset. +pub(crate) const SPEED_PRESETS: [u16; 6] = [250, 500, 1000, 1500, 2000, 4000]; + +/// A rate from a number of thousandths that may have run off either end -- what +/// a keystroke and a drag both produce. Clamped, not refused: a hand pushing +/// past the limit means "as far as it goes", exactly as a trim does. +pub(crate) fn speed_at(permille: i32) -> Speed { + Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16) +} + +/// The silence card's rows, in the order it lists them: how wide the apply +/// reaches, the threshold and the unit it is read in, the three durations a +/// scan is told, and the rate the speed-up plays at. What `silence_field` +/// indexes and what [`Player::nudge_silence`] moves. +pub(crate) const SILENCE_ROWS: usize = 7; + +/// How wide a jumpcut reaches. A ripple used to be the whole timeline's +/// business and nothing else; it is a *choice* now, because a podcast track's +/// silences are not the music track's business -- and the choice has to be on +/// screen, because "everything after this moved" is not a thing to discover +/// afterwards. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Scope { + /// The lanes of the take the scanned clip belongs to: its picture and its + /// sound stay one take, and nothing else moves. The default, because a clip + /// picked on screen is what a person means by "this". + Take, + /// That clip's lane, alone. Refused by the engine, by name, while the take + /// has a half elsewhere -- detaching is how a person says they mean it. + Track, + /// Every lane, which is what a ripple always was and what the timeline-wide + /// jumpcut still is. + Everything, +} + +/// The order the card cycles them in. +pub(crate) const SCOPES: [Scope; 3] = [Scope::Take, Scope::Track, Scope::Everything]; + +impl Scope { + /// What the row says, given the lanes it works out to: the *names* of the + /// tracks, because "this take" means nothing until it says which two. + pub(crate) fn label(self, lanes: &[Lane]) -> String { + let named = lanes + .iter() + .map(|l| l.label()) + .collect::>() + .join("+"); + match self { + Scope::Take => format!("this take ({named})"), + Scope::Track => format!("this track ({named})"), + Scope::Everything => "every track".to_string(), + } + } +} + +/// One press of a nudge key on each kind of row: a dB on the threshold, a +/// twentieth of a second on the three durations, and the speed card's own step +/// on the rate. +pub(crate) const SILENCE_DB_STEP: f32 = 1.; +pub(crate) const SILENCE_SECS_STEP: f64 = 0.05; + +/// How far each of them may be pushed. UI decisions, all of them: the engine +/// takes any finite number, but a forgiveness of ten seconds finds nothing in a +/// talking head. The threshold reaches full scale, which calls a whole take +/// silent -- that is a thing someone may want to ask for (the preview on the +/// lane says what it would cost before anything is cut), so the top is 0 rather +/// than a number this card picked for them. +pub(crate) const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.); +pub(crate) const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.); + +/// One press of a nudge key on the mix card, in dB: the step every fader and +/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone +/// hears as a move -- and it lands on round numbers, so a track set by ear +/// still reads as a number a person would say. +pub(crate) const MIX_DB_STEP: f32 = 1.; + +/// The mix card's rows below the faders: the limiter's ceiling and its switch. +/// One fader per audio track comes first, however many there are. +pub(crate) const MIX_MASTER_ROWS: usize = 2; + +/// The speed-up rate is bounded *below* by real time: a "speed-up" that slows +/// the silence down would make the timeline longer, which is the one thing +/// neither button may do. The top is [`Speed::MAX`]. +pub(crate) fn silence_rate(permille: i32) -> Speed { + speed_at(permille.clamp( + i32::from(Speed::NORMAL.permille()) + SPEED_STEP, + i32::from(Speed::MAX.permille()), + )) +} + +/// The graph's frequency axis: the range an ear works in, and the range every +/// band a file can carry sits inside. Log-spaced, so an octave is an octave +/// wherever it falls. +pub(crate) const EQ_FREQ_LOW: f32 = 20.; +pub(crate) const EQ_FREQ_HIGH: f32 = 20_000.; + +/// The curve box. Tall enough that 1 dB is a visible move at the ±12 dB axis, +/// and short enough that the card still fits a 360 px window. +pub(crate) const EQ_GRAPH_H: f32 = 132.; + +/// How wide the equalizer card is allowed to get. It is the one card that is a +/// *graph*: every pixel across is frequency resolution, and at the 320 px the +/// other cards use, a third of an octave was a couple of pixels. Past this the +/// curve stops gaining anything and the card starts reading as a wall. +pub(crate) const EQ_W_MAX: f32 = 720.; + +/// The gap the card leaves either side of it, so it reads as a card on a scrim +/// rather than as a second window: it takes the width it can get inside that. +pub(crate) const EQ_W_MARGIN: f32 = 32.; + +/// How many bands one clip's equalizer may carry from this card. Ten because +/// the keyboard picks a band with a digit and a keyboard has ten of them -- +/// past that a band would be reachable by pointer only. The engine itself caps +/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more +/// and this card will draw and edit every one it finds. +pub(crate) const EQ_BANDS_MAX: usize = 10; + +/// One press of the frequency keys, as a factor: a sixth of an octave, so a +/// band walks the whole axis in about sixty presses and still lands close +/// enough to a named frequency to aim at one. +pub(crate) const EQ_FREQ_STEP: f32 = 1.122_462; + +/// One press of the Q keys, as a factor, and the range they move in. Below the +/// bottom a peak is barely a peak any more; above the top it is a whistle on +/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside +/// them, so nothing a file carries has to be dragged into range first. +pub(crate) const EQ_Q_STEP: f32 = 1.25; +pub(crate) const EQ_Q_LOW: f32 = 0.3; +pub(crate) const EQ_Q_HIGH: f32 = 12.; + +/// How many points the curve is drawn from. One per ~3 px across the card: +/// past that the line is smooth and the extra biquad evaluations are wasted. +pub(crate) const EQ_CURVE_STEPS: usize = 96; + +/// A band's handle on the curve. Only the dot -- what is *grabbed* is the whole +/// graph (the nearest band along the frequency axis), so the target is the box. +pub(crate) const EQ_HANDLE: f32 = 10.; + +/// The frequencies the graph names, so the curve can be read as a curve *of +/// something*. The two ends label themselves at the edges. +pub(crate) const EQ_TICKS: [(f32, &str); 5] = [ + (20., "20 Hz"), + (100., "100"), + (1000., "1k"), + (10000., "10k"), + (20000., "20k"), +]; + +/// The gains the graph rules a line across, besides the 0 dB one it already +/// had: half way to each limit, so a boost can be read as "about six" without +/// counting pixels. The limits themselves are the box's own edges and are +/// named at the corners instead. +pub(crate) const EQ_DB_GRID: [f32; 2] = [6., -6.]; + + +/// How many played samples one spectrum frame is transformed from. A power of +/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz +/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough +/// (21 ms) that the analyser moves with the music. +pub(crate) const EQ_FFT: usize = 1024; + +/// The level range the analyser is drawn across, floor to ceiling in dBFS: the +/// bottom of the box is silence and the top is a bin at -12 dBFS, which is +/// about where a mixed track's loudest band sits. A look, not a measurement -- +/// the numbers on the axis are the curve's dB, never the analyser's. +pub(crate) const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.); diff --git a/crates/app/src/color_ui.rs b/crates/app/src/color_ui.rs new file mode 100644 index 0000000..bd2ffd1 --- /dev/null +++ b/crates/app/src/color_ui.rs @@ -0,0 +1,108 @@ +//! The colour card's numbers and its histogram. + +use crate::*; + +/// The colour card's four controls, in the order it lists them: what each is +/// called and the range it moves in. The order is `ColorParams`' own, which is +/// what [`color_band`] indexes. +pub(crate) const COLOR_BANDS: [(&str, f32, f32); 4] = [ + ("Brightness", -1., 1.), + ("Contrast", 0., 2.), + ("Saturation", 0., 2.), + ("Tint (cool–warm)", -1., 1.), +]; + +/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it +/// in forty presses and every stop is a number the file can write. A drag lands +/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard +/// cannot reach two different sets of values. +pub(crate) const COLOR_STEP: f32 = 0.05; + +/// The card's width: a slider row is a label, the bar and the value, and the +/// longest label has to fit beside all three without truncating (measured +/// against "Tint (cool–warm)"). +pub(crate) const COLOR_W: f32 = 460.; +/// How much of a slider row the bar itself gets -- what a drag is read against, +/// so it takes the width the two nudge buttons used to. +pub(crate) const COLOR_BAR_W: f32 = 240.; + +/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin: +/// fine enough to see a grade tilt, coarse enough that a subsampled count is +/// not noise. +pub(crate) const HIST_BINS: usize = 64; + +/// How many pixels of a frame the histogram reads. The stride is +/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a +/// thousandth of the frame and walks across columns rather than down one. +pub(crate) const HIST_SAMPLES: usize = 8_192; + +/// The histogram box. Shorter than the equalizer's curve because four slider +/// rows stand under it and the card still has to fit a 360 px window. +pub(crate) const HIST_H: f32 = 96.; + +/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the +/// pointer stops where the arrow keys do and "0.35" on screen is the number the +/// file writes rather than a rounding of one. +pub(crate) fn color_snap(value: f32) -> f32 { + (value / COLOR_STEP).round() * COLOR_STEP +} + +/// How the frame on screen is spread across the tone range: `HIST_BINS` counts +/// per channel, read off the BGRA the decoder handed over -- which is the +/// *graded* picture, because the grade is folded into the conversion +/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye +/// is looking at, and moving a slider moves it. +/// +/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn +/// from eight thousand samples is the same shape, at a thousandth of the reads. +pub(crate) fn histogram(bgra: &[u8]) -> [[u32; HIST_BINS]; 3] { + let pixels = bgra.len() / 4; + let stride = (pixels / HIST_SAMPLES).max(1); + let mut bins = [[0u32; HIST_BINS]; 3]; + for p in (0..pixels).step_by(stride) { + let px = &bgra[p * 4..]; + // BGRA on the wire, `[r, g, b]` in the bins: the graph names channels + // the way a person does. + for (channel, value) in [px[2], px[1], px[0]].into_iter().enumerate() { + bins[channel][usize::from(value) * HIST_BINS / 256] += 1; + } + } + bins +} + +/// The three counts drawn as three lines across the box, tallest bin to the top. +/// +/// Square root, not linear: a shot with a big flat area (a night sky, a title +/// card) puts one bin so far above the rest that a linear graph is a single +/// spike beside a flat line, and the tilt a grade puts in the rest is exactly +/// what the card is for. +pub(crate) fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + // Shared across the channels, so their relative weight is readable; + // never zero, so an unpumped (all-zero) histogram is a flat line + // rather than a division by nothing. + let top = bins.iter().flatten().copied().max().unwrap_or(0).max(1) as f32; + for (channel, counts) in bins.iter().enumerate() { + let mut path = PathBuilder::stroke(px(1.5)); + for (bin, &count) in counts.iter().enumerate() { + let at = point( + o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32), + o.y + s.height * (1. - (count as f32 / top).sqrt()), + ); + match bin { + 0 => path.move_to(at), + _ => path.line_to(at), + } + } + if let Ok(path) = path.build() { + window.paint_path(path, rgb(HIST_INK()[channel])); + } + } + }, + ) + .absolute() + .size_full() +} diff --git a/crates/app/src/eq_ui.rs b/crates/app/src/eq_ui.rs new file mode 100644 index 0000000..a452d81 --- /dev/null +++ b/crates/app/src/eq_ui.rs @@ -0,0 +1,279 @@ +//! The equalizer graph: its geometry, its analyser and its curve. + +use crate::*; + +/// Where a frequency sits across the graph, 0..1. Log, because an octave is an +/// octave whether it is 40 Hz wide or 10 kHz wide -- a linear axis would spend +/// three quarters of the card on the top two octaves and squeeze the bass, the +/// half of the range people actually reach for, into nothing. +pub(crate) fn eq_x(freq_hz: f32) -> f32 { + let span = (EQ_FREQ_HIGH / EQ_FREQ_LOW).log10(); + ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.) +} + +/// The frequency at a fraction across the graph -- [`eq_x`] backwards, which is +/// how a drag and the curve's own sample points read one. Clamped to the axis +/// either way, so a pointer that leaves the box stops at 20 Hz or 20 kHz. +pub(crate) fn eq_freq(along: f32) -> f32 { + EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along.clamp(0., 1.)) +} + +/// The band an "add" makes: a flat peak half way -- in octaves, which is what +/// the log axis draws -- between the picked band and whatever sits above it, so +/// a new band lands in the gap on screen rather than on top of its neighbour. +/// Above the topmost band the gap is the rest of the axis. +pub(crate) fn inserted_band(bands: &[Band], after: usize) -> Band { + let below = bands.get(after).map_or(1000., |b| b.freq_hz); + let above = bands + .iter() + .map(|b| b.freq_hz) + .filter(|f| *f > below) + .min_by(f32::total_cmp) + .unwrap_or(EQ_FREQ_HIGH); + Band { + freq_hz: (below * above).sqrt().clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH), + gain_db: 0., + // A shade narrower than the flat-shelf 0.707 the defaults use: a band + // someone asked for is a band they mean to aim, and a wide one aimed at + // 300 Hz is really a band at everything. + q: 1., + kind: BandKind::Peak, + } +} + +/// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle, +/// so a cut reads as a dip below the line it is a cut from. The inverse of +/// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a +/// curve loaded from a file with a gain past the card's limit paints on the +/// edge of the box rather than outside it. +pub(crate) fn eq_y(gain_db: f32) -> f32 { + 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. +} + +/// A frequency as the card writes it. Two decimals of a kHz at most, with the +/// zeroes trimmed, so "1 kHz" stays "1 kHz" and a band nudged off it reads as +/// 1.12 kHz rather than as the same "1 kHz" it was before the keystroke -- a +/// number that does not move under an edit is worse than no number. +pub(crate) fn eq_freq_label(freq_hz: f32) -> String { + if freq_hz < 1000. { + return format!("{freq_hz:.0} Hz"); + } + let khz = format!("{:.2}", freq_hz / 1000.); + let khz = khz.trim_end_matches('0').trim_end_matches('.'); + format!("{khz} kHz") +} + +/// What a band row calls itself: the corner or centre frequency, and for a +/// shelf the fact that it tilts everything past it -- which is the difference +/// between "12 kHz" moving the last octave and moving one band inside it. +pub(crate) fn band_label(band: &Band) -> String { + let freq = eq_freq_label(band.freq_hz); + match band.kind { + BandKind::LowShelf => format!("{freq} low shelf"), + BandKind::HighShelf => format!("{freq} high shelf"), + BandKind::Peak => freq, + } +} + +/// In-place radix-2 FFT of `re`/`im`, whose length must be a power of two. +/// +/// Hand-written, and deliberately: a 1024-point transform once a frame is a +/// few tens of microseconds of plain arithmetic, and a dependency for it would +/// be a build cost this editor pays on every compile for one card's backdrop. +pub(crate) fn fft(re: &mut [f32], im: &mut [f32]) { + let n = re.len(); + // Decimation in time: the input is first put in bit-reversed order, after + // which the butterflies run over neighbours. + let mut j = 0usize; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut span = 2; + while span <= n { + let step = std::f32::consts::TAU / span as f32; + for start in (0..n).step_by(span) { + for k in 0..span / 2 { + // e^{-i2πk/span}: the negative sign is the forward transform. + let (sin, cos) = (-step * k as f32).sin_cos(); + let (a, b) = (start + k, start + k + span / 2); + let (tr, ti) = (cos * re[b] - sin * im[b], cos * im[b] + sin * re[b]); + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] += tr; + im[a] += ti; + } + } + span <<= 1; + } +} + +/// The played signal as one height per curve point, 0 (silence) to 1 (the top +/// of the box) -- the analyser the response curve is drawn on top of. +/// +/// The newest [`EQ_FFT`] samples of the engine's tap, Hann-windowed so a tone +/// that does not land on a bin centre is one hump rather than a smear across +/// the axis. Each column takes the *loudest* bin between it and its +/// neighbours: the axis is logarithmic, so one column near 20 Hz is a fraction +/// of a bin while one near 20 kHz is hundreds, and averaging those would sink +/// every peak up there into the noise beside it. +/// +/// Empty -- nothing to draw -- for a tap too short to transform, which is what +/// a session has just after a seek. +/// +/// corner-cut: one transform length for the whole axis, so the bass end is a bin +/// (47 Hz at 48 kHz) wide however many columns are drawn across it -- a 60 Hz +/// hum and an 80 Hz one are the same hump down there. Upgrade path is the +/// analyser every mastering EQ uses: two or three transforms of different +/// lengths, each drawn over the octaves it resolves. +pub(crate) fn eq_spectrum(samples: &[f32], sample_rate: u32) -> Vec { + if samples.len() < EQ_FFT { + return Vec::new(); + } + let tail = &samples[samples.len() - EQ_FFT..]; + let mut re: Vec = tail + .iter() + .enumerate() + .map(|(i, s)| { + let w = 0.5 * (1. - (std::f32::consts::TAU * i as f32 / EQ_FFT as f32).cos()); + s * w + }) + .collect(); + let mut im = vec![0.; EQ_FFT]; + fft(&mut re, &mut im); + // Magnitude per bin, scaled so a full-scale sine reads 0 dBFS: half the + // energy is in the mirrored half of the transform, and the Hann window + // takes another factor of two off. + let mags: Vec = (0..EQ_FFT / 2) + .map(|k| (re[k] * re[k] + im[k] * im[k]).sqrt() * 4. / EQ_FFT as f32) + .collect(); + let bin_hz = sample_rate as f32 / EQ_FFT as f32; + let (floor, ceiling) = EQ_SPECTRUM_DB; + let at = |along: f32| EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); + (0..=EQ_CURVE_STEPS) + .map(|step| { + let along = step as f32 / EQ_CURVE_STEPS as f32; + let half = 0.5 / EQ_CURVE_STEPS as f32; + // Bin 0 is DC and means nothing here, so the low end starts at 1. + let low = (at(along - half) / bin_hz).round().max(1.) as usize; + let high = (at(along + half) / bin_hz).round().max(1.) as usize; + let peak = (low..=high) + .filter_map(|k| mags.get(k)) + .fold(0f32, |a, &b| a.max(b)); + let db = 20. * peak.max(1e-9).log10(); + ((db - floor) / (ceiling - floor)).clamp(0., 1.) + }) + .collect() +} + +/// The analyser drawn as one filled shape from the floor of the box. +pub(crate) fn eq_spectrum_curve(levels: Vec) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let last = levels.len().saturating_sub(1).max(1) as f32; + let mut path = PathBuilder::fill(); + path.move_to(point(o.x, o.y + s.height)); + for (i, level) in levels.iter().enumerate() { + path.line_to(point( + o.x + s.width * (i as f32 / last), + o.y + s.height * (1. - level), + )); + } + path.line_to(point(o.x + s.width, o.y + s.height)); + path.close(); + if let Ok(path) = path.build() { + window.paint_path(path, rgba(EQ_SPECTRUM_INK())); + } + }, + ) + .absolute() + .size_full() +} + +/// The cascade's frequency response, drawn as one line across the graph, with +/// each band's own response threaded dimly under it. +/// +/// Every point comes from `EqParams::response_db`, which reads the very +/// coefficients the samples are filtered through: the curve cannot drift from +/// what is heard, because there is no second copy of the maths. A single band's +/// thread is that same call on a cascade of one, so the two cannot disagree +/// either -- and it is what makes a boost sitting inside a cut visible at all, +/// where the sum alone would draw a flat line and say nothing. +/// +/// corner-cut: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the +/// curve then rides the edge of the box; upgrade = a wider dB axis with the +/// handles and [`Player::drag_band`] rescaled to it. +pub(crate) fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let line = |of: &EqParams| -> Vec<_> { + (0..=EQ_CURVE_STEPS) + .map(|step| { + let along = step as f32 / EQ_CURVE_STEPS as f32; + point( + o.x + s.width * along, + o.y + s.height + * eq_y(of.response_db(eq_freq(along), sample_rate)), + ) + }) + .collect() + }; + // One thread per band, first, so the sum is drawn over them. + for band in ¶ms.bands { + let mut bell = PathBuilder::stroke(px(1.)); + for (step, at) in line(&EqParams { + bands: vec![*band], + }) + .into_iter() + .enumerate() + { + match step { + 0 => bell.move_to(at), + _ => bell.line_to(at), + } + } + if let Ok(bell) = bell.build() { + window.paint_path(bell, rgba(EQ_BELL_INK())); + } + } + let points = line(¶ms); + // The area between the curve and 0 dB, closed along that line: a + // boost and a cut wind opposite ways around it, which is exactly + // what makes both of them fill and the flat parts stay empty. + let mut area = PathBuilder::fill(); + area.move_to(point(o.x, o.y + s.height / 2.)); + for at in &points { + area.line_to(*at); + } + area.line_to(point(o.x + s.width, o.y + s.height / 2.)); + area.close(); + if let Ok(area) = area.build() { + window.paint_path(area, rgba(EQ_FILL_INK())); + } + let mut path = PathBuilder::stroke(px(2.)); + for (step, at) in points.into_iter().enumerate() { + match step { + 0 => path.move_to(at), + _ => path.line_to(at), + } + } + if let Ok(path) = path.build() { + window.paint_path(path, rgb(ACCENT_PRIMARY())); + } + }, + ) + .absolute() + .size_full() +} diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs new file mode 100644 index 0000000..5885505 --- /dev/null +++ b/crates/app/src/export_ui.rs @@ -0,0 +1,810 @@ +//! What the export card offers and what it writes. + +use crate::*; + +/// The project resolutions [`Player::cycle_resolution`] offers, largest first. +/// A short list of the sizes people name; the media's own is cycled in beside +/// them, which is what makes the trip round come back to where it started. +pub(crate) const RESOLUTIONS: [(u32, u32); 5] = [ + (3840, 2160), + (2560, 1440), + (1920, 1080), + (1280, 720), + (854, 480), +]; + +/// The project frame rates the list offers, slowest first: the rates footage is +/// actually shot and delivered at, the NTSC ones written as the ratios they are +/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very +/// number it is handed, so a rate rounded here would be a rate no timescale can +/// name. The media's own is cycled in beside them +/// ([`frame_rate_ladder`]), which is what keeps the way back on the list. +pub(crate) const FRAME_RATES: [f64; 8] = [ + 24_000. / 1001., + 24., + 25., + 30_000. / 1001., + 30., + 50., + 60_000. / 1001., + 60., +]; + +/// What the export card offers, top to bottom. Bitrate is the only thing the +/// encoder actually takes: the codec and the container are what this program +/// can write and nothing else, so the card states them rather than offering +/// them. +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum Quality { + Auto, + Low, + Medium, + High, + Custom, +} + +impl Quality { + pub(crate) const ALL: [Quality; 5] = [ + Quality::Auto, + Quality::Low, + Quality::Medium, + Quality::High, + Quality::Custom, + ]; + + pub(crate) fn label(self) -> &'static str { + match self { + Quality::Auto => "Auto", + Quality::Low => "Low", + Quality::Medium => "Medium", + Quality::High => "High", + Quality::Custom => "Custom", + } + } + + /// The figure the row stands for, said in the units the row is chosen by. + pub(crate) fn detail(self, custom_mbps: u32) -> String { + match self { + Quality::Auto => "from the picture size and frame rate".to_string(), + Quality::Custom => { + format!("{custom_mbps} Mbps — wheel or ± steps, n types one, {MBPS_MIN}–{MBPS_MAX}") + } + other => format!( + "{} Mbps", + export_settings(other, 0, Format::Mp4, DEFAULT_AUDIO_KBPS) + .bitrate + .unwrap_or_default() + / 1_000_000 + ), + } + } +} + +/// The export card's format rows: the key that picks one, its name, and what it +/// writes -- or, where this program cannot write it, the reason it cannot. A +/// format with no entry at all would read as an oversight, and a menu of three +/// as a claim that nothing else exists -- so the refusals are rows too, dimmed +/// and unclickable. +/// +/// `None` is exactly that kind of row, and there are two left. MP3 stopped +/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL +/// `shine-rs` was the licence question, and it is not the only encoder any +/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an +/// encoder — an *intra-only* one, which the rows say rather than let a user +/// find out from the size of the file. VP9 is the one this program still only +/// *reads*: the plugin decodes it and there is no encoder for it here, so it is +/// a row for the reason the refusals are rows at all — a codec that opens but +/// never comes back out is exactly the gap a user would otherwise go looking +/// for. AAC is not a row at all: it is what both containers' sound *is*, never a +/// file of its own. +/// +/// A codec is one row, and the boxes it can be written into are the row's +/// containers: the same AV1 picture and the same AAC track go into a Matroska +/// file or into an mp4, and which one a user needs is about what has to play +/// the file, not about the encode. So the container is asked *once*, in a row +/// of its own, and only where there is more than one to ask about -- five +/// picture rows to read past were four of them saying the same codec twice. +pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [ + ( + &[Format::Mp4], + "m", + "H.264", + "plays everywhere · AAC sound · MP4 only", + ), + ( + &[Format::Av1, Format::Av1Mp4], + "a", + "AV1", + "smallest file for the picture · AAC sound", + ), + ( + &[Format::Hevc, Format::HevcMp4], + "h", + "HEVC", + "intra-only, every frame a cut point — large files", + ), + (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"), + (&[Format::Flac], "f", "FLAC", "lossless — audio only"), + (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"), + ( + &[Format::Ogg], + "o", + "OGG", + "Vorbis (rusty_vorbis) — quality-coded, stereo", + ), + (&[], "", "VP9", "AV1 above replaces it"), +]; + +/// The codec row a key picks, landed in the container already chosen: pressing +/// `a` after an mp4 gives AV1 *in mp4*, because a box decided once is not a +/// question again. A letter of the row's own name, spelled out in the table +/// rather than taken from the initial (`MP4` and `MP3` share one). Never a +/// digit -- those are the bitrate field's. `None` for every other stroke, the rows +/// that cannot be picked included. +pub(crate) fn format_key(key: &str, current: Format) -> Option { + FORMATS + .into_iter() + .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key)) + .find_map(|(row, ..)| same_box(row, current)) +} + +/// The boxes one codec may be written into, in the order its container row +/// cycles them. Empty for a codec this program cannot write at all. +pub(crate) fn containers(format: Format) -> &'static [Format] { + FORMATS + .into_iter() + .map(|(row, ..)| row) + .find(|row| row.contains(&format)) + .unwrap_or(&[]) +} + +/// This row's format under the container `current` is already in, or the row's +/// first when it has no such box: an AV1 picked from a WAV lands in Matroska, +/// and picked from an mp4 stays in the mp4. +pub(crate) fn same_box(row: &[Format], current: Format) -> Option { + row.iter() + .copied() + .find(|f| f.ext() == current.ext()) + .or_else(|| row.first().copied()) +} + +/// The next box for the same codec, wrapping -- what the container row's key +/// does. The format itself for a codec with only one, so the stroke cannot +/// change what it is not offering. +pub(crate) fn next_container(format: Format) -> Format { + let row = containers(format); + let at = row.iter().position(|&f| f == format).unwrap_or(0); + row.get((at + 1) % row.len().max(1)) + .copied() + .unwrap_or(format) +} + +/// The next rate the Sound row offers, wrapping -- what its key does, and what +/// the row itself names so the stroke is never a guess. [`next_container`]'s +/// shape, for the same reason: one place decides what "next" means. +pub(crate) fn next_audio_kbps(kbps: u32) -> u32 { + let at = AUDIO_KBPS.iter().position(|&k| k == kbps).unwrap_or(0); + AUDIO_KBPS[(at + 1) % AUDIO_KBPS.len()] +} + +/// Why the quality rows say nothing about this format, or `None` where they +/// decide the picture. Only a picture encoder is given a bitrate here: the two +/// lossless audio formats have none to give and MP3 is written at one fixed +/// figure, so a live row over either would be a control that changes nothing. +pub(crate) fn bitrate_refusal(format: Format) -> Option<&'static str> { + match format { + Format::Wav | Format::Flac => Some("lossless audio — no bitrate to pick"), + Format::Mp3 => Some("sound only — its rate is the Sound row"), + // The guard is the question and not a list of names: an audio format + // added without a line of its own above would otherwise show live + // quality rows over a file that has no picture to spend a bitrate on. + // OGG is exactly that format -- and it wants this sentence rather than + // one of its own, because its *Sound* row already says the Vorbis half + // ("quality-coded — Vorbis holds no rate to pick") and two rows saying + // the same thing is one of them wasted. + _ if !format.has_video() => Some("sound only — no picture to spend a bitrate on"), + _ => None, + } +} + +/// What one of the colour card's own strokes does. Its keys are card-local -- +/// they mean nothing outside it -- so they are a table here rather than keymap +/// bindings, exactly as the export card's format initials are. Listed in +/// `keymap::FIXED` all the same, which is how the keys menu still says so. +pub(crate) enum ColorKey { + Close, + /// Steps down the four sliders, wrapping. + Band(usize), + /// Moves the picked slider, in [`COLOR_STEP`]s. + Nudge(f32), + Reset, +} + +/// Why the silence card has nothing to scan on that clip, in its own voice: the +/// lane and index the user picked, the file it is of, and which of the two +/// soundless things it is. One place, because a still and a silent video are +/// the same answer to the same question -- "a box with a larger size than it" +/// is what the *demuxer* would say about a png, and it is not an answer. +/// +/// Costs nothing: the scan reads a file and writes marks, so a refusal here +/// leaves the project (and its undo history) exactly where it was. +pub(crate) fn unscannable(lane: Lane, idx: usize, path: &Path) -> String { + let what = match engine::is_image(path) { + true => "is a picture", + false => "is silent", + }; + format!( + "{} clip {} has no audio to scan — {} {what}", + lane.label(), + idx + 1, + file_name(path) + ) +} + +/// The half of a take whose *sound* the silence card scans: a link is one span +/// on however many lanes, so a card opened on the picture opens on the sound it +/// is grouped with. That is the lane the waveform is drawn on, and so the lane +/// the marks have to land on to be read against it -- and the ranges agree, +/// because a group is one span. +/// +/// The clip itself for one already on an audio lane, for a detached picture, +/// and for a take whose sound is not on any lane: there is nothing better to +/// open on, and the refusal for a source with no audio at all is `scan`'s. +pub(crate) fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) { + if lane.kind == LaneKind::Audio { + return (lane, idx); + } + let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else { + return (lane, idx); + }; + session + .lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Audio) + .find_map(|l| { + session + .lane_clips(l) + .iter() + .position(|c| c.link == Some(link)) + .map(|i| (l, i)) + }) + .unwrap_or((lane, idx)) +} + +pub(crate) fn color_key(key: &str) -> Option { + Some(match key { + ESCAPE => ColorKey::Close, + "down" => ColorKey::Band(1), + "up" => ColorKey::Band(COLOR_BANDS.len() - 1), + "right" => ColorKey::Nudge(1.), + "left" => ColorKey::Nudge(-1.), + "r" => ColorKey::Reset, + _ => return None, + }) +} + +/// The band'th control of a grade, to read or to write. The order is +/// [`COLOR_BANDS`]', which is the order the card lists them in. +pub(crate) fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 { + match band { + 0 => &mut params.brightness, + 1 => &mut params.contrast, + 2 => &mut params.saturation, + _ => &mut params.tint, + } +} + +/// The line under the rows: what the picked format really writes, in the terms +/// a file is judged by afterwards. +/// The next policy round the cycle, in the order the action's label reads. +/// Every fit policy, in the order the list offers them -- which is the order +/// [`next_fit`] steps through them, pinned by the test below: a list and a +/// stroke that disagreed about what comes next would be two settings. +pub(crate) const FITS: [FitPolicy; 4] = [ + FitPolicy::Fit, + FitPolicy::Fill, + FitPolicy::Stretch, + FitPolicy::Center, +]; + +pub(crate) fn next_fit(fit: FitPolicy) -> FitPolicy { + match fit { + FitPolicy::Fit => FitPolicy::Fill, + FitPolicy::Fill => FitPolicy::Stretch, + FitPolicy::Stretch => FitPolicy::Center, + FitPolicy::Center => FitPolicy::Fit, + } +} + +/// What a person calls one, said as what it does to the picture. +pub(crate) fn fit_label(fit: FitPolicy) -> &'static str { + match fit { + FitPolicy::Fit => "fit (whole picture, bars)", + FitPolicy::Fill => "fill (cropped, no bars)", + FitPolicy::Stretch => "stretch (aspect broken)", + FitPolicy::Center => "centre (1:1, no resample)", + } +} + +/// Every project resolution on offer, largest first: [`RESOLUTIONS`] with the +/// media's own size cycled in at its place by size -- so a project already at a +/// listed size does not see it twice, and the media's own shape, whatever it is, +/// is always on the list. The one order both the stroke and the list use. +pub(crate) fn resolution_ladder(native: (u32, u32)) -> Vec<(u32, u32)> { + let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec(); + if !sizes.contains(&native) { + // By area, descending, like the list itself: the cycle then reads as one + // ladder rather than a list with a stray rung at the end. + let at = sizes + .iter() + .position(|&(w, h)| { + u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1) + }) + .unwrap_or(sizes.len()); + sizes.insert(at, native); + } + sizes +} + +/// The resolution list's rows: every rung of the ladder, the media's own said +/// so, and the one in force marked. A size is named by its height the way the +/// button that opens the list names it, with the full figure beside it. +pub(crate) fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec { + resolution_ladder(native) + .into_iter() + .map(|(w, h)| { + ( + Choice::Size(w, h), + format!("{h}p").into(), + match (w, h) == native { + // Short enough to sit beside the label inside `MENU_W`: + // the longer phrase lost its last word to the truncation. + true => format!("{w}x{h} · the media's own"), + false => format!("{w}x{h}"), + } + .into(), + (w, h) == current, + ) + }) + .collect() +} + +/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the +/// media's own cycled in at its place by speed, so a project already cut at a +/// listed rate does not see it twice and the media's own rate -- the one a +/// project moved off it has no other way back to -- is always there. +/// [`resolution_ladder`]'s rule, for the other setting the project has of its +/// own. +pub(crate) fn frame_rate_ladder(native: f64) -> Vec { + let mut rates = FRAME_RATES.to_vec(); + // Bit for bit: 23.976023976... is not 23.976, and a rate that read as + // "already listed" when it is not would take the media's own off the list. + if !rates.contains(&native) { + let at = rates + .iter() + .position(|&fps| fps > native) + .unwrap_or(rates.len()); + rates.insert(at, native); + } + rates +} + +/// The rate list's rows: every rung of the ladder, the media's own said so, and +/// the one in force marked. Named as a person writes a rate ([`fps_label`]), +/// with what it is for beside it -- short, or the row loses its tail to the +/// truncation the resolution list already met. +pub(crate) fn fps_choices(current: f64, native: f64) -> Vec { + frame_rate_ladder(native) + .into_iter() + .map(|fps| { + ( + Choice::Fps(fps), + format!("{} fps", fps_label(fps)).into(), + match fps == native { + true => "the media's own".to_string(), + // The rates that are a ratio are the ones nobody can tell + // from their neighbour by the label alone. + false => match (fps - fps.round()).abs() < 0.001 { + true => String::new(), + false => "NTSC".to_string(), + }, + } + .into(), + fps == current, + ) + }) + .collect() +} + +/// The fit list's rows: all four policies against the canvas they place a +/// picture on, since the word alone ("fill") says nothing about the size it is +/// filling -- which is the very thing the notice says after a stroke. +pub(crate) fn fit_choices(lane: Lane, idx: usize, current: FitPolicy, (w, h): (u32, u32)) -> Vec { + FITS.into_iter() + .map(|fit| { + ( + Choice::Fit(lane, idx, fit), + fit_label(fit).into(), + // The canvas alone, worded as the resolution list words a size: + // the policy names are long and anything wordier here loses its + // tail to the truncation. + format!("{w}x{h}").into(), + fit == current, + ) + }) + .collect() +} + +/// The sound-rate list's rows: every offered rate, the one in force marked, and +/// what each buys said in the fewest words that fit beside the label (a longer +/// phrase loses its tail to `MENU_W`'s truncation, as the two lists above say). +pub(crate) fn audio_rate_choices(current: u32) -> Vec { + AUDIO_KBPS + .into_iter() + .enumerate() + .map(|(n, kbps)| { + ( + Choice::AudioRate(kbps), + format!("{kbps} kbps").into(), + match (kbps, n) { + (DEFAULT_AUDIO_KBPS, _) => "the default", + (_, 0) => "smallest file", + (k, _) if k < DEFAULT_AUDIO_KBPS => "smaller file", + _ => "better sound", + } + .into(), + kbps == current, + ) + }) + .collect() +} + +/// How a rendition is named where a person reads it: the panel button, the +/// notice and the list row all say the same word ([`engine::tonemap::Preset`]). +pub(crate) fn tone_label(preset: Preset) -> &'static str { + match preset { + Preset::Reference => "Reference", + Preset::Standard => "Standard", + Preset::Vivid => "Vivid", + } +} + +/// The HDR list's rows: all three renditions, the one in force marked, and what +/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the +/// truncation the three lists above already met. Always offered, whatever is on +/// the timeline: a setting that appeared and vanished with the media would be a +/// setting nobody could find, and the row says who it acts on instead. +pub(crate) fn tone_choices(current: Preset) -> Vec { + Preset::ALL + .into_iter() + .map(|preset| { + ( + Choice::Tone(preset), + tone_label(preset).into(), + match preset { + Preset::Reference => "BT.2446-A, as published", + Preset::Standard => "brighter, player-like", + Preset::Vivid => "brightest, richer colour", + } + .into(), + preset == current, + ) + }) + .collect() +} + +/// The next project resolution after `current`, over [`RESOLUTIONS`] with the +/// media's own size cycled in at its place by size -- so the trip round always +/// comes back to the media, whatever odd shape it is, and a project already at a +/// listed size does not see it twice. +pub(crate) fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) { + let sizes = resolution_ladder(native); + let at = sizes.iter().position(|&s| s == current); + // A project at a size nobody listed (a hand-edited file) joins the cycle at + // the top rather than being stuck. + sizes[at.map_or(0, |at| (at + 1) % sizes.len())] +} + +/// The first of the two lines the card keeps above its button: what will be +/// *inside* the file. [`format_line`]'s codec and box, then the project's own +/// picture size and rate -- which is what a video export is written at however +/// many sizes and rates the media on the timeline are -- and last what the +/// sound will be, or that there is none. Every field here is one `ffprobe` +/// reads back off the finished file, so the line is checkable rather than a +/// promise. +pub(crate) fn summary_head(format: Format, picture: Option<((u32, u32), f64)>, audio: &str) -> String { + let line = match picture.filter(|_| format.has_video()) { + Some(((w, h), fps)) => { + format!("{} · {w}x{h} · {} fps", format_line(format), fps_label(fps)) + } + None => format_line(format).to_string(), + }; + join_detail(&line, audio) +} + +/// The second: where it lands, roughly how big, and what will encode the +/// picture -- the seat as the probe found it (`…` until it lands, never a +/// guess), which is what the running export then names on its progress line. +pub(crate) fn summary_tail(path: &Path, bytes: Option, seat: Option<&'static str>, video: bool) -> String { + let size = bytes.map_or_else(String::new, |bytes| format!("≈ {}", size_label(bytes))); + let seat = match (video, seat) { + (true, Some(seat)) => seat, + (true, None) => "encoder …", + (false, _) => "", + }; + join_detail(&join_detail(&file_name(path), &size), seat) +} + +/// A frame rate as a person writes it: `30`, not `30.000`, and `23.976` for the +/// rate that is a ratio. +pub(crate) fn fps_label(fps: f64) -> String { + match (fps - fps.round()).abs() < 0.001 { + true => format!("{fps:.0}"), + false => format!("{fps:.3}") + .trim_end_matches('0') + .trim_end_matches('.') + .to_string(), + } +} + +/// About how big a *chosen* bitrate makes the file: the picture's bits over the +/// timeline's length, in bytes -- the unit the line is written in is +/// [`size_label`]'s to pick. `None` for `Auto`, whose figure is the encoder's to +/// decide, and for a format with no bitrate at all -- a number nobody picked is +/// not an estimate. The sound and the container's own overhead are not in it, +/// which is why the card says "≈". +pub(crate) fn estimated_bytes(bitrate: Option, duration: f64) -> Option { + let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?; + Some((bitrate as f64 * duration / 8.).round() as u64) +} + +/// A size in the largest unit that can state it, [`rate_scale`]'s rule: +/// megabytes for an export of any length, kilobytes below the one a whole +/// megabyte rounds away. A three second clip at the floor bitrate really is +/// 375 kB, and "≈ 0 MB" would be this line saying the file it is about to write +/// is empty -- the one thing the size field is there to deny. Never "0 kB" +/// either: an estimate that exists is at least a kilobyte of file. +pub(crate) fn size_label(bytes: u64) -> String { + match (bytes as f64 / 1e6).round() as u64 { + 0 => format!("{} kB", (bytes as f64 / 1e3).round().max(1.) as u64), + mb => format!("{mb} MB"), + } +} + +/// What is in the file and what box it is in, which is the head of the summary. +/// Terse on purpose: the fields after it (size, rate, sound) are what the line +/// is *for*, and a head that spent its width on prose used to push the whole +/// summary onto a second line -- what each codec means is on its row. +pub(crate) fn format_line(format: Format) -> &'static str { + match format { + Format::Mp4 => "H.264 · MP4", + Format::Av1 => "AV1 · MKV", + Format::Av1Mp4 => "AV1 · MP4", + Format::Hevc => "HEVC intra · MKV", + Format::HevcMp4 => "HEVC intra · MP4", + // The three whose codec *is* their box: naming it twice would be the + // only field on this line that says nothing. + Format::Wav => "16-bit PCM · WAV", + Format::Flac => "FLAC · lossless", + Format::Mp3 => "MP3 · lossy", + Format::Ogg => "Vorbis · OGG", + } +} + +/// The row a format is picked by, which is what a refusal calls it: the codec, +/// since the container is a row of its own now -- `AV1`, not the `mkv` such a +/// file is named with. +pub(crate) fn format_label(format: Format) -> &'static str { + FORMATS + .iter() + .find(|(row, ..)| row.contains(&format)) + .map_or("EXPORT", |(_, _, label, _)| *label) +} + +/// The destination under a format: `take.export.mp4` becomes `take.export.wav`. +/// The stem is untouched, so a name typed into the save dialog survives a +/// change of mind about the format -- only the extension is the format's to say. +pub(crate) fn retarget(path: &std::path::Path, format: Format) -> PathBuf { + let mut path = path.to_path_buf(); + path.set_extension(format.ext()); + path +} + +/// The card's rows as the engine takes them. `Auto` leaves the bitrate to the +/// exporter, which derives it from the picture; the fixed rows are figures that +/// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the +/// engine clamps every explicit bitrate to 1..50 Mbps (`MAX_EXPLICIT_BITRATE`), so this +/// must not clamp it a second time and disagree about where the edge is. +/// +/// The bitrate travels even for an audio format, where the engine ignores it: +/// one settings value, and a row the card has dimmed cannot have been changed. +pub(crate) fn export_settings( + quality: Quality, + custom_mbps: u32, + format: Format, + audio_kbps: u32, +) -> ExportSettings { + ExportSettings { + format, + // Always travels, exactly as the picture's bitrate does above: the + // engine ignores it where nothing encodes the sound, and a row the card + // has dimmed cannot have been changed. + audio_kbps: Some(audio_kbps), + bitrate: match quality { + Quality::Auto => None, + Quality::Low => Some(2_000_000), + Quality::Medium => Some(6_000_000), + Quality::High => Some(12_000_000), + Quality::Custom => Some(u64::from(custom_mbps) * 1_000_000), + }, + // No row of its own: the software pin is for a driver that encodes + // badly, which is a thing about the machine and not about the output -- + // `VE_SW_ENC` already says it, and to the whole run rather than once. + force_sw: false, + // The picked track is put on by `start_export`, which is the only + // caller that writes a file; the rest of them are asking about the + // bitrate and the format. + subtitles: Vec::new(), + } +} + +/// What the engine will code an explicit bitrate at, in whole Mbps: outside +/// this it clamps (`export.rs` `MIN_BITRATE`/`MAX_EXPLICIT_BITRATE`), so a +/// number typed past either end would be written as a different one. The field +/// refuses it instead of clamping quietly -- a card that changes the user's +/// number without saying so is the one thing a field like this must never do. +/// +/// The ceiling was 20, which was never a limit of any encoder here: it was the +/// top of the range the exporter *derives* an automatic bitrate in, borrowed as +/// the cap on a typed one. A 1080p master or a 4K edit wants more than that, so +/// the asked-for rate has its own ceiling now and this is it. +pub(crate) const MBPS_MIN: u32 = 1; +pub(crate) const MBPS_MAX: u32 = 50; + +/// How many digits the field takes. Two reach the ceiling; the third is there so +/// a number *past* it can be typed whole and refused in its own words, rather +/// than being dropped keystroke by keystroke. +pub(crate) const MBPS_DIGITS: usize = 3; + +/// A number being typed into a card row: the digits so far and, once a commit +/// has been refused, why. Text-field semantics on a card that has no text field +/// -- typing, backspace, arrows that step, enter that commits and escape that +/// gives up -- held as state and driven by the root's key handler, since +/// nothing in these cards takes gpui focus. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct NumberEdit { + pub(crate) text: String, + pub(crate) refusal: Option, +} + +impl NumberEdit { + /// Starts on the number the row already carries, so backspace edits it + /// rather than the field opening empty over a value that is still in force. + /// Zero is no number at all -- it is what the card opens at, before anyone + /// has typed one. + pub(crate) fn new(value: u32) -> Self { + NumberEdit { + text: match value { + 0 => String::new(), + v => v.to_string(), + }, + refusal: None, + } + } + + /// A digit against what is there. The one past [`MBPS_DIGITS`] is refused + /// *out loud*: a keystroke dropped in silence is how the old digit capture + /// left the card showing a number the user had already typed past. + pub(crate) fn digit(&mut self, digit: u32) { + if self.text.chars().count() >= MBPS_DIGITS { + self.refusal = Some(format!("{MBPS_DIGITS} digits is already past the ceiling")); + return; + } + match char::from_digit(digit, 10) { + Some(c) => { + self.text.push(c); + self.refusal = None; + } + None => self.refusal = Some("digits only".into()), + } + } + + /// Erases the last digit, and the refusal with it: the number on screen has + /// changed, so the reason the old one was refused no longer describes it. + pub(crate) fn backspace(&mut self) { + self.text.pop(); + self.refusal = None; + } + + /// The arrows, which is how a number gets picked rather than typed. Steps + /// from what is in the field -- an empty one starts at the floor, so the + /// first press up is `MBPS_MIN` and not a jump to some remembered value -- + /// and stays inside the range, because a step is a walk through the legal + /// numbers rather than a way out of them. + pub(crate) fn step(&mut self, by: i32) { + let at = self.text.parse::().unwrap_or(MBPS_MIN as i32 - by.signum()); + self.text = (at + by) + .clamp(MBPS_MIN as i32, MBPS_MAX as i32) + .to_string(); + self.refusal = None; + } + + /// The number, or `None` with the reason recorded where the row will read + /// it. Never clamped: 45 committed as 20 is a number the user did not type. + pub(crate) fn commit(&mut self) -> Option { + match commit_mbps(&self.text) { + Ok(mbps) => Some(mbps), + Err(why) => { + self.refusal = Some(why); + None + } + } + } + + /// What the row shows while it is being typed into: the digits, the caret + /// that says they are landing *here*, and either the refusal or the two + /// keys that end the edit. + pub(crate) fn detail(&self) -> String { + format!( + "{}▏ Mbps — {}", + self.text, + match &self.refusal { + Some(why) => why.as_str(), + None => "enter commits · esc cancels", + } + ) + } +} + +/// A typed bitrate as the card takes it, or the reason it is not one. The words +/// are the row's: they are what the field shows in place of its hint. +pub(crate) fn commit_mbps(text: &str) -> Result { + match text.parse::() { + Ok(mbps) if (MBPS_MIN..=MBPS_MAX).contains(&mbps) => Ok(mbps), + Ok(0) => Err(format!("0 is not a rate — {MBPS_MIN}–{MBPS_MAX} Mbps")), + Ok(mbps) => Err(format!("{mbps} is past the {MBPS_MAX} Mbps ceiling")), + Err(_) => Err(format!("type a number — {MBPS_MIN}–{MBPS_MAX} Mbps")), + } +} + +/// Whether a stroke gets out of a running export. Escape does, whatever +/// modifiers are held with it, for the same reason it gets out of a capture and +/// out of the overlay: it is this window's way out, and a way out that only +/// works with the right modifiers is not one. Whatever the keymap has on cancel +/// works too, so rebinding it adds a way rather than replacing the one that +/// always worked -- and that binding is still what the progress line shows. +pub(crate) fn cancels_export(key: &str, action: Option) -> bool { + key == ESCAPE || action == Some(ActionId::CancelExport) +} + +/// A clip's share of the lane. A timeline with no length reads as one full-width +/// box rather than as NaN, which gpui would carry into layout. +/// Why this timeline cannot be written in `format`, if it cannot. +/// +/// An audio-only timeline is the one both picture formats refuse: every frame of +/// it is a gap, so the file would be a black picture over the sound. The engine +/// refuses it too (`export::start`); this is what greys the row before a +/// destination has been picked. +/// +/// It is the *only* reason left. A second audio lane, a speeded clip, a source +/// no mp4 sample table holds: each of those used to grey the MP4 row, because +/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy +/// cannot say what the timeline says (`export::copy_audio`), so none of them is +/// a refusal any more -- and every video format carries the sound, so there is +/// nothing here that is one format's alone. +pub(crate) fn format_refusal(session: &PlaybackSession, format: Format) -> Option { + if !format.has_video() { + return None; + } + let picture = session + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); + match picture { + true => None, + false => Some(format!( + "no picture — {} would be black; export WAV, FLAC, MP3 or OGG", + format.name() + )), + } +} diff --git a/crates/app/src/files.rs b/crates/app/src/files.rs new file mode 100644 index 0000000..1cc039e --- /dev/null +++ b/crates/app/src/files.rs @@ -0,0 +1,155 @@ +//! Paths in and out: the pickers, the URIs, the names. + +use crate::*; + +/// How a finished export announces itself. Written by `poll_export` and read +/// by the notice bar, which is what makes that one line clickable. +pub(crate) const EXPORT_DONE: &str = "EXPORT DONE → "; + +/// The path as a URI the bus will take: percent-encoded, because an export +/// lands wherever its source lives and those directories have spaces in them. +/// Bytes, not chars -- a path is not required to be UTF-8. +pub(crate) fn file_uri(path: &std::path::Path) -> String { + use std::os::unix::ffi::OsStrExt; + let mut uri = String::from("file://"); + for &b in path.as_os_str().as_bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { + uri.push(b as char) + } + _ => uri.push_str(&format!("%{b:02X}")), + } + } + uri +} + +/// Shows a file in the desktop's file manager, selected: the freedesktop +/// interface every major one answers, asked for over the session bus. With no +/// file manager on the bus the folder itself is the next best thing, and with +/// neither there is nothing to say -- the notice the click retired was the +/// answer, and a machine without a desktop opener is not one a second notice +/// would help. Blocks on two child processes, so it is never called on the UI +/// thread. +pub(crate) fn show_in_file_manager(path: &std::path::Path) { + // The URI must be absolute; an export path is only as absolute as the + // source it was built from. + let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let shown = std::process::Command::new("busctl") + .args([ + "--user", + "call", + "org.freedesktop.FileManager1", + "/org/freedesktop/FileManager1", + "org.freedesktop.FileManager1", + "ShowItems", + "ass", + "1", + &file_uri(&path), + "", + ]) + .status() + .is_ok_and(|s| s.success()); + if shown { + return; + } + if let Some(dir) = path.parent() { + let _ = std::process::Command::new("xdg-open").arg(dir).status(); + } +} + +/// Runs the first chooser that is installed. `Some(None)` is a cancelled +/// dialog; `None` is a machine with no chooser at all, and what still works +/// without one differs per dialog, so the caller words that refusal. +/// +/// The desktop's own choosers, asked for by name because gpui 0.2 has no file +/// dialog of its own and none of these is worth a dependency. +pub(crate) fn run_picker(pickers: [(&str, Vec); 2]) -> Option> { + for (bin, args) in pickers { + // Not installed: try the next one. Anything else (a cancel, a refusal) + // is that chooser's answer and is taken as final. + let Ok(out) = std::process::Command::new(bin).args(args).output() else { + continue; + }; + let path = String::from_utf8_lossy(&out.stdout).trim().to_string(); + return Some((!path.is_empty()).then(|| PathBuf::from(path))); + } + None +} + +/// `title` is what the dialog calls itself: two buttons open this same chooser +/// for two different questions -- a file to import, a file to take subtitles out +/// of -- and a dialog titled "import" over the second one is the wrong question +/// answered. No extension filter on either: what can be read is the engine's +/// answer (`PlaybackSession::parse_subtitles` takes a container as readily as a +/// `.srt`), and a list of suffixes written here would hide a file edith would +/// have taken. +pub(crate) fn pick_file(title: &str) -> Result, &'static str> { + run_picker([ + ( + "zenity", + vec!["--file-selection".into(), format!("--title={title}")], + ), + ("kdialog", vec!["--getopenfilename".into()]), + ]) + .ok_or( + "NO FILE CHOOSER — install zenity or kdialog, or drag the file onto this window to import it", + ) +} + +/// The save-side dialog, opened on where the export would land anyway: with no +/// chooser installed that default is still what gets written, so this refusal +/// costs the export nothing and says so. +pub(crate) fn pick_save(default: &std::path::Path) -> Result, &'static str> { + let default = default.to_string_lossy().into_owned(); + run_picker([ + ( + "zenity", + vec![ + "--file-selection".into(), + // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated + // and does the confirming itself. + "--save".into(), + "--title=edith — export to".into(), + format!("--filename={default}"), + ], + ), + ("kdialog", vec!["--getsavefilename".into(), default]), + ]) + .ok_or( + "NO FILE CHOOSER — install zenity or kdialog to choose where; exporting beside the source", + ) +} + +/// Where an export goes: the source path with `.export.mp4` for an extension, +/// so it lands beside the original and can never be the original. +pub(crate) fn export_path(source: impl Into) -> PathBuf { + let mut path = source.into(); + path.set_extension("export.mp4"); + path +} + +/// Where a save goes when the timeline did not come from a project file: the +/// media path with `.edith` for an extension, beside it like an export. A +/// project loaded from disk keeps its own path instead, so saving it twice +/// writes the same file. +pub(crate) fn project_path(source: impl Into) -> PathBuf { + let mut path = source.into(); + path.set_extension("edith"); + path +} + +/// Whether a dropped or named path is a project rather than media. Exactly the +/// lowercase extension `save_project` writes -- anything else goes to the +/// demuxer, which is the one that can say what it really is. +pub(crate) fn is_project(path: &std::path::Path) -> bool { + path.extension().is_some_and(|e| e == "edith") +} + +/// The tail of a path, for showing. A path that is all root has none, and reads +/// as itself. +pub(crate) fn file_name(path: &std::path::Path) -> String { + path.file_name().map_or_else( + || path.display().to_string(), + |n| n.to_string_lossy().into(), + ) +} diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs new file mode 100644 index 0000000..f73d9e1 --- /dev/null +++ b/crates/app/src/importing.rs @@ -0,0 +1,374 @@ +//! Bringing a file in: the library's tabs, the import and scan state, the stages. + +use crate::*; + +/// The library's three categories, in the order the giants list them: the +/// pictures, the sound, and the words. A file is in exactly one of them, so a +/// tab is a question with an answer rather than a filter with a guess. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum LibraryTab { + Media, + Audio, + Text, +} + +pub(crate) const LIBRARY_TABS: [LibraryTab; 3] = [LibraryTab::Media, LibraryTab::Audio, LibraryTab::Text]; + +impl LibraryTab { + pub(crate) fn label(self) -> &'static str { + match self { + LibraryTab::Media => "Media", + LibraryTab::Audio => "Audio", + LibraryTab::Text => "Text", + } + } + + /// Whether a source belongs on this tab. Subtitles are not sources at all + /// -- they are the [`Player::subtitle_section`] under the list -- so the + /// Text tab holds no rows of its own and says so. + pub(crate) fn holds(self, path: &Path) -> bool { + match self { + LibraryTab::Media => !engine::is_audio(path), + LibraryTab::Audio => engine::is_audio(path), + LibraryTab::Text => false, + } + } + + /// What an empty tab says instead of being a blank column. + pub(crate) fn empty(self) -> &'static str { + match self { + LibraryTab::Media => "No video or stills yet — Import, or drop a file on the window", + LibraryTab::Audio => "No sound yet — Import, or drop a file on the window", + LibraryTab::Text => { + "No subtitles yet — Add subtitles from a file, or drop an .srt on the window" + } + } + } +} + +/// What is known about a source's audio. Three states and not two, because a +/// file whose peaks have not come back yet must not be drawn as one that has no +/// audio at all: the first shows a bed, the second shows nothing. +#[derive(Clone)] +pub(crate) enum Wave { + /// Asked for; the decode is running on a background thread. + Loading, + /// The file has no audio track. An answer, not a miss. + Silent, + /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]: + /// "this file's sound could not be read" and "this file has no sound" look + /// the same on a lane, and the first is a bug report waiting to happen. + Failed, + Peaks(Arc>), +} + +/// The import a worker is reading, as the line above the panel shows it. No +/// fraction anywhere: neither read reports how far into the file it has come, +/// so what is honest is the file's name, the stage, and two clocks -- one that +/// proves the window is answering, one that says the stage has not moved. +pub(crate) struct Import { + pub(crate) path: PathBuf, + /// When the worker started, for the elapsed clock. + pub(crate) started: Instant, + /// Written by the worker between its two reads, read here every repaint. + pub(crate) stage: Arc, + /// The stage the line last saw and when it last changed. The pair is the + /// whole stall detector: a stage older than [`IMPORT_STALL`] is what the + /// honest wording is for. + pub(crate) seen: ImportStage, + pub(crate) since: Instant, + /// Set by the Cancel beside the line ([`Player::cancel_import`]), read at + /// the landing: what the worker read is dropped instead of joining the + /// timeline. + /// + /// corner-cut: the *read* is not stopped -- a demuxer walk polls nothing, so + /// the worker finishes into a result nobody takes, and the window is given + /// back at the click either way. Ceiling: a cancelled cold 24 GB import + /// still costs the disk its twenty seconds. Upgrade: a flag + /// `engine::demux::Demuxer::open` polls between clusters, which is where an + /// export's own cancel already lives ([`engine::ExportHandle::cancel`]). + pub(crate) cancelled: Arc, +} + +impl Import { + /// Reads the worker's stage and keeps the stall clock: it restarts when the + /// stage actually changes and at no other time, which is what makes "has + /// not moved in five seconds" a fact rather than a guess about the elapsed + /// clock. Hands back how long the current stage has stood, so the line has + /// one place to ask. + pub(crate) fn poll(&mut self) -> f32 { + let stage = ImportStage::from_u8(self.stage.load(std::sync::atomic::Ordering::Relaxed)); + if stage != self.seen { + self.seen = stage; + self.since = Instant::now(); + } + self.since.elapsed().as_secs_f32() + } +} + +/// What a scan is *of*: the source, which of its audio streams, and the clip's +/// own `[in, out)` source frames. The range is part of the name because it is +/// part of the read -- a clip cut in half is a different, shorter decode than +/// the whole take was, and levels read for one are not the other's. +pub(crate) type ScanKey = (PathBuf, usize, u32, u32); + +/// The silence scan a worker is running, as the card shows it. Same two clocks +/// as an [`Import`] and for the same reason -- one proves the window answers, +/// one says the read has stopped moving -- over a progress that *can* move: +/// a decode knows how far into the sound it has come, so the card says so. +pub(crate) struct SilenceScan { + /// Source, stream and source range being scanned, which is the cache key + /// the levels land under and what tells a second open of the same clip from + /// a new one. + pub(crate) key: ScanKey, + /// When the worker started, for the elapsed clock. + pub(crate) started: Instant, + /// Written by the worker, read here every repaint. The cancel flag in it is + /// this side's only word to a scan already running. + pub(crate) progress: Arc, + /// The tenths-of-a-second mark the line last saw and when it last changed: + /// the stall detector, exactly [`Import::poll`]'s. + pub(crate) seen: u64, + pub(crate) since: Instant, +} + +impl SilenceScan { + /// Reads the worker's mark and keeps the stall clock, restarting it only + /// when the mark actually moves -- [`Import::poll`]'s contract, over a + /// number instead of a stage. + pub(crate) fn poll(&mut self) -> f32 { + let scanned = self.progress.scanned.load(std::sync::atomic::Ordering::Relaxed); + if scanned != self.seen { + self.seen = scanned; + self.since = Instant::now(); + } + self.since.elapsed().as_secs_f32() + } +} + +/// How long a stage may sit without moving before the import line stops +/// reading like a progress line and says outright that the wait is the file's, +/// not the window's. Five seconds: a 25 GB remux spends eleven in its header +/// alone, and a person watching a still line for that long has already decided +/// the editor hung. +pub(crate) const IMPORT_STALL: f32 = 5.; + +/// Which of an import's two reads the worker is inside. Travels as one atomic, +/// the way an export's progress does ([`engine::ExportHandle`]) -- there is no +/// fraction to send, because neither read reports where in the file it is. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum ImportStage { + /// The container header: the sample tables, the cue index, the frame count. + /// Eleven seconds on a cold 29 GB remux, a hundred and fifty milliseconds + /// once the pages are warm -- the whole reason this runs off the UI thread. + Header, + /// The subtitle tracks inside a Matroska, which is a walk over the file's + /// blocks rather than a header read (~200 ms on a two-hour film). + Subtitles, +} + +impl ImportStage { + /// The atomic the worker writes; `u8` because that is what an + /// [`AtomicU8`](std::sync::atomic::AtomicU8) carries. + pub(crate) fn from_u8(n: u8) -> Self { + match n { + 0 => Self::Header, + _ => Self::Subtitles, + } + } + + /// What the line calls this stage. + pub(crate) fn what(self) -> &'static str { + match self { + Self::Header => "reading the header", + Self::Subtitles => "reading the subtitle tracks", + } + } +} + +/// argv sorted into the file that becomes the timeline and the queue every +/// named file is read through, in the order they were named. The whole of what +/// a launch does before the window is on screen -- and it touches no disk, +/// which is the point: the header walk happens on a worker with the window +/// already up ([`Player::take_import`]). +pub(crate) fn launch_queue( + args: impl Iterator, +) -> (Option, std::collections::VecDeque) { + let queue: std::collections::VecDeque = args.collect(); + (queue.front().cloned(), queue) +} + +/// What a queued file turns into. Every file goes through one queue -- argv's +/// first file, argv's extras, a drop, the Import button -- and this is the fork +/// its worker is started on. +#[derive(PartialEq, Eq, Debug, Clone, Copy)] +pub(crate) enum Landing { + /// The media argv named: it becomes the timeline, and the canvas, the fps, + /// the title and the export path come from it. + Open, + /// A `.edith` argv named: a whole timeline restored, not a source. + Project, + /// Everything else: a row in the library, the timeline untouched. + Import, +} + +/// Which of the three a queued file is (`landing` above is the drag's). +/// `opening` is the one path argv named and is cleared as it lands, so a second +/// arrival of the same *media* path -- a drop of the film that is already open +/// -- is an import, which is what a drop has always been. +/// +/// A `.edith` is never an import, whichever door it came through: it is a whole +/// timeline and there is nothing to add it to. Argv's, a dropped one and the +/// Import button's are one landing, so the seconds its open costs are the +/// worker's for all three ([`open_ahead`]) and the line above the panel names it +/// while it runs. +pub(crate) fn arrival(opening: Option<&std::path::Path>, path: &std::path::Path) -> Landing { + match (is_project(path), opening == Some(path)) { + (true, _) => Landing::Project, + (false, true) => Landing::Open, + (false, false) => Landing::Import, + } +} + +/// The whole of what an import shows while it runs: which file, which stage, +/// the clock that proves the window is still answering, and what is behind it +/// in the queue. +/// +/// `since` is how long the *stage* has stood still, which is the only movement +/// an unmeasurable read has: past [`IMPORT_STALL`] the line says so in words, +/// because a bar that cannot move and a bar that has stopped look identical. +/// +/// `opening` is the file argv named, which is read through the same queue and +/// says so in the same words -- except that it is being *opened*, and a line +/// that called it an import would be describing the wrong thing to the one +/// person who typed the name. +pub(crate) fn import_line( + name: &str, + stage: ImportStage, + elapsed: f32, + since: f32, + waiting: usize, + opening: bool, +) -> String { + let tail = match waiting { + 0 => String::new(), + n => format!(" · {n} more waiting"), + }; + let what = stage.what(); + let verb = match opening { + true => "OPENING", + false => "IMPORTING", + }; + match since >= IMPORT_STALL { + true => format!( + "{verb} {name} · still {what} — a big file is minutes of reading, and the window is \ + not frozen · {} elapsed{tail}", + clock(elapsed) + ), + false => format!("{verb} {name} · {what} · {} elapsed{tail}", clock(elapsed)), + } +} + +/// What opening the silence card on a source costs. +#[derive(PartialEq, Eq, Debug)] +pub(crate) enum ScanPlan { + /// Its levels are already read: the marks are arithmetic on this frame. + Marks, + /// Nothing read: a worker, and a card that says so meanwhile. + Start, + /// A worker is already reading this very source -- the other half of a take + /// names the same file, and a second card on it waits for the first read + /// rather than throwing away the minute already spent. + Wait, +} + +/// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole +/// of the cache policy, and the reason a second film does not cost the first +/// one its levels: what is cached is asked per source, never "the last one". +pub(crate) fn scan_plan(cached: bool, running: Option<&ScanKey>, key: &ScanKey) -> ScanPlan { + match (cached, running) { + (true, _) => ScanPlan::Marks, + (false, Some(at)) if at == key => ScanPlan::Wait, + _ => ScanPlan::Start, + } +} + +/// The half-open source seconds a [`ScanKey`]'s frames name, at the project's +/// rate -- what [`engine::silence::levels`] is asked to read, and the same +/// arithmetic playback puts a clip's `in_frame` through. A rate that is not a +/// rate reads the whole file rather than an empty window: a scan of nothing is +/// worse than a scan of too much. +pub(crate) fn source_secs(key: &ScanKey, fps: f64) -> (f64, f64) { + match fps.is_finite() && fps > 0. { + true => (f64::from(key.2) / fps, f64::from(key.3) / fps), + false => (0., f64::INFINITY), + } +} + +/// What the silence card says while its worker reads. Unlike an import this +/// one *has* a fraction -- a decode knows how far into the sound it has come -- +/// so the line is where it is up to, out of what the header claims the track is +/// (`total` of 0 for a header that does not say, drawn as nothing rather than +/// as a guess). Both in seconds. +/// +/// The stall clock is [`IMPORT_STALL`]'s, for its reason: past five seconds +/// without the mark moving, a line that cannot move and a line that has stopped +/// look identical, and only one of them is worth words. +pub(crate) fn silence_line(scanned: f32, total: f32, elapsed: f32, since: f32) -> String { + let far = match total > 0. { + true => format!("{} of ~{} scanned", clock(scanned), clock(total)), + false => format!("{} scanned", clock(scanned)), + }; + match since >= IMPORT_STALL { + true => format!( + "SCANNING · still reading the sound — a big film is minutes of decoding, and the \ + window is not frozen · {far} · {} elapsed", + clock(elapsed) + ), + false => format!("SCANNING · {far} · {} elapsed", clock(elapsed)), + } +} + +/// How often a progress mark is worth keeping, how far back the rate is +/// measured, and the least span that may answer at all. An export crosses +/// hardware and software segments that run at different speeds, so the +/// estimate is a window's average and never the instant's. +pub(crate) const ETA_SAMPLE: f32 = 0.5; +pub(crate) const ETA_WINDOW: f32 = 8.; +pub(crate) const ETA_SPAN: f32 = 1.5; + +/// Records where the export has got to and forgets what has fallen out of the +/// window. One mark per `ETA_SAMPLE`, a window's worth kept: a bounded list +/// whichever way the encode goes. +pub(crate) fn note_progress(marks: &mut Vec<(f32, f32)>, elapsed: f32, progress: f32) { + if marks.last().is_none_or(|&(t, _)| elapsed - t >= ETA_SAMPLE) { + marks.push((elapsed, progress)); + } + while marks.len() > 2 && marks[0].0 < elapsed - ETA_WINDOW { + marks.remove(0); + } +} + +/// Seconds left at the window's rate, or `None` while nothing measurable has +/// happened yet -- which the line says as "estimating…" rather than as a +/// number it would have to take back. +pub(crate) fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Option { + // A finished pass is not a guess: it is over. + if progress >= 1. { + return Some(0.); + } + if progress <= 0. || elapsed < ETA_SPAN { + return None; + } + // Two rates, averaged. The window's follows the encode across a + // hardware-to-software handover; the whole run's is what keeps a window + // that is all stall from throwing the number minutes out and back. Neither + // alone reads well: raw window rate spikes eightfold on either edge of a + // stall, and the run average alone never notices a segment change. + let overall = progress / elapsed; + let recent = marks + .first() + .filter(|&&(t, _)| elapsed - t >= ETA_SPAN) + .map_or(overall, |&(t, p)| (progress - p) / (elapsed - t)); + Some(2. * (1. - progress) / (recent + overall)) +} diff --git a/crates/app/src/interact.rs b/crates/app/src/interact.rs new file mode 100644 index 0000000..101f7e8 --- /dev/null +++ b/crates/app/src/interact.rs @@ -0,0 +1,220 @@ +//! What a pointer is doing: the drags, the ghosts, the trims and the key repeat. + +use crate::*; + +/// A library row being dragged: the file and which of its audio streams that +/// row is, which is the whole of what a row names. Where it lands does not +/// change what is inserted. +pub(crate) struct AssetDrag(pub(crate) PathBuf, pub(crate) usize); + +/// A clip already on the timeline being dragged: the lane it is on and its index +/// there, which is how every other edit names a clip. Unlike an [`AssetDrag`] +/// nothing is inserted -- the same clip changes lane and keeps the frames it +/// plays -- but where along the bed it is let go is exactly where it lands, less +/// the offset the hand grabbed it at ([`Player::grab`]). +#[derive(Clone, Copy)] +pub(crate) struct ClipDrag { + pub(crate) lane: Lane, + pub(crate) idx: usize, + /// The clip that was picked up, so the drop can find it again: gpui freezes + /// the payload for the whole gesture, and an edit made *during* one -- a + /// stroke deletes, undoes or pastes, none of which a drag blocks -- ripples + /// the indices under it. The index alone would then name a different take at + /// the release, and the drag would move a clip nobody touched (see + /// [`live_idx`]). + pub(crate) clip: Clip, +} + +/// A track *header* being dragged: which track the hand took hold of, to be +/// let go over the header of the one whose place it is to take +/// ([`Player::reorder_lane`]). The lane alone -- a track carries its own clips +/// wherever it goes, so unlike a [`ClipDrag`] there is nothing else to name. +#[derive(Clone, Copy)] +pub(crate) struct LaneDrag(pub(crate) Lane); + +/// Where a header drag in flight would leave the track in the hand: the lane +/// whose slot it is about to take, and whether the line is drawn at that lane's +/// top edge (it is coming up from below) or its bottom one. The drop indicator +/// every editor draws between two tracks, and the header answer to the ghost a +/// clip drag lays on a lane ([`Ghost`]) -- stale between gestures, which costs +/// nothing because it is drawn only while one is live. +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct LaneDrop { + pub(crate) lane: Lane, + pub(crate) above: bool, +} + +/// Where the drag in flight would leave what it is carrying: the lane the +/// pointer is over, the snapped head the release will commit ([`landing`]), and +/// how long the thing is. Drawn on that lane as a translucent box the size of +/// the take, so a landing is *seen* before the release rather than discovered +/// after it -- the line ([`Player::snap_cue`]) marks the frame, this shows the +/// body. `refused` is a drop the lane cannot take -- a picture over an audio +/// track, a sound over a video one -- tinted rather than silent, because the +/// refusal is coming at the release either way ([`lane_refuses`], +/// [`Project::move_clip`]). +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct Ghost { + pub(crate) lane: Lane, + pub(crate) start: u32, + /// Timeline frames, which a speed has already been counted into: the box is + /// as wide as the clip is *long where it lands*. Zero for a library row of + /// unknown length, drawn as a head marker. + pub(crate) frames: u32, + /// The swatch of the file being carried ([`file_tint`]), so the + /// ghost reads as the thing in the hand. + pub(crate) tint: u32, + pub(crate) refused: bool, +} + +/// A clip edge being dragged: which end of which clip, and the timeline frame +/// the pointer has pulled it to. The box on screen is drawn from `to` while this +/// is set and the engine hears about it once, at the release +/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture, +/// exactly as an equalizer drag works. +#[derive(Clone, Copy)] +pub(crate) struct Trim { + pub(crate) lane: Lane, + pub(crate) idx: usize, + pub(crate) edge: Edge, + /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from + /// it is the width the release commits -- an edge stops under the pointer + /// rather than snapping back after the fact. + pub(crate) to: u32, + /// The dragged clip's group, so its other halves' boxes follow the edge on + /// screen exactly as the engine will move them. + pub(crate) link: Option, +} + +/// How wide a clip's edge is as a *target*: the strip at each end where a press +/// means "make this longer or shorter" instead of "move this to another lane". +/// Wide enough to hit, narrow enough that the middle of even a small box is +/// still the body. +pub(crate) const EDGE_W: f32 = 6.; + +/// Whether a clip box this wide gets its two trim strips at all. Below three +/// handles wide the pair would occlude the whole box: every press on it would +/// trim, and the clip could not be selected, dragged to another lane or picked +/// up by its middle -- which is exactly what a jumpcut leaves behind +/// ([`Player::cut_silences`] manufactures a great many short clips). Above it, +/// what is left between the two strips is a handle's width of body in its own +/// right. A clip too short for its handles is trimmed by zooming in first: the +/// bed is a magnifier, and the strip grows with the box. +pub(crate) fn trims(width: f32) -> bool { + width >= 3. * EDGE_W +} + +/// How wide a clip's box is *drawn*, given the width its own length is worth +/// (`span`). Never under [`HIT_MIN`], even where that is wider than the clip is +/// long: zoomed far out a short take is worth a fraction of a pixel, and a box +/// nobody can put a pointer on is a clip that cannot be selected, dragged, given +/// a menu or reached at all -- which is strictly worse than one drawn a few +/// pixels too wide. The same call [`cue_box`] makes for a mark, and what every +/// editor draws. +/// +/// A drawing only: [`Scale::time_at`] still reads the bed, so a press inside the +/// padding names the frame it points at, and the box's head is the clip's own. +pub(crate) fn clip_width(span: f32) -> f32 { + span.max(HIT_MIN) +} + +/// The sheet a card or a menu is painted on: the whole window, and the mouse +/// stops at it. Occluding is what tells gpui that nothing under this sheet is +/// hovered any more (`Hitbox::is_hovered`) -- without it the window carries on +/// hovering behind an open menu and pops *its* tooltip over the menu's items, +/// which is a card being painted over by the thing it covers. +/// +/// Every card and every menu takes its sheet from here, so no surface can be +/// drawn over the top of one by having been given a plain scrim. +pub(crate) fn scrim() -> Div { + div().absolute().inset_0().occlude() +} + +/// The sheet a card with a *slider* in it takes instead: the same scrim, with +/// the window's own drag listeners on it as well. +/// +/// A scrim occludes, and occluding is where gpui's hit test stops +/// (`Hitbox::is_hovered`, window.rs:788) -- so while a card is up the root is +/// not hovered anywhere behind it and its `on_mouse_move`/`on_mouse_up` hear +/// nothing at all. Every drag in this window is tracked from the root, because +/// each of them starts on a strip a few pixels wide that the pointer leaves at +/// once ([`Player::drag_move`]), so a card's handles were set by the press and +/// then frozen: the value never followed the hand and the release never wrote. +/// The scrim is the one surface above the occluder that covers the whole card, +/// so the same two listeners go here, and a drag that leaves the card is picked +/// up by the root's copy of them without a seam. +pub(crate) fn drag_scrim(cx: &mut Context) -> Div { + scrim() + .on_mouse_move(cx.listener(Player::drag_move)) + .on_mouse_up(MouseButton::Left, cx.listener(Player::drag_release)) +} + +/// A press that stops here. What every card's body hands its scrim: the scrim +/// closes the card on a press, and the card is painted after it, so this listener +/// runs first (gpui dispatches topmost-first, window.rs:3705) and a press meant +/// for a button never closes the card out from under its own click -- the rule +/// the menus already follow ([`Player::library_card`]). +pub(crate) fn swallow(_: &MouseDownEvent, _: &mut Window, cx: &mut App) { + cx.stop_propagation(); +} + +/// How close to an edge a dragged clip has to be let go for it to land *on* it: +/// the snap every timeline has, in pixels rather than frames so that it feels +/// the same at every zoom. Narrower than [`EDGE_W`] -- a hand aiming between two +/// takes must still be able to leave a gap of a few frames there. +pub(crate) const SNAP_PX: f64 = 5.; + +/// Where a held key would land, which is the whole of what auto-repeat has to +/// know. [`Player::repeat_scope`] answers it from the same state the handler +/// walks below itself. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Repeat { + /// A card with values in it owns the keyboard: equalizer, colour, speed or + /// silence. Its arrows are sliders. + Card, + /// Nobody does, so the keymap answers -- and only one pair of its actions + /// is a value being moved rather than a thing being done once. + Keymap, + /// A stroke is being captured, an export is running, or an overlay with no + /// value in it is up. Nothing there is worth a repeat. + Nothing, +} + +/// Whether a *held* stroke means it again. One press is always one action; a +/// hold is only ever a value running, so this is what tells the two apart. +/// +/// The cards' arrows, because that is what every one of them moves a slider +/// with -- and only the arrows, so the equalizer's `r` cannot flatten five +/// bands forty times a second and the silence card's `enter` cannot cut forty +/// places again on the next tick. Outside a card the volume pair and nothing +/// else: play, cut, delete, save, export and every other binding is a one-shot, +/// exactly as it was when the handler filtered every held key alike. +pub(crate) fn repeats(scope: Repeat, key: &str, action: Option) -> bool { + match scope { + Repeat::Card => matches!(key, "up" | "down" | "left" | "right"), + Repeat::Keymap => matches!( + action, + Some( + ActionId::VolumeUp + | ActionId::VolumeDown + // A zoom is a value being moved as much as a level is: + // held, it runs from the whole timeline down to a handful + // of frames and stops there. The fit is one press. + | ActionId::ZoomIn + | ActionId::ZoomOut + ) + ), + Repeat::Nothing => false, + } +} + +/// The keys that are only ever half a chord. gpui delivers a lone modifier +/// press as a keystroke of its own, and taking one as a binding would leave an +/// action that fires the moment the user reaches for any chord that uses it -- +/// so a capture waits through them instead. +pub(crate) fn is_bare_modifier(key: &str) -> bool { + matches!( + key, + "control" | "shift" | "alt" | "super" | "platform" | "function" | "fn" | "meta" | "command" + ) +} diff --git a/crates/app/src/layout.rs b/crates/app/src/layout.rs new file mode 100644 index 0000000..8c3dc71 --- /dev/null +++ b/crates/app/src/layout.rs @@ -0,0 +1,291 @@ +//! The window's fixed geometry: what every region is measured in. + +/// ...and the narrowest it is drawn: a library row whose length the engine has +/// not measured yet has a landing place but no width, and a head marker says +/// where it goes where a zero-width box would say nothing. +pub(crate) const GHOST_MIN: f32 = 2.; + +/// Fixed so the video region takes every pixel the window gains and the controls +/// never clip at 640x360. +pub(crate) const HEADER_H: f32 = 32.; +// 28 button row + 24 scrub strip + two 48 lanes + the timecode line + the gaps +// between them, with a few px of slack so a taller text line cannot push a lane +// off the bottom. +pub(crate) const PANEL_H: f32 = 220.; +/// How many lane rows are drawn before the lane column starts scrolling: past +/// this the panel would be taller than the picture it belongs under, and a +/// timeline that pushes the video off the window is not a timeline. +pub(crate) const LANES_MAX: usize = 6; +pub(crate) const LANE_H: f32 = 48.; +/// The lane header column: wide enough for `V1`/`A1` and fixed, so both lanes +/// and the ruler above them start at the same pixel and are the same width -- +/// one x-to-time mapping for the whole timeline. `HEADER_GAP` is part of that +/// offset and is therefore shared by all three rows. +pub(crate) const HEADER_W: f32 = 40.; +pub(crate) const HEADER_GAP: f32 = 4.; +/// The label row inside a clip; a waveform paints under it, never through it. +pub(crate) const LABEL_H: f32 = 15.; +/// A clip narrower than this shows no name: two characters and an ellipsis say +/// nothing that the tint has not already said, and cost the picture a smear. +pub(crate) const LABEL_MIN_W: f32 = 36.; +/// Peak buckets per second of source. Fixed and modest on purpose: `peaks` +/// allocates one bucket per window, so a rate taken from anything the user can +/// influence is an allocation bomb -- and 40 is already finer than the pixels a +/// clip is ever given. +/// +/// corner-cut: "finer than the pixels" stops being true once the timeline is +/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as +/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade +/// is a second, finer pass over the visible span only, cached like `waves` is. +pub(crate) const WAVE_BPS: u32 = 40; +/// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, +/// and a path with a point per pixel is a path per repaint. +pub(crate) const WAVE_COL: f32 = 2.; +/// The most columns one envelope is ever built from. A waveform is drawn into +/// the slice of its box that is on the bed ([`visible_slice`]), and a bed is a +/// screen wide, so nothing on screen ever reaches this -- it is the backstop for +/// a box laid out wider than any screen, whose path would otherwise cost a point +/// per two pixels of a width nobody can see and stall the repaint that was +/// meant to draw the wave. +pub(crate) const WAVE_COLS_MAX: usize = 4096; +/// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px +/// to look at -- `RULER_HIT_H` is the strip that has to be hit. +pub(crate) const HIT_MIN: f32 = 24.; +/// The media library's column: a share of the window rather than a fixed width, +/// so it yields on a narrow one, and never more than a third of it -- the +/// picture is what this program is for and keeps the majority at every size. +/// The floor is what a file name and a timecode need to be readable at all. +pub(crate) const LIBRARY_FRAC: f32 = 0.2; +pub(crate) const LIBRARY_MIN_W: f32 = 120.; +pub(crate) const LIBRARY_MAX_W: f32 = 220.; +/// A library row: a name over its duration, two lines and a click target, so +/// `HIT_MIN` binds it like every other one. +pub(crate) const ROW_H: f32 = 32.; +/// The tint swatch down the left of a row: the same colour that source's clips +/// wear in the lanes, which is the whole of the panel<->timeline association. +pub(crate) const SWATCH_W: f32 = 4.; +pub(crate) const CONTROL_H: f32 = 28.; +/// The volume slider beside its button: a hundred steps across it, so a pixel +/// is finer than a step and the drag reads as continuous. +pub(crate) const VOLUME_W: f32 = 110.; +pub(crate) const RULER_HIT_H: f32 = HIT_MIN; +/// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits +/// cannot push the layout around. +pub(crate) const TIME_W: f32 = 200.; +/// The keybindings card: a row per action, a title and a status line, inside a +/// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too. +/// Wider than the export card, and for the same reason that one is wider than +/// this used to be: at 320 the longest labels ("Remove the last video track (it +/// must be empty)") ran straight over the stroke printed at the other end of +/// their row. Every label in the registry fits beside its stroke here, and the +/// one that cannot -- a row waiting for a key to be pressed -- truncates rather +/// than overprinting. Still inside the 640 px floor. +pub(crate) const KEYS_W: f32 = 480.; +pub(crate) const KEYS_ROW_H: f32 = HIT_MIN; +/// How much of the row list is on screen at once; past this it scrolls. What +/// keeps the card inside the smallest window no matter how many actions the +/// editor grows -- ten rows fit here, and the eleventh is a scroll away. +pub(crate) const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; +/// The same for the export card, which carries two summary lines and a button +/// under its list and so has less room: a section header, six codecs, the +/// container, five qualities and the destination are more rows than a 360 px +/// window holds. Eight on screen, which is the whole format section and its +/// header -- what a user picks first is never behind a scroll. +pub(crate) const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; +/// The export card is wider than the keybindings one: its rows carry a key, a +/// name *and* what the choice means, and the two summary lines under them state +/// the whole file. At `KEYS_W` every one of those wrapped to two lines, which is +/// the card the user called unfriendly. Still inside the 640 px floor with the +/// scrim showing either side of it. +pub(crate) const EXPORT_W: f32 = 420.; +/// The column the key of a row is printed in, wide enough for `0–9`: every row +/// in the export card says what picks it, so the card is drivable by keyboard +/// without a legend to memorise. +pub(crate) const EXPORT_KEY_W: f32 = 26.; +/// Everything in the export card that is *not* the row list: the title, the +/// status line, the head and tail of the summary, the button, the gaps between +/// them and the padding around the lot. What the list may be is the window +/// minus this -- and never less than [`EXPORT_ROWS_H`], which is the number +/// that makes the card fit the 360 px floor. +pub(crate) const EXPORT_FIXED_H: f32 = 17. + 28. + 15. + 30. + CONTROL_H + 4. + 10. + 24.; +/// The menu a right-click on a clip opens: wide enough for the longest label +/// beside the stroke that does the same thing, with the click targets `HIT_MIN` +/// binds like every other list here. +pub(crate) const MENU_W: f32 = 260.; +pub(crate) const MENU_ROW_H: f32 = HIT_MIN; +pub(crate) const MENU_PAD: f32 = 6.; + +/// A cue's text, and the line it sits on. Fixed rather than a share of the +/// picture: the video region is 108 px tall at the 640x360 floor and a +/// proportional size there would be unreadable at exactly the size where it has +/// to be read. +pub(crate) const SUB_TEXT: f32 = 14.; +pub(crate) const SUB_LINE_H: f32 = 18.; +/// How far off the bottom of the picture the plate sits. +pub(crate) const SUB_BOTTOM: f32 = 8.; +/// The subtitle strip under the lanes: thin, because it is a picture of where +/// the cues are and nothing on it can be dragged -- `HIT_MIN` binds targets, and +/// this row has none. +pub(crate) const SUB_LANE_H: f32 = 16.; +/// A mark narrower than this is still drawn this wide: a one-frame cue on a +/// zoomed-out bed is worth a fraction of a pixel, and a mark nobody can see says +/// the track is empty. The silence preview's marks are floored by it too -- they +/// are the same kind of thing, a picture of where something is and no target. +pub(crate) const SUB_CUE_MIN_W: f32 = 2.; +/// How much of the subtitle list in the library column is on screen at once, +/// past which it scrolls -- the media list above it is what keeps the height. +pub(crate) const SUB_ROWS_H: f32 = 3. * ROW_H; +/// The row naming the file a block of tracks came out of. Shorter than a track +/// row because nothing on it is clicked -- `HIT_MIN` binds targets and a header +/// is a label, not a way in -- and drawn at all only where the column has the +/// height to show tracks under it ([`sub_headers_fit`]). +pub(crate) const SUB_HEAD_H: f32 = 18.; +/// How much of the subtitle list is on screen at the 640x360 floor: one row, +/// measured -- the section's own heading and the Add button under it take the +/// rest of the 84 px the column has there. +pub(crate) const SUB_ROWS_AT_FLOOR: f32 = ROW_H; +/// How much of a subtitle row's width the file's name in front of the label may +/// take. Half: which file and which language are both worth reading, and a name +/// given the whole row is a row where the language is what gets truncated. +pub(crate) const SUB_STEM_SHARE: f32 = 0.5; +/// Roughly how wide one character of an 11 px list row is. Generous on purpose: +/// the element truncates for real, and a budget that overshoots would have the +/// element cut the tail off after [`clip_middle`] had already kept it. +pub(crate) const LIST_CHAR_W: f32 = 6.; +/// The fewest characters a clipped name is cut to, however narrow the column +/// gets: past this there is nothing on either side of the gap to read. +pub(crate) const LIST_CLIP_MIN: usize = 5; +/// How long the export card's Subtitles line may get before it counts tracks +/// instead of naming them ([`subtitle_plan`]). Three lines of that row's value +/// box, at [`LIST_CHAR_W`] to a character: [`EXPORT_W`] less the row's padding +/// and gap, its tick and [`EXPORT_KEY_W`] key column, and the word "Subtitles" +/// in front of the value. Not a track count -- what walks the Destination row +/// off the bottom of the card is the *wrapping*, and thirty-five one-word +/// labels wrap less than three long ones. +pub(crate) const SUB_PLAN_CHARS: usize = (3. + * (EXPORT_W - 12. - 12. - (10. + 8. + EXPORT_KEY_W + 8. + 9. * LIST_CHAR_W)) + / LIST_CHAR_W) as usize; + +/// The one key name this file still spells out, and gpui's spelling of it: it +/// is the way out of a capture and out of the overlay, and both have to work +/// while the keymap itself is what is being changed -- so neither can go +/// through the keymap to find it. +pub(crate) const ESCAPE: &str = "escape"; + +/// How tall a column of `lanes` rows is, gaps included -- the panel's own gap +/// between them, since the rows sit in it. +pub(crate) fn lanes_h(lanes: usize) -> f32 { + match lanes { + 0 => 0., + n => n as f32 * LANE_H + (n - 1) as f32 * 8., + } +} + +/// How many whole lane rows a box this tall shows. At least one: a box too +/// short for a single lane still shows part of one, and "0 shown" would count +/// every lane there is as hidden. +pub(crate) fn lanes_shown(box_h: f32) -> usize { + (((box_h + 8.) / (LANE_H + 8.)).floor() as usize).max(1) +} + +/// How many rows are still below the fold *now*: the count the affordance says +/// out loud, and the reason it is a function of the scroll rather than of the +/// lane count alone. A line that keeps saying "2 more tracks below" after the +/// user has scrolled to the last one is a line that has stopped being true, and +/// an affordance nobody can make go away is read as a bug rather than as an +/// instruction. +/// +/// `scrolled` is how far down the column has been taken, in pixels. Rounded to +/// the nearest row: a half-scrolled row is showing, so it is not below. +pub(crate) fn rows_below(total: usize, box_h: f32, scrolled: f32) -> usize { + let past = ((scrolled / (LANE_H + 8.)).round().max(0.)) as usize; + total.saturating_sub(past + lanes_shown(box_h)) +} + +/// The same question for a column whose rows are not one height -- the +/// inspector's sections -- answered in pixels off what the scroll itself +/// reports: how far it may still be taken (`max_offset`) less how far it has +/// been (`offset`, which gpui keeps negative going down). +pub(crate) fn px_below(max_offset_h: f32, offset_y: f32) -> f32 { + (max_offset_h + offset_y).max(0.) +} + +/// What the subtitle strip adds to the panel: its own row and the panel's gap +/// above it, and nothing at all for a timeline with no subtitles on it -- the +/// picture does not pay for a strip that is not drawn. +pub(crate) fn subtitle_strip_h(shown: bool) -> f32 { + match shown { + true => SUB_LANE_H + 8., + false => 0., + } +} + +/// How tall the panel is with `lanes` tracks in it: [`PANEL_H`] is sized for the +/// two a project starts with, and every further one adds its own row -- up to +/// [`LANES_MAX`], past which the lane column scrolls instead and the panel stops +/// growing. +pub(crate) fn panel_h(lanes: usize) -> f32 { + PANEL_H + lanes_h(lanes.clamp(2, LANES_MAX)) - lanes_h(2) +} + +/// How tall the timeline region is: its own padding, the timecode line, the +/// ruler and the gaps between them, plus a row per lane. Measured from its +/// parts rather than taken off [`PANEL_H`] -- the button row moved out of it +/// ([`Player::toolbar`]), and a height still carrying that row's pixels is a +/// height that cuts the last lane off the bottom of the window. +pub(crate) fn timeline_h(lanes: usize) -> f32 { + TIMELINE_FIXED_H + lanes_h(lanes.clamp(2, LANES_MAX)) +} + +/// 8+8 padding, the timecode line, the 24 px ruler strip and the two 8 px gaps +/// between the three rows, with a couple of px of slack so a taller text line +/// cannot push a lane off the bottom. +pub(crate) const TIMELINE_FIXED_H: f32 = 16. + 18. + 8. + RULER_HIT_H + 8. + 4.; + +/// The most of a short window the timeline may take. At the 640x360 floor that +/// is 151 px of the 360, which leaves the picture a region rather than a +/// letterbox stripe -- and the lanes scroll inside it. +pub(crate) const TIMELINE_SHARE: f32 = 0.42; + +/// The edit toolbar directly above the timeline: one control's height in its +/// own padding, fixed so nothing in it can push the timeline down. +pub(crate) const TOOLBAR_H: f32 = CONTROL_H + 16.; + +/// The top bar: the project's name on the left, the two file actions on the +/// right. Fixed for the reason [`HEADER_H`] is. +pub(crate) const TOPBAR_H: f32 = 36.; + +/// The transport strip under the picture -- play, timecode, volume -- where a +/// player's own controls live in every consumer editor. +pub(crate) const TRANSPORT_H: f32 = CONTROL_H + 12.; + +/// One press of a zoom key, or one notch of ctrl+wheel. +pub(crate) const ZOOM_STEP: f32 = 1.25; + +/// How far one notch of a bare wheel slides the view along, as a share of what +/// is on the bed. A *share* rather than a number of pixels or of seconds: one +/// gesture then moves the same fraction of what is being looked at whether the +/// bed is showing five seconds or five hours, which is the only way a wheel is +/// usable at both ends of the zoom. +pub(crate) const SCROLL_NOTCH_SHARE: f32 = 0.1; + +/// How few frames the bed may be narrowed down to. Past this there is nothing +/// left to aim at -- a single frame across a whole window is a wall of colour, +/// not an edit surface. +pub(crate) const ZOOM_MIN_FRAMES: f64 = 8.; + +/// How thin a second of timeline may be drawn on a bed that is already showing +/// all of it: the far stop for a *short* project, which has no length of its own +/// worth widening to, so a five second import can still be zoomed out of. +pub(crate) const PPS_MIN: f64 = 1.; + +/// How much bed the far stop leaves past the last frame, as a multiple of the +/// timeline's own length -- so a timeline zoomed all the way out ends a sliver +/// short of the window's edge rather than glued to it. +pub(crate) const ZOOM_OUT_MARGIN: f64 = 1.05; + +/// How wide a second of timeline is drawn before anyone zooms: a five second +/// import is 200 px of a bed several times that, so a short clip reads as +/// short -- the thing a bed scaled to the content's own length cannot say. +/// [`View::fit`] is the one way back to "the whole timeline across the bed". +pub(crate) const PPS_DEFAULT: f64 = 40.; diff --git a/crates/app/src/library_meta.rs b/crates/app/src/library_meta.rs new file mode 100644 index 0000000..b24e7b8 --- /dev/null +++ b/crates/app/src/library_meta.rs @@ -0,0 +1,426 @@ +//! What a library row is and what it says about its file. + +use crate::*; + +/// What is left on the clipboard after the library row at `removed` was taken +/// out. A copied clip names its file by *index* into the source list +/// (`engine::Clip::source`) and a removal renumbers that list +/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste +/// **a different file** -- the next one along -- over the range it was copied +/// from. +/// +/// The clip's own file gone means there is nothing to paste: `None`, and the +/// next paste says the clipboard is empty rather than putting some other take +/// down. Every index past it moves down by one, exactly as the lanes' clips do. +pub(crate) fn clipboard_after_remove(clip: Option, removed: usize) -> Option { + let mut clip = clip?; + match clip.source.cmp(&removed) { + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Greater => { + clip.source -= 1; + Some(clip) + } + std::cmp::Ordering::Less => Some(clip), + } +} + +/// One library row: a file and one of its audio streams. Plain data, planned +/// before anything is drawn -- which rows exist at all is the branchy part. +#[derive(Debug, PartialEq)] +pub(crate) struct Row { + pub(crate) path: PathBuf, + pub(crate) stream: usize, + /// The file, plus which stream this is when the file has several. + pub(crate) name: String, + /// What the stream is, or blank for a file with a single one. + pub(crate) detail: String, + /// Why it cannot be put on this timeline, for a row that cannot: shown in + /// place of the length and the only thing that greys a row out. + pub(crate) unusable: Option, + /// Frames of the *file*, for the length line. + pub(crate) frames: u32, + /// Index into `SOURCE_TINTS`, shared by every stream of one file: the + /// swatch says which file, and the lanes tint their clips the same way. + pub(crate) tint: usize, +} + +/// Every row the library shows: one per source entry, plus one for each further +/// audio stream those files have that no clip plays yet -- a remux with a track +/// per language lists them all, the ones this engine cannot use greyed out +/// rather than hidden. Streams a file has not been probed for yet simply are +/// not there; the row for what *is* on the timeline is always there. +/// +/// `timeline_audio` is the rate and layout of source 0's stream, which every +/// other source must match: one output device and one copied AAC track for the +/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown, +/// and then nothing is greyed for it -- the engine still refuses. +pub(crate) fn library_rows( + sources: &[Source], + streams: &HashMap>, + decoders: &HashMap, Backend)>>, + timeline_audio: Option<(u32, u16)>, + frames: impl Fn(&Path) -> u32, +) -> Vec { + let mut rows = Vec::new(); + for (i, source) in sources.iter().enumerate() { + let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice); + let info = of_file.iter().find(|s| s.index == source.audio_stream); + let tint = sources + .iter() + .position(|s| s.path == source.path) + .expect("a source finds itself"); + rows.push(Row { + path: source.path.clone(), + stream: source.audio_stream, + name: row_name(&source.path, source.audio_stream, of_file.len() > 1), + // The decoder first: it is the same for every row of a file and + // it is what a person opening the panel is asking about. The + // stream half only where there is a choice to describe -- a file + // with one audio track is the row it has always been, name and + // length, and the length is what would be squeezed out at the + // panel's least width. + detail: join_detail( + &decoders + .get(&source.path) + .copied() + .flatten() + .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)), + &info + .filter(|_| of_file.len() > 1) + .map_or_else(String::new, stream_detail), + ), + // A stream already on the timeline is playing: whatever a probe + // would say about it now, it is usable by demonstration. + unusable: None, + frames: frames(&source.path), + tint, + }); + // The file's other streams, listed once, right after the last entry + // that names the file -- so a file's rows sit together. + if sources[i + 1..].iter().any(|s| s.path == source.path) { + continue; + } + for info in of_file { + if sources + .iter() + .any(|s| s.path == source.path && s.audio_stream == info.index) + { + continue; // it has a row of its own above + } + rows.push(Row { + path: source.path.clone(), + stream: info.index, + name: row_name(&source.path, info.index, true), + detail: stream_detail(info), + unusable: unusable(info, timeline_audio), + frames: frames(&source.path), + tint, + }); + } + } + rows +} + +/// The row's second line: what the stream is and then either how long it is or +/// why it cannot be used, with the separator only where both halves exist (a +/// single-stream file says nothing about its stream). +pub(crate) fn join_detail(detail: &str, tail: &str) -> String { + match (detail.is_empty(), tail.is_empty()) { + (true, _) => tail.to_string(), + (false, true) => detail.to_string(), + (false, false) => format!("{detail} · {tail}"), + } +} + +/// How a source's decoder reads: the codec and which seat has it, or the seat +/// alone for a still, which has no coded stream to name. The one place either +/// answer is spelled, so a row, a transport line and a card cannot disagree. +pub(crate) fn decode_label(codec: Option, backend: Backend) -> String { + match codec { + Some(codec) => format!("{} · {}", codec.name(), backend.label()), + None => backend.label().to_string(), + } +} + +/// How a row names its file: the file alone when it has one audio stream or +/// none, and the file plus which stream this row is when it has several -- +/// counted from 1, the way a player numbers tracks. +pub(crate) fn row_name(path: &Path, stream: usize, several: bool) -> String { + match several { + false => file_name(path), + true => format!("{} [audio {}]", file_name(path), stream + 1), + } +} + +/// What a stream is, for the row's second line: the language if the file says +/// one, then rate and layout. A field the header does not give is left out +/// rather than shown as a zero -- a stream we cannot parse says nothing about +/// itself, and saying "0 Hz" would be saying something. +pub(crate) fn stream_detail(info: &StreamInfo) -> String { + let mut parts: Vec = Vec::new(); + if let Some(lang) = &info.lang { + parts.push(lang_human(lang).to_string()); + } + if info.sample_rate > 0 { + parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.)); + } + parts.extend(layout(info.channels)); + parts.join(" ") +} + +/// What a file is coded at, for the properties cards: the rate of the whole +/// file, then each track's own beside it. A component the container does not +/// state is left out for `stream_detail`'s reason -- a fabricated `0` would be +/// saying something -- and a file that states none of the three says so rather +/// than showing an empty row. `None` is the probe still running, which is a +/// real wait: it walks a Matroska's clusters. +/// +/// The whole file's rate is the one that carries the unit and no word: named +/// "total" as well, the line loses its last component to `MENU_W`'s truncation +/// on an ordinary 1080p file -- and a rate cut to "0.13 soun" is a number the +/// card did not give. +/// +/// `tracks` is how many sound tracks the file has, from `probe_streams`. The +/// rate is the one track this engine plays -- the first, neither their sum nor +/// the biggest -- so a file with more says which of how many: a bare "0.16 +/// sound" on a file whose name says AC3.5.1 names a track without saying it is +/// one of two, and the card's Audio row above it may be describing the other. +/// +/// The marker costs the word "sound", the way the whole file's rate costs the +/// word "total" above, and for the same reason. Measured in Noto Sans 11 px +/// against the 186 px this value has beside a "Bitrate" label: "0.16 sound 1/2" +/// wants 192 px on a 4.7 Mb/s film and 205 on the 39.8 Mb/s remux -- +/// the marker is what gets cut, which is the one part of the line that is new. +/// Nothing that keeps the word fits the wide files -- the shortest, "snd 1/2", +/// still wants 188 px on that remux -- so the word goes and the number keeps +/// the answer: "0.16 1 of 2" wants 172 px, and 185 on the widest line a +/// library can produce (the 10.9 Mb/s three-track film). +pub(crate) fn bitrate_detail(rate: Option, tracks: usize) -> String { + let Some(rate) = rate else { + return "…".to_string(); + }; + let (per, unit) = rate_scale(rate); + let mut parts: Vec = Vec::new(); + if let Some(total) = rate.total { + // One unit for the three numbers, carried once, on the whole file's + // rate: the components are read against it. + parts.push(format!("{} {unit}", scaled(total, per))); + } + if let Some(video) = rate.video { + parts.push(format!("{} video", scaled(video, per))); + } + if let Some(audio) = rate.audio { + parts.push(match tracks > 1 { + true => format!("{} 1 of {tracks}", scaled(audio, per)), + false => format!("{} sound", scaled(audio, per)), + }); + } + match parts.is_empty() { + true => "not stated".to_string(), + false => parts.join(" · "), + } +} + +/// Below this a megabit's two decimals cannot state a rate, so the line is read +/// in kilobits instead. +pub(crate) const MB_FLOOR: u64 = 10_000; + +/// What the line counts in, and the name of it: the largest unit that can state +/// its *smallest* component, because that is the one a bigger unit rounds away. +/// Megabits for everything a real file produces -- the smallest component over +/// an 18-file sweep of a library was 0.13 Mb/s -- kilobits for the sub-32x32 +/// encodes below that. +/// +/// corner-cut: one unit for the whole line, so a file mixing a multi-megabit +/// picture with a sub-10 kb/s sound track prints the picture as four or five +/// digits of kilobits and loses the line's tail to `MENU_W`. No such file +/// exists in a library, and both units at once ("0.01 Mb/s · 1.2 kb/s video · +/// 9.5 kb/s sound") wants 215 px of the 186 the row has. Upgrade path is a +/// suffix per component ("1.2k video"), which measures 177 px. +pub(crate) fn rate_scale(rate: MediaBitrate) -> (f64, &'static str) { + match [rate.total, rate.video, rate.audio] + .into_iter() + .flatten() + .min() + { + // A rate this small is a broken header rather than a track, but it is + // still a number the file stated, and bits state it. + Some(bits) if bits < 10 => (1., "b/s"), + Some(bits) if bits < MB_FLOOR => (1_000., "kb/s"), + _ => (1_000_000., "Mb/s"), + } +} + +/// A rate in the line's unit as a person reads it: one decimal above 1 of it, +/// two below -- a 128 kbps song rounded to one decimal is "0.1", which reads as +/// a guess where "0.13" reads as a measurement. +/// +/// Never `0.00`: [`rate_scale`] picks the unit off the smallest component, so +/// two decimals always reach it. Every rate that gets here is one the container +/// really stated (the probe leaves out what it does not state, it never zeroes +/// it), and a "0.00 sound" would be this card saying a track that plays is +/// silent. +pub(crate) fn scaled(bits: u64, per: f64) -> String { + let n = bits as f64 / per; + match n >= 1. { + true => format!("{n:.1}"), + false => format!("{n:.2}"), + } +} + +/// A language tag as a person reads it. Everything a file writes is passed +/// through untouched bar the one tag that is not a language: "und" is what a +/// muxer writes when nobody said, and a row showing it verbatim names a +/// language nobody speaks. +pub(crate) fn lang_human(lang: &str) -> &str { + match lang { + "und" => "unknown language", + lang => lang, + } +} + +pub(crate) fn layout(channels: u16) -> Option { + match channels { + 0 => None, + 1 => Some("mono".to_string()), + 2 => Some("stereo".to_string()), + n => Some(format!("{n} ch")), + } +} + +/// Why a stream cannot go on this timeline, or `None` if it can. Both answers +/// are shown: a stream nothing can be done with is listed greyed with the +/// reason, never dropped from the list -- a file has the tracks it has, and a +/// picker that hides them is a picker that lies. +pub(crate) fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option { + if !info.decodable { + // AAC and AC-3 name themselves (`StreamInfo::codec`, which reads the + // stsd fourcc by hand); anything else mp4 0.14 does not parse has no + // name to give, and a row with no name still says why it is greyed. + return Some(match info.codec.as_str() { + "unknown" => "unsupported codec".to_string(), + codec => format!("{codec} is not supported"), + }); + } + // The **layout** and not the rate, which is what the engine's own gate now + // asks (`PlaybackSession::import`): a stream written at another sample rate + // is resampled onto the timeline's at the decoder's door, so greying its row + // would be this picker refusing what the timeline accepts. + let (_, channels) = timeline_audio?; + (info.channels != channels).then(|| { + format!( + "the timeline is {}", + layout(channels).unwrap_or_else(|| "silent".to_string()) + ) + }) +} + +/// How wide the equalizer card is drawn in a window this wide: all of it bar a +/// margin, up to [`EQ_W_MAX`]. The card is a graph, and a graph of twenty +/// thousand hertz on 320 px spends four pixels on the octave below middle C -- +/// so it takes the room a big window has and stays inside a small one. Floored +/// at the other cards' width, which is the last size the rows still read at. +pub(crate) fn eq_card_w(window_w: f32) -> f32 { + (window_w - EQ_W_MARGIN).clamp(KEYS_W, EQ_W_MAX) +} + +/// What the media list is given of the window. A share of it, so a narrow +/// window gives the panel less rather than giving the picture nothing, floored +/// where a name stops being readable and capped at a third of the window -- +/// the picture is what the program is for and keeps the majority at every size. +pub(crate) fn library_w(window_w: f32) -> f32 { + (window_w * LIBRARY_FRAC) + .clamp(LIBRARY_MIN_W, LIBRARY_MAX_W) + .min(window_w / 3.) +} + +/// What is left of a library column this wide for a row's *words*: the panel's +/// padding on both sides, the tint bar, the gap after it and the row's own right +/// inset. Every row in the column -- media and subtitle -- is built to this +/// shape, so one number answers for both. +pub(crate) fn row_text_w(width: f32) -> f32 { + // 8 px of panel padding each side, then the bar, the gap after it and the + // row's own right inset -- the numbers the rows are built with. + width - 16. - SWATCH_W - 6. - 6. +} + +/// A name cut to what a column this wide can hold, out of the *middle*. Two +/// files off one release differ in their last characters and nowhere else -- +/// "…Episode 01" against "…02" -- so a name cut from the right is the same +/// name twice and the list stops naming anything. The width decides how much +/// survives, not a number of characters somebody guessed: a wider window spells +/// more of the file out, and the floor still keeps both ends. +/// +/// The element truncates for real; this only decides where what is lost comes +/// out of. +pub(crate) fn clip_middle(name: &str, width: f32) -> String { + let budget = ((width / LIST_CHAR_W) as usize).max(LIST_CLIP_MIN); + let chars: Vec = name.chars().collect(); + if chars.len() <= budget { + return name.to_string(); + } + // The gap costs a character, and what is left of the odd one goes to the + // tail: the tail is the half that tells two of them apart. + let head = (budget - 1) / 2; + let tail = budget - 1 - head; + format!( + "{}…{}", + chars[..head].iter().collect::(), + chars[chars.len() - tail..].iter().collect::() + ) +} + +/// Whether the subtitle list has the height to name each file over its tracks. +/// A header is worth its own height only where there are still tracks under it +/// to read: at the 640x360 floor the list is one row tall, and a header there +/// would name a film and show none of it -- so at the floor there are no +/// headers and the rows say which file they came from themselves. +/// +/// The window's height answers it on its own: the row above the picture and the +/// panel under it are fixed, so every pixel the window gains past the floor is a +/// pixel this column gains. +pub(crate) fn sub_headers_fit(viewport_h: f32) -> bool { + SUB_ROWS_AT_FLOOR + (viewport_h - 360.).max(0.) >= SUB_HEAD_H + 2. * ROW_H +} + +/// What the window is called: the program, and what is open in it. The name is +/// what the header shows, so an empty window says the program alone rather than +/// "no file open — edith". +pub(crate) fn window_title(name: &str) -> String { + if name == NO_FILE { + "edith".to_string() + } else { + format!("{name} — edith") + } +} + +/// The tint a clip from source `n` wears. Cycled rather than extended: past the +/// palette two sources share a colour, which is a smaller lie than a fifth tint +/// bright enough to leave the family. +pub(crate) fn source_tint(source: usize) -> u32 { + SOURCE_TINTS()[source % SOURCE_TINTS().len()] +} + +/// The tint of a *file*, which is what a library row is named by: the first +/// source entry naming it, since two audio streams of one file are two sources +/// and one colour. +/// +/// `None` for a path no source names -- a standalone `.srt` is on nobody's +/// timeline, and painting it with the first file's colour would say it came out +/// of that file. No swatch says what is true: it belongs to itself. +pub(crate) fn file_tint(sources: &[Source], path: &Path) -> Option { + sources + .iter() + .position(|s| s.path == path) + .or_else(|| { + // A source entry is stored symlink-resolved (`Source::new`) and a + // path from anywhere else -- a subtitle track, a file being + // dragged -- is stored as it was spelled. `edith assets/film.mkv` + // is one file under two spellings, and matching by spelling alone + // said the film had no colour. Only asked when the spellings + // differ, so the common paint costs no syscall. + let path = std::fs::canonicalize(path).ok()?; + sources.iter().position(|s| s.path == path) + }) + .map(source_tint) +} diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index c89ec2f..df400bf 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1,6 +1,40 @@ mod keymap; mod ui; +mod audio_cards; +mod color_ui; +mod eq_ui; +mod export_ui; +mod files; +mod importing; +mod interact; +mod layout; +mod library_meta; +mod menus; +mod notices; +mod oracle; +mod subs; +mod timeline_math; +mod transport; +mod viewport; + +pub(crate) use audio_cards::*; +pub(crate) use color_ui::*; +pub(crate) use eq_ui::*; +pub(crate) use export_ui::*; +pub(crate) use files::*; +pub(crate) use importing::*; +pub(crate) use interact::*; +pub(crate) use layout::*; +pub(crate) use library_meta::*; +pub(crate) use menus::*; +pub(crate) use notices::*; +pub(crate) use oracle::*; +pub(crate) use subs::*; +pub(crate) use timeline_math::*; +pub(crate) use transport::*; +pub(crate) use viewport::*; + use ui::inspector::section_head; use ui::theme::*; use ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W, ZOOM_SLOT_W}; @@ -34,1131 +68,6 @@ use gpui::{ canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size, }; -/// ...and the narrowest it is drawn: a library row whose length the engine has -/// not measured yet has a landing place but no width, and a head marker says -/// where it goes where a zero-width box would say nothing. -const GHOST_MIN: f32 = 2.; - -/// Fixed so the video region takes every pixel the window gains and the controls -/// never clip at 640x360. -const HEADER_H: f32 = 32.; -// 28 button row + 24 scrub strip + two 48 lanes + the timecode line + the gaps -// between them, with a few px of slack so a taller text line cannot push a lane -// off the bottom. -const PANEL_H: f32 = 220.; -/// How many lane rows are drawn before the lane column starts scrolling: past -/// this the panel would be taller than the picture it belongs under, and a -/// timeline that pushes the video off the window is not a timeline. -const LANES_MAX: usize = 6; -const LANE_H: f32 = 48.; -/// The lane header column: wide enough for `V1`/`A1` and fixed, so both lanes -/// and the ruler above them start at the same pixel and are the same width -- -/// one x-to-time mapping for the whole timeline. `HEADER_GAP` is part of that -/// offset and is therefore shared by all three rows. -const HEADER_W: f32 = 40.; -const HEADER_GAP: f32 = 4.; -/// The label row inside a clip; a waveform paints under it, never through it. -const LABEL_H: f32 = 15.; -/// A clip narrower than this shows no name: two characters and an ellipsis say -/// nothing that the tint has not already said, and cost the picture a smear. -const LABEL_MIN_W: f32 = 36.; -/// Peak buckets per second of source. Fixed and modest on purpose: `peaks` -/// allocates one bucket per window, so a rate taken from anything the user can -/// influence is an allocation bomb -- and 40 is already finer than the pixels a -/// clip is ever given. -/// -/// corner-cut: "finer than the pixels" stops being true once the timeline is -/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as -/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade -/// is a second, finer pass over the visible span only, cached like `waves` is. -const WAVE_BPS: u32 = 40; -/// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, -/// and a path with a point per pixel is a path per repaint. -const WAVE_COL: f32 = 2.; -/// The most columns one envelope is ever built from. A waveform is drawn into -/// the slice of its box that is on the bed ([`visible_slice`]), and a bed is a -/// screen wide, so nothing on screen ever reaches this -- it is the backstop for -/// a box laid out wider than any screen, whose path would otherwise cost a point -/// per two pixels of a width nobody can see and stall the repaint that was -/// meant to draw the wave. -const WAVE_COLS_MAX: usize = 4096; -/// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px -/// to look at -- `RULER_HIT_H` is the strip that has to be hit. -const HIT_MIN: f32 = 24.; -/// The media library's column: a share of the window rather than a fixed width, -/// so it yields on a narrow one, and never more than a third of it -- the -/// picture is what this program is for and keeps the majority at every size. -/// The floor is what a file name and a timecode need to be readable at all. -const LIBRARY_FRAC: f32 = 0.2; -const LIBRARY_MIN_W: f32 = 120.; -const LIBRARY_MAX_W: f32 = 220.; -/// A library row: a name over its duration, two lines and a click target, so -/// `HIT_MIN` binds it like every other one. -const ROW_H: f32 = 32.; -/// The tint swatch down the left of a row: the same colour that source's clips -/// wear in the lanes, which is the whole of the panel<->timeline association. -const SWATCH_W: f32 = 4.; -const CONTROL_H: f32 = 28.; -/// The volume slider beside its button: a hundred steps across it, so a pixel -/// is finer than a step and the drag reads as continuous. -const VOLUME_W: f32 = 110.; -const RULER_HIT_H: f32 = HIT_MIN; -/// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits -/// cannot push the layout around. -const TIME_W: f32 = 200.; -/// The keybindings card: a row per action, a title and a status line, inside a -/// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too. -/// Wider than the export card, and for the same reason that one is wider than -/// this used to be: at 320 the longest labels ("Remove the last video track (it -/// must be empty)") ran straight over the stroke printed at the other end of -/// their row. Every label in the registry fits beside its stroke here, and the -/// one that cannot -- a row waiting for a key to be pressed -- truncates rather -/// than overprinting. Still inside the 640 px floor. -const KEYS_W: f32 = 480.; -const KEYS_ROW_H: f32 = HIT_MIN; -/// How much of the row list is on screen at once; past this it scrolls. What -/// keeps the card inside the smallest window no matter how many actions the -/// editor grows -- ten rows fit here, and the eleventh is a scroll away. -const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; -/// The same for the export card, which carries two summary lines and a button -/// under its list and so has less room: a section header, six codecs, the -/// container, five qualities and the destination are more rows than a 360 px -/// window holds. Eight on screen, which is the whole format section and its -/// header -- what a user picks first is never behind a scroll. -const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; -/// The export card is wider than the keybindings one: its rows carry a key, a -/// name *and* what the choice means, and the two summary lines under them state -/// the whole file. At `KEYS_W` every one of those wrapped to two lines, which is -/// the card the user called unfriendly. Still inside the 640 px floor with the -/// scrim showing either side of it. -const EXPORT_W: f32 = 420.; -/// The column the key of a row is printed in, wide enough for `0–9`: every row -/// in the export card says what picks it, so the card is drivable by keyboard -/// without a legend to memorise. -const EXPORT_KEY_W: f32 = 26.; -/// Everything in the export card that is *not* the row list: the title, the -/// status line, the head and tail of the summary, the button, the gaps between -/// them and the padding around the lot. What the list may be is the window -/// minus this -- and never less than [`EXPORT_ROWS_H`], which is the number -/// that makes the card fit the 360 px floor. -const EXPORT_FIXED_H: f32 = 17. + 28. + 15. + 30. + CONTROL_H + 4. + 10. + 24.; -/// The menu a right-click on a clip opens: wide enough for the longest label -/// beside the stroke that does the same thing, with the click targets `HIT_MIN` -/// binds like every other list here. -const MENU_W: f32 = 260.; -const MENU_ROW_H: f32 = HIT_MIN; -const MENU_PAD: f32 = 6.; - -/// A cue's text, and the line it sits on. Fixed rather than a share of the -/// picture: the video region is 108 px tall at the 640x360 floor and a -/// proportional size there would be unreadable at exactly the size where it has -/// to be read. -const SUB_TEXT: f32 = 14.; -const SUB_LINE_H: f32 = 18.; -/// How far off the bottom of the picture the plate sits. -const SUB_BOTTOM: f32 = 8.; -/// The subtitle strip under the lanes: thin, because it is a picture of where -/// the cues are and nothing on it can be dragged -- `HIT_MIN` binds targets, and -/// this row has none. -const SUB_LANE_H: f32 = 16.; -/// A mark narrower than this is still drawn this wide: a one-frame cue on a -/// zoomed-out bed is worth a fraction of a pixel, and a mark nobody can see says -/// the track is empty. The silence preview's marks are floored by it too -- they -/// are the same kind of thing, a picture of where something is and no target. -const SUB_CUE_MIN_W: f32 = 2.; -/// How much of the subtitle list in the library column is on screen at once, -/// past which it scrolls -- the media list above it is what keeps the height. -const SUB_ROWS_H: f32 = 3. * ROW_H; -/// The row naming the file a block of tracks came out of. Shorter than a track -/// row because nothing on it is clicked -- `HIT_MIN` binds targets and a header -/// is a label, not a way in -- and drawn at all only where the column has the -/// height to show tracks under it ([`sub_headers_fit`]). -const SUB_HEAD_H: f32 = 18.; -/// How much of the subtitle list is on screen at the 640x360 floor: one row, -/// measured -- the section's own heading and the Add button under it take the -/// rest of the 84 px the column has there. -const SUB_ROWS_AT_FLOOR: f32 = ROW_H; -/// How much of a subtitle row's width the file's name in front of the label may -/// take. Half: which file and which language are both worth reading, and a name -/// given the whole row is a row where the language is what gets truncated. -const SUB_STEM_SHARE: f32 = 0.5; -/// Roughly how wide one character of an 11 px list row is. Generous on purpose: -/// the element truncates for real, and a budget that overshoots would have the -/// element cut the tail off after [`clip_middle`] had already kept it. -const LIST_CHAR_W: f32 = 6.; -/// The fewest characters a clipped name is cut to, however narrow the column -/// gets: past this there is nothing on either side of the gap to read. -const LIST_CLIP_MIN: usize = 5; -/// How long the export card's Subtitles line may get before it counts tracks -/// instead of naming them ([`subtitle_plan`]). Three lines of that row's value -/// box, at [`LIST_CHAR_W`] to a character: [`EXPORT_W`] less the row's padding -/// and gap, its tick and [`EXPORT_KEY_W`] key column, and the word "Subtitles" -/// in front of the value. Not a track count -- what walks the Destination row -/// off the bottom of the card is the *wrapping*, and thirty-five one-word -/// labels wrap less than three long ones. -const SUB_PLAN_CHARS: usize = (3. - * (EXPORT_W - 12. - 12. - (10. + 8. + EXPORT_KEY_W + 8. + 9. * LIST_CHAR_W)) - / LIST_CHAR_W) as usize; - -/// The one key name this file still spells out, and gpui's spelling of it: it -/// is the way out of a capture and out of the overlay, and both have to work -/// while the keymap itself is what is being changed -- so neither can go -/// through the keymap to find it. -const ESCAPE: &str = "escape"; - -/// What the header says with no timeline open, and what the window title reads -/// as a program name rather than as a file name. -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. -const NOTHING_TO_PLAY: &str = "NOTHING TO PLAY — put a clip on the timeline first"; - -/// 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. -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)] -struct Volume { - steps: u8, - 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. - 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. - 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. - 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. - 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. - 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. - fn along(self) -> f32 { - f32::from(self.steps) / f32::from(Self::MAX_STEPS) - } - - /// The level as a whole number, for the button's fixed rect: muting swaps - /// the glyph beside it, never the width of the box. - fn percent(self) -> u32 { - u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS) - } - - /// What the button reads. The level shows while muted too: it is what the - /// next press of the mute key brings back. - fn label(self) -> String { - let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS); - if self.muted { - format!("Muted {percent}%") - } else { - format!("Vol {percent}%") - } - } -} - -impl Default for Volume { - fn default() -> Self { - Self { - steps: Self::MAX_STEPS, - muted: false, - } - } -} - -/// The library's three categories, in the order the giants list them: the -/// pictures, the sound, and the words. A file is in exactly one of them, so a -/// tab is a question with an answer rather than a filter with a guess. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum LibraryTab { - Media, - Audio, - Text, -} - -const LIBRARY_TABS: [LibraryTab; 3] = [LibraryTab::Media, LibraryTab::Audio, LibraryTab::Text]; - -impl LibraryTab { - fn label(self) -> &'static str { - match self { - LibraryTab::Media => "Media", - LibraryTab::Audio => "Audio", - LibraryTab::Text => "Text", - } - } - - /// Whether a source belongs on this tab. Subtitles are not sources at all - /// -- they are the [`Player::subtitle_section`] under the list -- so the - /// Text tab holds no rows of its own and says so. - fn holds(self, path: &Path) -> bool { - match self { - LibraryTab::Media => !engine::is_audio(path), - LibraryTab::Audio => engine::is_audio(path), - LibraryTab::Text => false, - } - } - - /// What an empty tab says instead of being a blank column. - fn empty(self) -> &'static str { - match self { - LibraryTab::Media => "No video or stills yet — Import, or drop a file on the window", - LibraryTab::Audio => "No sound yet — Import, or drop a file on the window", - LibraryTab::Text => { - "No subtitles yet — Add subtitles from a file, or drop an .srt on the window" - } - } - } -} - -/// What is known about a source's audio. Three states and not two, because a -/// file whose peaks have not come back yet must not be drawn as one that has no -/// audio at all: the first shows a bed, the second shows nothing. -#[derive(Clone)] -enum Wave { - /// Asked for; the decode is running on a background thread. - Loading, - /// The file has no audio track. An answer, not a miss. - Silent, - /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]: - /// "this file's sound could not be read" and "this file has no sound" look - /// the same on a lane, and the first is a bug report waiting to happen. - Failed, - Peaks(Arc>), -} - -/// The import a worker is reading, as the line above the panel shows it. No -/// fraction anywhere: neither read reports how far into the file it has come, -/// so what is honest is the file's name, the stage, and two clocks -- one that -/// proves the window is answering, one that says the stage has not moved. -struct Import { - path: PathBuf, - /// When the worker started, for the elapsed clock. - started: Instant, - /// Written by the worker between its two reads, read here every repaint. - stage: Arc, - /// The stage the line last saw and when it last changed. The pair is the - /// whole stall detector: a stage older than [`IMPORT_STALL`] is what the - /// honest wording is for. - seen: ImportStage, - since: Instant, - /// Set by the Cancel beside the line ([`Player::cancel_import`]), read at - /// the landing: what the worker read is dropped instead of joining the - /// timeline. - /// - /// corner-cut: the *read* is not stopped -- a demuxer walk polls nothing, so - /// the worker finishes into a result nobody takes, and the window is given - /// back at the click either way. Ceiling: a cancelled cold 24 GB import - /// still costs the disk its twenty seconds. Upgrade: a flag - /// `engine::demux::Demuxer::open` polls between clusters, which is where an - /// export's own cancel already lives ([`engine::ExportHandle::cancel`]). - cancelled: Arc, -} - -impl Import { - /// Reads the worker's stage and keeps the stall clock: it restarts when the - /// stage actually changes and at no other time, which is what makes "has - /// not moved in five seconds" a fact rather than a guess about the elapsed - /// clock. Hands back how long the current stage has stood, so the line has - /// one place to ask. - fn poll(&mut self) -> f32 { - let stage = ImportStage::from_u8(self.stage.load(std::sync::atomic::Ordering::Relaxed)); - if stage != self.seen { - self.seen = stage; - self.since = Instant::now(); - } - self.since.elapsed().as_secs_f32() - } -} - -/// What a scan is *of*: the source, which of its audio streams, and the clip's -/// own `[in, out)` source frames. The range is part of the name because it is -/// part of the read -- a clip cut in half is a different, shorter decode than -/// the whole take was, and levels read for one are not the other's. -type ScanKey = (PathBuf, usize, u32, u32); - -/// The silence scan a worker is running, as the card shows it. Same two clocks -/// as an [`Import`] and for the same reason -- one proves the window answers, -/// one says the read has stopped moving -- over a progress that *can* move: -/// a decode knows how far into the sound it has come, so the card says so. -struct SilenceScan { - /// Source, stream and source range being scanned, which is the cache key - /// the levels land under and what tells a second open of the same clip from - /// a new one. - key: ScanKey, - /// When the worker started, for the elapsed clock. - started: Instant, - /// Written by the worker, read here every repaint. The cancel flag in it is - /// this side's only word to a scan already running. - progress: Arc, - /// The tenths-of-a-second mark the line last saw and when it last changed: - /// the stall detector, exactly [`Import::poll`]'s. - seen: u64, - since: Instant, -} - -impl SilenceScan { - /// Reads the worker's mark and keeps the stall clock, restarting it only - /// when the mark actually moves -- [`Import::poll`]'s contract, over a - /// number instead of a stage. - fn poll(&mut self) -> f32 { - let scanned = self.progress.scanned.load(std::sync::atomic::Ordering::Relaxed); - if scanned != self.seen { - self.seen = scanned; - self.since = Instant::now(); - } - self.since.elapsed().as_secs_f32() - } -} - -/// A library row being dragged: the file and which of its audio streams that -/// row is, which is the whole of what a row names. Where it lands does not -/// change what is inserted. -struct AssetDrag(PathBuf, usize); - -/// A clip already on the timeline being dragged: the lane it is on and its index -/// there, which is how every other edit names a clip. Unlike an [`AssetDrag`] -/// nothing is inserted -- the same clip changes lane and keeps the frames it -/// plays -- but where along the bed it is let go is exactly where it lands, less -/// the offset the hand grabbed it at ([`Player::grab`]). -#[derive(Clone, Copy)] -struct ClipDrag { - lane: Lane, - idx: usize, - /// The clip that was picked up, so the drop can find it again: gpui freezes - /// the payload for the whole gesture, and an edit made *during* one -- a - /// stroke deletes, undoes or pastes, none of which a drag blocks -- ripples - /// the indices under it. The index alone would then name a different take at - /// the release, and the drag would move a clip nobody touched (see - /// [`live_idx`]). - clip: Clip, -} - -/// A track *header* being dragged: which track the hand took hold of, to be -/// let go over the header of the one whose place it is to take -/// ([`Player::reorder_lane`]). The lane alone -- a track carries its own clips -/// wherever it goes, so unlike a [`ClipDrag`] there is nothing else to name. -#[derive(Clone, Copy)] -struct LaneDrag(Lane); - -/// Where a header drag in flight would leave the track in the hand: the lane -/// whose slot it is about to take, and whether the line is drawn at that lane's -/// top edge (it is coming up from below) or its bottom one. The drop indicator -/// every editor draws between two tracks, and the header answer to the ghost a -/// clip drag lays on a lane ([`Ghost`]) -- stale between gestures, which costs -/// nothing because it is drawn only while one is live. -#[derive(Clone, Copy, PartialEq)] -struct LaneDrop { - lane: Lane, - above: bool, -} - -/// Where the drag in flight would leave what it is carrying: the lane the -/// pointer is over, the snapped head the release will commit ([`landing`]), and -/// how long the thing is. Drawn on that lane as a translucent box the size of -/// the take, so a landing is *seen* before the release rather than discovered -/// after it -- the line ([`Player::snap_cue`]) marks the frame, this shows the -/// body. `refused` is a drop the lane cannot take -- a picture over an audio -/// track, a sound over a video one -- tinted rather than silent, because the -/// refusal is coming at the release either way ([`lane_refuses`], -/// [`Project::move_clip`]). -#[derive(Clone, Copy, PartialEq)] -struct Ghost { - lane: Lane, - start: u32, - /// Timeline frames, which a speed has already been counted into: the box is - /// as wide as the clip is *long where it lands*. Zero for a library row of - /// unknown length, drawn as a head marker. - frames: u32, - /// The swatch of the file being carried ([`file_tint`]), so the - /// ghost reads as the thing in the hand. - tint: u32, - refused: bool, -} - -/// A clip edge being dragged: which end of which clip, and the timeline frame -/// the pointer has pulled it to. The box on screen is drawn from `to` while this -/// is set and the engine hears about it once, at the release -/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture, -/// exactly as an equalizer drag works. -#[derive(Clone, Copy)] -struct Trim { - lane: Lane, - idx: usize, - edge: Edge, - /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from - /// it is the width the release commits -- an edge stops under the pointer - /// rather than snapping back after the fact. - to: u32, - /// The dragged clip's group, so its other halves' boxes follow the edge on - /// screen exactly as the engine will move them. - link: Option, -} - -/// How wide a clip's edge is as a *target*: the strip at each end where a press -/// means "make this longer or shorter" instead of "move this to another lane". -/// Wide enough to hit, narrow enough that the middle of even a small box is -/// still the body. -const EDGE_W: f32 = 6.; - -/// Whether a clip box this wide gets its two trim strips at all. Below three -/// handles wide the pair would occlude the whole box: every press on it would -/// trim, and the clip could not be selected, dragged to another lane or picked -/// up by its middle -- which is exactly what a jumpcut leaves behind -/// ([`Player::cut_silences`] manufactures a great many short clips). Above it, -/// what is left between the two strips is a handle's width of body in its own -/// right. A clip too short for its handles is trimmed by zooming in first: the -/// bed is a magnifier, and the strip grows with the box. -fn trims(width: f32) -> bool { - width >= 3. * EDGE_W -} - -/// How wide a clip's box is *drawn*, given the width its own length is worth -/// (`span`). Never under [`HIT_MIN`], even where that is wider than the clip is -/// long: zoomed far out a short take is worth a fraction of a pixel, and a box -/// nobody can put a pointer on is a clip that cannot be selected, dragged, given -/// a menu or reached at all -- which is strictly worse than one drawn a few -/// pixels too wide. The same call [`cue_box`] makes for a mark, and what every -/// editor draws. -/// -/// A drawing only: [`Scale::time_at`] still reads the bed, so a press inside the -/// padding names the frame it points at, and the box's head is the clip's own. -fn clip_width(span: f32) -> f32 { - span.max(HIT_MIN) -} - -/// The sheet a card or a menu is painted on: the whole window, and the mouse -/// stops at it. Occluding is what tells gpui that nothing under this sheet is -/// hovered any more (`Hitbox::is_hovered`) -- without it the window carries on -/// hovering behind an open menu and pops *its* tooltip over the menu's items, -/// which is a card being painted over by the thing it covers. -/// -/// Every card and every menu takes its sheet from here, so no surface can be -/// drawn over the top of one by having been given a plain scrim. -fn scrim() -> Div { - div().absolute().inset_0().occlude() -} - -/// The sheet a card with a *slider* in it takes instead: the same scrim, with -/// the window's own drag listeners on it as well. -/// -/// A scrim occludes, and occluding is where gpui's hit test stops -/// (`Hitbox::is_hovered`, window.rs:788) -- so while a card is up the root is -/// not hovered anywhere behind it and its `on_mouse_move`/`on_mouse_up` hear -/// nothing at all. Every drag in this window is tracked from the root, because -/// each of them starts on a strip a few pixels wide that the pointer leaves at -/// once ([`Player::drag_move`]), so a card's handles were set by the press and -/// then frozen: the value never followed the hand and the release never wrote. -/// The scrim is the one surface above the occluder that covers the whole card, -/// so the same two listeners go here, and a drag that leaves the card is picked -/// up by the root's copy of them without a seam. -fn drag_scrim(cx: &mut Context) -> Div { - scrim() - .on_mouse_move(cx.listener(Player::drag_move)) - .on_mouse_up(MouseButton::Left, cx.listener(Player::drag_release)) -} - -/// A press that stops here. What every card's body hands its scrim: the scrim -/// closes the card on a press, and the card is painted after it, so this listener -/// runs first (gpui dispatches topmost-first, window.rs:3705) and a press meant -/// for a button never closes the card out from under its own click -- the rule -/// the menus already follow ([`Player::library_card`]). -fn swallow(_: &MouseDownEvent, _: &mut Window, cx: &mut App) { - cx.stop_propagation(); -} - -/// How close to an edge a dragged clip has to be let go for it to land *on* it: -/// the snap every timeline has, in pixels rather than frames so that it feels -/// the same at every zoom. Narrower than [`EDGE_W`] -- a hand aiming between two -/// takes must still be able to leave a gap of a few frames there. -const SNAP_PX: f64 = 5.; - -/// An open clip menu: which clip it was opened on, where it hangs, and whether -/// it has been turned over to show what that clip *is* instead of what can be -/// done to it. The lane and index are the ones the same click selected, so -/// every item acts on exactly the box under the pointer. -#[derive(Clone, Copy)] -struct ContextMenu { - lane: Lane, - idx: usize, - at: Point, - details: bool, -} - -/// An open library menu: which row it was opened on -- the file and the stream, -/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a -/// probe landing, a source going) cannot slide another row beneath the menu the -/// way a row *index* would -- where it hangs, and whether it has been turned -/// over to show what the file *is*. -#[derive(Clone)] -struct LibraryMenu { - path: PathBuf, - stream: usize, - at: Point, - details: bool, -} - -/// An open choice list: which setting it offers and where it hangs. What a -/// button that stepped one value on per click used to be -- a setting with more -/// than two values is a list to look at, not a thing to click round. Placed by -/// [`menu_at`] and closed by a stroke, exactly like the two menus above it. -#[derive(Clone, Copy, PartialEq)] -struct Picker { - of: Pick, - at: Point, - /// Which row the keyboard is on, from the value in force when the list - /// opened. The list answers ↑↓ and enter as well as a click: a setting whose - /// only door is a pointer is a setting half this editor's users cannot - /// reach, which is the rule `FIXED` already writes down for every card. - sel: usize, -} - -/// Which setting an open list is offering. The fit policy names the clip it is -/// about, like the clip menu it opens from -- indices move under every edit, so -/// the list closes on the first stroke as that menu does. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Pick { - Resolution, - Fps, - Fit(Lane, usize), - /// What the export's *sound* is coded at. Opened from the card's Sound row, - /// which is the only place it means anything. - AudioRate, - /// Which HDR-to-SDR rendition the project is watched and exported in - /// ([`engine::tonemap::Preset`]). Opened from the panel, beside the two - /// other settings that are the project's rather than the media's. - Tone, - /// Which palette the window is painted in ([`ui::theme`]). The one setting - /// here that is nobody's project: it is the person's, so it outlives the - /// timeline and every file opened in it. - Theme, -} - -/// One value a list offers, carrying everything picking it needs -- so a click -/// goes straight to the value rather than to a position in a list that was -/// built somewhere else. -/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told, -/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a -/// choice -- comparing two is all a list row ever does. -#[derive(Clone, Copy, PartialEq, Debug)] -enum Choice { - Size(u32, u32), - Fps(f64), - Fit(Lane, usize, FitPolicy), - AudioRate(u32), - Tone(Preset), - Theme(ui::theme::PaletteId), -} - -/// One row of an open list: the value, its name, the small print beside it, and -/// whether it is the one in force. -type ChoiceRow = (Choice, SharedString, SharedString, bool); - -/// What a library row's menu offers, in the order it lists them. Unlike the clip -/// menu's items none of these is a stroke -- there is no keyboard way to a row -- -/// so the label and the hint are written here rather than read off the keymap. -#[derive(Clone, Copy, PartialEq)] -enum RowItem { - Add, - Remove, - Reveal, - Properties, -} - -const ROW_ITEMS: [RowItem; 4] = [ - RowItem::Add, - RowItem::Remove, - RowItem::Reveal, - RowItem::Properties, -]; - -impl RowItem { - fn label(self) -> &'static str { - match self { - Self::Add => "Add at playhead", - Self::Remove => "Remove from library", - Self::Reveal => "Reveal in files", - Self::Properties => "Properties", - } - } - - /// The dim right-hand column, where the clip menu prints the stroke: what - /// the item will do to the timeline, so nothing here is a surprise. - fn hint(self) -> &'static str { - match self { - // Short enough to sit beside its label inside `MENU_W`, the clip - // menu's rule for a refusal: this column truncates, and a hint cut - // off mid-word says less than a shorter one. - Self::Add => "the whole file", - Self::Remove => "nothing plays it", - Self::Reveal => "file manager", - Self::Properties => "…", - } - } -} - -/// What the menu offers, in the order it lists them. Every one of these is an -/// action a stroke already reaches -- the menu is a second way *to* the actions -/// and never a second version of them -- so both the label and the hint come -/// out of the keymap registry and the two can never disagree. -const MENU_ITEMS: [ActionId; 14] = [ - ActionId::Cut, - // The clipboard pair, which had no door but a chord: copy takes the clip the - // menu names, and paste is the timeline's rather than this clip's -- the - // same kind of global item the mute below already is. - ActionId::Copy, - ActionId::Paste, - ActionId::Delete, - ActionId::Lift, - ActionId::Regroup, - ActionId::Detach, - ActionId::Group, - ActionId::Equalizer, - ActionId::Speed, - // The scan is a clip card like the two above it -- opened on whichever half - // was clicked -- and a card only a stroke could open is one a pointer never - // finds. - ActionId::Silence, - ActionId::Color, - ActionId::Fit, - ActionId::ToggleMute, -]; - -/// One row of the actions card, in the order it lists them: a heading, then -/// every action the registry files under it, then the strokes the modal cards -/// answer themselves. -/// -/// A list rather than a loop inside the render, so the card and -/// `every_action_is_on_the_actions_card` read the *same* order: an action that -/// reaches no row fails a test instead of quietly becoming pointer-unreachable. -enum KeyRow { - Head(keymap::Category), - /// Click its label to do it, click its stroke to change that stroke. - Act(ActionId), - /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may - /// unbind the way out of a card. - Fixed(usize), -} - -/// Every action, under its heading, and the card-local strokes beside them. -/// Generated from the registry -- [`ActionId::ALL`] in its own order, under -/// [`keymap::Category::ALL`] -- so an action added there is on the card the -/// moment it exists and there is no second list here to forget. -fn keys_rows() -> Vec { - let mut rows = Vec::new(); - for category in keymap::Category::ALL { - rows.push(KeyRow::Head(category)); - rows.extend( - ActionId::ALL - .into_iter() - .filter(|a| a.category() == category) - .map(KeyRow::Act), - ); - rows.extend( - keymap::FIXED - .iter() - .enumerate() - .filter(|(_, f)| f.category == category) - .map(|(i, _)| KeyRow::Fixed(i)), - ); - } - rows -} - -/// [`keys_rows`] with a search applied: the rows whose label or whose stroke -/// carries `needle`, and the heading each one lives under. A heading with -/// nothing left beneath it goes with them -- an empty "Playback" over a gap -/// reads as a list that lost its rows rather than as a search that found none. -/// -/// Each row keeps the index it has in the unfiltered list, so an element id is -/// the same one before and after a keystroke: filtering is a look at the list, -/// and gpui's per-element state is keyed on that id. -/// -/// Case-insensitive substring, on both columns: people look for an action by -/// what it does ("vol") and for a stroke by what they pressed ("ctrl"). -fn keys_filter(needle: &str, keymap: &Keymap) -> Vec<(usize, KeyRow)> { - let needle = needle.trim().to_lowercase(); - let rows = keys_rows().into_iter().enumerate(); - if needle.is_empty() { - return rows.collect(); - } - let hit = |label: &str, chord: &str| { - label.to_lowercase().contains(&needle) || chord.to_lowercase().contains(&needle) - }; - let mut out: Vec<(usize, KeyRow)> = Vec::new(); - // The heading above the row being looked at, until a row under it earns it - // a place -- then it goes in once, ahead of that row. - let mut pending: Option<(usize, KeyRow)> = None; - for (i, row) in rows { - match &row { - KeyRow::Head(_) => pending = Some((i, row)), - KeyRow::Act(action) => { - if hit(action.label(), &keymap.display(*action)) { - out.extend(pending.take()); - out.push((i, row)); - } - } - KeyRow::Fixed(f) => { - let fixed = &keymap::FIXED[*f]; - if hit(fixed.label, &fixed.chord) { - out.extend(pending.take()); - out.push((i, row)); - } - } - } - } - out -} - -/// The character a stroke types into the actions card's search box, if it types -/// one. gpui reports a printable key as itself and the space bar by name -/// (platform.rs:866), and everything else -- the arrows, the function keys -- -/// is a word this must not spell into the box letter by letter. -fn typed(key: &str) -> Option { - match key { - "space" => Some(' '), - _ => key - .chars() - .next() - .filter(|c| c.is_ascii_graphic() && key.chars().count() == 1), - } -} - -/// The project resolutions [`Player::cycle_resolution`] offers, largest first. -/// A short list of the sizes people name; the media's own is cycled in beside -/// them, which is what makes the trip round come back to where it started. -const RESOLUTIONS: [(u32, u32); 5] = [ - (3840, 2160), - (2560, 1440), - (1920, 1080), - (1280, 720), - (854, 480), -]; - -/// The project frame rates the list offers, slowest first: the rates footage is -/// actually shot and delivered at, the NTSC ones written as the ratios they are -/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very -/// number it is handed, so a rate rounded here would be a rate no timescale can -/// name. The media's own is cycled in beside them -/// ([`frame_rate_ladder`]), which is what keeps the way back on the list. -const FRAME_RATES: [f64; 8] = [ - 24_000. / 1001., - 24., - 25., - 30_000. / 1001., - 30., - 50., - 60_000. / 1001., - 60., -]; - -/// How far a band may be pushed either way, in dB. The engine clamps nothing -/// here -- it will filter whatever it is given -- so this is a UI decision: -/// past about this a peaking band stops sounding like tone and starts sounding -/// like a fault. -const EQ_GAIN_LIMIT: f32 = 12.; - -/// One dB per keystroke, which is roughly the smallest step anyone hears on a -/// single band. -const EQ_STEP: f32 = 1.; - -/// A twentieth of real time per keystroke, in the thousandths a [`Speed`] is -/// held in: fine enough to creep up on a rate, coarse enough that the whole -/// range is eighty presses and not eight hundred -- and it divides 1000, so -/// stepping from anywhere lands on exactly 1.00x on the way past. -const SPEED_STEP: i32 = 50; - -/// The rates the card's buttons offer, so the ones people actually name are one -/// click and not a drag. Real time is among them: it is the reset. -const SPEED_PRESETS: [u16; 6] = [250, 500, 1000, 1500, 2000, 4000]; - -/// A rate from a number of thousandths that may have run off either end -- what -/// a keystroke and a drag both produce. Clamped, not refused: a hand pushing -/// past the limit means "as far as it goes", exactly as a trim does. -fn speed_at(permille: i32) -> Speed { - Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16) -} - -/// The silence card's rows, in the order it lists them: how wide the apply -/// reaches, the threshold and the unit it is read in, the three durations a -/// scan is told, and the rate the speed-up plays at. What `silence_field` -/// indexes and what [`Player::nudge_silence`] moves. -const SILENCE_ROWS: usize = 7; - -/// How wide a jumpcut reaches. A ripple used to be the whole timeline's -/// business and nothing else; it is a *choice* now, because a podcast track's -/// silences are not the music track's business -- and the choice has to be on -/// screen, because "everything after this moved" is not a thing to discover -/// afterwards. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Scope { - /// The lanes of the take the scanned clip belongs to: its picture and its - /// sound stay one take, and nothing else moves. The default, because a clip - /// picked on screen is what a person means by "this". - Take, - /// That clip's lane, alone. Refused by the engine, by name, while the take - /// has a half elsewhere -- detaching is how a person says they mean it. - Track, - /// Every lane, which is what a ripple always was and what the timeline-wide - /// jumpcut still is. - Everything, -} - -/// The order the card cycles them in. -const SCOPES: [Scope; 3] = [Scope::Take, Scope::Track, Scope::Everything]; - -impl Scope { - /// What the row says, given the lanes it works out to: the *names* of the - /// tracks, because "this take" means nothing until it says which two. - fn label(self, lanes: &[Lane]) -> String { - let named = lanes - .iter() - .map(|l| l.label()) - .collect::>() - .join("+"); - match self { - Scope::Take => format!("this take ({named})"), - Scope::Track => format!("this track ({named})"), - Scope::Everything => "every track".to_string(), - } - } -} - -/// One press of a nudge key on each kind of row: a dB on the threshold, a -/// twentieth of a second on the three durations, and the speed card's own step -/// on the rate. -const SILENCE_DB_STEP: f32 = 1.; -const SILENCE_SECS_STEP: f64 = 0.05; - -/// How far each of them may be pushed. UI decisions, all of them: the engine -/// takes any finite number, but a forgiveness of ten seconds finds nothing in a -/// talking head. The threshold reaches full scale, which calls a whole take -/// silent -- that is a thing someone may want to ask for (the preview on the -/// lane says what it would cost before anything is cut), so the top is 0 rather -/// than a number this card picked for them. -const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.); -const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.); - -/// One press of a nudge key on the mix card, in dB: the step every fader and -/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone -/// hears as a move -- and it lands on round numbers, so a track set by ear -/// still reads as a number a person would say. -const MIX_DB_STEP: f32 = 1.; - -/// The mix card's rows below the faders: the limiter's ceiling and its switch. -/// One fader per audio track comes first, however many there are. -const MIX_MASTER_ROWS: usize = 2; - -/// The speed-up rate is bounded *below* by real time: a "speed-up" that slows -/// the silence down would make the timeline longer, which is the one thing -/// neither button may do. The top is [`Speed::MAX`]. -fn silence_rate(permille: i32) -> Speed { - speed_at(permille.clamp( - i32::from(Speed::NORMAL.permille()) + SPEED_STEP, - i32::from(Speed::MAX.permille()), - )) -} - -/// The graph's frequency axis: the range an ear works in, and the range every -/// band a file can carry sits inside. Log-spaced, so an octave is an octave -/// wherever it falls. -const EQ_FREQ_LOW: f32 = 20.; -const EQ_FREQ_HIGH: f32 = 20_000.; - -/// The curve box. Tall enough that 1 dB is a visible move at the ±12 dB axis, -/// and short enough that the card still fits a 360 px window. -const EQ_GRAPH_H: f32 = 132.; - -/// How wide the equalizer card is allowed to get. It is the one card that is a -/// *graph*: every pixel across is frequency resolution, and at the 320 px the -/// other cards use, a third of an octave was a couple of pixels. Past this the -/// curve stops gaining anything and the card starts reading as a wall. -const EQ_W_MAX: f32 = 720.; - -/// The gap the card leaves either side of it, so it reads as a card on a scrim -/// rather than as a second window: it takes the width it can get inside that. -const EQ_W_MARGIN: f32 = 32.; - -/// How many bands one clip's equalizer may carry from this card. Ten because -/// the keyboard picks a band with a digit and a keyboard has ten of them -- -/// past that a band would be reachable by pointer only. The engine itself caps -/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more -/// and this card will draw and edit every one it finds. -const EQ_BANDS_MAX: usize = 10; - -/// One press of the frequency keys, as a factor: a sixth of an octave, so a -/// band walks the whole axis in about sixty presses and still lands close -/// enough to a named frequency to aim at one. -const EQ_FREQ_STEP: f32 = 1.122_462; - -/// One press of the Q keys, as a factor, and the range they move in. Below the -/// bottom a peak is barely a peak any more; above the top it is a whistle on -/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside -/// them, so nothing a file carries has to be dragged into range first. -const EQ_Q_STEP: f32 = 1.25; -const EQ_Q_LOW: f32 = 0.3; -const EQ_Q_HIGH: f32 = 12.; - -/// How many points the curve is drawn from. One per ~3 px across the card: -/// past that the line is smooth and the extra biquad evaluations are wasted. -const EQ_CURVE_STEPS: usize = 96; - -/// A band's handle on the curve. Only the dot -- what is *grabbed* is the whole -/// graph (the nearest band along the frequency axis), so the target is the box. -const EQ_HANDLE: f32 = 10.; - -/// The frequencies the graph names, so the curve can be read as a curve *of -/// something*. The two ends label themselves at the edges. -const EQ_TICKS: [(f32, &str); 5] = [ - (20., "20 Hz"), - (100., "100"), - (1000., "1k"), - (10000., "10k"), - (20000., "20k"), -]; - -/// The gains the graph rules a line across, besides the 0 dB one it already -/// had: half way to each limit, so a boost can be read as "about six" without -/// counting pixels. The limits themselves are the box's own edges and are -/// named at the corners instead. -const EQ_DB_GRID: [f32; 2] = [6., -6.]; - - -/// How many played samples one spectrum frame is transformed from. A power of -/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz -/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough -/// (21 ms) that the analyser moves with the music. -const EQ_FFT: usize = 1024; - -/// The level range the analyser is drawn across, floor to ceiling in dBFS: the -/// bottom of the box is silence and the top is a bin at -12 dBFS, which is -/// about where a mixed track's loudest band sits. A look, not a measurement -- -/// the numbers on the axis are the curve's dB, never the analyser's. -const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.); - - - - -/// The colour card's four controls, in the order it lists them: what each is -/// called and the range it moves in. The order is `ColorParams`' own, which is -/// what [`color_band`] indexes. -const COLOR_BANDS: [(&str, f32, f32); 4] = [ - ("Brightness", -1., 1.), - ("Contrast", 0., 2.), - ("Saturation", 0., 2.), - ("Tint (cool–warm)", -1., 1.), -]; - -/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it -/// in forty presses and every stop is a number the file can write. A drag lands -/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard -/// cannot reach two different sets of values. -const COLOR_STEP: f32 = 0.05; - -/// The card's width: a slider row is a label, the bar and the value, and the -/// longest label has to fit beside all three without truncating (measured -/// against "Tint (cool–warm)"). -const COLOR_W: f32 = 460.; -/// How much of a slider row the bar itself gets -- what a drag is read against, -/// so it takes the width the two nudge buttons used to. -const COLOR_BAR_W: f32 = 240.; - -/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin: -/// fine enough to see a grade tilt, coarse enough that a subsampled count is -/// not noise. -const HIST_BINS: usize = 64; - -/// How many pixels of a frame the histogram reads. The stride is -/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a -/// thousandth of the frame and walks across columns rather than down one. -const HIST_SAMPLES: usize = 8_192; - -/// The histogram box. Shorter than the equalizer's curve because four slider -/// rows stand under it and the card still has to fit a 360 px window. -const HIST_H: f32 = 96.; - - -/// 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)] -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. - 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. - 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. -fn transport(playing: bool, played_out: bool) -> Transport { - match (played_out, playing) { - (true, _) => Transport::Ended, - (_, true) => Transport::Playing, - (_, false) => Transport::Paused, - } -} - struct Player { /// The timeline, once there is one. A run with no file opens without it and /// waits: the first media import or project load is what fills it, and @@ -6553,3771 +5462,6 @@ impl Render for Player { } } - -/// 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. -const SCRUB_GAP: Duration = Duration::from_millis(100); - -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. -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. -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`]). -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. -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), - } -} - -/// 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. -const SEEK_STALL: Duration = Duration::from_secs(2); - -/// 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. -/// The import bar's words, for the import bar's reason -- a window that cannot -/// move and a window that has hung look identical, so this one says which. -fn seek_line(standing: Option) -> Option { - let since = standing.filter(|d| *d >= SEEK_STALL)?; - Some(format!( - "still opening the picture — a cold read of a big file is seconds of it, and the window \ - is not frozen · {} elapsed", - clock(since.as_secs_f32()) - )) -} - -/// How a finished export announces itself. Written by `poll_export` and read -/// by the notice bar, which is what makes that one line clickable. -const EXPORT_DONE: &str = "EXPORT DONE → "; - -/// The path as a URI the bus will take: percent-encoded, because an export -/// lands wherever its source lives and those directories have spaces in them. -/// Bytes, not chars -- a path is not required to be UTF-8. -fn file_uri(path: &std::path::Path) -> String { - use std::os::unix::ffi::OsStrExt; - let mut uri = String::from("file://"); - for &b in path.as_os_str().as_bytes() { - match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { - uri.push(b as char) - } - _ => uri.push_str(&format!("%{b:02X}")), - } - } - uri -} - -/// Shows a file in the desktop's file manager, selected: the freedesktop -/// interface every major one answers, asked for over the session bus. With no -/// file manager on the bus the folder itself is the next best thing, and with -/// neither there is nothing to say -- the notice the click retired was the -/// answer, and a machine without a desktop opener is not one a second notice -/// would help. Blocks on two child processes, so it is never called on the UI -/// thread. -fn show_in_file_manager(path: &std::path::Path) { - // The URI must be absolute; an export path is only as absolute as the - // source it was built from. - let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); - let shown = std::process::Command::new("busctl") - .args([ - "--user", - "call", - "org.freedesktop.FileManager1", - "/org/freedesktop/FileManager1", - "org.freedesktop.FileManager1", - "ShowItems", - "ass", - "1", - &file_uri(&path), - "", - ]) - .status() - .is_ok_and(|s| s.success()); - if shown { - return; - } - if let Some(dir) = path.parent() { - let _ = std::process::Command::new("xdg-open").arg(dir).status(); - } -} - -/// Runs the first chooser that is installed. `Some(None)` is a cancelled -/// dialog; `None` is a machine with no chooser at all, and what still works -/// without one differs per dialog, so the caller words that refusal. -/// -/// The desktop's own choosers, asked for by name because gpui 0.2 has no file -/// dialog of its own and none of these is worth a dependency. -fn run_picker(pickers: [(&str, Vec); 2]) -> Option> { - for (bin, args) in pickers { - // Not installed: try the next one. Anything else (a cancel, a refusal) - // is that chooser's answer and is taken as final. - let Ok(out) = std::process::Command::new(bin).args(args).output() else { - continue; - }; - let path = String::from_utf8_lossy(&out.stdout).trim().to_string(); - return Some((!path.is_empty()).then(|| PathBuf::from(path))); - } - None -} - -/// `title` is what the dialog calls itself: two buttons open this same chooser -/// for two different questions -- a file to import, a file to take subtitles out -/// of -- and a dialog titled "import" over the second one is the wrong question -/// answered. No extension filter on either: what can be read is the engine's -/// answer (`PlaybackSession::parse_subtitles` takes a container as readily as a -/// `.srt`), and a list of suffixes written here would hide a file edith would -/// have taken. -fn pick_file(title: &str) -> Result, &'static str> { - run_picker([ - ( - "zenity", - vec!["--file-selection".into(), format!("--title={title}")], - ), - ("kdialog", vec!["--getopenfilename".into()]), - ]) - .ok_or( - "NO FILE CHOOSER — install zenity or kdialog, or drag the file onto this window to import it", - ) -} - -/// The save-side dialog, opened on where the export would land anyway: with no -/// chooser installed that default is still what gets written, so this refusal -/// costs the export nothing and says so. -fn pick_save(default: &std::path::Path) -> Result, &'static str> { - let default = default.to_string_lossy().into_owned(); - run_picker([ - ( - "zenity", - vec![ - "--file-selection".into(), - // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated - // and does the confirming itself. - "--save".into(), - "--title=edith — export to".into(), - format!("--filename={default}"), - ], - ), - ("kdialog", vec!["--getsavefilename".into(), default]), - ]) - .ok_or( - "NO FILE CHOOSER — install zenity or kdialog to choose where; exporting beside the source", - ) -} - -/// Where an export goes: the source path with `.export.mp4` for an extension, -/// so it lands beside the original and can never be the original. -fn export_path(source: impl Into) -> PathBuf { - let mut path = source.into(); - path.set_extension("export.mp4"); - path -} - -/// Where a save goes when the timeline did not come from a project file: the -/// media path with `.edith` for an extension, beside it like an export. A -/// project loaded from disk keeps its own path instead, so saving it twice -/// writes the same file. -fn project_path(source: impl Into) -> PathBuf { - let mut path = source.into(); - path.set_extension("edith"); - path -} - -/// Whether a dropped or named path is a project rather than media. Exactly the -/// lowercase extension `save_project` writes -- anything else goes to the -/// demuxer, which is the one that can say what it really is. -fn is_project(path: &std::path::Path) -> bool { - path.extension().is_some_and(|e| e == "edith") -} - -/// The tail of a path, for showing. A path that is all root has none, and reads -/// as itself. -fn file_name(path: &std::path::Path) -> String { - path.file_name().map_or_else( - || path.display().to_string(), - |n| n.to_string_lossy().into(), - ) -} - -/// How many messages wait behind the one on the bar before the oldest is -/// dropped. A queue with no ceiling is a way for a stuck loop to eat the heap; -/// eight is more than a user will ever answer in a row. -const NOTICES_MAX: usize = 8; - -/// The narrowest a notice's *message* is allowed to be squeezed before its hint -/// gives up the line and drops below it. -/// -/// The bar is a message beside a hint, and at the 640x360 floor the picture -/// region it hangs under is narrower than the hint alone -- so the message was -/// squeezed to nothing and wrapped one character per line, which is a failure -/// rendered as a column of letters. Wide enough that a line of it is a phrase -/// rather than a word ladder, and narrow enough to still fit beside the hint in -/// any window worth putting two things on a line in. -const NOTICE_MIN_W: f32 = 180.; - -/// The whole of the queue's policy, where it can be read at once and tested -/// without a window: dedupe against the back, a ceiling, oldest out first. -/// [`Player::notify_user`] is the door every message comes through; this is what -/// the door does. -fn push_notice(notices: &mut std::collections::VecDeque, message: SharedString) { - // A repeat of what is already at the back is dropped -- holding a key that - // refuses would otherwise fill the queue with one sentence, and the count on - // the bar would be a count of how long the key was held. - if notices.back() == Some(&message) { - return; - } - if notices.len() >= NOTICES_MAX { - notices.pop_front(); - } - notices.push_back(message); -} - -/// The tail an open/load notice grows when the file has sound the engine cannot -/// decode: it plays perfectly, in silence, and that is the one thing the window -/// would otherwise never say (the engine's own word for it, verbatim). -fn audio_notice(session: &PlaybackSession) -> Option { - session - .audio_disabled_reason() - .map(|reason| format!(" — NO AUDIO: {reason}")) -} - -/// Whether a dropped or named path is a subtitle file rather than media: the -/// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s -/// reason -- the import door has to know which of the engine's two doors a file -/// goes through before anything is opened. -/// -/// `.mks` is one of them, and it is the only Matroska extension that is: it is -/// the *subtitles alone*, so there is no source in it to import and a drop of -/// one used to be refused for having no video track -- while `+ S` on the same -/// bytes took it ([`PlaybackSession::parse_subtitles`] reads it as Matroska). -/// The other two are media and stay media: `.mka` is the sound alone, which -/// [`engine::is_audio`] already imports as a song, and `.mk3d` is a film. Both -/// may *carry* subtitles, which is [`carries_subtitles`] and not this. -fn is_subtitle(path: &std::path::Path) -> bool { - path.extension().and_then(|e| e.to_str()).is_some_and(|e| { - matches!( - e.to_ascii_lowercase().as_str(), - "srt" | "vtt" | "webvtt" | "ass" | "ssa" | "mks" - ) - }) -} - -/// Whether a media path is a container that can carry subtitle tracks *inside* -/// it -- every Matroska extension and the three ISO-BMFF ones, which is the list -/// [`PlaybackSession::parse_subtitles`] walks (Matroska blocks and mp4 `tx3g` -/// alike). Named for what it gates and not for one of the two families, because -/// an mp4 answers `true` here now. -/// -/// Matroska's set is the standard's own and closed by it -/// (`engine::demux::is_matroska`), so it is copied whole rather than trimmed to -/// the two that carry a film: a `.mk3d` opened as media has its tracks walked -/// like the `.mkv` it is, and a `.mka` song can hold a lyric track. A suffix -/// wider than the engine's would be a file taken here and refused deeper down. -fn carries_subtitles(path: &std::path::Path) -> bool { - path.extension().and_then(|e| e.to_str()).is_some_and(|e| { - matches!( - e.to_ascii_lowercase().as_str(), - "mkv" | "mka" | "mks" | "mk3d" | "webm" | "mp4" | "m4v" | "mov" - ) - }) -} - -/// What a worker hands back, which is the fork [`arrival`] made when it was -/// started. An import is *read* and thrown away; the file argv named is opened -/// outright, because nothing else is going to open it afterwards. -enum Landed { - /// An import into a timeline that is up: the container probed and the - /// subtitle tracks walked, both *kept* -- they are the expensive halves and - /// the worker is where they belong, so [`Player::take_import`] is left with - /// two pushes ([`engine::PlaybackSession::import_probed`], - /// [`subtitle_tail`]). - Read(Subs, Probe), - /// A whole timeline the worker opened, with the tail its subtitle tracks - /// earn, ready to be hung off the window -- or the engine's refusal. `true` - /// is the media argv named, which *becomes* the timeline; `false` is a file - /// arriving at a window that had none, which fills the library and leaves - /// the lanes empty for a drag ([`Player::install_media`]). - Media(Result<(PlaybackSession, String), String>, bool), - /// A `.edith`, restored: argv's, and the one a drop or the Import button - /// brought ([`arrival`]). - Project(Result), -} - -/// What the container walk found, for [`Player::take_import`] to register, or -/// the engine's refusal in the words it would have used on the UI thread. -/// -/// `None` for the doors that never reach a demuxer: a song, a still and a -/// subtitle file, whose own small reads stay where they were -/// ([`engine::PlaybackSession::import`]). -type Probe = Option>; - -/// A media file opened as a session, with the subtitle tracks it carries inside -/// it taken in the same breath -- the two reads a file costs, in the one place -/// both doors ([`Player::open_media`] and the worker below) go through. -/// -/// `place` is which door: a file *opened* is the timeline, one *imported* into -/// an empty window fills the library and leaves the lanes empty for a drag. -fn open_session( - path: &std::path::Path, - place: bool, - subs: Subs, -) -> Result<(PlaybackSession, String), String> { - let opened = match place { - true => PlaybackSession::open(path), - false => PlaybackSession::open_library(path), - }; - let mut session = opened.map_err(|e| e.to_string())?; - let tail = subtitle_tail(&mut session, subs).unwrap_or_default(); - Ok((session, tail)) -} - -/// The whole of what a queued file costs, off the UI thread. An import only -/// needs its pages warmed ([`read_ahead`]); the file argv named is *opened* -/// here instead, and that is the difference between a warm launch paying for -/// one header walk and paying for two -- the window is up either way. -fn open_ahead( - what: Landing, - path: &std::path::Path, - stage: &std::sync::atomic::AtomicU8, - gate: Option, -) -> Landed { - match what { - Landing::Import => read_ahead(path, stage, gate), - Landing::Project => { - let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string()); - Landed::Project(opened) - } - Landing::Open => open_whole(path, true, stage), - } -} - -/// A whole timeline, opened here and handed over: the file argv named (`place`, -/// which *is* the timeline) and a file arriving at a window with no timeline to -/// import into, which fills the library instead. One function because they are -/// one read -- the engine's two doors differ by which lanes come up empty -/// ([`engine::PlaybackSession::open_library`]), not by what they walk. -fn open_whole(path: &std::path::Path, place: bool, stage: &std::sync::atomic::AtomicU8) -> Landed { - use std::sync::atomic::Ordering::Relaxed; - let opened = match place { - true => PlaybackSession::open(path), - false => PlaybackSession::open_library(path), - }; - // The same two stages a read reports, because they are the same two - // reads: the container, and then the tracks inside it. - stage.store(ImportStage::Subtitles as u8, Relaxed); - Landed::Media( - opened.map_err(|e| e.to_string()).map(|mut session| { - let subs = subtitle_notice(&mut session, path).unwrap_or_default(); - (session, subs) - }), - place, - ) -} - -/// Reads, off the UI thread, everything the import that follows would have read -/// -- and hands all of it over. Nothing here is a warm-up any more: the -/// container is *probed* ([`engine::PlaybackSession::probe_import`]) and the -/// subtitle tracks are *walked*, and [`Player::take_import`] registers what came -/// back. Measured on the 24 GB 4K HEVC remux: 21.4 s of header cold, 429 ms -/// warm, plus 1-4 s of probing the timeline's own first source, plus the cue -/// walk -- all of it here, and the window keeps painting through it. -/// -/// `gate` is the timeline the file is checked against -/// ([`engine::PlaybackSession::import_gate`]), taken before the worker started -/// because a worker cannot reach the session. `None` is a window with no -/// timeline to import into: then there is nothing to check against and nothing -/// to register, so the file is *opened* here instead, whole -/// ([`open_whole`]) -- which is the same twenty seconds, on the same thread, -/// rather than on the one that draws. -/// -/// The header error is carried back now rather than dropped: it is the engine's -/// own refusal, from the only walk anybody makes, so it is worded once and shown -/// at the landing. The subtitle refusal travels beside it for the same reason. -/// -/// `stage` is what the line above the panel is naming while this runs. -fn read_ahead( - path: &std::path::Path, - stage: &std::sync::atomic::AtomicU8, - gate: Option, -) -> Landed { - use std::sync::atomic::Ordering::Relaxed; - stage.store(ImportStage::Header as u8, Relaxed); - // Nothing to import into, and nothing a subtitle file needs opened: the - // first opens the library itself, here; the second has no container at all. - let Some(gate) = gate else { - return match is_subtitle(path) { - true => Landed::Read(walk_subtitles(path), None), - false => open_whole(path, false, stage), - }; - }; - // The three doors an import goes through: a song is measured by its - // duration and a still by its header -- both the engine's own reads, warmed - // here and paid again at the landing, which is a header apiece -- and - // everything else is the container walk, which is handed over whole. - let probe = if engine::is_audio(path) { - engine::AudioSession::duration_secs(path).ok(); - None - } else if engine::is_image(path) || is_subtitle(path) { - None - } else { - Some(PlaybackSession::probe_import(gate, path)) - }; - stage.store(ImportStage::Subtitles as u8, Relaxed); - // ...and the tracks inside it, kept. - Landed::Read(walk_subtitles(path), probe) -} - -/// Every subtitle track a file carries, cues and all -- the walk that costs, in -/// the one place every door that pays it goes through. `Ok` and empty for a file -/// with none to read, which is what a file that is neither a container we can -/// walk ([`carries_subtitles`]) nor a subtitle file is: the same answer -/// `add_subtitle_tracks` gives it, and nothing is opened to find that out. -/// -/// Nothing in here is a session, on purpose ([`PlaybackSession::parse_subtitles`] -/// is an associated fn): no borrow crosses the await, so this runs whole on a -/// worker while the window keeps painting. -fn walk_subtitles(path: &std::path::Path) -> Subs { - match carries_subtitles(path) || is_subtitle(path) { - true => PlaybackSession::parse_subtitles(path), - false => Ok(Vec::new()), - } -} - -/// The subtitle tracks a media file carries, taken into the session as it is -/// opened, and the tail the notice grows for them: an mkv or an mp4 with -/// subtitles in it arrives with its subtitles, because a track nobody imported -/// is a track nobody knows is there. Every other container answers `None` -/// without being read. -/// -/// A refusal is a tail too, never a failure of the open: the picture and the -/// sound of a film whose subtitle tracks cannot be walked are still the film. -/// -/// Both halves at once, which only a *worker* may do: the walk reads the whole -/// file for its cues (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour -/// 4K remux, 9.7 s on a cold 25 GB one. The one caller is the open beside which -/// this runs on the worker ([`open_ahead`]), never the render thread; an -/// import splits the two halves across the hop instead ([`read_ahead`] walks, -/// [`subtitle_tail`] pushes). -fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option { - subtitle_tail(session, walk_subtitles(path)) -} - -/// What a subtitle walk ([`walk_subtitles`]) gave, on its way from whichever -/// thread paid for it to the timeline. `Send` all the way down (`sendable()`, -/// `engine/tests/subtitles.rs`), which is what lets the walk be a worker's. -type Subs = engine::Result>; - -/// The tail a file's own subtitle tracks earn on the notice that names it, and -/// the push that puts them on the timeline -- the second half of the walk, the -/// cheap one ([`PlaybackSession::add_subtitle_tracks`]: no open, no seek, no -/// decode). Every door that arrives with a *file* words it here, once: the file -/// argv named, an import, and an import into an empty window cannot say the same -/// thing differently, whichever thread read the cues. -/// -/// `None` for a file that gave none and for one whose tracks are on the timeline -/// already -- an import that adds nothing says nothing about subtitles. A -/// refusal is a tail too, never a failure of the import: the picture and the -/// sound of a film whose subtitle tracks cannot be walked are still the film. -fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option { - match subs { - Ok(tracks) => match session.add_subtitle_tracks(tracks) { - 0 => None, - n => Some(format!(" — {n} subtitle track(s) in the file")), - }, - Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")), - } -} - -/// The push both deliberate add-subtitles doors end on -- `+ S` and its key -/// ([`Player::add_subtitles`]) and a dropped or argv'd subtitle file -/// ([`Player::take_subtitles`]) -- so the two cannot come to word the same file -/// differently. -/// -/// The walk having found *nothing* is a refusal and not a count: a container -/// with no subtitle track in it and a file whose tracks are all on the timeline -/// already both push zero rows, and they are opposite answers -- one says look -/// somewhere else, the other says you already have them. The engine's own door -/// draws the same line in the same words -/// ([`PlaybackSession::no_subtitles_in`], asked here because this route splits -/// the walk from the push to keep the walk off the render thread). -/// -/// The file itself joins nothing either way: no library row, no lane, no clip. -/// Subtitles are a list the timeline carries, and this is the only thing that -/// touches it. -fn pushed( - session: &mut PlaybackSession, - path: &std::path::Path, - tracks: Vec, -) -> engine::Result { - match tracks.is_empty() { - true => Err(PlaybackSession::no_subtitles_in(path)), - false => Ok(session.add_subtitle_tracks(tracks)), - } -} - -/// What a subtitle row says under its name: how many cues it holds and whether -/// they are pictures ([`engine::subtitle::SubtitleTrack::is_bitmap`]) -- which -/// is the difference between a track an export writes into the file and one it -/// can only draw -- or, for a track that could not be read, the engine's own -/// reason verbatim. A refusal is still what a row can be *for*: a VobSub track -/// dropped from the list would say the film has no subtitles at all. -fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String { - match (&track.refused, track.is_bitmap()) { - (Some(why), _) => why.clone(), - (None, true) => format!("{} cues — pictures", track.cues.len()), - (None, false) => format!("{} cues", track.cues.len()), - } -} - -/// What the export card's Subtitles row says: the engine's own words for the -/// tracks an export carries (`plan`, [`engine::export::planned_subtitles`] asked -/// about `picks`) and, beside them, the rows it is carrying nothing of. -/// -/// `picks` is [`Player::export_subs`] -- every track with a cue left in the -/// exported range -- so a track sitting in the list with eighty-three cues -/// nowhere near a trimmed timeline never reaches the engine at all, and the card -/// said nothing about it while the list went on showing it. Which tracks have -/// cues *here* is this side's answer and nobody else's, so this side words it. -/// -/// Past [`SUB_PLAN_CHARS`] the line counts rather than names: every name is more -/// words in a value box `MENU_W` wide, and at 35 tracks the row wrapped to ten -/// lines and pushed the Destination row under the fold of the card. The names -/// are still one row each in the Subtitles list, with the cue count and the -/// reason under them ([`subtitle_detail`]) -- more than this line ever said. -/// -/// The counted split follows the engine's own order of reasons (`refused`, then -/// pictures, then no cues), with the last asked of the timeline instead of the -/// track. -/// -/// corner-cut: that split reads the same public fields the list rows read -/// (`refused`, [`engine::subtitle::SubtitleTrack::is_bitmap`]) rather than the -/// engine's decision, so a *new* reason to drop a track would be counted here as -/// embedded until this follows it -- the named line, which is the engine's -/// string verbatim, would say it correctly meanwhile. Upgrade path: reasons out -/// of `planned_subtitles` as data rather than as one sentence, which is an -/// engine change. -fn subtitle_plan( - plan: String, - tracks: &[engine::subtitle::SubtitleTrack], - picks: &[usize], -) -> String { - let mut parts: Vec = Vec::new(); - // "none" is the engine's word for an empty pick list and would read as a - // verdict on the tracks named after it. - if !picks.is_empty() { - parts.push(plan); - } - parts.extend( - tracks - .iter() - .enumerate() - .filter(|(i, _)| !picks.contains(i)) - .map(|(_, track)| format!("{} — no cues here", track.label)), - ); - let named = parts.join("; "); - if named.chars().count() <= SUB_PLAN_CHARS { - return match named.is_empty() { - true => "none".to_string(), - false => named, - }; - } - let (mut embedded, mut unread, mut pictures, mut off) = (0, 0, 0, 0); - for (i, track) in tracks.iter().enumerate() { - match ( - track.refused.is_some(), - track.is_bitmap(), - picks.contains(&i), - ) { - (true, _, _) => unread += 1, - (_, true, _) => pictures += 1, - (_, _, false) => off += 1, - _ => embedded += 1, - } - } - let mut counted = vec![format!("{embedded} of {} → embedded", tracks.len())]; - counted.extend( - [ - (pictures, "pictures"), - (unread, "unread"), - (off, "no cues here"), - ] - .into_iter() - .filter(|(n, _)| *n > 0) - .map(|(n, why)| format!("{n} {why}")), - ); - counted.join("; ") -} - -/// Every subtitle track one file gave, kept together. Plain data, planned -/// before anything is drawn -- the grouping is the branchy part and it is the -/// same answer whatever a styling puts around it. -/// -/// [`Player::subtitle_section`] draws one block per group of these, and -/// [`sub_pick_name`] names the pick out of the same answer -- so what a heading -/// says and what a row a person clicked says cannot disagree. -#[derive(Debug, PartialEq)] -struct SubGroup { - /// What the group is called: the file without its extension, which is what - /// a person named the film even when the subtitles came out of a remux. - name: String, - /// What the swatch is asked by ([`file_tint`]) -- the file, so a subtitle - /// row and the media rows of the same file wear one colour. `None` from - /// that lookup for a standalone `.srt`, which is nobody's stream. - path: PathBuf, - rows: Vec, -} - -/// One subtitle track, as a row shows it. -#[derive(Debug, PartialEq)] -struct SubRow { - /// Which track of the session's list this row is: the *flat* index into the - /// add-order Vec `PlaybackSession::subtitles` hands back, which is what a - /// click sets `sub_track` to and what a save writes into the `.edith`. - /// Grouping moves rows around on screen and never touches this number. - track: usize, - /// Which of *this file's* tracks it is, counted from 1 -- the numbering - /// [`row_name`] gives audio streams, for the same reason: two tracks off one - /// remux that both say "eng" are told apart by nothing else. - number: usize, - label: String, - /// The row's second line ([`subtitle_detail`]). - detail: String, - /// Why it cannot be shown, for a track that cannot: the only thing that - /// greys a row out. Listed all the same -- a picker that hides them is a - /// picker that lies. - refused: Option, - /// Pictures rather than lines ([`engine::subtitle::SubtitleTrack::bitmap`]). - bitmap: bool, -} - -/// What a subtitle row is called, off the two fields the container really -/// stated rather than out of the flattened -/// [`label`](engine::subtitle::SubtitleTrack::label). The pair is what an export -/// writes (`TRACK_LANGUAGE` and `TRACK_NAME` are two fields), and reading the -/// display string back apart is the very heuristic that sent every French track -/// out as English: `lang_human` on a whole "und — Signs" matches nothing and -/// names a language nobody speaks. -/// -/// The three shapes a track arrives in, all three of them real: a standalone -/// file states no language and is its own name, an embedded one states a -/// language and sometimes a title beside it, and a refused one states neither -/// and keeps the label it was refused under (`SubtitleTrack::refused`). -fn sub_title(sub: &engine::subtitle::SubtitleTrack) -> String { - match (sub.language.as_str(), sub.name.as_str()) { - ("", "") => sub.label.clone(), - ("", name) => name.to_string(), - // A track whose only name is the tag for "nobody said" says that in - // words rather than showing the tag itself. - (lang, "") => lang_human(lang).to_string(), - // ...and one that says "nobody said" *and* gives a title is the title: - // "unknown language — Signs" pads it with a word the file never said. - ("und", name) => name.to_string(), - (lang, name) => format!("{lang} — {name}"), - } -} - -/// The subtitle list as rows under the file each came out of: one group per -/// distinct path, in the order the files first appear, and each file's tracks -/// in the order they were added. Two remuxes' tracks arriving interleaved -- -/// which is what importing a second film does -- still read as two films. -fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec { - let mut groups: Vec = Vec::new(); - for (track, sub) in tracks.iter().enumerate() { - let group = match groups.iter().position(|g| g.path == sub.path) { - Some(i) => &mut groups[i], - None => { - groups.push(SubGroup { - name: sub - .path - .file_stem() - .map_or_else(|| file_name(&sub.path), |s| s.to_string_lossy().into()), - path: sub.path.clone(), - rows: Vec::new(), - }); - groups.last_mut().expect("just pushed") - } - }; - group.rows.push(SubRow { - track, - number: group.rows.len() + 1, - label: sub_title(sub), - detail: subtitle_detail(sub), - refused: sub.refused.clone(), - bitmap: sub.is_bitmap(), - }); - } - groups -} - -/// How the picked track is named wherever the pick is echoed -- the strip -/// header, the section heading, the toggle's own notice. What the track is -/// *and* which file it came out of: two remuxes each carrying an "eng" track -/// give the same word twice, and the file is the only thing that tells them -/// apart. A file that gave several of them numbers them within itself, the way -/// [`row_name`] numbers audio streams, since "eng" twice off one remux is the -/// same problem one file down. -/// -/// Goes through [`subtitle_rows`], so the name a header says and the row a -/// person clicked cannot disagree -- and the label is humanised there, so an -/// "und" track is named in words here without being passed through -/// [`lang_human`] twice. -/// -/// `None` for an index no track answers to, which is the silence -/// [`Player::subtitle_track`] gives at the same moment. -/// Where the picked subtitle row lands once `removed` has been taken off a list -/// that is `left` long afterwards. The pick follows the list: the same *track* -/// while it is still there -- every index past the one that went moves down -/// ([`engine::Project::remove_subtitles`]) -- the row that slid into the empty -/// place when the picked one is what went, and the last row when that was the -/// last. Zero on an emptied list, which is the index the section is not drawn at -/// all. -/// -/// Its own function because the pick is what the overlay draws: left where it -/// was it would name a different track, and the plate over the picture would -/// change language on its own the moment a row above it went. What an export -/// writes is *not* this pick and cannot be desynced by a removal -- it is worked -/// out from the cues on the timeline each time ([`Player::export_subs`]). -fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) -> usize { - let picked = match removed < picked { - true => picked - 1, - false => picked, - }; - picked.min(left.saturating_sub(1)) -} - -fn sub_pick_name(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option { - subtitle_rows(tracks).into_iter().find_map(|group| { - let row = group.rows.iter().find(|row| row.track == track)?; - let track = match group.rows.len() > 1 { - false => row.label.clone(), - true => format!("{} {}", row.label, row.number), - }; - // A standalone `.srt` is already named after its own file: "sub.srt — - // sub" says the one thing twice, and the film is only worth naming - // where it is not in the label yet. - Some(match row.label.starts_with(&group.name) { - true => track, - false => format!("{track} — {}", group.name), - }) - }) -} - -/// Where a cue is drawn on the bed: left edge and width in pixels, through the -/// same [`Scale`] every clip box goes through -- so a cue and the take it is -/// spoken over line up at every zoom, which is the only reason the strip is -/// worth drawing. Microseconds are the cue's unit and seconds are the scale's, -/// and this is the one place they meet. -/// -/// Never narrower than [`SUB_CUE_MIN_W`]: zoomed out, a one-second cue is a -/// fraction of a pixel, and a mark that rounds away reads as a track with -/// nothing in it. -fn cue_box(scale: Scale, cue: &engine::subtitle::Cue) -> (f32, f32) { - let (start, end) = (cue.start_us as f64 / 1e6, cue.end_us as f64 / 1e6); - ( - scale.px_at(start), - scale.width_px(end - start).max(SUB_CUE_MIN_W), - ) -} - -/// Which cues of a track are on screen at `at` seconds. Half-open, as the cue -/// itself is: one that ends exactly where the next begins hands over rather than -/// overlapping it for a frame, and several that genuinely overlap all come back -/// -- a sign and a line of dialogue are two cues at one moment. -fn cues_at(cues: &[engine::subtitle::Cue], at: f64) -> Vec<&engine::subtitle::Cue> { - let us = (at * 1e6) as i64; - cues.iter() - .filter(|cue| cue.start_us <= us && us < cue.end_us) - .collect() -} - -/// The sources a repaint has not asked about yet. A key that is already there -/// means "asked", whatever state it is in, which is what stops a decode already -/// running from being started again by the next of sixty repaints a second. -fn unseen_sources( - sources: &[Source], - waves: &HashMap<(PathBuf, usize), Wave>, -) -> Vec<(PathBuf, usize)> { - sources - .iter() - .map(|s| (s.path.clone(), s.audio_stream)) - .filter(|key| !waves.contains_key(key)) - .collect() -} - -/// The same, for the per-file caches: one entry per *file*, however many of its -/// streams the timeline plays. Generic in the value, because the stream probe -/// and the still's own size are both asked once per file and answered by -/// presence in a map. -fn unseen_paths(sources: &[Source], seen: &HashMap) -> Vec { - let mut out: Vec = Vec::new(); - for s in sources { - if !seen.contains_key(&s.path) && !out.contains(&s.path) { - out.push(s.path.clone()); - } - } - out -} - -/// Which timeline frame the playhead is on, by the rule the engine's own edits -/// use (playback.rs `secs_to_frame`): the frame that has started, with the -/// epsilon that keeps a clock sitting exactly on a boundary from reading as the -/// frame before it. Only ever a hint here -- what an edit does is still the -/// engine's answer, taken from the same seconds. -fn frame_at(secs: f64, fps: f64) -> u32 { - (secs * fps + 1e-6).floor().max(0.) as u32 -} - -/// Where a frequency sits across the graph, 0..1. Log, because an octave is an -/// octave whether it is 40 Hz wide or 10 kHz wide -- a linear axis would spend -/// three quarters of the card on the top two octaves and squeeze the bass, the -/// half of the range people actually reach for, into nothing. -fn eq_x(freq_hz: f32) -> f32 { - let span = (EQ_FREQ_HIGH / EQ_FREQ_LOW).log10(); - ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.) -} - -/// The frequency at a fraction across the graph -- [`eq_x`] backwards, which is -/// how a drag and the curve's own sample points read one. Clamped to the axis -/// either way, so a pointer that leaves the box stops at 20 Hz or 20 kHz. -fn eq_freq(along: f32) -> f32 { - EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along.clamp(0., 1.)) -} - -/// The band an "add" makes: a flat peak half way -- in octaves, which is what -/// the log axis draws -- between the picked band and whatever sits above it, so -/// a new band lands in the gap on screen rather than on top of its neighbour. -/// Above the topmost band the gap is the rest of the axis. -fn inserted_band(bands: &[Band], after: usize) -> Band { - let below = bands.get(after).map_or(1000., |b| b.freq_hz); - let above = bands - .iter() - .map(|b| b.freq_hz) - .filter(|f| *f > below) - .min_by(f32::total_cmp) - .unwrap_or(EQ_FREQ_HIGH); - Band { - freq_hz: (below * above).sqrt().clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH), - gain_db: 0., - // A shade narrower than the flat-shelf 0.707 the defaults use: a band - // someone asked for is a band they mean to aim, and a wide one aimed at - // 300 Hz is really a band at everything. - q: 1., - kind: BandKind::Peak, - } -} - -/// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle, -/// so a cut reads as a dip below the line it is a cut from. The inverse of -/// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a -/// curve loaded from a file with a gain past the card's limit paints on the -/// edge of the box rather than outside it. -fn eq_y(gain_db: f32) -> f32 { - 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. -} - -/// A frequency as the card writes it. Two decimals of a kHz at most, with the -/// zeroes trimmed, so "1 kHz" stays "1 kHz" and a band nudged off it reads as -/// 1.12 kHz rather than as the same "1 kHz" it was before the keystroke -- a -/// number that does not move under an edit is worse than no number. -fn eq_freq_label(freq_hz: f32) -> String { - if freq_hz < 1000. { - return format!("{freq_hz:.0} Hz"); - } - let khz = format!("{:.2}", freq_hz / 1000.); - let khz = khz.trim_end_matches('0').trim_end_matches('.'); - format!("{khz} kHz") -} - -/// What a band row calls itself: the corner or centre frequency, and for a -/// shelf the fact that it tilts everything past it -- which is the difference -/// between "12 kHz" moving the last octave and moving one band inside it. -fn band_label(band: &Band) -> String { - let freq = eq_freq_label(band.freq_hz); - match band.kind { - BandKind::LowShelf => format!("{freq} low shelf"), - BandKind::HighShelf => format!("{freq} high shelf"), - BandKind::Peak => freq, - } -} - -/// Whether an action can be asked for, and what to say when it cannot. Two -/// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at -/// -- an audio clip has no picture, so a grade is not a thing that exists for -/// it, whatever the editor does next -- and `No` is about the state of this -/// moment, which the next click of the playhead can change. The clip menu -/// leaves the class refusals *out* and dims the state ones ([`Enable::listed`]); -/// the actions card, which is the whole registry laid out, dims both with their -/// reason -- an action missing from the one surface that lists everything would -/// read as an action that does not exist. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Enable { - Yes, - No(&'static str), - Hidden(&'static str), -} - -impl Enable { - /// Whether the row takes a click. - fn yes(self) -> bool { - self == Enable::Yes - } - - /// Whether a menu *about this clip* draws the row at all: a class refusal - /// is a thing that does not exist for what was clicked, and a row nothing - /// the user does could ever light is noise between the ones they came for. - fn listed(self) -> bool { - !matches!(self, Enable::Hidden(_)) - } - - /// What the row says instead of its stroke, if it says anything. - fn why(self) -> Option<&'static str> { - match self { - Enable::Yes => None, - Enable::No(why) | Enable::Hidden(why) => Some(why), - } - } -} - -/// What an enablement question is asked *about*: the clip in question, if there -/// is one, and the little of the editor's state the answers need. Handed in -/// rather than read off the player, so [`enable`] is a pure function a test can -/// ask about a clip without building a window. -#[derive(Clone, Copy, Default)] -struct Ctx { - /// The clip the question is about -- the one a menu was opened on, or the - /// marked one. `None` means the question is about the editor as a whole, - /// and the clip-relative answers stand aside: those actions find their own - /// clip under the playhead and word their own refusal. - clip: Option<(Clip, Lane)>, - /// The clip plays a still ([`engine::is_image`]), which has no sound to - /// reach at all -- not the lane's business, because a still sits on a video - /// lane exactly like a take whose sound is one lane down. - image: bool, - playhead: u32, - /// A timeline is open. - timeline: bool, - /// Something has been copied. - clipboard: bool, - /// This timeline has at least one subtitle track: a toggle with nothing to - /// show is a switch that does nothing, and it says so rather than flipping. - subtitles: bool, - /// There is something on the lanes to play. A transport with nothing under - /// it is the one refusal that is about the timeline's contents rather than - /// about a clip. - playable: bool, - exporting: bool, -} - -/// Whether `action` can be asked for, on `ctx`. One arm per action and nothing -/// else in the editor asks the question: the clip menu dims a row with this, -/// the actions card dims a row with this, and the two can never come to -/// disagree about what an action needs -- exactly the reason [`Player::act`] is -/// one table too. -fn enable(action: ActionId, ctx: Ctx) -> Enable { - // The one action that is about the editor rather than about the timeline: - // the list of what everything does, and where a key is changed. An empty - // window has no clips and still has keys -- so this answers ahead of the - // timeline question, and only an export shuts it (a waiting row would - // swallow the escape the progress line promises cancels the export). - // The window's own colours: there is always a window, and repainting it - // touches no timeline -- so this one is live even while an export is - // reading one, which is the only state that dims the list above. - if action == ActionId::Theme { - return Enable::Yes; - } - if action == ActionId::ShowActions { - return match ctx.exporting { - true => Enable::No("an export is running"), - false => Enable::Yes, - }; - } - // The four that are about the *editor* and its monitoring rather than - // about the edit list: they work with nothing open, the keyboard has - // always fired them there, and so their buttons are live there too. - if matches!( - action, - ActionId::ToggleSnap | ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown - ) { - return match ctx.exporting { - true => Enable::No("an export is running"), - false => Enable::Yes, - }; - } - if !ctx.timeline { - return Enable::No("no timeline open"); - } - // An export is reading the edit list every other action would change, which - // is the rule the key handler already follows. - if ctx.exporting { - return match action { - ActionId::CancelExport => Enable::Yes, - _ => Enable::No("an export is running"), - }; - } - match action { - // -- class: what kind of thing the action is about. The equalizer - // filters samples, and a video clip has none of its own here: the sound - // is the audio lane's, clip for clip. - ActionId::Equalizer => match ctx.clip { - Some((_, lane)) if lane.kind != LaneKind::Audio => Enable::Hidden("this clip is picture"), - _ => Enable::Yes, - }, - // A grade is a picture setting and an audio clip has no picture. A fit - // policy is a picture setting for the same reason. - ActionId::Color | ActionId::Fit => match ctx.clip { - Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"), - _ => Enable::Yes, - }, - // The scan reads samples, and a still has none -- ever, unlike a video - // clip whose sound may be one lane down or simply silent. Exactly what - // `unscannable` says after the fact, said before the row is drawn so - // there is no row left to click. - ActionId::Silence if ctx.image => Enable::Hidden("this clip is a still"), - // -- state: true of this clip now, and the next playhead click or the - // next selection changes the answer. Splits this clip only from inside - // it: at either edge there is nothing to split off -- and, on a speeded - // clip, only at a frame its own rate can address, which is the same - // question `splittable` asks. - ActionId::Cut => match ctx.clip { - Some((clip, _)) if !(clip.start < ctx.playhead && ctx.playhead < clip.end()) => { - Enable::No("only from inside a clip") - } - // Inside it, and still not a cut: a slowed clip shows one frame of - // the file for several frames of the timeline, and only the first of - // those is a frame the file has ([`Speed::split_at`]). Cutting - // between two showings of one frame would leave halves whose lengths - // no longer add up, so it is refused -- and it says *that* rather - // than repeating "inside a clip" at a playhead that plainly is. - Some((clip, _)) - if clip - .speed - .split_at(clip.len(), ctx.playhead - clip.start) - .is_none() => - { - Enable::No("this speed holds one frame here — step to the next") - } - _ => Enable::Yes, - }, - // Rejoins whatever meets at the playhead, so it can mean something only - // at an edge of this clip. Whether those two halves were ever one take - // is the engine's question, and it words that refusal itself. - ActionId::Regroup => match ctx.clip { - Some((clip, _)) if ctx.playhead != clip.start && ctx.playhead != clip.end() => { - Enable::No("only where two clips meet") - } - _ => Enable::Yes, - }, - // Nothing to take apart in a clip that names no group at all. Whether - // the group it names still has another half is the engine's question, - // like the regroup above. - ActionId::Detach => match ctx.clip { - Some((clip, _)) if clip.link.is_none() => Enable::No("this clip is not grouped"), - _ => Enable::Yes, - }, - // The three that act on the marked clip and on nothing else: with none - // marked they would silently do nothing, which is what the Delete - // button's own dimming has always said. - ActionId::Copy | ActionId::Delete | ActionId::Lift if ctx.clip.is_none() => { - Enable::No("click a clip first") - } - ActionId::Paste if !ctx.clipboard => Enable::No("nothing copied yet"), - // Nothing to draw over the picture, so nothing to switch off: the - // library says how subtitles arrive, and this row would flip a state - // with no visible half either way. - // ...and nothing to take off the timeline either, for the same reason: - // the row would name a track that is not there. - ActionId::ToggleSubtitles | ActionId::RemoveSubtitleTrack if !ctx.subtitles => { - Enable::No("no subtitles yet") - } - // Not `No`: with nothing running there is no export for this to be - // about at all, which is what keeps `esc` -- the same key -- a quiet - // way out of a card rather than a line about exports. - ActionId::CancelExport => Enable::Hidden("nothing is exporting"), - // A clock started against an empty timeline is a clock counting - // nothing: the transport says so by being dim, which is what its own - // ad-hoc boolean used to say before the oracle knew the question. - ActionId::Play if !ctx.playable => Enable::No("put a clip on a lane first"), - // A rate applies to a clip of either kind and to its whole group, so - // there is no lane it means nothing on, and the engine words the one - // refusal there is (no room). Everything else is the editor's own and - // needs nothing but a timeline. - _ => Enable::Yes, - } -} - -/// The rows a clip menu draws, for the clip it was opened on: the registry -/// filtered by the one availability oracle, and the *only* way that menu is -/// built. An action that means nothing for what was right-clicked -- a grade on -/// a waveform, an equalizer on a picture -- is not a row at all, so a future -/// action cannot appear where it does not apply by being added to -/// [`MENU_ITEMS`] alone. -fn menu_items(ctx: Ctx) -> Vec { - MENU_ITEMS - .into_iter() - .filter(|&action| enable(action, ctx).listed()) - .collect() -} - -/// What a library row's items are asked *about*: the file that was -/// right-clicked and the little of the editor's state the answers need. The -/// library's [`Ctx`], handed in for the same reason. -#[derive(Clone, Copy, Default)] -struct RowCtx { - /// A timeline to put it on. - timeline: bool, - exporting: bool, - /// This row can join *this* timeline: what greys it in the list, and what - /// the engine would otherwise refuse the Add with after the click. - usable: bool, - /// How many clips play this exact row -- a source with any is one the - /// engine will not take out of the list. - placed: usize, -} - -/// Whether a library row's item can be asked for. The library's half of -/// [`enable`], and the same rule: one table, no second policy in the render. -fn row_enable(item: RowItem, ctx: RowCtx) -> Enable { - match item { - // The two that change the timeline, so an export reading it stops them - // both -- the key handler's rule, applied to a menu. - RowItem::Add | RowItem::Remove if ctx.exporting => Enable::No("an export is running"), - RowItem::Add | RowItem::Remove if !ctx.timeline => Enable::No("no timeline open"), - // Dimmed and saying why rather than clicked and refused afterwards: the - // row's own grey already says the file cannot join this timeline. - RowItem::Add if !ctx.usable => Enable::No("it cannot join this one"), - RowItem::Remove if ctx.placed > 0 => Enable::No("clips play it"), - // Neither of these touches the timeline: a file can be found on disk and - // described whatever the editor is doing, with no timeline at all. - _ => Enable::Yes, - } -} - -/// The rows a library menu draws, for the row it was opened on -- the clip -/// menu's [`menu_items`] on the other panel, and the only way that menu is -/// built. -fn row_items(ctx: RowCtx) -> Vec { - ROW_ITEMS - .into_iter() - .filter(|&item| row_enable(item, ctx).listed()) - .collect() -} - -/// How tall a menu's list may draw: the whole of it where the window has room, -/// and what the window has where it has not -- only then does the list scroll. -/// A cap fixed at twelve rows put the last items behind a scroll on a window -/// with room to spare, which reads as a menu cut off by the bottom edge. -fn menu_rows_h(rows: usize, viewport: Size) -> f32 { - let room = f32::from(viewport.height) - MENU_PAD * 2.; - (rows as f32 * MENU_ROW_H).min(room.max(MENU_ROW_H)) -} - -/// Where the menu actually hangs: at the pointer, pulled back inside the window -/// when it would not fit -- an item off the bottom edge is an item nobody can -/// click. Never negative, so a window smaller than the menu loses the bottom of -/// it rather than the top, where the items are. -fn menu_at(at: Point, viewport: Size, height: f32) -> (f32, f32) { - let fit = |v: f32, size: f32, room: f32| v.min(room - size).max(0.); - ( - fit(f32::from(at.x), MENU_W, f32::from(viewport.width)), - fit(f32::from(at.y), height, f32::from(viewport.height)), - ) -} - -/// Whether the Add button does anything: a row picked, a timeline to put it on, -/// and no export reading that timeline. A button that would do nothing is dimmed -/// and takes no click, like every other one here. -fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -> bool { - picked.is_some() && timeline && !exporting -} - -/// What is left on the clipboard after the library row at `removed` was taken -/// out. A copied clip names its file by *index* into the source list -/// (`engine::Clip::source`) and a removal renumbers that list -/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste -/// **a different file** -- the next one along -- over the range it was copied -/// from. -/// -/// The clip's own file gone means there is nothing to paste: `None`, and the -/// next paste says the clipboard is empty rather than putting some other take -/// down. Every index past it moves down by one, exactly as the lanes' clips do. -fn clipboard_after_remove(clip: Option, removed: usize) -> Option { - let mut clip = clip?; - match clip.source.cmp(&removed) { - std::cmp::Ordering::Equal => None, - std::cmp::Ordering::Greater => { - clip.source -= 1; - Some(clip) - } - std::cmp::Ordering::Less => Some(clip), - } -} - -/// One library row: a file and one of its audio streams. Plain data, planned -/// before anything is drawn -- which rows exist at all is the branchy part. -#[derive(Debug, PartialEq)] -struct Row { - path: PathBuf, - stream: usize, - /// The file, plus which stream this is when the file has several. - name: String, - /// What the stream is, or blank for a file with a single one. - detail: String, - /// Why it cannot be put on this timeline, for a row that cannot: shown in - /// place of the length and the only thing that greys a row out. - unusable: Option, - /// Frames of the *file*, for the length line. - frames: u32, - /// Index into `SOURCE_TINTS`, shared by every stream of one file: the - /// swatch says which file, and the lanes tint their clips the same way. - tint: usize, -} - -/// Every row the library shows: one per source entry, plus one for each further -/// audio stream those files have that no clip plays yet -- a remux with a track -/// per language lists them all, the ones this engine cannot use greyed out -/// rather than hidden. Streams a file has not been probed for yet simply are -/// not there; the row for what *is* on the timeline is always there. -/// -/// `timeline_audio` is the rate and layout of source 0's stream, which every -/// other source must match: one output device and one copied AAC track for the -/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown, -/// and then nothing is greyed for it -- the engine still refuses. -fn library_rows( - sources: &[Source], - streams: &HashMap>, - decoders: &HashMap, Backend)>>, - timeline_audio: Option<(u32, u16)>, - frames: impl Fn(&Path) -> u32, -) -> Vec { - let mut rows = Vec::new(); - for (i, source) in sources.iter().enumerate() { - let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice); - let info = of_file.iter().find(|s| s.index == source.audio_stream); - let tint = sources - .iter() - .position(|s| s.path == source.path) - .expect("a source finds itself"); - rows.push(Row { - path: source.path.clone(), - stream: source.audio_stream, - name: row_name(&source.path, source.audio_stream, of_file.len() > 1), - // The decoder first: it is the same for every row of a file and - // it is what a person opening the panel is asking about. The - // stream half only where there is a choice to describe -- a file - // with one audio track is the row it has always been, name and - // length, and the length is what would be squeezed out at the - // panel's least width. - detail: join_detail( - &decoders - .get(&source.path) - .copied() - .flatten() - .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)), - &info - .filter(|_| of_file.len() > 1) - .map_or_else(String::new, stream_detail), - ), - // A stream already on the timeline is playing: whatever a probe - // would say about it now, it is usable by demonstration. - unusable: None, - frames: frames(&source.path), - tint, - }); - // The file's other streams, listed once, right after the last entry - // that names the file -- so a file's rows sit together. - if sources[i + 1..].iter().any(|s| s.path == source.path) { - continue; - } - for info in of_file { - if sources - .iter() - .any(|s| s.path == source.path && s.audio_stream == info.index) - { - continue; // it has a row of its own above - } - rows.push(Row { - path: source.path.clone(), - stream: info.index, - name: row_name(&source.path, info.index, true), - detail: stream_detail(info), - unusable: unusable(info, timeline_audio), - frames: frames(&source.path), - tint, - }); - } - } - rows -} - -/// The row's second line: what the stream is and then either how long it is or -/// why it cannot be used, with the separator only where both halves exist (a -/// single-stream file says nothing about its stream). -fn join_detail(detail: &str, tail: &str) -> String { - match (detail.is_empty(), tail.is_empty()) { - (true, _) => tail.to_string(), - (false, true) => detail.to_string(), - (false, false) => format!("{detail} · {tail}"), - } -} - -/// How a source's decoder reads: the codec and which seat has it, or the seat -/// alone for a still, which has no coded stream to name. The one place either -/// answer is spelled, so a row, a transport line and a card cannot disagree. -fn decode_label(codec: Option, backend: Backend) -> String { - match codec { - Some(codec) => format!("{} · {}", codec.name(), backend.label()), - None => backend.label().to_string(), - } -} - -/// How a row names its file: the file alone when it has one audio stream or -/// none, and the file plus which stream this row is when it has several -- -/// counted from 1, the way a player numbers tracks. -fn row_name(path: &Path, stream: usize, several: bool) -> String { - match several { - false => file_name(path), - true => format!("{} [audio {}]", file_name(path), stream + 1), - } -} - -/// What a stream is, for the row's second line: the language if the file says -/// one, then rate and layout. A field the header does not give is left out -/// rather than shown as a zero -- a stream we cannot parse says nothing about -/// itself, and saying "0 Hz" would be saying something. -fn stream_detail(info: &StreamInfo) -> String { - let mut parts: Vec = Vec::new(); - if let Some(lang) = &info.lang { - parts.push(lang_human(lang).to_string()); - } - if info.sample_rate > 0 { - parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.)); - } - parts.extend(layout(info.channels)); - parts.join(" ") -} - -/// What a file is coded at, for the properties cards: the rate of the whole -/// file, then each track's own beside it. A component the container does not -/// state is left out for `stream_detail`'s reason -- a fabricated `0` would be -/// saying something -- and a file that states none of the three says so rather -/// than showing an empty row. `None` is the probe still running, which is a -/// real wait: it walks a Matroska's clusters. -/// -/// The whole file's rate is the one that carries the unit and no word: named -/// "total" as well, the line loses its last component to `MENU_W`'s truncation -/// on an ordinary 1080p file -- and a rate cut to "0.13 soun" is a number the -/// card did not give. -/// -/// `tracks` is how many sound tracks the file has, from `probe_streams`. The -/// rate is the one track this engine plays -- the first, neither their sum nor -/// the biggest -- so a file with more says which of how many: a bare "0.16 -/// sound" on a file whose name says AC3.5.1 names a track without saying it is -/// one of two, and the card's Audio row above it may be describing the other. -/// -/// The marker costs the word "sound", the way the whole file's rate costs the -/// word "total" above, and for the same reason. Measured in Noto Sans 11 px -/// against the 186 px this value has beside a "Bitrate" label: "0.16 sound 1/2" -/// wants 192 px on a 4.7 Mb/s film and 205 on the 39.8 Mb/s remux -- -/// the marker is what gets cut, which is the one part of the line that is new. -/// Nothing that keeps the word fits the wide files -- the shortest, "snd 1/2", -/// still wants 188 px on that remux -- so the word goes and the number keeps -/// the answer: "0.16 1 of 2" wants 172 px, and 185 on the widest line a -/// library can produce (the 10.9 Mb/s three-track film). -fn bitrate_detail(rate: Option, tracks: usize) -> String { - let Some(rate) = rate else { - return "…".to_string(); - }; - let (per, unit) = rate_scale(rate); - let mut parts: Vec = Vec::new(); - if let Some(total) = rate.total { - // One unit for the three numbers, carried once, on the whole file's - // rate: the components are read against it. - parts.push(format!("{} {unit}", scaled(total, per))); - } - if let Some(video) = rate.video { - parts.push(format!("{} video", scaled(video, per))); - } - if let Some(audio) = rate.audio { - parts.push(match tracks > 1 { - true => format!("{} 1 of {tracks}", scaled(audio, per)), - false => format!("{} sound", scaled(audio, per)), - }); - } - match parts.is_empty() { - true => "not stated".to_string(), - false => parts.join(" · "), - } -} - -/// Below this a megabit's two decimals cannot state a rate, so the line is read -/// in kilobits instead. -const MB_FLOOR: u64 = 10_000; - -/// What the line counts in, and the name of it: the largest unit that can state -/// its *smallest* component, because that is the one a bigger unit rounds away. -/// Megabits for everything a real file produces -- the smallest component over -/// an 18-file sweep of a library was 0.13 Mb/s -- kilobits for the sub-32x32 -/// encodes below that. -/// -/// corner-cut: one unit for the whole line, so a file mixing a multi-megabit -/// picture with a sub-10 kb/s sound track prints the picture as four or five -/// digits of kilobits and loses the line's tail to `MENU_W`. No such file -/// exists in a library, and both units at once ("0.01 Mb/s · 1.2 kb/s video · -/// 9.5 kb/s sound") wants 215 px of the 186 the row has. Upgrade path is a -/// suffix per component ("1.2k video"), which measures 177 px. -fn rate_scale(rate: MediaBitrate) -> (f64, &'static str) { - match [rate.total, rate.video, rate.audio] - .into_iter() - .flatten() - .min() - { - // A rate this small is a broken header rather than a track, but it is - // still a number the file stated, and bits state it. - Some(bits) if bits < 10 => (1., "b/s"), - Some(bits) if bits < MB_FLOOR => (1_000., "kb/s"), - _ => (1_000_000., "Mb/s"), - } -} - -/// A rate in the line's unit as a person reads it: one decimal above 1 of it, -/// two below -- a 128 kbps song rounded to one decimal is "0.1", which reads as -/// a guess where "0.13" reads as a measurement. -/// -/// Never `0.00`: [`rate_scale`] picks the unit off the smallest component, so -/// two decimals always reach it. Every rate that gets here is one the container -/// really stated (the probe leaves out what it does not state, it never zeroes -/// it), and a "0.00 sound" would be this card saying a track that plays is -/// silent. -fn scaled(bits: u64, per: f64) -> String { - let n = bits as f64 / per; - match n >= 1. { - true => format!("{n:.1}"), - false => format!("{n:.2}"), - } -} - -/// A language tag as a person reads it. Everything a file writes is passed -/// through untouched bar the one tag that is not a language: "und" is what a -/// muxer writes when nobody said, and a row showing it verbatim names a -/// language nobody speaks. -fn lang_human(lang: &str) -> &str { - match lang { - "und" => "unknown language", - lang => lang, - } -} - -fn layout(channels: u16) -> Option { - match channels { - 0 => None, - 1 => Some("mono".to_string()), - 2 => Some("stereo".to_string()), - n => Some(format!("{n} ch")), - } -} - -/// Why a stream cannot go on this timeline, or `None` if it can. Both answers -/// are shown: a stream nothing can be done with is listed greyed with the -/// reason, never dropped from the list -- a file has the tracks it has, and a -/// picker that hides them is a picker that lies. -fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option { - if !info.decodable { - // AAC and AC-3 name themselves (`StreamInfo::codec`, which reads the - // stsd fourcc by hand); anything else mp4 0.14 does not parse has no - // name to give, and a row with no name still says why it is greyed. - return Some(match info.codec.as_str() { - "unknown" => "unsupported codec".to_string(), - codec => format!("{codec} is not supported"), - }); - } - // The **layout** and not the rate, which is what the engine's own gate now - // asks (`PlaybackSession::import`): a stream written at another sample rate - // is resampled onto the timeline's at the decoder's door, so greying its row - // would be this picker refusing what the timeline accepts. - let (_, channels) = timeline_audio?; - (info.channels != channels).then(|| { - format!( - "the timeline is {}", - layout(channels).unwrap_or_else(|| "silent".to_string()) - ) - }) -} - -/// How wide the equalizer card is drawn in a window this wide: all of it bar a -/// margin, up to [`EQ_W_MAX`]. The card is a graph, and a graph of twenty -/// thousand hertz on 320 px spends four pixels on the octave below middle C -- -/// so it takes the room a big window has and stays inside a small one. Floored -/// at the other cards' width, which is the last size the rows still read at. -fn eq_card_w(window_w: f32) -> f32 { - (window_w - EQ_W_MARGIN).clamp(KEYS_W, EQ_W_MAX) -} - -/// What the media list is given of the window. A share of it, so a narrow -/// window gives the panel less rather than giving the picture nothing, floored -/// where a name stops being readable and capped at a third of the window -- -/// the picture is what the program is for and keeps the majority at every size. -fn library_w(window_w: f32) -> f32 { - (window_w * LIBRARY_FRAC) - .clamp(LIBRARY_MIN_W, LIBRARY_MAX_W) - .min(window_w / 3.) -} - -/// What is left of a library column this wide for a row's *words*: the panel's -/// padding on both sides, the tint bar, the gap after it and the row's own right -/// inset. Every row in the column -- media and subtitle -- is built to this -/// shape, so one number answers for both. -fn row_text_w(width: f32) -> f32 { - // 8 px of panel padding each side, then the bar, the gap after it and the - // row's own right inset -- the numbers the rows are built with. - width - 16. - SWATCH_W - 6. - 6. -} - -/// A name cut to what a column this wide can hold, out of the *middle*. Two -/// files off one release differ in their last characters and nowhere else -- -/// "…Episode 01" against "…02" -- so a name cut from the right is the same -/// name twice and the list stops naming anything. The width decides how much -/// survives, not a number of characters somebody guessed: a wider window spells -/// more of the file out, and the floor still keeps both ends. -/// -/// The element truncates for real; this only decides where what is lost comes -/// out of. -fn clip_middle(name: &str, width: f32) -> String { - let budget = ((width / LIST_CHAR_W) as usize).max(LIST_CLIP_MIN); - let chars: Vec = name.chars().collect(); - if chars.len() <= budget { - return name.to_string(); - } - // The gap costs a character, and what is left of the odd one goes to the - // tail: the tail is the half that tells two of them apart. - let head = (budget - 1) / 2; - let tail = budget - 1 - head; - format!( - "{}…{}", - chars[..head].iter().collect::(), - chars[chars.len() - tail..].iter().collect::() - ) -} - -/// Whether the subtitle list has the height to name each file over its tracks. -/// A header is worth its own height only where there are still tracks under it -/// to read: at the 640x360 floor the list is one row tall, and a header there -/// would name a film and show none of it -- so at the floor there are no -/// headers and the rows say which file they came from themselves. -/// -/// The window's height answers it on its own: the row above the picture and the -/// panel under it are fixed, so every pixel the window gains past the floor is a -/// pixel this column gains. -fn sub_headers_fit(viewport_h: f32) -> bool { - SUB_ROWS_AT_FLOOR + (viewport_h - 360.).max(0.) >= SUB_HEAD_H + 2. * ROW_H -} - -/// What the window is called: the program, and what is open in it. The name is -/// what the header shows, so an empty window says the program alone rather than -/// "no file open — edith". -fn window_title(name: &str) -> String { - if name == NO_FILE { - "edith".to_string() - } else { - format!("{name} — edith") - } -} - -/// The tint a clip from source `n` wears. Cycled rather than extended: past the -/// palette two sources share a colour, which is a smaller lie than a fifth tint -/// bright enough to leave the family. -fn source_tint(source: usize) -> u32 { - SOURCE_TINTS()[source % SOURCE_TINTS().len()] -} - -/// The tint of a *file*, which is what a library row is named by: the first -/// source entry naming it, since two audio streams of one file are two sources -/// and one colour. -/// -/// `None` for a path no source names -- a standalone `.srt` is on nobody's -/// timeline, and painting it with the first file's colour would say it came out -/// of that file. No swatch says what is true: it belongs to itself. -fn file_tint(sources: &[Source], path: &Path) -> Option { - sources - .iter() - .position(|s| s.path == path) - .or_else(|| { - // A source entry is stored symlink-resolved (`Source::new`) and a - // path from anywhere else -- a subtitle track, a file being - // dragged -- is stored as it was spelled. `edith assets/film.mkv` - // is one file under two spellings, and matching by spelling alone - // said the film had no colour. Only asked when the spellings - // differ, so the common paint costs no syscall. - let path = std::fs::canonicalize(path).ok()?; - sources.iter().position(|s| s.path == path) - }) - .map(source_tint) -} - -/// What the export card offers, top to bottom. Bitrate is the only thing the -/// encoder actually takes: the codec and the container are what this program -/// can write and nothing else, so the card states them rather than offering -/// them. -#[derive(Clone, Copy, PartialEq, Debug)] -enum Quality { - Auto, - Low, - Medium, - High, - Custom, -} - -impl Quality { - const ALL: [Quality; 5] = [ - Quality::Auto, - Quality::Low, - Quality::Medium, - Quality::High, - Quality::Custom, - ]; - - fn label(self) -> &'static str { - match self { - Quality::Auto => "Auto", - Quality::Low => "Low", - Quality::Medium => "Medium", - Quality::High => "High", - Quality::Custom => "Custom", - } - } - - /// The figure the row stands for, said in the units the row is chosen by. - fn detail(self, custom_mbps: u32) -> String { - match self { - Quality::Auto => "from the picture size and frame rate".to_string(), - Quality::Custom => { - format!("{custom_mbps} Mbps — wheel or ± steps, n types one, {MBPS_MIN}–{MBPS_MAX}") - } - other => format!( - "{} Mbps", - export_settings(other, 0, Format::Mp4, DEFAULT_AUDIO_KBPS) - .bitrate - .unwrap_or_default() - / 1_000_000 - ), - } - } -} - -/// The export card's format rows: the key that picks one, its name, and what it -/// writes -- or, where this program cannot write it, the reason it cannot. A -/// format with no entry at all would read as an oversight, and a menu of three -/// as a claim that nothing else exists -- so the refusals are rows too, dimmed -/// and unclickable. -/// -/// `None` is exactly that kind of row, and there are two left. MP3 stopped -/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL -/// `shine-rs` was the licence question, and it is not the only encoder any -/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an -/// encoder — an *intra-only* one, which the rows say rather than let a user -/// find out from the size of the file. VP9 is the one this program still only -/// *reads*: the plugin decodes it and there is no encoder for it here, so it is -/// a row for the reason the refusals are rows at all — a codec that opens but -/// never comes back out is exactly the gap a user would otherwise go looking -/// for. AAC is not a row at all: it is what both containers' sound *is*, never a -/// file of its own. -/// -/// A codec is one row, and the boxes it can be written into are the row's -/// containers: the same AV1 picture and the same AAC track go into a Matroska -/// file or into an mp4, and which one a user needs is about what has to play -/// the file, not about the encode. So the container is asked *once*, in a row -/// of its own, and only where there is more than one to ask about -- five -/// picture rows to read past were four of them saying the same codec twice. -const FORMATS: [(&[Format], &str, &str, &str); 8] = [ - ( - &[Format::Mp4], - "m", - "H.264", - "plays everywhere · AAC sound · MP4 only", - ), - ( - &[Format::Av1, Format::Av1Mp4], - "a", - "AV1", - "smallest file for the picture · AAC sound", - ), - ( - &[Format::Hevc, Format::HevcMp4], - "h", - "HEVC", - "intra-only, every frame a cut point — large files", - ), - (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"), - (&[Format::Flac], "f", "FLAC", "lossless — audio only"), - (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"), - ( - &[Format::Ogg], - "o", - "OGG", - "Vorbis (rusty_vorbis) — quality-coded, stereo", - ), - (&[], "", "VP9", "AV1 above replaces it"), -]; - -/// The codec row a key picks, landed in the container already chosen: pressing -/// `a` after an mp4 gives AV1 *in mp4*, because a box decided once is not a -/// question again. A letter of the row's own name, spelled out in the table -/// rather than taken from the initial (`MP4` and `MP3` share one). Never a -/// digit -- those are the bitrate field's. `None` for every other stroke, the rows -/// that cannot be picked included. -fn format_key(key: &str, current: Format) -> Option { - FORMATS - .into_iter() - .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key)) - .find_map(|(row, ..)| same_box(row, current)) -} - -/// The boxes one codec may be written into, in the order its container row -/// cycles them. Empty for a codec this program cannot write at all. -fn containers(format: Format) -> &'static [Format] { - FORMATS - .into_iter() - .map(|(row, ..)| row) - .find(|row| row.contains(&format)) - .unwrap_or(&[]) -} - -/// This row's format under the container `current` is already in, or the row's -/// first when it has no such box: an AV1 picked from a WAV lands in Matroska, -/// and picked from an mp4 stays in the mp4. -fn same_box(row: &[Format], current: Format) -> Option { - row.iter() - .copied() - .find(|f| f.ext() == current.ext()) - .or_else(|| row.first().copied()) -} - -/// The next box for the same codec, wrapping -- what the container row's key -/// does. The format itself for a codec with only one, so the stroke cannot -/// change what it is not offering. -fn next_container(format: Format) -> Format { - let row = containers(format); - let at = row.iter().position(|&f| f == format).unwrap_or(0); - row.get((at + 1) % row.len().max(1)) - .copied() - .unwrap_or(format) -} - -/// The next rate the Sound row offers, wrapping -- what its key does, and what -/// the row itself names so the stroke is never a guess. [`next_container`]'s -/// shape, for the same reason: one place decides what "next" means. -fn next_audio_kbps(kbps: u32) -> u32 { - let at = AUDIO_KBPS.iter().position(|&k| k == kbps).unwrap_or(0); - AUDIO_KBPS[(at + 1) % AUDIO_KBPS.len()] -} - -/// Why the quality rows say nothing about this format, or `None` where they -/// decide the picture. Only a picture encoder is given a bitrate here: the two -/// lossless audio formats have none to give and MP3 is written at one fixed -/// figure, so a live row over either would be a control that changes nothing. -fn bitrate_refusal(format: Format) -> Option<&'static str> { - match format { - Format::Wav | Format::Flac => Some("lossless audio — no bitrate to pick"), - Format::Mp3 => Some("sound only — its rate is the Sound row"), - // The guard is the question and not a list of names: an audio format - // added without a line of its own above would otherwise show live - // quality rows over a file that has no picture to spend a bitrate on. - // OGG is exactly that format -- and it wants this sentence rather than - // one of its own, because its *Sound* row already says the Vorbis half - // ("quality-coded — Vorbis holds no rate to pick") and two rows saying - // the same thing is one of them wasted. - _ if !format.has_video() => Some("sound only — no picture to spend a bitrate on"), - _ => None, - } -} - -/// What one of the colour card's own strokes does. Its keys are card-local -- -/// they mean nothing outside it -- so they are a table here rather than keymap -/// bindings, exactly as the export card's format initials are. Listed in -/// `keymap::FIXED` all the same, which is how the keys menu still says so. -enum ColorKey { - Close, - /// Steps down the four sliders, wrapping. - Band(usize), - /// Moves the picked slider, in [`COLOR_STEP`]s. - Nudge(f32), - Reset, -} - -/// Why the silence card has nothing to scan on that clip, in its own voice: the -/// lane and index the user picked, the file it is of, and which of the two -/// soundless things it is. One place, because a still and a silent video are -/// the same answer to the same question -- "a box with a larger size than it" -/// is what the *demuxer* would say about a png, and it is not an answer. -/// -/// Costs nothing: the scan reads a file and writes marks, so a refusal here -/// leaves the project (and its undo history) exactly where it was. -fn unscannable(lane: Lane, idx: usize, path: &Path) -> String { - let what = match engine::is_image(path) { - true => "is a picture", - false => "is silent", - }; - format!( - "{} clip {} has no audio to scan — {} {what}", - lane.label(), - idx + 1, - file_name(path) - ) -} - -/// The half of a take whose *sound* the silence card scans: a link is one span -/// on however many lanes, so a card opened on the picture opens on the sound it -/// is grouped with. That is the lane the waveform is drawn on, and so the lane -/// the marks have to land on to be read against it -- and the ranges agree, -/// because a group is one span. -/// -/// The clip itself for one already on an audio lane, for a detached picture, -/// and for a take whose sound is not on any lane: there is nothing better to -/// open on, and the refusal for a source with no audio at all is `scan`'s. -fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) { - if lane.kind == LaneKind::Audio { - return (lane, idx); - } - let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else { - return (lane, idx); - }; - session - .lanes() - .into_iter() - .filter(|l| l.kind == LaneKind::Audio) - .find_map(|l| { - session - .lane_clips(l) - .iter() - .position(|c| c.link == Some(link)) - .map(|i| (l, i)) - }) - .unwrap_or((lane, idx)) -} - -fn color_key(key: &str) -> Option { - Some(match key { - ESCAPE => ColorKey::Close, - "down" => ColorKey::Band(1), - "up" => ColorKey::Band(COLOR_BANDS.len() - 1), - "right" => ColorKey::Nudge(1.), - "left" => ColorKey::Nudge(-1.), - "r" => ColorKey::Reset, - _ => return None, - }) -} - -/// The band'th control of a grade, to read or to write. The order is -/// [`COLOR_BANDS`]', which is the order the card lists them in. -fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 { - match band { - 0 => &mut params.brightness, - 1 => &mut params.contrast, - 2 => &mut params.saturation, - _ => &mut params.tint, - } -} - -/// The line under the rows: what the picked format really writes, in the terms -/// a file is judged by afterwards. -/// The next policy round the cycle, in the order the action's label reads. -/// Every fit policy, in the order the list offers them -- which is the order -/// [`next_fit`] steps through them, pinned by the test below: a list and a -/// stroke that disagreed about what comes next would be two settings. -const FITS: [FitPolicy; 4] = [ - FitPolicy::Fit, - FitPolicy::Fill, - FitPolicy::Stretch, - FitPolicy::Center, -]; - -fn next_fit(fit: FitPolicy) -> FitPolicy { - match fit { - FitPolicy::Fit => FitPolicy::Fill, - FitPolicy::Fill => FitPolicy::Stretch, - FitPolicy::Stretch => FitPolicy::Center, - FitPolicy::Center => FitPolicy::Fit, - } -} - -/// What a person calls one, said as what it does to the picture. -fn fit_label(fit: FitPolicy) -> &'static str { - match fit { - FitPolicy::Fit => "fit (whole picture, bars)", - FitPolicy::Fill => "fill (cropped, no bars)", - FitPolicy::Stretch => "stretch (aspect broken)", - FitPolicy::Center => "centre (1:1, no resample)", - } -} - -/// Every project resolution on offer, largest first: [`RESOLUTIONS`] with the -/// media's own size cycled in at its place by size -- so a project already at a -/// listed size does not see it twice, and the media's own shape, whatever it is, -/// is always on the list. The one order both the stroke and the list use. -fn resolution_ladder(native: (u32, u32)) -> Vec<(u32, u32)> { - let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec(); - if !sizes.contains(&native) { - // By area, descending, like the list itself: the cycle then reads as one - // ladder rather than a list with a stray rung at the end. - let at = sizes - .iter() - .position(|&(w, h)| { - u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1) - }) - .unwrap_or(sizes.len()); - sizes.insert(at, native); - } - sizes -} - -/// The resolution list's rows: every rung of the ladder, the media's own said -/// so, and the one in force marked. A size is named by its height the way the -/// button that opens the list names it, with the full figure beside it. -fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec { - resolution_ladder(native) - .into_iter() - .map(|(w, h)| { - ( - Choice::Size(w, h), - format!("{h}p").into(), - match (w, h) == native { - // Short enough to sit beside the label inside `MENU_W`: - // the longer phrase lost its last word to the truncation. - true => format!("{w}x{h} · the media's own"), - false => format!("{w}x{h}"), - } - .into(), - (w, h) == current, - ) - }) - .collect() -} - -/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the -/// media's own cycled in at its place by speed, so a project already cut at a -/// listed rate does not see it twice and the media's own rate -- the one a -/// project moved off it has no other way back to -- is always there. -/// [`resolution_ladder`]'s rule, for the other setting the project has of its -/// own. -fn frame_rate_ladder(native: f64) -> Vec { - let mut rates = FRAME_RATES.to_vec(); - // Bit for bit: 23.976023976... is not 23.976, and a rate that read as - // "already listed" when it is not would take the media's own off the list. - if !rates.contains(&native) { - let at = rates - .iter() - .position(|&fps| fps > native) - .unwrap_or(rates.len()); - rates.insert(at, native); - } - rates -} - -/// The rate list's rows: every rung of the ladder, the media's own said so, and -/// the one in force marked. Named as a person writes a rate ([`fps_label`]), -/// with what it is for beside it -- short, or the row loses its tail to the -/// truncation the resolution list already met. -fn fps_choices(current: f64, native: f64) -> Vec { - frame_rate_ladder(native) - .into_iter() - .map(|fps| { - ( - Choice::Fps(fps), - format!("{} fps", fps_label(fps)).into(), - match fps == native { - true => "the media's own".to_string(), - // The rates that are a ratio are the ones nobody can tell - // from their neighbour by the label alone. - false => match (fps - fps.round()).abs() < 0.001 { - true => String::new(), - false => "NTSC".to_string(), - }, - } - .into(), - fps == current, - ) - }) - .collect() -} - -/// The fit list's rows: all four policies against the canvas they place a -/// picture on, since the word alone ("fill") says nothing about the size it is -/// filling -- which is the very thing the notice says after a stroke. -fn fit_choices(lane: Lane, idx: usize, current: FitPolicy, (w, h): (u32, u32)) -> Vec { - FITS.into_iter() - .map(|fit| { - ( - Choice::Fit(lane, idx, fit), - fit_label(fit).into(), - // The canvas alone, worded as the resolution list words a size: - // the policy names are long and anything wordier here loses its - // tail to the truncation. - format!("{w}x{h}").into(), - fit == current, - ) - }) - .collect() -} - -/// The sound-rate list's rows: every offered rate, the one in force marked, and -/// what each buys said in the fewest words that fit beside the label (a longer -/// phrase loses its tail to `MENU_W`'s truncation, as the two lists above say). -fn audio_rate_choices(current: u32) -> Vec { - AUDIO_KBPS - .into_iter() - .enumerate() - .map(|(n, kbps)| { - ( - Choice::AudioRate(kbps), - format!("{kbps} kbps").into(), - match (kbps, n) { - (DEFAULT_AUDIO_KBPS, _) => "the default", - (_, 0) => "smallest file", - (k, _) if k < DEFAULT_AUDIO_KBPS => "smaller file", - _ => "better sound", - } - .into(), - kbps == current, - ) - }) - .collect() -} - -/// How a rendition is named where a person reads it: the panel button, the -/// notice and the list row all say the same word ([`engine::tonemap::Preset`]). -fn tone_label(preset: Preset) -> &'static str { - match preset { - Preset::Reference => "Reference", - Preset::Standard => "Standard", - Preset::Vivid => "Vivid", - } -} - -/// The HDR list's rows: all three renditions, the one in force marked, and what -/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the -/// truncation the three lists above already met. Always offered, whatever is on -/// the timeline: a setting that appeared and vanished with the media would be a -/// setting nobody could find, and the row says who it acts on instead. -fn tone_choices(current: Preset) -> Vec { - Preset::ALL - .into_iter() - .map(|preset| { - ( - Choice::Tone(preset), - tone_label(preset).into(), - match preset { - Preset::Reference => "BT.2446-A, as published", - Preset::Standard => "brighter, player-like", - Preset::Vivid => "brightest, richer colour", - } - .into(), - preset == current, - ) - }) - .collect() -} - -/// The next project resolution after `current`, over [`RESOLUTIONS`] with the -/// media's own size cycled in at its place by size -- so the trip round always -/// comes back to the media, whatever odd shape it is, and a project already at a -/// listed size does not see it twice. -fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) { - let sizes = resolution_ladder(native); - let at = sizes.iter().position(|&s| s == current); - // A project at a size nobody listed (a hand-edited file) joins the cycle at - // the top rather than being stuck. - sizes[at.map_or(0, |at| (at + 1) % sizes.len())] -} - -/// The first of the two lines the card keeps above its button: what will be -/// *inside* the file. [`format_line`]'s codec and box, then the project's own -/// picture size and rate -- which is what a video export is written at however -/// many sizes and rates the media on the timeline are -- and last what the -/// sound will be, or that there is none. Every field here is one `ffprobe` -/// reads back off the finished file, so the line is checkable rather than a -/// promise. -fn summary_head(format: Format, picture: Option<((u32, u32), f64)>, audio: &str) -> String { - let line = match picture.filter(|_| format.has_video()) { - Some(((w, h), fps)) => { - format!("{} · {w}x{h} · {} fps", format_line(format), fps_label(fps)) - } - None => format_line(format).to_string(), - }; - join_detail(&line, audio) -} - -/// The second: where it lands, roughly how big, and what will encode the -/// picture -- the seat as the probe found it (`…` until it lands, never a -/// guess), which is what the running export then names on its progress line. -fn summary_tail(path: &Path, bytes: Option, seat: Option<&'static str>, video: bool) -> String { - let size = bytes.map_or_else(String::new, |bytes| format!("≈ {}", size_label(bytes))); - let seat = match (video, seat) { - (true, Some(seat)) => seat, - (true, None) => "encoder …", - (false, _) => "", - }; - join_detail(&join_detail(&file_name(path), &size), seat) -} - -/// A frame rate as a person writes it: `30`, not `30.000`, and `23.976` for the -/// rate that is a ratio. -fn fps_label(fps: f64) -> String { - match (fps - fps.round()).abs() < 0.001 { - true => format!("{fps:.0}"), - false => format!("{fps:.3}") - .trim_end_matches('0') - .trim_end_matches('.') - .to_string(), - } -} - -/// About how big a *chosen* bitrate makes the file: the picture's bits over the -/// timeline's length, in bytes -- the unit the line is written in is -/// [`size_label`]'s to pick. `None` for `Auto`, whose figure is the encoder's to -/// decide, and for a format with no bitrate at all -- a number nobody picked is -/// not an estimate. The sound and the container's own overhead are not in it, -/// which is why the card says "≈". -fn estimated_bytes(bitrate: Option, duration: f64) -> Option { - let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?; - Some((bitrate as f64 * duration / 8.).round() as u64) -} - -/// A size in the largest unit that can state it, [`rate_scale`]'s rule: -/// megabytes for an export of any length, kilobytes below the one a whole -/// megabyte rounds away. A three second clip at the floor bitrate really is -/// 375 kB, and "≈ 0 MB" would be this line saying the file it is about to write -/// is empty -- the one thing the size field is there to deny. Never "0 kB" -/// either: an estimate that exists is at least a kilobyte of file. -fn size_label(bytes: u64) -> String { - match (bytes as f64 / 1e6).round() as u64 { - 0 => format!("{} kB", (bytes as f64 / 1e3).round().max(1.) as u64), - mb => format!("{mb} MB"), - } -} - -/// What is in the file and what box it is in, which is the head of the summary. -/// Terse on purpose: the fields after it (size, rate, sound) are what the line -/// is *for*, and a head that spent its width on prose used to push the whole -/// summary onto a second line -- what each codec means is on its row. -fn format_line(format: Format) -> &'static str { - match format { - Format::Mp4 => "H.264 · MP4", - Format::Av1 => "AV1 · MKV", - Format::Av1Mp4 => "AV1 · MP4", - Format::Hevc => "HEVC intra · MKV", - Format::HevcMp4 => "HEVC intra · MP4", - // The three whose codec *is* their box: naming it twice would be the - // only field on this line that says nothing. - Format::Wav => "16-bit PCM · WAV", - Format::Flac => "FLAC · lossless", - Format::Mp3 => "MP3 · lossy", - Format::Ogg => "Vorbis · OGG", - } -} - -/// The row a format is picked by, which is what a refusal calls it: the codec, -/// since the container is a row of its own now -- `AV1`, not the `mkv` such a -/// file is named with. -fn format_label(format: Format) -> &'static str { - FORMATS - .iter() - .find(|(row, ..)| row.contains(&format)) - .map_or("EXPORT", |(_, _, label, _)| *label) -} - -/// The destination under a format: `take.export.mp4` becomes `take.export.wav`. -/// The stem is untouched, so a name typed into the save dialog survives a -/// change of mind about the format -- only the extension is the format's to say. -fn retarget(path: &std::path::Path, format: Format) -> PathBuf { - let mut path = path.to_path_buf(); - path.set_extension(format.ext()); - path -} - -/// The card's rows as the engine takes them. `Auto` leaves the bitrate to the -/// exporter, which derives it from the picture; the fixed rows are figures that -/// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the -/// engine clamps every explicit bitrate to 1..50 Mbps (`MAX_EXPLICIT_BITRATE`), so this -/// must not clamp it a second time and disagree about where the edge is. -/// -/// The bitrate travels even for an audio format, where the engine ignores it: -/// one settings value, and a row the card has dimmed cannot have been changed. -fn export_settings( - quality: Quality, - custom_mbps: u32, - format: Format, - audio_kbps: u32, -) -> ExportSettings { - ExportSettings { - format, - // Always travels, exactly as the picture's bitrate does above: the - // engine ignores it where nothing encodes the sound, and a row the card - // has dimmed cannot have been changed. - audio_kbps: Some(audio_kbps), - bitrate: match quality { - Quality::Auto => None, - Quality::Low => Some(2_000_000), - Quality::Medium => Some(6_000_000), - Quality::High => Some(12_000_000), - Quality::Custom => Some(u64::from(custom_mbps) * 1_000_000), - }, - // No row of its own: the software pin is for a driver that encodes - // badly, which is a thing about the machine and not about the output -- - // `VE_SW_ENC` already says it, and to the whole run rather than once. - force_sw: false, - // The picked track is put on by `start_export`, which is the only - // caller that writes a file; the rest of them are asking about the - // bitrate and the format. - subtitles: Vec::new(), - } -} - -/// What the engine will code an explicit bitrate at, in whole Mbps: outside -/// this it clamps (`export.rs` `MIN_BITRATE`/`MAX_EXPLICIT_BITRATE`), so a -/// number typed past either end would be written as a different one. The field -/// refuses it instead of clamping quietly -- a card that changes the user's -/// number without saying so is the one thing a field like this must never do. -/// -/// The ceiling was 20, which was never a limit of any encoder here: it was the -/// top of the range the exporter *derives* an automatic bitrate in, borrowed as -/// the cap on a typed one. A 1080p master or a 4K edit wants more than that, so -/// the asked-for rate has its own ceiling now and this is it. -const MBPS_MIN: u32 = 1; -const MBPS_MAX: u32 = 50; - -/// How many digits the field takes. Two reach the ceiling; the third is there so -/// a number *past* it can be typed whole and refused in its own words, rather -/// than being dropped keystroke by keystroke. -const MBPS_DIGITS: usize = 3; - -/// A number being typed into a card row: the digits so far and, once a commit -/// has been refused, why. Text-field semantics on a card that has no text field -/// -- typing, backspace, arrows that step, enter that commits and escape that -/// gives up -- held as state and driven by the root's key handler, since -/// nothing in these cards takes gpui focus. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -struct NumberEdit { - text: String, - refusal: Option, -} - -impl NumberEdit { - /// Starts on the number the row already carries, so backspace edits it - /// rather than the field opening empty over a value that is still in force. - /// Zero is no number at all -- it is what the card opens at, before anyone - /// has typed one. - fn new(value: u32) -> Self { - NumberEdit { - text: match value { - 0 => String::new(), - v => v.to_string(), - }, - refusal: None, - } - } - - /// A digit against what is there. The one past [`MBPS_DIGITS`] is refused - /// *out loud*: a keystroke dropped in silence is how the old digit capture - /// left the card showing a number the user had already typed past. - fn digit(&mut self, digit: u32) { - if self.text.chars().count() >= MBPS_DIGITS { - self.refusal = Some(format!("{MBPS_DIGITS} digits is already past the ceiling")); - return; - } - match char::from_digit(digit, 10) { - Some(c) => { - self.text.push(c); - self.refusal = None; - } - None => self.refusal = Some("digits only".into()), - } - } - - /// Erases the last digit, and the refusal with it: the number on screen has - /// changed, so the reason the old one was refused no longer describes it. - fn backspace(&mut self) { - self.text.pop(); - self.refusal = None; - } - - /// The arrows, which is how a number gets picked rather than typed. Steps - /// from what is in the field -- an empty one starts at the floor, so the - /// first press up is `MBPS_MIN` and not a jump to some remembered value -- - /// and stays inside the range, because a step is a walk through the legal - /// numbers rather than a way out of them. - fn step(&mut self, by: i32) { - let at = self.text.parse::().unwrap_or(MBPS_MIN as i32 - by.signum()); - self.text = (at + by) - .clamp(MBPS_MIN as i32, MBPS_MAX as i32) - .to_string(); - self.refusal = None; - } - - /// The number, or `None` with the reason recorded where the row will read - /// it. Never clamped: 45 committed as 20 is a number the user did not type. - fn commit(&mut self) -> Option { - match commit_mbps(&self.text) { - Ok(mbps) => Some(mbps), - Err(why) => { - self.refusal = Some(why); - None - } - } - } - - /// What the row shows while it is being typed into: the digits, the caret - /// that says they are landing *here*, and either the refusal or the two - /// keys that end the edit. - fn detail(&self) -> String { - format!( - "{}▏ Mbps — {}", - self.text, - match &self.refusal { - Some(why) => why.as_str(), - None => "enter commits · esc cancels", - } - ) - } -} - -/// A typed bitrate as the card takes it, or the reason it is not one. The words -/// are the row's: they are what the field shows in place of its hint. -fn commit_mbps(text: &str) -> Result { - match text.parse::() { - Ok(mbps) if (MBPS_MIN..=MBPS_MAX).contains(&mbps) => Ok(mbps), - Ok(0) => Err(format!("0 is not a rate — {MBPS_MIN}–{MBPS_MAX} Mbps")), - Ok(mbps) => Err(format!("{mbps} is past the {MBPS_MAX} Mbps ceiling")), - Err(_) => Err(format!("type a number — {MBPS_MIN}–{MBPS_MAX} Mbps")), - } -} - -/// Whether a stroke gets out of a running export. Escape does, whatever -/// modifiers are held with it, for the same reason it gets out of a capture and -/// out of the overlay: it is this window's way out, and a way out that only -/// works with the right modifiers is not one. Whatever the keymap has on cancel -/// works too, so rebinding it adds a way rather than replacing the one that -/// always worked -- and that binding is still what the progress line shows. -fn cancels_export(key: &str, action: Option) -> bool { - key == ESCAPE || action == Some(ActionId::CancelExport) -} - -/// Where a held key would land, which is the whole of what auto-repeat has to -/// know. [`Player::repeat_scope`] answers it from the same state the handler -/// walks below itself. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Repeat { - /// A card with values in it owns the keyboard: equalizer, colour, speed or - /// silence. Its arrows are sliders. - Card, - /// Nobody does, so the keymap answers -- and only one pair of its actions - /// is a value being moved rather than a thing being done once. - Keymap, - /// A stroke is being captured, an export is running, or an overlay with no - /// value in it is up. Nothing there is worth a repeat. - Nothing, -} - -/// Whether a *held* stroke means it again. One press is always one action; a -/// hold is only ever a value running, so this is what tells the two apart. -/// -/// The cards' arrows, because that is what every one of them moves a slider -/// with -- and only the arrows, so the equalizer's `r` cannot flatten five -/// bands forty times a second and the silence card's `enter` cannot cut forty -/// places again on the next tick. Outside a card the volume pair and nothing -/// else: play, cut, delete, save, export and every other binding is a one-shot, -/// exactly as it was when the handler filtered every held key alike. -fn repeats(scope: Repeat, key: &str, action: Option) -> bool { - match scope { - Repeat::Card => matches!(key, "up" | "down" | "left" | "right"), - Repeat::Keymap => matches!( - action, - Some( - ActionId::VolumeUp - | ActionId::VolumeDown - // A zoom is a value being moved as much as a level is: - // held, it runs from the whole timeline down to a handful - // of frames and stops there. The fit is one press. - | ActionId::ZoomIn - | ActionId::ZoomOut - ) - ), - Repeat::Nothing => false, - } -} - -/// The keys that are only ever half a chord. gpui delivers a lone modifier -/// press as a keystroke of its own, and taking one as a binding would leave an -/// action that fires the moment the user reaches for any chord that uses it -- -/// so a capture waits through them instead. -fn is_bare_modifier(key: &str) -> bool { - matches!( - key, - "control" | "shift" | "alt" | "super" | "platform" | "function" | "fn" | "meta" | "command" - ) -} - -/// A clip's share of the lane. A timeline with no length reads as one full-width -/// box rather than as NaN, which gpui would carry into layout. -/// Why this timeline cannot be written in `format`, if it cannot. -/// -/// An audio-only timeline is the one both picture formats refuse: every frame of -/// it is a gap, so the file would be a black picture over the sound. The engine -/// refuses it too (`export::start`); this is what greys the row before a -/// destination has been picked. -/// -/// It is the *only* reason left. A second audio lane, a speeded clip, a source -/// no mp4 sample table holds: each of those used to grey the MP4 row, because -/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy -/// cannot say what the timeline says (`export::copy_audio`), so none of them is -/// a refusal any more -- and every video format carries the sound, so there is -/// nothing here that is one format's alone. -fn format_refusal(session: &PlaybackSession, format: Format) -> Option { - if !format.has_video() { - return None; - } - let picture = session - .lanes() - .into_iter() - .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); - match picture { - true => None, - false => Some(format!( - "no picture — {} would be black; export WAV, FLAC, MP3 or OGG", - format.name() - )), - } -} - -/// How tall a column of `lanes` rows is, gaps included -- the panel's own gap -/// between them, since the rows sit in it. -fn lanes_h(lanes: usize) -> f32 { - match lanes { - 0 => 0., - n => n as f32 * LANE_H + (n - 1) as f32 * 8., - } -} - -/// How many whole lane rows a box this tall shows. At least one: a box too -/// short for a single lane still shows part of one, and "0 shown" would count -/// every lane there is as hidden. -fn lanes_shown(box_h: f32) -> usize { - (((box_h + 8.) / (LANE_H + 8.)).floor() as usize).max(1) -} - -/// How many rows are still below the fold *now*: the count the affordance says -/// out loud, and the reason it is a function of the scroll rather than of the -/// lane count alone. A line that keeps saying "2 more tracks below" after the -/// user has scrolled to the last one is a line that has stopped being true, and -/// an affordance nobody can make go away is read as a bug rather than as an -/// instruction. -/// -/// `scrolled` is how far down the column has been taken, in pixels. Rounded to -/// the nearest row: a half-scrolled row is showing, so it is not below. -fn rows_below(total: usize, box_h: f32, scrolled: f32) -> usize { - let past = ((scrolled / (LANE_H + 8.)).round().max(0.)) as usize; - total.saturating_sub(past + lanes_shown(box_h)) -} - -/// The same question for a column whose rows are not one height -- the -/// inspector's sections -- answered in pixels off what the scroll itself -/// reports: how far it may still be taken (`max_offset`) less how far it has -/// been (`offset`, which gpui keeps negative going down). -fn px_below(max_offset_h: f32, offset_y: f32) -> f32 { - (max_offset_h + offset_y).max(0.) -} - -/// What the subtitle strip adds to the panel: its own row and the panel's gap -/// above it, and nothing at all for a timeline with no subtitles on it -- the -/// picture does not pay for a strip that is not drawn. -fn subtitle_strip_h(shown: bool) -> f32 { - match shown { - true => SUB_LANE_H + 8., - false => 0., - } -} - -/// How tall the panel is with `lanes` tracks in it: [`PANEL_H`] is sized for the -/// two a project starts with, and every further one adds its own row -- up to -/// [`LANES_MAX`], past which the lane column scrolls instead and the panel stops -/// growing. -fn panel_h(lanes: usize) -> f32 { - PANEL_H + lanes_h(lanes.clamp(2, LANES_MAX)) - lanes_h(2) -} - -/// How tall the timeline region is: its own padding, the timecode line, the -/// ruler and the gaps between them, plus a row per lane. Measured from its -/// parts rather than taken off [`PANEL_H`] -- the button row moved out of it -/// ([`Player::toolbar`]), and a height still carrying that row's pixels is a -/// height that cuts the last lane off the bottom of the window. -fn timeline_h(lanes: usize) -> f32 { - TIMELINE_FIXED_H + lanes_h(lanes.clamp(2, LANES_MAX)) -} - -/// 8+8 padding, the timecode line, the 24 px ruler strip and the two 8 px gaps -/// between the three rows, with a couple of px of slack so a taller text line -/// cannot push a lane off the bottom. -const TIMELINE_FIXED_H: f32 = 16. + 18. + 8. + RULER_HIT_H + 8. + 4.; - -/// The most of a short window the timeline may take. At the 640x360 floor that -/// is 151 px of the 360, which leaves the picture a region rather than a -/// letterbox stripe -- and the lanes scroll inside it. -const TIMELINE_SHARE: f32 = 0.42; - -/// The edit toolbar directly above the timeline: one control's height in its -/// own padding, fixed so nothing in it can push the timeline down. -const TOOLBAR_H: f32 = CONTROL_H + 16.; - -/// The top bar: the project's name on the left, the two file actions on the -/// right. Fixed for the reason [`HEADER_H`] is. -const TOPBAR_H: f32 = 36.; - -/// The transport strip under the picture -- play, timecode, volume -- where a -/// player's own controls live in every consumer editor. -const TRANSPORT_H: f32 = CONTROL_H + 12.; - -/// One press of a zoom key, or one notch of ctrl+wheel. -const ZOOM_STEP: f32 = 1.25; - -/// How far one notch of a bare wheel slides the view along, as a share of what -/// is on the bed. A *share* rather than a number of pixels or of seconds: one -/// gesture then moves the same fraction of what is being looked at whether the -/// bed is showing five seconds or five hours, which is the only way a wheel is -/// usable at both ends of the zoom. -const SCROLL_NOTCH_SHARE: f32 = 0.1; - -/// How few frames the bed may be narrowed down to. Past this there is nothing -/// left to aim at -- a single frame across a whole window is a wall of colour, -/// not an edit surface. -const ZOOM_MIN_FRAMES: f64 = 8.; - -/// How thin a second of timeline may be drawn on a bed that is already showing -/// all of it: the far stop for a *short* project, which has no length of its own -/// worth widening to, so a five second import can still be zoomed out of. -const PPS_MIN: f64 = 1.; - -/// How much bed the far stop leaves past the last frame, as a multiple of the -/// timeline's own length -- so a timeline zoomed all the way out ends a sliver -/// short of the window's edge rather than glued to it. -const ZOOM_OUT_MARGIN: f64 = 1.05; - -/// How wide a second of timeline is drawn before anyone zooms: a five second -/// import is 200 px of a bed several times that, so a short clip reads as -/// short -- the thing a bed scaled to the content's own length cannot say. -/// [`View::fit`] is the one way back to "the whole timeline across the bed". -const PPS_DEFAULT: f64 = 40.; - -/// What the zoom button says it is showing: how much timeline fits on the bed, -/// in the coarsest unit that still tells two zooms apart. -fn span_label(span: f64) -> String { - match span { - s if !s.is_finite() || s <= 0. => "—".to_string(), - // Hours once a timeline is long enough to be measured in them: the far - // stop follows the content now, so "315m" is a span a user can be sat - // at, and no one reads a pill in minutes past sixty. - s if s >= 3600. => format!("{:.1}h", s / 3600.), - s if s >= 600. => format!("{:.0}m", s / 60.), - s if s >= 60. => format!("{:.1}m", s / 60.), - s if s >= 10. => format!("{s:.0}s"), - s => secs_label(s), - } -} - -/// A span of seconds as a person reads it: one decimal above a second, two -/// below -- [`scaled`]'s rule, for its reason. The tightest zoom is -/// [`ZOOM_MIN_FRAMES`] across the bed, which on the 240 fps slow-motion a phone -/// writes is 0.03s, and a single frame of quiet at 60 fps is 0.02s: one decimal -/// prints both as "0.0s", a pill and a notice saying the thing they are about -/// has no length at all. -fn secs_label(secs: f64) -> String { - match secs >= 1. { - true => format!("{secs:.1}s"), - false => format!("{secs:.2}s"), - } -} - -/// The mapping the whole panel is drawn and clicked through: `pps` pixels to a -/// second of timeline, `start` the moment at the bed's left edge. Absolute -- -/// how wide a clip is drawn depends on how long the clip is and on nothing -/// else, so adding a second clip does not redraw the first one narrower and -/// zooming out always makes every box smaller. -/// -/// The one place seconds become pixels: every box, the playhead, a seek and a -/// trim all go through it, so none of them can drift away from the others when -/// the view moves. What clamps it -- the stops, the scroll, the fit -- needs the -/// bed it is drawn on and lives on [`View`]. -#[derive(Clone, Copy, Debug, PartialEq)] -struct Scale { - pps: f64, - start: f64, -} - -impl Default for Scale { - fn default() -> Self { - Scale { - pps: PPS_DEFAULT, - start: 0., - } - } -} - -impl Scale { - /// Where a moment sits on the bed, in pixels from its left edge. Negative - /// for a moment scrolled off to the left, which is exactly the offset a - /// half-visible clip is drawn at. - fn px_at(self, at: f64) -> f32 { - ((at - self.start) * self.pps) as f32 - } - - /// How wide a stretch of `len` seconds is drawn. Wider than the bed once - /// zoomed in, which is the point of zooming in; never negative, which gpui - /// has no meaning for. - fn width_px(self, len: f64) -> f32 { - (len * self.pps).max(0.) as f32 - } - - /// The moment `x` pixels along the bed is pointing at: the inverse of - /// [`Scale::px_at`], and what every seek and every trim reads. Clamped at - /// the head of the timeline only -- there is bed past the last frame now, - /// and a tail dragged into it is a longer clip, not an error. - fn time_at(self, x: f32) -> f64 { - if self.pps > 0. { - (self.start + f64::from(x) / self.pps).max(0.) - } else { - self.start - } - } - - /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: a snap - /// is a distance on screen, so zoomed right in it is worth less than a frame - /// (no snap at all, which is what a hand placing single frames wants) and - /// zoomed out it is worth many. - fn snap_frames(self, fps: f64) -> u32 { - if self.pps > 0. { - (SNAP_PX / self.pps * fps) as u32 - } else { - 0 - } - } -} - -/// A [`Scale`] against the bed it is drawn on and the timeline it is drawn -/// from. The bed's width is what turns a scale into "how much is on screen", -/// and that is all the stops, the scroll clamp and the fit are made of. -/// -/// Built per use out of [`Player::view`] and thrown away again -- the state is -/// the `Scale`, and this is what a bed of `bed` px showing `duration` seconds -/// at `fps` may do to it. So no call site can measure a moment against a bed or -/// a duration that another one did not. -#[derive(Clone, Copy, Debug, PartialEq)] -struct View { - scale: Scale, - bed: f32, - duration: f64, - fps: f64, -} - -impl View { - /// How much of the timeline is on the bed, in seconds. - fn span(self) -> f64 { - if self.scale.pps > 0. { - f64::from(self.bed) / self.scale.pps - } else { - 0. - } - } - - /// The two stops, in pixels per second: [`ZOOM_MIN_FRAMES`] across the bed - /// is as tight as it goes, and as wide as it goes is the whole timeline on - /// the bed with [`ZOOM_OUT_MARGIN`] to spare -- the far stop is *relative*, - /// so the end of a five hour timeline is reachable for the same reason the - /// end of a five minute one is. A fixed far stop could not say that: a - /// timeline longer than it had an end no zoom could reach, which is the bug - /// this is. Short of [`PPS_MIN`] the timeline's own length is not worth - /// widening to and the pixel takes over, so a short import can still be - /// zoomed out of and the resting scale is nobody's content. - /// - /// `None` on a bed that was never painted -- there is nothing to measure - /// them against yet, and a stop guessed off a zero width would throw away a - /// zoom the user asked for. - fn stops(self) -> Option<(f64, f64)> { - (self.bed > 0.).then(|| { - let bed = f64::from(self.bed); - let whole = match self.duration > 0. { - true => bed / (self.duration * ZOOM_OUT_MARGIN), - false => PPS_MIN, - }; - let min = whole.min(PPS_MIN); - (min, (bed * self.fps / ZOOM_MIN_FRAMES).max(min)) - }) - } - - /// Clamped to the bed it draws on: between the two stops, and never - /// scrolled past either end of the timeline. Unlike the fractional view - /// this replaced, the *resting* scale is not the content -- a five second - /// timeline zooms out as far as an hour long one does, and both are drawn - /// at [`PPS_DEFAULT`] until someone zooms. Only the far stop knows the - /// length, and only once the length is worth more than [`PPS_MIN`]. - fn settled(self) -> Scale { - let pps = match self.scale.pps.is_finite() && self.scale.pps > 0. { - true => self.scale.pps, - false => PPS_DEFAULT, - }; - let start = match self.scale.start.is_finite() { - true => self.scale.start, - false => 0., - }; - let Some((min, max)) = self.stops() else { - return Scale { - pps, - start: start.max(0.), - }; - }; - let pps = pps.clamp(min, max); - let span = f64::from(self.bed) / pps; - Scale { - pps, - start: start.clamp(0., (self.duration - span).max(0.)), - } - } - - /// Zoomed by `factor` about `anchor` (pixels along the bed): whatever moment - /// was under that point stays under it, so a zoom magnifies what was being - /// looked at rather than throwing it off the edge. - fn zoomed(self, factor: f32, anchor: f32) -> Scale { - let at = self.scale.time_at(anchor); - // Clamped *before* the offset is worked out, not after: a press that - // runs into either stop must still leave the anchor where it is, and a - // start measured against a scale the stop then took away would slide it. - let raw = self.scale.pps * f64::from(factor); - let pps = match self.stops() { - Some((min, max)) => raw.clamp(min, max), - None => raw, - }; - View { - scale: Scale { - pps, - start: at - f64::from(anchor) / pps, - }, - ..self - } - .settled() - } - - /// Slid along by `by` pixels, later in the timeline for a positive one: the - /// one move that changes what is on the bed without changing how wide a - /// second is drawn, which is what a bare wheel does. Clamped by - /// [`View::settled`] like every other move, so a run at either end stops at - /// the end rather than scrolling the timeline off the bed -- and the extent - /// it stops against is the content's own length, never a number. - fn scrolled(self, by: f32) -> Scale { - let pps = self.settled().pps; - View { - scale: Scale { - pps, - start: self.scale.start + f64::from(by) / pps, - }, - ..self - } - .settled() - } - - /// The whole timeline across the bed. The one place the content's own - /// length sets the scale, and the only one -- everywhere else a second is a - /// second -- because this is a user pressing a key that asks for exactly - /// that. - fn fit(self) -> Scale { - let pps = match self.duration > 0. && self.bed > 0. { - true => f64::from(self.bed) / self.duration, - false => PPS_DEFAULT, - }; - View { - scale: Scale { pps, start: 0. }, - ..self - } - .settled() - } - - /// The scale a playhead at `at` needs: the same one while it is on the bed, - /// and one centred on it once it has run off -- which is how a zoomed-in - /// timeline scrolls, during playback and after a seek alike. With the whole - /// timeline on the bed this can never fire, so a panel showing all of it is - /// untouched by it. - fn following(self, at: f64) -> Scale { - // Nothing is drawn yet, so nothing has run off anything. - if self.bed <= 0. { - return self.scale; - } - let scale = self.settled(); - if self.shows(at) { - return scale; - } - let span = f64::from(self.bed) / scale.pps; - View { - scale: Scale { - start: at - span / 2., - ..scale - }, - ..self - } - .settled() - } - - /// Whether the moment `at` is on the bed as it is drawn now. The one - /// question both halves of the follow ask -- [`View::following`] to decide - /// whether to chase a head that has run off, and the render to decide when - /// a hand's own scroll ([`Player::panned`]) has been caught up with and the - /// follow may have the view back -- so the two can never disagree about - /// where the edge of the bed is. - fn shows(self, at: f64) -> bool { - if self.bed <= 0. { - return false; - } - let scale = self.settled(); - at >= scale.start && at <= scale.start + f64::from(self.bed) / scale.pps - } -} - -/// Whether this clip is a whole take, i.e. whether deleting it may close the -/// hole under it: a take is what the first pair of lanes carries between them, -/// `V1`'s picture and the sound grouped with it, and dropping one moves the -/// frames after it on every lane. -/// -/// Everything else is a half or a layer, and is *lifted* instead: a half whose -/// picture was lifted (what a lift leaves behind) has no take to ripple, and a -/// clip on a further lane is laid over the timeline rather than part of it -- -/// closing a hole under it would drag the take beneath out of step with it. -fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool { - let Some(clip) = session.lane_clips(lane).get(idx) else { - return false; - }; - let paired = || { - session - .lanes() - .into_iter() - .filter(|&other| other != lane) - .flat_map(|other| session.lane_clips(other)) - .any(|o| o.link.is_some() && o.link == clip.link) - }; - match (lane.kind, lane.ord) { - (_, 1..) => false, - // The picture of a take -- unless the take has been taken apart: a - // detached picture (a group id no other lane carries, which is also what - // a lift of the sound leaves) is a half like the sound is, and a ripple - // under it would drag away the very half it was detached from. A clip in - // no group at all is not a half but a placement, and on `V1` a placement - // is the take there is. - (LaneKind::Video, _) => clip.link.is_none() || paired(), - // The sound of a take, only while the take is still there: its group is - // carried by a clip on some other lane. - (LaneKind::Audio, _) => paired(), - } -} - -/// The clip a Group would pair this one with: the first clip on another track, -/// in the order the lanes are drawn, covering exactly the same frames and not in -/// this clip's group already. Exactly the same frames because that is all a -/// group id can mean (engine `links_are_consistent`), which is what leaves -/// nothing for a second click to choose. `None` when no track has one, and the -/// notice says so. -fn span_partner(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> { - let clip = *session.lane_clips(lane).get(idx)?; - let matches = |other: Lane| { - let i = session.lane_clips(other).iter().position(|c| { - (c.start, c.end()) == (clip.start, clip.end()) - && !(c.link.is_some() && c.link == clip.link) - })?; - Some((other, i)) - }; - // Sound before picture (and picture before sound): "group this" means the - // other half of the take, and a project whose audio lane was added after a - // second video one has that half *after* the layer in storage order -- which - // is the order the lanes come in. A same-kind lane is still groupable (V1 - // and V2 may be one take), but only where no opposite one covers the span. - let (opposite, same): (Vec, Vec) = session - .lanes() - .into_iter() - .filter(|&other| other != lane) - .partition(|other| other.kind != lane.kind); - opposite.into_iter().chain(same).find_map(matches) -} - -/// Whether a click marks this clip: the clip that was clicked always, and the -/// other lane's clip of the same group with it. A clip whose group has no other -/// half -- what a lift leaves behind -- marks only itself, which is what makes a -/// detached half separately deletable. -fn marked( - here: (Lane, usize), - link: Option, - sel: Option<(Lane, usize)>, - sel_link: Option, -) -> bool { - sel == Some(here) || (link.is_some() && link == sel_link) -} - -/// Whether a clip is wide enough to be worth naming. -fn show_label(w: f32) -> bool { - w >= LABEL_MIN_W -} - -/// The clip a trim is *showing*, worked out the way `Project::trim` will write -/// it: the timeline room the edge leaves is turned into source frames by the one -/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from -/// that. The preview and the commit are then the same arithmetic -- a box let go -/// of stays where the hand left it at every rate. Assigning the timeline count -/// straight to the source field, as this used to, drew a speeded clip's tail -/// moving at the wrong rate (it snapped on release) and drew a *head* trim -/// moving the clip's other edge, since the length it implied was not the length -/// the release would commit. -/// -/// A still grows forward from source frame 0 instead: every frame of it is the -/// same picture, so there is no earlier one for an in-point to walk back to. -/// -/// Room too narrow to hold one source frame is the edit the engine refuses, and -/// the box is drawn unchanged rather than as something that will not be -/// committed. -fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip { - // An edge that has not moved is not an edit, and `Project::trim` refuses it - // as one: the press that starts a drag must draw the clip it pressed, not a - // clip a rounding narrower. - if to - == match edge { - Edge::Start => clip.start, - Edge::End => clip.end(), - } - { - return clip; - } - match edge { - Edge::Start => { - // What survives is measured from the *end* -- the frames that stay - // play what they always played, which is what makes this a trim. - let Some(keep) = clip.speed.fit(clip.end().saturating_sub(to)) else { - return clip; - }; - match still { - true => Clip { - in_frame: 0, - out_frame: keep, - start: to, - ..clip - }, - false => Clip { - in_frame: clip.out_frame - keep.min(clip.out_frame), - start: to, - ..clip - }, - } - } - Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) { - Some(keep) => Clip { - out_frame: clip.in_frame + keep, - ..clip - }, - None => clip, - }, - } -} - -/// Which index on its own lane a dragged clip is at *now*: the one it was picked -/// up at while nothing has moved, and wherever the clip itself has slid to when -/// an edit during the drag rippled the lane's indices -- a delete, an undo or a -/// paste from a stroke, none of which gpui's frozen drag payload hears about. -/// `None` when the clip is gone altogether, and then the drop is not an edit at -/// all: moving whatever slid into its place is the one thing the hand did not -/// ask for. A lane's clips are disjoint and sorted, so at most one of them can -/// be the clip that was picked up. -fn live_idx(clips: &[Clip], idx: usize, clip: Clip) -> Option { - match clips.get(idx) { - Some(&at) if at == clip => Some(idx), - _ => clips.iter().position(|&c| c == clip), - } -} - -/// The part of a clip's box that is on the bed, in the box's own pixels: -/// `(left, width)` of its intersection with the visible strip. Everything drawn -/// *inside* a box -- its waveform, its name, its speed badge -- is placed in -/// here rather than at the box's own edges, which at a deep zoom sit thousands -/// of pixels off either side of the screen: a label out there is a label nobody -/// can read, and a waveform out there is a path with a point per two pixels of a -/// width nobody can see. A bed that has not been measured yet answers with the -/// whole box, which is what was drawn before there was a bed to clip to. -fn visible_slice(left: f32, width: f32, bed: f32) -> (f32, f32) { - if bed <= 0. { - return (0., width); - } - let from = (-left).clamp(0., width); - let to = (bed - left).clamp(from, width); - (from, to - from) -} - -/// Scales an envelope to its own loudest sample, so a quietly mastered source -/// still draws as a shape. The fixtures peak around an eighth of full scale, and -/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file -/// that is not. -fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> { - let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi)); - if loudest > 0. { - for (lo, hi) in &mut peaks { - *lo /= loudest; - *hi /= loudest; - } - } - peaks -} - -/// The min/max envelope of `peaks` over the source seconds `from..to`, as -/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box -/// -- a clip's waveform cannot paint over its neighbour -- and every column is -/// at least a pixel tall, so silence reads as a line through the middle rather -/// than as a polygon with no area. -fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f32, f32, f32)> { - if peaks.is_empty() || w <= 0. || h <= 0. { - return Vec::new(); - } - let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX); - let mid = h / 2.; - (0..=cols) - .map(|col| { - let along = col as f64 / cols as f64; - let at = from + (to - from) * along; - // Casting a float to an integer saturates in Rust, so a source - // second past the end of the peaks clamps rather than wrapping. - let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1); - let (lo, hi) = peaks[bucket]; - let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5); - let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5); - (w * along as f32, top.max(0.), bottom.min(h)) - }) - .collect() -} - - - - - - - - -/// Records its parent's laid-out box: gpui hands a mouse listener the window -/// position only, and the ruler sits behind the panel's padding. Paints -/// nothing and takes no hitbox of its own, so the click still reaches the bar. -fn bounds_probe(into: Rc>>) -> impl IntoElement { - canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ()) - .absolute() - .size_full() -} - -/// Where along an element a click landed, 0..1. An element that was never -/// painted has no width, and reads as its start rather than as NaN. -fn frac_along(x: Pixels, bounds: Bounds) -> f32 { - if bounds.size.width <= px(0.) { - return 0.; - } - ((x - bounds.left()) / bounds.size.width).clamp(0., 1.) -} - -/// Where along an element a click landed, in pixels from its own left edge: -/// [`frac_along`] in the units the timeline is drawn in, since a [`Scale`] -/// measures in pixels and not in shares of a bed. Clamped to the element -- a -/// drag that slid off the end names its end -- and an element that was never -/// painted reads as its start. -fn px_along(x: Pixels, bounds: Bounds) -> f32 { - f32::from(x - bounds.left()).clamp(0., f32::from(bounds.size.width).max(0.)) -} - -/// One turn of the wheel as a single number, positive for a turn *up*, in -/// whatever units the device sends (a mouse counts lines, a touchpad pixels). -/// A tilt wheel's own axis counts as the same gesture: it is the sideways -/// scroll a mouse that has one sends, and the controls this drives have one -/// direction each, so the two axes are one answer here. -fn wheel_delta(event: &ScrollWheelEvent) -> f32 { - let (dx, dy) = match event.delta { - ScrollDelta::Lines(d) => (d.x, d.y), - ScrollDelta::Pixels(d) => (f32::from(d.x), f32::from(d.y)), - }; - match dy == 0. { - true => dx, - false => dy, - } -} - -/// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is -/// within `tol` frames of where its head -- or its tail, `len` frames along -- -/// would come to rest, in which case that edge wins. The snap every timeline -/// has: clips meet exactly instead of a frame apart, and the hand does not have -/// to aim. The nearest mark wins, and a head landing on one beats a tail at the -/// same distance -- what was dragged is the head. -fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 { - let mut best: Option<(u32, u32)> = None; - for &mark in marks { - // Head on the mark, then tail on it -- a clip dragged up against the - // take in front of it snaps by whichever end reaches first. - for start in [Some(mark), mark.checked_sub(len)] { - let Some(start) = start else { continue }; - let d = start.abs_diff(raw); - if d <= tol && best.is_none_or(|(near, _)| d < near) { - best = Some((d, start)); - } - } - } - best.map_or(raw, |(_, start)| start) -} - -/// The edges worth landing on, off *every* lane: both ends of every clip on the -/// timeline, less `skip` -- the clip being dragged, which does not snap to where -/// it already is -- and less the other halves of its group, which travel with -/// it. `skip` is a lane's place in `lanes` and an index into it. The playhead -/// and the head of the timeline go on the end: a clip meets the cursor and the -/// start of the show as readily as it meets another take. -/// -/// All lanes rather than the one being dropped on, because a cut is made across -/// the timeline: a title on V2 lines up with the shot under it, and a sound -/// effect lines up with the frame it belongs to. -fn snap_marks(lanes: &[&[Clip]], skip: Option<(usize, usize)>, playhead: u32) -> Vec { - let link = skip - .and_then(|(lane, idx)| lanes.get(lane)?.get(idx)) - .and_then(|clip| clip.link); - let mut marks: Vec = lanes - .iter() - .enumerate() - .flat_map(|(lane, clips)| { - clips - .iter() - .enumerate() - .filter(move |&(idx, clip)| { - Some((lane, idx)) != skip && !(link.is_some() && clip.link == link) - }) - .flat_map(|(_, clip)| [clip.start, clip.end()]) - }) - .collect(); - marks.push(playhead); - marks.push(0); - marks -} - -/// [`snapped`], and the mark that pulled it there -- the line the bed draws -/// while the hand is still moving. `None` when nothing was near enough: a line -/// standing over open bed would promise a landing that is not going to happen. -/// The head is read before the tail, exactly as [`snapped`] prefers it. -/// -/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and -/// draws no line at all, which is the whole point of being able to turn it off. -fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option) { - if !on { - return (raw, None); - } - let start = snapped(raw, len, tol, marks); - let mark = [start, start.saturating_add(len)] - .into_iter() - .find(|mark| marks.contains(mark)); - (start, mark) -} - -/// Where a drag lands and the mark that pulled it there: the frame under the -/// pointer, less however far into the box the hand grabbed it (so a clip travels -/// with the pointer rather than jumping its head under it), snapped by -/// [`snap_cue`]. One answer, asked by the shadow drawn in flight -/// ([`Player::preview_ghost`]), by the line ([`Player::preview_drop`]) and by -/// the drop that commits ([`Player::move_clip`]) -- which is what makes the -/// promise and the landing the same frame. -fn landing( - under: u32, - grab: u32, - len: u32, - on: bool, - tol: u32, - marks: &[u32], -) -> (u32, Option) { - snap_cue(on, under.saturating_sub(grab), len, tol, marks) -} - -/// Why this file may not go on that lane, in the words the refusal is told in -- -/// `None` when it may. A file with no picture belongs on an audio lane and -/// nowhere else, and a still is silent, so an audio lane is the one place it -/// cannot go. Asked twice: by the ghost tinting itself as refused on the way -/// down, and by the insert that commits ([`Player::insert_source`]), so what is -/// shown as impossible is exactly what is refused. -fn lane_refuses(path: &Path, lane: Lane) -> Option { - let name = file_name(path); - let label = lane.label(); - match lane.kind { - LaneKind::Video if engine::is_audio(path) => { - Some(format!("NOT ON {label} — {name} has no picture; drop it on an audio lane")) - } - LaneKind::Audio if engine::is_image(path) => { - Some(format!("NOT ON {label} — {name} is a still image; drop it on a video lane")) - } - _ => None, - } -} - -/// Where down an element a pointer sits, 0..1 from the top: the vertical twin -/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An -/// element that was never painted reads as its middle -- flat, the one answer -/// that changes nothing -- rather than as a full boost. -fn frac_down(y: Pixels, bounds: Bounds) -> f32 { - if bounds.size.height <= px(0.) { - return 0.5; - } - ((y - bounds.top()) / bounds.size.height).clamp(0., 1.) -} - -/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the -/// pointer stops where the arrow keys do and "0.35" on screen is the number the -/// file writes rather than a rounding of one. -fn color_snap(value: f32) -> f32 { - (value / COLOR_STEP).round() * COLOR_STEP -} - -/// How the frame on screen is spread across the tone range: `HIST_BINS` counts -/// per channel, read off the BGRA the decoder handed over -- which is the -/// *graded* picture, because the grade is folded into the conversion -/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye -/// is looking at, and moving a slider moves it. -/// -/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn -/// from eight thousand samples is the same shape, at a thousandth of the reads. -fn histogram(bgra: &[u8]) -> [[u32; HIST_BINS]; 3] { - let pixels = bgra.len() / 4; - let stride = (pixels / HIST_SAMPLES).max(1); - let mut bins = [[0u32; HIST_BINS]; 3]; - for p in (0..pixels).step_by(stride) { - let px = &bgra[p * 4..]; - // BGRA on the wire, `[r, g, b]` in the bins: the graph names channels - // the way a person does. - for (channel, value) in [px[2], px[1], px[0]].into_iter().enumerate() { - bins[channel][usize::from(value) * HIST_BINS / 256] += 1; - } - } - bins -} - -/// The three counts drawn as three lines across the box, tallest bin to the top. -/// -/// Square root, not linear: a shot with a big flat area (a night sky, a title -/// card) puts one bin so far above the rest that a linear graph is a single -/// spike beside a flat line, and the tilt a grade puts in the rest is exactly -/// what the card is for. -fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement { - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let (o, s) = (bounds.origin, bounds.size); - // Shared across the channels, so their relative weight is readable; - // never zero, so an unpumped (all-zero) histogram is a flat line - // rather than a division by nothing. - let top = bins.iter().flatten().copied().max().unwrap_or(0).max(1) as f32; - for (channel, counts) in bins.iter().enumerate() { - let mut path = PathBuilder::stroke(px(1.5)); - for (bin, &count) in counts.iter().enumerate() { - let at = point( - o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32), - o.y + s.height * (1. - (count as f32 / top).sqrt()), - ); - match bin { - 0 => path.move_to(at), - _ => path.line_to(at), - } - } - if let Ok(path) = path.build() { - window.paint_path(path, rgb(HIST_INK()[channel])); - } - } - }, - ) - .absolute() - .size_full() -} - -/// In-place radix-2 FFT of `re`/`im`, whose length must be a power of two. -/// -/// Hand-written, and deliberately: a 1024-point transform once a frame is a -/// few tens of microseconds of plain arithmetic, and a dependency for it would -/// be a build cost this editor pays on every compile for one card's backdrop. -fn fft(re: &mut [f32], im: &mut [f32]) { - let n = re.len(); - // Decimation in time: the input is first put in bit-reversed order, after - // which the butterflies run over neighbours. - let mut j = 0usize; - for i in 1..n { - let mut bit = n >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j |= bit; - if i < j { - re.swap(i, j); - im.swap(i, j); - } - } - let mut span = 2; - while span <= n { - let step = std::f32::consts::TAU / span as f32; - for start in (0..n).step_by(span) { - for k in 0..span / 2 { - // e^{-i2πk/span}: the negative sign is the forward transform. - let (sin, cos) = (-step * k as f32).sin_cos(); - let (a, b) = (start + k, start + k + span / 2); - let (tr, ti) = (cos * re[b] - sin * im[b], cos * im[b] + sin * re[b]); - re[b] = re[a] - tr; - im[b] = im[a] - ti; - re[a] += tr; - im[a] += ti; - } - } - span <<= 1; - } -} - -/// The played signal as one height per curve point, 0 (silence) to 1 (the top -/// of the box) -- the analyser the response curve is drawn on top of. -/// -/// The newest [`EQ_FFT`] samples of the engine's tap, Hann-windowed so a tone -/// that does not land on a bin centre is one hump rather than a smear across -/// the axis. Each column takes the *loudest* bin between it and its -/// neighbours: the axis is logarithmic, so one column near 20 Hz is a fraction -/// of a bin while one near 20 kHz is hundreds, and averaging those would sink -/// every peak up there into the noise beside it. -/// -/// Empty -- nothing to draw -- for a tap too short to transform, which is what -/// a session has just after a seek. -/// -/// corner-cut: one transform length for the whole axis, so the bass end is a bin -/// (47 Hz at 48 kHz) wide however many columns are drawn across it -- a 60 Hz -/// hum and an 80 Hz one are the same hump down there. Upgrade path is the -/// analyser every mastering EQ uses: two or three transforms of different -/// lengths, each drawn over the octaves it resolves. -fn eq_spectrum(samples: &[f32], sample_rate: u32) -> Vec { - if samples.len() < EQ_FFT { - return Vec::new(); - } - let tail = &samples[samples.len() - EQ_FFT..]; - let mut re: Vec = tail - .iter() - .enumerate() - .map(|(i, s)| { - let w = 0.5 * (1. - (std::f32::consts::TAU * i as f32 / EQ_FFT as f32).cos()); - s * w - }) - .collect(); - let mut im = vec![0.; EQ_FFT]; - fft(&mut re, &mut im); - // Magnitude per bin, scaled so a full-scale sine reads 0 dBFS: half the - // energy is in the mirrored half of the transform, and the Hann window - // takes another factor of two off. - let mags: Vec = (0..EQ_FFT / 2) - .map(|k| (re[k] * re[k] + im[k] * im[k]).sqrt() * 4. / EQ_FFT as f32) - .collect(); - let bin_hz = sample_rate as f32 / EQ_FFT as f32; - let (floor, ceiling) = EQ_SPECTRUM_DB; - let at = |along: f32| EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); - (0..=EQ_CURVE_STEPS) - .map(|step| { - let along = step as f32 / EQ_CURVE_STEPS as f32; - let half = 0.5 / EQ_CURVE_STEPS as f32; - // Bin 0 is DC and means nothing here, so the low end starts at 1. - let low = (at(along - half) / bin_hz).round().max(1.) as usize; - let high = (at(along + half) / bin_hz).round().max(1.) as usize; - let peak = (low..=high) - .filter_map(|k| mags.get(k)) - .fold(0f32, |a, &b| a.max(b)); - let db = 20. * peak.max(1e-9).log10(); - ((db - floor) / (ceiling - floor)).clamp(0., 1.) - }) - .collect() -} - -/// The analyser drawn as one filled shape from the floor of the box. -fn eq_spectrum_curve(levels: Vec) -> impl IntoElement { - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let (o, s) = (bounds.origin, bounds.size); - let last = levels.len().saturating_sub(1).max(1) as f32; - let mut path = PathBuilder::fill(); - path.move_to(point(o.x, o.y + s.height)); - for (i, level) in levels.iter().enumerate() { - path.line_to(point( - o.x + s.width * (i as f32 / last), - o.y + s.height * (1. - level), - )); - } - path.line_to(point(o.x + s.width, o.y + s.height)); - path.close(); - if let Ok(path) = path.build() { - window.paint_path(path, rgba(EQ_SPECTRUM_INK())); - } - }, - ) - .absolute() - .size_full() -} - -/// The cascade's frequency response, drawn as one line across the graph, with -/// each band's own response threaded dimly under it. -/// -/// Every point comes from `EqParams::response_db`, which reads the very -/// coefficients the samples are filtered through: the curve cannot drift from -/// what is heard, because there is no second copy of the maths. A single band's -/// thread is that same call on a cascade of one, so the two cannot disagree -/// either -- and it is what makes a boost sitting inside a cut visible at all, -/// where the sum alone would draw a flat line and say nothing. -/// -/// corner-cut: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the -/// curve then rides the edge of the box; upgrade = a wider dB axis with the -/// handles and [`Player::drag_band`] rescaled to it. -fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement { - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let (o, s) = (bounds.origin, bounds.size); - let line = |of: &EqParams| -> Vec<_> { - (0..=EQ_CURVE_STEPS) - .map(|step| { - let along = step as f32 / EQ_CURVE_STEPS as f32; - point( - o.x + s.width * along, - o.y + s.height - * eq_y(of.response_db(eq_freq(along), sample_rate)), - ) - }) - .collect() - }; - // One thread per band, first, so the sum is drawn over them. - for band in ¶ms.bands { - let mut bell = PathBuilder::stroke(px(1.)); - for (step, at) in line(&EqParams { - bands: vec![*band], - }) - .into_iter() - .enumerate() - { - match step { - 0 => bell.move_to(at), - _ => bell.line_to(at), - } - } - if let Ok(bell) = bell.build() { - window.paint_path(bell, rgba(EQ_BELL_INK())); - } - } - let points = line(¶ms); - // The area between the curve and 0 dB, closed along that line: a - // boost and a cut wind opposite ways around it, which is exactly - // what makes both of them fill and the flat parts stay empty. - let mut area = PathBuilder::fill(); - area.move_to(point(o.x, o.y + s.height / 2.)); - for at in &points { - area.line_to(*at); - } - area.line_to(point(o.x + s.width, o.y + s.height / 2.)); - area.close(); - if let Ok(area) = area.build() { - window.paint_path(area, rgba(EQ_FILL_INK())); - } - let mut path = PathBuilder::stroke(px(2.)); - for (step, at) in points.into_iter().enumerate() { - match step { - 0 => path.move_to(at), - _ => path.line_to(at), - } - } - if let Ok(path) = path.build() { - window.paint_path(path, rgb(ACCENT_PRIMARY())); - } - }, - ) - .absolute() - .size_full() -} - - - -/// NLE timecode: `HH:MM:SS:FF`, the frame counted inside its own second. -fn timecode(t: f64, fps: f64) -> String { - let t = t.max(0.); - let secs = t as u64; - let last = (fps.ceil() as u64).saturating_sub(1); - let frame = ((t - secs as f64) * fps) as u64; - format!( - "{:02}:{:02}:{:02}:{:02}", - secs / 3600, - secs / 60 % 60, - secs % 60, - frame.min(last) - ) -} - -/// Wall clock for a progress line: `M:SS`, minutes past the hour included -/// rather than an hours field nobody reads on an export. -fn clock(secs: f32) -> String { - let secs = secs.max(0.) as u64; - format!("{}:{:02}", secs / 60, secs % 60) -} - -/// How long a stage may sit without moving before the import line stops -/// reading like a progress line and says outright that the wait is the file's, -/// not the window's. Five seconds: a 25 GB remux spends eleven in its header -/// alone, and a person watching a still line for that long has already decided -/// the editor hung. -const IMPORT_STALL: f32 = 5.; - -/// Which of an import's two reads the worker is inside. Travels as one atomic, -/// the way an export's progress does ([`engine::ExportHandle`]) -- there is no -/// fraction to send, because neither read reports where in the file it is. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum ImportStage { - /// The container header: the sample tables, the cue index, the frame count. - /// Eleven seconds on a cold 29 GB remux, a hundred and fifty milliseconds - /// once the pages are warm -- the whole reason this runs off the UI thread. - Header, - /// The subtitle tracks inside a Matroska, which is a walk over the file's - /// blocks rather than a header read (~200 ms on a two-hour film). - Subtitles, -} - -impl ImportStage { - /// The atomic the worker writes; `u8` because that is what an - /// [`AtomicU8`](std::sync::atomic::AtomicU8) carries. - fn from_u8(n: u8) -> Self { - match n { - 0 => Self::Header, - _ => Self::Subtitles, - } - } - - /// What the line calls this stage. - fn what(self) -> &'static str { - match self { - Self::Header => "reading the header", - Self::Subtitles => "reading the subtitle tracks", - } - } -} - -/// argv sorted into the file that becomes the timeline and the queue every -/// named file is read through, in the order they were named. The whole of what -/// a launch does before the window is on screen -- and it touches no disk, -/// which is the point: the header walk happens on a worker with the window -/// already up ([`Player::take_import`]). -fn launch_queue( - args: impl Iterator, -) -> (Option, std::collections::VecDeque) { - let queue: std::collections::VecDeque = args.collect(); - (queue.front().cloned(), queue) -} - -/// What a queued file turns into. Every file goes through one queue -- argv's -/// first file, argv's extras, a drop, the Import button -- and this is the fork -/// its worker is started on. -#[derive(PartialEq, Eq, Debug, Clone, Copy)] -enum Landing { - /// The media argv named: it becomes the timeline, and the canvas, the fps, - /// the title and the export path come from it. - Open, - /// A `.edith` argv named: a whole timeline restored, not a source. - Project, - /// Everything else: a row in the library, the timeline untouched. - Import, -} - -/// Which of the three a queued file is (`landing` above is the drag's). -/// `opening` is the one path argv named and is cleared as it lands, so a second -/// arrival of the same *media* path -- a drop of the film that is already open -/// -- is an import, which is what a drop has always been. -/// -/// A `.edith` is never an import, whichever door it came through: it is a whole -/// timeline and there is nothing to add it to. Argv's, a dropped one and the -/// Import button's are one landing, so the seconds its open costs are the -/// worker's for all three ([`open_ahead`]) and the line above the panel names it -/// while it runs. -fn arrival(opening: Option<&std::path::Path>, path: &std::path::Path) -> Landing { - match (is_project(path), opening == Some(path)) { - (true, _) => Landing::Project, - (false, true) => Landing::Open, - (false, false) => Landing::Import, - } -} - -/// The whole of what an import shows while it runs: which file, which stage, -/// the clock that proves the window is still answering, and what is behind it -/// in the queue. -/// -/// `since` is how long the *stage* has stood still, which is the only movement -/// an unmeasurable read has: past [`IMPORT_STALL`] the line says so in words, -/// because a bar that cannot move and a bar that has stopped look identical. -/// -/// `opening` is the file argv named, which is read through the same queue and -/// says so in the same words -- except that it is being *opened*, and a line -/// that called it an import would be describing the wrong thing to the one -/// person who typed the name. -fn import_line( - name: &str, - stage: ImportStage, - elapsed: f32, - since: f32, - waiting: usize, - opening: bool, -) -> String { - let tail = match waiting { - 0 => String::new(), - n => format!(" · {n} more waiting"), - }; - let what = stage.what(); - let verb = match opening { - true => "OPENING", - false => "IMPORTING", - }; - match since >= IMPORT_STALL { - true => format!( - "{verb} {name} · still {what} — a big file is minutes of reading, and the window is \ - not frozen · {} elapsed{tail}", - clock(elapsed) - ), - false => format!("{verb} {name} · {what} · {} elapsed{tail}", clock(elapsed)), - } -} - -/// What opening the silence card on a source costs. -#[derive(PartialEq, Eq, Debug)] -enum ScanPlan { - /// Its levels are already read: the marks are arithmetic on this frame. - Marks, - /// Nothing read: a worker, and a card that says so meanwhile. - Start, - /// A worker is already reading this very source -- the other half of a take - /// names the same file, and a second card on it waits for the first read - /// rather than throwing away the minute already spent. - Wait, -} - -/// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole -/// of the cache policy, and the reason a second film does not cost the first -/// one its levels: what is cached is asked per source, never "the last one". -fn scan_plan(cached: bool, running: Option<&ScanKey>, key: &ScanKey) -> ScanPlan { - match (cached, running) { - (true, _) => ScanPlan::Marks, - (false, Some(at)) if at == key => ScanPlan::Wait, - _ => ScanPlan::Start, - } -} - -/// The half-open source seconds a [`ScanKey`]'s frames name, at the project's -/// rate -- what [`engine::silence::levels`] is asked to read, and the same -/// arithmetic playback puts a clip's `in_frame` through. A rate that is not a -/// rate reads the whole file rather than an empty window: a scan of nothing is -/// worse than a scan of too much. -fn source_secs(key: &ScanKey, fps: f64) -> (f64, f64) { - match fps.is_finite() && fps > 0. { - true => (f64::from(key.2) / fps, f64::from(key.3) / fps), - false => (0., f64::INFINITY), - } -} - -/// What the silence card says while its worker reads. Unlike an import this -/// one *has* a fraction -- a decode knows how far into the sound it has come -- -/// so the line is where it is up to, out of what the header claims the track is -/// (`total` of 0 for a header that does not say, drawn as nothing rather than -/// as a guess). Both in seconds. -/// -/// The stall clock is [`IMPORT_STALL`]'s, for its reason: past five seconds -/// without the mark moving, a line that cannot move and a line that has stopped -/// look identical, and only one of them is worth words. -fn silence_line(scanned: f32, total: f32, elapsed: f32, since: f32) -> String { - let far = match total > 0. { - true => format!("{} of ~{} scanned", clock(scanned), clock(total)), - false => format!("{} scanned", clock(scanned)), - }; - match since >= IMPORT_STALL { - true => format!( - "SCANNING · still reading the sound — a big film is minutes of decoding, and the \ - window is not frozen · {far} · {} elapsed", - clock(elapsed) - ), - false => format!("SCANNING · {far} · {} elapsed", clock(elapsed)), - } -} - -/// How often a progress mark is worth keeping, how far back the rate is -/// measured, and the least span that may answer at all. An export crosses -/// hardware and software segments that run at different speeds, so the -/// estimate is a window's average and never the instant's. -const ETA_SAMPLE: f32 = 0.5; -const ETA_WINDOW: f32 = 8.; -const ETA_SPAN: f32 = 1.5; - -/// Records where the export has got to and forgets what has fallen out of the -/// window. One mark per `ETA_SAMPLE`, a window's worth kept: a bounded list -/// whichever way the encode goes. -fn note_progress(marks: &mut Vec<(f32, f32)>, elapsed: f32, progress: f32) { - if marks.last().is_none_or(|&(t, _)| elapsed - t >= ETA_SAMPLE) { - marks.push((elapsed, progress)); - } - while marks.len() > 2 && marks[0].0 < elapsed - ETA_WINDOW { - marks.remove(0); - } -} - -/// Seconds left at the window's rate, or `None` while nothing measurable has -/// happened yet -- which the line says as "estimating…" rather than as a -/// number it would have to take back. -fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Option { - // A finished pass is not a guess: it is over. - if progress >= 1. { - return Some(0.); - } - if progress <= 0. || elapsed < ETA_SPAN { - return None; - } - // Two rates, averaged. The window's follows the encode across a - // hardware-to-software handover; the whole run's is what keeps a window - // that is all stall from throwing the number minutes out and back. Neither - // alone reads well: raw window rate spikes eightfold on either edge of a - // stall, and the run average alone never notices a segment change. - let overall = progress / elapsed; - let recent = marks - .first() - .filter(|&&(t, _)| elapsed - t >= ETA_SPAN) - .map_or(overall, |&(t, p)| (progress - p) / (elapsed - t)); - Some(2. * (1. - progress) / (recent + overall)) -} - #[cfg(test)] mod tests; diff --git a/crates/app/src/menus.rs b/crates/app/src/menus.rs new file mode 100644 index 0000000..3e19ccb --- /dev/null +++ b/crates/app/src/menus.rs @@ -0,0 +1,254 @@ +//! The lists the window opens over itself: the clip menu, the pickers, the key rows. + +use crate::*; + +/// An open clip menu: which clip it was opened on, where it hangs, and whether +/// it has been turned over to show what that clip *is* instead of what can be +/// done to it. The lane and index are the ones the same click selected, so +/// every item acts on exactly the box under the pointer. +#[derive(Clone, Copy)] +pub(crate) struct ContextMenu { + pub(crate) lane: Lane, + pub(crate) idx: usize, + pub(crate) at: Point, + pub(crate) details: bool, +} + +/// An open library menu: which row it was opened on -- the file and the stream, +/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a +/// probe landing, a source going) cannot slide another row beneath the menu the +/// way a row *index* would -- where it hangs, and whether it has been turned +/// over to show what the file *is*. +#[derive(Clone)] +pub(crate) struct LibraryMenu { + pub(crate) path: PathBuf, + pub(crate) stream: usize, + pub(crate) at: Point, + pub(crate) details: bool, +} + +/// An open choice list: which setting it offers and where it hangs. What a +/// button that stepped one value on per click used to be -- a setting with more +/// than two values is a list to look at, not a thing to click round. Placed by +/// [`menu_at`] and closed by a stroke, exactly like the two menus above it. +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct Picker { + pub(crate) of: Pick, + pub(crate) at: Point, + /// Which row the keyboard is on, from the value in force when the list + /// opened. The list answers ↑↓ and enter as well as a click: a setting whose + /// only door is a pointer is a setting half this editor's users cannot + /// reach, which is the rule `FIXED` already writes down for every card. + pub(crate) sel: usize, +} + +/// Which setting an open list is offering. The fit policy names the clip it is +/// about, like the clip menu it opens from -- indices move under every edit, so +/// the list closes on the first stroke as that menu does. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Pick { + Resolution, + Fps, + Fit(Lane, usize), + /// What the export's *sound* is coded at. Opened from the card's Sound row, + /// which is the only place it means anything. + AudioRate, + /// Which HDR-to-SDR rendition the project is watched and exported in + /// ([`engine::tonemap::Preset`]). Opened from the panel, beside the two + /// other settings that are the project's rather than the media's. + Tone, + /// Which palette the window is painted in ([`ui::theme`]). The one setting + /// here that is nobody's project: it is the person's, so it outlives the + /// timeline and every file opened in it. + Theme, +} + +/// One value a list offers, carrying everything picking it needs -- so a click +/// goes straight to the value rather than to a position in a list that was +/// built somewhere else. +/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told, +/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a +/// choice -- comparing two is all a list row ever does. +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum Choice { + Size(u32, u32), + Fps(f64), + Fit(Lane, usize, FitPolicy), + AudioRate(u32), + Tone(Preset), + Theme(ui::theme::PaletteId), +} + +/// One row of an open list: the value, its name, the small print beside it, and +/// whether it is the one in force. +pub(crate) type ChoiceRow = (Choice, SharedString, SharedString, bool); + +/// What a library row's menu offers, in the order it lists them. Unlike the clip +/// menu's items none of these is a stroke -- there is no keyboard way to a row -- +/// so the label and the hint are written here rather than read off the keymap. +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum RowItem { + Add, + Remove, + Reveal, + Properties, +} + +pub(crate) const ROW_ITEMS: [RowItem; 4] = [ + RowItem::Add, + RowItem::Remove, + RowItem::Reveal, + RowItem::Properties, +]; + +impl RowItem { + pub(crate) fn label(self) -> &'static str { + match self { + Self::Add => "Add at playhead", + Self::Remove => "Remove from library", + Self::Reveal => "Reveal in files", + Self::Properties => "Properties", + } + } + + /// The dim right-hand column, where the clip menu prints the stroke: what + /// the item will do to the timeline, so nothing here is a surprise. + pub(crate) fn hint(self) -> &'static str { + match self { + // Short enough to sit beside its label inside `MENU_W`, the clip + // menu's rule for a refusal: this column truncates, and a hint cut + // off mid-word says less than a shorter one. + Self::Add => "the whole file", + Self::Remove => "nothing plays it", + Self::Reveal => "file manager", + Self::Properties => "…", + } + } +} + +/// What the menu offers, in the order it lists them. Every one of these is an +/// action a stroke already reaches -- the menu is a second way *to* the actions +/// and never a second version of them -- so both the label and the hint come +/// out of the keymap registry and the two can never disagree. +pub(crate) const MENU_ITEMS: [ActionId; 14] = [ + ActionId::Cut, + // The clipboard pair, which had no door but a chord: copy takes the clip the + // menu names, and paste is the timeline's rather than this clip's -- the + // same kind of global item the mute below already is. + ActionId::Copy, + ActionId::Paste, + ActionId::Delete, + ActionId::Lift, + ActionId::Regroup, + ActionId::Detach, + ActionId::Group, + ActionId::Equalizer, + ActionId::Speed, + // The scan is a clip card like the two above it -- opened on whichever half + // was clicked -- and a card only a stroke could open is one a pointer never + // finds. + ActionId::Silence, + ActionId::Color, + ActionId::Fit, + ActionId::ToggleMute, +]; + +/// One row of the actions card, in the order it lists them: a heading, then +/// every action the registry files under it, then the strokes the modal cards +/// answer themselves. +/// +/// A list rather than a loop inside the render, so the card and +/// `every_action_is_on_the_actions_card` read the *same* order: an action that +/// reaches no row fails a test instead of quietly becoming pointer-unreachable. +pub(crate) enum KeyRow { + Head(keymap::Category), + /// Click its label to do it, click its stroke to change that stroke. + Act(ActionId), + /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may + /// unbind the way out of a card. + Fixed(usize), +} + +/// Every action, under its heading, and the card-local strokes beside them. +/// Generated from the registry -- [`ActionId::ALL`] in its own order, under +/// [`keymap::Category::ALL`] -- so an action added there is on the card the +/// moment it exists and there is no second list here to forget. +pub(crate) fn keys_rows() -> Vec { + let mut rows = Vec::new(); + for category in keymap::Category::ALL { + rows.push(KeyRow::Head(category)); + rows.extend( + ActionId::ALL + .into_iter() + .filter(|a| a.category() == category) + .map(KeyRow::Act), + ); + rows.extend( + keymap::FIXED + .iter() + .enumerate() + .filter(|(_, f)| f.category == category) + .map(|(i, _)| KeyRow::Fixed(i)), + ); + } + rows +} + +/// [`keys_rows`] with a search applied: the rows whose label or whose stroke +/// carries `needle`, and the heading each one lives under. A heading with +/// nothing left beneath it goes with them -- an empty "Playback" over a gap +/// reads as a list that lost its rows rather than as a search that found none. +/// +/// Each row keeps the index it has in the unfiltered list, so an element id is +/// the same one before and after a keystroke: filtering is a look at the list, +/// and gpui's per-element state is keyed on that id. +/// +/// Case-insensitive substring, on both columns: people look for an action by +/// what it does ("vol") and for a stroke by what they pressed ("ctrl"). +pub(crate) fn keys_filter(needle: &str, keymap: &Keymap) -> Vec<(usize, KeyRow)> { + let needle = needle.trim().to_lowercase(); + let rows = keys_rows().into_iter().enumerate(); + if needle.is_empty() { + return rows.collect(); + } + let hit = |label: &str, chord: &str| { + label.to_lowercase().contains(&needle) || chord.to_lowercase().contains(&needle) + }; + let mut out: Vec<(usize, KeyRow)> = Vec::new(); + // The heading above the row being looked at, until a row under it earns it + // a place -- then it goes in once, ahead of that row. + let mut pending: Option<(usize, KeyRow)> = None; + for (i, row) in rows { + match &row { + KeyRow::Head(_) => pending = Some((i, row)), + KeyRow::Act(action) => { + if hit(action.label(), &keymap.display(*action)) { + out.extend(pending.take()); + out.push((i, row)); + } + } + KeyRow::Fixed(f) => { + let fixed = &keymap::FIXED[*f]; + if hit(fixed.label, &fixed.chord) { + out.extend(pending.take()); + out.push((i, row)); + } + } + } + } + out +} + +/// The character a stroke types into the actions card's search box, if it types +/// one. gpui reports a printable key as itself and the space bar by name +/// (platform.rs:866), and everything else -- the arrows, the function keys -- +/// is a word this must not spell into the box letter by letter. +pub(crate) fn typed(key: &str) -> Option { + match key { + "space" => Some(' '), + _ => key + .chars() + .next() + .filter(|c| c.is_ascii_graphic() && key.chars().count() == 1), + } +} diff --git a/crates/app/src/notices.rs b/crates/app/src/notices.rs new file mode 100644 index 0000000..c15198f --- /dev/null +++ b/crates/app/src/notices.rs @@ -0,0 +1,45 @@ +//! The notice bar's queue. + +use crate::*; + +/// How many messages wait behind the one on the bar before the oldest is +/// dropped. A queue with no ceiling is a way for a stuck loop to eat the heap; +/// eight is more than a user will ever answer in a row. +pub(crate) const NOTICES_MAX: usize = 8; + +/// The narrowest a notice's *message* is allowed to be squeezed before its hint +/// gives up the line and drops below it. +/// +/// The bar is a message beside a hint, and at the 640x360 floor the picture +/// region it hangs under is narrower than the hint alone -- so the message was +/// squeezed to nothing and wrapped one character per line, which is a failure +/// rendered as a column of letters. Wide enough that a line of it is a phrase +/// rather than a word ladder, and narrow enough to still fit beside the hint in +/// any window worth putting two things on a line in. +pub(crate) const NOTICE_MIN_W: f32 = 180.; + +/// The whole of the queue's policy, where it can be read at once and tested +/// without a window: dedupe against the back, a ceiling, oldest out first. +/// [`Player::notify_user`] is the door every message comes through; this is what +/// the door does. +pub(crate) fn push_notice(notices: &mut std::collections::VecDeque, message: SharedString) { + // A repeat of what is already at the back is dropped -- holding a key that + // refuses would otherwise fill the queue with one sentence, and the count on + // the bar would be a count of how long the key was held. + if notices.back() == Some(&message) { + return; + } + if notices.len() >= NOTICES_MAX { + notices.pop_front(); + } + notices.push_back(message); +} + +/// The tail an open/load notice grows when the file has sound the engine cannot +/// decode: it plays perfectly, in silence, and that is the one thing the window +/// would otherwise never say (the engine's own word for it, verbatim). +pub(crate) fn audio_notice(session: &PlaybackSession) -> Option { + session + .audio_disabled_reason() + .map(|reason| format!(" — NO AUDIO: {reason}")) +} diff --git a/crates/app/src/oracle.rs b/crates/app/src/oracle.rs new file mode 100644 index 0000000..bd6e7e6 --- /dev/null +++ b/crates/app/src/oracle.rs @@ -0,0 +1,293 @@ +//! Whether an action can be asked for -- the one answer every surface reads. + +use crate::*; + +/// Whether an action can be asked for, and what to say when it cannot. Two +/// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at +/// -- an audio clip has no picture, so a grade is not a thing that exists for +/// it, whatever the editor does next -- and `No` is about the state of this +/// moment, which the next click of the playhead can change. The clip menu +/// leaves the class refusals *out* and dims the state ones ([`Enable::listed`]); +/// the actions card, which is the whole registry laid out, dims both with their +/// reason -- an action missing from the one surface that lists everything would +/// read as an action that does not exist. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Enable { + Yes, + No(&'static str), + Hidden(&'static str), +} + +impl Enable { + /// Whether the row takes a click. + pub(crate) fn yes(self) -> bool { + self == Enable::Yes + } + + /// Whether a menu *about this clip* draws the row at all: a class refusal + /// is a thing that does not exist for what was clicked, and a row nothing + /// the user does could ever light is noise between the ones they came for. + pub(crate) fn listed(self) -> bool { + !matches!(self, Enable::Hidden(_)) + } + + /// What the row says instead of its stroke, if it says anything. + pub(crate) fn why(self) -> Option<&'static str> { + match self { + Enable::Yes => None, + Enable::No(why) | Enable::Hidden(why) => Some(why), + } + } +} + +/// What an enablement question is asked *about*: the clip in question, if there +/// is one, and the little of the editor's state the answers need. Handed in +/// rather than read off the player, so [`enable`] is a pure function a test can +/// ask about a clip without building a window. +#[derive(Clone, Copy, Default)] +pub(crate) struct Ctx { + /// The clip the question is about -- the one a menu was opened on, or the + /// marked one. `None` means the question is about the editor as a whole, + /// and the clip-relative answers stand aside: those actions find their own + /// clip under the playhead and word their own refusal. + pub(crate) clip: Option<(Clip, Lane)>, + /// The clip plays a still ([`engine::is_image`]), which has no sound to + /// reach at all -- not the lane's business, because a still sits on a video + /// lane exactly like a take whose sound is one lane down. + pub(crate) image: bool, + pub(crate) playhead: u32, + /// A timeline is open. + pub(crate) timeline: bool, + /// Something has been copied. + pub(crate) clipboard: bool, + /// This timeline has at least one subtitle track: a toggle with nothing to + /// show is a switch that does nothing, and it says so rather than flipping. + pub(crate) subtitles: bool, + /// There is something on the lanes to play. A transport with nothing under + /// it is the one refusal that is about the timeline's contents rather than + /// about a clip. + pub(crate) playable: bool, + pub(crate) exporting: bool, +} + +/// Whether `action` can be asked for, on `ctx`. One arm per action and nothing +/// else in the editor asks the question: the clip menu dims a row with this, +/// the actions card dims a row with this, and the two can never come to +/// disagree about what an action needs -- exactly the reason [`Player::act`] is +/// one table too. +pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable { + // The one action that is about the editor rather than about the timeline: + // the list of what everything does, and where a key is changed. An empty + // window has no clips and still has keys -- so this answers ahead of the + // timeline question, and only an export shuts it (a waiting row would + // swallow the escape the progress line promises cancels the export). + // The window's own colours: there is always a window, and repainting it + // touches no timeline -- so this one is live even while an export is + // reading one, which is the only state that dims the list above. + if action == ActionId::Theme { + return Enable::Yes; + } + if action == ActionId::ShowActions { + return match ctx.exporting { + true => Enable::No("an export is running"), + false => Enable::Yes, + }; + } + // The four that are about the *editor* and its monitoring rather than + // about the edit list: they work with nothing open, the keyboard has + // always fired them there, and so their buttons are live there too. + if matches!( + action, + ActionId::ToggleSnap | ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown + ) { + return match ctx.exporting { + true => Enable::No("an export is running"), + false => Enable::Yes, + }; + } + if !ctx.timeline { + return Enable::No("no timeline open"); + } + // An export is reading the edit list every other action would change, which + // is the rule the key handler already follows. + if ctx.exporting { + return match action { + ActionId::CancelExport => Enable::Yes, + _ => Enable::No("an export is running"), + }; + } + match action { + // -- class: what kind of thing the action is about. The equalizer + // filters samples, and a video clip has none of its own here: the sound + // is the audio lane's, clip for clip. + ActionId::Equalizer => match ctx.clip { + Some((_, lane)) if lane.kind != LaneKind::Audio => Enable::Hidden("this clip is picture"), + _ => Enable::Yes, + }, + // A grade is a picture setting and an audio clip has no picture. A fit + // policy is a picture setting for the same reason. + ActionId::Color | ActionId::Fit => match ctx.clip { + Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"), + _ => Enable::Yes, + }, + // The scan reads samples, and a still has none -- ever, unlike a video + // clip whose sound may be one lane down or simply silent. Exactly what + // `unscannable` says after the fact, said before the row is drawn so + // there is no row left to click. + ActionId::Silence if ctx.image => Enable::Hidden("this clip is a still"), + // -- state: true of this clip now, and the next playhead click or the + // next selection changes the answer. Splits this clip only from inside + // it: at either edge there is nothing to split off -- and, on a speeded + // clip, only at a frame its own rate can address, which is the same + // question `splittable` asks. + ActionId::Cut => match ctx.clip { + Some((clip, _)) if !(clip.start < ctx.playhead && ctx.playhead < clip.end()) => { + Enable::No("only from inside a clip") + } + // Inside it, and still not a cut: a slowed clip shows one frame of + // the file for several frames of the timeline, and only the first of + // those is a frame the file has ([`Speed::split_at`]). Cutting + // between two showings of one frame would leave halves whose lengths + // no longer add up, so it is refused -- and it says *that* rather + // than repeating "inside a clip" at a playhead that plainly is. + Some((clip, _)) + if clip + .speed + .split_at(clip.len(), ctx.playhead - clip.start) + .is_none() => + { + Enable::No("this speed holds one frame here — step to the next") + } + _ => Enable::Yes, + }, + // Rejoins whatever meets at the playhead, so it can mean something only + // at an edge of this clip. Whether those two halves were ever one take + // is the engine's question, and it words that refusal itself. + ActionId::Regroup => match ctx.clip { + Some((clip, _)) if ctx.playhead != clip.start && ctx.playhead != clip.end() => { + Enable::No("only where two clips meet") + } + _ => Enable::Yes, + }, + // Nothing to take apart in a clip that names no group at all. Whether + // the group it names still has another half is the engine's question, + // like the regroup above. + ActionId::Detach => match ctx.clip { + Some((clip, _)) if clip.link.is_none() => Enable::No("this clip is not grouped"), + _ => Enable::Yes, + }, + // The three that act on the marked clip and on nothing else: with none + // marked they would silently do nothing, which is what the Delete + // button's own dimming has always said. + ActionId::Copy | ActionId::Delete | ActionId::Lift if ctx.clip.is_none() => { + Enable::No("click a clip first") + } + ActionId::Paste if !ctx.clipboard => Enable::No("nothing copied yet"), + // Nothing to draw over the picture, so nothing to switch off: the + // library says how subtitles arrive, and this row would flip a state + // with no visible half either way. + // ...and nothing to take off the timeline either, for the same reason: + // the row would name a track that is not there. + ActionId::ToggleSubtitles | ActionId::RemoveSubtitleTrack if !ctx.subtitles => { + Enable::No("no subtitles yet") + } + // Not `No`: with nothing running there is no export for this to be + // about at all, which is what keeps `esc` -- the same key -- a quiet + // way out of a card rather than a line about exports. + ActionId::CancelExport => Enable::Hidden("nothing is exporting"), + // A clock started against an empty timeline is a clock counting + // nothing: the transport says so by being dim, which is what its own + // ad-hoc boolean used to say before the oracle knew the question. + ActionId::Play if !ctx.playable => Enable::No("put a clip on a lane first"), + // A rate applies to a clip of either kind and to its whole group, so + // there is no lane it means nothing on, and the engine words the one + // refusal there is (no room). Everything else is the editor's own and + // needs nothing but a timeline. + _ => Enable::Yes, + } +} + +/// The rows a clip menu draws, for the clip it was opened on: the registry +/// filtered by the one availability oracle, and the *only* way that menu is +/// built. An action that means nothing for what was right-clicked -- a grade on +/// a waveform, an equalizer on a picture -- is not a row at all, so a future +/// action cannot appear where it does not apply by being added to +/// [`MENU_ITEMS`] alone. +pub(crate) fn menu_items(ctx: Ctx) -> Vec { + MENU_ITEMS + .into_iter() + .filter(|&action| enable(action, ctx).listed()) + .collect() +} + +/// What a library row's items are asked *about*: the file that was +/// right-clicked and the little of the editor's state the answers need. The +/// library's [`Ctx`], handed in for the same reason. +#[derive(Clone, Copy, Default)] +pub(crate) struct RowCtx { + /// A timeline to put it on. + pub(crate) timeline: bool, + pub(crate) exporting: bool, + /// This row can join *this* timeline: what greys it in the list, and what + /// the engine would otherwise refuse the Add with after the click. + pub(crate) usable: bool, + /// How many clips play this exact row -- a source with any is one the + /// engine will not take out of the list. + pub(crate) placed: usize, +} + +/// Whether a library row's item can be asked for. The library's half of +/// [`enable`], and the same rule: one table, no second policy in the render. +pub(crate) fn row_enable(item: RowItem, ctx: RowCtx) -> Enable { + match item { + // The two that change the timeline, so an export reading it stops them + // both -- the key handler's rule, applied to a menu. + RowItem::Add | RowItem::Remove if ctx.exporting => Enable::No("an export is running"), + RowItem::Add | RowItem::Remove if !ctx.timeline => Enable::No("no timeline open"), + // Dimmed and saying why rather than clicked and refused afterwards: the + // row's own grey already says the file cannot join this timeline. + RowItem::Add if !ctx.usable => Enable::No("it cannot join this one"), + RowItem::Remove if ctx.placed > 0 => Enable::No("clips play it"), + // Neither of these touches the timeline: a file can be found on disk and + // described whatever the editor is doing, with no timeline at all. + _ => Enable::Yes, + } +} + +/// The rows a library menu draws, for the row it was opened on -- the clip +/// menu's [`menu_items`] on the other panel, and the only way that menu is +/// built. +pub(crate) fn row_items(ctx: RowCtx) -> Vec { + ROW_ITEMS + .into_iter() + .filter(|&item| row_enable(item, ctx).listed()) + .collect() +} + +/// How tall a menu's list may draw: the whole of it where the window has room, +/// and what the window has where it has not -- only then does the list scroll. +/// A cap fixed at twelve rows put the last items behind a scroll on a window +/// with room to spare, which reads as a menu cut off by the bottom edge. +pub(crate) fn menu_rows_h(rows: usize, viewport: Size) -> f32 { + let room = f32::from(viewport.height) - MENU_PAD * 2.; + (rows as f32 * MENU_ROW_H).min(room.max(MENU_ROW_H)) +} + +/// Where the menu actually hangs: at the pointer, pulled back inside the window +/// when it would not fit -- an item off the bottom edge is an item nobody can +/// click. Never negative, so a window smaller than the menu loses the bottom of +/// it rather than the top, where the items are. +pub(crate) fn menu_at(at: Point, viewport: Size, height: f32) -> (f32, f32) { + let fit = |v: f32, size: f32, room: f32| v.min(room - size).max(0.); + ( + fit(f32::from(at.x), MENU_W, f32::from(viewport.width)), + fit(f32::from(at.y), height, f32::from(viewport.height)), + ) +} + +/// Whether the Add button does anything: a row picked, a timeline to put it on, +/// and no export reading that timeline. A button that would do nothing is dimmed +/// and takes no click, like every other one here. +pub(crate) fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -> bool { + picked.is_some() && timeline && !exporting +} diff --git a/crates/app/src/subs.rs b/crates/app/src/subs.rs new file mode 100644 index 0000000..ae9fd2d --- /dev/null +++ b/crates/app/src/subs.rs @@ -0,0 +1,589 @@ +//! Subtitles: what is parsed, what is listed and what is drawn. + +use crate::*; + +/// Whether a dropped or named path is a subtitle file rather than media: the +/// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s +/// reason -- the import door has to know which of the engine's two doors a file +/// goes through before anything is opened. +/// +/// `.mks` is one of them, and it is the only Matroska extension that is: it is +/// the *subtitles alone*, so there is no source in it to import and a drop of +/// one used to be refused for having no video track -- while `+ S` on the same +/// bytes took it ([`PlaybackSession::parse_subtitles`] reads it as Matroska). +/// The other two are media and stay media: `.mka` is the sound alone, which +/// [`engine::is_audio`] already imports as a song, and `.mk3d` is a film. Both +/// may *carry* subtitles, which is [`carries_subtitles`] and not this. +pub(crate) fn is_subtitle(path: &std::path::Path) -> bool { + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e.to_ascii_lowercase().as_str(), + "srt" | "vtt" | "webvtt" | "ass" | "ssa" | "mks" + ) + }) +} + +/// Whether a media path is a container that can carry subtitle tracks *inside* +/// it -- every Matroska extension and the three ISO-BMFF ones, which is the list +/// [`PlaybackSession::parse_subtitles`] walks (Matroska blocks and mp4 `tx3g` +/// alike). Named for what it gates and not for one of the two families, because +/// an mp4 answers `true` here now. +/// +/// Matroska's set is the standard's own and closed by it +/// (`engine::demux::is_matroska`), so it is copied whole rather than trimmed to +/// the two that carry a film: a `.mk3d` opened as media has its tracks walked +/// like the `.mkv` it is, and a `.mka` song can hold a lyric track. A suffix +/// wider than the engine's would be a file taken here and refused deeper down. +pub(crate) fn carries_subtitles(path: &std::path::Path) -> bool { + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e.to_ascii_lowercase().as_str(), + "mkv" | "mka" | "mks" | "mk3d" | "webm" | "mp4" | "m4v" | "mov" + ) + }) +} + +/// What a worker hands back, which is the fork [`arrival`] made when it was +/// started. An import is *read* and thrown away; the file argv named is opened +/// outright, because nothing else is going to open it afterwards. +pub(crate) enum Landed { + /// An import into a timeline that is up: the container probed and the + /// subtitle tracks walked, both *kept* -- they are the expensive halves and + /// the worker is where they belong, so [`Player::take_import`] is left with + /// two pushes ([`engine::PlaybackSession::import_probed`], + /// [`subtitle_tail`]). + Read(Subs, Probe), + /// A whole timeline the worker opened, with the tail its subtitle tracks + /// earn, ready to be hung off the window -- or the engine's refusal. `true` + /// is the media argv named, which *becomes* the timeline; `false` is a file + /// arriving at a window that had none, which fills the library and leaves + /// the lanes empty for a drag ([`Player::install_media`]). + Media(Result<(PlaybackSession, String), String>, bool), + /// A `.edith`, restored: argv's, and the one a drop or the Import button + /// brought ([`arrival`]). + Project(Result), +} + +/// What the container walk found, for [`Player::take_import`] to register, or +/// the engine's refusal in the words it would have used on the UI thread. +/// +/// `None` for the doors that never reach a demuxer: a song, a still and a +/// subtitle file, whose own small reads stay where they were +/// ([`engine::PlaybackSession::import`]). +pub(crate) type Probe = Option>; + +/// A media file opened as a session, with the subtitle tracks it carries inside +/// it taken in the same breath -- the two reads a file costs, in the one place +/// both doors ([`Player::open_media`] and the worker below) go through. +/// +/// `place` is which door: a file *opened* is the timeline, one *imported* into +/// an empty window fills the library and leaves the lanes empty for a drag. +pub(crate) fn open_session( + path: &std::path::Path, + place: bool, + subs: Subs, +) -> Result<(PlaybackSession, String), String> { + let opened = match place { + true => PlaybackSession::open(path), + false => PlaybackSession::open_library(path), + }; + let mut session = opened.map_err(|e| e.to_string())?; + let tail = subtitle_tail(&mut session, subs).unwrap_or_default(); + Ok((session, tail)) +} + +/// The whole of what a queued file costs, off the UI thread. An import only +/// needs its pages warmed ([`read_ahead`]); the file argv named is *opened* +/// here instead, and that is the difference between a warm launch paying for +/// one header walk and paying for two -- the window is up either way. +pub(crate) fn open_ahead( + what: Landing, + path: &std::path::Path, + stage: &std::sync::atomic::AtomicU8, + gate: Option, +) -> Landed { + match what { + Landing::Import => read_ahead(path, stage, gate), + Landing::Project => { + let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string()); + Landed::Project(opened) + } + Landing::Open => open_whole(path, true, stage), + } +} + +/// A whole timeline, opened here and handed over: the file argv named (`place`, +/// which *is* the timeline) and a file arriving at a window with no timeline to +/// import into, which fills the library instead. One function because they are +/// one read -- the engine's two doors differ by which lanes come up empty +/// ([`engine::PlaybackSession::open_library`]), not by what they walk. +pub(crate) fn open_whole(path: &std::path::Path, place: bool, stage: &std::sync::atomic::AtomicU8) -> Landed { + use std::sync::atomic::Ordering::Relaxed; + let opened = match place { + true => PlaybackSession::open(path), + false => PlaybackSession::open_library(path), + }; + // The same two stages a read reports, because they are the same two + // reads: the container, and then the tracks inside it. + stage.store(ImportStage::Subtitles as u8, Relaxed); + Landed::Media( + opened.map_err(|e| e.to_string()).map(|mut session| { + let subs = subtitle_notice(&mut session, path).unwrap_or_default(); + (session, subs) + }), + place, + ) +} + +/// Reads, off the UI thread, everything the import that follows would have read +/// -- and hands all of it over. Nothing here is a warm-up any more: the +/// container is *probed* ([`engine::PlaybackSession::probe_import`]) and the +/// subtitle tracks are *walked*, and [`Player::take_import`] registers what came +/// back. Measured on the 24 GB 4K HEVC remux: 21.4 s of header cold, 429 ms +/// warm, plus 1-4 s of probing the timeline's own first source, plus the cue +/// walk -- all of it here, and the window keeps painting through it. +/// +/// `gate` is the timeline the file is checked against +/// ([`engine::PlaybackSession::import_gate`]), taken before the worker started +/// because a worker cannot reach the session. `None` is a window with no +/// timeline to import into: then there is nothing to check against and nothing +/// to register, so the file is *opened* here instead, whole +/// ([`open_whole`]) -- which is the same twenty seconds, on the same thread, +/// rather than on the one that draws. +/// +/// The header error is carried back now rather than dropped: it is the engine's +/// own refusal, from the only walk anybody makes, so it is worded once and shown +/// at the landing. The subtitle refusal travels beside it for the same reason. +/// +/// `stage` is what the line above the panel is naming while this runs. +pub(crate) fn read_ahead( + path: &std::path::Path, + stage: &std::sync::atomic::AtomicU8, + gate: Option, +) -> Landed { + use std::sync::atomic::Ordering::Relaxed; + stage.store(ImportStage::Header as u8, Relaxed); + // Nothing to import into, and nothing a subtitle file needs opened: the + // first opens the library itself, here; the second has no container at all. + let Some(gate) = gate else { + return match is_subtitle(path) { + true => Landed::Read(walk_subtitles(path), None), + false => open_whole(path, false, stage), + }; + }; + // The three doors an import goes through: a song is measured by its + // duration and a still by its header -- both the engine's own reads, warmed + // here and paid again at the landing, which is a header apiece -- and + // everything else is the container walk, which is handed over whole. + let probe = if engine::is_audio(path) { + engine::AudioSession::duration_secs(path).ok(); + None + } else if engine::is_image(path) || is_subtitle(path) { + None + } else { + Some(PlaybackSession::probe_import(gate, path)) + }; + stage.store(ImportStage::Subtitles as u8, Relaxed); + // ...and the tracks inside it, kept. + Landed::Read(walk_subtitles(path), probe) +} + +/// Every subtitle track a file carries, cues and all -- the walk that costs, in +/// the one place every door that pays it goes through. `Ok` and empty for a file +/// with none to read, which is what a file that is neither a container we can +/// walk ([`carries_subtitles`]) nor a subtitle file is: the same answer +/// `add_subtitle_tracks` gives it, and nothing is opened to find that out. +/// +/// Nothing in here is a session, on purpose ([`PlaybackSession::parse_subtitles`] +/// is an associated fn): no borrow crosses the await, so this runs whole on a +/// worker while the window keeps painting. +pub(crate) fn walk_subtitles(path: &std::path::Path) -> Subs { + match carries_subtitles(path) || is_subtitle(path) { + true => PlaybackSession::parse_subtitles(path), + false => Ok(Vec::new()), + } +} + +/// The subtitle tracks a media file carries, taken into the session as it is +/// opened, and the tail the notice grows for them: an mkv or an mp4 with +/// subtitles in it arrives with its subtitles, because a track nobody imported +/// is a track nobody knows is there. Every other container answers `None` +/// without being read. +/// +/// A refusal is a tail too, never a failure of the open: the picture and the +/// sound of a film whose subtitle tracks cannot be walked are still the film. +/// +/// Both halves at once, which only a *worker* may do: the walk reads the whole +/// file for its cues (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour +/// 4K remux, 9.7 s on a cold 25 GB one. The one caller is the open beside which +/// this runs on the worker ([`open_ahead`]), never the render thread; an +/// import splits the two halves across the hop instead ([`read_ahead`] walks, +/// [`subtitle_tail`] pushes). +pub(crate) fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option { + subtitle_tail(session, walk_subtitles(path)) +} + +/// What a subtitle walk ([`walk_subtitles`]) gave, on its way from whichever +/// thread paid for it to the timeline. `Send` all the way down (`sendable()`, +/// `engine/tests/subtitles.rs`), which is what lets the walk be a worker's. +pub(crate) type Subs = engine::Result>; + +/// The tail a file's own subtitle tracks earn on the notice that names it, and +/// the push that puts them on the timeline -- the second half of the walk, the +/// cheap one ([`PlaybackSession::add_subtitle_tracks`]: no open, no seek, no +/// decode). Every door that arrives with a *file* words it here, once: the file +/// argv named, an import, and an import into an empty window cannot say the same +/// thing differently, whichever thread read the cues. +/// +/// `None` for a file that gave none and for one whose tracks are on the timeline +/// already -- an import that adds nothing says nothing about subtitles. A +/// refusal is a tail too, never a failure of the import: the picture and the +/// sound of a film whose subtitle tracks cannot be walked are still the film. +pub(crate) fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option { + match subs { + Ok(tracks) => match session.add_subtitle_tracks(tracks) { + 0 => None, + n => Some(format!(" — {n} subtitle track(s) in the file")), + }, + Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")), + } +} + +/// The push both deliberate add-subtitles doors end on -- `+ S` and its key +/// ([`Player::add_subtitles`]) and a dropped or argv'd subtitle file +/// ([`Player::take_subtitles`]) -- so the two cannot come to word the same file +/// differently. +/// +/// The walk having found *nothing* is a refusal and not a count: a container +/// with no subtitle track in it and a file whose tracks are all on the timeline +/// already both push zero rows, and they are opposite answers -- one says look +/// somewhere else, the other says you already have them. The engine's own door +/// draws the same line in the same words +/// ([`PlaybackSession::no_subtitles_in`], asked here because this route splits +/// the walk from the push to keep the walk off the render thread). +/// +/// The file itself joins nothing either way: no library row, no lane, no clip. +/// Subtitles are a list the timeline carries, and this is the only thing that +/// touches it. +pub(crate) fn pushed( + session: &mut PlaybackSession, + path: &std::path::Path, + tracks: Vec, +) -> engine::Result { + match tracks.is_empty() { + true => Err(PlaybackSession::no_subtitles_in(path)), + false => Ok(session.add_subtitle_tracks(tracks)), + } +} + +/// What a subtitle row says under its name: how many cues it holds and whether +/// they are pictures ([`engine::subtitle::SubtitleTrack::is_bitmap`]) -- which +/// is the difference between a track an export writes into the file and one it +/// can only draw -- or, for a track that could not be read, the engine's own +/// reason verbatim. A refusal is still what a row can be *for*: a VobSub track +/// dropped from the list would say the film has no subtitles at all. +pub(crate) fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String { + match (&track.refused, track.is_bitmap()) { + (Some(why), _) => why.clone(), + (None, true) => format!("{} cues — pictures", track.cues.len()), + (None, false) => format!("{} cues", track.cues.len()), + } +} + +/// What the export card's Subtitles row says: the engine's own words for the +/// tracks an export carries (`plan`, [`engine::export::planned_subtitles`] asked +/// about `picks`) and, beside them, the rows it is carrying nothing of. +/// +/// `picks` is [`Player::export_subs`] -- every track with a cue left in the +/// exported range -- so a track sitting in the list with eighty-three cues +/// nowhere near a trimmed timeline never reaches the engine at all, and the card +/// said nothing about it while the list went on showing it. Which tracks have +/// cues *here* is this side's answer and nobody else's, so this side words it. +/// +/// Past [`SUB_PLAN_CHARS`] the line counts rather than names: every name is more +/// words in a value box `MENU_W` wide, and at 35 tracks the row wrapped to ten +/// lines and pushed the Destination row under the fold of the card. The names +/// are still one row each in the Subtitles list, with the cue count and the +/// reason under them ([`subtitle_detail`]) -- more than this line ever said. +/// +/// The counted split follows the engine's own order of reasons (`refused`, then +/// pictures, then no cues), with the last asked of the timeline instead of the +/// track. +/// +/// corner-cut: that split reads the same public fields the list rows read +/// (`refused`, [`engine::subtitle::SubtitleTrack::is_bitmap`]) rather than the +/// engine's decision, so a *new* reason to drop a track would be counted here as +/// embedded until this follows it -- the named line, which is the engine's +/// string verbatim, would say it correctly meanwhile. Upgrade path: reasons out +/// of `planned_subtitles` as data rather than as one sentence, which is an +/// engine change. +pub(crate) fn subtitle_plan( + plan: String, + tracks: &[engine::subtitle::SubtitleTrack], + picks: &[usize], +) -> String { + let mut parts: Vec = Vec::new(); + // "none" is the engine's word for an empty pick list and would read as a + // verdict on the tracks named after it. + if !picks.is_empty() { + parts.push(plan); + } + parts.extend( + tracks + .iter() + .enumerate() + .filter(|(i, _)| !picks.contains(i)) + .map(|(_, track)| format!("{} — no cues here", track.label)), + ); + let named = parts.join("; "); + if named.chars().count() <= SUB_PLAN_CHARS { + return match named.is_empty() { + true => "none".to_string(), + false => named, + }; + } + let (mut embedded, mut unread, mut pictures, mut off) = (0, 0, 0, 0); + for (i, track) in tracks.iter().enumerate() { + match ( + track.refused.is_some(), + track.is_bitmap(), + picks.contains(&i), + ) { + (true, _, _) => unread += 1, + (_, true, _) => pictures += 1, + (_, _, false) => off += 1, + _ => embedded += 1, + } + } + let mut counted = vec![format!("{embedded} of {} → embedded", tracks.len())]; + counted.extend( + [ + (pictures, "pictures"), + (unread, "unread"), + (off, "no cues here"), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, why)| format!("{n} {why}")), + ); + counted.join("; ") +} + +/// Every subtitle track one file gave, kept together. Plain data, planned +/// before anything is drawn -- the grouping is the branchy part and it is the +/// same answer whatever a styling puts around it. +/// +/// [`Player::subtitle_section`] draws one block per group of these, and +/// [`sub_pick_name`] names the pick out of the same answer -- so what a heading +/// says and what a row a person clicked says cannot disagree. +#[derive(Debug, PartialEq)] +pub(crate) struct SubGroup { + /// What the group is called: the file without its extension, which is what + /// a person named the film even when the subtitles came out of a remux. + pub(crate) name: String, + /// What the swatch is asked by ([`file_tint`]) -- the file, so a subtitle + /// row and the media rows of the same file wear one colour. `None` from + /// that lookup for a standalone `.srt`, which is nobody's stream. + pub(crate) path: PathBuf, + pub(crate) rows: Vec, +} + +/// One subtitle track, as a row shows it. +#[derive(Debug, PartialEq)] +pub(crate) struct SubRow { + /// Which track of the session's list this row is: the *flat* index into the + /// add-order Vec `PlaybackSession::subtitles` hands back, which is what a + /// click sets `sub_track` to and what a save writes into the `.edith`. + /// Grouping moves rows around on screen and never touches this number. + pub(crate) track: usize, + /// Which of *this file's* tracks it is, counted from 1 -- the numbering + /// [`row_name`] gives audio streams, for the same reason: two tracks off one + /// remux that both say "eng" are told apart by nothing else. + pub(crate) number: usize, + pub(crate) label: String, + /// The row's second line ([`subtitle_detail`]). + pub(crate) detail: String, + /// Why it cannot be shown, for a track that cannot: the only thing that + /// greys a row out. Listed all the same -- a picker that hides them is a + /// picker that lies. + pub(crate) refused: Option, + /// Pictures rather than lines ([`engine::subtitle::SubtitleTrack::bitmap`]). + pub(crate) bitmap: bool, +} + +/// What a subtitle row is called, off the two fields the container really +/// stated rather than out of the flattened +/// [`label`](engine::subtitle::SubtitleTrack::label). The pair is what an export +/// writes (`TRACK_LANGUAGE` and `TRACK_NAME` are two fields), and reading the +/// display string back apart is the very heuristic that sent every French track +/// out as English: `lang_human` on a whole "und — Signs" matches nothing and +/// names a language nobody speaks. +/// +/// The three shapes a track arrives in, all three of them real: a standalone +/// file states no language and is its own name, an embedded one states a +/// language and sometimes a title beside it, and a refused one states neither +/// and keeps the label it was refused under (`SubtitleTrack::refused`). +pub(crate) fn sub_title(sub: &engine::subtitle::SubtitleTrack) -> String { + match (sub.language.as_str(), sub.name.as_str()) { + ("", "") => sub.label.clone(), + ("", name) => name.to_string(), + // A track whose only name is the tag for "nobody said" says that in + // words rather than showing the tag itself. + (lang, "") => lang_human(lang).to_string(), + // ...and one that says "nobody said" *and* gives a title is the title: + // "unknown language — Signs" pads it with a word the file never said. + ("und", name) => name.to_string(), + (lang, name) => format!("{lang} — {name}"), + } +} + +/// The subtitle list as rows under the file each came out of: one group per +/// distinct path, in the order the files first appear, and each file's tracks +/// in the order they were added. Two remuxes' tracks arriving interleaved -- +/// which is what importing a second film does -- still read as two films. +pub(crate) fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec { + let mut groups: Vec = Vec::new(); + for (track, sub) in tracks.iter().enumerate() { + let group = match groups.iter().position(|g| g.path == sub.path) { + Some(i) => &mut groups[i], + None => { + groups.push(SubGroup { + name: sub + .path + .file_stem() + .map_or_else(|| file_name(&sub.path), |s| s.to_string_lossy().into()), + path: sub.path.clone(), + rows: Vec::new(), + }); + groups.last_mut().expect("just pushed") + } + }; + group.rows.push(SubRow { + track, + number: group.rows.len() + 1, + label: sub_title(sub), + detail: subtitle_detail(sub), + refused: sub.refused.clone(), + bitmap: sub.is_bitmap(), + }); + } + groups +} + +/// How the picked track is named wherever the pick is echoed -- the strip +/// header, the section heading, the toggle's own notice. What the track is +/// *and* which file it came out of: two remuxes each carrying an "eng" track +/// give the same word twice, and the file is the only thing that tells them +/// apart. A file that gave several of them numbers them within itself, the way +/// [`row_name`] numbers audio streams, since "eng" twice off one remux is the +/// same problem one file down. +/// +/// Goes through [`subtitle_rows`], so the name a header says and the row a +/// person clicked cannot disagree -- and the label is humanised there, so an +/// "und" track is named in words here without being passed through +/// [`lang_human`] twice. +/// +/// `None` for an index no track answers to, which is the silence +/// [`Player::subtitle_track`] gives at the same moment. +/// Where the picked subtitle row lands once `removed` has been taken off a list +/// that is `left` long afterwards. The pick follows the list: the same *track* +/// while it is still there -- every index past the one that went moves down +/// ([`engine::Project::remove_subtitles`]) -- the row that slid into the empty +/// place when the picked one is what went, and the last row when that was the +/// last. Zero on an emptied list, which is the index the section is not drawn at +/// all. +/// +/// Its own function because the pick is what the overlay draws: left where it +/// was it would name a different track, and the plate over the picture would +/// change language on its own the moment a row above it went. What an export +/// writes is *not* this pick and cannot be desynced by a removal -- it is worked +/// out from the cues on the timeline each time ([`Player::export_subs`]). +pub(crate) fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) -> usize { + let picked = match removed < picked { + true => picked - 1, + false => picked, + }; + picked.min(left.saturating_sub(1)) +} + +pub(crate) fn sub_pick_name(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option { + subtitle_rows(tracks).into_iter().find_map(|group| { + let row = group.rows.iter().find(|row| row.track == track)?; + let track = match group.rows.len() > 1 { + false => row.label.clone(), + true => format!("{} {}", row.label, row.number), + }; + // A standalone `.srt` is already named after its own file: "sub.srt — + // sub" says the one thing twice, and the film is only worth naming + // where it is not in the label yet. + Some(match row.label.starts_with(&group.name) { + true => track, + false => format!("{track} — {}", group.name), + }) + }) +} + +/// Where a cue is drawn on the bed: left edge and width in pixels, through the +/// same [`Scale`] every clip box goes through -- so a cue and the take it is +/// spoken over line up at every zoom, which is the only reason the strip is +/// worth drawing. Microseconds are the cue's unit and seconds are the scale's, +/// and this is the one place they meet. +/// +/// Never narrower than [`SUB_CUE_MIN_W`]: zoomed out, a one-second cue is a +/// fraction of a pixel, and a mark that rounds away reads as a track with +/// nothing in it. +pub(crate) fn cue_box(scale: Scale, cue: &engine::subtitle::Cue) -> (f32, f32) { + let (start, end) = (cue.start_us as f64 / 1e6, cue.end_us as f64 / 1e6); + ( + scale.px_at(start), + scale.width_px(end - start).max(SUB_CUE_MIN_W), + ) +} + +/// Which cues of a track are on screen at `at` seconds. Half-open, as the cue +/// itself is: one that ends exactly where the next begins hands over rather than +/// overlapping it for a frame, and several that genuinely overlap all come back +/// -- a sign and a line of dialogue are two cues at one moment. +pub(crate) fn cues_at(cues: &[engine::subtitle::Cue], at: f64) -> Vec<&engine::subtitle::Cue> { + let us = (at * 1e6) as i64; + cues.iter() + .filter(|cue| cue.start_us <= us && us < cue.end_us) + .collect() +} + +/// The sources a repaint has not asked about yet. A key that is already there +/// means "asked", whatever state it is in, which is what stops a decode already +/// running from being started again by the next of sixty repaints a second. +pub(crate) fn unseen_sources( + sources: &[Source], + waves: &HashMap<(PathBuf, usize), Wave>, +) -> Vec<(PathBuf, usize)> { + sources + .iter() + .map(|s| (s.path.clone(), s.audio_stream)) + .filter(|key| !waves.contains_key(key)) + .collect() +} + +/// The same, for the per-file caches: one entry per *file*, however many of its +/// streams the timeline plays. Generic in the value, because the stream probe +/// and the still's own size are both asked once per file and answered by +/// presence in a map. +pub(crate) fn unseen_paths(sources: &[Source], seen: &HashMap) -> Vec { + let mut out: Vec = Vec::new(); + for s in sources { + if !seen.contains_key(&s.path) && !out.contains(&s.path) { + out.push(s.path.clone()); + } + } + out +} + +/// Which timeline frame the playhead is on, by the rule the engine's own edits +/// use (playback.rs `secs_to_frame`): the frame that has started, with the +/// epsilon that keeps a clock sitting exactly on a boundary from reading as the +/// frame before it. Only ever a hint here -- what an edit does is still the +/// engine's answer, taken from the same seconds. +pub(crate) fn frame_at(secs: f64, fps: f64) -> u32 { + (secs * fps + 1e-6).floor().max(0.) as u32 +} diff --git a/crates/app/src/timeline_math.rs b/crates/app/src/timeline_math.rs new file mode 100644 index 0000000..467ca0d --- /dev/null +++ b/crates/app/src/timeline_math.rs @@ -0,0 +1,388 @@ +//! The timeline's arithmetic: takes, trims, snapping and envelopes. + +use crate::*; + +/// Whether this clip is a whole take, i.e. whether deleting it may close the +/// hole under it: a take is what the first pair of lanes carries between them, +/// `V1`'s picture and the sound grouped with it, and dropping one moves the +/// frames after it on every lane. +/// +/// Everything else is a half or a layer, and is *lifted* instead: a half whose +/// picture was lifted (what a lift leaves behind) has no take to ripple, and a +/// clip on a further lane is laid over the timeline rather than part of it -- +/// closing a hole under it would drag the take beneath out of step with it. +pub(crate) fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool { + let Some(clip) = session.lane_clips(lane).get(idx) else { + return false; + }; + let paired = || { + session + .lanes() + .into_iter() + .filter(|&other| other != lane) + .flat_map(|other| session.lane_clips(other)) + .any(|o| o.link.is_some() && o.link == clip.link) + }; + match (lane.kind, lane.ord) { + (_, 1..) => false, + // The picture of a take -- unless the take has been taken apart: a + // detached picture (a group id no other lane carries, which is also what + // a lift of the sound leaves) is a half like the sound is, and a ripple + // under it would drag away the very half it was detached from. A clip in + // no group at all is not a half but a placement, and on `V1` a placement + // is the take there is. + (LaneKind::Video, _) => clip.link.is_none() || paired(), + // The sound of a take, only while the take is still there: its group is + // carried by a clip on some other lane. + (LaneKind::Audio, _) => paired(), + } +} + +/// The clip a Group would pair this one with: the first clip on another track, +/// in the order the lanes are drawn, covering exactly the same frames and not in +/// this clip's group already. Exactly the same frames because that is all a +/// group id can mean (engine `links_are_consistent`), which is what leaves +/// nothing for a second click to choose. `None` when no track has one, and the +/// notice says so. +pub(crate) fn span_partner(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> { + let clip = *session.lane_clips(lane).get(idx)?; + let matches = |other: Lane| { + let i = session.lane_clips(other).iter().position(|c| { + (c.start, c.end()) == (clip.start, clip.end()) + && !(c.link.is_some() && c.link == clip.link) + })?; + Some((other, i)) + }; + // Sound before picture (and picture before sound): "group this" means the + // other half of the take, and a project whose audio lane was added after a + // second video one has that half *after* the layer in storage order -- which + // is the order the lanes come in. A same-kind lane is still groupable (V1 + // and V2 may be one take), but only where no opposite one covers the span. + let (opposite, same): (Vec, Vec) = session + .lanes() + .into_iter() + .filter(|&other| other != lane) + .partition(|other| other.kind != lane.kind); + opposite.into_iter().chain(same).find_map(matches) +} + +/// Whether a click marks this clip: the clip that was clicked always, and the +/// other lane's clip of the same group with it. A clip whose group has no other +/// half -- what a lift leaves behind -- marks only itself, which is what makes a +/// detached half separately deletable. +pub(crate) fn marked( + here: (Lane, usize), + link: Option, + sel: Option<(Lane, usize)>, + sel_link: Option, +) -> bool { + sel == Some(here) || (link.is_some() && link == sel_link) +} + +/// Whether a clip is wide enough to be worth naming. +pub(crate) fn show_label(w: f32) -> bool { + w >= LABEL_MIN_W +} + +/// The clip a trim is *showing*, worked out the way `Project::trim` will write +/// it: the timeline room the edge leaves is turned into source frames by the one +/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from +/// that. The preview and the commit are then the same arithmetic -- a box let go +/// of stays where the hand left it at every rate. Assigning the timeline count +/// straight to the source field, as this used to, drew a speeded clip's tail +/// moving at the wrong rate (it snapped on release) and drew a *head* trim +/// moving the clip's other edge, since the length it implied was not the length +/// the release would commit. +/// +/// A still grows forward from source frame 0 instead: every frame of it is the +/// same picture, so there is no earlier one for an in-point to walk back to. +/// +/// Room too narrow to hold one source frame is the edit the engine refuses, and +/// the box is drawn unchanged rather than as something that will not be +/// committed. +pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip { + // An edge that has not moved is not an edit, and `Project::trim` refuses it + // as one: the press that starts a drag must draw the clip it pressed, not a + // clip a rounding narrower. + if to + == match edge { + Edge::Start => clip.start, + Edge::End => clip.end(), + } + { + return clip; + } + match edge { + Edge::Start => { + // What survives is measured from the *end* -- the frames that stay + // play what they always played, which is what makes this a trim. + let Some(keep) = clip.speed.fit(clip.end().saturating_sub(to)) else { + return clip; + }; + match still { + true => Clip { + in_frame: 0, + out_frame: keep, + start: to, + ..clip + }, + false => Clip { + in_frame: clip.out_frame - keep.min(clip.out_frame), + start: to, + ..clip + }, + } + } + Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) { + Some(keep) => Clip { + out_frame: clip.in_frame + keep, + ..clip + }, + None => clip, + }, + } +} + +/// Which index on its own lane a dragged clip is at *now*: the one it was picked +/// up at while nothing has moved, and wherever the clip itself has slid to when +/// an edit during the drag rippled the lane's indices -- a delete, an undo or a +/// paste from a stroke, none of which gpui's frozen drag payload hears about. +/// `None` when the clip is gone altogether, and then the drop is not an edit at +/// all: moving whatever slid into its place is the one thing the hand did not +/// ask for. A lane's clips are disjoint and sorted, so at most one of them can +/// be the clip that was picked up. +pub(crate) fn live_idx(clips: &[Clip], idx: usize, clip: Clip) -> Option { + match clips.get(idx) { + Some(&at) if at == clip => Some(idx), + _ => clips.iter().position(|&c| c == clip), + } +} + +/// The part of a clip's box that is on the bed, in the box's own pixels: +/// `(left, width)` of its intersection with the visible strip. Everything drawn +/// *inside* a box -- its waveform, its name, its speed badge -- is placed in +/// here rather than at the box's own edges, which at a deep zoom sit thousands +/// of pixels off either side of the screen: a label out there is a label nobody +/// can read, and a waveform out there is a path with a point per two pixels of a +/// width nobody can see. A bed that has not been measured yet answers with the +/// whole box, which is what was drawn before there was a bed to clip to. +pub(crate) fn visible_slice(left: f32, width: f32, bed: f32) -> (f32, f32) { + if bed <= 0. { + return (0., width); + } + let from = (-left).clamp(0., width); + let to = (bed - left).clamp(from, width); + (from, to - from) +} + +/// Scales an envelope to its own loudest sample, so a quietly mastered source +/// still draws as a shape. The fixtures peak around an eighth of full scale, and +/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file +/// that is not. +pub(crate) fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> { + let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi)); + if loudest > 0. { + for (lo, hi) in &mut peaks { + *lo /= loudest; + *hi /= loudest; + } + } + peaks +} + +/// The min/max envelope of `peaks` over the source seconds `from..to`, as +/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box +/// -- a clip's waveform cannot paint over its neighbour -- and every column is +/// at least a pixel tall, so silence reads as a line through the middle rather +/// than as a polygon with no area. +pub(crate) fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f32, f32, f32)> { + if peaks.is_empty() || w <= 0. || h <= 0. { + return Vec::new(); + } + let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX); + let mid = h / 2.; + (0..=cols) + .map(|col| { + let along = col as f64 / cols as f64; + let at = from + (to - from) * along; + // Casting a float to an integer saturates in Rust, so a source + // second past the end of the peaks clamps rather than wrapping. + let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1); + let (lo, hi) = peaks[bucket]; + let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5); + let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5); + (w * along as f32, top.max(0.), bottom.min(h)) + }) + .collect() +} + + + + + + + + +/// Records its parent's laid-out box: gpui hands a mouse listener the window +/// position only, and the ruler sits behind the panel's padding. Paints +/// nothing and takes no hitbox of its own, so the click still reaches the bar. +pub(crate) fn bounds_probe(into: Rc>>) -> impl IntoElement { + canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ()) + .absolute() + .size_full() +} + +/// Where along an element a click landed, 0..1. An element that was never +/// painted has no width, and reads as its start rather than as NaN. +pub(crate) fn frac_along(x: Pixels, bounds: Bounds) -> f32 { + if bounds.size.width <= px(0.) { + return 0.; + } + ((x - bounds.left()) / bounds.size.width).clamp(0., 1.) +} + +/// Where along an element a click landed, in pixels from its own left edge: +/// [`frac_along`] in the units the timeline is drawn in, since a [`Scale`] +/// measures in pixels and not in shares of a bed. Clamped to the element -- a +/// drag that slid off the end names its end -- and an element that was never +/// painted reads as its start. +pub(crate) fn px_along(x: Pixels, bounds: Bounds) -> f32 { + f32::from(x - bounds.left()).clamp(0., f32::from(bounds.size.width).max(0.)) +} + +/// One turn of the wheel as a single number, positive for a turn *up*, in +/// whatever units the device sends (a mouse counts lines, a touchpad pixels). +/// A tilt wheel's own axis counts as the same gesture: it is the sideways +/// scroll a mouse that has one sends, and the controls this drives have one +/// direction each, so the two axes are one answer here. +pub(crate) fn wheel_delta(event: &ScrollWheelEvent) -> f32 { + let (dx, dy) = match event.delta { + ScrollDelta::Lines(d) => (d.x, d.y), + ScrollDelta::Pixels(d) => (f32::from(d.x), f32::from(d.y)), + }; + match dy == 0. { + true => dx, + false => dy, + } +} + +/// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is +/// within `tol` frames of where its head -- or its tail, `len` frames along -- +/// would come to rest, in which case that edge wins. The snap every timeline +/// has: clips meet exactly instead of a frame apart, and the hand does not have +/// to aim. The nearest mark wins, and a head landing on one beats a tail at the +/// same distance -- what was dragged is the head. +pub(crate) fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 { + let mut best: Option<(u32, u32)> = None; + for &mark in marks { + // Head on the mark, then tail on it -- a clip dragged up against the + // take in front of it snaps by whichever end reaches first. + for start in [Some(mark), mark.checked_sub(len)] { + let Some(start) = start else { continue }; + let d = start.abs_diff(raw); + if d <= tol && best.is_none_or(|(near, _)| d < near) { + best = Some((d, start)); + } + } + } + best.map_or(raw, |(_, start)| start) +} + +/// The edges worth landing on, off *every* lane: both ends of every clip on the +/// timeline, less `skip` -- the clip being dragged, which does not snap to where +/// it already is -- and less the other halves of its group, which travel with +/// it. `skip` is a lane's place in `lanes` and an index into it. The playhead +/// and the head of the timeline go on the end: a clip meets the cursor and the +/// start of the show as readily as it meets another take. +/// +/// All lanes rather than the one being dropped on, because a cut is made across +/// the timeline: a title on V2 lines up with the shot under it, and a sound +/// effect lines up with the frame it belongs to. +pub(crate) fn snap_marks(lanes: &[&[Clip]], skip: Option<(usize, usize)>, playhead: u32) -> Vec { + let link = skip + .and_then(|(lane, idx)| lanes.get(lane)?.get(idx)) + .and_then(|clip| clip.link); + let mut marks: Vec = lanes + .iter() + .enumerate() + .flat_map(|(lane, clips)| { + clips + .iter() + .enumerate() + .filter(move |&(idx, clip)| { + Some((lane, idx)) != skip && !(link.is_some() && clip.link == link) + }) + .flat_map(|(_, clip)| [clip.start, clip.end()]) + }) + .collect(); + marks.push(playhead); + marks.push(0); + marks +} + +/// [`snapped`], and the mark that pulled it there -- the line the bed draws +/// while the hand is still moving. `None` when nothing was near enough: a line +/// standing over open bed would promise a landing that is not going to happen. +/// The head is read before the tail, exactly as [`snapped`] prefers it. +/// +/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and +/// draws no line at all, which is the whole point of being able to turn it off. +pub(crate) fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option) { + if !on { + return (raw, None); + } + let start = snapped(raw, len, tol, marks); + let mark = [start, start.saturating_add(len)] + .into_iter() + .find(|mark| marks.contains(mark)); + (start, mark) +} + +/// Where a drag lands and the mark that pulled it there: the frame under the +/// pointer, less however far into the box the hand grabbed it (so a clip travels +/// with the pointer rather than jumping its head under it), snapped by +/// [`snap_cue`]. One answer, asked by the shadow drawn in flight +/// ([`Player::preview_ghost`]), by the line ([`Player::preview_drop`]) and by +/// the drop that commits ([`Player::move_clip`]) -- which is what makes the +/// promise and the landing the same frame. +pub(crate) fn landing( + under: u32, + grab: u32, + len: u32, + on: bool, + tol: u32, + marks: &[u32], +) -> (u32, Option) { + snap_cue(on, under.saturating_sub(grab), len, tol, marks) +} + +/// Why this file may not go on that lane, in the words the refusal is told in -- +/// `None` when it may. A file with no picture belongs on an audio lane and +/// nowhere else, and a still is silent, so an audio lane is the one place it +/// cannot go. Asked twice: by the ghost tinting itself as refused on the way +/// down, and by the insert that commits ([`Player::insert_source`]), so what is +/// shown as impossible is exactly what is refused. +pub(crate) fn lane_refuses(path: &Path, lane: Lane) -> Option { + let name = file_name(path); + let label = lane.label(); + match lane.kind { + LaneKind::Video if engine::is_audio(path) => { + Some(format!("NOT ON {label} — {name} has no picture; drop it on an audio lane")) + } + LaneKind::Audio if engine::is_image(path) => { + Some(format!("NOT ON {label} — {name} is a still image; drop it on a video lane")) + } + _ => None, + } +} + +/// Where down an element a pointer sits, 0..1 from the top: the vertical twin +/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An +/// element that was never painted reads as its middle -- flat, the one answer +/// that changes nothing -- rather than as a full boost. +pub(crate) fn frac_down(y: Pixels, bounds: Bounds) -> f32 { + if bounds.size.height <= px(0.) { + return 0.5; + } + ((y - bounds.top()) / bounds.size.height).clamp(0., 1.) +} diff --git a/crates/app/src/transport.rs b/crates/app/src/transport.rs new file mode 100644 index 0000000..a67c1ae --- /dev/null +++ b/crates/app/src/transport.rs @@ -0,0 +1,214 @@ +//! 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 — put a clip on the timeline first"; + +/// 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 whole number, for the button's fixed rect: muting swaps + /// the glyph beside it, never the width of the box. + pub(crate) fn percent(self) -> u32 { + u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS) + } + + /// What the button reads. The level shows while muted too: it is what the + /// next press of the mute key brings back. + pub(crate) fn label(self) -> String { + let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS); + 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), + } +} + +/// 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); + +/// 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. +/// The import bar's words, for the import bar's reason -- a window that cannot +/// move and a window that has hung look identical, so this one says which. +pub(crate) fn seek_line(standing: Option) -> Option { + let since = standing.filter(|d| *d >= SEEK_STALL)?; + Some(format!( + "still opening the picture — a cold read of a big file is seconds of it, and the window \ + is not frozen · {} elapsed", + clock(since.as_secs_f32()) + )) +} diff --git a/crates/app/src/viewport.rs b/crates/app/src/viewport.rs new file mode 100644 index 0000000..6a887c5 --- /dev/null +++ b/crates/app/src/viewport.rs @@ -0,0 +1,296 @@ +//! How much timeline is on the bed, and how a time is written. + +use crate::*; + +/// What the zoom button says it is showing: how much timeline fits on the bed, +/// in the coarsest unit that still tells two zooms apart. +pub(crate) fn span_label(span: f64) -> String { + match span { + s if !s.is_finite() || s <= 0. => "—".to_string(), + // Hours once a timeline is long enough to be measured in them: the far + // stop follows the content now, so "315m" is a span a user can be sat + // at, and no one reads a pill in minutes past sixty. + s if s >= 3600. => format!("{:.1}h", s / 3600.), + s if s >= 600. => format!("{:.0}m", s / 60.), + s if s >= 60. => format!("{:.1}m", s / 60.), + s if s >= 10. => format!("{s:.0}s"), + s => secs_label(s), + } +} + +/// A span of seconds as a person reads it: one decimal above a second, two +/// below -- [`scaled`]'s rule, for its reason. The tightest zoom is +/// [`ZOOM_MIN_FRAMES`] across the bed, which on the 240 fps slow-motion a phone +/// writes is 0.03s, and a single frame of quiet at 60 fps is 0.02s: one decimal +/// prints both as "0.0s", a pill and a notice saying the thing they are about +/// has no length at all. +pub(crate) fn secs_label(secs: f64) -> String { + match secs >= 1. { + true => format!("{secs:.1}s"), + false => format!("{secs:.2}s"), + } +} + +/// The mapping the whole panel is drawn and clicked through: `pps` pixels to a +/// second of timeline, `start` the moment at the bed's left edge. Absolute -- +/// how wide a clip is drawn depends on how long the clip is and on nothing +/// else, so adding a second clip does not redraw the first one narrower and +/// zooming out always makes every box smaller. +/// +/// The one place seconds become pixels: every box, the playhead, a seek and a +/// trim all go through it, so none of them can drift away from the others when +/// the view moves. What clamps it -- the stops, the scroll, the fit -- needs the +/// bed it is drawn on and lives on [`View`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Scale { + pub(crate) pps: f64, + pub(crate) start: f64, +} + +impl Default for Scale { + fn default() -> Self { + Scale { + pps: PPS_DEFAULT, + start: 0., + } + } +} + +impl Scale { + /// Where a moment sits on the bed, in pixels from its left edge. Negative + /// for a moment scrolled off to the left, which is exactly the offset a + /// half-visible clip is drawn at. + pub(crate) fn px_at(self, at: f64) -> f32 { + ((at - self.start) * self.pps) as f32 + } + + /// How wide a stretch of `len` seconds is drawn. Wider than the bed once + /// zoomed in, which is the point of zooming in; never negative, which gpui + /// has no meaning for. + pub(crate) fn width_px(self, len: f64) -> f32 { + (len * self.pps).max(0.) as f32 + } + + /// The moment `x` pixels along the bed is pointing at: the inverse of + /// [`Scale::px_at`], and what every seek and every trim reads. Clamped at + /// the head of the timeline only -- there is bed past the last frame now, + /// and a tail dragged into it is a longer clip, not an error. + pub(crate) fn time_at(self, x: f32) -> f64 { + if self.pps > 0. { + (self.start + f64::from(x) / self.pps).max(0.) + } else { + self.start + } + } + + /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: a snap + /// is a distance on screen, so zoomed right in it is worth less than a frame + /// (no snap at all, which is what a hand placing single frames wants) and + /// zoomed out it is worth many. + pub(crate) fn snap_frames(self, fps: f64) -> u32 { + if self.pps > 0. { + (SNAP_PX / self.pps * fps) as u32 + } else { + 0 + } + } +} + +/// A [`Scale`] against the bed it is drawn on and the timeline it is drawn +/// from. The bed's width is what turns a scale into "how much is on screen", +/// and that is all the stops, the scroll clamp and the fit are made of. +/// +/// Built per use out of [`Player::view`] and thrown away again -- the state is +/// the `Scale`, and this is what a bed of `bed` px showing `duration` seconds +/// at `fps` may do to it. So no call site can measure a moment against a bed or +/// a duration that another one did not. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct View { + pub(crate) scale: Scale, + pub(crate) bed: f32, + pub(crate) duration: f64, + pub(crate) fps: f64, +} + +impl View { + /// How much of the timeline is on the bed, in seconds. + pub(crate) fn span(self) -> f64 { + if self.scale.pps > 0. { + f64::from(self.bed) / self.scale.pps + } else { + 0. + } + } + + /// The two stops, in pixels per second: [`ZOOM_MIN_FRAMES`] across the bed + /// is as tight as it goes, and as wide as it goes is the whole timeline on + /// the bed with [`ZOOM_OUT_MARGIN`] to spare -- the far stop is *relative*, + /// so the end of a five hour timeline is reachable for the same reason the + /// end of a five minute one is. A fixed far stop could not say that: a + /// timeline longer than it had an end no zoom could reach, which is the bug + /// this is. Short of [`PPS_MIN`] the timeline's own length is not worth + /// widening to and the pixel takes over, so a short import can still be + /// zoomed out of and the resting scale is nobody's content. + /// + /// `None` on a bed that was never painted -- there is nothing to measure + /// them against yet, and a stop guessed off a zero width would throw away a + /// zoom the user asked for. + pub(crate) fn stops(self) -> Option<(f64, f64)> { + (self.bed > 0.).then(|| { + let bed = f64::from(self.bed); + let whole = match self.duration > 0. { + true => bed / (self.duration * ZOOM_OUT_MARGIN), + false => PPS_MIN, + }; + let min = whole.min(PPS_MIN); + (min, (bed * self.fps / ZOOM_MIN_FRAMES).max(min)) + }) + } + + /// Clamped to the bed it draws on: between the two stops, and never + /// scrolled past either end of the timeline. Unlike the fractional view + /// this replaced, the *resting* scale is not the content -- a five second + /// timeline zooms out as far as an hour long one does, and both are drawn + /// at [`PPS_DEFAULT`] until someone zooms. Only the far stop knows the + /// length, and only once the length is worth more than [`PPS_MIN`]. + pub(crate) fn settled(self) -> Scale { + let pps = match self.scale.pps.is_finite() && self.scale.pps > 0. { + true => self.scale.pps, + false => PPS_DEFAULT, + }; + let start = match self.scale.start.is_finite() { + true => self.scale.start, + false => 0., + }; + let Some((min, max)) = self.stops() else { + return Scale { + pps, + start: start.max(0.), + }; + }; + let pps = pps.clamp(min, max); + let span = f64::from(self.bed) / pps; + Scale { + pps, + start: start.clamp(0., (self.duration - span).max(0.)), + } + } + + /// Zoomed by `factor` about `anchor` (pixels along the bed): whatever moment + /// was under that point stays under it, so a zoom magnifies what was being + /// looked at rather than throwing it off the edge. + pub(crate) fn zoomed(self, factor: f32, anchor: f32) -> Scale { + let at = self.scale.time_at(anchor); + // Clamped *before* the offset is worked out, not after: a press that + // runs into either stop must still leave the anchor where it is, and a + // start measured against a scale the stop then took away would slide it. + let raw = self.scale.pps * f64::from(factor); + let pps = match self.stops() { + Some((min, max)) => raw.clamp(min, max), + None => raw, + }; + View { + scale: Scale { + pps, + start: at - f64::from(anchor) / pps, + }, + ..self + } + .settled() + } + + /// Slid along by `by` pixels, later in the timeline for a positive one: the + /// one move that changes what is on the bed without changing how wide a + /// second is drawn, which is what a bare wheel does. Clamped by + /// [`View::settled`] like every other move, so a run at either end stops at + /// the end rather than scrolling the timeline off the bed -- and the extent + /// it stops against is the content's own length, never a number. + pub(crate) fn scrolled(self, by: f32) -> Scale { + let pps = self.settled().pps; + View { + scale: Scale { + pps, + start: self.scale.start + f64::from(by) / pps, + }, + ..self + } + .settled() + } + + /// The whole timeline across the bed. The one place the content's own + /// length sets the scale, and the only one -- everywhere else a second is a + /// second -- because this is a user pressing a key that asks for exactly + /// that. + pub(crate) fn fit(self) -> Scale { + let pps = match self.duration > 0. && self.bed > 0. { + true => f64::from(self.bed) / self.duration, + false => PPS_DEFAULT, + }; + View { + scale: Scale { pps, start: 0. }, + ..self + } + .settled() + } + + /// The scale a playhead at `at` needs: the same one while it is on the bed, + /// and one centred on it once it has run off -- which is how a zoomed-in + /// timeline scrolls, during playback and after a seek alike. With the whole + /// timeline on the bed this can never fire, so a panel showing all of it is + /// untouched by it. + pub(crate) fn following(self, at: f64) -> Scale { + // Nothing is drawn yet, so nothing has run off anything. + if self.bed <= 0. { + return self.scale; + } + let scale = self.settled(); + if self.shows(at) { + return scale; + } + let span = f64::from(self.bed) / scale.pps; + View { + scale: Scale { + start: at - span / 2., + ..scale + }, + ..self + } + .settled() + } + + /// Whether the moment `at` is on the bed as it is drawn now. The one + /// question both halves of the follow ask -- [`View::following`] to decide + /// whether to chase a head that has run off, and the render to decide when + /// a hand's own scroll ([`Player::panned`]) has been caught up with and the + /// follow may have the view back -- so the two can never disagree about + /// where the edge of the bed is. + pub(crate) fn shows(self, at: f64) -> bool { + if self.bed <= 0. { + return false; + } + let scale = self.settled(); + at >= scale.start && at <= scale.start + f64::from(self.bed) / scale.pps + } +} + +/// NLE timecode: `HH:MM:SS:FF`, the frame counted inside its own second. +pub(crate) fn timecode(t: f64, fps: f64) -> String { + let t = t.max(0.); + let secs = t as u64; + let last = (fps.ceil() as u64).saturating_sub(1); + let frame = ((t - secs as f64) * fps) as u64; + format!( + "{:02}:{:02}:{:02}:{:02}", + secs / 3600, + secs / 60 % 60, + secs % 60, + frame.min(last) + ) +} + +/// Wall clock for a progress line: `M:SS`, minutes past the hour included +/// rather than an hours field nobody reads on an export. +pub(crate) fn clock(secs: f32) -> String { + let secs = secs.max(0.) as u64; + format!("{}:{:02}", secs / 60, secs % 60) +}