forge
Explore
Log in

Don't you dare go Hollow

The preview paints at its own size, not the project's

Browse files at this commit

62b680ed5b9d1857431de4842aea05dfaa26809eAhmet Kaan GümüşParent: 72e32b8
  • perf
    • the preview paints at its own size, not the project's
Show full message
⚡ perf(audio): the preview paints at its own size, not the project's

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.rsmodified+20 -0
@@ -761,6 +761,23 @@ struct Player {
761761 viz_hs_dragging: bool,
762762 /// The wheel's box, recorded at prepaint for a drag's window position.
763763 viz_wheel: Rc<Cell<Bounds<Pixels>>>,
764+ /// Where the picture actually lands on screen, probed by the picture area
765+ /// (`render.rs`): what tells the session to paint at the size the preview
766+ /// is *watched* at rather than at the project's own
767+ /// ([`engine::PlaybackSession::set_view_size`]).
768+ picture_box: Rc<Cell<Bounds<Pixels>>>,
769+ /// A screenshot asked for while the picture was painted at the preview's
770+ /// own size: `(session, stem, timecode)`, written by [`Player::flush_shot`]
771+ /// once the seat has painted one frame at the project's size. Taken at the
772+ /// ask so a shot mid-playback is named for the frame it was asked at, not
773+ /// for the one it landed on -- and *keyed to the session that asked*, so a
774+ /// swap mid-flight (a preview opened, another file opened, a session
775+ /// closed) cannot have the new session's frame written under the old name
776+ /// ([`Player::session_swapped`]).
777+ shot_pending: Option<(u64, String, String)>,
778+ /// The active session's identity, for the above: bumped by every door that
779+ /// swaps `session` or `preview_session`.
780+ session_gen: u64,
764781 /// Which of the clip's two inks the look section's wheel and colour field
765782 /// act on ([`VizSlot`]): the clip's own colour, or the ring's dual half.
766783 /// The pick stays picked across clips, the way the dock tab's does.
@@ -1086,6 +1103,9 @@ fn main() {
10861103 color_dragging: false,
10871104 viz_hs_dragging: false,
10881105 viz_wheel: Rc::default(),
1106+ picture_box: Rc::default(),
1107+ shot_pending: None,
1108+ session_gen: 0,
10891109 viz_slot: VizSlot::Main,
10901110 viz_hex_edit: None,
10911111 pending_viz: None,
crates/app/src/player/library.rsmodified+4 -0
@@ -569,6 +569,7 @@ impl Player {
569569 /// again.
570570 pub(crate) fn close_session(&mut self) {
571571 self.session = None;
572+ self.session_swapped();
572573 // The picture goes with it, or the empty window would keep showing the
573574 // last frame of a timeline that no longer exists.
574575 //
@@ -677,6 +678,7 @@ impl Player {
677678 // reads as a frozen picture, not as a player awaiting a click.
678679 session.play();
679680 self.preview_session = Some(session);
681+ self.session_swapped();
680682 self.notify_user(
681683 format!(
682684 "PREVIEWING {} — not on the timeline; esc stops it",
@@ -1477,6 +1479,7 @@ impl Player {
14771479 // is not track 3 of this.
14781480 self.sub_track = 0;
14791481 self.session = Some(session);
1482+ self.session_swapped();
14801483 // A fresh session comes up at full volume; the player's own
14811484 // setting outlives the file, so it is pushed at every new one.
14821485 self.apply_volume();
@@ -1790,6 +1793,7 @@ impl Player {
17901793 // media: that is the only place an export has ever landed.
17911794 self.export_path = retarget(&export_path(&session.sources()[0].path), self.format);
17921795 self.session = Some(session);
1796+ self.session_swapped();
17931797 self.apply_volume();
17941798 // The other way round from every other door: a project carries
17951799 // its own two switches ([`engine::edith`]) and they are what it
crates/app/src/render.rsmodified+57 -0
@@ -76,6 +76,9 @@ impl Player {
7676 // bottom of the picture region, which is the one box that is the
7777 // picture and nothing else.
7878 .relative()
79+ // ...and the box the frame is *watched* in, which is what the
80+ // session paints at ([`Player::push_view_size`]).
81+ .child(bounds_probe(self.picture_box.clone()))
7982 .flex()
8083 .justify_center()
8184 .items_center()
@@ -125,6 +128,51 @@ impl Player {
125128 }
126129 }
127130
131+impl Player {
132+ /// Tells the active session where the picture actually lands, in device
133+ /// pixels, so its seats can paint at that size instead of the project's
134+ /// ([`engine::PlaybackSession::set_view_size`]). Read off the picture
135+ /// area's own bounds -- the box `letterboxed_image` fits the frame into --
136+ /// and the project's aspect, which is the aspect of every frame it hands
137+ /// over.
138+ ///
139+ /// A size that moved enough for the eye to see gets a fresh picture: the
140+ /// canvas a span paints at is decided when it opens, so a resized window
141+ /// would otherwise sharpen on its next seek and not before.
142+ fn push_view_size(&mut self, window: &mut Window) {
143+ if self.shot_pending.is_some() {
144+ // A screenshot in flight asked for the project's own size and is
145+ // waiting on that frame: pushing the preview's size back now would
146+ // cancel the very picture it is waiting for.
147+ return;
148+ }
149+ let region = self.picture_box.get();
150+ if region.size.width <= px(1.) || region.size.height <= px(1.) {
151+ // Before the first paint there is no box to read, and a floor is
152+ // not a measurement.
153+ return;
154+ }
155+ let scale = window.scale_factor();
156+ let Some(session) = self.active_session_mut() else {
157+ return;
158+ };
159+ // Device pixels, the unit `Contain` measures its fitting size in.
160+ let meta = session.meta();
161+ let fitted = gpui::ObjectFit::Contain.get_bounds(
162+ region,
163+ size(
164+ gpui::DevicePixels(meta.width as i32),
165+ gpui::DevicePixels(meta.height as i32),
166+ ),
167+ );
168+ let w = (f32::from(fitted.size.width) * scale).round() as u32;
169+ let h = (f32::from(fitted.size.height) * scale).round() as u32;
170+ if session.set_view_size(w, h) {
171+ session.resync_picture();
172+ }
173+ }
174+}
175+
128176 impl Render for Player {
129177 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
130178 // A file that has just been opened sits on its first frame with the
@@ -134,6 +182,15 @@ impl Render for Player {
134182 session.tick();
135183 }
136184 self.pump(window);
185+ // A screenshot waiting for its project-sized frame is written on the
186+ // repaint that lands it -- and before the size push below, which is
187+ // what gives the preview its own size back.
188+ self.flush_shot(cx);
189+ // ...at the size it is watched at, not the project's: a visualizer
190+ // seat redrawing 1920x1080 for a 600 px preview is nine times the
191+ // pixels for nothing the eye can see. An export has a seat of its own
192+ // and never comes through here.
193+ self.push_view_size(window);
137194 // What every hover label asks before it paints: a card or a menu is
138195 // drawn over whatever the pointer is resting on.
139196 OVERLAID.store(self.overlaid(), Ordering::Relaxed);
crates/app/src/ui/preview.rsmodified+112 -22
@@ -123,44 +123,134 @@ impl Player {
123123 )
124124 }
125125
126- /// The frame on screen right now, written to a PNG: `image` and its
127- /// `as_bytes` are gpui's own cached copy of what was last handed to the
128- /// atlas ([`Player::pump`]), so this reads no decoder and races nothing --
129- /// works during preview or on the timeline, whichever is showing.
126+ /// The frame on screen right now, written to a PNG -- at the size the
127+ /// **project** is, not at the size the preview shows it.
128+ ///
129+ /// The picture area asks the session for frames the size of its own box
130+ /// ([`PlaybackSession::set_view_size`]), so the atlas holds a preview-sized
131+ /// picture: saving that would cost the user the resolution they asked for
132+ /// (a still of a 1080p project, an 11th of it). So the seat is asked for
133+ /// one picture at the project's own size and the file is written when it
134+ /// lands ([`Player::flush_shot`], off `pump`'s frame-owed signal). Every
135+ /// other part of the gesture is what it always was: the same directory,
136+ /// the same name, the same notice.
137+ ///
138+ /// A library preview is the same rule about *its* file: the seat paints at
139+ /// the file's own resolution for it, which is the full size a still of that
140+ /// file wants.
130141 pub(crate) fn take_screenshot(&mut self, cx: &mut Context<Self>) {
131- let no_frame = || "NO FRAME TO SAVE — nothing is showing yet".to_string();
132- let Some(image) = self.image.clone() else {
133- self.notify_user(no_frame().into());
134- cx.notify();
135- return;
136- };
137- let Some(bytes) = image.as_bytes(0) else {
138- self.notify_user(no_frame().into());
142+ if self.shot_pending.is_some() {
143+ return; // one at a time: the picture is on its way
144+ }
145+ let Some(session) = self.active_session() else {
146+ self.notify_user("NO FRAME TO SAVE — nothing is showing yet".into());
139147 cx.notify();
140148 return;
141149 };
142- let size = image.size(0);
143- let stem = self
144- .active_session()
145- .and_then(|s| s.sources().first())
150+ let full = (session.meta().width, session.meta().height);
151+ let stem = session
152+ .sources()
153+ .first()
146154 .map_or_else(|| self.name.to_string(), |s| file_name(&s.path));
147155 let stem = std::path::Path::new(&stem)
148156 .file_stem()
149157 .map_or(stem.clone(), |s| s.to_string_lossy().into_owned());
150- let tc = timecode(
151- self.active_session().map_or(0., PlaybackSession::now),
152- self.active_fps(),
153- )
154- .replace(':', "-");
158+ let tc = timecode(session.now(), self.active_fps()).replace(':', "-");
159+ // The *exact* setter, not the deadbanded push: a view within 8 px of
160+ // the project is a still of the wrong size. `false` says the view is
161+ // already at it -- and then the frame in hand *is* the project's frame,
162+ // so waiting for a picture that would never come (nothing moved, so
163+ // nothing reseeks) is exactly the trap this avoids.
164+ let moved = self
165+ .active_session_mut()
166+ .is_some_and(|s| s.set_view_size_exact(full.0, full.1));
167+ if moved {
168+ // One frame at the project's own size, which is a reseek like any
169+ // other edit: the frame it owes is what the flush waits on.
170+ if let Some(session) = self.active_session_mut() {
171+ session.resync_picture();
172+ }
173+ self.shot_pending = Some((self.session_gen, stem, tc));
174+ self.reset_after_reseek();
175+ } else if !self.write_shot(&stem, &tc) {
176+ self.notify_user("NO FRAME TO SAVE — nothing is showing yet".into());
177+ }
178+ cx.notify();
179+ }
180+
181+ /// Writes the picture the atlas is holding, at the size it holds it, and
182+ /// says whether there was one. The tail [`Player::take_screenshot`] and
183+ /// [`Player::flush_shot`] share, so the two doors cannot write differently.
184+ fn write_shot(&mut self, stem: &str, tc: &str) -> bool {
185+ let Some(image) = self.image.clone() else {
186+ return false;
187+ };
188+ let Some(bytes) = image.as_bytes(0) else {
189+ return false;
190+ };
191+ let size = image.size(0);
155192 let text =
156- match save_screenshot(bytes, size.width.0 as u32, size.height.0 as u32, &stem, &tc) {
193+ match save_screenshot(bytes, size.width.0 as u32, size.height.0 as u32, stem, tc) {
157194 Ok(path) => format!("SAVED {}", path.display()),
158195 Err(e) => format!("SCREENSHOT FAILED: {e}"),
159196 };
160197 self.notify_user(text.into());
198+ true
199+ }
200+
201+ /// The screenshot a preview-sized picture had to wait for: written once the
202+ /// seat's project-sized frame has landed, then the preview takes its own
203+ /// size back ([`Player::push_view_size`] pushes it on the next repaint).
204+ ///
205+ /// A picture that never lands -- the timeline emptied, a source that died
206+ /// -- gives up rather than leaving the preview stuck at the project's size:
207+ /// the wait is bounded, and the notice names what happened.
208+ pub(crate) fn flush_shot(&mut self, cx: &mut Context<Self>) {
209+ let Some((asked, stem, tc)) = self.shot_pending.clone() else {
210+ return;
211+ };
212+ if asked != self.session_gen {
213+ // The session that asked is gone (a preview opened, another file
214+ // opened, a session closed): its picture is not coming, and the new
215+ // session's frame must not be written under its name.
216+ self.shot_pending = None;
217+ self.notify_user("NO FRAME TO SAVE — the session changed meanwhile".into());
218+ cx.notify();
219+ return;
220+ }
221+ if self
222+ .seek_since
223+ .is_some_and(|since| since.elapsed() < std::time::Duration::from_secs(2))
224+ {
225+ return; // the frame is still being painted
226+ }
227+ self.shot_pending = None;
228+ // The seat's own clamp is the truth about the size it can paint, which
229+ // is what the ask settled on ([`PlaybackSession::set_view_size_exact`]),
230+ // and with the push held while the shot is in flight
231+ // ([`Player::push_view_size`]) it is still holding it here.
232+ let want = self.active_session().map(PlaybackSession::view_size);
233+ let landed = self
234+ .image
235+ .as_ref()
236+ .map(|i| (i.size(0).width.0 as u32, i.size(0).height.0 as u32))
237+ == want;
238+ if !landed || !self.write_shot(&stem, &tc) {
239+ self.notify_user("NO FRAME TO SAVE — the picture could not be redrawn".into());
240+ }
161241 cx.notify();
162242 }
163243
244+ /// The active session has been swapped (`session` or `preview_session`):
245+ /// what anything keyed to a session has to hear. A screenshot in flight is
246+ /// the one such thing ([`Player::shot_pending`]), and it is *keyed* rather
247+ /// than cleared here because a door that forgot to call this would still be
248+ /// caught by the key -- the picture it is holding came from a session that
249+ /// is no longer the one on screen.
250+ pub(crate) fn session_swapped(&mut self) {
251+ self.session_gen += 1;
252+ }
253+
164254 /// The cues the *subtitle lanes* put on screen at `at`, over the picture and
165255 /// nothing else: bottom-centred where every player puts them, white on a
166256 /// plate so the film underneath cannot swallow them, and each cue its own
crates/engine/src/decode.rsmodified+94 -59
@@ -668,6 +668,9 @@ impl DecodeSession {
668668 return;
669669 }
670670 let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };
671+ // One frame's painting no longer allocates per strand per
672+ // frame: this thread lives for the span.
673+ let mut scratch = VizScratch::default();
671674 let mut render = Render::new(
672675 color,
673676 transform,
@@ -681,7 +684,8 @@ impl DecodeSession {
681684 return;
682685 }
683686 let t = f64::from(start_frame + index) / fps;
684- let (y, u, v) = visualizer_i420(&peaks, t, width, height, flags, paint);
687+ let (y, u, v) =
688+ visualizer_i420(&mut scratch, &peaks, t, width, height, flags, paint);
685689 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);
686690 if tx.send(frame).is_err() {
687691 return; // caller moved on
@@ -1735,6 +1739,26 @@ fn viz_span(
17351739 }
17361740 }
17371741
1742+/// What one frame's painting borrows instead of allocating, owned by whoever
1743+/// paints a *stream* of frames -- the visualizer worker's own thread, an
1744+/// export seat, a test -- and reused for every strand of every frame. Eight
1745+/// `Vec`s, against the twenty-seven a fresh set per strand cost a ring at
1746+/// eight strands.
1747+#[derive(Default)]
1748+pub(crate) struct VizScratch {
1749+ /// The frame's own columns, kept across frames to the widest picture yet.
1750+ lo: Vec<f32>,
1751+ hi: Vec<f32>,
1752+ sig: Vec<f32>,
1753+ /// One strand's sampled positions, the cells its Bresenham runs cover,
1754+ /// the chain's rows, the row band's candidates and their lower hull.
1755+ pts: Vec<(i32, i32)>,
1756+ chain: Vec<(i32, i32)>,
1757+ rows: Vec<(i32, usize, usize)>,
1758+ cand: Vec<(i32, i32)>,
1759+ hull: Vec<usize>,
1760+}
1761+
17381762 /// One segment's glow as its own disc, stamped at every Bresenham cell: what
17391763 /// a chain was painted by before [`viz_chain`], and still the cheaper of the
17401764 /// 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 {
18071831 (samples as u64) * (2 * u64::from(glow) + 1) < cells as u64
18081832 }
18091833
1834+/// How many cells [`viz_walk`] would push for these samples, without walking
1835+/// them: one per iteration of that loop, and it iterates `max(dx, dy) + 1`
1836+/// times a segment.
1837+fn chain_cells(pts: &[(i32, i32)]) -> usize {
1838+ pts.windows(2)
1839+ .map(|w| {
1840+ let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
1841+ dx.max(dy) as usize + 1
1842+ })
1843+ .sum()
1844+}
1845+
18101846 /// The Bresenham cells of one segment, collected rather than stamped: the same
18111847 /// walk [`viz_line`] used to rasterise, kept for [`viz_chain`] to paint the
18121848 /// whole chain from.
@@ -1855,13 +1891,18 @@ fn viz_chain(
18551891 h: usize,
18561892 cw: usize,
18571893 ch: usize,
1858- chain: &mut Vec<(i32, i32)>,
1894+ scratch: &mut VizScratch,
18591895 bg_y: u8,
18601896 ink_y: u8,
18611897 ink_u: u8,
18621898 ink_v: u8,
18631899 glow: u8,
18641900 ) {
1901+ let VizScratch { pts, chain, rows, cand, hull, .. } = scratch;
1902+ chain.clear();
1903+ for pair in pts.windows(2) {
1904+ viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain);
1905+ }
18651906 if chain.is_empty() {
18661907 return;
18671908 }
@@ -1880,7 +1921,7 @@ fn viz_chain(
18801921 // a pixel) and a repeat is the same candidate.
18811922 chain.sort_unstable_by_key(|&(x, row)| (row, x));
18821923 chain.dedup();
1883- let mut rows: Vec<(i32, usize, usize)> = Vec::new();
1924+ rows.clear();
18841925 let mut i = 0;
18851926 while i < chain.len() {
18861927 let row = chain[i].1;
@@ -1895,10 +1936,8 @@ fn viz_chain(
18951936 let mut band = 0usize;
18961937 // `(x, dy^2)` -- a candidate's horizontal offset is left to the cell that
18971938 // asks, its vertical one is its own.
1898- let mut cand: Vec<(i32, i32)> = Vec::new();
1899- // The candidates a run's cells are decided by, once the ones that can never
1900- // be nearest are off ([`viz_chain`]'s own note).
1901- let mut hull: Vec<usize> = Vec::new();
1939+ // ...and the candidates a run's cells are decided by, once the ones that
1940+ // can never be nearest are off ([`viz_chain`]'s own note).
19021941 for row in first..=last {
19031942 while band < rows.len() && rows[band].0 < row - g {
19041943 band += 1;
@@ -1981,25 +2020,25 @@ fn viz_chain(
19812020 }
19822021 hull.push(c);
19832022 }
2023+ // Only the hull's last two entries can change places as x moves
2024+ // forward, so this is a walk and not a search -- and `value` is
2025+ // asked of those two alone.
19842026 let mut hp = 0usize;
19852027 for x in x_lo..=x_hi {
1986- while hp + 1 < hull.len()
1987- && value(hull[hp + 1], x) <= value(hull[hp], x)
1988- {
2028+ while hp + 1 < hull.len() && value(hull[hp + 1], x) <= value(hull[hp], x) {
19892029 hp += 1;
19902030 }
19912031 let (cx, dy2) = cand[hull[hp]];
19922032 let d = x - cx;
19932033 let d2 = d * d + dy2;
1994- if d2 > g * g {
1995- continue;
2034+ if d2 <= g * g {
2035+ let fall = if d2 == 0 {
2036+ 1.0
2037+ } else {
2038+ (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()
2039+ };
2040+ viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v);
19962041 }
1997- let fall = if d2 == 0 {
1998- 1.0
1999- } else {
2000- (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()
2001- };
2002- viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v);
20032042 }
20042043 }
20052044 }
@@ -2010,6 +2049,7 @@ fn viz_chain(
20102049 /// envelope at pixel resolution, or a multi-strand ribbon. Ink is
20112050 /// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line.
20122051 pub(crate) fn visualizer_i420(
2052+ scratch: &mut VizScratch,
20132053 peaks: &[(f32, f32)],
20142054 t_secs: f64,
20152055 width: u32,
@@ -2036,9 +2076,12 @@ pub(crate) fn visualizer_i420(
20362076 y[z * w + col] = y[z * w + col].max(bg_y.saturating_add(18));
20372077 }
20382078
2039- let mut lo = vec![0.0f32; w];
2040- let mut hi = vec![0.0f32; w];
2041- let mut sig = vec![0.0f32; w];
2079+ scratch.lo.clear();
2080+ scratch.lo.resize(w, 0.0);
2081+ scratch.hi.clear();
2082+ scratch.hi.resize(w, 0.0);
2083+ scratch.sig.clear();
2084+ scratch.sig.resize(w, 0.0);
20422085 if !peaks.is_empty() {
20432086 let duration = peaks.len() as f64 / f64::from(VIZ_BUCKETS_PER_SEC);
20442087 let per_sec = f64::from(VIZ_BUCKETS_PER_SEC);
@@ -2081,9 +2124,9 @@ pub(crate) fn visualizer_i420(
20812124 mn = mn.min(l);
20822125 mx = mx.max(h);
20832126 }
2084- lo[col] = mn;
2085- hi[col] = mx;
2086- sig[col] = signed_at(origin + (col as f64 + 0.5) / w as f64 * window);
2127+ scratch.lo[col] = mn;
2128+ scratch.hi[col] = mx;
2129+ scratch.sig[col] = signed_at(origin + (col as f64 + 0.5) / w as f64 * window);
20872130 }
20882131 // Whole-file peak, not the window's: a 2s window that gains or loses
20892132 // a loud hit used to rescale every column, so the same bump changed
@@ -2094,9 +2137,9 @@ pub(crate) fn visualizer_i420(
20942137 .fold(0.0f32, f32::max);
20952138 if peak > 1e-4 {
20962139 for i in 0..w {
2097- lo[i] /= peak;
2098- hi[i] /= peak;
2099- sig[i] /= peak;
2140+ scratch.lo[i] /= peak;
2141+ scratch.hi[i] /= peak;
2142+ scratch.sig[i] /= peak;
21002143 }
21012144 }
21022145 }
@@ -2106,7 +2149,7 @@ pub(crate) fn visualizer_i420(
21062149 let tau = std::f64::consts::TAU;
21072150 let travel = t_secs * 1.35;
21082151 for col in 0..w {
2109- let env = lo[col].abs().max(hi[col]).max(0.06);
2152+ let env = scratch.lo[col].abs().max(scratch.hi[col]).max(0.06);
21102153 let x_phase = (col as f64 / w.max(1) as f64) * 2.15 * tau;
21112154 for s in 0..u32::from(viz_strands_of(paint)).max(1) {
21122155 let frac = s as f32 / (viz_strands_of(paint).max(2) as f32 - 1.0);
@@ -2141,8 +2184,6 @@ pub(crate) fn visualizer_i420(
21412184 let steps = w.max(h) * 4;
21422185 let strands = viz_strands_of(paint);
21432186 let glow = viz_glow_of(paint);
2144- let mut chain: Vec<(i32, i32)> = Vec::new();
2145- let mut pts: Vec<(i32, i32)> = Vec::new();
21462187 for strand in 0..strands {
21472188 let dual = strands >= 2 && strand >= strands / 2;
21482189 // The dual half takes the clip's own strand colour when it
@@ -2164,24 +2205,20 @@ pub(crate) fn visualizer_i420(
21642205 let (iy, iu, iv) = rgb_yuv(ir as i32, ig as i32, ib as i32);
21652206 let scale = 0.65 + 0.35 * f32::from(strand % 4) / 3.0;
21662207 let phase = f32::from(strand) * 0.35;
2167- pts.clear();
2208+ scratch.pts.clear();
21682209 for i in 0..=steps {
21692210 let t = i as f32 / steps as f32;
21702211 let theta = t * tau + t_secs as f32 * 1.1 + phase;
21712212 let col = ((t * w as f32) as usize).min(w.saturating_sub(1));
2172- let env = lo[col].abs().max(hi[col]);
2213+ let env = scratch.lo[col].abs().max(scratch.hi[col]);
21732214 let wobble = (theta * 3.0 + phase).sin() * 0.12 * env;
21742215 let r = r0 + amp * env * scale + amp * wobble;
21752216 let x = (cx + r * theta.cos()).round() as i32;
21762217 let row = (cy + r * theta.sin()).round() as i32;
2177- pts.push((x, row));
2178- }
2179- chain.clear();
2180- for pair in pts.windows(2) {
2181- viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, &mut chain);
2218+ scratch.pts.push((x, row));
21822219 }
2183- if viz_discs_are_cheaper(pts.len(), chain.len(), glow) {
2184- for pair in pts.windows(2) {
2220+ if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
2221+ for pair in scratch.pts.windows(2) {
21852222 viz_line(
21862223 &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0,
21872224 pair[1].1, bg_y, iy, iu, iv, glow,
@@ -2189,23 +2226,21 @@ pub(crate) fn visualizer_i420(
21892226 }
21902227 } else {
21912228 viz_chain(
2192- &mut y, &mut u, &mut v, w, h, cw, ch, &mut chain, bg_y, iy, iu, iv, glow,
2229+ &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, iy, iu, iv, glow,
21932230 );
21942231 }
21952232 }
21962233 }
21972234 VIZ_STYLE_WAVE => {
2198- let mut chain: Vec<(i32, i32)> = Vec::new();
2199- let mut pts: Vec<(i32, i32)> = Vec::new();
2235+ scratch.pts.clear();
22002236 for col in 0..w {
2201- pts.push((col as i32, (center - sig[col] * half).round() as i32));
2202- }
2203- for pair in pts.windows(2) {
2204- viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, &mut chain);
2237+ scratch
2238+ .pts
2239+ .push((col as i32, (center - scratch.sig[col] * half).round() as i32));
22052240 }
22062241 let glow = viz_glow_of(paint);
2207- if viz_discs_are_cheaper(pts.len(), chain.len(), glow) {
2208- for pair in pts.windows(2) {
2242+ if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
2243+ for pair in scratch.pts.windows(2) {
22092244 viz_line(
22102245 &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0,
22112246 pair[1].1, bg_y, ink_y, ink_u, ink_v, glow,
@@ -2213,7 +2248,7 @@ pub(crate) fn visualizer_i420(
22132248 }
22142249 } else {
22152250 viz_chain(
2216- &mut y, &mut u, &mut v, w, h, cw, ch, &mut chain, bg_y, ink_y, ink_u, ink_v,
2251+ &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v,
22172252 glow,
22182253 );
22192254 }
@@ -2223,8 +2258,8 @@ pub(crate) fn visualizer_i420(
22232258 // the fold+smooth above. Default look.
22242259 let glow = i32::from(viz_glow_of(paint));
22252260 for col in 0..w {
2226- let top = (center - hi[col] * half).round() as i32;
2227- let bot = (center - lo[col] * half).round() as i32;
2261+ let top = (center - scratch.hi[col] * half).round() as i32;
2262+ let bot = (center - scratch.lo[col] * half).round() as i32;
22282263 viz_span(
22292264 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top, bot, bg_y, ink_y, ink_u,
22302265 ink_v,
@@ -2570,7 +2605,7 @@ mod tests {
25702605 *p = (-a.abs(), a.abs());
25712606 }
25722607 let flags = 1u8;
2573- let (y, u, v) = visualizer_i420(&peaks, 1.0, 320, 180, flags, 0);
2608+ let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0);
25742609 let ink = y.iter().filter(|&&p| p > 40).count();
25752610 assert!(ink > 200, "envelope missing: {ink}");
25762611 assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}");
@@ -2583,13 +2618,13 @@ mod tests {
25832618 assert!(blue > 10, "default ink was not timeline blue: {blue}");
25842619
25852620 let ring = with_viz_style(flags, VIZ_STYLE_RING);
2586- let (yr, _, _) = visualizer_i420(&peaks, 1.0, 320, 180, ring, 0);
2621+ let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0);
25872622 let ring_ink = yr.iter().filter(|&&p| p > 40).count();
25882623 assert!(ring_ink > 80, "ring missing: {ring_ink}");
25892624 assert!(ring_ink < ink, "ring should be a stroke, not a fill");
25902625
25912626 let hue_paint = with_viz_paint_hue(0, 40);
2592- let (_, u2, v2) = visualizer_i420(&peaks, 1.0, 64, 32, flags, hue_paint);
2627+ let (_, u2, v2) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 64, 32, flags, hue_paint);
25932628 let mut shifted = 0usize;
25942629 for i in 0..u2.len() {
25952630 if u2[i] < 120 && v2[i] > 130 {
@@ -2686,7 +2721,7 @@ mod tests {
26862721 }
26872722 let ring = with_viz_style(1, VIZ_STYLE_RING);
26882723 let auto = VIZ_PAINT_AZURE;
2689- let (y0, u0, v0) = visualizer_i420(&peaks, 1.0, 320, 180, ring, auto);
2724+ let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto);
26902725
26912726 // The automatic dual is half a wheel from the clip's hue at the
26922727 // clip's own saturation; choosing exactly that colour changes
@@ -2696,14 +2731,14 @@ mod tests {
26962731 viz_sat_ui(auto),
26972732 );
26982733 assert!(viz_strand_set(same));
2699- let (ys, us, vs) = visualizer_i420(&peaks, 1.0, 320, 180, ring, same);
2734+ let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same);
27002735 assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame");
27012736 assert_eq!(us, u0);
27022737 assert_eq!(vs, v0);
27032738
27042739 // A colour of its own repaints the dual strands in it.
27052740 let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255);
2706- let (_, u1, v1) = visualizer_i420(&peaks, 1.0, 320, 180, ring, red);
2741+ let (_, u1, v1) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red);
27072742 let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count();
27082743 let auto_px = (0..u0.len()).filter(|&i| u0[i] < 110 && v0[i] > 200).count();
27092744 assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}");
@@ -2713,7 +2748,7 @@ mod tests {
27132748 // the unset picture, byte for byte.
27142749 let stale = auto | (77u64 << 32) | (9u64 << 40);
27152750 assert!(!viz_strand_set(stale));
2716- let (yt, ut, vt) = visualizer_i420(&peaks, 1.0, 320, 180, ring, stale);
2751+ let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale);
27172752 assert_eq!(yt, y0, "an unset strand colour is the frame it always was");
27182753 assert_eq!(ut, u0);
27192754 assert_eq!(vt, v0);
@@ -2761,7 +2796,7 @@ mod tests {
27612796 };
27622797 let flags = with_viz_style(1, style);
27632798 let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow);
2764- let (y, u, v) = visualizer_i420(&peaks, 37.5, 1920, 1080, flags, paint);
2799+ let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 37.5, 1920, 1080, flags, paint);
27652800 let mut hash = 0xcbf2_9ce4_8422_2325u64;
27662801 for buf in [&y, &u, &v] {
27672802 for &b in buf.iter() {
crates/engine/src/export.rsmodified+14 -2
@@ -4427,6 +4427,9 @@ enum ClipDecoder {
44274427 next: u32,
44284428 flags: u8,
44294429 paint: u64,
4430+ /// This seat's own painting scratch, kept for the whole export: the
4431+ /// same reuse the playback worker's thread does.
4432+ scratch: crate::decode::VizScratch,
44304433 y: Vec<u8>,
44314434 u: Vec<u8>,
44324435 v: Vec<u8>,
@@ -4555,6 +4558,7 @@ impl ClipDecoder {
45554558 next: start_frame,
45564559 flags,
45574560 paint,
4561+ scratch: crate::decode::VizScratch::default(),
45584562 y: Vec::new(),
45594563 u: Vec::new(),
45604564 v: Vec::new(),
@@ -4577,12 +4581,20 @@ impl ClipDecoder {
45774581 next,
45784582 flags,
45794583 paint,
4584+ scratch,
45804585 y,
45814586 u,
45824587 v,
45834588 } => {
4584- let (yy, uu, vv) =
4585- crate::decode::visualizer_i420(peaks, f64::from(*next) / *fps, *width, *height, *flags, *paint);
4589+ let (yy, uu, vv) = crate::decode::visualizer_i420(
4590+ scratch,
4591+ peaks,
4592+ f64::from(*next) / *fps,
4593+ *width,
4594+ *height,
4595+ *flags,
4596+ *paint,
4597+ );
45864598 *y = yy;
45874599 *u = uu;
45884600 *v = vv;
crates/engine/src/playback.rsmodified+107 -9
@@ -431,6 +431,11 @@ pub struct PlaybackSession {
431431 /// span most of the time.
432432 dissolve: Option<Dissolve>,
433433 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
434+ /// The size a front-end showing this session *on screen* wants its
435+ /// pictures at, in device pixels ([`Self::set_view_size`]). `None` is the
436+ /// project's own -- every file-level caller, every test, and an export,
437+ /// which has a seat of its own ([`crate::export`]) and never comes here.
438+ view: Option<(u32, u32)>,
434439 eos: bool,
435440 /// The mix the running mixer is reading, when there is one: what lets a
436441 /// fader and the master ceiling move without rebuilding the audio pipeline
@@ -632,6 +637,7 @@ impl PlaybackSession {
632637 span,
633638 span_priming: true,
634639 dissolve: None,
640+ view: None,
635641 eos: false,
636642 mix: None,
637643 priming: false,
@@ -761,6 +767,7 @@ impl PlaybackSession {
761767 span,
762768 span_priming: true,
763769 dissolve: None,
770+ view: None,
764771 eos: false,
765772 mix: None,
766773 priming: false,
@@ -854,6 +861,7 @@ impl PlaybackSession {
854861 span,
855862 span_priming: true,
856863 dissolve: None,
864+ view: None,
857865 eos: false,
858866 mix: None,
859867 priming: false,
@@ -1207,6 +1215,7 @@ impl PlaybackSession {
12071215 span,
12081216 span_priming: true,
12091217 dissolve: None,
1218+ view: None,
12101219 eos: false,
12111220 mix: None,
12121221 priming: false,
@@ -1749,6 +1758,10 @@ impl PlaybackSession {
17491758 /// video that is now the worker's own doing -- it opens the file, so it is
17501759 /// the one that finds out -- and nothing on this thread waits to hear it.
17511760 fn start_span(&mut self, span: Option<Span>) {
1761+ // The viewer's own size, once one has said it ([`Self::set_view_size`]):
1762+ // every picture below is painted at *this*, and the project's
1763+ // resolution otherwise.
1764+ let (canvas_w, canvas_h) = self.view_size();
17521765 // The outgoing span's own dissolve, if it ever opened B's decoder:
17531766 // that decoder's pictures were for a window this span is leaving
17541767 // (played through, paused before, or seeked away from), and never
@@ -1828,8 +1841,8 @@ impl PlaybackSession {
18281841 .copied()
18291842 .unwrap_or_default(),
18301843 Composer::new(
1831- self.meta.width,
1832- self.meta.height,
1844+ canvas_w,
1845+ canvas_h,
18331846 self.project.composite_fit_at(start),
18341847 ),
18351848 )
@@ -1861,8 +1874,8 @@ impl PlaybackSession {
18611874 .copied()
18621875 .unwrap_or_default(),
18631876 Composer::new(
1864- self.meta.width,
1865- self.meta.height,
1877+ canvas_w,
1878+ canvas_h,
18661879 self.project.composite_fit_at(start),
18671880 ),
18681881 self.project.composite_visualizer_at(start),
@@ -1918,7 +1931,7 @@ impl PlaybackSession {
19181931 // than kept in a local, because a `Composer` owns the scratch
19191932 // buffers it places through -- the value is not copied about.
19201933 let fit = self.project.composite_fit_at(start);
1921- let canvas = || Composer::new(self.meta.width, self.meta.height, fit);
1934+ let canvas = || Composer::new(canvas_w, canvas_h, fit);
19221935 // ...and the rendition an HDR source among them is mapped to,
19231936 // the project's own and constant across the span for that
19241937 // reason too.
@@ -1975,8 +1988,8 @@ impl PlaybackSession {
19751988 // span at all and gets one frame of it -- enough to put black on
19761989 // screen, and it ends where the timeline does, at once.
19771990 gap => Ok(DecodeSession::open_black(
1978- self.meta.width,
1979- self.meta.height,
1991+ canvas_w,
1992+ canvas_h,
19801993 gap.map_or(1, |s| s.len),
19811994 )),
19821995 };
@@ -2018,6 +2031,7 @@ impl PlaybackSession {
20182031 /// (still inside A's span) -- the same asymmetry
20192032 /// [`crate::export`]'s own `Dissolve` is built with.
20202033 fn open_dissolve_b(&mut self) {
2034+ let (canvas_w, canvas_h) = self.view_size();
20212035 let Some(d) = &self.dissolve else { return };
20222036 if d.b.is_some() {
20232037 return;
@@ -2038,8 +2052,8 @@ impl PlaybackSession {
20382052 .copied()
20392053 .unwrap_or_default();
20402054 let canvas = Composer::new(
2041- self.meta.width,
2042- self.meta.height,
2055+ canvas_w,
2056+ canvas_h,
20432057 self.project.composite_fit_at(b_start),
20442058 );
20452059 let tone = self.project.tone();
@@ -3567,6 +3581,55 @@ impl PlaybackSession {
35673581 }
35683582 }
35693583
3584+ /// Says how big the picture is on screen, in device pixels -- what a
3585+ /// front-end showing this session pushes once it knows where the picture
3586+ /// actually lands. Rendering a 1080p project's visualizer for a 600 px
3587+ /// preview costs nine times the pixels for nothing the eye can see; a
3588+ /// window that is fullscreen gets the project's own size back by pushing
3589+ /// it. `true` when the size moved enough to be worth a new picture: under
3590+ /// 8 px on both axes is a resize nobody can see, and a window being
3591+ /// dragged would otherwise restart the picture every tick.
3592+ pub fn set_view_size(&mut self, width: u32, height: u32) -> bool {
3593+ let want = self.view_want(width, height);
3594+ match self.view {
3595+ Some(now) if now.0.abs_diff(want.0) < 8 && now.1.abs_diff(want.1) < 8 => false,
3596+ _ => {
3597+ self.view = Some(want);
3598+ true
3599+ }
3600+ }
3601+ }
3602+
3603+ /// [`Self::set_view_size`] with no deadband: what asks for the *exact*
3604+ /// size rather than one within 8 px of it. A still saved at the project's
3605+ /// own pixels is a file whose dimensions are read back, so "close enough
3606+ /// to be invisible" is not close enough to be right. `true` when the view
3607+ /// moved, `false` when it was already there -- which is also the answer
3608+ /// that lets a caller skip waiting for a frame it already has.
3609+ pub fn set_view_size_exact(&mut self, width: u32, height: u32) -> bool {
3610+ let want = self.view_want(width, height);
3611+ match self.view {
3612+ Some(now) if now == want => false,
3613+ _ => {
3614+ self.view = Some(want);
3615+ true
3616+ }
3617+ }
3618+ }
3619+
3620+ /// The size a push of `(width, height)` settles on: even on both axes
3621+ /// (YUV 4:2:0 has no odd chroma) and never past the project's own.
3622+ fn view_want(&self, width: u32, height: u32) -> (u32, u32) {
3623+ let fit = |n: u32, cap: u32| (n & !1).clamp(2, cap.max(2));
3624+ (fit(width, self.meta.width), fit(height, self.meta.height))
3625+ }
3626+
3627+ /// The canvas a span's pictures are painted at: [`Self::set_view_size`]'s
3628+ /// size once one has been pushed, the project's own otherwise.
3629+ pub fn view_size(&self) -> (u32, u32) {
3630+ self.view.unwrap_or((self.meta.width, self.meta.height))
3631+ }
3632+
35703633 /// Current timeline position in seconds.
35713634 pub fn now(&self) -> f64 {
35723635 self.clock.now()
@@ -4453,6 +4516,41 @@ mod tests {
44534516 assert_eq!(blend_bgra(&a, &b, 0.5), [60, 70, 80, 255]);
44544517 }
44554518
4519+ /// A still wants the project's own pixels, not a view near them.
4520+ /// [`PlaybackSession::set_view_size`] calls under 8 px no change at all (a
4521+ /// window being dragged must not restart the picture every tick), so a
4522+ /// caller that means "paint at the project's size" has to say it through
4523+ /// [`PlaybackSession::set_view_size_exact`] -- and read its `false` as "the
4524+ /// view is already there, the frame in hand is the one wanted", which is
4525+ /// what stops it waiting for a picture nothing will reseek into existence.
4526+ #[test]
4527+ fn a_still_gets_the_exact_view_size_where_a_push_settles_for_near() {
4528+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4529+ assert!(session.set_resolution(1920, 1080));
4530+ let (w, h) = session.resolution();
4531+ assert_eq!((w, h), (1920, 1080));
4532+ // A preview-sized push, then the ask a still makes: two pixels short on
4533+ // each axis, which the deadbanded push calls no change at all.
4534+ assert!(session.set_view_size(1918, 1078));
4535+ assert!(
4536+ std::ops::Not::not(session.set_view_size(w, h)),
4537+ "the push's deadband is exactly what a still cannot use"
4538+ );
4539+ assert_eq!(
4540+ session.view_size(),
4541+ (1918, 1078),
4542+ "the push left the view near, not at, full -- so a still written now would be short"
4543+ );
4544+ assert!(
4545+ session.set_view_size_exact(w, h),
4546+ "the exact setter must move a view the push called close enough"
4547+ );
4548+ assert_eq!(session.view_size(), (w, h));
4549+ // ...and at the size already it says so rather than repainting: that
4550+ // `false` is the caller's "write the frame you have".
4551+ assert!(std::ops::Not::not(session.set_view_size_exact(w, h)));
4552+ }
4553+
44564554 /// The dissolve window's own edges, in the units [`PlaybackSession::start_span`]
44574555 /// computes them in: a `tail_start` of `span.start + span.len - window`
44584556 /// puts the very first output frame of the window at `idx_in_window == 0`