//! `voelin-ui`'s `video.rs` delivery (`deliver`, `FrameSlot`, `Handoff`, //! `Buffers`, video.rs:360-480) ported to GPUI: decoded frames become //! `Arc` (BGRA) instead of Slint pixel buffers. //! //! What carries over unchanged: the decoder hands over its newest frame only //! and never waits for the conversion; a converter thread converts only what //! the window can show; the window takes the newest picture from a //! [`Latest`] and is woken only when the slot was empty. //! //! What does not: buffer reuse. A `RenderImage` owns its pixels //! (`SmallVec<[image::Frame; 1]>`, private, no accessor), so the buffer of //! a picture the window let go of cannot be recovered and every frame is a //! new allocation. [`Buffers`] keeps the shape (and the size check) without //! the reuse; the allocator may still hand the same memory back. use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError}; use gpui_kit::RenderImage; use spike_common::bgra::render_image; use spike_common::meter::Counter; use voelin_core::media::Latest; use voelin_media::VideoFrame; use crate::convert::Order; /// What the converter counts. #[derive(Clone, Default)] pub struct Counts { /// Frames the decoder (or the raw source) handed over. pub arrived: Counter, /// Frames converted into pictures. pub converted: Counter, /// Microseconds spent converting (with the allocation), summed. pub convert_us: Counter, } /// A callback for the decoder that converts its newest frame on a thread of /// its own into `pictures`; `wake` runs (on that thread) when a picture is /// ready and none was waiting. pub fn deliver( pictures: Arc>>, order: Order, counts: Counts, wake: impl Fn() + Send + Sync + 'static, ) -> impl FnMut(Arc) + Send + 'static { let slot = Arc::new(FrameSlot::default()); let wake = Arc::new(wake); let thread = { let (slot, pictures, wake, counts) = (slot.clone(), pictures.clone(), wake.clone(), counts.clone()); std::thread::Builder::new().name("voelin-picture".into()).spawn(move || { let mut buffers = Buffers::new(order, counts); while let Some(frame) = slot.wait() { buffers.show(&frame, &pictures, &*wake); } }) }; let mut inline = match thread { Ok(_) => None, Err(e) => { log::warn!("no picture thread, converting on the decoder's: {e}"); Some(Buffers::new(order, counts.clone())) } }; let handoff = Handoff(slot); move |frame: Arc| { counts.arrived.incr(); match &mut inline { Some(buffers) => buffers.show(&frame, &pictures, &*wake), None => handoff.0.put(frame), } } } /// The newest decoded frame, waiting for the converter thread. #[derive(Default)] struct FrameSlot { /// The frame, and whether the decoder is gone. state: Mutex<(Option>, bool)>, ready: Condvar, } impl FrameSlot { /// Replace the waiting frame (an older one is never converted). fn put(&self, frame: Arc) { self.state.lock().unwrap_or_else(PoisonError::into_inner).0 = Some(frame); self.ready.notify_one(); } fn close(&self) { self.state.lock().unwrap_or_else(PoisonError::into_inner).1 = true; self.ready.notify_one(); } /// The next frame; `None` once the decoder is gone. fn wait(&self) -> Option> { let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); loop { if state.1 { return None; } if let Some(frame) = state.0.take() { return Some(frame); } state = self.ready.wait(state).unwrap_or_else(PoisonError::into_inner); } } } /// The decoder's side of a [`FrameSlot`]: dropped with the decoder's /// callback, it ends the converter thread. struct Handoff(Arc); impl Drop for Handoff { fn drop(&mut self) { self.0.close(); } } /// Converts frames into new pictures (see the module docs on reuse). struct Buffers { order: Order, counts: Counts, /// Size of the last picture. size: (u32, u32), } /// Pictures converted so far (for the log line of the first one). static CONVERTED: AtomicU64 = AtomicU64::new(0); impl Buffers { fn new(order: Order, counts: Counts) -> Self { Self { order, counts, size: (0, 0) } } fn show(&mut self, frame: &VideoFrame, pictures: &Latest>, wake: &dyn Fn()) { let (width, height) = (frame.width, frame.height); if self.size != (width, height) { log::info!("pictures of {width}x{height}"); self.size = (width, height); } let started = std::time::Instant::now(); let stride = width as usize * 4; let mut bgra = vec![0u8; stride * height as usize]; if let Err(e) = self.order.convert(frame, &mut bgra, stride) { log::warn!("cannot show a picture: {e}"); return; } let picture = render_image(width, height, bgra); self.counts.convert_us.add(started.elapsed().as_micros() as u64); self.counts.converted.incr(); if CONVERTED.fetch_add(1, Ordering::Relaxed) == 0 { log::info!("first picture converted ({:?})", self.order); } if pictures.put(picture) { wake(); } } }