Skip to main content

libobs_wrapper\display/
mod.rs

1//! This module is used to create a `OBS display` which you can use to preview the
2//! output of your recording.
3
4mod creation_data;
5mod enums;
6mod geometry;
7mod window_manager;
8
9pub use window_manager::{MiscDisplayTrait, ShowHideTrait, WindowPositionTrait};
10
11pub use creation_data::*;
12pub use enums::*;
13pub use geometry::*;
14use libobs::obs_video_info;
15
16use crate::unsafe_send::SmartPointerSendable;
17use crate::utils::{ObsDropGuard, ObsError};
18use crate::{data::object::ObsObjectTrait, scenes::ObsSceneRef, sources::ObsSourceRef};
19use crate::{impl_obs_drop, run_with_obs, runtime::ObsRuntime, unsafe_send::Sendable};
20use std::mem::MaybeUninit;
21use std::{
22    ffi::c_void,
23    marker::PhantomPinned,
24    sync::{atomic::AtomicUsize, Arc, RwLock},
25};
26
27static ID_COUNTER: AtomicUsize = AtomicUsize::new(1);
28#[derive(Debug, Clone)]
29/// You can use the `ObsContext` to create this struct. This struct is stored in the
30/// `ObsContext` itself and the display is removed if every instance of this struct is dropped
31/// (and you have called `remove_display` on the `ObsContext`).
32pub struct ObsDisplayRef {
33    id: usize,
34    render_state: Arc<DisplayRenderState>,
35
36    /// Keep for window, manager is accessed by render thread as well so Arc and RwLock
37    ///
38    /// This is mostly used on windows to handle the size and position of the child window.
39    #[cfg(windows)]
40    #[allow(dead_code)]
41    child_window_handler:
42        Option<Arc<RwLock<window_manager::windows::WindowsPreviewChildWindowHandler>>>,
43
44    /// Stored so the obs context is not dropped while this is alive
45    runtime: ObsRuntime,
46    display: SmartPointerSendable<*mut libobs::obs_display_t>,
47}
48
49/// Content rendered by a preview display. The managed variants retain their native source/scene
50/// lifetime while selected, including while the graphics callback is executing.
51#[derive(Debug, Clone)]
52pub enum PreviewTarget {
53    Program,
54    Scene(ObsSceneRef),
55    Source(ObsSourceRef),
56}
57
58#[derive(Debug)]
59pub(super) struct DisplayRenderState {
60    pub(super) position: RwLock<(i32, i32)>,
61    pub(super) scale_mode: RwLock<PreviewScaleMode>,
62    pub(super) target: RwLock<PreviewTarget>,
63}
64
65#[allow(unknown_lints)]
66#[allow(ensure_obs_call_in_runtime)]
67/// # Safety
68/// libobs must invoke this on its graphics thread with its graphics context active.
69/// `data` must point to the DisplayRenderState retained by the display drop guard.
70/// That Arc outlives callback removal: obs_display_remove_draw_callback takes the
71/// same draw_callbacks_mutex held by the renderer, waiting for in-flight callbacks.
72/// Mutable state is protected by RwLocks; the target read guard retains the selected
73/// source/scene lease until rendering completes.
74unsafe extern "C" fn render_display(data: *mut c_void, width: u32, height: u32) {
75    let Some(state) = (data as *const DisplayRenderState).as_ref() else {
76        log::error!("Display render callback received null userdata");
77        return;
78    };
79    let pos = *state
80        .position
81        .read()
82        .unwrap_or_else(|poisoned| poisoned.into_inner());
83    let mode = *state
84        .scale_mode
85        .read()
86        .unwrap_or_else(|poisoned| poisoned.into_inner());
87    let target = state
88        .target
89        .read()
90        .unwrap_or_else(|poisoned| poisoned.into_inner());
91
92    let mut ovi = MaybeUninit::<obs_video_info>::uninit();
93    let was_ok = libobs::obs_get_video_info(ovi.as_mut_ptr());
94    if !was_ok {
95        log::error!("Failed to get video info in display render callback");
96        return;
97    }
98    let ovi = unsafe {
99        // Safety: was_ok checked that the video info was properly initialized.
100        ovi.assume_init()
101    };
102
103    let (content_width, content_height, source_ptr) = match &*target {
104        PreviewTarget::Program => (ovi.base_width, ovi.base_height, None),
105        PreviewTarget::Source(source) => {
106            let ptr = source.__native_handle();
107            let width = libobs::obs_source_get_width(ptr.get_ptr());
108            let height = libobs::obs_source_get_height(ptr.get_ptr());
109            (width.max(1), height.max(1), Some(ptr.get_ptr()))
110        }
111        PreviewTarget::Scene(scene) => {
112            let source = libobs::obs_scene_get_source(scene.as_ptr().get_ptr());
113            if source.is_null() {
114                return;
115            }
116            let width = libobs::obs_source_get_width(source)
117                .max(ovi.base_width)
118                .max(1);
119            let height = libobs::obs_source_get_height(source)
120                .max(ovi.base_height)
121                .max(1);
122            (width, height, Some(source))
123        }
124    };
125    let Some(geometry) =
126        PreviewGeometry::new(content_width, content_height, width, height, mode, 1.0)
127    else {
128        return;
129    };
130
131    libobs::gs_viewport_push();
132    libobs::gs_projection_push();
133    libobs::gs_ortho(
134        0.0,
135        content_width as f32,
136        0.0,
137        content_height as f32,
138        -100.0,
139        100.0,
140    );
141    libobs::gs_set_viewport(
142        pos.0 + geometry.render_rect.x.round() as i32,
143        pos.1 + geometry.render_rect.y.round() as i32,
144        geometry.render_rect.width.round().max(1.0) as i32,
145        geometry.render_rect.height.round().max(1.0) as i32,
146    );
147
148    match source_ptr {
149        Some(source) => libobs::obs_source_video_render(source),
150        None => libobs::obs_render_main_texture_src_color_only(),
151    }
152
153    libobs::gs_projection_pop();
154    libobs::gs_viewport_pop();
155}
156
157pub struct LockedPosition {
158    pub x: i32,
159    pub y: i32,
160    /// This must not be moved in memory as the draw callback is a raw pointer to this struct
161    _fixed_in_heap: PhantomPinned,
162}
163
164#[derive(Clone, Debug)]
165pub struct ObsWindowHandle {
166    pub(crate) window: Sendable<libobs::gs_window>,
167    #[allow(dead_code)]
168    pub(crate) is_wayland: bool,
169}
170
171impl ObsWindowHandle {
172    /// Construct from an HWND supplied by an external windowing toolkit.
173    ///
174    /// # Safety
175    /// `handle` must be a live HWND for the complete lifetime of any OBS display created
176    /// from this value, and all toolkit thread-affinity requirements must be respected.
177    #[cfg(windows)]
178    pub unsafe fn new_from_handle(handle: *mut std::os::raw::c_void) -> Self {
179        Self {
180            window: Sendable(libobs::gs_window { hwnd: handle }),
181            is_wayland: false,
182        }
183    }
184
185    #[cfg(windows)]
186    /// Returns a borrowed OS handle without transferring ownership. Operations on it
187    /// must obey Win32 thread restrictions; destroy it only on its creating thread.
188    pub fn get_hwnd(&self) -> windows::Win32::Foundation::HWND {
189        windows::Win32::Foundation::HWND(self.window.0.hwnd)
190    }
191
192    /// Construct from a Wayland surface supplied by an external windowing toolkit.
193    ///
194    /// # Safety
195    /// `surface` must be a live `wl_surface` belonging to the configured Wayland display
196    /// and must outlive any OBS display created from this handle.
197    #[cfg(target_os = "linux")]
198    pub unsafe fn new_from_wayland(surface: *mut c_void) -> Self {
199        Self {
200            window: Sendable(libobs::gs_window {
201                display: surface,
202                id: 0,
203            }),
204            is_wayland: true,
205        }
206    }
207
208    #[cfg(target_os = "linux")]
209    pub fn new_from_x11(runtime: &ObsRuntime, id: u32) -> Result<Self, ObsError> {
210        let runtime = runtime.clone();
211        let display = run_with_obs!(runtime, (), move || unsafe {
212            // Safety: We are just getting a pointer and we are in the runtime
213            Sendable(libobs::obs_get_nix_platform_display())
214        })?;
215
216        Ok(Self {
217            window: Sendable(libobs::gs_window {
218                display: display.0,
219                id,
220            }),
221            is_wayland: false,
222        })
223    }
224}
225
226impl ObsDisplayRef {
227    /// Call initialize to ObsDisplay#create the display
228    pub(crate) fn new(data: ObsDisplayCreationData, runtime: ObsRuntime) -> Result<Self, ObsError> {
229        use std::sync::atomic::Ordering;
230
231        use creation_data::ObsDisplayCreationData;
232
233        use crate::run_with_obs;
234
235        let ObsDisplayCreationData {
236            x,
237            y,
238            background_color,
239            create_child,
240            #[cfg(windows)]
241            height,
242            #[cfg(windows)]
243            width,
244            #[cfg(windows)]
245            window_handle,
246            ..
247        } = data.clone();
248
249        #[cfg(windows)]
250        let mut child_handler = if create_child {
251            Some(
252                window_manager::windows::WindowsPreviewChildWindowHandler::new_child(
253                    window_handle.clone(),
254                    x,
255                    y,
256                    width,
257                    height,
258                )?,
259            )
260        } else {
261            None
262        };
263
264        #[cfg(windows)]
265        let init_data = Sendable(data.build(child_handler.as_ref().map(|e| e.get_window_handle())));
266
267        #[cfg(not(windows))]
268        let init_data = Sendable(data.build(None));
269
270        log::trace!("Creating obs display...");
271        let display = run_with_obs!(runtime, (init_data), move || {
272            let display_ptr = unsafe {
273                // SAFETY: The actor owns init_data through this synchronous call. Its
274                // borrowed window is retained by the child handler or by the caller's
275                // ObsWindowHandle contract for the complete display lifetime.
276                libobs::obs_display_create(&init_data.0 .0, background_color)
277            };
278
279            if display_ptr.is_null() {
280                Err(ObsError::NullPointer(None))
281            } else {
282                Ok(Sendable(display_ptr))
283            }
284        })??;
285
286        let initial_pos = if create_child && cfg!(windows) {
287            (0, 0)
288        } else {
289            (x, y)
290        };
291        let render_state = Arc::new(DisplayRenderState {
292            position: RwLock::new(initial_pos),
293            scale_mode: RwLock::new(PreviewScaleMode::Fit),
294            target: RwLock::new(PreviewTarget::Program),
295        });
296
297        let display = SmartPointerSendable::new(
298            display.0,
299            Arc::new(_ObsDisplayDropGuard {
300                display,
301                render_state: render_state.clone(),
302                runtime: runtime.clone(),
303            }),
304            runtime.native_registry(),
305        );
306
307        #[cfg(windows)]
308        if let Some(handler) = &mut child_handler {
309            handler.set_display_handle(display.clone());
310        }
311
312        let id = ID_COUNTER.fetch_add(1, Ordering::Relaxed);
313        let instance = Self {
314            display: display.clone(),
315            id,
316            render_state: render_state.clone(),
317            runtime: runtime.clone(),
318
319            #[cfg(windows)]
320            child_window_handler: child_handler.map(|e| Arc::new(RwLock::new(e))),
321        };
322
323        log::trace!("Adding draw callback with display {:?}", instance.display);
324
325        let display_ptr = instance.as_ptr();
326        run_with_obs!(runtime, (display_ptr), move || {
327            unsafe {
328                // Safety: The pointer is valid because we are using a smart pointer
329                libobs::obs_display_add_draw_callback(
330                    display_ptr.get_ptr(),
331                    Some(render_display),
332                    Arc::as_ptr(&render_state) as *mut c_void,
333                );
334            }
335        })?;
336
337        Ok(instance)
338    }
339
340    pub fn id(&self) -> usize {
341        self.id
342    }
343
344    pub fn update_color_space(&self) -> Result<(), ObsError> {
345        let display_ptr = self.as_ptr();
346        run_with_obs!(self.runtime, (display_ptr), move || {
347            unsafe {
348                // Safety: The pointer is valid because we are using a smart pointer
349                libobs::obs_display_update_color_space(display_ptr.get_ptr())
350            }
351        })
352    }
353
354    /// Selects fit/letterbox, fill/crop, or stretch mapping for subsequent renders.
355    pub fn set_scale_mode(&self, mode: PreviewScaleMode) -> Result<(), ObsError> {
356        *self
357            .render_state
358            .scale_mode
359            .write()
360            .map_err(|e| ObsError::LockError(e.to_string()))? = mode;
361        Ok(())
362    }
363
364    pub fn scale_mode(&self) -> Result<PreviewScaleMode, ObsError> {
365        self.render_state
366            .scale_mode
367            .read()
368            .map(|mode| *mode)
369            .map_err(|e| ObsError::LockError(e.to_string()))
370    }
371
372    /// Switches the preview target while retaining the selected source/scene for the graphics
373    /// callback. Runtime affinity is checked before the target becomes visible to rendering.
374    pub fn set_target(&self, target: PreviewTarget) -> Result<(), ObsError> {
375        match &target {
376            PreviewTarget::Program => {}
377            PreviewTarget::Source(source) => self.runtime.ensure_same_runtime(source.runtime())?,
378            PreviewTarget::Scene(scene) => self.runtime.ensure_same_runtime(scene.runtime())?,
379        }
380        *self
381            .render_state
382            .target
383            .write()
384            .map_err(|e| ObsError::LockError(e.to_string()))? = target;
385        Ok(())
386    }
387
388    pub fn target(&self) -> Result<PreviewTarget, ObsError> {
389        self.render_state
390            .target
391            .read()
392            .map(|target| target.clone())
393            .map_err(|e| ObsError::LockError(e.to_string()))
394    }
395
396    /// Resizes the native OBS display in physical pixels.
397    pub fn resize(&self, width: u32, height: u32) -> Result<(), ObsError> {
398        if width == 0 || height == 0 {
399            return Err(ObsError::InvalidOperation(
400                "preview display dimensions must be non-zero".into(),
401            ));
402        }
403        let display = self.as_ptr();
404        let runtime = self.runtime.clone();
405        run_with_obs!(runtime, (display), move || unsafe {
406            // Safety: display is retained for the actor call.
407            libobs::obs_display_resize(display.get_ptr(), width, height);
408        })
409    }
410
411    /// Computes the same geometry used by rendering for editor pointer conversion. Display size is
412    /// physical pixels. Pass the toolkit's physical/logical DPI ratio for logical pointer helpers.
413    pub fn preview_geometry(&self, dpi_scale: f32) -> Result<PreviewGeometry, ObsError> {
414        let target = self.target()?;
415        let mode = self.scale_mode()?;
416        let display = self.as_ptr();
417        let runtime = self.runtime.clone();
418        run_with_obs!(runtime, (display, target), move || {
419            let mut viewport_width = 0_u32;
420            let mut viewport_height = 0_u32;
421            unsafe {
422                // Safety: display is retained and output pointers are valid stack locations.
423                libobs::obs_display_size(
424                    display.get_ptr(),
425                    &mut viewport_width,
426                    &mut viewport_height,
427                );
428            }
429
430            let (content_width, content_height) = match target {
431                PreviewTarget::Program => {
432                    let mut ovi = MaybeUninit::<obs_video_info>::uninit();
433                    // SAFETY: `ovi` is valid writable storage and this runs on the OBS actor.
434                    if !unsafe { libobs::obs_get_video_info(ovi.as_mut_ptr()) } {
435                        return Err(ObsError::InvalidOperation(
436                            "OBS video info is unavailable for preview geometry".into(),
437                        ));
438                    }
439                    // SAFETY: successful `obs_get_video_info` initialized the complete structure.
440                    let ovi = unsafe { ovi.assume_init() };
441                    (ovi.base_width, ovi.base_height)
442                }
443                PreviewTarget::Source(source) => {
444                    let ptr = source.__native_handle();
445                    // SAFETY: the managed source lease is retained for this actor command.
446                    unsafe {
447                        (
448                            libobs::obs_source_get_width(ptr.get_ptr()),
449                            libobs::obs_source_get_height(ptr.get_ptr()),
450                        )
451                    }
452                }
453                PreviewTarget::Scene(scene) => {
454                    // SAFETY: the managed scene lease is retained for this actor command.
455                    let source = unsafe { libobs::obs_scene_get_source(scene.as_ptr().get_ptr()) };
456                    if source.is_null() {
457                        return Err(ObsError::NullPointer(Some("scene preview source".into())));
458                    }
459                    // SAFETY: `source` is the non-null scene source borrowed for this actor call.
460                    unsafe {
461                        (
462                            libobs::obs_source_get_width(source),
463                            libobs::obs_source_get_height(source),
464                        )
465                    }
466                }
467            };
468            PreviewGeometry::new(
469                content_width,
470                content_height,
471                viewport_width,
472                viewport_height,
473                mode,
474                dpi_scale,
475            )
476            .ok_or_else(|| ObsError::InvalidOperation("invalid preview geometry".into()))
477        })?
478    }
479
480    pub(crate) fn as_ptr(&self) -> SmartPointerSendable<*mut libobs::obs_display_t> {
481        self.display.clone()
482    }
483}
484
485#[derive(Debug)]
486struct _ObsDisplayDropGuard {
487    display: Sendable<*mut libobs::obs_display_t>,
488    render_state: Arc<DisplayRenderState>,
489    runtime: ObsRuntime,
490}
491
492impl ObsDropGuard for _ObsDisplayDropGuard {}
493
494impl_obs_drop!(
495    _ObsDisplayDropGuard,
496    (display, render_state),
497    move || unsafe {
498        // SAFETY: `render_state` remains alive through callback deregistration and display
499        // destruction, and the native pointer is owned by this drop guard. libobs takes
500        // draw_callbacks_mutex during both rendering and removal, so removal waits for
501        // an active callback before this task can release its Arc.
502        log::trace!("Removing callback of display {:?}...", display);
503        libobs::obs_display_remove_draw_callback(
504            display.0,
505            Some(render_display),
506            Arc::as_ptr(&render_state) as *mut c_void,
507        );
508        libobs::obs_display_destroy(display.0);
509    }
510);