Owned pixel buffer for no-copy presentation

This is based on the API that will be used for no-copy presentation. But
wraps it in `set_buffer`.

This also fixes the Wayland buffer code to set `self.width` and
`self.height` on resize, and set the length of the shared memory file
when the buffer is created.

Co-authored-by: jtnunley <jtnunley01@gmail.com>
This commit is contained in:
Ian Douglas Scott 2023-04-06 00:30:59 -07:00 committed by GitHub
parent e5d546ff9e
commit a09e4cf679
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 1176 additions and 438 deletions

View file

@ -1,7 +1,9 @@
use memmap2::MmapMut;
use std::{
ffi::CStr,
fs::File,
os::unix::prelude::{AsRawFd, FileExt, FromRawFd},
os::unix::prelude::{AsRawFd, FromRawFd},
slice,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
@ -69,9 +71,19 @@ fn create_memfile() -> File {
panic!("Failed to generate non-existant shm name")
}
// Round size to use for pool for given dimentions, rounding up to power of 2
fn get_pool_size(width: i32, height: i32) -> i32 {
((width * height * 4) as u32).next_power_of_two() as i32
}
unsafe fn map_file(file: &File) -> MmapMut {
unsafe { MmapMut::map_mut(file.as_raw_fd()).expect("Failed to map shared memory") }
}
pub(super) struct WaylandBuffer {
qh: QueueHandle<State>,
tempfile: File,
map: MmapMut,
pool: wl_shm_pool::WlShmPool,
pool_size: i32,
buffer: wl_buffer::WlBuffer,
@ -82,8 +94,15 @@ pub(super) struct WaylandBuffer {
impl WaylandBuffer {
pub fn new(shm: &wl_shm::WlShm, width: i32, height: i32, qh: &QueueHandle<State>) -> Self {
// Calculate size to use for shm pool
let pool_size = get_pool_size(width, height);
// Create an `mmap` shared memory
let tempfile = create_memfile();
let pool_size = width * height * 4;
let _ = tempfile.set_len(pool_size as u64);
let map = unsafe { map_file(&tempfile) };
// Create wayland shm pool and buffer
let pool = shm.create_pool(tempfile.as_raw_fd(), pool_size, qh, ());
let released = Arc::new(AtomicBool::new(true));
let buffer = pool.create_buffer(
@ -95,8 +114,10 @@ impl WaylandBuffer {
qh,
released.clone(),
);
Self {
qh: qh.clone(),
map,
tempfile,
pool,
pool_size,
@ -119,6 +140,7 @@ impl WaylandBuffer {
let _ = self.tempfile.set_len(size as u64);
self.pool.resize(size);
self.pool_size = size;
self.map = unsafe { map_file(&self.tempfile) };
}
// Create buffer with correct size
@ -136,14 +158,6 @@ impl WaylandBuffer {
}
}
pub fn write(&self, buffer: &[u32]) {
let buffer =
unsafe { std::slice::from_raw_parts(buffer.as_ptr() as *const u8, buffer.len() * 4) };
self.tempfile
.write_all_at(buffer, 0)
.expect("Failed to write buffer to temporary file.");
}
pub fn attach(&self, surface: &wl_surface::WlSurface) {
self.released.store(false, Ordering::SeqCst);
surface.attach(Some(&self.buffer), 0, 0);
@ -152,6 +166,14 @@ impl WaylandBuffer {
pub fn released(&self) -> bool {
self.released.load(Ordering::SeqCst)
}
fn len(&self) -> usize {
self.width as usize * self.height as usize
}
pub unsafe fn mapped_mut(&mut self) -> &mut [u32] {
unsafe { slice::from_raw_parts_mut(self.map.as_mut_ptr() as *mut u32, self.len()) }
}
}
impl Drop for WaylandBuffer {

View file

@ -1,6 +1,10 @@
use crate::{error::unwrap, SoftBufferError};
use crate::{error::unwrap, util, SoftBufferError};
use raw_window_handle::{WaylandDisplayHandle, WaylandWindowHandle};
use std::sync::{Arc, Mutex};
use std::{
cell::RefCell,
num::{NonZeroI32, NonZeroU32},
rc::Rc,
};
use wayland_client::{
backend::{Backend, ObjectId},
globals::{registry_queue_init, GlobalListContents},
@ -15,7 +19,7 @@ struct State;
pub struct WaylandDisplayImpl {
conn: Connection,
event_queue: Mutex<EventQueue<State>>,
event_queue: RefCell<EventQueue<State>>,
qh: QueueHandle<State>,
shm: wl_shm::WlShm,
}
@ -36,7 +40,7 @@ impl WaylandDisplayImpl {
)?;
Ok(Self {
conn,
event_queue: Mutex::new(event_queue),
event_queue: RefCell::new(event_queue),
qh,
shm,
})
@ -44,15 +48,16 @@ impl WaylandDisplayImpl {
}
pub struct WaylandImpl {
display: Arc<WaylandDisplayImpl>,
display: Rc<WaylandDisplayImpl>,
surface: wl_surface::WlSurface,
buffers: Option<(WaylandBuffer, WaylandBuffer)>,
size: Option<(NonZeroI32, NonZeroI32)>,
}
impl WaylandImpl {
pub unsafe fn new(
window_handle: WaylandWindowHandle,
display: Arc<WaylandDisplayImpl>,
display: Rc<WaylandDisplayImpl>,
) -> Result<Self, SoftBufferError> {
// SAFETY: Ensured by user
let surface_id = unwrap(
@ -72,60 +77,119 @@ impl WaylandImpl {
display,
surface,
buffers: Default::default(),
size: None,
})
}
fn buffer(&mut self, width: i32, height: i32) -> &WaylandBuffer {
self.buffers = Some(if let Some((front, mut back)) = self.buffers.take() {
// Swap buffers; block if back buffer not released yet
if !back.released() {
let mut event_queue = self.display.event_queue.lock().unwrap();
while !back.released() {
event_queue.blocking_dispatch(&mut State).unwrap();
}
}
back.resize(width, height);
(back, front)
} else {
// Allocate front and back buffer
(
WaylandBuffer::new(&self.display.shm, width, height, &self.display.qh),
WaylandBuffer::new(&self.display.shm, width, height, &self.display.qh),
)
});
&self.buffers.as_ref().unwrap().0
pub fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) -> Result<(), SoftBufferError> {
self.size = Some(
(|| {
let width = NonZeroI32::try_from(width).ok()?;
let height = NonZeroI32::try_from(height).ok()?;
Some((width, height))
})()
.ok_or(SoftBufferError::SizeOutOfRange { width, height })?,
);
Ok(())
}
pub(super) unsafe fn set_buffer(&mut self, buffer: &[u32], width: u16, height: u16) {
let _ = self
pub fn buffer_mut(&mut self) -> Result<BufferImpl, SoftBufferError> {
let (width, height) = self
.size
.expect("Must set size of surface before calling `buffer_mut()`");
if let Some((_front, back)) = &mut self.buffers {
// Block if back buffer not released yet
if !back.released() {
let mut event_queue = self.display.event_queue.borrow_mut();
while !back.released() {
event_queue.blocking_dispatch(&mut State).map_err(|err| {
SoftBufferError::PlatformError(
Some("Wayland dispatch failure".to_string()),
Some(Box::new(err)),
)
})?;
}
}
// Resize, if buffer isn't large enough
back.resize(width.get(), height.get());
} else {
// Allocate front and back buffer
self.buffers = Some((
WaylandBuffer::new(
&self.display.shm,
width.get(),
height.get(),
&self.display.qh,
),
WaylandBuffer::new(
&self.display.shm,
width.get(),
height.get(),
&self.display.qh,
),
));
};
Ok(BufferImpl(util::BorrowStack::new(self, |buffer| {
Ok(unsafe { buffer.buffers.as_mut().unwrap().1.mapped_mut() })
})?))
}
}
pub struct BufferImpl<'a>(util::BorrowStack<'a, WaylandImpl, [u32]>);
impl<'a> BufferImpl<'a> {
#[inline]
pub fn pixels(&self) -> &[u32] {
self.0.member()
}
#[inline]
pub fn pixels_mut(&mut self) -> &mut [u32] {
self.0.member_mut()
}
pub fn present(self) -> Result<(), SoftBufferError> {
let imp = self.0.into_container();
let (width, height) = imp
.size
.expect("Must set size of surface before calling `present()`");
let _ = imp
.display
.event_queue
.lock()
.unwrap()
.borrow_mut()
.dispatch_pending(&mut State);
let surface = self.surface.clone();
let wayland_buffer = self.buffer(width.into(), height.into());
wayland_buffer.write(buffer);
wayland_buffer.attach(&surface);
if let Some((front, back)) = &mut imp.buffers {
// Swap front and back buffer
std::mem::swap(front, back);
// FIXME: Proper damaging mechanism.
//
// In order to propagate changes on compositors which track damage, for now damage the entire surface.
if self.surface.version() < 4 {
// FIXME: Accommodate scale factor since wl_surface::damage is in terms of surface coordinates while
// wl_surface::damage_buffer is in buffer coordinates.
front.attach(&imp.surface);
// FIXME: Proper damaging mechanism.
//
// i32::MAX is a valid damage box (most compositors interpret the damage box as "the entire surface")
self.surface.damage(0, 0, i32::MAX, i32::MAX);
} else {
// Introduced in version 4, it is an error to use this request in version 3 or lower.
self.surface
.damage_buffer(0, 0, width as i32, height as i32);
}
self.surface.commit();
// In order to propagate changes on compositors which track damage, for now damage the entire surface.
if imp.surface.version() < 4 {
// FIXME: Accommodate scale factor since wl_surface::damage is in terms of surface coordinates while
// wl_surface::damage_buffer is in buffer coordinates.
//
// i32::MAX is a valid damage box (most compositors interpret the damage box as "the entire surface")
imp.surface.damage(0, 0, i32::MAX, i32::MAX);
} else {
// Introduced in version 4, it is an error to use this request in version 3 or lower.
imp.surface.damage_buffer(0, 0, width.get(), height.get());
}
let _ = self.display.event_queue.lock().unwrap().flush();
imp.surface.commit();
}
let _ = imp.display.event_queue.borrow_mut().flush();
Ok(())
}
}