BlueGit

ict rusty-teams

Files

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

screen.rs

screen.rs 7.0 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 capturer.capture_frame();
96 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
97 return Some(picture);
98 }
99 std::thread::sleep(THUMBNAIL_RETRY);
100 }
101 None
102}
103
104fn scaled_bgra(bytes: &[u8], width: u32, height: u32, stride: u32, max_width: u32, max_height: u32) -> Option<VideoPicture> {
105 if width == 0 || height == 0 || (stride as usize) < width as usize * 4 || bytes.len() < stride as usize * height as usize {
106 return None;
107 }
108 let scale = (max_width as f32 / width as f32).min(max_height as f32 / height as f32).min(1.);
109 let (target_width, target_height) = (((width as f32 * scale) as u32).max(1), ((height as f32 * scale) as u32).max(1));
110 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
111 for row in 0..target_height {
112 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
113 for column in 0..target_width {
114 let source_column = (column as u64 * width as u64 / target_width as u64) as usize;
115 let offset = source_row * stride as usize + source_column * 4;
116 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
117 }
118 }
119 Some(VideoPicture { width: target_width, height: target_height, bgra })
120}
121
122fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
123 let mut buffer = I420Buffer::new(width, height);
124 let (stride_y, stride_u, stride_v) = buffer.strides();
125 let (plane_y, plane_u, plane_v) = buffer.data_mut();
126 argb_to_i420(bytes, stride, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
127 buffer
128}
129
130pub fn start_screen_capture(
131 wanted: ShareSource,
132 fps: Arc<AtomicU32>,
133 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
134 failed: impl FnOnce(String) + Send + 'static,
135) -> Result<Capture> {
136 Capture::spawn_thread("screen-capture", move |stop| {
137 let Some(source) = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw) else {
138 return failed("the shared source is gone".to_owned());
139 };
140 let Some(mut capturer) = capturer(wanted.kind) else {
141 return failed("screen capture is not available".to_owned());
142 };
143 capturer.start_capture(Some(source), move |result| {
144 let Ok(frame) = result else { return };
145 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
146 if width >= 2 && height >= 2 {
147 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
148 }
149 });
150 while !stop.load(Ordering::SeqCst) {
151 capturer.capture_frame();
152 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
153 }
154 })
155 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn sources_get_readable_labels() {
164 let screen = ShareSource { id: 1, kind: ShareKind::Screen, title: String::new() };
165 assert_eq!(screen.label(), "Entire screen");
166 let window = ShareSource { id: 2, kind: ShareKind::Window, title: " Notes ".into() };
167 assert_eq!(window.label(), "Notes");
168 }
169}
170
171#[cfg(test)]
172mod thumbnail_tests {
173 use super::scaled_bgra;
174
175 #[test]
176 fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() {
177 let (width, height, stride) = (8u32, 4u32, 40u32);
178 let mut bytes = vec![0u8; (stride * height) as usize];
179 for row in 0..height as usize {
180 for column in 0..width as usize {
181 let offset = row * stride as usize + column * 4;
182 bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]);
183 }
184 }
185 let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap();
186 assert_eq!((picture.width, picture.height), (4, 2));
187 assert_eq!(picture.bgra.len(), 4 * 2 * 4);
188 assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]);
189 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
190 }
191}