BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / screen.rs

screen.rs

screen.rs 7.6 KiB Download Raw
1use std::sync::{Arc, Mutex};
2use std::sync::atomic::{AtomicU32, Ordering};
3use std::time::Duration;
4
5use libwebrtc::desktop_capturer::{CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions};
6use libwebrtc::native::yuv_helper::argb_to_i420;
7use libwebrtc::video_frame::I420Buffer;
8
9use crate::capture::Capture;
10use crate::video_frame::VideoPicture;
11use crate::error::{Error, Result};
12
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ShareKind {
16 Screen,
17 Window,
18}
19
20impl ShareKind {
21 fn source_type(self) -> DesktopCaptureSourceType {
22 match self {
23 ShareKind::Screen => DesktopCaptureSourceType::Screen,
24 ShareKind::Window => DesktopCaptureSourceType::Window,
25 }
26 }
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ShareSource {
31 pub id: u64,
32 pub kind: ShareKind,
33 pub title: String,
34}
35
36impl ShareSource {
37 pub fn label(&self) -> String {
38 match (self.kind, self.title.trim()) {
39 (ShareKind::Screen, "") => "Entire screen".to_owned(),
40 (_, "") => "Window".to_owned(),
41 (_, title) => title.to_owned(),
42 }
43 }
44}
45
46fn capturer(kind: ShareKind) -> Option<DesktopCapturer> {
47 let mut options = DesktopCapturerOptions::new(kind.source_type());
48 options.set_include_cursor(true);
49 DesktopCapturer::new(options)
50}
51
52fn sources_of(kind: ShareKind) -> Vec<(ShareSource, CaptureSource)> {
53 let Some(capturer) = capturer(kind) else { return Vec::new() };
54 capturer
55 .get_source_list()
56 .into_iter()
57 .map(|source| {
58 (
59 ShareSource {
60 id: source.id(),
61 kind,
62 title: source.title(),
63 },
64 source,
65 )
66 })
67 .collect()
68}
69
70pub fn list_share_sources() -> Vec<ShareSource> {
71 [ShareKind::Screen, ShareKind::Window]
72 .into_iter()
73 .flat_map(|kind| sources_of(kind).into_iter().map(|(source, _)| source))
74 .collect()
75}
76
77const THUMBNAIL_ATTEMPTS: u32 = 5;
78const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
79
80pub fn share_thumbnail(wanted: &ShareSource, max_width: u32, max_height: u32) -> Option<VideoPicture> {
81 let source = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw)?;
82 let mut capturer = capturer(wanted.kind)?;
83 let captured: Arc<Mutex<Option<VideoPicture>>> = Arc::default();
84 let sink = captured.clone();
85 capturer.start_capture(Some(source), move |result| {
86 let Ok(frame) = result else { return };
87 let (width, height) = (frame.width().max(0) as u32, frame.height().max(0) as u32);
88 if let Some(picture) = scaled_bgra(frame.data(), width, height, frame.stride(), max_width, max_height)
89 && let Ok(mut slot) = sink.lock()
90 {
91 *slot = Some(picture);
92 }
93 });
94 for _ in 0..THUMBNAIL_ATTEMPTS {
95 pump_messages();
96 capturer.capture_frame();
97 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
98 return Some(picture);
99 }
100 std::thread::sleep(THUMBNAIL_RETRY);
101 }
102 None
103}
104
105// Windows Graphics Capture hands frames to a DispatcherQueue on this thread; without a pump none arrive.
106#[cfg(windows)]
107fn pump_messages() {
108 use windows::Win32::UI::WindowsAndMessaging::{DispatchMessageW, MSG, PM_REMOVE, PeekMessageW, TranslateMessage};
109 let mut message = MSG::default();
110 unsafe {
111 while PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() {
112 let _ = TranslateMessage(&message);
113 let _ = DispatchMessageW(&message);
114 }
115 }
116}
117
118#[cfg(not(windows))]
119fn pump_messages() {}
120
121fn scaled_bgra(bytes: &[u8], width: u32, height: u32, stride: u32, max_width: u32, max_height: u32) -> Option<VideoPicture> {
122 if width == 0 || height == 0 || (stride as usize) < width as usize * 4 || bytes.len() < stride as usize * height as usize {
123 return None;
124 }
125 let scale = (max_width as f32 / width as f32).min(max_height as f32 / height as f32).min(1.);
126 let (target_width, target_height) = (((width as f32 * scale) as u32).max(1), ((height as f32 * scale) as u32).max(1));
127 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
128 for row in 0..target_height {
129 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
130 for column in 0..target_width {
131 let source_column = (column as u64 * width as u64 / target_width as u64) as usize;
132 let offset = source_row * stride as usize + source_column * 4;
133 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
134 }
135 }
136 Some(VideoPicture { width: target_width, height: target_height, bgra })
137}
138
139fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
140 let mut buffer = I420Buffer::new(width, height);
141 let (stride_y, stride_u, stride_v) = buffer.strides();
142 let (plane_y, plane_u, plane_v) = buffer.data_mut();
143 argb_to_i420(bytes, stride, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
144 buffer
145}
146
147pub fn start_screen_capture(
148 wanted: ShareSource,
149 fps: Arc<AtomicU32>,
150 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
151 failed: impl FnOnce(String) + Send + 'static,
152) -> Result<Capture> {
153 Capture::spawn_thread("screen-capture", move |stop| {
154 let Some(source) = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw) else {
155 return failed("the shared source is gone".to_owned());
156 };
157 let Some(mut capturer) = capturer(wanted.kind) else {
158 return failed("screen capture is not available".to_owned());
159 };
160 capturer.start_capture(Some(source), move |result| {
161 let Ok(frame) = result else { return };
162 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
163 if width >= 2 && height >= 2 {
164 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
165 }
166 });
167 while !stop.load(Ordering::SeqCst) {
168 pump_messages();
169 capturer.capture_frame();
170 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
171 }
172 })
173 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn sources_get_readable_labels() {
182 let screen = ShareSource { id: 1, kind: ShareKind::Screen, title: String::new() };
183 assert_eq!(screen.label(), "Entire screen");
184 let window = ShareSource { id: 2, kind: ShareKind::Window, title: " Notes ".into() };
185 assert_eq!(window.label(), "Notes");
186 }
187}
188
189#[cfg(test)]
190mod thumbnail_tests {
191 use super::scaled_bgra;
192
193 #[test]
194 fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() {
195 let (width, height, stride) = (8u32, 4u32, 40u32);
196 let mut bytes = vec![0u8; (stride * height) as usize];
197 for row in 0..height as usize {
198 for column in 0..width as usize {
199 let offset = row * stride as usize + column * 4;
200 bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]);
201 }
202 }
203 let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap();
204 assert_eq!((picture.width, picture.height), (4, 2));
205 assert_eq!(picture.bgra.len(), 4 * 2 * 4);
206 assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]);
207 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
208 }
209}