From 62b680ed5b9d1857431de4842aea05dfaa26809e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 17 Sep 2026 06:55:35 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf(audio):=20the=20preview=20pain?= =?UTF-8?q?ts=20at=20its=20own=20size,=20not=20the=20project's?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The visualizer rebuilt the picture at the project resolution (1920x1080) for a preview displayed at ~584x328, so every look edit paid 4-5x what it needed. `PlaybackSession::set_view_size`/`view_size` now feed every composer the playback path opens (span, dissolve-B, black) and the app pushes the Contain-fitted display box from a probe on the picture area, with an 8 px deadband so a resize drag does not thrash. The export keeps its own seat at the project resolution and is untouched. Ring, a test song, ms per painted frame, glow 2/4/8/12/16: 18.5/35.7/64.7/93.2/117.1 -> 5.7/5.9/9.6/12.9/15.9 "Save frame as PNG" would otherwise have followed the preview down to that size, so it now asks the seat for one frame at the project's own size and writes the PNG when it lands (keyed to the session that asked, with a 2 s bound), and the preview's size comes back on the next repaint. The painter's per-frame buffers (VizScratch) are owned by the painting thread: 27 Vecs a frame -> 8, and none on later frames. --- crates/app/src/main.rs | 20 ++++ crates/app/src/player/library.rs | 4 + crates/app/src/render.rs | 57 ++++++++++++ crates/app/src/ui/preview.rs | 134 ++++++++++++++++++++++----- crates/engine/src/decode.rs | 153 +++++++++++++++++++------------ crates/engine/src/export.rs | 16 +++- crates/engine/src/playback.rs | 116 +++++++++++++++++++++-- 7 files changed, 408 insertions(+), 92 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 443809c..47d7f38 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -761,6 +761,23 @@ struct Player { viz_hs_dragging: bool, /// The wheel's box, recorded at prepaint for a drag's window position. viz_wheel: Rc>>, + /// Where the picture actually lands on screen, probed by the picture area + /// (`render.rs`): what tells the session to paint at the size the preview + /// is *watched* at rather than at the project's own + /// ([`engine::PlaybackSession::set_view_size`]). + picture_box: Rc>>, + /// A screenshot asked for while the picture was painted at the preview's + /// own size: `(session, stem, timecode)`, written by [`Player::flush_shot`] + /// once the seat has painted one frame at the project's size. Taken at the + /// ask so a shot mid-playback is named for the frame it was asked at, not + /// for the one it landed on -- and *keyed to the session that asked*, so a + /// swap mid-flight (a preview opened, another file opened, a session + /// closed) cannot have the new session's frame written under the old name + /// ([`Player::session_swapped`]). + shot_pending: Option<(u64, String, String)>, + /// The active session's identity, for the above: bumped by every door that + /// swaps `session` or `preview_session`. + session_gen: u64, /// Which of the clip's two inks the look section's wheel and colour field /// act on ([`VizSlot`]): the clip's own colour, or the ring's dual half. /// The pick stays picked across clips, the way the dock tab's does. @@ -1086,6 +1103,9 @@ fn main() { color_dragging: false, viz_hs_dragging: false, viz_wheel: Rc::default(), + picture_box: Rc::default(), + shot_pending: None, + session_gen: 0, viz_slot: VizSlot::Main, viz_hex_edit: None, pending_viz: None, diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 1be6c30..83cdc53 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -569,6 +569,7 @@ impl Player { /// again. pub(crate) fn close_session(&mut self) { self.session = None; + self.session_swapped(); // The picture goes with it, or the empty window would keep showing the // last frame of a timeline that no longer exists. // @@ -677,6 +678,7 @@ impl Player { // reads as a frozen picture, not as a player awaiting a click. session.play(); self.preview_session = Some(session); + self.session_swapped(); self.notify_user( format!( "PREVIEWING {} — not on the timeline; esc stops it", @@ -1477,6 +1479,7 @@ impl Player { // is not track 3 of this. self.sub_track = 0; self.session = Some(session); + self.session_swapped(); // A fresh session comes up at full volume; the player's own // setting outlives the file, so it is pushed at every new one. self.apply_volume(); @@ -1790,6 +1793,7 @@ impl Player { // media: that is the only place an export has ever landed. self.export_path = retarget(&export_path(&session.sources()[0].path), self.format); self.session = Some(session); + self.session_swapped(); self.apply_volume(); // The other way round from every other door: a project carries // its own two switches ([`engine::edith`]) and they are what it diff --git a/crates/app/src/render.rs b/crates/app/src/render.rs index 012115e..872d558 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -76,6 +76,9 @@ impl Player { // bottom of the picture region, which is the one box that is the // picture and nothing else. .relative() + // ...and the box the frame is *watched* in, which is what the + // session paints at ([`Player::push_view_size`]). + .child(bounds_probe(self.picture_box.clone())) .flex() .justify_center() .items_center() @@ -125,6 +128,51 @@ impl Player { } } +impl Player { + /// Tells the active session where the picture actually lands, in device + /// pixels, so its seats can paint at that size instead of the project's + /// ([`engine::PlaybackSession::set_view_size`]). Read off the picture + /// area's own bounds -- the box `letterboxed_image` fits the frame into -- + /// and the project's aspect, which is the aspect of every frame it hands + /// over. + /// + /// A size that moved enough for the eye to see gets a fresh picture: the + /// canvas a span paints at is decided when it opens, so a resized window + /// would otherwise sharpen on its next seek and not before. + fn push_view_size(&mut self, window: &mut Window) { + if self.shot_pending.is_some() { + // A screenshot in flight asked for the project's own size and is + // waiting on that frame: pushing the preview's size back now would + // cancel the very picture it is waiting for. + return; + } + let region = self.picture_box.get(); + if region.size.width <= px(1.) || region.size.height <= px(1.) { + // Before the first paint there is no box to read, and a floor is + // not a measurement. + return; + } + let scale = window.scale_factor(); + let Some(session) = self.active_session_mut() else { + return; + }; + // Device pixels, the unit `Contain` measures its fitting size in. + let meta = session.meta(); + let fitted = gpui::ObjectFit::Contain.get_bounds( + region, + size( + gpui::DevicePixels(meta.width as i32), + gpui::DevicePixels(meta.height as i32), + ), + ); + let w = (f32::from(fitted.size.width) * scale).round() as u32; + let h = (f32::from(fitted.size.height) * scale).round() as u32; + if session.set_view_size(w, h) { + session.resync_picture(); + } + } +} + impl Render for Player { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { // A file that has just been opened sits on its first frame with the @@ -134,6 +182,15 @@ impl Render for Player { session.tick(); } self.pump(window); + // A screenshot waiting for its project-sized frame is written on the + // repaint that lands it -- and before the size push below, which is + // what gives the preview its own size back. + self.flush_shot(cx); + // ...at the size it is watched at, not the project's: a visualizer + // seat redrawing 1920x1080 for a 600 px preview is nine times the + // pixels for nothing the eye can see. An export has a seat of its own + // and never comes through here. + self.push_view_size(window); // What every hover label asks before it paints: a card or a menu is // drawn over whatever the pointer is resting on. OVERLAID.store(self.overlaid(), Ordering::Relaxed); diff --git a/crates/app/src/ui/preview.rs b/crates/app/src/ui/preview.rs index e6d70bd..49534a0 100644 --- a/crates/app/src/ui/preview.rs +++ b/crates/app/src/ui/preview.rs @@ -123,44 +123,134 @@ impl Player { ) } - /// The frame on screen right now, written to a PNG: `image` and its - /// `as_bytes` are gpui's own cached copy of what was last handed to the - /// atlas ([`Player::pump`]), so this reads no decoder and races nothing -- - /// works during preview or on the timeline, whichever is showing. + /// The frame on screen right now, written to a PNG -- at the size the + /// **project** is, not at the size the preview shows it. + /// + /// The picture area asks the session for frames the size of its own box + /// ([`PlaybackSession::set_view_size`]), so the atlas holds a preview-sized + /// picture: saving that would cost the user the resolution they asked for + /// (a still of a 1080p project, an 11th of it). So the seat is asked for + /// one picture at the project's own size and the file is written when it + /// lands ([`Player::flush_shot`], off `pump`'s frame-owed signal). Every + /// other part of the gesture is what it always was: the same directory, + /// the same name, the same notice. + /// + /// A library preview is the same rule about *its* file: the seat paints at + /// the file's own resolution for it, which is the full size a still of that + /// file wants. pub(crate) fn take_screenshot(&mut self, cx: &mut Context) { - let no_frame = || "NO FRAME TO SAVE — nothing is showing yet".to_string(); - let Some(image) = self.image.clone() else { - self.notify_user(no_frame().into()); - cx.notify(); - return; - }; - let Some(bytes) = image.as_bytes(0) else { - self.notify_user(no_frame().into()); + if self.shot_pending.is_some() { + return; // one at a time: the picture is on its way + } + let Some(session) = self.active_session() else { + self.notify_user("NO FRAME TO SAVE — nothing is showing yet".into()); cx.notify(); return; }; - let size = image.size(0); - let stem = self - .active_session() - .and_then(|s| s.sources().first()) + let full = (session.meta().width, session.meta().height); + let stem = session + .sources() + .first() .map_or_else(|| self.name.to_string(), |s| file_name(&s.path)); let stem = std::path::Path::new(&stem) .file_stem() .map_or(stem.clone(), |s| s.to_string_lossy().into_owned()); - let tc = timecode( - self.active_session().map_or(0., PlaybackSession::now), - self.active_fps(), - ) - .replace(':', "-"); + let tc = timecode(session.now(), self.active_fps()).replace(':', "-"); + // The *exact* setter, not the deadbanded push: a view within 8 px of + // the project is a still of the wrong size. `false` says the view is + // already at it -- and then the frame in hand *is* the project's frame, + // so waiting for a picture that would never come (nothing moved, so + // nothing reseeks) is exactly the trap this avoids. + let moved = self + .active_session_mut() + .is_some_and(|s| s.set_view_size_exact(full.0, full.1)); + if moved { + // One frame at the project's own size, which is a reseek like any + // other edit: the frame it owes is what the flush waits on. + if let Some(session) = self.active_session_mut() { + session.resync_picture(); + } + self.shot_pending = Some((self.session_gen, stem, tc)); + self.reset_after_reseek(); + } else if !self.write_shot(&stem, &tc) { + self.notify_user("NO FRAME TO SAVE — nothing is showing yet".into()); + } + cx.notify(); + } + + /// Writes the picture the atlas is holding, at the size it holds it, and + /// says whether there was one. The tail [`Player::take_screenshot`] and + /// [`Player::flush_shot`] share, so the two doors cannot write differently. + fn write_shot(&mut self, stem: &str, tc: &str) -> bool { + let Some(image) = self.image.clone() else { + return false; + }; + let Some(bytes) = image.as_bytes(0) else { + return false; + }; + let size = image.size(0); let text = - match save_screenshot(bytes, size.width.0 as u32, size.height.0 as u32, &stem, &tc) { + match save_screenshot(bytes, size.width.0 as u32, size.height.0 as u32, stem, tc) { Ok(path) => format!("SAVED {}", path.display()), Err(e) => format!("SCREENSHOT FAILED: {e}"), }; self.notify_user(text.into()); + true + } + + /// The screenshot a preview-sized picture had to wait for: written once the + /// seat's project-sized frame has landed, then the preview takes its own + /// size back ([`Player::push_view_size`] pushes it on the next repaint). + /// + /// A picture that never lands -- the timeline emptied, a source that died + /// -- gives up rather than leaving the preview stuck at the project's size: + /// the wait is bounded, and the notice names what happened. + pub(crate) fn flush_shot(&mut self, cx: &mut Context) { + let Some((asked, stem, tc)) = self.shot_pending.clone() else { + return; + }; + if asked != self.session_gen { + // The session that asked is gone (a preview opened, another file + // opened, a session closed): its picture is not coming, and the new + // session's frame must not be written under its name. + self.shot_pending = None; + self.notify_user("NO FRAME TO SAVE — the session changed meanwhile".into()); + cx.notify(); + return; + } + if self + .seek_since + .is_some_and(|since| since.elapsed() < std::time::Duration::from_secs(2)) + { + return; // the frame is still being painted + } + self.shot_pending = None; + // The seat's own clamp is the truth about the size it can paint, which + // is what the ask settled on ([`PlaybackSession::set_view_size_exact`]), + // and with the push held while the shot is in flight + // ([`Player::push_view_size`]) it is still holding it here. + let want = self.active_session().map(PlaybackSession::view_size); + let landed = self + .image + .as_ref() + .map(|i| (i.size(0).width.0 as u32, i.size(0).height.0 as u32)) + == want; + if !landed || !self.write_shot(&stem, &tc) { + self.notify_user("NO FRAME TO SAVE — the picture could not be redrawn".into()); + } cx.notify(); } + /// The active session has been swapped (`session` or `preview_session`): + /// what anything keyed to a session has to hear. A screenshot in flight is + /// the one such thing ([`Player::shot_pending`]), and it is *keyed* rather + /// than cleared here because a door that forgot to call this would still be + /// caught by the key -- the picture it is holding came from a session that + /// is no longer the one on screen. + pub(crate) fn session_swapped(&mut self) { + self.session_gen += 1; + } + /// The cues the *subtitle lanes* put on screen at `at`, over the picture and /// nothing else: bottom-centred where every player puts them, white on a /// plate so the film underneath cannot swallow them, and each cue its own diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index d506374..67082af 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -668,6 +668,9 @@ impl DecodeSession { return; } let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; + // One frame's painting no longer allocates per strand per + // frame: this thread lives for the span. + let mut scratch = VizScratch::default(); let mut render = Render::new( color, transform, @@ -681,7 +684,8 @@ impl DecodeSession { return; } let t = f64::from(start_frame + index) / fps; - let (y, u, v) = visualizer_i420(&peaks, t, width, height, flags, paint); + let (y, u, v) = + visualizer_i420(&mut scratch, &peaks, t, width, height, flags, paint); let frame = render.frame(start_frame + index, &y, &u, &v, width, height); if tx.send(frame).is_err() { return; // caller moved on @@ -1735,6 +1739,26 @@ fn viz_span( } } +/// What one frame's painting borrows instead of allocating, owned by whoever +/// paints a *stream* of frames -- the visualizer worker's own thread, an +/// export seat, a test -- and reused for every strand of every frame. Eight +/// `Vec`s, against the twenty-seven a fresh set per strand cost a ring at +/// eight strands. +#[derive(Default)] +pub(crate) struct VizScratch { + /// The frame's own columns, kept across frames to the widest picture yet. + lo: Vec, + hi: Vec, + sig: Vec, + /// One strand's sampled positions, the cells its Bresenham runs cover, + /// the chain's rows, the row band's candidates and their lower hull. + pts: Vec<(i32, i32)>, + chain: Vec<(i32, i32)>, + rows: Vec<(i32, usize, usize)>, + cand: Vec<(i32, i32)>, + hull: Vec, +} + /// One segment's glow as its own disc, stamped at every Bresenham cell: what /// a chain was painted by before [`viz_chain`], and still the cheaper of the /// two when the chain is long ([`viz_discs_are_cheaper`]). @@ -1807,6 +1831,18 @@ fn viz_discs_are_cheaper(samples: usize, cells: usize, glow: u8) -> bool { (samples as u64) * (2 * u64::from(glow) + 1) < cells as u64 } +/// How many cells [`viz_walk`] would push for these samples, without walking +/// them: one per iteration of that loop, and it iterates `max(dx, dy) + 1` +/// times a segment. +fn chain_cells(pts: &[(i32, i32)]) -> usize { + pts.windows(2) + .map(|w| { + let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs()); + dx.max(dy) as usize + 1 + }) + .sum() +} + /// The Bresenham cells of one segment, collected rather than stamped: the same /// walk [`viz_line`] used to rasterise, kept for [`viz_chain`] to paint the /// whole chain from. @@ -1855,13 +1891,18 @@ fn viz_chain( h: usize, cw: usize, ch: usize, - chain: &mut Vec<(i32, i32)>, + scratch: &mut VizScratch, bg_y: u8, ink_y: u8, ink_u: u8, ink_v: u8, glow: u8, ) { + let VizScratch { pts, chain, rows, cand, hull, .. } = scratch; + chain.clear(); + for pair in pts.windows(2) { + viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain); + } if chain.is_empty() { return; } @@ -1880,7 +1921,7 @@ fn viz_chain( // a pixel) and a repeat is the same candidate. chain.sort_unstable_by_key(|&(x, row)| (row, x)); chain.dedup(); - let mut rows: Vec<(i32, usize, usize)> = Vec::new(); + rows.clear(); let mut i = 0; while i < chain.len() { let row = chain[i].1; @@ -1895,10 +1936,8 @@ fn viz_chain( let mut band = 0usize; // `(x, dy^2)` -- a candidate's horizontal offset is left to the cell that // asks, its vertical one is its own. - let mut cand: Vec<(i32, i32)> = Vec::new(); - // The candidates a run's cells are decided by, once the ones that can never - // be nearest are off ([`viz_chain`]'s own note). - let mut hull: Vec = Vec::new(); + // ...and the candidates a run's cells are decided by, once the ones that + // can never be nearest are off ([`viz_chain`]'s own note). for row in first..=last { while band < rows.len() && rows[band].0 < row - g { band += 1; @@ -1981,25 +2020,25 @@ fn viz_chain( } hull.push(c); } + // Only the hull's last two entries can change places as x moves + // forward, so this is a walk and not a search -- and `value` is + // asked of those two alone. let mut hp = 0usize; for x in x_lo..=x_hi { - while hp + 1 < hull.len() - && value(hull[hp + 1], x) <= value(hull[hp], x) - { + while hp + 1 < hull.len() && value(hull[hp + 1], x) <= value(hull[hp], x) { hp += 1; } let (cx, dy2) = cand[hull[hp]]; let d = x - cx; let d2 = d * d + dy2; - if d2 > g * g { - continue; + if d2 <= g * g { + let fall = if d2 == 0 { + 1.0 + } else { + (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp() + }; + viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v); } - let fall = if d2 == 0 { - 1.0 - } else { - (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp() - }; - viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v); } } } @@ -2010,6 +2049,7 @@ fn viz_chain( /// envelope at pixel resolution, or a multi-strand ribbon. Ink is /// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line. pub(crate) fn visualizer_i420( + scratch: &mut VizScratch, peaks: &[(f32, f32)], t_secs: f64, width: u32, @@ -2036,9 +2076,12 @@ pub(crate) fn visualizer_i420( y[z * w + col] = y[z * w + col].max(bg_y.saturating_add(18)); } - let mut lo = vec![0.0f32; w]; - let mut hi = vec![0.0f32; w]; - let mut sig = vec![0.0f32; w]; + scratch.lo.clear(); + scratch.lo.resize(w, 0.0); + scratch.hi.clear(); + scratch.hi.resize(w, 0.0); + scratch.sig.clear(); + scratch.sig.resize(w, 0.0); if !peaks.is_empty() { let duration = peaks.len() as f64 / f64::from(VIZ_BUCKETS_PER_SEC); let per_sec = f64::from(VIZ_BUCKETS_PER_SEC); @@ -2081,9 +2124,9 @@ pub(crate) fn visualizer_i420( mn = mn.min(l); mx = mx.max(h); } - lo[col] = mn; - hi[col] = mx; - sig[col] = signed_at(origin + (col as f64 + 0.5) / w as f64 * window); + scratch.lo[col] = mn; + scratch.hi[col] = mx; + scratch.sig[col] = signed_at(origin + (col as f64 + 0.5) / w as f64 * window); } // Whole-file peak, not the window's: a 2s window that gains or loses // a loud hit used to rescale every column, so the same bump changed @@ -2094,9 +2137,9 @@ pub(crate) fn visualizer_i420( .fold(0.0f32, f32::max); if peak > 1e-4 { for i in 0..w { - lo[i] /= peak; - hi[i] /= peak; - sig[i] /= peak; + scratch.lo[i] /= peak; + scratch.hi[i] /= peak; + scratch.sig[i] /= peak; } } } @@ -2106,7 +2149,7 @@ pub(crate) fn visualizer_i420( let tau = std::f64::consts::TAU; let travel = t_secs * 1.35; for col in 0..w { - let env = lo[col].abs().max(hi[col]).max(0.06); + let env = scratch.lo[col].abs().max(scratch.hi[col]).max(0.06); let x_phase = (col as f64 / w.max(1) as f64) * 2.15 * tau; for s in 0..u32::from(viz_strands_of(paint)).max(1) { let frac = s as f32 / (viz_strands_of(paint).max(2) as f32 - 1.0); @@ -2141,8 +2184,6 @@ pub(crate) fn visualizer_i420( let steps = w.max(h) * 4; let strands = viz_strands_of(paint); let glow = viz_glow_of(paint); - let mut chain: Vec<(i32, i32)> = Vec::new(); - let mut pts: Vec<(i32, i32)> = Vec::new(); for strand in 0..strands { let dual = strands >= 2 && strand >= strands / 2; // The dual half takes the clip's own strand colour when it @@ -2164,24 +2205,20 @@ pub(crate) fn visualizer_i420( let (iy, iu, iv) = rgb_yuv(ir as i32, ig as i32, ib as i32); let scale = 0.65 + 0.35 * f32::from(strand % 4) / 3.0; let phase = f32::from(strand) * 0.35; - pts.clear(); + scratch.pts.clear(); for i in 0..=steps { let t = i as f32 / steps as f32; let theta = t * tau + t_secs as f32 * 1.1 + phase; let col = ((t * w as f32) as usize).min(w.saturating_sub(1)); - let env = lo[col].abs().max(hi[col]); + let env = scratch.lo[col].abs().max(scratch.hi[col]); let wobble = (theta * 3.0 + phase).sin() * 0.12 * env; let r = r0 + amp * env * scale + amp * wobble; let x = (cx + r * theta.cos()).round() as i32; let row = (cy + r * theta.sin()).round() as i32; - pts.push((x, row)); - } - chain.clear(); - for pair in pts.windows(2) { - viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, &mut chain); + scratch.pts.push((x, row)); } - if viz_discs_are_cheaper(pts.len(), chain.len(), glow) { - for pair in pts.windows(2) { + if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) { + for pair in scratch.pts.windows(2) { viz_line( &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0, pair[1].1, bg_y, iy, iu, iv, glow, @@ -2189,23 +2226,21 @@ pub(crate) fn visualizer_i420( } } else { viz_chain( - &mut y, &mut u, &mut v, w, h, cw, ch, &mut chain, bg_y, iy, iu, iv, glow, + &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, iy, iu, iv, glow, ); } } } VIZ_STYLE_WAVE => { - let mut chain: Vec<(i32, i32)> = Vec::new(); - let mut pts: Vec<(i32, i32)> = Vec::new(); + scratch.pts.clear(); for col in 0..w { - pts.push((col as i32, (center - sig[col] * half).round() as i32)); - } - for pair in pts.windows(2) { - viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, &mut chain); + scratch + .pts + .push((col as i32, (center - scratch.sig[col] * half).round() as i32)); } let glow = viz_glow_of(paint); - if viz_discs_are_cheaper(pts.len(), chain.len(), glow) { - for pair in pts.windows(2) { + if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) { + for pair in scratch.pts.windows(2) { viz_line( &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0, pair[1].1, bg_y, ink_y, ink_u, ink_v, glow, @@ -2213,7 +2248,7 @@ pub(crate) fn visualizer_i420( } } else { viz_chain( - &mut y, &mut u, &mut v, w, h, cw, ch, &mut chain, bg_y, ink_y, ink_u, ink_v, + &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, glow, ); } @@ -2223,8 +2258,8 @@ pub(crate) fn visualizer_i420( // the fold+smooth above. Default look. let glow = i32::from(viz_glow_of(paint)); for col in 0..w { - let top = (center - hi[col] * half).round() as i32; - let bot = (center - lo[col] * half).round() as i32; + let top = (center - scratch.hi[col] * half).round() as i32; + let bot = (center - scratch.lo[col] * half).round() as i32; viz_span( &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top, bot, bg_y, ink_y, ink_u, ink_v, @@ -2570,7 +2605,7 @@ mod tests { *p = (-a.abs(), a.abs()); } let flags = 1u8; - let (y, u, v) = visualizer_i420(&peaks, 1.0, 320, 180, flags, 0); + let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0); let ink = y.iter().filter(|&&p| p > 40).count(); assert!(ink > 200, "envelope missing: {ink}"); assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}"); @@ -2583,13 +2618,13 @@ mod tests { assert!(blue > 10, "default ink was not timeline blue: {blue}"); let ring = with_viz_style(flags, VIZ_STYLE_RING); - let (yr, _, _) = visualizer_i420(&peaks, 1.0, 320, 180, ring, 0); + let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0); let ring_ink = yr.iter().filter(|&&p| p > 40).count(); assert!(ring_ink > 80, "ring missing: {ring_ink}"); assert!(ring_ink < ink, "ring should be a stroke, not a fill"); let hue_paint = with_viz_paint_hue(0, 40); - let (_, u2, v2) = visualizer_i420(&peaks, 1.0, 64, 32, flags, hue_paint); + let (_, u2, v2) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 64, 32, flags, hue_paint); let mut shifted = 0usize; for i in 0..u2.len() { if u2[i] < 120 && v2[i] > 130 { @@ -2686,7 +2721,7 @@ mod tests { } let ring = with_viz_style(1, VIZ_STYLE_RING); let auto = VIZ_PAINT_AZURE; - let (y0, u0, v0) = visualizer_i420(&peaks, 1.0, 320, 180, ring, auto); + let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto); // The automatic dual is half a wheel from the clip's hue at the // clip's own saturation; choosing exactly that colour changes @@ -2696,14 +2731,14 @@ mod tests { viz_sat_ui(auto), ); assert!(viz_strand_set(same)); - let (ys, us, vs) = visualizer_i420(&peaks, 1.0, 320, 180, ring, same); + let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same); assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame"); assert_eq!(us, u0); assert_eq!(vs, v0); // A colour of its own repaints the dual strands in it. let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255); - let (_, u1, v1) = visualizer_i420(&peaks, 1.0, 320, 180, ring, red); + let (_, u1, v1) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red); let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count(); let auto_px = (0..u0.len()).filter(|&i| u0[i] < 110 && v0[i] > 200).count(); assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}"); @@ -2713,7 +2748,7 @@ mod tests { // the unset picture, byte for byte. let stale = auto | (77u64 << 32) | (9u64 << 40); assert!(!viz_strand_set(stale)); - let (yt, ut, vt) = visualizer_i420(&peaks, 1.0, 320, 180, ring, stale); + let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale); assert_eq!(yt, y0, "an unset strand colour is the frame it always was"); assert_eq!(ut, u0); assert_eq!(vt, v0); @@ -2761,7 +2796,7 @@ mod tests { }; let flags = with_viz_style(1, style); let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow); - let (y, u, v) = visualizer_i420(&peaks, 37.5, 1920, 1080, flags, paint); + let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 37.5, 1920, 1080, flags, paint); let mut hash = 0xcbf2_9ce4_8422_2325u64; for buf in [&y, &u, &v] { for &b in buf.iter() { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index e8843b8..463fe68 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -4427,6 +4427,9 @@ enum ClipDecoder { next: u32, flags: u8, paint: u64, + /// This seat's own painting scratch, kept for the whole export: the + /// same reuse the playback worker's thread does. + scratch: crate::decode::VizScratch, y: Vec, u: Vec, v: Vec, @@ -4555,6 +4558,7 @@ impl ClipDecoder { next: start_frame, flags, paint, + scratch: crate::decode::VizScratch::default(), y: Vec::new(), u: Vec::new(), v: Vec::new(), @@ -4577,12 +4581,20 @@ impl ClipDecoder { next, flags, paint, + scratch, y, u, v, } => { - let (yy, uu, vv) = - crate::decode::visualizer_i420(peaks, f64::from(*next) / *fps, *width, *height, *flags, *paint); + let (yy, uu, vv) = crate::decode::visualizer_i420( + scratch, + peaks, + f64::from(*next) / *fps, + *width, + *height, + *flags, + *paint, + ); *y = yy; *u = uu; *v = vv; diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 213bc9a..f718a18 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -431,6 +431,11 @@ pub struct PlaybackSession { /// span most of the time. dissolve: Option, /// The last clip has been played out; see [`PlaybackSession::is_eos`]. + /// The size a front-end showing this session *on screen* wants its + /// pictures at, in device pixels ([`Self::set_view_size`]). `None` is the + /// project's own -- every file-level caller, every test, and an export, + /// which has a seat of its own ([`crate::export`]) and never comes here. + view: Option<(u32, u32)>, eos: bool, /// The mix the running mixer is reading, when there is one: what lets a /// fader and the master ceiling move without rebuilding the audio pipeline @@ -632,6 +637,7 @@ impl PlaybackSession { span, span_priming: true, dissolve: None, + view: None, eos: false, mix: None, priming: false, @@ -761,6 +767,7 @@ impl PlaybackSession { span, span_priming: true, dissolve: None, + view: None, eos: false, mix: None, priming: false, @@ -854,6 +861,7 @@ impl PlaybackSession { span, span_priming: true, dissolve: None, + view: None, eos: false, mix: None, priming: false, @@ -1207,6 +1215,7 @@ impl PlaybackSession { span, span_priming: true, dissolve: None, + view: None, eos: false, mix: None, priming: false, @@ -1749,6 +1758,10 @@ impl PlaybackSession { /// video that is now the worker's own doing -- it opens the file, so it is /// the one that finds out -- and nothing on this thread waits to hear it. fn start_span(&mut self, span: Option) { + // The viewer's own size, once one has said it ([`Self::set_view_size`]): + // every picture below is painted at *this*, and the project's + // resolution otherwise. + let (canvas_w, canvas_h) = self.view_size(); // The outgoing span's own dissolve, if it ever opened B's decoder: // that decoder's pictures were for a window this span is leaving // (played through, paused before, or seeked away from), and never @@ -1828,8 +1841,8 @@ impl PlaybackSession { .copied() .unwrap_or_default(), Composer::new( - self.meta.width, - self.meta.height, + canvas_w, + canvas_h, self.project.composite_fit_at(start), ), ) @@ -1861,8 +1874,8 @@ impl PlaybackSession { .copied() .unwrap_or_default(), Composer::new( - self.meta.width, - self.meta.height, + canvas_w, + canvas_h, self.project.composite_fit_at(start), ), self.project.composite_visualizer_at(start), @@ -1918,7 +1931,7 @@ impl PlaybackSession { // than kept in a local, because a `Composer` owns the scratch // buffers it places through -- the value is not copied about. let fit = self.project.composite_fit_at(start); - let canvas = || Composer::new(self.meta.width, self.meta.height, fit); + let canvas = || Composer::new(canvas_w, canvas_h, fit); // ...and the rendition an HDR source among them is mapped to, // the project's own and constant across the span for that // reason too. @@ -1975,8 +1988,8 @@ impl PlaybackSession { // span at all and gets one frame of it -- enough to put black on // screen, and it ends where the timeline does, at once. gap => Ok(DecodeSession::open_black( - self.meta.width, - self.meta.height, + canvas_w, + canvas_h, gap.map_or(1, |s| s.len), )), }; @@ -2018,6 +2031,7 @@ impl PlaybackSession { /// (still inside A's span) -- the same asymmetry /// [`crate::export`]'s own `Dissolve` is built with. fn open_dissolve_b(&mut self) { + let (canvas_w, canvas_h) = self.view_size(); let Some(d) = &self.dissolve else { return }; if d.b.is_some() { return; @@ -2038,8 +2052,8 @@ impl PlaybackSession { .copied() .unwrap_or_default(); let canvas = Composer::new( - self.meta.width, - self.meta.height, + canvas_w, + canvas_h, self.project.composite_fit_at(b_start), ); let tone = self.project.tone(); @@ -3567,6 +3581,55 @@ impl PlaybackSession { } } + /// Says how big the picture is on screen, in device pixels -- what a + /// front-end showing this session pushes once it knows where the picture + /// actually lands. Rendering a 1080p project's visualizer for a 600 px + /// preview costs nine times the pixels for nothing the eye can see; a + /// window that is fullscreen gets the project's own size back by pushing + /// it. `true` when the size moved enough to be worth a new picture: under + /// 8 px on both axes is a resize nobody can see, and a window being + /// dragged would otherwise restart the picture every tick. + pub fn set_view_size(&mut self, width: u32, height: u32) -> bool { + let want = self.view_want(width, height); + match self.view { + Some(now) if now.0.abs_diff(want.0) < 8 && now.1.abs_diff(want.1) < 8 => false, + _ => { + self.view = Some(want); + true + } + } + } + + /// [`Self::set_view_size`] with no deadband: what asks for the *exact* + /// size rather than one within 8 px of it. A still saved at the project's + /// own pixels is a file whose dimensions are read back, so "close enough + /// to be invisible" is not close enough to be right. `true` when the view + /// moved, `false` when it was already there -- which is also the answer + /// that lets a caller skip waiting for a frame it already has. + pub fn set_view_size_exact(&mut self, width: u32, height: u32) -> bool { + let want = self.view_want(width, height); + match self.view { + Some(now) if now == want => false, + _ => { + self.view = Some(want); + true + } + } + } + + /// The size a push of `(width, height)` settles on: even on both axes + /// (YUV 4:2:0 has no odd chroma) and never past the project's own. + fn view_want(&self, width: u32, height: u32) -> (u32, u32) { + let fit = |n: u32, cap: u32| (n & !1).clamp(2, cap.max(2)); + (fit(width, self.meta.width), fit(height, self.meta.height)) + } + + /// The canvas a span's pictures are painted at: [`Self::set_view_size`]'s + /// size once one has been pushed, the project's own otherwise. + pub fn view_size(&self) -> (u32, u32) { + self.view.unwrap_or((self.meta.width, self.meta.height)) + } + /// Current timeline position in seconds. pub fn now(&self) -> f64 { self.clock.now() @@ -4453,6 +4516,41 @@ mod tests { assert_eq!(blend_bgra(&a, &b, 0.5), [60, 70, 80, 255]); } + /// A still wants the project's own pixels, not a view near them. + /// [`PlaybackSession::set_view_size`] calls under 8 px no change at all (a + /// window being dragged must not restart the picture every tick), so a + /// caller that means "paint at the project's size" has to say it through + /// [`PlaybackSession::set_view_size_exact`] -- and read its `false` as "the + /// view is already there, the frame in hand is the one wanted", which is + /// what stops it waiting for a picture nothing will reseek into existence. + #[test] + fn a_still_gets_the_exact_view_size_where_a_push_settles_for_near() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + assert!(session.set_resolution(1920, 1080)); + let (w, h) = session.resolution(); + assert_eq!((w, h), (1920, 1080)); + // A preview-sized push, then the ask a still makes: two pixels short on + // each axis, which the deadbanded push calls no change at all. + assert!(session.set_view_size(1918, 1078)); + assert!( + std::ops::Not::not(session.set_view_size(w, h)), + "the push's deadband is exactly what a still cannot use" + ); + assert_eq!( + session.view_size(), + (1918, 1078), + "the push left the view near, not at, full -- so a still written now would be short" + ); + assert!( + session.set_view_size_exact(w, h), + "the exact setter must move a view the push called close enough" + ); + assert_eq!(session.view_size(), (w, h)); + // ...and at the size already it says so rather than repainting: that + // `false` is the caller's "write the frame you have". + assert!(std::ops::Not::not(session.set_view_size_exact(w, h))); + } + /// The dissolve window's own edges, in the units [`PlaybackSession::start_span`] /// computes them in: a `tail_start` of `span.start + span.len - window` /// puts the very first output frame of the window at `idx_in_window == 0`