Skip to main content

moq_ext_egui/
lib.rs

1//! Video views for egui, on top of [`moq_ext_player`].
2//!
3//! The views draw decoded frames through the `wgpu` renderer in
4//! [`moq_video::render`]. They need an [`egui_wgpu::RenderState`]. A view without
5//! one shows a black placeholder.
6//!
7//! This draws a player's video:
8//!
9//! ```no_run
10//! use moq_ext_egui::VideoView;
11//!
12//! # fn draw(
13//! #     ctx: &egui::Context,
14//! #     ui: &mut egui::Ui,
15//! #     player: &moq_ext_player::Player,
16//! #     render_state: Option<&moq_ext_egui::egui_wgpu::RenderState>,
17//! # ) {
18//! let mut view = VideoView::new(ctx, "video", player.video_frames(), render_state);
19//! // in the update loop:
20//! ui.add(view.render());
21//! # }
22//! ```
23//!
24//! [`VideoView`] draws a [`VideoFrames`] stream, and [`FrameView`] the frames
25//! you hand it. [`overlay::DebugOverlay`] paints stats over a video.
26//! [`Pending`] runs a task, such as a dial, whose result a window collects on
27//! a later frame.
28//!
29//! Open the window with [`egui_wgpu_config`] as eframe's `wgpu_options`.
30//! Without it, eframe builds a device that cannot import DMA-BUF frames on
31//! Linux, so hardware-decoded video and screen capture are copied through the
32//! CPU, and a GPU with small limits, such as the Raspberry Pi 4, fails to open
33//! the window:
34//!
35//! ```ignore
36//! let options = eframe::NativeOptions {
37//!     wgpu_options: moq_ext_egui::egui_wgpu_config(),
38//!     ..Default::default()
39//! };
40//! ```
41
42#![forbid(unsafe_code)]
43
44pub mod overlay;
45mod pending;
46
47use std::sync::Arc;
48
49pub use egui_wgpu;
50/// The `wgpu` crate the renderer links.
51///
52/// Use it to name `wgpu` types, so they always match the renderer's version.
53/// egui-wgpu and moq-video link the same `wgpu` major (see the workspace
54/// manifest).
55pub use egui_wgpu::wgpu;
56use moq_ext_player::VideoFrames;
57use tracing::warn;
58#[cfg(target_os = "linux")]
59use tracing::{debug, info};
60
61pub use self::pending::Pending;
62
63/// Formats a bitrate as `1.5 Mbps`, `320 kbps` or `64 bps`.
64#[must_use]
65pub fn format_bitrate(rate: moq_net::bandwidth::Rate) -> String {
66    let bps = rate.as_bps() as f64;
67    if bps >= 1_000_000.0 {
68        format!("{:.1} Mbps", bps / 1_000_000.0)
69    } else if bps >= 1_000.0 {
70        format!("{:.0} kbps", bps / 1_000.0)
71    } else {
72        format!("{bps:.0} bps")
73    }
74}
75
76/// A renderer that draws decoded frames into an egui texture.
77#[derive(derive_more::Debug)]
78struct EguiVideoRenderer {
79    #[debug(skip)]
80    renderer: moq_video::render::Renderer,
81    #[debug(skip)]
82    render_state: egui_wgpu::RenderState,
83    /// The registered texture and its size, once a frame is drawn.
84    texture: Option<(egui::TextureId, (u32, u32))>,
85}
86
87impl EguiVideoRenderer {
88    /// Creates a renderer bound to `render_state`'s device and queue.
89    fn new(render_state: &egui_wgpu::RenderState) -> Result<Self, moq_video::Error> {
90        #[cfg(target_os = "linux")]
91        hint_dmabuf_import(render_state);
92        let renderer = moq_video::render::Renderer::new(
93            &render_state.device,
94            &render_state.queue,
95            moq_video::render::Config::new(),
96        )?;
97        Ok(Self {
98            renderer,
99            render_state: render_state.clone(),
100            texture: None,
101        })
102    }
103
104    /// Draws `frame` and registers or updates its egui texture.
105    fn render(&mut self, frame: &moq_video::Frame) -> Result<(), moq_video::Error> {
106        let texture = self.renderer.render(frame)?;
107        let view = texture.create_view(&Default::default());
108        let size = (texture.width(), texture.height());
109
110        let device = &self.render_state.device;
111        let mut egui_renderer = self.render_state.renderer.write();
112        let id = match self.texture {
113            Some((id, _)) => {
114                egui_renderer.update_egui_texture_from_wgpu_texture(
115                    device,
116                    &view,
117                    wgpu::FilterMode::Linear,
118                    id,
119                );
120                id
121            }
122            None => egui_renderer.register_native_texture(device, &view, wgpu::FilterMode::Linear),
123        };
124        self.texture = Some((id, size));
125        Ok(())
126    }
127}
128
129impl Drop for EguiVideoRenderer {
130    /// Frees the texture registered with egui.
131    ///
132    /// Without this, every dropped view would leave a stale native texture
133    /// registration in egui's render state.
134    fn drop(&mut self) {
135        if let Some((id, _)) = self.texture.take() {
136            self.render_state.renderer.write().free_texture(&id);
137        }
138    }
139}
140
141/// A view that draws the frames you hand it.
142///
143/// It shows the last drawn frame, or a black placeholder before the first.
144#[derive(derive_more::Debug)]
145pub struct FrameView {
146    renderer: Option<EguiVideoRenderer>,
147    #[debug(skip)]
148    placeholder: egui::TextureHandle,
149    /// Whether the last frame failed to draw, so a run of failures warns once.
150    failing: bool,
151}
152
153impl FrameView {
154    /// Creates a view that draws through `render_state`.
155    ///
156    /// `name` names the placeholder texture. If `render_state` is `None` or the
157    /// renderer fails to build, the view only shows the placeholder.
158    #[must_use]
159    pub fn new(
160        ctx: &egui::Context,
161        name: &str,
162        render_state: Option<&egui_wgpu::RenderState>,
163    ) -> Self {
164        let renderer = render_state.and_then(|render_state| {
165            EguiVideoRenderer::new(render_state)
166                .inspect_err(|err| warn!(error = %err, "wgpu video renderer init failed"))
167                .ok()
168        });
169        let placeholder = ctx.load_texture(
170            name,
171            egui::ColorImage::filled([1, 1], egui::Color32::BLACK),
172            Default::default(),
173        );
174        Self {
175            renderer,
176            placeholder,
177            failing: false,
178        }
179    }
180
181    /// Draws `frame`, replacing what the view showed before.
182    ///
183    /// Keeps the old picture if drawing fails, and warns once per run of
184    /// failures. A view without a renderer ignores the frame.
185    pub fn render_frame(&mut self, frame: &moq_video::Frame) {
186        let Some(renderer) = &mut self.renderer else {
187            return;
188        };
189        match renderer.render(frame) {
190            Ok(()) => self.failing = false,
191            Err(err) if !self.failing => {
192                self.failing = true;
193                warn!(error = %err, "video render failed, keeping the last picture");
194            }
195            Err(_) => {}
196        }
197    }
198
199    /// Returns an [`egui::Image`] of the current frame, or of the placeholder.
200    pub fn image(&self) -> egui::Image<'_> {
201        match self.renderer.as_ref().and_then(|renderer| renderer.texture) {
202            Some((id, (width, height))) => {
203                let size = egui::vec2(width as f32, height as f32);
204                egui::Image::from_texture(egui::load::SizedTexture::new(id, size)).shrink_to_fit()
205            }
206            None => egui::Image::from_texture(&self.placeholder).shrink_to_fit(),
207        }
208    }
209}
210
211/// A view that draws a [`VideoFrames`] stream.
212///
213/// It wakes the window when a frame arrives and draws the newest frame on the
214/// next pass.
215#[derive(derive_more::Debug)]
216pub struct VideoView {
217    frames: Option<VideoFrames>,
218    frame_view: FrameView,
219    #[debug(skip)]
220    last: Option<Arc<moq_video::Frame>>,
221    /// The context a new stream's wake task repaints.
222    #[debug(skip)]
223    ctx: egui::Context,
224    /// Wakes the window on each frame. Dropping it stops the task.
225    _wake: Option<n0_future::task::AbortOnDropHandle<()>>,
226}
227
228/// Spawns a task that requests a repaint whenever a frame arrives.
229///
230/// The player hands a frame over when it is due. Repainting on a timer would
231/// show it up to one tick late, and the uneven delay makes a steady stream
232/// judder. The task reads its own clone of `frames`, so it does not take
233/// frames from the drawing pass.
234fn wake_on_frame(
235    ctx: &egui::Context,
236    frames: Option<&VideoFrames>,
237) -> Option<n0_future::task::AbortOnDropHandle<()>> {
238    let ctx = ctx.clone();
239    let mut frames = frames?.clone();
240    Some(n0_future::task::AbortOnDropHandle::new(
241        n0_future::task::spawn(async move {
242            while frames.next().await.is_some() {
243                ctx.request_repaint();
244            }
245        }),
246    ))
247}
248
249impl VideoView {
250    /// Creates a view of `frames` that draws through `render_state`.
251    ///
252    /// `name` names the placeholder texture. A view without frames shows the
253    /// placeholder until [`set_frames`](Self::set_frames) gives it some.
254    ///
255    /// # Panics
256    ///
257    /// Panics when called outside a Tokio runtime with `frames` given.
258    #[must_use]
259    pub fn new(
260        ctx: &egui::Context,
261        name: &str,
262        frames: impl Into<Option<VideoFrames>>,
263        render_state: Option<&egui_wgpu::RenderState>,
264    ) -> Self {
265        let frames = frames.into();
266        Self {
267            _wake: wake_on_frame(ctx, frames.as_ref()),
268            frames,
269            frame_view: FrameView::new(ctx, name, render_state),
270            last: None,
271            ctx: ctx.clone(),
272        }
273    }
274
275    /// Replaces the stream this view draws, or removes it with `None`.
276    ///
277    /// The last frame stays on screen until the new stream delivers one.
278    ///
279    /// # Panics
280    ///
281    /// Panics when called outside a Tokio runtime with `frames` given.
282    pub fn set_frames(&mut self, frames: impl Into<Option<VideoFrames>>) {
283        let frames = frames.into();
284        self._wake = wake_on_frame(&self.ctx, frames.as_ref());
285        self.frames = frames;
286    }
287
288    /// Draws the newest frame, if a new one arrived, and returns the image.
289    pub fn render(&mut self) -> egui::Image<'_> {
290        if let Some(frame) = self.frames.as_mut().and_then(VideoFrames::try_next) {
291            self.frame_view.render_frame(&frame);
292            self.last = Some(frame);
293        }
294        self.frame_view.image()
295    }
296
297    /// Returns the frame [`render`](Self::render) last drew, or `None` before the first.
298    ///
299    /// A frame that failed to draw still counts, as does one a view without a
300    /// renderer skipped. The frame stays after [`set_frames`](Self::set_frames),
301    /// as the picture does.
302    ///
303    /// # Examples
304    ///
305    /// ```no_run
306    /// # fn draw(ui: &mut egui::Ui, view: &mut moq_ext_egui::VideoView) {
307    /// ui.add(view.render());
308    /// if let Some(frame) = view.last_frame() {
309    ///     ui.label(format!("{} at {:?}", frame.size(), frame.timestamp));
310    /// }
311    /// # }
312    /// ```
313    #[must_use]
314    pub fn last_frame(&self) -> Option<&Arc<moq_video::Frame>> {
315        self.last.as_ref()
316    }
317}
318
319/// Creates an [`egui_wgpu::WgpuConfiguration`] for video rendering.
320///
321/// On Linux, this builds a Vulkan device and enables
322/// [`wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF`] if the adapter supports
323/// it. The renderer can then import DMA-BUF frames, such as PipeWire screen
324/// capture, without a copy through the CPU. It blocks while it requests the
325/// adapter and device.
326///
327/// Elsewhere, or if Vulkan is not available or excluded by `WGPU_BACKEND`,
328/// egui builds the device and the renderer uploads frames from the CPU. The
329/// device always requests the adapter's own limits.
330#[must_use]
331pub fn egui_wgpu_config() -> egui_wgpu::WgpuConfiguration {
332    #[cfg(target_os = "linux")]
333    {
334        egui_wgpu_config_dmabuf()
335    }
336    #[cfg(not(target_os = "linux"))]
337    {
338        adapter_limits_config()
339    }
340}
341
342/// Returns a device descriptor that requests the adapter's own limits.
343///
344/// egui requests [`wgpu::Limits::default()`] on non-GL backends. Those are
345/// desktop limits, for example eight color attachments. The Raspberry Pi 4
346/// Vulkan driver allows four, so the request fails and eframe exits before a
347/// window opens. Video rendering needs nothing beyond the adapter's limits.
348fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
349    wgpu::DeviceDescriptor {
350        label: Some("moq-ext-egui video device"),
351        required_limits: adapter.limits(),
352        ..Default::default()
353    }
354}
355
356/// Returns egui's configuration with the device limits taken from the adapter.
357///
358/// See [`device_descriptor`] for why.
359fn adapter_limits_config() -> egui_wgpu::WgpuConfiguration {
360    egui_wgpu::WgpuConfiguration {
361        wgpu_setup: egui_wgpu::WgpuSetup::CreateNew(egui_wgpu::WgpuSetupCreateNew {
362            device_descriptor: Arc::new(device_descriptor),
363            ..egui_wgpu::WgpuSetupCreateNew::without_display_handle()
364        }),
365        ..Default::default()
366    }
367}
368
369/// Logs once when the device leaves out the DMA-BUF import its adapter offers.
370///
371/// That is the device eframe builds without [`egui_wgpu_config`], and every
372/// DMA-BUF frame then takes a copy through the CPU.
373#[cfg(target_os = "linux")]
374fn hint_dmabuf_import(render_state: &egui_wgpu::RenderState) {
375    static HINTED: std::sync::Once = std::sync::Once::new();
376    let feature = wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF;
377    if render_state.adapter.features().contains(feature)
378        && !render_state.device.features().contains(feature)
379    {
380        HINTED.call_once(|| {
381            info!(
382                "the wgpu device cannot import DMA-BUF frames, so they are copied through \
383                 the CPU; pass moq_ext_egui::egui_wgpu_config() as eframe's wgpu_options"
384            );
385        });
386    }
387}
388
389/// Builds a Vulkan device that imports DMA-BUF memory where the adapter can.
390///
391/// [`moq_video::render::request_device`] adds the DMA-BUF feature and the
392/// timeline-semaphore extension that the zero-copy paths need.
393#[cfg(target_os = "linux")]
394fn egui_wgpu_config_dmabuf() -> egui_wgpu::WgpuConfiguration {
395    // DMA-BUF import needs Vulkan. If `WGPU_BACKEND` asks for another
396    // backend, fall back to egui's setup, which reads the same variable.
397    if let Some(requested) = wgpu::Backends::from_env()
398        && !requested.contains(wgpu::Backends::VULKAN)
399    {
400        info!(
401            ?requested,
402            "WGPU_BACKEND excludes Vulkan, so the DMA-BUF import path is not used",
403        );
404        return adapter_limits_config();
405    }
406
407    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
408        backends: wgpu::Backends::VULKAN,
409        ..wgpu::InstanceDescriptor::new_without_display_handle()
410    });
411
412    let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
413        power_preference: wgpu::PowerPreference::HighPerformance,
414        ..Default::default()
415    })) {
416        Ok(adapter) => adapter,
417        Err(err) => {
418            warn!(error = %err, "no Vulkan adapter available, letting egui pick one");
419            return adapter_limits_config();
420        }
421    };
422
423    let (device, queue) = match pollster::block_on(moq_video::render::request_device(
424        &adapter,
425        &device_descriptor(&adapter),
426    )) {
427        Ok(pair) => pair,
428        Err(err) => {
429            warn!(error = %err, "wgpu device request failed, letting egui build one");
430            return adapter_limits_config();
431        }
432    };
433    if !device
434        .features()
435        .contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF)
436    {
437        debug!(
438            "the adapter cannot import DMA-BUF memory, so video frames are uploaded from the CPU"
439        );
440    }
441
442    egui_wgpu::WgpuConfiguration {
443        wgpu_setup: egui_wgpu::WgpuSetup::Existing(egui_wgpu::WgpuSetupExisting {
444            instance,
445            adapter,
446            device,
447            queue,
448        }),
449        ..Default::default()
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use moq_ext_sources::frames::FrameSlot;
456
457    use super::*;
458
459    fn frame(micros: u64) -> Arc<moq_video::Frame> {
460        let size = moq_video::Size::new(2, 2);
461        let surface = moq_video::Surface::rgba(&[0u8; 16], size).expect("a 2x2 picture");
462        let timestamp = moq_net::Timestamp::from_micros(micros).expect("in range");
463        Arc::new(moq_video::Frame::new(timestamp, surface))
464    }
465
466    /// The view reports the frame each render took, and keeps it across a new stream.
467    #[tokio::test]
468    async fn the_last_frame_is_the_one_render_took() {
469        let ctx = egui::Context::default();
470        let slot = FrameSlot::new();
471        let mut view = VideoView::new(&ctx, "test", slot.frames(), None);
472        assert!(view.last_frame().is_none());
473        slot.send(frame(1));
474        slot.send(frame(2));
475        let _ = view.render();
476        let micros =
477            |view: &VideoView| view.last_frame().and_then(|f| f.timestamp.as_micros().ok());
478        assert_eq!(micros(&view), Some(2));
479        view.set_frames(None);
480        let _ = view.render();
481        assert_eq!(micros(&view), Some(2));
482    }
483}