1use 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 _, Pixels, Point,
21 Render, RenderImage, SharedString, Styled as _, StyledImage as _, Subscription, Window, canvas, div, img, point,
22 px,
23};
24use kitchen_ui::theme::{self, color};
25use smallvec::SmallVec;
26
27use crate::clock::{Clock, ClockEvent, Faster, JumpBack, JumpForward, Slower, StepBack, StepForward, TogglePlay};
28use crate::sync::Alignment;
29use crate::video::{Frame, FrameCache, VideoError, VideoInfo, VideoSource};
30
31#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct OverlayFrame {
35 pub index: usize,
36 pub time: f64,
38 pub width: u32,
39 pub height: u32,
40 pub origin: Point<Pixels>,
41 pub scale: f32,
42}
43
44impl OverlayFrame {
45 pub fn at(&self, x: f32, y: f32) -> Point<Pixels> {
47 point(self.origin.x + px(x * self.scale), self.origin.y + px(y * self.scale))
48 }
49}
50
51pub type Overlay = Rc<dyn Fn(&mut Window, OverlayFrame)>;
53
54pub fn fit(bounds: Bounds<Pixels>, width: u32, height: u32) -> (Point<Pixels>, f32) {
57 let (bw, bh) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
58 let scale = (bw / width.max(1) as f32).min(bh / height.max(1) as f32);
59 let (w, h) = (width as f32 * scale, height as f32 * scale);
60 (point(bounds.origin.x + px((bw - w) / 2.0), bounds.origin.y + px((bh - h) / 2.0)), scale)
61}
62
63const CACHE_BYTES: usize = 512 << 20;
65
66pub struct VideoView {
68 source: Arc<Mutex<Box<dyn VideoSource>>>,
69 info: VideoInfo,
70 clock: Entity<Clock>,
71 alignment: Alignment,
72 cache: Arc<Mutex<FrameCache>>,
73 shown: Option<(usize, Arc<RenderImage>)>,
74 busy: bool,
76 wanted: Option<usize>,
78 overlays: Vec<Overlay>,
79 error: Option<String>,
80 _clock: Subscription,
81}
82
83impl VideoView {
84 pub fn new(
86 source: Box<dyn VideoSource>,
87 clock: Entity<Clock>,
88 alignment: Alignment,
89 cx: &mut Context<Self>,
90 ) -> Self {
91 let info = source.info().clone();
92 let sub = cx.subscribe(&clock, |this, _, e: &ClockEvent, cx| {
93 if let ClockEvent::Moved(t) = e {
94 this.show_time(*t, cx);
95 }
96 });
97 let step = info.times.median_interval();
99 let span = info.times.span().map(|(a, b)| (alignment.to_reference(a), alignment.to_reference(b)));
100 clock.update(cx, |c, cx| {
101 if let Some(s) = step {
102 c.set_step(s * alignment.slope);
103 }
104 if let Some((a, b)) = span {
105 let (a0, b0) = c.range().unwrap_or((a, b));
106 c.set_range(a.min(a0), b.max(b0), cx);
107 }
108 });
109 let mut view = Self {
110 source: Arc::new(Mutex::new(source)),
111 info,
112 clock: clock.clone(),
113 alignment,
114 cache: Arc::new(Mutex::new(FrameCache::new(CACHE_BYTES))),
115 shown: None,
116 busy: false,
117 wanted: None,
118 overlays: Vec::new(),
119 error: None,
120 _clock: sub,
121 };
122 let t = clock.read(cx).position();
123 view.show_time(t, cx);
124 view
125 }
126
127 pub fn info(&self) -> &VideoInfo {
128 &self.info
129 }
130
131 pub fn set_alignment(&mut self, alignment: Alignment, cx: &mut Context<Self>) {
134 self.alignment = alignment;
135 let t = self.clock.read(cx).position();
136 self.show_time(t, cx);
137 }
138
139 pub fn add_overlay(&mut self, overlay: Overlay, cx: &mut Context<Self>) {
141 self.overlays.push(overlay);
142 cx.notify();
143 }
144
145 pub fn clear_overlays(&mut self, cx: &mut Context<Self>) {
147 self.overlays.clear();
148 cx.notify();
149 }
150
151 pub fn shown_frame(&self) -> Option<usize> {
153 self.shown.as_ref().map(|(i, _)| *i)
154 }
155
156 fn show_time(&mut self, t: f64, cx: &mut Context<Self>) {
158 let Some(index) = self.info.times.frame_at(self.alignment.to_source(t)) else { return };
159 self.show(index, cx);
160 }
161
162 fn show(&mut self, index: usize, cx: &mut Context<Self>) {
164 if self.shown_frame() == Some(index) {
165 return;
166 }
167 let cached = self.cache.lock().unwrap_or_else(|e| e.into_inner()).get(index);
169 if let Some(frame) = cached {
170 self.set_shown(frame, cx);
171 return;
172 }
173 if self.busy {
174 self.wanted = Some(index);
175 return;
176 }
177 self.busy = true;
178 let (source, cache) = (self.source.clone(), self.cache.clone());
179 cx.spawn(async move |this, cx| {
180 let decoded = cx
181 .background_executor()
182 .spawn(async move { source.lock().unwrap_or_else(|e| e.into_inner()).frame(index) })
183 .await;
184 let _ = this.update(cx, |v, cx| {
185 v.busy = false;
186 match decoded {
187 Ok(frame) => {
188 cache.lock().unwrap_or_else(|e| e.into_inner()).put(frame.clone());
189 v.error = None;
190 v.set_shown(frame, cx);
191 }
192 Err(e) => v.error = Some(e.to_string()),
193 }
194 if let Some(next) = v.wanted.take() {
195 v.show(next, cx);
196 }
197 cx.notify();
198 });
199 })
200 .detach();
201 }
202
203 fn set_shown(&mut self, frame: Frame, cx: &mut Context<Self>) {
204 match render_image(&frame) {
205 Ok(image) => self.shown = Some((frame.index, image)),
206 Err(e) => self.error = Some(e.to_string()),
207 }
208 cx.notify();
209 }
210
211 fn status(&self, cx: &App) -> String {
212 let clock = self.clock.read(cx);
213 let frames = self.info.frames();
214 let index = self.shown_frame().map_or("–".to_string(), |i| (i + 1).to_string());
215 let t_video = self.shown_frame().and_then(|i| self.info.times.time(i)).unwrap_or(0.0);
216 let gaps = self.info.times.gaps();
217 let dropped: usize = gaps.iter().map(|g| g.missing).sum();
218 let mut parts = vec![
219 format!("frame {index} / {frames}"),
220 format!("video {t_video:.3} s"),
221 format!("reference {:.3} s", clock.position()),
222 ];
223 if let Some(rate) = self.info.times.rate() {
224 parts.push(format!("{rate:.2} fps"));
225 }
226 if dropped > 0 {
227 parts.push(format!("{dropped} dropped in {} gaps", gaps.len()));
228 }
229 if self.alignment.pulses > 0 {
230 parts.push(format!("aligned on {} pulses, {:.2} ms rms", self.alignment.pulses, self.alignment.rms * 1e3));
231 }
232 if (clock.rate() - 1.0).abs() > 1e-9 {
233 parts.push(format!("{}×", clock.rate()));
234 }
235 parts.join(" · ")
236 }
237}
238
239fn render_image(frame: &Frame) -> Result<Arc<RenderImage>, VideoError> {
241 let mut bgra = frame.rgba.as_ref().clone();
242 for px in bgra.chunks_exact_mut(4) {
243 px.swap(0, 2);
244 }
245 let buffer = image::RgbaImage::from_raw(frame.width, frame.height, bgra)
246 .ok_or_else(|| VideoError::Decode(format!("frame {}: wrong size", frame.index)))?;
247 let frames: SmallVec<[image::Frame; 1]> = SmallVec::from_elem(image::Frame::new(buffer), 1);
248 Ok(Arc::new(RenderImage::new(frames)))
249}
250
251impl Render for VideoView {
252 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
253 let (w, h) = (self.info.width, self.info.height);
254 let overlay = self.shown_frame().filter(|_| !self.overlays.is_empty()).map(|index| {
255 let (overlays, time) = (self.overlays.clone(), self.info.times.time(index).unwrap_or(0.0));
256 canvas(
257 |_, _, _| (),
258 move |bounds, _, window, _| {
259 let (origin, scale) = fit(bounds, w, h);
260 let frame = OverlayFrame { index, time, width: w, height: h, origin, scale };
261 for paint in &overlays {
262 paint(window, frame);
263 }
264 },
265 )
266 .absolute()
267 .top_0()
268 .left_0()
269 .size_full()
270 });
271 let picture = match &self.shown {
272 Some((_, image)) => div()
273 .relative()
274 .size_full()
275 .child(img(image.clone()).size_full().object_fit(ObjectFit::Contain))
276 .children(overlay)
277 .into_any_element(),
278 None => div()
279 .size_full()
280 .flex()
281 .items_center()
282 .justify_center()
283 .text_sm()
284 .text_color(color::text_muted())
285 .child(SharedString::from(self.error.clone().unwrap_or_else(|| "Decoding…".into())))
286 .into_any_element(),
287 };
288 let clock = self.clock.clone();
289 let step = move |frames: i64, cx: &mut App| clock.update(cx, |c, cx| c.step_by(frames, cx));
290 let (s1, s2, s3, s4) = (step.clone(), step.clone(), step.clone(), step);
291 let (c1, c2, c3) = (self.clock.clone(), self.clock.clone(), self.clock.clone());
292 v_flex()
293 .size_full()
294 .bg(gpui_kit::black())
295 .on_action(move |_: &StepForward, _, cx| s1(1, cx))
296 .on_action(move |_: &StepBack, _, cx| s2(-1, cx))
297 .on_action(move |_: &JumpForward, _, cx| s3(10, cx))
298 .on_action(move |_: &JumpBack, _, cx| s4(-10, cx))
299 .on_action(move |_: &TogglePlay, _, cx| c1.update(cx, |c, cx| c.toggle_play(cx)))
300 .on_action(move |_: &Faster, _, cx| c2.update(cx, |c, cx| c.change_rate(true, cx)))
301 .on_action(move |_: &Slower, _, cx| c3.update(cx, |c, cx| c.change_rate(false, cx)))
302 .child(div().flex_1().min_h_0().child(picture))
303 .child(
304 h_flex()
305 .flex_none()
306 .px(px(theme::SM))
307 .py(px(theme::XS))
308 .gap(px(theme::SM))
309 .bg(color::panel())
310 .border_t_1()
311 .border_color(color::border())
312 .text_xs()
313 .font_family("monospace")
314 .text_color(color::text_muted())
315 .child(div().flex_1().min_w_0().truncate().child(self.status(cx)))
316 .child(div().flex_none().child(SharedString::from(self.info.format.clone()))),
317 )
318 .children(
319 self.error
320 .clone()
321 .filter(|_| self.shown.is_some())
322 .map(|e| div().px(px(theme::SM)).text_xs().text_color(color::danger()).child(e)),
323 )
324 }
325}
326
327#[cfg(test)]
328mod tests {
329 use gpui_kit::size;
330
331 use super::*;
332
333 #[test]
334 fn videos_fit_their_bounds_centred() {
335 let bounds = Bounds { origin: point(px(0.), px(0.)), size: size(px(200.), px(100.)) };
336 let (origin, scale) = fit(bounds, 100, 100);
337 assert_eq!((f32::from(origin.x), f32::from(origin.y), scale), (50.0, 0.0, 1.0));
338 let frame = OverlayFrame { index: 0, time: 0.0, width: 100, height: 100, origin, scale };
339 assert_eq!(f32::from(frame.at(10.0, 20.0).x), 60.0);
340 }
341}