forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

pw_utils.rs1043 lines, 36.7 KiBHistoryRawDownload
1use std::cell::{Cell, RefCell};
2use std::collections::HashMap;
3use std::io::Cursor;
4use std::iter::zip;
5use std::mem;
6use std::os::fd::{AsFd, AsRawFd, BorrowedFd};
7use std::rc::Rc;
8use std::time::Duration;
9
10use anyhow::Context as _;
11use calloop::timer::{TimeoutAction, Timer};
12use calloop::RegistrationToken;
13use pipewire::context::Context;
14use pipewire::core::Core;
15use pipewire::main_loop::MainLoop;
16use pipewire::properties::Properties;
17use pipewire::spa::buffer::DataType;
18use pipewire::spa::param::format::{FormatProperties, MediaSubtype, MediaType};
19use pipewire::spa::param::format_utils::parse_format;
20use pipewire::spa::param::video::{VideoFormat, VideoInfoRaw};
21use pipewire::spa::param::ParamType;
22use pipewire::spa::pod::deserialize::PodDeserializer;
23use pipewire::spa::pod::serialize::PodSerializer;
24use pipewire::spa::pod::{self, ChoiceValue, Pod, PodPropFlags, Property, PropertyFlags};
25use pipewire::spa::sys::*;
26use pipewire::spa::utils::{
27 Choice, ChoiceEnum, ChoiceFlags, Direction, Fraction, Rectangle, SpaTypes,
28};
29use pipewire::spa::{self};
30use pipewire::stream::{Stream, StreamFlags, StreamListener, StreamState};
31use smithay::backend::allocator::dmabuf::{AsDmabuf, Dmabuf};
32use smithay::backend::allocator::format::FormatSet;
33use smithay::backend::allocator::gbm::{GbmBuffer, GbmBufferFlags, GbmDevice};
34use smithay::backend::allocator::{Format, Fourcc};
35use smithay::backend::drm::DrmDeviceFd;
36use smithay::backend::renderer::damage::OutputDamageTracker;
37use smithay::backend::renderer::element::RenderElement;
38use smithay::backend::renderer::gles::GlesRenderer;
39use smithay::output::{Output, OutputModeSource, WeakOutput};
40use smithay::reexports::calloop::generic::Generic;
41use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
42use smithay::reexports::gbm::Modifier;
43use smithay::utils::{Physical, Scale, Size, Transform};
44use zbus::SignalContext;
45
46use crate::dbus::mutter_screen_cast::{self, CursorMode};
47use crate::niri::State;
48use crate::render_helpers::render_to_dmabuf;
49use crate::utils::get_monotonic_time;
50
51// Give a 0.1 ms allowance for presentation time errors.
52const CAST_DELAY_ALLOWANCE: Duration = Duration::from_micros(100);
53
54pub struct PipeWire {
55 _context: Context,
56 pub core: Core,
57 to_niri: calloop::channel::Sender<PwToNiri>,
58}
59
60pub enum PwToNiri {
61 StopCast { session_id: usize },
62 Redraw(CastTarget),
63}
64
65pub struct Cast {
66 pub session_id: usize,
67 pub stream: Stream,
68 _listener: StreamListener<()>,
69 pub is_active: Rc<Cell<bool>>,
70 pub target: CastTarget,
71 formats: FormatSet,
72 state: Rc<RefCell<CastState>>,
73 refresh: Rc<Cell<u32>>,
74 offer_alpha: bool,
75 pub cursor_mode: CursorMode,
76 pub last_frame_time: Duration,
77 min_time_between_frames: Rc<Cell<Duration>>,
78 dmabufs: Rc<RefCell<HashMap<i64, Dmabuf>>>,
79 scheduled_redraw: Option<RegistrationToken>,
80}
81
82#[derive(Debug)]
83pub enum CastState {
84 ResizePending {
85 pending_size: Size<u32, Physical>,
86 },
87 ConfirmationPending {
88 size: Size<u32, Physical>,
89 alpha: bool,
90 modifier: Modifier,
91 plane_count: i32,
92 },
93 Ready {
94 size: Size<u32, Physical>,
95 alpha: bool,
96 modifier: Modifier,
97 plane_count: i32,
98 // Lazily-initialized to keep the initialization to a single place.
99 damage_tracker: Option<OutputDamageTracker>,
100 },
101}
102
103#[derive(PartialEq, Eq)]
104pub enum CastSizeChange {
105 Ready,
106 Pending,
107}
108
109#[derive(Clone, PartialEq, Eq)]
110pub enum CastTarget {
111 Output(WeakOutput),
112 Window { id: u64 },
113}
114
115macro_rules! make_params {
116 ($params:ident, $formats:expr, $size:expr, $refresh:expr, $alpha:expr) => {
117 let mut b1 = Vec::new();
118 let mut b2 = Vec::new();
119
120 let o1 = make_video_params($formats, $size, $refresh, false);
121 let pod1 = make_pod(&mut b1, o1);
122
123 let mut p1;
124 let mut p2;
125 $params = if $alpha {
126 let o2 = make_video_params($formats, $size, $refresh, true);
127 p2 = [pod1, make_pod(&mut b2, o2)];
128 &mut p2[..]
129 } else {
130 p1 = [pod1];
131 &mut p1[..]
132 };
133 };
134}
135
136impl PipeWire {
137 pub fn new(event_loop: &LoopHandle<'static, State>) -> anyhow::Result<Self> {
138 let main_loop = MainLoop::new(None).context("error creating MainLoop")?;
139 let context = Context::new(&main_loop).context("error creating Context")?;
140 let core = context.connect(None).context("error creating Core")?;
141
142 let listener = core
143 .add_listener_local()
144 .error(|id, seq, res, message| {
145 warn!(id, seq, res, message, "pw error");
146 })
147 .register();
148 mem::forget(listener);
149
150 struct AsFdWrapper(MainLoop);
151 impl AsFd for AsFdWrapper {
152 fn as_fd(&self) -> BorrowedFd<'_> {
153 self.0.loop_().fd()
154 }
155 }
156 let generic = Generic::new(AsFdWrapper(main_loop), Interest::READ, Mode::Level);
157 event_loop
158 .insert_source(generic, move |_, wrapper, _| {
159 let _span = tracy_client::span!("pipewire iteration");
160 wrapper.0.loop_().iterate(Duration::ZERO);
161 Ok(PostAction::Continue)
162 })
163 .unwrap();
164
165 let (to_niri, from_pipewire) = calloop::channel::channel();
166 event_loop
167 .insert_source(from_pipewire, move |event, _, state| match event {
168 calloop::channel::Event::Msg(msg) => state.on_pw_msg(msg),
169 calloop::channel::Event::Closed => (),
170 })
171 .unwrap();
172
173 Ok(Self {
174 _context: context,
175 core,
176 to_niri,
177 })
178 }
179
180 #[allow(clippy::too_many_arguments)]
181 pub fn start_cast(
182 &self,
183 gbm: GbmDevice<DrmDeviceFd>,
184 formats: FormatSet,
185 session_id: usize,
186 target: CastTarget,
187 size: Size<i32, Physical>,
188 refresh: u32,
189 alpha: bool,
190 cursor_mode: CursorMode,
191 signal_ctx: SignalContext<'static>,
192 ) -> anyhow::Result<Cast> {
193 let _span = tracy_client::span!("PipeWire::start_cast");
194
195 let to_niri_ = self.to_niri.clone();
196 let stop_cast = move || {
197 if let Err(err) = to_niri_.send(PwToNiri::StopCast { session_id }) {
198 warn!("error sending StopCast to niri: {err:?}");
199 }
200 };
201 let target_ = target.clone();
202 let to_niri_ = self.to_niri.clone();
203 let redraw = move || {
204 if let Err(err) = to_niri_.send(PwToNiri::Redraw(target_.clone())) {
205 warn!("error sending Redraw to niri: {err:?}");
206 }
207 };
208 let redraw_ = redraw.clone();
209
210 let stream = Stream::new(&self.core, "niri-screen-cast-src", Properties::new())
211 .context("error creating Stream")?;
212
213 // Like in good old wayland-rs times...
214 let node_id = Rc::new(Cell::new(None));
215 let is_active = Rc::new(Cell::new(false));
216 let min_time_between_frames = Rc::new(Cell::new(Duration::ZERO));
217 let dmabufs = Rc::new(RefCell::new(HashMap::new()));
218 let refresh = Rc::new(Cell::new(refresh));
219
220 let pending_size = Size::from((size.w as u32, size.h as u32));
221 let state = Rc::new(RefCell::new(CastState::ResizePending { pending_size }));
222
223 let listener = stream
224 .add_local_listener_with_user_data(())
225 .state_changed({
226 let is_active = is_active.clone();
227 let stop_cast = stop_cast.clone();
228 move |stream, (), old, new| {
229 debug!("pw stream: state changed: {old:?} -> {new:?}");
230
231 match new {
232 StreamState::Paused => {
233 if node_id.get().is_none() {
234 let id = stream.node_id();
235 node_id.set(Some(id));
236 debug!("pw stream: sending signal with {id}");
237
238 let _span = tracy_client::span!("sending PipeWireStreamAdded");
239 async_io::block_on(async {
240 let res = mutter_screen_cast::Stream::pipe_wire_stream_added(
241 &signal_ctx,
242 id,
243 )
244 .await;
245
246 if let Err(err) = res {
247 warn!("error sending PipeWireStreamAdded: {err:?}");
248 stop_cast();
249 }
250 });
251 }
252
253 is_active.set(false);
254 }
255 StreamState::Error(_) => {
256 if is_active.get() {
257 is_active.set(false);
258 stop_cast();
259 }
260 }
261 StreamState::Unconnected => (),
262 StreamState::Connecting => (),
263 StreamState::Streaming => {
264 is_active.set(true);
265 redraw();
266 }
267 }
268 }
269 })
270 .param_changed({
271 let min_time_between_frames = min_time_between_frames.clone();
272 let stop_cast = stop_cast.clone();
273 let state = state.clone();
274 let gbm = gbm.clone();
275 let formats = formats.clone();
276 let refresh = refresh.clone();
277 move |stream, (), id, pod| {
278 let id = ParamType::from_raw(id);
279 trace!(?id, "pw stream: param_changed");
280
281 if id != ParamType::Format {
282 return;
283 }
284
285 let Some(pod) = pod else { return };
286
287 let (m_type, m_subtype) = match parse_format(pod) {
288 Ok(x) => x,
289 Err(err) => {
290 warn!("pw stream: error parsing format: {err:?}");
291 return;
292 }
293 };
294
295 if m_type != MediaType::Video || m_subtype != MediaSubtype::Raw {
296 return;
297 }
298
299 let mut format = VideoInfoRaw::new();
300 format.parse(pod).unwrap();
301 debug!("pw stream: got format = {format:?}");
302
303 let format_size = Size::from((format.size().width, format.size().height));
304
305 let mut state = state.borrow_mut();
306 if format_size != state.expected_format_size() {
307 if !matches!(&*state, CastState::ResizePending { .. }) {
308 warn!("pw stream: wrong size, but we're not resizing");
309 stop_cast();
310 return;
311 }
312
313 debug!("pw stream: wrong size, waiting");
314 return;
315 }
316
317 let format_has_alpha = format.format() == VideoFormat::BGRA;
318 let fourcc = if format_has_alpha {
319 Fourcc::Argb8888
320 } else {
321 Fourcc::Xrgb8888
322 };
323
324 let max_frame_rate = format.max_framerate();
325 let min_frame_time = Duration::from_micros(
326 1_000_000 * u64::from(max_frame_rate.denom) / u64::from(max_frame_rate.num),
327 );
328 min_time_between_frames.set(min_frame_time);
329
330 let object = pod.as_object().unwrap();
331 let Some(prop_modifier) =
332 object.find_prop(spa::utils::Id(FormatProperties::VideoModifier.0))
333 else {
334 warn!("pw stream: modifier prop missing");
335 stop_cast();
336 return;
337 };
338
339 if prop_modifier.flags().contains(PodPropFlags::DONT_FIXATE) {
340 debug!("pw stream: fixating the modifier");
341
342 let pod_modifier = prop_modifier.value();
343 let Ok((_, modifiers)) = PodDeserializer::deserialize_from::<Choice<i64>>(
344 pod_modifier.as_bytes(),
345 ) else {
346 warn!("pw stream: wrong modifier property type");
347 stop_cast();
348 return;
349 };
350
351 let ChoiceEnum::Enum { alternatives, .. } = modifiers.1 else {
352 warn!("pw stream: wrong modifier choice type");
353 stop_cast();
354 return;
355 };
356
357 let (modifier, plane_count) = match find_preferred_modifier(
358 &gbm,
359 format_size,
360 fourcc,
361 alternatives,
362 ) {
363 Ok(x) => x,
364 Err(err) => {
365 warn!("pw stream: couldn't find preferred modifier: {err:?}");
366 stop_cast();
367 return;
368 }
369 };
370
371 debug!(
372 "pw stream: allocation successful \
373 (modifier={modifier:?}, plane_count={plane_count}), \
374 moving to confirmation pending"
375 );
376
377 *state = CastState::ConfirmationPending {
378 size: format_size,
379 alpha: format_has_alpha,
380 modifier,
381 plane_count: plane_count as i32,
382 };
383
384 let fixated_format = FormatSet::from_iter([Format {
385 code: fourcc,
386 modifier,
387 }]);
388
389 let mut b1 = Vec::new();
390 let mut b2 = Vec::new();
391
392 let o1 = make_video_params(
393 &fixated_format,
394 format_size,
395 refresh.get(),
396 format_has_alpha,
397 );
398 let pod1 = make_pod(&mut b1, o1);
399
400 let o2 = make_video_params(
401 &formats,
402 format_size,
403 refresh.get(),
404 format_has_alpha,
405 );
406 let mut params = [pod1, make_pod(&mut b2, o2)];
407
408 if let Err(err) = stream.update_params(&mut params) {
409 warn!("error updating stream params: {err:?}");
410 stop_cast();
411 }
412
413 return;
414 }
415
416 // Verify that alpha and modifier didn't change.
417 let plane_count = match &*state {
418 CastState::ConfirmationPending {
419 size,
420 alpha,
421 modifier,
422 plane_count,
423 }
424 | CastState::Ready {
425 size,
426 alpha,
427 modifier,
428 plane_count,
429 ..
430 } if *alpha == format_has_alpha
431 && *modifier == Modifier::from(format.modifier()) =>
432 {
433 let size = *size;
434 let alpha = *alpha;
435 let modifier = *modifier;
436 let plane_count = *plane_count;
437
438 let damage_tracker =
439 if let CastState::Ready { damage_tracker, .. } = &mut *state {
440 damage_tracker.take()
441 } else {
442 None
443 };
444
445 debug!("pw stream: moving to ready state");
446
447 *state = CastState::Ready {
448 size,
449 alpha,
450 modifier,
451 plane_count,
452 damage_tracker,
453 };
454
455 plane_count
456 }
457 _ => {
458 // We're negotiating a single modifier, or alpha or modifier changed,
459 // so we need to do a test allocation.
460 let (modifier, plane_count) = match find_preferred_modifier(
461 &gbm,
462 format_size,
463 fourcc,
464 vec![format.modifier() as i64],
465 ) {
466 Ok(x) => x,
467 Err(err) => {
468 warn!("pw stream: test allocation failed: {err:?}");
469 stop_cast();
470 return;
471 }
472 };
473
474 debug!(
475 "pw stream: allocation successful \
476 (modifier={modifier:?}, plane_count={plane_count}), \
477 moving to ready"
478 );
479
480 *state = CastState::Ready {
481 size: format_size,
482 alpha: format_has_alpha,
483 modifier,
484 plane_count: plane_count as i32,
485 damage_tracker: None,
486 };
487
488 plane_count as i32
489 }
490 };
491
492 // const BPP: u32 = 4;
493 // let stride = format.size().width * BPP;
494 // let size = stride * format.size().height;
495
496 let o1 = pod::object!(
497 SpaTypes::ObjectParamBuffers,
498 ParamType::Buffers,
499 Property::new(
500 SPA_PARAM_BUFFERS_buffers,
501 pod::Value::Choice(ChoiceValue::Int(Choice(
502 ChoiceFlags::empty(),
503 ChoiceEnum::Range {
504 default: 16,
505 min: 2,
506 max: 16
507 }
508 ))),
509 ),
510 Property::new(SPA_PARAM_BUFFERS_blocks, pod::Value::Int(plane_count)),
511 // Property::new(SPA_PARAM_BUFFERS_size, pod::Value::Int(size as i32)),
512 // Property::new(SPA_PARAM_BUFFERS_stride, pod::Value::Int(stride as i32)),
513 // Property::new(SPA_PARAM_BUFFERS_align, pod::Value::Int(16)),
514 Property::new(
515 SPA_PARAM_BUFFERS_dataType,
516 pod::Value::Choice(ChoiceValue::Int(Choice(
517 ChoiceFlags::empty(),
518 ChoiceEnum::Flags {
519 default: 1 << DataType::DmaBuf.as_raw(),
520 flags: vec![1 << DataType::DmaBuf.as_raw()],
521 },
522 ))),
523 ),
524 );
525
526 // FIXME: Hidden / embedded / metadata cursor
527
528 // let o2 = pod::object!(
529 // SpaTypes::ObjectParamMeta,
530 // ParamType::Meta,
531 // Property::new(SPA_PARAM_META_type,
532 // pod::Value::Id(Id(SPA_META_Header))),
533 // Property::new(
534 // SPA_PARAM_META_size,
535 // pod::Value::Int(size_of::<spa_meta_header>() as i32)
536 // ),
537 // );
538 let mut b1 = vec![];
539 // let mut b2 = vec![];
540 let mut params = [
541 make_pod(&mut b1, o1), // make_pod(&mut b2, o2)
542 ];
543
544 if let Err(err) = stream.update_params(&mut params) {
545 warn!("error updating stream params: {err:?}");
546 stop_cast();
547 }
548 }
549 })
550 .add_buffer({
551 let dmabufs = dmabufs.clone();
552 let stop_cast = stop_cast.clone();
553 let state = state.clone();
554 move |stream, (), buffer| {
555 let (size, alpha, modifier) = if let CastState::Ready {
556 size,
557 alpha,
558 modifier,
559 ..
560 } = &*state.borrow()
561 {
562 (*size, *alpha, *modifier)
563 } else {
564 trace!("pw stream: add buffer, but not ready yet");
565 return;
566 };
567
568 trace!(
569 "pw stream: add_buffer, size={size:?}, alpha={alpha}, \
570 modifier={modifier:?}"
571 );
572
573 unsafe {
574 let spa_buffer = (*buffer).buffer;
575
576 let fourcc = if alpha {
577 Fourcc::Argb8888
578 } else {
579 Fourcc::Xrgb8888
580 };
581
582 let dmabuf = match allocate_dmabuf(&gbm, size, fourcc, modifier) {
583 Ok(dmabuf) => dmabuf,
584 Err(err) => {
585 warn!("error allocating dmabuf: {err:?}");
586 stop_cast();
587 return;
588 }
589 };
590
591 let plane_count = dmabuf.num_planes();
592 assert_eq!((*spa_buffer).n_datas as usize, plane_count);
593
594 for (i, fd) in dmabuf.handles().enumerate() {
595 let spa_data = (*spa_buffer).datas.add(i);
596 assert!((*spa_data).type_ & (1 << DataType::DmaBuf.as_raw()) > 0);
597
598 (*spa_data).type_ = DataType::DmaBuf.as_raw();
599 (*spa_data).maxsize = 1;
600 (*spa_data).fd = fd.as_raw_fd() as i64;
601 (*spa_data).flags = SPA_DATA_FLAG_READWRITE;
602 }
603
604 let fd = (*(*spa_buffer).datas).fd;
605 assert!(dmabufs.borrow_mut().insert(fd, dmabuf).is_none());
606 }
607
608 // During size re-negotiation, the stream sometimes just keeps running, in
609 // which case we may need to force a redraw once we got a newly sized buffer.
610 if dmabufs.borrow().len() == 1 && stream.state() == StreamState::Streaming {
611 redraw_();
612 }
613 }
614 })
615 .remove_buffer({
616 let dmabufs = dmabufs.clone();
617 move |_stream, (), buffer| {
618 trace!("pw stream: remove_buffer");
619
620 unsafe {
621 let spa_buffer = (*buffer).buffer;
622 let spa_data = (*spa_buffer).datas;
623 assert!((*spa_buffer).n_datas > 0);
624
625 let fd = (*spa_data).fd;
626 dmabufs.borrow_mut().remove(&fd);
627 }
628 }
629 })
630 .register()
631 .unwrap();
632
633 trace!("starting pw stream with size={pending_size:?}, refresh={refresh:?}");
634
635 let params;
636 make_params!(params, &formats, pending_size, refresh.get(), alpha);
637 stream
638 .connect(
639 Direction::Output,
640 None,
641 StreamFlags::DRIVER | StreamFlags::ALLOC_BUFFERS,
642 params,
643 )
644 .context("error connecting stream")?;
645
646 let cast = Cast {
647 session_id,
648 stream,
649 _listener: listener,
650 is_active,
651 target,
652 formats,
653 state,
654 refresh,
655 offer_alpha: alpha,
656 cursor_mode,
657 last_frame_time: Duration::ZERO,
658 min_time_between_frames,
659 dmabufs,
660 scheduled_redraw: None,
661 };
662 Ok(cast)
663 }
664}
665
666impl Cast {
667 pub fn ensure_size(&self, size: Size<i32, Physical>) -> anyhow::Result<CastSizeChange> {
668 let new_size = Size::from((size.w as u32, size.h as u32));
669
670 let mut state = self.state.borrow_mut();
671 if matches!(&*state, CastState::Ready { size, .. } if *size == new_size) {
672 return Ok(CastSizeChange::Ready);
673 }
674
675 if state.pending_size() == Some(new_size) {
676 debug!("stream size still hasn't changed, skipping frame");
677 return Ok(CastSizeChange::Pending);
678 }
679
680 let _span = tracy_client::span!("Cast::ensure_size");
681 debug!("cast size changed, updating stream size");
682
683 *state = CastState::ResizePending {
684 pending_size: new_size,
685 };
686
687 let params;
688 make_params!(
689 params,
690 &self.formats,
691 new_size,
692 self.refresh.get(),
693 self.offer_alpha
694 );
695 self.stream
696 .update_params(params)
697 .context("error updating stream params")?;
698
699 Ok(CastSizeChange::Pending)
700 }
701
702 pub fn set_refresh(&mut self, refresh: u32) -> anyhow::Result<()> {
703 if self.refresh.get() == refresh {
704 return Ok(());
705 }
706
707 let _span = tracy_client::span!("Cast::set_refresh");
708 debug!("cast FPS changed, updating stream FPS");
709 self.refresh.set(refresh);
710
711 let size = self.state.borrow().expected_format_size();
712 let params;
713 make_params!(params, &self.formats, size, refresh, self.offer_alpha);
714 self.stream
715 .update_params(params)
716 .context("error updating stream params")?;
717
718 Ok(())
719 }
720
721 fn compute_extra_delay(&self, target_frame_time: Duration) -> Duration {
722 let last = self.last_frame_time;
723 let min = self.min_time_between_frames.get();
724
725 if last.is_zero() {
726 trace!(?target_frame_time, ?last, "last is zero, recording");
727 return Duration::ZERO;
728 }
729
730 if target_frame_time < last {
731 // Record frame with a warning; in case it was an overflow this will fix it.
732 warn!(
733 ?target_frame_time,
734 ?last,
735 "target frame time is below last, did it overflow or did we mispredict?"
736 );
737 return Duration::ZERO;
738 }
739
740 let diff = target_frame_time - last;
741 if diff < min {
742 let delay = min - diff;
743 trace!(
744 ?target_frame_time,
745 ?last,
746 "frame is too soon: min={min:?}, delay={:?}",
747 delay
748 );
749 return delay;
750 } else {
751 trace!("overshoot={:?}", diff - min);
752 }
753
754 Duration::ZERO
755 }
756
757 fn schedule_redraw(
758 &mut self,
759 event_loop: &LoopHandle<'static, State>,
760 output: Output,
761 target_time: Duration,
762 ) {
763 if self.scheduled_redraw.is_some() {
764 return;
765 }
766
767 let now = get_monotonic_time();
768 let duration = target_time.saturating_sub(now);
769 let timer = Timer::from_duration(duration);
770 let token = event_loop
771 .insert_source(timer, move |_, _, state| {
772 state.niri.queue_redraw(&output);
773 TimeoutAction::Drop
774 })
775 .unwrap();
776 self.scheduled_redraw = Some(token);
777 }
778
779 fn remove_scheduled_redraw(&mut self, event_loop: &LoopHandle<'static, State>) {
780 if let Some(token) = self.scheduled_redraw.take() {
781 event_loop.remove(token);
782 }
783 }
784
785 /// Checks whether this frame should be skipped because it's too soon.
786 ///
787 /// If the frame should be skipped, schedules a redraw and returns `true`. Otherwise, removes a
788 /// scheduled redraw, if any, and returns `false`.
789 ///
790 /// When this method returns `false`, the calling code is assumed to follow up with
791 /// [`Cast::dequeue_buffer_and_render()`].
792 pub fn check_time_and_schedule(
793 &mut self,
794 event_loop: &LoopHandle<'static, State>,
795 output: &Output,
796 target_frame_time: Duration,
797 ) -> bool {
798 let delay = self.compute_extra_delay(target_frame_time);
799 if delay >= CAST_DELAY_ALLOWANCE {
800 trace!("delay >= allowance, scheduling redraw");
801 self.schedule_redraw(event_loop, output.clone(), target_frame_time + delay);
802 true
803 } else {
804 self.remove_scheduled_redraw(event_loop);
805 false
806 }
807 }
808
809 pub fn dequeue_buffer_and_render(
810 &mut self,
811 renderer: &mut GlesRenderer,
812 elements: &[impl RenderElement<GlesRenderer>],
813 size: Size<i32, Physical>,
814 scale: Scale<f64>,
815 ) -> bool {
816 let CastState::Ready { damage_tracker, .. } = &mut *self.state.borrow_mut() else {
817 error!("cast must be in Ready state to render");
818 return false;
819 };
820 let damage_tracker = damage_tracker
821 .get_or_insert_with(|| OutputDamageTracker::new(size, scale, Transform::Normal));
822
823 // Size change will drop the damage tracker, but scale change won't, so check it here.
824 let OutputModeSource::Static { scale: t_scale, .. } = damage_tracker.mode() else {
825 unreachable!();
826 };
827 if *t_scale != scale {
828 *damage_tracker = OutputDamageTracker::new(size, scale, Transform::Normal);
829 }
830
831 let (damage, _states) = damage_tracker.damage_output(1, elements).unwrap();
832 if damage.is_none() {
833 trace!("no damage, skipping frame");
834 return false;
835 }
836
837 let mut buffer = match self.stream.dequeue_buffer() {
838 Some(buffer) => buffer,
839 None => {
840 warn!("no available buffer in pw stream, skipping frame");
841 return false;
842 }
843 };
844
845 let fd = buffer.datas_mut()[0].as_raw().fd;
846 let dmabuf = &self.dmabufs.borrow()[&fd];
847
848 if let Err(err) = render_to_dmabuf(
849 renderer,
850 dmabuf.clone(),
851 size,
852 scale,
853 Transform::Normal,
854 elements.iter().rev(),
855 ) {
856 warn!("error rendering to dmabuf: {err:?}");
857 return false;
858 }
859
860 for (data, (stride, offset)) in
861 zip(buffer.datas_mut(), zip(dmabuf.strides(), dmabuf.offsets()))
862 {
863 let chunk = data.chunk_mut();
864 *chunk.size_mut() = 1;
865 *chunk.stride_mut() = stride as i32;
866 *chunk.offset_mut() = offset;
867
868 trace!(
869 "pw buffer: fd = {}, stride = {stride}, offset = {offset}",
870 data.as_raw().fd
871 );
872 }
873
874 true
875 }
876}
877
878impl CastState {
879 fn pending_size(&self) -> Option<Size<u32, Physical>> {
880 match self {
881 CastState::ResizePending { pending_size } => Some(*pending_size),
882 CastState::ConfirmationPending { size, .. } => Some(*size),
883 CastState::Ready { .. } => None,
884 }
885 }
886
887 fn expected_format_size(&self) -> Size<u32, Physical> {
888 match self {
889 CastState::ResizePending { pending_size } => *pending_size,
890 CastState::ConfirmationPending { size, .. } => *size,
891 CastState::Ready { size, .. } => *size,
892 }
893 }
894}
895
896fn make_video_params(
897 formats: &FormatSet,
898 size: Size<u32, Physical>,
899 refresh: u32,
900 alpha: bool,
901) -> pod::Object {
902 let format = if alpha {
903 VideoFormat::BGRA
904 } else {
905 VideoFormat::BGRx
906 };
907
908 let fourcc = if alpha {
909 Fourcc::Argb8888
910 } else {
911 Fourcc::Xrgb8888
912 };
913
914 let formats: Vec<_> = formats
915 .iter()
916 .filter_map(|f| (f.code == fourcc).then_some(u64::from(f.modifier) as i64))
917 .collect();
918
919 trace!("offering: {formats:?}");
920
921 let dont_fixate = if formats.len() > 1 {
922 PropertyFlags::DONT_FIXATE
923 } else {
924 PropertyFlags::empty()
925 };
926
927 pod::object!(
928 SpaTypes::ObjectParamFormat,
929 ParamType::EnumFormat,
930 pod::property!(FormatProperties::MediaType, Id, MediaType::Video),
931 pod::property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
932 pod::property!(FormatProperties::VideoFormat, Id, format),
933 Property {
934 key: FormatProperties::VideoModifier.as_raw(),
935 flags: PropertyFlags::MANDATORY | dont_fixate,
936 value: pod::Value::Choice(ChoiceValue::Long(Choice(
937 ChoiceFlags::empty(),
938 ChoiceEnum::Enum {
939 default: formats[0],
940 alternatives: formats,
941 }
942 )))
943 },
944 pod::property!(
945 FormatProperties::VideoSize,
946 Rectangle,
947 Rectangle {
948 width: size.w,
949 height: size.h,
950 }
951 ),
952 pod::property!(
953 FormatProperties::VideoFramerate,
954 Fraction,
955 Fraction { num: 0, denom: 1 }
956 ),
957 pod::property!(
958 FormatProperties::VideoMaxFramerate,
959 Choice,
960 Range,
961 Fraction,
962 Fraction {
963 num: refresh,
964 denom: 1000
965 },
966 Fraction { num: 1, denom: 1 },
967 Fraction {
968 num: refresh,
969 denom: 1000
970 }
971 ),
972 )
973}
974
975fn make_pod(buffer: &mut Vec<u8>, object: pod::Object) -> &Pod {
976 PodSerializer::serialize(Cursor::new(&mut *buffer), &pod::Value::Object(object)).unwrap();
977 Pod::from_bytes(buffer).unwrap()
978}
979
980fn find_preferred_modifier(
981 gbm: &GbmDevice<DrmDeviceFd>,
982 size: Size<u32, Physical>,
983 fourcc: Fourcc,
984 modifiers: Vec<i64>,
985) -> anyhow::Result<(Modifier, usize)> {
986 debug!("find_preferred_modifier: size={size:?}, fourcc={fourcc}, modifiers={modifiers:?}");
987
988 let (buffer, modifier) = allocate_buffer(gbm, size, fourcc, &modifiers)?;
989
990 let dmabuf = buffer
991 .export()
992 .context("error exporting GBM buffer object as dmabuf")?;
993 let plane_count = dmabuf.num_planes();
994
995 // FIXME: Ideally this also needs to try binding the dmabuf for rendering.
996
997 Ok((modifier, plane_count))
998}
999
1000fn allocate_buffer(
1001 gbm: &GbmDevice<DrmDeviceFd>,
1002 size: Size<u32, Physical>,
1003 fourcc: Fourcc,
1004 modifiers: &[i64],
1005) -> anyhow::Result<(GbmBuffer, Modifier)> {
1006 let (w, h) = (size.w, size.h);
1007 let flags = GbmBufferFlags::RENDERING;
1008
1009 if modifiers.len() == 1 && Modifier::from(modifiers[0] as u64) == Modifier::Invalid {
1010 let bo = gbm
1011 .create_buffer_object::<()>(w, h, fourcc, flags)
1012 .context("error creating GBM buffer object")?;
1013
1014 let buffer = GbmBuffer::from_bo(bo, true);
1015 Ok((buffer, Modifier::Invalid))
1016 } else {
1017 let modifiers = modifiers
1018 .iter()
1019 .map(|m| Modifier::from(*m as u64))
1020 .filter(|m| *m != Modifier::Invalid);
1021
1022 let bo = gbm
1023 .create_buffer_object_with_modifiers2::<()>(w, h, fourcc, modifiers, flags)
1024 .context("error creating GBM buffer object")?;
1025
1026 let modifier = bo.modifier().unwrap();
1027 let buffer = GbmBuffer::from_bo(bo, false);
1028 Ok((buffer, modifier))
1029 }
1030}
1031
1032fn allocate_dmabuf(
1033 gbm: &GbmDevice<DrmDeviceFd>,
1034 size: Size<u32, Physical>,
1035 fourcc: Fourcc,
1036 modifier: Modifier,
1037) -> anyhow::Result<Dmabuf> {
1038 let (buffer, _modifier) = allocate_buffer(gbm, size, fourcc, &[u64::from(modifier) as i64])?;
1039 let dmabuf = buffer
1040 .export()
1041 .context("error exporting GBM buffer object as dmabuf")?;
1042 Ok(dmabuf)
1043}