| 1 | // Copyright 2025 LiveKit, Inc. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | use crate::imp::desktop_capturer as imp_dc; |
| 16 | |
| 17 | /// Starts one GLib main loop for the process, on the default context. |
| 18 | /// |
| 19 | /// Wayland's screen-cast portal needs this loop before a capturer starts or shows its picker. |
| 20 | /// Dropping a capturer does not stop the loop. |
| 21 | pub fn ensure_shared_glib_loop() { |
| 22 | imp_dc::ensure_shared_glib_loop(); |
| 23 | } |
| 24 | |
| 25 | /// Identity of the process-wide GLib loop. `0` when the loop is not built into this target. |
| 26 | pub fn shared_glib_loop_id() -> usize { |
| 27 | imp_dc::shared_glib_loop_id() |
| 28 | } |
| 29 | |
| 30 | /// Configuration options for creating a desktop capturer. |
| 31 | /// |
| 32 | /// It contains a subset of libwebrtc's DesktopCaptureOptions. |
| 33 | /// |
| 34 | /// By default, it captures the entire screen and does not include the cursor. |
| 35 | /// |
| 36 | /// # Example |
| 37 | /// ```no_run |
| 38 | /// use libwebrtc::desktop_capturer::{DesktopCapturerOptions, DesktopCaptureSourceType}; |
| 39 | /// |
| 40 | /// let mut options = DesktopCapturerOptions::new(DesktopCaptureSourceType::Screen); |
| 41 | /// options.set_include_cursor(true); |
| 42 | /// ``` |
| 43 | pub struct DesktopCapturerOptions { |
| 44 | sys_handle: imp_dc::DesktopCapturerOptions, |
| 45 | } |
| 46 | |
| 47 | /// Specifies the type of source that a desktop capturer should capture. |
| 48 | #[derive(Debug, Copy, Clone, PartialEq)] |
| 49 | pub enum DesktopCaptureSourceType { |
| 50 | Screen, |
| 51 | Window, |
| 52 | #[cfg(any(target_os = "macos", target_os = "linux"))] |
| 53 | Generic, |
| 54 | } |
| 55 | |
| 56 | impl DesktopCapturerOptions { |
| 57 | /// Creates a new `DesktopCapturerOptions` with default values. |
| 58 | /// |
| 59 | /// # Arguments |
| 60 | /// |
| 61 | /// * `source_type` - The type of source to capture (screen or window). |
| 62 | /// |
| 63 | /// # Defaults |
| 64 | /// |
| 65 | /// - Cursor is not included in captured frames (use [`set_include_cursor`](Self::set_include_cursor) to change) |
| 66 | /// - On macOS, the ScreenCaptureKit system picker is enabled (use [`set_sck_system_picker`](Self::set_sck_system_picker) to change) |
| 67 | pub fn new(source_type: DesktopCaptureSourceType) -> Self { |
| 68 | let source_type = match source_type { |
| 69 | DesktopCaptureSourceType::Screen => imp_dc::SourceType::Screen, |
| 70 | DesktopCaptureSourceType::Window => imp_dc::SourceType::Window, |
| 71 | #[cfg(any(target_os = "macos", target_os = "linux"))] |
| 72 | DesktopCaptureSourceType::Generic => imp_dc::SourceType::Generic, |
| 73 | }; |
| 74 | Self { sys_handle: imp_dc::DesktopCapturerOptions::new(source_type) } |
| 75 | } |
| 76 | |
| 77 | /// Sets whether to include the cursor in captured frames. |
| 78 | pub fn set_include_cursor(&mut self, include: bool) { |
| 79 | self.sys_handle = self.sys_handle.with_cursor(include); |
| 80 | } |
| 81 | |
| 82 | /// Sets whether to allow the ScreenCaptureKit system picker on macOS. |
| 83 | /// |
| 84 | /// This is enabled by default. |
| 85 | /// |
| 86 | /// When disabled, for capturing displays the client should get the source id |
| 87 | /// via a different way as [`DesktopCapturer::get_source_list`] returns an empty vector. |
| 88 | #[cfg(target_os = "macos")] |
| 89 | pub fn set_sck_system_picker(&mut self, allow_sck_system_picker: bool) { |
| 90 | self.sys_handle = self.sys_handle.with_sck_system_picker(allow_sck_system_picker); |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// A desktop capturer for capturing screens or windows. |
| 95 | pub struct DesktopCapturer { |
| 96 | handle: imp_dc::DesktopCapturer, |
| 97 | } |
| 98 | |
| 99 | impl DesktopCapturer { |
| 100 | /// Creates a new `DesktopCapturer` with the specified callback and options. |
| 101 | /// |
| 102 | /// # Arguments |
| 103 | /// |
| 104 | /// * `options` - Configuration options for the capturer |
| 105 | /// |
| 106 | /// # Returns |
| 107 | /// |
| 108 | /// Returns `Some(DesktopCapturer)` if the capturer was created successfully, |
| 109 | /// or `None` if creation failed (e.g., due to platform limitations or permissions). |
| 110 | pub fn new(options: DesktopCapturerOptions) -> Option<Self> { |
| 111 | let desktop_capturer = imp_dc::DesktopCapturer::new(options.sys_handle); |
| 112 | if desktop_capturer.is_none() { |
| 113 | return None; |
| 114 | } |
| 115 | Some(Self { handle: desktop_capturer.unwrap() }) |
| 116 | } |
| 117 | |
| 118 | /// Starts capturing from the specified source. |
| 119 | /// |
| 120 | /// # Arguments |
| 121 | /// |
| 122 | /// * `source` - The capture source to use. It should be None when the capturer |
| 123 | /// is configured to use the system picker (on platforms that support it). |
| 124 | /// * `callback` - A function that will be called for each captured frame. The callback |
| 125 | /// receives a [`CaptureResult`] indicating success or error, and a [`DesktopFrame`] |
| 126 | /// containing the captured image data. |
| 127 | /// |
| 128 | /// # Note |
| 129 | /// |
| 130 | /// After calling this method, you must call [`capture_frame`](Self::capture_frame) |
| 131 | /// to actually capture frames. This method only initializes the capture session. |
| 132 | pub fn start_capture<T>(&mut self, source: Option<CaptureSource>, mut callback: T) |
| 133 | where |
| 134 | T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static, |
| 135 | { |
| 136 | if let Some(source) = source { |
| 137 | self.handle.select_source(source.sys_handle.id()); |
| 138 | } |
| 139 | let inner_callback = move |result: Result<imp_dc::DesktopFrame, imp_dc::CaptureError>| { |
| 140 | callback(capture_result_from_sys(result)); |
| 141 | }; |
| 142 | self.handle.start(inner_callback); |
| 143 | } |
| 144 | |
| 145 | /// Captures a single frame. |
| 146 | /// |
| 147 | /// You must call [`start_capture`](Self::start_capture) before calling this method. |
| 148 | pub fn capture_frame(&mut self) { |
| 149 | self.handle.capture_frame(); |
| 150 | } |
| 151 | |
| 152 | /// Sets the target maximum frame rate for the capturer (best effort). |
| 153 | pub fn set_max_frame_rate(&mut self, max_fps: u32) { |
| 154 | self.handle.set_max_frame_rate(max_fps); |
| 155 | } |
| 156 | |
| 157 | /// Retrieves a list of available capture sources. |
| 158 | /// |
| 159 | /// Returns a list of screens or windows that can be captured, depending |
| 160 | /// on whether the capturer was configured for window or screen capture. |
| 161 | /// |
| 162 | /// # Returns |
| 163 | /// |
| 164 | /// A vector of [`CaptureSource`] objects representing available capture sources. |
| 165 | pub fn get_source_list(&self) -> Vec<CaptureSource> { |
| 166 | let source_list = self.handle.get_source_list(); |
| 167 | source_list.into_iter().map(|source| CaptureSource { sys_handle: source }).collect() |
| 168 | } |
| 169 | |
| 170 | /// Selects one source after a delegated picker has already chosen it. |
| 171 | pub fn select_source(&self, id: u64) -> bool { |
| 172 | self.handle.select_source(id) |
| 173 | } |
| 174 | |
| 175 | /// Whether this capturer shows its own source picker (Wayland portal, macOS system picker). |
| 176 | pub fn has_delegated_picker(&self) -> bool { |
| 177 | self.handle.has_delegated_picker() |
| 178 | } |
| 179 | |
| 180 | /// Receives selection, cancel, and failure from the delegated picker. |
| 181 | /// |
| 182 | /// Call this after [`start_capture`](Self::start_capture) and before [`ensure_picker_visible`](Self::ensure_picker_visible). |
| 183 | pub fn watch_picker<T>(&mut self, mut callback: T) |
| 184 | where |
| 185 | T: FnMut(PortalPickerEvent) + Send + 'static, |
| 186 | { |
| 187 | self.handle.observe_picker(move |event| { |
| 188 | callback(match event { |
| 189 | imp_dc::PickerEvent::Selected => PortalPickerEvent::Selected, |
| 190 | imp_dc::PickerEvent::Cancelled => PortalPickerEvent::Cancelled, |
| 191 | imp_dc::PickerEvent::Failed => PortalPickerEvent::Failed, |
| 192 | }); |
| 193 | }); |
| 194 | } |
| 195 | |
| 196 | /// Shows the delegated picker. No-op when [`has_delegated_picker`](Self::has_delegated_picker) is false. |
| 197 | pub fn ensure_picker_visible(&mut self) { |
| 198 | self.handle.ensure_picker_visible(); |
| 199 | } |
| 200 | |
| 201 | /// Hides the delegated picker. No-op when there is none. |
| 202 | pub fn ensure_picker_hidden(&mut self) { |
| 203 | self.handle.ensure_picker_hidden(); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | pub struct DesktopFrame { |
| 208 | sys_handle: imp_dc::DesktopFrame, |
| 209 | } |
| 210 | |
| 211 | impl DesktopFrame { |
| 212 | fn new(sys_handle: imp_dc::DesktopFrame) -> Self { |
| 213 | Self { sys_handle } |
| 214 | } |
| 215 | |
| 216 | pub fn width(&self) -> i32 { |
| 217 | self.sys_handle.width() as i32 |
| 218 | } |
| 219 | |
| 220 | pub fn height(&self) -> i32 { |
| 221 | self.sys_handle.height() as i32 |
| 222 | } |
| 223 | |
| 224 | pub fn stride(&self) -> u32 { |
| 225 | self.sys_handle.stride() as u32 |
| 226 | } |
| 227 | |
| 228 | pub fn left(&self) -> i32 { |
| 229 | self.sys_handle.left() |
| 230 | } |
| 231 | |
| 232 | pub fn top(&self) -> i32 { |
| 233 | self.sys_handle.top() |
| 234 | } |
| 235 | |
| 236 | pub fn data(&self) -> &[u8] { |
| 237 | self.sys_handle.data() |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | #[derive(Clone)] |
| 242 | pub struct CaptureSource { |
| 243 | sys_handle: imp_dc::CaptureSource, |
| 244 | } |
| 245 | |
| 246 | impl CaptureSource { |
| 247 | pub fn id(&self) -> u64 { |
| 248 | self.sys_handle.id() |
| 249 | } |
| 250 | pub fn title(&self) -> String { |
| 251 | self.sys_handle.title() |
| 252 | } |
| 253 | pub fn display_id(&self) -> i64 { |
| 254 | self.sys_handle.display_id() |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | impl std::fmt::Display for CaptureSource { |
| 259 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 260 | f.debug_struct("CaptureSource") |
| 261 | .field("id", &self.id()) |
| 262 | .field("title", &self.title()) |
| 263 | .field("display_id", &self.display_id()) |
| 264 | .finish() |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 269 | pub enum CaptureError { |
| 270 | Temporary, |
| 271 | Permanent, |
| 272 | /// The picker or capture stream failed to start. |
| 273 | StartFailed, |
| 274 | /// Sharing was stopped from the system UI, such as the macOS menu bar. |
| 275 | StoppedByUser, |
| 276 | /// The shared source is closed or gone (on macOS 15.2+ it may reopen). |
| 277 | SourceGone, |
| 278 | /// The OS stopped the capture stream for another reason. |
| 279 | Interrupted, |
| 280 | } |
| 281 | |
| 282 | /// Outcome of a desktop-owned source picker. |
| 283 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 284 | pub enum PortalPickerEvent { |
| 285 | Selected, |
| 286 | Cancelled, |
| 287 | Failed, |
| 288 | } |
| 289 | |
| 290 | fn capture_result_from_sys( |
| 291 | result: Result<imp_dc::DesktopFrame, imp_dc::CaptureError>, |
| 292 | ) -> Result<DesktopFrame, CaptureError> { |
| 293 | match result { |
| 294 | Ok(frame) => Ok(DesktopFrame::new(frame)), |
| 295 | Err(error) => Err(match error { |
| 296 | imp_dc::CaptureError::Temporary => CaptureError::Temporary, |
| 297 | imp_dc::CaptureError::Permanent => CaptureError::Permanent, |
| 298 | imp_dc::CaptureError::StartFailed => CaptureError::StartFailed, |
| 299 | imp_dc::CaptureError::StoppedByUser => CaptureError::StoppedByUser, |
| 300 | imp_dc::CaptureError::SourceGone => CaptureError::SourceGone, |
| 301 | imp_dc::CaptureError::Interrupted => CaptureError::Interrupted, |
| 302 | }), |
| 303 | } |
| 304 | } |