Skip to main content

kitchen_views/
video_view.rs

1//! The video view: the frame at the clock's moment, an app's overlays over it, and what a
2//! researcher needs under it (the frame number, the time on both clocks, dropped frames, how well the clocks are
3//! aligned).
4//!
5//! It follows the workspace's [`Clock`]: on every move it maps the reference time onto the video's
6//! clock ([`Alignment`]), finds the frame shown then ([`crate::video::FrameTimes::frame_at`]), and
7//! shows it, from the cache or decoded off the UI thread (only the latest frame asked for is
8//! decoded: scrubbing fast does not queue up). Opening a video sets the clock's step to its frame
9//! interval, so frame steps land on frames. The playback keys work over it.
10//!
11//! Overlays ([`Overlay`]) are what an app paints over the frame without the view knowing what
12//! they are: segmentation outlines on a time-lapse (lucem), ROIs of calcium imaging or spike-time
13//! markers (dspk). Each is told where the frame is drawn and which frame it is ([`OverlayFrame`]).
14
15use std::rc::Rc;
16use std::sync::{Arc, Mutex};
17
18use gpui_kit::component::{h_flex, v_flex};
19use gpui_kit::{
20    App, Bounds, Context, Entity, InteractiveElement as _, IntoElement, ObjectFit, ParentElement as _, Render, RenderImage, SharedString, Styled as _, StyledImage as _,
21    Pixels, Point, Subscription, Window, canvas, div, img, point, px,
22};
23use kitchen_ui::theme::{self, color};
24use smallvec::SmallVec;
25
26use crate::clock::{Clock, ClockEvent, Faster, JumpBack, JumpForward, Slower, StepBack, StepForward, TogglePlay};
27use crate::sync::Alignment;
28use crate::video::{Frame, FrameCache, VideoError, VideoInfo, VideoSource};
29
30/// Where the shown frame is drawn and which it is, for an overlay to place what it paints:
31/// a point `(x, y)` in the video's pixels is at `origin + (x, y) · scale` in the window.
32#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct OverlayFrame {
34    pub index: usize,
35    /// On the video's own clock, in seconds.
36    pub time: f64,
37    pub width: u32,
38    pub height: u32,
39    pub origin: Point<Pixels>,
40    pub scale: f32,
41}
42
43impl OverlayFrame {
44    /// A point in the video's pixels, in the window.
45    pub fn at(&self, x: f32, y: f32) -> Point<Pixels> {
46        point(self.origin.x + px(x * self.scale), self.origin.y + px(y * self.scale))
47    }
48}
49
50/// Something an app paints over the video at the shown frame.
51pub type Overlay = Rc<dyn Fn(&mut Window, OverlayFrame)>;
52
53/// Where a video of `width` × `height` pixels is drawn inside `bounds` (scaled to fit, centred):
54/// its origin and scale.
55pub fn fit(bounds: Bounds<Pixels>, width: u32, height: u32) -> (Point<Pixels>, f32) {
56    let (bw, bh) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
57    let scale = (bw / width.max(1) as f32).min(bh / height.max(1) as f32);
58    let (w, h) = (width as f32 * scale, height as f32 * scale);
59    (point(bounds.origin.x + px((bw - w) / 2.0), bounds.origin.y + px((bh - h) / 2.0)), scale)
60}
61
62/// Decoded frames kept for scrubbing (bytes).
63const CACHE_BYTES: usize = 512 << 20;
64
65/// A video in a view, following a clock.
66pub struct VideoView {
67    source: Arc<Mutex<Box<dyn VideoSource>>>,
68    info: VideoInfo,
69    clock: Entity<Clock>,
70    alignment: Alignment,
71    cache: Arc<Mutex<FrameCache>>,
72    shown: Option<(usize, Arc<RenderImage>)>,
73    /// A decode is running.
74    busy: bool,
75    /// The frame to show next (asked for while a decode ran).
76    wanted: Option<usize>,
77    overlays: Vec<Overlay>,
78    error: Option<String>,
79    _clock: Subscription,
80}
81
82impl VideoView {
83    /// `source` in a view following `clock`, its time mapped onto the clock's by `alignment`.
84    pub fn new(source: Box<dyn VideoSource>, clock: Entity<Clock>, alignment: Alignment, cx: &mut Context<Self>) -> Self {
85        let info = source.info().clone();
86        let sub = cx.subscribe(&clock, |this, _, e: &ClockEvent, cx| {
87            if let ClockEvent::Moved(t) = e {
88                this.show_time(*t, cx);
89            }
90        });
91        // The clock steps by this video's frames, and runs over it
92        let step = info.times.median_interval();
93        let span = info.times.span().map(|(a, b)| (alignment.to_reference(a), alignment.to_reference(b)));
94        clock.update(cx, |c, cx| {
95            if let Some(s) = step {
96                c.set_step(s * alignment.slope);
97            }
98            if let Some((a, b)) = span {
99                let (a0, b0) = c.range().unwrap_or((a, b));
100                c.set_range(a.min(a0), b.max(b0), cx);
101            }
102        });
103        let mut view = Self {
104            source: Arc::new(Mutex::new(source)),
105            info,
106            clock: clock.clone(),
107            alignment,
108            cache: Arc::new(Mutex::new(FrameCache::new(CACHE_BYTES))),
109            shown: None,
110            busy: false,
111            wanted: None,
112            overlays: Vec::new(),
113            error: None,
114            _clock: sub,
115        };
116        let t = clock.read(cx).position();
117        view.show_time(t, cx);
118        view
119    }
120
121    pub fn info(&self) -> &VideoInfo {
122        &self.info
123    }
124
125    /// Maps the video's clock onto the reference with `alignment` (a sync-pulse fit, or a shift
126    /// set by hand); the frame shown follows.
127    pub fn set_alignment(&mut self, alignment: Alignment, cx: &mut Context<Self>) {
128        self.alignment = alignment;
129        let t = self.clock.read(cx).position();
130        self.show_time(t, cx);
131    }
132
133    /// Paints `overlay` over every frame shown, after the ones added before.
134    pub fn add_overlay(&mut self, overlay: Overlay, cx: &mut Context<Self>) {
135        self.overlays.push(overlay);
136        cx.notify();
137    }
138
139    /// Removes every overlay.
140    pub fn clear_overlays(&mut self, cx: &mut Context<Self>) {
141        self.overlays.clear();
142        cx.notify();
143    }
144
145    /// The frame index shown, when one is.
146    pub fn shown_frame(&self) -> Option<usize> {
147        self.shown.as_ref().map(|(i, _)| *i)
148    }
149
150    /// Shows the frame at reference time `t`.
151    fn show_time(&mut self, t: f64, cx: &mut Context<Self>) {
152        let Some(index) = self.info.times.frame_at(self.alignment.to_source(t)) else { return };
153        self.show(index, cx);
154    }
155
156    /// Shows frame `index`: from the cache at once, else decoded off the UI thread.
157    fn show(&mut self, index: usize, cx: &mut Context<Self>) {
158        if self.shown_frame() == Some(index) {
159            return;
160        }
161        // The lock is released at the end of this statement, before the frame is shown
162        let cached = self.cache.lock().unwrap_or_else(|e| e.into_inner()).get(index);
163        if let Some(frame) = cached {
164            self.set_shown(frame, cx);
165            return;
166        }
167        if self.busy {
168            self.wanted = Some(index);
169            return;
170        }
171        self.busy = true;
172        let (source, cache) = (self.source.clone(), self.cache.clone());
173        cx.spawn(async move |this, cx| {
174            let decoded = cx.background_executor().spawn(async move { source.lock().unwrap_or_else(|e| e.into_inner()).frame(index) }).await;
175            let _ = this.update(cx, |v, cx| {
176                v.busy = false;
177                match decoded {
178                    Ok(frame) => {
179                        cache.lock().unwrap_or_else(|e| e.into_inner()).put(frame.clone());
180                        v.error = None;
181                        v.set_shown(frame, cx);
182                    }
183                    Err(e) => v.error = Some(e.to_string()),
184                }
185                if let Some(next) = v.wanted.take() {
186                    v.show(next, cx);
187                }
188                cx.notify();
189            });
190        })
191        .detach();
192    }
193
194    fn set_shown(&mut self, frame: Frame, cx: &mut Context<Self>) {
195        match render_image(&frame) {
196            Ok(image) => self.shown = Some((frame.index, image)),
197            Err(e) => self.error = Some(e.to_string()),
198        }
199        cx.notify();
200    }
201
202    fn status(&self, cx: &App) -> String {
203        let clock = self.clock.read(cx);
204        let frames = self.info.frames();
205        let index = self.shown_frame().map_or("–".to_string(), |i| (i + 1).to_string());
206        let t_video = self.shown_frame().and_then(|i| self.info.times.time(i)).unwrap_or(0.0);
207        let gaps = self.info.times.gaps();
208        let dropped: usize = gaps.iter().map(|g| g.missing).sum();
209        let mut parts = vec![
210            format!("frame {index} / {frames}"),
211            format!("video {t_video:.3} s"),
212            format!("reference {:.3} s", clock.position()),
213        ];
214        if let Some(rate) = self.info.times.rate() {
215            parts.push(format!("{rate:.2} fps"));
216        }
217        if dropped > 0 {
218            parts.push(format!("{dropped} dropped in {} gaps", gaps.len()));
219        }
220        if self.alignment.pulses > 0 {
221            parts.push(format!("aligned on {} pulses, {:.2} ms rms", self.alignment.pulses, self.alignment.rms * 1e3));
222        }
223        if (clock.rate() - 1.0).abs() > 1e-9 {
224            parts.push(format!("{}×", clock.rate()));
225        }
226        parts.join(" · ")
227    }
228}
229
230/// `frame` as an image GPUI draws (BGRA).
231fn render_image(frame: &Frame) -> Result<Arc<RenderImage>, VideoError> {
232    let mut bgra = frame.rgba.as_ref().clone();
233    for px in bgra.chunks_exact_mut(4) {
234        px.swap(0, 2);
235    }
236    let buffer = image::RgbaImage::from_raw(frame.width, frame.height, bgra).ok_or_else(|| VideoError::Decode(format!("frame {}: wrong size", frame.index)))?;
237    let frames: SmallVec<[image::Frame; 1]> = SmallVec::from_elem(image::Frame::new(buffer), 1);
238    Ok(Arc::new(RenderImage::new(frames)))
239}
240
241impl Render for VideoView {
242    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
243        let (w, h) = (self.info.width, self.info.height);
244        let overlay = self.shown_frame().filter(|_| !self.overlays.is_empty()).map(|index| {
245            let (overlays, time) = (self.overlays.clone(), self.info.times.time(index).unwrap_or(0.0));
246            canvas(|_, _, _| (), move |bounds, _, window, _| {
247                let (origin, scale) = fit(bounds, w, h);
248                let frame = OverlayFrame { index, time, width: w, height: h, origin, scale };
249                for paint in &overlays {
250                    paint(window, frame);
251                }
252            })
253            .absolute()
254            .top_0()
255            .left_0()
256            .size_full()
257        });
258        let picture = match &self.shown {
259            Some((_, image)) => div().relative().size_full().child(img(image.clone()).size_full().object_fit(ObjectFit::Contain)).children(overlay).into_any_element(),
260            None => div()
261                .size_full()
262                .flex()
263                .items_center()
264                .justify_center()
265                .text_sm()
266                .text_color(color::text_muted())
267                .child(SharedString::from(self.error.clone().unwrap_or_else(|| "Decoding…".into())))
268                .into_any_element(),
269        };
270        let clock = self.clock.clone();
271        let step = move |frames: i64, cx: &mut App| clock.update(cx, |c, cx| c.step_by(frames, cx));
272        let (s1, s2, s3, s4) = (step.clone(), step.clone(), step.clone(), step);
273        let (c1, c2, c3) = (self.clock.clone(), self.clock.clone(), self.clock.clone());
274        v_flex()
275            .size_full()
276            .bg(gpui_kit::black())
277            .on_action(move |_: &StepForward, _, cx| s1(1, cx))
278            .on_action(move |_: &StepBack, _, cx| s2(-1, cx))
279            .on_action(move |_: &JumpForward, _, cx| s3(10, cx))
280            .on_action(move |_: &JumpBack, _, cx| s4(-10, cx))
281            .on_action(move |_: &TogglePlay, _, cx| c1.update(cx, |c, cx| c.toggle_play(cx)))
282            .on_action(move |_: &Faster, _, cx| c2.update(cx, |c, cx| c.change_rate(true, cx)))
283            .on_action(move |_: &Slower, _, cx| c3.update(cx, |c, cx| c.change_rate(false, cx)))
284            .child(div().flex_1().min_h_0().child(picture))
285            .child(
286                h_flex()
287                    .flex_none()
288                    .px(px(theme::SM))
289                    .py(px(theme::XS))
290                    .gap(px(theme::SM))
291                    .bg(color::panel())
292                    .border_t_1()
293                    .border_color(color::border())
294                    .text_xs()
295                    .font_family("monospace")
296                    .text_color(color::text_muted())
297                    .child(div().flex_1().min_w_0().truncate().child(self.status(cx)))
298                    .child(div().flex_none().child(SharedString::from(self.info.format.clone()))),
299            )
300            .children(self.error.clone().filter(|_| self.shown.is_some()).map(|e| div().px(px(theme::SM)).text_xs().text_color(color::danger()).child(e)))
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use gpui_kit::size;
307
308    use super::*;
309
310    #[test]
311    fn videos_fit_their_bounds_centred() {
312        let bounds = Bounds { origin: point(px(0.), px(0.)), size: size(px(200.), px(100.)) };
313        let (origin, scale) = fit(bounds, 100, 100);
314        assert_eq!((f32::from(origin.x), f32::from(origin.y), scale), (50.0, 0.0, 1.0));
315        let frame = OverlayFrame { index: 0, time: 0.0, width: 100, height: 100, origin, scale };
316        assert_eq!(f32::from(frame.at(10.0, 20.0).x), 60.0);
317    }
318}