niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·b0eb8ad·Ivan Molodetskikh·3 months ago·2857 commits
| 1 | use std::cell::RefCell; |
| 2 | use std::cmp::min; |
| 3 | use std::collections::HashMap; |
| 4 | use std::io::Cursor; |
| 5 | use std::iter::zip; |
| 6 | use std::os::fd::{AsFd, AsRawFd, BorrowedFd}; |
| 7 | use std::ptr::NonNull; |
| 8 | use std::rc::Rc; |
| 9 | use std::time::Duration; |
| 10 | use std::{mem, slice}; |
| 11 | |
| 12 | use anyhow::Context as _; |
| 13 | use calloop::timer::{TimeoutAction, Timer}; |
| 14 | use calloop::RegistrationToken; |
| 15 | use pipewire::context::ContextRc; |
| 16 | use pipewire::core::{CoreRc, PW_ID_CORE}; |
| 17 | use pipewire::loop_::Timeout; |
| 18 | use pipewire::main_loop::MainLoopRc; |
| 19 | use pipewire::properties::PropertiesBox; |
| 20 | use pipewire::spa::buffer::DataType; |
| 21 | use pipewire::spa::param::format::{FormatProperties, MediaSubtype, MediaType}; |
| 22 | use pipewire::spa::param::format_utils::parse_format; |
| 23 | use pipewire::spa::param::video::{VideoFormat, VideoInfoRaw}; |
| 24 | use pipewire::spa::param::ParamType; |
| 25 | use pipewire::spa::pod::deserialize::PodDeserializer; |
| 26 | use pipewire::spa::pod::serialize::PodSerializer; |
| 27 | use pipewire::spa::pod::{self, ChoiceValue, Pod, PodPropFlags, Property, PropertyFlags}; |
| 28 | use pipewire::spa::sys::*; |
| 29 | use pipewire::spa::utils::{ |
| 30 | Choice, ChoiceEnum, ChoiceFlags, Direction, Fraction, Rectangle, SpaTypes, |
| 31 | }; |
| 32 | use pipewire::spa::{self}; |
| 33 | use pipewire::stream::{Stream, StreamFlags, StreamListener, StreamRc, StreamState}; |
| 34 | use pipewire::sys::{pw_buffer, pw_check_library_version, pw_stream_queue_buffer}; |
| 35 | use smithay::backend::allocator::dmabuf::{AsDmabuf, Dmabuf}; |
| 36 | use smithay::backend::allocator::format::FormatSet; |
| 37 | use smithay::backend::allocator::gbm::{GbmBuffer, GbmBufferFlags, GbmDevice}; |
| 38 | use smithay::backend::allocator::{Format, Fourcc}; |
| 39 | use smithay::backend::drm::DrmDeviceFd; |
| 40 | use smithay::backend::renderer::damage::OutputDamageTracker; |
| 41 | use smithay::backend::renderer::element::utils::{Relocate, RelocateRenderElement}; |
| 42 | use smithay::backend::renderer::element::{Element, RenderElement}; |
| 43 | use smithay::backend::renderer::gles::GlesRenderer; |
| 44 | use smithay::backend::renderer::sync::SyncPoint; |
| 45 | use smithay::backend::renderer::ExportMem; |
| 46 | use smithay::output::{Output, OutputModeSource}; |
| 47 | use smithay::reexports::calloop::generic::Generic; |
| 48 | use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction}; |
| 49 | use smithay::reexports::gbm::Modifier; |
| 50 | use smithay::utils::{Logical, Physical, Point, Scale, Size, Transform}; |
| 51 | use zbus::object_server::SignalEmitter; |
| 52 | |
| 53 | use crate::dbus::mutter_screen_cast::{self, CursorMode}; |
| 54 | use crate::niri::{CastTarget, State}; |
| 55 | use crate::render_helpers::{ |
| 56 | clear_dmabuf, encompassing_geo, render_and_download, render_to_dmabuf, |
| 57 | }; |
| 58 | use crate::screencasting::CastRenderElement; |
| 59 | use crate::utils::{get_monotonic_time, CastSessionId, CastStreamId}; |
| 60 | |
| 61 | // Give a 0.1 ms allowance for presentation time errors. |
| 62 | const CAST_DELAY_ALLOWANCE: Duration = Duration::from_micros(100); |
| 63 | |
| 64 | const CURSOR_FORMAT: spa_video_format = SPA_VIDEO_FORMAT_BGRA; |
| 65 | const CURSOR_BPP: u32 = 4; |
| 66 | const CURSOR_WIDTH: u32 = 384; |
| 67 | const CURSOR_HEIGHT: u32 = 384; |
| 68 | const CURSOR_BITMAP_SIZE: usize = (CURSOR_WIDTH * CURSOR_HEIGHT * CURSOR_BPP) as usize; |
| 69 | const CURSOR_META_SIZE: usize = |
| 70 | mem::size_of::<spa_meta_cursor>() + mem::size_of::<spa_meta_bitmap>() + CURSOR_BITMAP_SIZE; |
| 71 | const BITMAP_META_OFFSET: usize = mem::size_of::<spa_meta_cursor>(); |
| 72 | const BITMAP_DATA_OFFSET: usize = mem::size_of::<spa_meta_bitmap>(); |
| 73 | |
| 74 | pub struct PipeWire { |
| 75 | _context: ContextRc, |
| 76 | pub core: CoreRc, |
| 77 | pub token: RegistrationToken, |
| 78 | event_loop: LoopHandle<'static, State>, |
| 79 | to_niri: calloop::channel::Sender<PwToNiri>, |
| 80 | } |
| 81 | |
| 82 | pub enum PwToNiri { |
| 83 | StopCast { session_id: CastSessionId }, |
| 84 | Redraw { stream_id: CastStreamId }, |
| 85 | FatalError, |
| 86 | } |
| 87 | |
| 88 | pub struct Cast { |
| 89 | event_loop: LoopHandle<'static, State>, |
| 90 | pub session_id: CastSessionId, |
| 91 | pub stream_id: CastStreamId, |
| 92 | // Listener is dropped before Stream to prevent a use-after-free. |
| 93 | _listener: StreamListener<()>, |
| 94 | pub stream: StreamRc, |
| 95 | pub target: CastTarget, |
| 96 | pub dynamic_target: bool, |
| 97 | formats: FormatSet, |
| 98 | offer_alpha: bool, |
| 99 | cursor_mode: CursorMode, |
| 100 | pub last_frame_time: Duration, |
| 101 | scheduled_redraw: Option<RegistrationToken>, |
| 102 | // Incremented once per successful frame, stored in buffer meta. |
| 103 | sequence_counter: u64, |
| 104 | inner: Rc<RefCell<CastInner>>, |
| 105 | } |
| 106 | |
| 107 | /// Mutable `Cast` state shared with PipeWire callbacks. |
| 108 | #[derive(Debug)] |
| 109 | struct CastInner { |
| 110 | is_active: bool, |
| 111 | node_id: Option<u32>, |
| 112 | state: CastState, |
| 113 | refresh: u32, |
| 114 | min_time_between_frames: Duration, |
| 115 | dmabufs: HashMap<i64, Dmabuf>, |
| 116 | /// Buffers dequeued from PipeWire in process of rendering. |
| 117 | /// |
| 118 | /// This is an ordered list of buffers that we started rendering to and waiting for the |
| 119 | /// rendering to complete. The completion can be checked from the `SyncPoint`s. The buffers are |
| 120 | /// stored in order from oldest to newest, and the same ordering should be preserved when |
| 121 | /// submitting completed buffers to PipeWire. |
| 122 | rendering_buffers: Vec<(NonNull<pw_buffer>, SyncPoint)>, |
| 123 | } |
| 124 | |
| 125 | #[allow(clippy::large_enum_variant)] |
| 126 | #[derive(Debug)] |
| 127 | enum CastState { |
| 128 | ResizePending { |
| 129 | pending_size: Size<u32, Physical>, |
| 130 | }, |
| 131 | ConfirmationPending { |
| 132 | size: Size<u32, Physical>, |
| 133 | alpha: bool, |
| 134 | modifier: Modifier, |
| 135 | plane_count: i32, |
| 136 | }, |
| 137 | Ready { |
| 138 | size: Size<u32, Physical>, |
| 139 | alpha: bool, |
| 140 | modifier: Modifier, |
| 141 | plane_count: i32, |
| 142 | // Lazily-initialized to keep the initialization to a single place. |
| 143 | damage_tracker: Option<OutputDamageTracker>, |
| 144 | cursor_damage_tracker: Option<OutputDamageTracker>, |
| 145 | last_cursor_location: Option<Point<i32, Physical>>, |
| 146 | }, |
| 147 | } |
| 148 | |
| 149 | #[derive(PartialEq, Eq)] |
| 150 | pub enum CastSizeChange { |
| 151 | Ready, |
| 152 | Pending, |
| 153 | } |
| 154 | |
| 155 | /// Data for drawing a cursor either as metadata or embedded. |
| 156 | /// |
| 157 | /// The cursor elements are expected to be at the start of the main elements slice. `elem_count` is |
| 158 | /// the count of the pointer elements. This way, the full slice includes both main and cursor |
| 159 | /// elements for embedded mode, and `&elements[elem_count..]` gives just the main elements for |
| 160 | /// metadata mode. |
| 161 | /// |
| 162 | /// We have weird borrowed references here in order to support both metadata and embedded cases. |
| 163 | /// The cursor damage tracker needs a slice of impl Element at (0, 0), so we pass it `relocated` |
| 164 | /// (luckily, &impl Element also impls Element). Then, if we need to embed the cursor, we use the |
| 165 | /// full elements slice which starts with non-relocated pointer elements (that we borrow from). |
| 166 | #[derive(Debug)] |
| 167 | pub struct CursorData<'a, E> { |
| 168 | /// Count of the pointer elements in the slice (index of the first non-pointer element). |
| 169 | elem_count: usize, |
| 170 | /// Cursor elements relocated to (0, 0). |
| 171 | relocated: Vec<RelocateRenderElement<&'a E>>, |
| 172 | /// Location of the cursor's hotspot in the video buffer. |
| 173 | location: Point<i32, Physical>, |
| 174 | /// Location of the cursor's hotspot on the cursor bitmap. |
| 175 | hotspot: Point<i32, Physical>, |
| 176 | /// Size of the elements' encompassing geo. |
| 177 | size: Size<i32, Physical>, |
| 178 | /// Scale the elements should be rendered at. |
| 179 | scale: Scale<f64>, |
| 180 | } |
| 181 | |
| 182 | impl<'a, E: Element> CursorData<'a, E> { |
| 183 | pub fn compute( |
| 184 | elements: &'a [E], |
| 185 | elem_count: usize, |
| 186 | location: Point<f64, Logical>, |
| 187 | scale: Scale<f64>, |
| 188 | ) -> Self { |
| 189 | let pointer_elements = &elements[..elem_count]; |
| 190 | let location = location.to_physical_precise_round(scale); |
| 191 | |
| 192 | let geo = encompassing_geo(scale, pointer_elements.iter()); |
| 193 | let relocated = Vec::from_iter(pointer_elements.iter().map(|elem| { |
| 194 | RelocateRenderElement::from_element(elem, geo.loc.upscale(-1), Relocate::Relative) |
| 195 | })); |
| 196 | |
| 197 | Self { |
| 198 | elem_count, |
| 199 | relocated, |
| 200 | location, |
| 201 | hotspot: location - geo.loc, |
| 202 | size: geo.size, |
| 203 | scale, |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | macro_rules! make_params { |
| 209 | ($params:ident, $formats:expr, $size:expr, $refresh:expr, $alpha:expr) => { |
| 210 | let mut b1 = Vec::new(); |
| 211 | let mut b2 = Vec::new(); |
| 212 | |
| 213 | let o1 = make_video_params($formats, $size, $refresh, false); |
| 214 | let pod1 = make_pod(&mut b1, o1); |
| 215 | |
| 216 | let mut p1; |
| 217 | let mut p2; |
| 218 | $params = if $alpha { |
| 219 | let o2 = make_video_params($formats, $size, $refresh, true); |
| 220 | p2 = [pod1, make_pod(&mut b2, o2)]; |
| 221 | &mut p2[..] |
| 222 | } else { |
| 223 | p1 = [pod1]; |
| 224 | &mut p1[..] |
| 225 | }; |
| 226 | }; |
| 227 | } |
| 228 | |
| 229 | impl PipeWire { |
| 230 | pub fn new( |
| 231 | event_loop: LoopHandle<'static, State>, |
| 232 | to_niri: calloop::channel::Sender<PwToNiri>, |
| 233 | ) -> anyhow::Result<Self> { |
| 234 | let main_loop = MainLoopRc::new(None).context("error creating MainLoop")?; |
| 235 | let context = ContextRc::new(&main_loop, None).context("error creating Context")?; |
| 236 | let core = context.connect_rc(None).context("error creating Core")?; |
| 237 | |
| 238 | let to_niri_ = to_niri.clone(); |
| 239 | let listener = core |
| 240 | .add_listener_local() |
| 241 | .error(move |id, seq, res, message| { |
| 242 | warn!(id, seq, res, message, "pw error"); |
| 243 | |
| 244 | // Reset PipeWire on connection errors. |
| 245 | if id == PW_ID_CORE && res == -32 { |
| 246 | if let Err(err) = to_niri_.send(PwToNiri::FatalError) { |
| 247 | warn!("error sending FatalError to niri: {err:?}"); |
| 248 | } |
| 249 | } |
| 250 | }) |
| 251 | .register(); |
| 252 | mem::forget(listener); |
| 253 | |
| 254 | struct AsFdWrapper(MainLoopRc); |
| 255 | impl AsFd for AsFdWrapper { |
| 256 | fn as_fd(&self) -> BorrowedFd<'_> { |
| 257 | self.0.loop_().fd() |
| 258 | } |
| 259 | } |
| 260 | let generic = Generic::new(AsFdWrapper(main_loop), Interest::READ, Mode::Level); |
| 261 | let token = event_loop |
| 262 | .insert_source(generic, move |_, wrapper, _| { |
| 263 | let _span = tracy_client::span!("pipewire iteration"); |
| 264 | wrapper.0.loop_().iterate(Timeout::None); |
| 265 | Ok(PostAction::Continue) |
| 266 | }) |
| 267 | .unwrap(); |
| 268 | |
| 269 | Ok(Self { |
| 270 | _context: context, |
| 271 | core, |
| 272 | token, |
| 273 | event_loop, |
| 274 | to_niri, |
| 275 | }) |
| 276 | } |
| 277 | |
| 278 | #[allow(clippy::too_many_arguments)] |
| 279 | pub fn start_cast( |
| 280 | &self, |
| 281 | gbm: GbmDevice<DrmDeviceFd>, |
| 282 | formats: FormatSet, |
| 283 | session_id: CastSessionId, |
| 284 | stream_id: CastStreamId, |
| 285 | target: CastTarget, |
| 286 | size: Size<i32, Physical>, |
| 287 | refresh: u32, |
| 288 | alpha: bool, |
| 289 | mut cursor_mode: CursorMode, |
| 290 | signal_ctx: SignalEmitter<'static>, |
| 291 | ) -> anyhow::Result<Cast> { |
| 292 | let _span = tracy_client::span!("PipeWire::start_cast"); |
| 293 | |
| 294 | let to_niri_ = self.to_niri.clone(); |
| 295 | let stop_cast = move || { |
| 296 | if let Err(err) = to_niri_.send(PwToNiri::StopCast { session_id }) { |
| 297 | warn!(%session_id, "error sending StopCast to niri: {err:?}"); |
| 298 | } |
| 299 | }; |
| 300 | let to_niri_ = self.to_niri.clone(); |
| 301 | let redraw = move || { |
| 302 | if let Err(err) = to_niri_.send(PwToNiri::Redraw { stream_id }) { |
| 303 | warn!(%stream_id, "error sending Redraw to niri: {err:?}"); |
| 304 | } |
| 305 | }; |
| 306 | let redraw_ = redraw.clone(); |
| 307 | |
| 308 | let stream = StreamRc::new( |
| 309 | self.core.clone(), |
| 310 | "niri-screen-cast-src", |
| 311 | PropertiesBox::new(), |
| 312 | ) |
| 313 | .context("error creating Stream")?; |
| 314 | |
| 315 | if cursor_mode == CursorMode::Metadata && !pw_version_supports_cursor_metadata() { |
| 316 | debug!( |
| 317 | "metadata cursor mode requested, but PipeWire is too old (need >= 1.4.8); \ |
| 318 | switching to embedded cursor" |
| 319 | ); |
| 320 | cursor_mode = CursorMode::Embedded; |
| 321 | } |
| 322 | |
| 323 | let pending_size = Size::from((size.w as u32, size.h as u32)); |
| 324 | |
| 325 | // Like in good old wayland-rs times... |
| 326 | let inner = Rc::new(RefCell::new(CastInner { |
| 327 | is_active: false, |
| 328 | node_id: None, |
| 329 | state: CastState::ResizePending { pending_size }, |
| 330 | refresh, |
| 331 | min_time_between_frames: Duration::ZERO, |
| 332 | dmabufs: HashMap::new(), |
| 333 | rendering_buffers: Vec::new(), |
| 334 | })); |
| 335 | |
| 336 | let listener = stream |
| 337 | .add_local_listener_with_user_data(()) |
| 338 | .state_changed({ |
| 339 | let inner = inner.clone(); |
| 340 | let stop_cast = stop_cast.clone(); |
| 341 | move |stream, (), old, new| { |
| 342 | let _span = debug_span!("state_changed", %stream_id).entered(); |
| 343 | debug!("{old:?} -> {new:?}"); |
| 344 | let mut inner = inner.borrow_mut(); |
| 345 | |
| 346 | match new { |
| 347 | StreamState::Paused => { |
| 348 | if inner.node_id.is_none() { |
| 349 | let id = stream.node_id(); |
| 350 | inner.node_id = Some(id); |
| 351 | debug!("sending signal with {id}"); |
| 352 | |
| 353 | let _span = tracy_client::span!("sending PipeWireStreamAdded"); |
| 354 | async_io::block_on(async { |
| 355 | let res = mutter_screen_cast::Stream::pipe_wire_stream_added( |
| 356 | &signal_ctx, |
| 357 | id, |
| 358 | ) |
| 359 | .await; |
| 360 | |
| 361 | if let Err(err) = res { |
| 362 | warn!("error sending PipeWireStreamAdded: {err:?}"); |
| 363 | stop_cast(); |
| 364 | } |
| 365 | }); |
| 366 | } |
| 367 | |
| 368 | inner.is_active = false; |
| 369 | } |
| 370 | StreamState::Error(_) => { |
| 371 | if inner.is_active { |
| 372 | inner.is_active = false; |
| 373 | stop_cast(); |
| 374 | } |
| 375 | } |
| 376 | StreamState::Unconnected => (), |
| 377 | StreamState::Connecting => (), |
| 378 | StreamState::Streaming => { |
| 379 | inner.is_active = true; |
| 380 | redraw(); |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | }) |
| 385 | .param_changed({ |
| 386 | let inner = inner.clone(); |
| 387 | let stop_cast = stop_cast.clone(); |
| 388 | let gbm = gbm.clone(); |
| 389 | let formats = formats.clone(); |
| 390 | move |stream, (), id, pod| { |
| 391 | let id = ParamType::from_raw(id); |
| 392 | trace!(%stream_id, ?id, "param_changed"); |
| 393 | let mut inner = inner.borrow_mut(); |
| 394 | let inner = &mut *inner; |
| 395 | |
| 396 | if id != ParamType::Format { |
| 397 | return; |
| 398 | } |
| 399 | |
| 400 | let _span = debug_span!("param_changed", %stream_id).entered(); |
| 401 | |
| 402 | let Some(pod) = pod else { return }; |
| 403 | |
| 404 | let (m_type, m_subtype) = match parse_format(pod) { |
| 405 | Ok(x) => x, |
| 406 | Err(err) => { |
| 407 | warn!("error parsing format: {err:?}"); |
| 408 | return; |
| 409 | } |
| 410 | }; |
| 411 | |
| 412 | if m_type != MediaType::Video || m_subtype != MediaSubtype::Raw { |
| 413 | return; |
| 414 | } |
| 415 | |
| 416 | let mut format = VideoInfoRaw::new(); |
| 417 | format.parse(pod).unwrap(); |
| 418 | debug!("got format = {format:?}"); |
| 419 | |
| 420 | let format_size = Size::from((format.size().width, format.size().height)); |
| 421 | |
| 422 | let state = &mut inner.state; |
| 423 | if format_size != state.expected_format_size() { |
| 424 | if !matches!(&*state, CastState::ResizePending { .. }) { |
| 425 | warn!("wrong size, but we're not resizing"); |
| 426 | stop_cast(); |
| 427 | return; |
| 428 | } |
| 429 | |
| 430 | debug!("wrong size, waiting"); |
| 431 | return; |
| 432 | } |
| 433 | |
| 434 | let format_has_alpha = format.format() == VideoFormat::BGRA; |
| 435 | let fourcc = if format_has_alpha { |
| 436 | Fourcc::Argb8888 |
| 437 | } else { |
| 438 | Fourcc::Xrgb8888 |
| 439 | }; |
| 440 | |
| 441 | let max_frame_rate = format.max_framerate(); |
| 442 | let min_frame_time = Duration::from_micros( |
| 443 | 1_000_000 * u64::from(max_frame_rate.denom) / u64::from(max_frame_rate.num), |
| 444 | ); |
| 445 | inner.min_time_between_frames = min_frame_time; |
| 446 | |
| 447 | let object = pod.as_object().unwrap(); |
| 448 | let Some(prop_modifier) = |
| 449 | object.find_prop(spa::utils::Id(FormatProperties::VideoModifier.0)) |
| 450 | else { |
| 451 | warn!("modifier prop missing"); |
| 452 | stop_cast(); |
| 453 | return; |
| 454 | }; |
| 455 | |
| 456 | if prop_modifier.flags().contains(PodPropFlags::DONT_FIXATE) { |
| 457 | debug!("fixating the modifier"); |
| 458 | |
| 459 | let pod_modifier = prop_modifier.value(); |
| 460 | let Ok((_, modifiers)) = PodDeserializer::deserialize_from::<Choice<i64>>( |
| 461 | pod_modifier.as_bytes(), |
| 462 | ) else { |
| 463 | warn!("wrong modifier property type"); |
| 464 | stop_cast(); |
| 465 | return; |
| 466 | }; |
| 467 | |
| 468 | let ChoiceEnum::Enum { alternatives, .. } = modifiers.1 else { |
| 469 | warn!("wrong modifier choice type"); |
| 470 | stop_cast(); |
| 471 | return; |
| 472 | }; |
| 473 | |
| 474 | let (modifier, plane_count) = match find_preferred_modifier( |
| 475 | &gbm, |
| 476 | format_size, |
| 477 | fourcc, |
| 478 | alternatives, |
| 479 | ) { |
| 480 | Ok(x) => x, |
| 481 | Err(err) => { |
| 482 | warn!("couldn't find preferred modifier: {err:?}"); |
| 483 | stop_cast(); |
| 484 | return; |
| 485 | } |
| 486 | }; |
| 487 | |
| 488 | debug!( |
| 489 | "allocation successful \ |
| 490 | (modifier={modifier:?}, plane_count={plane_count}), \ |
| 491 | moving to confirmation pending" |
| 492 | ); |
| 493 | |
| 494 | *state = CastState::ConfirmationPending { |
| 495 | size: format_size, |
| 496 | alpha: format_has_alpha, |
| 497 | modifier, |
| 498 | plane_count: plane_count as i32, |
| 499 | }; |
| 500 | |
| 501 | let fixated_format = FormatSet::from_iter([Format { |
| 502 | code: fourcc, |
| 503 | modifier, |
| 504 | }]); |
| 505 | |
| 506 | let mut b1 = Vec::new(); |
| 507 | let mut b2 = Vec::new(); |
| 508 | |
| 509 | let o1 = make_video_params( |
| 510 | &fixated_format, |
| 511 | format_size, |
| 512 | inner.refresh, |
| 513 | format_has_alpha, |
| 514 | ); |
| 515 | let pod1 = make_pod(&mut b1, o1); |
| 516 | |
| 517 | let o2 = make_video_params( |
| 518 | &formats, |
| 519 | format_size, |
| 520 | inner.refresh, |
| 521 | format_has_alpha, |
| 522 | ); |
| 523 | let mut params = [pod1, make_pod(&mut b2, o2)]; |
| 524 | |
| 525 | if let Err(err) = stream.update_params(&mut params) { |
| 526 | warn!("error updating stream params: {err:?}"); |
| 527 | stop_cast(); |
| 528 | } |
| 529 | |
| 530 | return; |
| 531 | } |
| 532 | |
| 533 | // Verify that alpha and modifier didn't change. |
| 534 | let plane_count = match &*state { |
| 535 | CastState::ConfirmationPending { |
| 536 | size, |
| 537 | alpha, |
| 538 | modifier, |
| 539 | plane_count, |
| 540 | } |
| 541 | | CastState::Ready { |
| 542 | size, |
| 543 | alpha, |
| 544 | modifier, |
| 545 | plane_count, |
| 546 | .. |
| 547 | } if *alpha == format_has_alpha |
| 548 | && *modifier == Modifier::from(format.modifier()) => |
| 549 | { |
| 550 | let size = *size; |
| 551 | let alpha = *alpha; |
| 552 | let modifier = *modifier; |
| 553 | let plane_count = *plane_count; |
| 554 | |
| 555 | let (damage_tracker, cursor_damage_tracker) = |
| 556 | if let CastState::Ready { |
| 557 | damage_tracker, |
| 558 | cursor_damage_tracker, |
| 559 | .. |
| 560 | } = &mut *state |
| 561 | { |
| 562 | (damage_tracker.take(), cursor_damage_tracker.take()) |
| 563 | } else { |
| 564 | (None, None) |
| 565 | }; |
| 566 | |
| 567 | debug!("moving to ready state"); |
| 568 | |
| 569 | *state = CastState::Ready { |
| 570 | size, |
| 571 | alpha, |
| 572 | modifier, |
| 573 | plane_count, |
| 574 | damage_tracker, |
| 575 | cursor_damage_tracker, |
| 576 | last_cursor_location: None, |
| 577 | }; |
| 578 | |
| 579 | plane_count |
| 580 | } |
| 581 | _ => { |
| 582 | // We're negotiating a single modifier, or alpha or modifier changed, |
| 583 | // so we need to do a test allocation. |
| 584 | let (modifier, plane_count) = match find_preferred_modifier( |
| 585 | &gbm, |
| 586 | format_size, |
| 587 | fourcc, |
| 588 | vec![format.modifier() as i64], |
| 589 | ) { |
| 590 | Ok(x) => x, |
| 591 | Err(err) => { |
| 592 | warn!("test allocation failed: {err:?}"); |
| 593 | stop_cast(); |
| 594 | return; |
| 595 | } |
| 596 | }; |
| 597 | |
| 598 | debug!( |
| 599 | "allocation successful \ |
| 600 | (modifier={modifier:?}, plane_count={plane_count}), \ |
| 601 | moving to ready" |
| 602 | ); |
| 603 | |
| 604 | *state = CastState::Ready { |
| 605 | size: format_size, |
| 606 | alpha: format_has_alpha, |
| 607 | modifier, |
| 608 | plane_count: plane_count as i32, |
| 609 | damage_tracker: None, |
| 610 | cursor_damage_tracker: None, |
| 611 | last_cursor_location: None, |
| 612 | }; |
| 613 | |
| 614 | plane_count as i32 |
| 615 | } |
| 616 | }; |
| 617 | |
| 618 | // const BPP: u32 = 4; |
| 619 | // let stride = format.size().width * BPP; |
| 620 | // let size = stride * format.size().height; |
| 621 | |
| 622 | let o1 = pod::object!( |
| 623 | SpaTypes::ObjectParamBuffers, |
| 624 | ParamType::Buffers, |
| 625 | Property::new( |
| 626 | SPA_PARAM_BUFFERS_buffers, |
| 627 | pod::Value::Choice(ChoiceValue::Int(Choice( |
| 628 | ChoiceFlags::empty(), |
| 629 | ChoiceEnum::Range { |
| 630 | default: 8, |
| 631 | min: 2, |
| 632 | max: 16 |
| 633 | } |
| 634 | ))), |
| 635 | ), |
| 636 | Property::new(SPA_PARAM_BUFFERS_blocks, pod::Value::Int(plane_count)), |
| 637 | Property::new( |
| 638 | SPA_PARAM_BUFFERS_dataType, |
| 639 | pod::Value::Choice(ChoiceValue::Int(Choice( |
| 640 | ChoiceFlags::empty(), |
| 641 | ChoiceEnum::Flags { |
| 642 | default: 1 << DataType::DmaBuf.as_raw(), |
| 643 | flags: vec![1 << DataType::DmaBuf.as_raw()], |
| 644 | }, |
| 645 | ))), |
| 646 | ), |
| 647 | ); |
| 648 | |
| 649 | let o2 = pod::object!( |
| 650 | SpaTypes::ObjectParamMeta, |
| 651 | ParamType::Meta, |
| 652 | Property::new( |
| 653 | SPA_PARAM_META_type, |
| 654 | pod::Value::Id(spa::utils::Id(SPA_META_Header)) |
| 655 | ), |
| 656 | Property::new( |
| 657 | SPA_PARAM_META_size, |
| 658 | pod::Value::Int(size_of::<spa_meta_header>() as i32) |
| 659 | ), |
| 660 | ); |
| 661 | let mut b1 = vec![]; |
| 662 | let mut b2 = vec![]; |
| 663 | let mut params = vec![make_pod(&mut b1, o1), make_pod(&mut b2, o2)]; |
| 664 | |
| 665 | let mut b_cursor = vec![]; |
| 666 | if cursor_mode == CursorMode::Metadata { |
| 667 | let o_cursor = pod::object!( |
| 668 | SpaTypes::ObjectParamMeta, |
| 669 | ParamType::Meta, |
| 670 | Property::new( |
| 671 | SPA_PARAM_META_type, |
| 672 | pod::Value::Id(spa::utils::Id(SPA_META_Cursor)) |
| 673 | ), |
| 674 | Property::new( |
| 675 | SPA_PARAM_META_size, |
| 676 | pod::Value::Int(CURSOR_META_SIZE as i32) |
| 677 | ), |
| 678 | ); |
| 679 | params.push(make_pod(&mut b_cursor, o_cursor)); |
| 680 | } |
| 681 | |
| 682 | if let Err(err) = stream.update_params(&mut params) { |
| 683 | warn!("error updating stream params: {err:?}"); |
| 684 | stop_cast(); |
| 685 | } |
| 686 | } |
| 687 | }) |
| 688 | .add_buffer({ |
| 689 | let inner = inner.clone(); |
| 690 | let stop_cast = stop_cast.clone(); |
| 691 | move |stream, (), buffer| { |
| 692 | let _span = debug_span!("add_buffer", %stream_id).entered(); |
| 693 | let mut inner = inner.borrow_mut(); |
| 694 | |
| 695 | let (size, alpha, modifier) = if let CastState::Ready { |
| 696 | size, |
| 697 | alpha, |
| 698 | modifier, |
| 699 | .. |
| 700 | } = &inner.state |
| 701 | { |
| 702 | (*size, *alpha, *modifier) |
| 703 | } else { |
| 704 | trace!("add_buffer, but not ready yet"); |
| 705 | return; |
| 706 | }; |
| 707 | |
| 708 | trace!("size={size:?}, alpha={alpha}, modifier={modifier:?}"); |
| 709 | |
| 710 | unsafe { |
| 711 | let spa_buffer = (*buffer).buffer; |
| 712 | |
| 713 | let fourcc = if alpha { |
| 714 | Fourcc::Argb8888 |
| 715 | } else { |
| 716 | Fourcc::Xrgb8888 |
| 717 | }; |
| 718 | |
| 719 | let dmabuf = match allocate_dmabuf(&gbm, size, fourcc, modifier) { |
| 720 | Ok(dmabuf) => dmabuf, |
| 721 | Err(err) => { |
| 722 | warn!("error allocating dmabuf: {err:?}"); |
| 723 | stop_cast(); |
| 724 | return; |
| 725 | } |
| 726 | }; |
| 727 | |
| 728 | let plane_count = dmabuf.num_planes(); |
| 729 | assert_eq!((*spa_buffer).n_datas as usize, plane_count); |
| 730 | |
| 731 | for (i, (fd, (stride, offset))) in |
| 732 | zip(dmabuf.handles(), zip(dmabuf.strides(), dmabuf.offsets())) |
| 733 | .enumerate() |
| 734 | { |
| 735 | let spa_data = (*spa_buffer).datas.add(i); |
| 736 | assert!((*spa_data).type_ & (1 << DataType::DmaBuf.as_raw()) > 0); |
| 737 | |
| 738 | (*spa_data).type_ = DataType::DmaBuf.as_raw(); |
| 739 | |
| 740 | // With DMA-BUFs, consumers should ignore the maxsize field, and |
| 741 | // producers are allowed to set it to 0. |
| 742 | // |
| 743 | // https://docs.pipewire.org/page_dma_buf.html |
| 744 | (*spa_data).maxsize = 1; |
| 745 | (*spa_data).fd = fd.as_raw_fd() as i64; |
| 746 | (*spa_data).flags = SPA_DATA_FLAG_READWRITE; |
| 747 | |
| 748 | let chunk = (*spa_data).chunk; |
| 749 | (*chunk).stride = stride as i32; |
| 750 | (*chunk).offset = offset; |
| 751 | |
| 752 | trace!( |
| 753 | "pw buffer plane: fd={}, stride={stride}, offset={offset}", |
| 754 | (*spa_data).fd |
| 755 | ); |
| 756 | } |
| 757 | |
| 758 | let fd = (*(*spa_buffer).datas).fd; |
| 759 | assert!(inner.dmabufs.insert(fd, dmabuf).is_none()); |
| 760 | } |
| 761 | |
| 762 | // During size re-negotiation, the stream sometimes just keeps running, in |
| 763 | // which case we may need to force a redraw once we got a newly sized buffer. |
| 764 | if inner.dmabufs.len() == 1 && stream.state() == StreamState::Streaming { |
| 765 | redraw_(); |
| 766 | } |
| 767 | } |
| 768 | }) |
| 769 | .remove_buffer({ |
| 770 | let inner = inner.clone(); |
| 771 | move |_stream, (), buffer| { |
| 772 | trace!(%stream_id, "remove_buffer"); |
| 773 | let mut inner = inner.borrow_mut(); |
| 774 | |
| 775 | inner |
| 776 | .rendering_buffers |
| 777 | .retain(|(buf, _)| buf.as_ptr() != buffer); |
| 778 | |
| 779 | unsafe { |
| 780 | let spa_buffer = (*buffer).buffer; |
| 781 | let spa_data = (*spa_buffer).datas; |
| 782 | assert!((*spa_buffer).n_datas > 0); |
| 783 | |
| 784 | let fd = (*spa_data).fd; |
| 785 | inner.dmabufs.remove(&fd); |
| 786 | } |
| 787 | } |
| 788 | }) |
| 789 | .register() |
| 790 | .unwrap(); |
| 791 | |
| 792 | trace!( |
| 793 | %stream_id, |
| 794 | "starting pw stream with size={pending_size:?}, refresh={refresh:?}" |
| 795 | ); |
| 796 | |
| 797 | let params; |
| 798 | make_params!(params, &formats, pending_size, refresh, alpha); |
| 799 | stream |
| 800 | .connect( |
| 801 | Direction::Output, |
| 802 | None, |
| 803 | StreamFlags::DRIVER | StreamFlags::ALLOC_BUFFERS, |
| 804 | params, |
| 805 | ) |
| 806 | .context("error connecting stream")?; |
| 807 | |
| 808 | let cast = Cast { |
| 809 | event_loop: self.event_loop.clone(), |
| 810 | session_id, |
| 811 | stream_id, |
| 812 | stream, |
| 813 | _listener: listener, |
| 814 | target, |
| 815 | dynamic_target: false, |
| 816 | formats, |
| 817 | offer_alpha: alpha, |
| 818 | cursor_mode, |
| 819 | last_frame_time: Duration::ZERO, |
| 820 | scheduled_redraw: None, |
| 821 | sequence_counter: 0, |
| 822 | inner, |
| 823 | }; |
| 824 | Ok(cast) |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | impl Cast { |
| 829 | pub fn is_active(&self) -> bool { |
| 830 | self.inner.borrow().is_active |
| 831 | } |
| 832 | |
| 833 | pub fn node_id(&self) -> Option<u32> { |
| 834 | self.inner.borrow().node_id |
| 835 | } |
| 836 | |
| 837 | pub fn ensure_size(&self, size: Size<i32, Physical>) -> anyhow::Result<CastSizeChange> { |
| 838 | let mut inner = self.inner.borrow_mut(); |
| 839 | |
| 840 | let new_size = Size::from((size.w as u32, size.h as u32)); |
| 841 | |
| 842 | let state = &mut inner.state; |
| 843 | if matches!(state, CastState::Ready { size, .. } if *size == new_size) { |
| 844 | return Ok(CastSizeChange::Ready); |
| 845 | } |
| 846 | |
| 847 | if state.pending_size() == Some(new_size) { |
| 848 | debug!("stream size still hasn't changed, skipping frame"); |
| 849 | return Ok(CastSizeChange::Pending); |
| 850 | } |
| 851 | |
| 852 | let _span = tracy_client::span!("Cast::ensure_size"); |
| 853 | debug!("cast size changed, updating stream size"); |
| 854 | |
| 855 | *state = CastState::ResizePending { |
| 856 | pending_size: new_size, |
| 857 | }; |
| 858 | |
| 859 | let params; |
| 860 | make_params!( |
| 861 | params, |
| 862 | &self.formats, |
| 863 | new_size, |
| 864 | inner.refresh, |
| 865 | self.offer_alpha |
| 866 | ); |
| 867 | self.stream |
| 868 | .update_params(params) |
| 869 | .context("error updating stream params")?; |
| 870 | |
| 871 | Ok(CastSizeChange::Pending) |
| 872 | } |
| 873 | |
| 874 | pub fn set_refresh(&mut self, refresh: u32) -> anyhow::Result<()> { |
| 875 | let mut inner = self.inner.borrow_mut(); |
| 876 | |
| 877 | if inner.refresh == refresh { |
| 878 | return Ok(()); |
| 879 | } |
| 880 | |
| 881 | let _span = tracy_client::span!("Cast::set_refresh"); |
| 882 | debug!("cast FPS changed, updating stream FPS"); |
| 883 | inner.refresh = refresh; |
| 884 | |
| 885 | let size = inner.state.expected_format_size(); |
| 886 | let params; |
| 887 | make_params!(params, &self.formats, size, refresh, self.offer_alpha); |
| 888 | self.stream |
| 889 | .update_params(params) |
| 890 | .context("error updating stream params")?; |
| 891 | |
| 892 | Ok(()) |
| 893 | } |
| 894 | |
| 895 | fn compute_extra_delay(&self, target_frame_time: Duration) -> Duration { |
| 896 | let inner = self.inner.borrow(); |
| 897 | |
| 898 | let last = self.last_frame_time; |
| 899 | let min = inner.min_time_between_frames; |
| 900 | |
| 901 | if last.is_zero() { |
| 902 | trace!(?target_frame_time, ?last, "last is zero, recording"); |
| 903 | return Duration::ZERO; |
| 904 | } |
| 905 | |
| 906 | if target_frame_time < last { |
| 907 | // Record frame with a warning; in case it was an overflow this will fix it. |
| 908 | warn!( |
| 909 | ?target_frame_time, |
| 910 | ?last, |
| 911 | "target frame time is below last, did it overflow or did we mispredict?" |
| 912 | ); |
| 913 | return Duration::ZERO; |
| 914 | } |
| 915 | |
| 916 | let diff = target_frame_time - last; |
| 917 | if diff < min { |
| 918 | let delay = min - diff; |
| 919 | trace!( |
| 920 | ?target_frame_time, |
| 921 | ?last, |
| 922 | "frame is too soon: min={min:?}, delay={:?}", |
| 923 | delay |
| 924 | ); |
| 925 | return delay; |
| 926 | } else { |
| 927 | trace!("overshoot={:?}", diff - min); |
| 928 | } |
| 929 | |
| 930 | Duration::ZERO |
| 931 | } |
| 932 | |
| 933 | fn schedule_redraw(&mut self, output: Output, target_time: Duration) { |
| 934 | if self.scheduled_redraw.is_some() { |
| 935 | return; |
| 936 | } |
| 937 | |
| 938 | let now = get_monotonic_time(); |
| 939 | let duration = target_time.saturating_sub(now); |
| 940 | let timer = Timer::from_duration(duration); |
| 941 | let token = self |
| 942 | .event_loop |
| 943 | .insert_source(timer, move |_, _, state| { |
| 944 | // Guard against output disconnecting before the timer has a chance to run. |
| 945 | if state.niri.output_state.contains_key(&output) { |
| 946 | state.niri.queue_redraw(&output); |
| 947 | } |
| 948 | |
| 949 | TimeoutAction::Drop |
| 950 | }) |
| 951 | .unwrap(); |
| 952 | self.scheduled_redraw = Some(token); |
| 953 | } |
| 954 | |
| 955 | fn remove_scheduled_redraw(&mut self) { |
| 956 | if let Some(token) = self.scheduled_redraw.take() { |
| 957 | self.event_loop.remove(token); |
| 958 | } |
| 959 | } |
| 960 | |
| 961 | /// Checks whether this frame should be skipped because it's too soon. |
| 962 | /// |
| 963 | /// If the frame should be skipped, schedules a redraw and returns `true`. Otherwise, removes a |
| 964 | /// scheduled redraw, if any, and returns `false`. |
| 965 | /// |
| 966 | /// When this method returns `false`, the calling code is assumed to follow up with |
| 967 | /// [`Cast::dequeue_buffer_and_render()`]. |
| 968 | pub fn check_time_and_schedule( |
| 969 | &mut self, |
| 970 | output: &Output, |
| 971 | target_frame_time: Duration, |
| 972 | ) -> bool { |
| 973 | let delay = self.compute_extra_delay(target_frame_time); |
| 974 | if delay >= CAST_DELAY_ALLOWANCE { |
| 975 | trace!("delay >= allowance, scheduling redraw"); |
| 976 | self.schedule_redraw(output.clone(), target_frame_time + delay); |
| 977 | true |
| 978 | } else { |
| 979 | self.remove_scheduled_redraw(); |
| 980 | false |
| 981 | } |
| 982 | } |
| 983 | |
| 984 | fn dequeue_available_buffer(&mut self) -> Option<NonNull<pw_buffer>> { |
| 985 | unsafe { NonNull::new(self.stream.dequeue_raw_buffer()) } |
| 986 | } |
| 987 | |
| 988 | fn queue_completed_buffers(&mut self) { |
| 989 | let mut inner = self.inner.borrow_mut(); |
| 990 | |
| 991 | // We want to queue buffers in order, so find the first still-rendering buffer, and queue |
| 992 | // everything up to that. Even if there are completed buffers past the first |
| 993 | // still-rendering buffer, we do not want to queue them, since that would send frames out |
| 994 | // of order. |
| 995 | let first_in_progress_idx = inner |
| 996 | .rendering_buffers |
| 997 | .iter() |
| 998 | .position(|(_, sync)| !sync.is_reached()) |
| 999 | .unwrap_or(inner.rendering_buffers.len()); |
| 1000 | |
| 1001 | for (buffer, _) in inner.rendering_buffers.drain(..first_in_progress_idx) { |
| 1002 | trace!("queueing completed buffer"); |
| 1003 | unsafe { |
| 1004 | pw_stream_queue_buffer(self.stream.as_raw_ptr(), buffer.as_ptr()); |
| 1005 | } |
| 1006 | } |
| 1007 | } |
| 1008 | |
| 1009 | unsafe fn queue_after_sync(&mut self, pw_buffer: NonNull<pw_buffer>, sync_point: SyncPoint) { |
| 1010 | let _span = tracy_client::span!("Cast::queue_after_sync"); |
| 1011 | |
| 1012 | let mut inner = self.inner.borrow_mut(); |
| 1013 | |
| 1014 | let mut sync_point = sync_point; |
| 1015 | let sync_fd = match sync_point.export() { |
| 1016 | Some(sync_fd) => Some(sync_fd), |
| 1017 | None => { |
| 1018 | // There are two main ways this can happen. First is that the SyncPoint is |
| 1019 | // pre-signalled, then the buffer is already ready and no waiting is needed. Second |
| 1020 | // is that the SyncPoint is potentially still not signalled, but exporting a fence |
| 1021 | // fd had failed. In this case, there's not much we can do (perhaps do a blocking |
| 1022 | // wait for the SyncPoint, which itself might fail). |
| 1023 | // |
| 1024 | // So let's hope for the best and mark the buffer as submittable. We do not reuse |
| 1025 | // the original SyncPoint because if we do hit the second case (when it's not |
| 1026 | // signalled), then without a sync fd we cannot schedule a queue upon its |
| 1027 | // completion, effectively going stuck. It's better to queue an incomplete buffer |
| 1028 | // than getting stuck. |
| 1029 | sync_point = SyncPoint::signaled(); |
| 1030 | None |
| 1031 | } |
| 1032 | }; |
| 1033 | |
| 1034 | inner.rendering_buffers.push((pw_buffer, sync_point)); |
| 1035 | drop(inner); |
| 1036 | |
| 1037 | match sync_fd { |
| 1038 | None => { |
| 1039 | trace!("sync_fd is None, queueing completed buffers"); |
| 1040 | // In case this is the only buffer in the list, we will queue it right away. |
| 1041 | self.queue_completed_buffers(); |
| 1042 | } |
| 1043 | Some(sync_fd) => { |
| 1044 | trace!("scheduling buffer to queue"); |
| 1045 | let stream_id = self.stream_id; |
| 1046 | let source = Generic::new(sync_fd, Interest::READ, Mode::OneShot); |
| 1047 | self.event_loop |
| 1048 | .insert_source(source, move |_, _, state| { |
| 1049 | for cast in &mut state.niri.casting.casts { |
| 1050 | if cast.stream_id == stream_id { |
| 1051 | cast.queue_completed_buffers(); |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | Ok(PostAction::Remove) |
| 1056 | }) |
| 1057 | .unwrap(); |
| 1058 | } |
| 1059 | } |
| 1060 | } |
| 1061 | |
| 1062 | #[allow(clippy::too_many_arguments)] |
| 1063 | pub fn dequeue_buffer_and_render( |
| 1064 | &mut self, |
| 1065 | renderer: &mut GlesRenderer, |
| 1066 | mut elements: &[CastRenderElement<GlesRenderer>], |
| 1067 | cursor_data: &CursorData<CastRenderElement<GlesRenderer>>, |
| 1068 | size: Size<i32, Physical>, |
| 1069 | scale: Scale<f64>, |
| 1070 | ) -> bool { |
| 1071 | let mut inner = self.inner.borrow_mut(); |
| 1072 | |
| 1073 | let CastState::Ready { |
| 1074 | damage_tracker, |
| 1075 | cursor_damage_tracker, |
| 1076 | last_cursor_location, |
| 1077 | .. |
| 1078 | } = &mut inner.state |
| 1079 | else { |
| 1080 | error!("cast must be in Ready state to render"); |
| 1081 | return false; |
| 1082 | }; |
| 1083 | let damage_tracker = damage_tracker |
| 1084 | .get_or_insert_with(|| OutputDamageTracker::new(size, scale, Transform::Normal)); |
| 1085 | let cursor_damage_tracker = cursor_damage_tracker.get_or_insert_with(|| { |
| 1086 | OutputDamageTracker::new( |
| 1087 | Size::from((CURSOR_WIDTH as _, CURSOR_HEIGHT as _)), |
| 1088 | scale, |
| 1089 | Transform::Normal, |
| 1090 | ) |
| 1091 | }); |
| 1092 | |
| 1093 | // Size change will drop the damage tracker, but scale change won't, so check it here. |
| 1094 | let OutputModeSource::Static { scale: t_scale, .. } = damage_tracker.mode() else { |
| 1095 | unreachable!(); |
| 1096 | }; |
| 1097 | if *t_scale != scale { |
| 1098 | *damage_tracker = OutputDamageTracker::new(size, scale, Transform::Normal); |
| 1099 | *cursor_damage_tracker = OutputDamageTracker::new( |
| 1100 | Size::from((CURSOR_WIDTH as _, CURSOR_HEIGHT as _)), |
| 1101 | scale, |
| 1102 | Transform::Normal, |
| 1103 | ); |
| 1104 | } |
| 1105 | |
| 1106 | let mut has_cursor_update = false; |
| 1107 | let mut redraw_cursor = false; |
| 1108 | |
| 1109 | // For embedded cursor, pass the full slice (cursor + main) to the damage tracker. |
| 1110 | // For metadata or hidden cursor, pass only the main elements. |
| 1111 | if self.cursor_mode == CursorMode::Metadata || self.cursor_mode == CursorMode::Hidden { |
| 1112 | elements = &elements[cursor_data.elem_count..]; |
| 1113 | } |
| 1114 | let (damage, states) = damage_tracker.damage_output(1, elements).unwrap(); |
| 1115 | |
| 1116 | if self.cursor_mode == CursorMode::Metadata { |
| 1117 | let (damage, _states) = cursor_damage_tracker |
| 1118 | .damage_output(1, &cursor_data.relocated) |
| 1119 | .unwrap(); |
| 1120 | redraw_cursor = damage.is_some(); |
| 1121 | has_cursor_update = |
| 1122 | redraw_cursor || *last_cursor_location != Some(cursor_data.location); |
| 1123 | } |
| 1124 | |
| 1125 | if damage.is_none() && !has_cursor_update { |
| 1126 | trace!("no damage, skipping frame"); |
| 1127 | return false; |
| 1128 | } |
| 1129 | *last_cursor_location = Some(cursor_data.location); |
| 1130 | drop(inner); |
| 1131 | |
| 1132 | let Some(pw_buffer) = self.dequeue_available_buffer() else { |
| 1133 | warn!("no available buffer in pw stream, skipping frame"); |
| 1134 | return false; |
| 1135 | }; |
| 1136 | let buffer = pw_buffer.as_ptr(); |
| 1137 | |
| 1138 | let mut inner = self.inner.borrow_mut(); |
| 1139 | let inner_ = &mut *inner; |
| 1140 | let CastState::Ready { damage_tracker, .. } = &mut inner_.state else { |
| 1141 | unreachable!() |
| 1142 | }; |
| 1143 | let damage_tracker = damage_tracker.as_mut().unwrap(); |
| 1144 | |
| 1145 | unsafe { |
| 1146 | let spa_buffer = (*buffer).buffer; |
| 1147 | |
| 1148 | if self.cursor_mode == CursorMode::Metadata { |
| 1149 | add_cursor_metadata(renderer, spa_buffer, cursor_data, redraw_cursor); |
| 1150 | } |
| 1151 | |
| 1152 | // FIXME: would be good to skip rendering the full frame if only the pointer changed. |
| 1153 | // Unfortunately, I think the OBS PipeWire code needs to be updated first to cleanly |
| 1154 | // allow for that codepath. |
| 1155 | let fd = (*(*spa_buffer).datas).fd; |
| 1156 | let dmabuf = inner_.dmabufs[&fd].clone(); |
| 1157 | |
| 1158 | let res = render_to_dmabuf(renderer, damage_tracker, dmabuf, elements, states); |
| 1159 | drop(inner); |
| 1160 | |
| 1161 | match res { |
| 1162 | Ok(sync_point) => { |
| 1163 | mark_buffer_as_good(pw_buffer, &mut self.sequence_counter); |
| 1164 | trace!("queueing buffer with seq={}", self.sequence_counter); |
| 1165 | self.queue_after_sync(pw_buffer, sync_point); |
| 1166 | true |
| 1167 | } |
| 1168 | Err(err) => { |
| 1169 | warn!("error rendering to dmabuf: {err:?}"); |
| 1170 | return_unused_buffer(&self.stream, pw_buffer); |
| 1171 | false |
| 1172 | } |
| 1173 | } |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | pub fn dequeue_buffer_and_clear(&mut self, renderer: &mut GlesRenderer) -> bool { |
| 1178 | let mut inner = self.inner.borrow_mut(); |
| 1179 | |
| 1180 | // Clear out the damage tracker if we're in Ready state. |
| 1181 | if let CastState::Ready { |
| 1182 | damage_tracker, |
| 1183 | cursor_damage_tracker, |
| 1184 | .. |
| 1185 | } = &mut inner.state |
| 1186 | { |
| 1187 | *damage_tracker = None; |
| 1188 | *cursor_damage_tracker = None; |
| 1189 | }; |
| 1190 | drop(inner); |
| 1191 | |
| 1192 | let Some(pw_buffer) = self.dequeue_available_buffer() else { |
| 1193 | warn!("no available buffer in pw stream, skipping frame"); |
| 1194 | return false; |
| 1195 | }; |
| 1196 | let buffer = pw_buffer.as_ptr(); |
| 1197 | |
| 1198 | unsafe { |
| 1199 | let spa_buffer = (*buffer).buffer; |
| 1200 | |
| 1201 | if self.cursor_mode == CursorMode::Metadata { |
| 1202 | add_invisible_cursor(spa_buffer); |
| 1203 | } |
| 1204 | |
| 1205 | let fd = (*(*spa_buffer).datas).fd; |
| 1206 | let dmabuf = self.inner.borrow().dmabufs[&fd].clone(); |
| 1207 | |
| 1208 | match clear_dmabuf(renderer, dmabuf) { |
| 1209 | Ok(sync_point) => { |
| 1210 | mark_buffer_as_good(pw_buffer, &mut self.sequence_counter); |
| 1211 | trace!("queueing clear buffer with seq={}", self.sequence_counter); |
| 1212 | self.queue_after_sync(pw_buffer, sync_point); |
| 1213 | true |
| 1214 | } |
| 1215 | Err(err) => { |
| 1216 | warn!("error clearing dmabuf: {err:?}"); |
| 1217 | return_unused_buffer(&self.stream, pw_buffer); |
| 1218 | false |
| 1219 | } |
| 1220 | } |
| 1221 | } |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | impl CastState { |
| 1226 | fn pending_size(&self) -> Option<Size<u32, Physical>> { |
| 1227 | match self { |
| 1228 | CastState::ResizePending { pending_size } => Some(*pending_size), |
| 1229 | CastState::ConfirmationPending { size, .. } => Some(*size), |
| 1230 | CastState::Ready { .. } => None, |
| 1231 | } |
| 1232 | } |
| 1233 | |
| 1234 | fn expected_format_size(&self) -> Size<u32, Physical> { |
| 1235 | match self { |
| 1236 | CastState::ResizePending { pending_size } => *pending_size, |
| 1237 | CastState::ConfirmationPending { size, .. } => *size, |
| 1238 | CastState::Ready { size, .. } => *size, |
| 1239 | } |
| 1240 | } |
| 1241 | } |
| 1242 | |
| 1243 | fn pw_version_supports_cursor_metadata() -> bool { |
| 1244 | // This PipeWire version fixed a critical memory issue with cursor metadata: |
| 1245 | // https://gitlab.freedesktop.org/pipewire/pipewire/-/merge_requests/2538 |
| 1246 | unsafe { pw_check_library_version(1, 4, 8) } |
| 1247 | } |
| 1248 | |
| 1249 | fn make_video_params( |
| 1250 | formats: &FormatSet, |
| 1251 | size: Size<u32, Physical>, |
| 1252 | refresh: u32, |
| 1253 | alpha: bool, |
| 1254 | ) -> pod::Object { |
| 1255 | let format = if alpha { |
| 1256 | VideoFormat::BGRA |
| 1257 | } else { |
| 1258 | VideoFormat::BGRx |
| 1259 | }; |
| 1260 | |
| 1261 | let fourcc = if alpha { |
| 1262 | Fourcc::Argb8888 |
| 1263 | } else { |
| 1264 | Fourcc::Xrgb8888 |
| 1265 | }; |
| 1266 | |
| 1267 | let formats: Vec<_> = formats |
| 1268 | .iter() |
| 1269 | .filter_map(|f| (f.code == fourcc).then_some(u64::from(f.modifier) as i64)) |
| 1270 | .collect(); |
| 1271 | |
| 1272 | trace!("offering: {formats:?}"); |
| 1273 | |
| 1274 | let dont_fixate = if formats.len() > 1 { |
| 1275 | PropertyFlags::DONT_FIXATE |
| 1276 | } else { |
| 1277 | PropertyFlags::empty() |
| 1278 | }; |
| 1279 | |
| 1280 | pod::object!( |
| 1281 | SpaTypes::ObjectParamFormat, |
| 1282 | ParamType::EnumFormat, |
| 1283 | pod::property!(FormatProperties::MediaType, Id, MediaType::Video), |
| 1284 | pod::property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), |
| 1285 | pod::property!(FormatProperties::VideoFormat, Id, format), |
| 1286 | Property { |
| 1287 | key: FormatProperties::VideoModifier.as_raw(), |
| 1288 | flags: PropertyFlags::MANDATORY | dont_fixate, |
| 1289 | value: pod::Value::Choice(ChoiceValue::Long(Choice( |
| 1290 | ChoiceFlags::empty(), |
| 1291 | ChoiceEnum::Enum { |
| 1292 | default: formats[0], |
| 1293 | alternatives: formats, |
| 1294 | } |
| 1295 | ))) |
| 1296 | }, |
| 1297 | pod::property!( |
| 1298 | FormatProperties::VideoSize, |
| 1299 | Rectangle, |
| 1300 | Rectangle { |
| 1301 | width: size.w, |
| 1302 | height: size.h, |
| 1303 | } |
| 1304 | ), |
| 1305 | pod::property!( |
| 1306 | FormatProperties::VideoFramerate, |
| 1307 | Fraction, |
| 1308 | Fraction { num: 0, denom: 1 } |
| 1309 | ), |
| 1310 | pod::property!( |
| 1311 | FormatProperties::VideoMaxFramerate, |
| 1312 | Choice, |
| 1313 | Range, |
| 1314 | Fraction, |
| 1315 | Fraction { |
| 1316 | num: refresh, |
| 1317 | denom: 1000 |
| 1318 | }, |
| 1319 | Fraction { num: 1, denom: 1 }, |
| 1320 | Fraction { |
| 1321 | num: refresh, |
| 1322 | denom: 1000 |
| 1323 | } |
| 1324 | ), |
| 1325 | ) |
| 1326 | } |
| 1327 | |
| 1328 | fn make_pod(buffer: &mut Vec<u8>, object: pod::Object) -> &Pod { |
| 1329 | PodSerializer::serialize(Cursor::new(&mut *buffer), &pod::Value::Object(object)).unwrap(); |
| 1330 | Pod::from_bytes(buffer).unwrap() |
| 1331 | } |
| 1332 | |
| 1333 | fn find_preferred_modifier( |
| 1334 | gbm: &GbmDevice<DrmDeviceFd>, |
| 1335 | size: Size<u32, Physical>, |
| 1336 | fourcc: Fourcc, |
| 1337 | modifiers: Vec<i64>, |
| 1338 | ) -> anyhow::Result<(Modifier, usize)> { |
| 1339 | debug!("find_preferred_modifier: size={size:?}, fourcc={fourcc}, modifiers={modifiers:?}"); |
| 1340 | |
| 1341 | let (buffer, modifier) = allocate_buffer(gbm, size, fourcc, &modifiers)?; |
| 1342 | |
| 1343 | let dmabuf = buffer |
| 1344 | .export() |
| 1345 | .context("error exporting GBM buffer object as dmabuf")?; |
| 1346 | let plane_count = dmabuf.num_planes(); |
| 1347 | |
| 1348 | // FIXME: Ideally this also needs to try binding the dmabuf for rendering. |
| 1349 | |
| 1350 | Ok((modifier, plane_count)) |
| 1351 | } |
| 1352 | |
| 1353 | fn allocate_buffer( |
| 1354 | gbm: &GbmDevice<DrmDeviceFd>, |
| 1355 | size: Size<u32, Physical>, |
| 1356 | fourcc: Fourcc, |
| 1357 | modifiers: &[i64], |
| 1358 | ) -> anyhow::Result<(GbmBuffer, Modifier)> { |
| 1359 | let (w, h) = (size.w, size.h); |
| 1360 | let flags = GbmBufferFlags::RENDERING; |
| 1361 | |
| 1362 | if modifiers.len() == 1 && Modifier::from(modifiers[0] as u64) == Modifier::Invalid { |
| 1363 | let bo = gbm |
| 1364 | .create_buffer_object::<()>(w, h, fourcc, flags) |
| 1365 | .context("error creating GBM buffer object")?; |
| 1366 | |
| 1367 | let buffer = GbmBuffer::from_bo(bo, true); |
| 1368 | Ok((buffer, Modifier::Invalid)) |
| 1369 | } else { |
| 1370 | let modifiers = modifiers |
| 1371 | .iter() |
| 1372 | .map(|m| Modifier::from(*m as u64)) |
| 1373 | .filter(|m| *m != Modifier::Invalid); |
| 1374 | |
| 1375 | let bo = gbm |
| 1376 | .create_buffer_object_with_modifiers2::<()>(w, h, fourcc, modifiers, flags) |
| 1377 | .context("error creating GBM buffer object")?; |
| 1378 | |
| 1379 | let modifier = bo.modifier(); |
| 1380 | let buffer = GbmBuffer::from_bo(bo, false); |
| 1381 | Ok((buffer, modifier)) |
| 1382 | } |
| 1383 | } |
| 1384 | |
| 1385 | fn allocate_dmabuf( |
| 1386 | gbm: &GbmDevice<DrmDeviceFd>, |
| 1387 | size: Size<u32, Physical>, |
| 1388 | fourcc: Fourcc, |
| 1389 | modifier: Modifier, |
| 1390 | ) -> anyhow::Result<Dmabuf> { |
| 1391 | let (buffer, _modifier) = allocate_buffer(gbm, size, fourcc, &[u64::from(modifier) as i64])?; |
| 1392 | let dmabuf = buffer |
| 1393 | .export() |
| 1394 | .context("error exporting GBM buffer object as dmabuf")?; |
| 1395 | Ok(dmabuf) |
| 1396 | } |
| 1397 | |
| 1398 | unsafe fn return_unused_buffer(stream: &Stream, pw_buffer: NonNull<pw_buffer>) { |
| 1399 | // pw_stream_return_buffer() requires too new PipeWire (1.4.0). So, mark as |
| 1400 | // corrupted and queue. |
| 1401 | let pw_buffer = pw_buffer.as_ptr(); |
| 1402 | let spa_buffer = (*pw_buffer).buffer; |
| 1403 | let chunk = (*(*spa_buffer).datas).chunk; |
| 1404 | // Some (older?) consumers will check for size == 0 instead of the CORRUPTED flag. |
| 1405 | (*chunk).size = 0; |
| 1406 | (*chunk).flags = SPA_CHUNK_FLAG_CORRUPTED as i32; |
| 1407 | |
| 1408 | if let Some(header) = find_meta_header(spa_buffer) { |
| 1409 | let header = header.as_ptr(); |
| 1410 | (*header).flags = SPA_META_HEADER_FLAG_CORRUPTED; |
| 1411 | } |
| 1412 | |
| 1413 | pw_stream_queue_buffer(stream.as_raw_ptr(), pw_buffer); |
| 1414 | } |
| 1415 | |
| 1416 | unsafe fn mark_buffer_as_good(pw_buffer: NonNull<pw_buffer>, sequence: &mut u64) { |
| 1417 | let pw_buffer = pw_buffer.as_ptr(); |
| 1418 | let spa_buffer = (*pw_buffer).buffer; |
| 1419 | let chunk = (*(*spa_buffer).datas).chunk; |
| 1420 | |
| 1421 | // With DMA-BUFs, consumers should ignore the size field, and producers are allowed |
| 1422 | // to set it to 0. |
| 1423 | // |
| 1424 | // https://docs.pipewire.org/page_dma_buf.html |
| 1425 | // |
| 1426 | // However, OBS checks for size != 0 as a workaround for old compositor versions, |
| 1427 | // so we set it to 1. |
| 1428 | (*chunk).size = 1; |
| 1429 | // Clear the corrupted flag we may have set before. |
| 1430 | (*chunk).flags = SPA_CHUNK_FLAG_NONE as i32; |
| 1431 | |
| 1432 | *sequence = sequence.wrapping_add(1); |
| 1433 | if let Some(header) = find_meta_header(spa_buffer) { |
| 1434 | let header = header.as_ptr(); |
| 1435 | // Clear the corrupted flag we may have set before. |
| 1436 | (*header).flags = 0; |
| 1437 | (*header).seq = *sequence; |
| 1438 | |
| 1439 | // Set buffer timestamp as unknown. |
| 1440 | // |
| 1441 | // FIXME: we could try passing real presentation timestamps for rendered frames here. |
| 1442 | // However, then we must also ensure that the time base never jumps (e.g. when switching a |
| 1443 | // dynamic cast between outputs) as this would mess up the timing downstream. |
| 1444 | (*header).pts = -1; |
| 1445 | } |
| 1446 | } |
| 1447 | |
| 1448 | unsafe fn find_meta_header(buffer: *mut spa_buffer) -> Option<NonNull<spa_meta_header>> { |
| 1449 | let p = spa_buffer_find_meta_data(buffer, SPA_META_Header, size_of::<spa_meta_header>()).cast(); |
| 1450 | NonNull::new(p) |
| 1451 | } |
| 1452 | |
| 1453 | unsafe fn add_invisible_cursor(spa_buffer: *mut spa_buffer) { |
| 1454 | unsafe { |
| 1455 | let cursor_meta_ptr: *mut spa_meta_cursor = spa_buffer_find_meta_data( |
| 1456 | spa_buffer, |
| 1457 | SPA_META_Cursor, |
| 1458 | mem::size_of::<spa_meta_cursor>(), |
| 1459 | ) |
| 1460 | .cast(); |
| 1461 | let Some(cursor_meta) = cursor_meta_ptr.as_mut() else { |
| 1462 | return; |
| 1463 | }; |
| 1464 | |
| 1465 | // The cursor is present but invisible. |
| 1466 | cursor_meta.id = 1; |
| 1467 | cursor_meta.position.x = 0; |
| 1468 | cursor_meta.position.y = 0; |
| 1469 | cursor_meta.hotspot.x = 0; |
| 1470 | cursor_meta.hotspot.y = 0; |
| 1471 | cursor_meta.bitmap_offset = BITMAP_META_OFFSET as _; |
| 1472 | |
| 1473 | let bitmap_meta_ptr = cursor_meta_ptr |
| 1474 | .byte_add(BITMAP_META_OFFSET) |
| 1475 | .cast::<spa_meta_bitmap>(); |
| 1476 | let bitmap_meta = &mut *bitmap_meta_ptr; |
| 1477 | |
| 1478 | // HACK: PipeWire docs say offset = 0 means invisible. |
| 1479 | // |
| 1480 | // Unfortunately, OBS doesn't actually check that, instead it checks that size isn't zero: |
| 1481 | // https://github.com/obsproject/obs-studio/blob/f4aaa5f0417c5ec40a3799551e125129fce1e007/plugins/linux-pipewire/pipewire.c#L900 |
| 1482 | // |
| 1483 | // Unfortunately, libwebrtc, on top of ignoring offset, also treats size = 0 as "preserve |
| 1484 | // previous cursor": |
| 1485 | // https://webrtc.googlesource.com/src/+/97b46e12582606a238d4f0c8524365cf5bdcb411/modules/desktop_capture/linux/wayland/shared_screencast_stream.cc#765 |
| 1486 | // |
| 1487 | // So, send a 1x1 transparent pixel instead... |
| 1488 | bitmap_meta.offset = BITMAP_DATA_OFFSET as _; |
| 1489 | bitmap_meta.size.width = 1; |
| 1490 | bitmap_meta.size.height = 1; |
| 1491 | bitmap_meta.stride = CURSOR_BPP as i32; |
| 1492 | bitmap_meta.format = CURSOR_FORMAT; |
| 1493 | |
| 1494 | let bitmap_data = bitmap_meta_ptr.cast::<u8>().add(BITMAP_DATA_OFFSET); |
| 1495 | let bitmap_slice = slice::from_raw_parts_mut(bitmap_data, CURSOR_BITMAP_SIZE); |
| 1496 | bitmap_slice[..4].copy_from_slice(&[0, 0, 0, 0]); |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | unsafe fn add_cursor_metadata( |
| 1501 | renderer: &mut GlesRenderer, |
| 1502 | spa_buffer: *mut spa_buffer, |
| 1503 | cursor_data: &CursorData<impl RenderElement<GlesRenderer>>, |
| 1504 | redraw: bool, |
| 1505 | ) { |
| 1506 | unsafe { |
| 1507 | let cursor_meta_ptr: *mut spa_meta_cursor = spa_buffer_find_meta_data( |
| 1508 | spa_buffer, |
| 1509 | SPA_META_Cursor, |
| 1510 | mem::size_of::<spa_meta_cursor>(), |
| 1511 | ) |
| 1512 | .cast(); |
| 1513 | let Some(cursor_meta) = cursor_meta_ptr.as_mut() else { |
| 1514 | return; |
| 1515 | }; |
| 1516 | |
| 1517 | cursor_meta.id = 1; |
| 1518 | cursor_meta.position.x = cursor_data.location.x; |
| 1519 | cursor_meta.position.y = cursor_data.location.y; |
| 1520 | cursor_meta.hotspot.x = cursor_data.hotspot.x; |
| 1521 | cursor_meta.hotspot.y = cursor_data.hotspot.y; |
| 1522 | |
| 1523 | if !redraw { |
| 1524 | trace!("cursor not damaged, skipping rerendering"); |
| 1525 | cursor_meta.bitmap_offset = 0; |
| 1526 | return; |
| 1527 | } |
| 1528 | |
| 1529 | cursor_meta.bitmap_offset = BITMAP_META_OFFSET as _; |
| 1530 | |
| 1531 | let bitmap_meta_ptr = cursor_meta_ptr |
| 1532 | .byte_add(BITMAP_META_OFFSET) |
| 1533 | .cast::<spa_meta_bitmap>(); |
| 1534 | let bitmap_meta = &mut *bitmap_meta_ptr; |
| 1535 | |
| 1536 | // Start with a 1x1 transparent pixel; see comment in add_invisible_cursor(). |
| 1537 | bitmap_meta.offset = BITMAP_DATA_OFFSET as _; |
| 1538 | bitmap_meta.size.width = 1; |
| 1539 | bitmap_meta.size.height = 1; |
| 1540 | bitmap_meta.stride = CURSOR_BPP as i32; |
| 1541 | bitmap_meta.format = CURSOR_FORMAT; |
| 1542 | |
| 1543 | let bitmap_data = bitmap_meta_ptr.cast::<u8>().add(BITMAP_DATA_OFFSET); |
| 1544 | let bitmap_slice = slice::from_raw_parts_mut(bitmap_data, CURSOR_BITMAP_SIZE); |
| 1545 | bitmap_slice[..4].copy_from_slice(&[0, 0, 0, 0]); |
| 1546 | |
| 1547 | let size = Size::new( |
| 1548 | min(cursor_data.size.w, CURSOR_WIDTH as i32), |
| 1549 | min(cursor_data.size.h, CURSOR_HEIGHT as i32), |
| 1550 | ); |
| 1551 | if size.w == 0 || size.h == 0 { |
| 1552 | trace!("cursor is invisible, skipping rendering"); |
| 1553 | return; |
| 1554 | } |
| 1555 | |
| 1556 | let _span = tracy_client::span!("add_cursor_metadata render cursor"); |
| 1557 | |
| 1558 | // FIXME: use a reliable buffer whenever we're rendering the cursor. |
| 1559 | // |
| 1560 | // PipeWire buffers are not normally guaranteed to reach the destination, so our buffer |
| 1561 | // with the rendered cursor bitmap may not reach the consumer. |
| 1562 | // |
| 1563 | // Reliable buffers should be available starting from 1.6.0: |
| 1564 | // https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/4885 |
| 1565 | let mapping = match render_and_download( |
| 1566 | renderer, |
| 1567 | size, |
| 1568 | cursor_data.scale, |
| 1569 | Transform::Normal, |
| 1570 | Fourcc::Argb8888, |
| 1571 | cursor_data.relocated.iter().rev(), |
| 1572 | ) { |
| 1573 | Ok(mapping) => mapping, |
| 1574 | Err(err) => { |
| 1575 | warn!("error rendering cursor: {err:?}"); |
| 1576 | return; |
| 1577 | } |
| 1578 | }; |
| 1579 | let pixels = match renderer.map_texture(&mapping) { |
| 1580 | Ok(pixels) => pixels, |
| 1581 | Err(err) => { |
| 1582 | warn!("error mapping cursor texture: {err:?}"); |
| 1583 | return; |
| 1584 | } |
| 1585 | }; |
| 1586 | |
| 1587 | bitmap_slice[..pixels.len()].copy_from_slice(pixels); |
| 1588 | |
| 1589 | // Fill the metadata now that everything succeeded. |
| 1590 | bitmap_meta.size.width = size.w as _; |
| 1591 | bitmap_meta.size.height = size.h as _; |
| 1592 | bitmap_meta.stride = size.w * CURSOR_BPP as i32; |
| 1593 | } |
| 1594 | } |