forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.010.6 MiB02871e1Tahinli2 hours ago415 commits

capture.rs563 lines, 16.5 KiBHistoryRawDownload
1use std::{
2 cell::Cell,
3 error::Error,
4 io::Cursor,
5 os::fd::OwnedFd,
6 rc::Rc,
7 sync::{
8 Arc,
9 atomic::{AtomicBool, Ordering},
10 mpsc::{Receiver, SyncSender, sync_channel},
11 },
12 thread::JoinHandle,
13 time::{Duration, Instant},
14};
15
16use ashpd::desktop::{
17 PersistMode, Session,
18 screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType},
19};
20use pipewire as pw;
21use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState};
22use spa::{
23 buffer::DataType,
24 param::{
25 ParamType,
26 format::{FormatProperties, MediaSubtype, MediaType},
27 format_utils,
28 video::{VideoFormat, VideoInfoRaw},
29 },
30 pod::{
31 ChoiceValue, Object, Pod, Property, PropertyFlags, Value, deserialize::PodDeserializer,
32 object, property, serialize::PodSerializer,
33 },
34 utils::{Choice, ChoiceEnum, ChoiceFlags, Direction, Fraction, Rectangle, SpaTypes},
35};
36
37use crate::lang::w;
38
39use super::frame::{
40 BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Feed, Frame, Gpu, Release, elapsed_ms,
41 pack_rows, take_gpu_failed,
42};
43
44const NEGOTIATE_TIMEOUT: Duration = Duration::from_secs(10);
45const STOP_CHECK: Duration = Duration::from_millis(100);
46const RELEASE_CHECK: Duration = Duration::from_millis(20);
47
48struct Negotiated {
49 width: u32,
50 height: u32,
51 refresh: u32,
52}
53
54pub struct Capture {
55 stop: Arc<AtomicBool>,
56 thread: Option<JoinHandle<()>>,
57 session: Option<Session<Screencast>>,
58 runtime: tokio::runtime::Handle,
59}
60
61impl Drop for Capture {
62 fn drop(&mut self) {
63 self.stop.store(true, Ordering::Relaxed);
64 if let Some(thread) = self.thread.take() {
65 let _ = thread.join();
66 }
67 if let Some(session) = self.session.take() {
68 self.runtime.spawn(async move {
69 let _ = session.close().await;
70 });
71 }
72 }
73}
74
75pub const PICKS: bool = false;
76
77pub fn targets(_: &dyn Fn(super::Target) -> bool) -> Vec<super::Source> {
78 Vec::new()
79}
80
81pub async fn open(_: Option<super::Target>) -> Result<(Feed, Capture), String> {
82 let runtime = tokio::runtime::Handle::current();
83 let screencast = Screencast::new().await.map_err(text)?;
84 let session = screencast
85 .create_session(Default::default())
86 .await
87 .map_err(text)?;
88 let (node_id, fd) = match pick(&screencast, &session).await {
89 Ok(picked) => picked,
90 Err(error) => {
91 let _ = session.close().await;
92 return Err(error);
93 }
94 };
95 match launch(fd, node_id).await {
96 Ok((size, frames, stop, thread)) => Ok((
97 Feed {
98 width: size.width,
99 height: size.height,
100 largest: (size.width, size.height),
101 modes: vec![(size.height, size.refresh)],
102 frames,
103 },
104 Capture {
105 stop,
106 thread: Some(thread),
107 session: Some(session),
108 runtime,
109 },
110 )),
111 Err(error) => {
112 let _ = session.close().await;
113 Err(error)
114 }
115 }
116}
117
118async fn pick(
119 screencast: &Screencast,
120 session: &Session<Screencast>,
121) -> Result<(u32, OwnedFd), String> {
122 screencast
123 .select_sources(
124 session,
125 SelectSourcesOptions::default()
126 .set_cursor_mode(CursorMode::EMBEDDED)
127 .set_sources(SourceType::MONITOR | SourceType::WINDOW)
128 .set_multiple(false)
129 .set_persist_mode(PersistMode::DoNot),
130 )
131 .await
132 .map_err(text)?
133 .response()
134 .map_err(text)?;
135 let streams = screencast
136 .start(session, None, Default::default())
137 .await
138 .map_err(text)?
139 .response()
140 .map_err(text)?;
141 let stream = streams.streams().first().ok_or(w().capture.no_stream)?;
142 let node_id = stream.pipe_wire_node_id();
143 let fd = screencast
144 .open_pipe_wire_remote(session, Default::default())
145 .await
146 .map_err(text)?;
147 Ok((node_id, fd))
148}
149
150async fn launch(
151 fd: OwnedFd,
152 node_id: u32,
153) -> Result<(Negotiated, Receiver<Frame>, Arc<AtomicBool>, JoinHandle<()>), String> {
154 let (negotiated_tx, negotiated_rx) = sync_channel::<Negotiated>(1);
155 let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE);
156 let stop = Arc::new(AtomicBool::new(false));
157 let thread = {
158 let stop = stop.clone();
159 std::thread::Builder::new()
160 .name("share-capture".to_string())
161 .spawn(move || {
162 if let Err(error) = run(fd, node_id, negotiated_tx, frames_tx, &stop) {
163 tracing::warn!("share capture: {error}");
164 }
165 })
166 .map_err(text)?
167 };
168
169 let negotiated =
170 tokio::task::spawn_blocking(move || negotiated_rx.recv_timeout(NEGOTIATE_TIMEOUT).ok())
171 .await
172 .ok()
173 .flatten();
174 match negotiated {
175 Some(size) => Ok((size, frames_rx, stop, thread)),
176 None => {
177 stop.store(true, Ordering::Relaxed);
178 let _ = thread.join();
179 Err(w().capture.did_not_start.into())
180 }
181 }
182}
183
184fn text(error: impl std::fmt::Display) -> String {
185 error.to_string()
186}
187
188#[derive(Clone, Copy, PartialEq)]
189struct Applied {
190 gpu: bool,
191 modifier: u64,
192 format: u32,
193 width: u32,
194 height: u32,
195}
196
197struct State {
198 format: VideoInfoRaw,
199 size: (u32, u32),
200 modifiers: Vec<u64>,
201 applied: Option<Applied>,
202 stop: Arc<AtomicBool>,
203 started: Instant,
204 negotiated: SyncSender<Negotiated>,
205 frames: SyncSender<Frame>,
206}
207
208fn run(
209 fd: OwnedFd,
210 node_id: u32,
211 negotiated: SyncSender<Negotiated>,
212 frames: SyncSender<Frame>,
213 stop: &Arc<AtomicBool>,
214) -> Result<(), Box<dyn Error>> {
215 pw::init();
216 take_gpu_failed();
217 let modifiers = modifiers();
218 let mainloop = pw::main_loop::MainLoopRc::new(None)?;
219 let context = pw::context::ContextRc::new(&mainloop, None)?;
220 let core = context.connect_fd_rc(fd, None)?;
221 let failed = Rc::new(Cell::new(false));
222
223 let core_failed = failed.clone();
224 let _core_listener = core
225 .add_listener_local()
226 .error(move |_, _, _, message| {
227 tracing::warn!("pipewire: {message}");
228 core_failed.set(true);
229 })
230 .register();
231
232 let registry = core.get_registry_rc()?;
233 let source_failed = failed.clone();
234 let _registry_listener = registry
235 .add_listener_local()
236 .global_remove(move |id| {
237 if id == node_id {
238 tracing::warn!("share source removed");
239 source_failed.set(true);
240 }
241 })
242 .register();
243
244 let stream = pw::stream::StreamBox::new(
245 &core,
246 "yumush-share",
247 properties! {
248 *pw::keys::MEDIA_TYPE => "Video",
249 *pw::keys::MEDIA_CATEGORY => "Capture",
250 *pw::keys::MEDIA_ROLE => "Screen",
251 },
252 )?;
253 let state = State {
254 format: VideoInfoRaw::new(),
255 size: (0, 0),
256 modifiers: modifiers.clone(),
257 applied: None,
258 stop: stop.clone(),
259 started: Instant::now(),
260 negotiated,
261 frames,
262 };
263 let stream_failed = failed.clone();
264 let _stream_listener = stream
265 .add_local_listener_with_user_data(state)
266 .state_changed(move |_, _, _, new| {
267 if let StreamState::Error(message) = new {
268 tracing::warn!("pipewire stream: {message}");
269 stream_failed.set(true);
270 }
271 })
272 .param_changed(on_param)
273 .process(on_process)
274 .register()?;
275
276 let gpu = format_values(Some(&modifiers)).ok_or("share format")?;
277 let shm = format_values(None).ok_or("share format")?;
278 let gpu = Pod::from_bytes(&gpu).ok_or("share format")?;
279 let shm = Pod::from_bytes(&shm).ok_or("share format")?;
280 let mut both = [gpu, shm];
281 let mut only_shm = [shm];
282 let params: &mut [&Pod] = if modifiers.is_empty() {
283 &mut only_shm
284 } else {
285 &mut both
286 };
287 stream.connect(
288 Direction::Input,
289 Some(node_id),
290 pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS,
291 params,
292 )?;
293
294 while !stop.load(Ordering::Relaxed) {
295 if failed.get() {
296 return Err("pipewire connection lost".into());
297 }
298 if take_gpu_failed() {
299 tracing::warn!("share capture falls back to shared memory");
300 let _ = stream.update_params(&mut [shm]);
301 }
302 mainloop.loop_().iterate(Timeout::Finite(STOP_CHECK));
303 }
304
305 Ok(())
306}
307
308fn modifiers() -> Vec<u64> {
309 if std::env::var_os("YUMUSH_NO_DMABUF").is_some() {
310 return Vec::new();
311 }
312 ec_hw::dmabuf_modifiers(ec_hw::RgbOrder::Bgra)
313}
314
315fn serialize(object: Object) -> Option<Vec<u8>> {
316 let (cursor, _) =
317 PodSerializer::serialize(Cursor::new(Vec::new()), &Value::Object(object)).ok()?;
318 Some(cursor.into_inner())
319}
320
321fn modifier_property(modifiers: &[u64], flags: PropertyFlags) -> Option<Property> {
322 let first = *modifiers.first()? as i64;
323 let alternatives = modifiers.iter().map(|modifier| *modifier as i64).collect();
324 Some(Property {
325 key: FormatProperties::VideoModifier.as_raw(),
326 flags,
327 value: Value::Choice(ChoiceValue::Long(Choice(
328 ChoiceFlags::empty(),
329 ChoiceEnum::Enum {
330 default: first,
331 alternatives,
332 },
333 ))),
334 })
335}
336
337fn format_values(modifiers: Option<&[u64]>) -> Option<Vec<u8>> {
338 let mut object = object! {
339 SpaTypes::ObjectParamFormat,
340 ParamType::EnumFormat,
341 property!(FormatProperties::MediaType, Id, MediaType::Video),
342 property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
343 property!(
344 FormatProperties::VideoFormat,
345 Choice,
346 Enum,
347 Id,
348 VideoFormat::BGRx,
349 VideoFormat::BGRA
350 ),
351 property!(
352 FormatProperties::VideoSize,
353 Choice,
354 Range,
355 Rectangle,
356 Rectangle { width: 1920, height: 1080 },
357 Rectangle { width: 1, height: 1 },
358 Rectangle { width: 8192, height: 8192 }
359 ),
360 property!(
361 FormatProperties::VideoFramerate,
362 Choice,
363 Range,
364 Fraction,
365 Fraction { num: 60, denom: 1 },
366 Fraction { num: 0, denom: 1 },
367 Fraction { num: 240, denom: 1 }
368 ),
369 };
370 if let Some(modifiers) = modifiers {
371 let flags = if modifiers.len() == 1 {
372 PropertyFlags::MANDATORY
373 } else {
374 PropertyFlags::MANDATORY | PropertyFlags::DONT_FIXATE
375 };
376 object.properties.push(modifier_property(modifiers, flags)?);
377 }
378 serialize(object)
379}
380
381fn buffers_values(gpu: bool) -> Option<Vec<u8>> {
382 let types = if gpu {
383 1 << DataType::DmaBuf.as_raw()
384 } else {
385 (1 << DataType::MemFd.as_raw()) | (1 << DataType::MemPtr.as_raw())
386 };
387 serialize(Object {
388 type_: SpaTypes::ObjectParamBuffers.as_raw(),
389 id: ParamType::Buffers.as_raw(),
390 properties: vec![Property {
391 key: spa::sys::SPA_PARAM_BUFFERS_dataType,
392 flags: PropertyFlags::empty(),
393 value: Value::Choice(ChoiceValue::Int(Choice(
394 ChoiceFlags::empty(),
395 ChoiceEnum::Flags {
396 default: types,
397 flags: Vec::new(),
398 },
399 ))),
400 }],
401 })
402}
403
404fn offered_modifier(param: &Pod) -> Option<(Vec<u64>, bool)> {
405 let (_, Value::Object(object)) =
406 PodDeserializer::deserialize_any_from(param.as_bytes()).ok()?
407 else {
408 return None;
409 };
410 let property = object
411 .properties
412 .into_iter()
413 .find(|property| property.key == FormatProperties::VideoModifier.as_raw())?;
414 let unfixed = property.flags.contains(PropertyFlags::DONT_FIXATE);
415 let values = match property.value {
416 Value::Long(value) => vec![value as u64],
417 Value::Choice(ChoiceValue::Long(Choice(
418 _,
419 ChoiceEnum::Enum {
420 default,
421 alternatives,
422 },
423 ))) => std::iter::once(default)
424 .chain(alternatives)
425 .map(|value| value as u64)
426 .collect(),
427 Value::Choice(ChoiceValue::Long(Choice(_, ChoiceEnum::None(value)))) => vec![value as u64],
428 _ => return None,
429 };
430 Some((values, unfixed))
431}
432
433fn on_param(stream: &pw::stream::Stream, state: &mut State, id: u32, param: Option<&Pod>) {
434 let Some(param) = param else {
435 return;
436 };
437 if id != ParamType::Format.as_raw() {
438 return;
439 }
440 let Ok((media_type, media_subtype)) = format_utils::parse_format(param) else {
441 return;
442 };
443 if media_type != MediaType::Video || media_subtype != MediaSubtype::Raw {
444 return;
445 }
446 if state.format.parse(param).is_err() {
447 return;
448 }
449 let offered = offered_modifier(param);
450 if let Some((offered, true)) = &offered {
451 let fixed = offered
452 .iter()
453 .find(|modifier| state.modifiers.contains(modifier))
454 .and_then(|chosen| format_values(Some(&[*chosen])));
455 let shm = format_values(None);
456 if let Some(shm) = shm.as_deref().and_then(Pod::from_bytes) {
457 let mut params: Vec<&Pod> = fixed
458 .as_deref()
459 .and_then(Pod::from_bytes)
460 .into_iter()
461 .chain(std::iter::once(shm))
462 .collect();
463 let _ = stream.update_params(&mut params);
464 }
465 return;
466 }
467 let gpu = offered.is_some();
468 let size = state.format.size();
469 let modifier = if gpu { state.format.modifier() } else { 0 };
470 let applied = Applied {
471 gpu,
472 modifier,
473 format: state.format.format().as_raw(),
474 width: size.width,
475 height: size.height,
476 };
477 if state.applied == Some(applied) {
478 return;
479 }
480 state.applied = Some(applied);
481 tracing::info!(gpu, modifier, format = ?state.format.format(), "share capture format");
482 if let Some(buffers) = buffers_values(gpu)
483 && let Some(buffers) = Pod::from_bytes(&buffers)
484 {
485 let _ = stream.update_params(&mut [buffers]);
486 }
487
488 let fps = state.format.max_framerate();
489 let refresh = fps
490 .num
491 .checked_div(fps.denom)
492 .filter(|refresh| *refresh > 0)
493 .unwrap_or(DEFAULT_REFRESH);
494 tracing::info!(refresh, "share capture refresh");
495 state.size = (size.width, size.height);
496 let _ = state.negotiated.try_send(Negotiated {
497 width: size.width,
498 height: size.height,
499 refresh,
500 });
501}
502
503fn on_process(stream: &pw::stream::Stream, state: &mut State) {
504 crate::usage::tick(crate::usage::Group::Camera);
505 let (width, height) = state.size;
506 if width == 0 || height == 0 {
507 return;
508 }
509 let Some(mut buffer) = stream.dequeue_buffer() else {
510 return;
511 };
512 let Some(plane) = buffer.datas_mut().first_mut() else {
513 return;
514 };
515 if plane.type_() == DataType::DmaBuf {
516 let (release, released) = sync_channel(1);
517 let chunk = plane.chunk();
518 let frame = Frame {
519 width,
520 height,
521 stride: width * BYTES_PER_PIXEL as u32,
522 timestamp_ms: elapsed_ms(state.started),
523 bgra: Vec::new(),
524 gpu: Some(Gpu {
525 fd: plane.fd(),
526 offset: chunk.offset(),
527 stride: u32::try_from(chunk.stride()).unwrap_or(0),
528 modifier: state.format.modifier(),
529 bgra: matches!(state.format.format(), VideoFormat::BGRx | VideoFormat::BGRA),
530 release: Release(release),
531 }),
532 };
533 if state.frames.try_send(frame).is_ok() {
534 while !state.stop.load(Ordering::Relaxed)
535 && released.recv_timeout(RELEASE_CHECK).is_err()
536 {}
537 }
538 return;
539 }
540
541 let row = width as usize * BYTES_PER_PIXEL;
542 let (offset, stride) = {
543 let chunk = plane.chunk();
544 (
545 chunk.offset() as usize,
546 usize::try_from(chunk.stride()).unwrap_or(0),
547 )
548 };
549 let stride = stride.max(row);
550 let Some(data) = plane.data() else {
551 return;
552 };
553 let Some(source) = data.get(offset..) else {
554 return;
555 };
556
557 let Some(bgra) = pack_rows(source, stride, row, height) else {
558 return;
559 };
560 let _ = state
561 .frames
562 .try_send(Frame::cpu(width, height, elapsed_ms(state.started), bgra));
563}