zwlr_screencopy v3 support

This commit is contained in:
galister
2026-01-09 18:47:45 +09:00
parent e6e1764b36
commit 5e77bab588
20 changed files with 578 additions and 192 deletions

View File

@@ -16,6 +16,7 @@ pub enum WlxFrame {
Dmabuf(DmabufFrame),
MemFd(MemFdFrame),
MemPtr(MemPtrFrame),
Implicit,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]

View File

@@ -29,6 +29,9 @@ use wayland_client::{
wl_shm::WlShm,
},
};
use wayland_protocols::wp::linux_dmabuf::zv1::client::{
zwp_linux_buffer_params_v1::ZwpLinuxBufferParamsV1, zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1,
};
use crate::frame;
@@ -61,6 +64,7 @@ pub struct WlxClient {
pub xdg_output_mgr: ZxdgOutputManagerV1,
pub maybe_wlr_dmabuf_mgr: Option<ZwlrExportDmabufManagerV1>,
pub maybe_wlr_screencopy_mgr: Option<ZwlrScreencopyManagerV1>,
pub maybe_zwp_linux_dmabuf: Option<ZwpLinuxDmabufV1>,
pub wl_seat: WlSeat,
pub wl_shm: WlShm,
pub outputs: IdMap<u32, WlxOutput>,
@@ -91,7 +95,8 @@ impl WlxClient {
.expect(WlSeat::interface().name),
wl_shm: globals.bind(&qh, 1..=1, ()).expect(WlShm::interface().name),
maybe_wlr_dmabuf_mgr: globals.bind(&qh, 1..=1, ()).ok(),
maybe_wlr_screencopy_mgr: globals.bind(&qh, 2..=2, ()).ok(),
maybe_wlr_screencopy_mgr: globals.bind(&qh, 3..=3, ()).ok(),
maybe_zwp_linux_dmabuf: globals.bind(&qh, 4..=4, ()).ok(),
outputs: IdMap::new(),
queue: Arc::new(Mutex::new(queue)),
globals,
@@ -441,3 +446,27 @@ impl Dispatch<WlShm, ()> for WlxClient {
) {
}
}
impl Dispatch<ZwpLinuxDmabufV1, ()> for WlxClient {
fn event(
_state: &mut Self,
_proxy: &ZwpLinuxDmabufV1,
_event: <ZwpLinuxDmabufV1 as Proxy>::Event,
_data: &(),
_conn: &Connection,
_qhandle: &QueueHandle<Self>,
) {
}
}
impl Dispatch<ZwpLinuxBufferParamsV1, ()> for WlxClient {
fn event(
_state: &mut Self,
_proxy: &ZwpLinuxBufferParamsV1,
_event: <ZwpLinuxBufferParamsV1 as Proxy>::Event,
_data: &(),
_conn: &Connection,
_qhandle: &QueueHandle<Self>,
) {
}
}

View File

@@ -14,6 +14,7 @@ use wayland_client::{
Connection, Dispatch, Proxy, QueueHandle, WEnum,
protocol::{wl_buffer::WlBuffer, wl_shm::Format, wl_shm_pool::WlShmPool},
};
use wayland_protocols::wp::linux_dmabuf::zv1::client::zwp_linux_buffer_params_v1;
use smithay_client_toolkit::reexports::protocols_wlr::screencopy::v1::client::zwlr_screencopy_frame_v1::{ZwlrScreencopyFrameV1, self};
@@ -23,59 +24,82 @@ use crate::{
wayland::WlxClient,
};
struct BufData {
wl_buffer: WlBuffer,
wl_pool: WlShmPool,
fd: RawFd,
pub trait DmaExporter {
fn next_frame(
&mut self,
width: u32,
height: u32,
fourcc: DrmFourcc,
) -> Option<(FramePlane, DrmModifier)>;
}
enum BufData {
Shm {
wl_buffer: WlBuffer,
wl_pool: WlShmPool,
fd: RawFd,
},
Dma {
wl_buffer: WlBuffer,
},
}
impl Drop for BufData {
fn drop(&mut self) {
self.wl_buffer.destroy();
self.wl_pool.destroy();
unsafe {
libc::close(self.fd);
match self {
Self::Shm {
wl_buffer,
wl_pool,
fd,
..
} => {
wl_buffer.destroy();
wl_pool.destroy();
unsafe {
libc::close(*fd);
}
}
Self::Dma { wl_buffer } => {
wl_buffer.destroy();
}
}
}
}
enum ScreenCopyEvent {
Buffer {
data: BufData,
drm_format: DrmFormat,
shm_format: Format,
width: u32,
height: u32,
stride: u32,
},
DmaBuf {
format: DrmFourcc,
width: u32,
height: u32,
},
BuffersDone,
Ready,
Failed,
}
struct CaptureData<U, R>
where
U: Any,
R: Any,
{
struct CaptureData<U, R> {
sender: mpsc::SyncSender<R>,
receiver: mpsc::Receiver<R>,
user_data: U,
user_data: Option<Box<U>>,
receive_callback: fn(&U, WlxFrame) -> Option<R>,
}
pub struct WlrScreencopyCapture<U, R>
where
U: Any + Send,
R: Any + Send,
{
pub struct WlrScreencopyCapture<U, R> {
output_id: u32,
wl: Option<Box<WlxClient>>,
handle: Option<JoinHandle<Box<WlxClient>>>,
handle: Option<JoinHandle<(Box<WlxClient>, Box<U>)>>,
data: Option<CaptureData<U, R>>,
}
impl<U, R> WlrScreencopyCapture<U, R>
where
U: Any + Send,
U: Any + Send + DmaExporter,
R: Any + Send,
{
pub fn new(wl: WlxClient, output_id: u32) -> Self {
@@ -90,7 +114,7 @@ where
impl<U, R> WlxCapture<U, R> for WlrScreencopyCapture<U, R>
where
U: Any + Send + Clone,
U: Any + Send + DmaExporter,
R: Any + Send,
{
fn init(
@@ -105,7 +129,7 @@ where
self.data = Some(CaptureData {
sender,
receiver,
user_data,
user_data: Some(Box::new(user_data)),
receive_callback,
});
}
@@ -113,7 +137,7 @@ where
self.data.is_some()
}
fn supports_dmbuf(&self) -> bool {
false // screencopy v1
true // screencopy v3+
}
fn receive(&mut self) -> Option<R> {
if let Some(data) = self.data.as_ref() {
@@ -135,7 +159,9 @@ where
if let Some(handle) = self.handle.take() {
if handle.is_finished() {
wait_for_damage = true;
self.wl = Some(handle.join().unwrap()); // safe to unwrap because we checked is_finished
let (wl, u) = handle.join().unwrap(); // safe to unwrap because is_finished
self.wl = Some(wl);
self.data.as_mut().unwrap().user_data = Some(u);
} else {
self.handle = Some(handle);
return;
@@ -148,12 +174,12 @@ where
let data = self
.data
.as_ref()
.as_mut()
.expect("must call init once before request_new_frame");
self.handle = Some(std::thread::spawn({
let sender = data.sender.clone();
let user_data = data.user_data.clone();
let user_data = data.user_data.take().unwrap();
let receive_callback = data.receive_callback;
let output_id = self.output_id;
@@ -176,20 +202,20 @@ fn request_screencopy_frame<U, R>(
client: Box<WlxClient>,
output_id: u32,
sender: SyncSender<R>,
user_data: U,
mut user_data: Box<U>,
receive_callback: fn(&U, WlxFrame) -> Option<R>,
wait_for_damage: bool,
) -> Box<WlxClient>
) -> (Box<WlxClient>, Box<U>)
where
U: Any + Send,
U: Any + Send + DmaExporter,
R: Any + Send,
{
let Some(screencopy_manager) = client.maybe_wlr_screencopy_mgr.as_ref() else {
return client;
return (client, user_data);
};
let Some(output) = client.outputs.get(output_id) else {
return client;
return (client, user_data);
};
let transform = output.transform;
@@ -206,44 +232,138 @@ where
let mut frame_buffer = None;
let mut maybe_buffer = None;
let mut maybe_dmabuf = None;
'receiver: loop {
for event in rx.try_iter() {
match event {
ScreenCopyEvent::Buffer {
data,
drm_format,
width,
height,
stride,
} => {
let frame = MemFdFrame {
format: FrameFormat {
ScreenCopyEvent::Buffer { .. } => {
log::trace!("{name}: ScreenCopy Buffer event received");
maybe_buffer = Some(event);
}
ScreenCopyEvent::DmaBuf { .. } => {
log::trace!("{name}: ScreenCopy LinuxDmabuf event received");
maybe_dmabuf = Some(event);
}
ScreenCopyEvent::BuffersDone => {
log::trace!("{name}: ScreenCopy BuffersDone event received");
if let Some(zwp_linux_dmabuf) = client.maybe_zwp_linux_dmabuf.as_ref()
&& let Some(ScreenCopyEvent::DmaBuf {
format,
width,
height,
drm_format,
transform,
},
plane: FramePlane {
fd: Some(data.fd),
offset: 0,
stride: stride as _,
},
mouse: None,
};
log::trace!("{}: Received screencopy buffer, copying", name.as_ref());
if wait_for_damage {
proxy.copy_with_damage(&data.wl_buffer);
}) = maybe_dmabuf
&& let Some((plane, modifier)) = user_data.next_frame(width, height, format)
{
let mod_hi = (u64::from(modifier) >> 32) as _;
let mod_lo = (u64::from(modifier) & 0xFFFFFFFF) as _;
let fd = unsafe { BorrowedFd::borrow_raw(plane.fd.unwrap()) };
let params = zwp_linux_dmabuf.create_params(&client.queue_handle, ());
params.add(fd, 0, plane.offset, plane.stride as _, mod_hi, mod_lo);
let wl_buffer = params.create_immed(
width as _,
height as _,
format as _,
zwp_linux_buffer_params_v1::Flags::empty(),
&client.queue_handle,
(),
);
log::trace!("{name}: ScreenCopy with Dmabuf");
// copy_with_damage seems to not work here
proxy.copy(&wl_buffer);
frame_buffer = Some((WlxFrame::Implicit, BufData::Dma { wl_buffer }));
} else if let Some(ScreenCopyEvent::Buffer {
shm_format,
width,
height,
stride,
}) = maybe_buffer
&& let Some(fourcc) = fourcc_from_wlshm(shm_format)
{
let fd_num = FD_COUNTER.fetch_add(1, Ordering::Relaxed);
let shm_name = CString::new(format!("wlx-{}", fd_num)).unwrap(); // safe
let size = stride * height;
let fd = unsafe {
let fd = libc::shm_open(
shm_name.as_ptr(),
O_CREAT | O_RDWR,
S_IRUSR | S_IWUSR,
);
libc::shm_unlink(shm_name.as_ptr());
libc::ftruncate(fd, size as _);
fd
};
let borrowed_fd = unsafe { BorrowedFd::borrow_raw(fd) };
let wl_pool = client.wl_shm.create_pool(
borrowed_fd,
size as _,
&client.queue_handle,
(),
);
let wl_buffer = wl_pool.create_buffer(
0,
width as _,
height as _,
stride as _,
shm_format,
&client.queue_handle,
(),
);
log::trace!("{name}: ScreenCopy with SHM");
if wait_for_damage {
proxy.copy_with_damage(&wl_buffer);
} else {
proxy.copy(&wl_buffer);
}
let frame = MemFdFrame {
format: FrameFormat {
width,
height,
drm_format: DrmFormat {
code: fourcc,
modifier: DrmModifier::Invalid,
},
transform,
},
plane: FramePlane {
fd: Some(fd),
offset: 0,
stride: stride as _,
},
mouse: None,
};
frame_buffer = Some((
WlxFrame::MemFd(frame),
BufData::Shm {
wl_buffer,
wl_pool,
fd,
},
));
} else {
proxy.copy(&data.wl_buffer);
log::error!("{name}: No usable ScreenCopy buffers received.");
proxy.destroy();
break 'receiver;
}
frame_buffer = Some((frame, data));
client.dispatch();
}
ScreenCopyEvent::Ready => {
log::trace!("{}: Frame ready?", name.as_ref());
if let Some((frame, buffer)) = frame_buffer {
if let Some(r) = receive_callback(&user_data, WlxFrame::MemFd(frame)) {
if let Some(r) = receive_callback(&user_data, frame) {
let _ = sender.send(r);
log::trace!("{}: Frame ready", name.as_ref());
log::trace!("{}: Frame ready!", name.as_ref());
}
drop(buffer);
}
@@ -257,19 +377,19 @@ where
}
}
client
(client, user_data)
}
static FD_COUNTER: AtomicUsize = AtomicUsize::new(0);
impl Dispatch<ZwlrScreencopyFrameV1, SyncSender<ScreenCopyEvent>> for WlxClient {
fn event(
state: &mut Self,
_state: &mut Self,
proxy: &ZwlrScreencopyFrameV1,
event: <ZwlrScreencopyFrameV1 as Proxy>::Event,
data: &SyncSender<ScreenCopyEvent>,
_conn: &Connection,
qhandle: &QueueHandle<Self>,
_qhandle: &QueueHandle<Self>,
) {
match event {
zwlr_screencopy_frame_v1::Event::Failed => {
@@ -289,58 +409,36 @@ impl Dispatch<ZwlrScreencopyFrameV1, SyncSender<ScreenCopyEvent>> for WlxClient
return;
};
let Some(fourcc) = fourcc_from_wlshm(shm_format) else {
log::warn!("Unsupported screencopy format");
let _ = data.send(ScreenCopyEvent::Failed);
proxy.destroy();
return;
};
let fd_num = FD_COUNTER.fetch_add(1, Ordering::Relaxed);
let name = CString::new(format!("wlx-{}", fd_num)).unwrap(); // safe
let size = stride * height;
let fd = unsafe {
let fd = libc::shm_open(name.as_ptr(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
libc::shm_unlink(name.as_ptr());
libc::ftruncate(fd, size as _);
fd
};
let borrowed_fd = unsafe { BorrowedFd::borrow_raw(fd) };
let wl_pool = state
.wl_shm
.create_pool(borrowed_fd, size as _, qhandle, ());
let wl_buffer = wl_pool.create_buffer(
0,
width as _,
height as _,
stride as _,
shm_format,
qhandle,
(),
);
let _ = data.send(ScreenCopyEvent::Buffer {
data: BufData {
wl_buffer,
wl_pool,
fd,
},
drm_format: DrmFormat {
code: fourcc,
modifier: DrmModifier::Invalid,
},
width,
height,
stride,
shm_format,
});
}
zwlr_screencopy_frame_v1::Event::Ready { .. } => {
let _ = data.send(ScreenCopyEvent::Ready);
proxy.destroy();
}
zwlr_screencopy_frame_v1::Event::LinuxDmabuf {
format,
width,
height,
} => {
let Ok(format) = DrmFourcc::try_from(format) else {
log::warn!("{format} is not a known FourCC");
return;
};
let _ = data.send(ScreenCopyEvent::DmaBuf {
width,
height,
format,
});
}
zwlr_screencopy_frame_v1::Event::BufferDone => {
let _ = data.send(ScreenCopyEvent::BuffersDone);
}
_ => {}
}
}