Skip to main content

libobs_simple\sources\windows\sources/
monitor_capture.rs

1//! Monitor capture source for Windows using libobs-rs
2//! This source captures the entire monitor and is used for screen recording.
3
4use std::sync::Arc;
5
6use super::ObsDisplayCaptureMethod;
7use crate::error::ObsSimpleError;
8use crate::{define_object_manager, sources::macro_helper::impl_custom_source};
9/// Note: This does not update the capture method directly, instead the capture method gets
10/// stored in the struct. The capture method is being set to WGC at first, then the source is created and then the capture method is updated to the desired method.
11use display_info::DisplayInfo;
12use libobs_simple_macro::obs_object_impl;
13use libobs_wrapper::run_with_obs;
14use libobs_wrapper::runtime::ObsRuntime;
15use libobs_wrapper::scenes::{ObsSceneItemRef, SceneItemExtSceneTrait};
16use libobs_wrapper::{
17    data::{ObsObjectBuilder, ObsObjectUpdater},
18    scenes::ObsSceneRef,
19    sources::{ObsSourceBuilder, ObsSourceRef, ObsSourceTrait},
20    utils::ObsError,
21};
22use num_traits::ToPrimitive;
23use windows::Win32::UI::HiDpi::{
24    GetAwarenessFromDpiAwarenessContext, GetThreadDpiAwarenessContext,
25    SetProcessDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,
26    DPI_AWARENESS_UNAWARE,
27};
28
29// Usage example
30define_object_manager!(
31    /// Provides an easy-to-use builder for the monitor capture source.
32    #[derive(Debug)]
33    struct MonitorCaptureSource("monitor_capture", *mut libobs::obs_source) for ObsSourceRef {
34        #[obs_property(type_t = "string", settings_key = "monitor_id")]
35        monitor_id_raw: String,
36
37        #[obs_property(type_t = "bool")]
38        /// Sets whether the cursor should be captured.
39        capture_cursor: bool,
40
41        #[obs_property(type_t = "bool")]
42        /// Compatibility mode for the monitor capture source.
43        compatibility: bool,
44
45        #[obs_property(type_t = "bool")]
46        /// If the capture should force SDR
47        force_sdr: bool,
48
49        capture_method: Option<ObsDisplayCaptureMethod>,
50    }
51);
52
53#[obs_object_impl]
54impl MonitorCaptureSource {
55    /// Gets all available monitors
56    pub fn get_monitors() -> Result<Vec<DisplayInfo>, ObsSimpleError> {
57        DisplayInfo::all().map_err(ObsSimpleError::DisplayInfoError)
58    }
59
60    pub fn set_monitor(self, monitor: &DisplayInfo) -> Self {
61        self.set_monitor_id_raw(monitor.name.as_str())
62    }
63}
64
65fn is_thread_dpi_unaware(runtime: &ObsRuntime) -> Result<bool, ObsError> {
66    run_with_obs!(runtime, (), move || {
67        unsafe {
68            // SAFETY: This actor command queries its own thread DPI context. The opaque
69            // context is passed directly to the awareness query, never dereferenced.
70            let ctx = GetThreadDpiAwarenessContext();
71            GetAwarenessFromDpiAwarenessContext(ctx) == DPI_AWARENESS_UNAWARE
72        }
73    })
74}
75
76fn set_dpi_awareness_if_needed(runtime: &ObsRuntime) -> Result<(), ObsError> {
77    if is_thread_dpi_unaware(runtime)? {
78        log::warn!(
79            "The current thread is DPI unaware. Setting the DPI awareness context to Per Monitor Aware V2 to allow DXGI capture method to work correctly."
80        );
81    } else {
82        return Ok(());
83    }
84
85    let set_result = unsafe {
86        // SAFETY: PER_MONITOR_AWARE_V2 is a documented pseudo-handle. Windows arbitrates
87        // this process-wide setting; manifest/concurrent initialization errors are handled below.
88        SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
89    };
90
91    if let Err(e) = set_result {
92        log::warn!(
93            "Could not set DPI awareness context: {:?}. This is fine if you don't want to use DXGI capture or if you have already specified DPI awareness in the application manifest.",
94            e
95        );
96        Err(ObsError::InvalidOperation("Process is not DPI aware and could not set DPI awareness. DPI awareness is required for DXGI monitor capture however".into()))
97    } else {
98        Ok(())
99    }
100}
101
102impl<'a> MonitorCaptureSourceUpdater<'a> {
103    pub fn set_capture_method(mut self, method: ObsDisplayCaptureMethod) -> Result<Self, ObsError> {
104        if method == ObsDisplayCaptureMethod::MethodDXGI {
105            set_dpi_awareness_if_needed(self.runtime())?;
106        }
107        self.get_settings_updater()
108            .set_int_ref("method", method.to_i32().unwrap() as i64);
109
110        Ok(self)
111    }
112}
113
114impl MonitorCaptureSourceBuilder {
115    /// Sets the capture method for the monitor capture source.
116    /// If you want to use DXGI, it is required for your application to be DPI aware.
117    pub fn set_capture_method(mut self, method: ObsDisplayCaptureMethod) -> Self {
118        self.capture_method = Some(method);
119
120        self
121    }
122}
123
124pub type GeneralSourceRef = Arc<dyn ObsSourceTrait>;
125impl ObsSourceBuilder for MonitorCaptureSourceBuilder {
126    type T = MonitorCaptureSource;
127
128    fn build(self) -> Result<Self::T, ObsError>
129    where
130        Self: Sized,
131    {
132        if self.capture_method == Some(ObsDisplayCaptureMethod::MethodDXGI) {
133            set_dpi_awareness_if_needed(self.runtime())?;
134        }
135
136        let runtime = self.runtime.clone();
137        let obj_info = self.object_build()?;
138
139        let res = ObsSourceRef::new_from_info(obj_info, runtime)?;
140        MonitorCaptureSource::new(res)
141    }
142
143    fn add_to_scene(mut self, scene: &mut ObsSceneRef) -> Result<ObsSceneItemRef<Self::T>, ObsError>
144    where
145        Self: Sized,
146    {
147        // Because of a black screen bug, we need to set the method to WGC first and then update
148        self.get_settings_updater().set_int_ref(
149            "method",
150            ObsDisplayCaptureMethod::MethodWgc.to_i32().unwrap() as i64,
151        );
152
153        let method_to_set = self.capture_method;
154
155        let mut res = self.build()?;
156        let scene_item = scene.add_source(res.clone())?;
157
158        if let Some(method) = method_to_set {
159            res.create_updater()?
160                .set_capture_method(method)? //
161                .update()?;
162        }
163
164        Ok(scene_item)
165    }
166}
167
168impl_custom_source!(MonitorCaptureSource);