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