Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make buffers mutable #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions examples/screenshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn main() {
loop {
// Wait until there's a frame.

let buffer = match capturer.frame() {
let mut buffer = match capturer.frame() {
Ok(buffer) => buffer,
Err(error) => {
if error.kind() == WouldBlock {
Expand All @@ -33,8 +33,7 @@ fn main() {

println!("Captured! Saving...");

// Flip the ARGB image into a BGRA image.

// Flip the BGRA image into a RGBA image.
let mut bitflipped = Vec::with_capacity(w * h * 4);
let stride = buffer.len() / h;

Expand All @@ -50,6 +49,17 @@ fn main() {
}
}

// Example doing it in-place with a mutable buffer
assert!(buffer.len() % 4 == 0);
unsafe {
for pixel in buffer.chunks_exact_mut(4) {
pixel.get_unchecked_mut(0..3).reverse();
*pixel.get_unchecked_mut(3) = 255;
}
}
// they're the same
assert_eq!(buffer.to_vec(), bitflipped);

// Save the image.

repng::encode(
Expand Down
10 changes: 8 additions & 2 deletions src/common/x11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,21 @@ impl Capturer {
}
}

pub struct Frame<'a>(&'a [u8]);
pub struct Frame<'a>(&'a mut [u8]);

impl<'a> ops::Deref for Frame<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
fn deref(&self) -> &Self::Target {
self.0
}
}

impl<'a> ops::DerefMut for Frame<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

pub struct Display(x11::Display);

impl Display {
Expand Down
8 changes: 4 additions & 4 deletions src/x11/capturer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub struct Capturer {
display: Display,
shmid: i32,
xcbid: u32,
buffer: *const u8,
buffer: *mut u8,

request: xcb_shm_get_image_cookie_t,
loading: usize,
Expand Down Expand Up @@ -45,7 +45,7 @@ impl Capturer {
libc::shmat(
shmid,
ptr::null(),
libc::SHM_RDONLY
0
)
} as *mut u8;

Expand Down Expand Up @@ -93,12 +93,12 @@ impl Capturer {
&self.display
}

pub fn frame<'b>(&'b mut self) -> &'b [u8] {
pub fn frame<'b>(&'b mut self) -> &'b mut [u8] {
// Get the return value.

let result = unsafe {
let off = self.loading & self.size;
slice::from_raw_parts(
slice::from_raw_parts_mut(
self.buffer.offset(off as isize),
self.size
)
Expand Down