Skip to content

Commit

Permalink
Improve capture performance on macOS (#87)
Browse files Browse the repository at this point in the history
* Simplify BGRA to RGBA conversion

* Pre-allocate buffer in `remove_extra_data`
  • Loading branch information
samrat authored Dec 15, 2023
1 parent 0885ce0 commit 06c6760
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
1 change: 1 addition & 0 deletions src/darwin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ fn capture(display_info: &DisplayInfo, cg_rect: CGRect) -> Result<RgbaImage> {
let height = cg_image.height();
let clean_buf = remove_extra_data(
width,
height,
cg_image.bytes_per_row(),
Vec::from(cg_image.data().bytes()),
);
Expand Down
31 changes: 21 additions & 10 deletions src/image_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ pub fn vec_to_rgba_image(width: u32, height: u32, buf: Vec<u8>) -> Result<RgbaIm

#[cfg(any(target_os = "windows", target_os = "macos", test))]
pub fn bgra_to_rgba_image(width: u32, height: u32, buf: Vec<u8>) -> Result<RgbaImage> {
// convert to rgba
let rgba_buf = buf
.chunks_exact(4)
.take((width * height) as usize)
.flat_map(|bgra| [bgra[2], bgra[1], bgra[0], bgra[3]])
.collect();
let mut rgba_buf = buf.clone();

for (src, dst) in buf.chunks_exact(4).zip(rgba_buf.chunks_exact_mut(4)) {
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
dst[3] = src[3];
}
vec_to_rgba_image(width, height, rgba_buf)
}

Expand All @@ -23,10 +24,19 @@ pub fn bgra_to_rgba_image(width: u32, height: u32, buf: Vec<u8>) -> Result<RgbaI
/// https://github.com/nashaofu/screenshots-rs/issues/29
/// https://github.com/nashaofu/screenshots-rs/issues/38
#[cfg(any(target_os = "macos", test))]
pub fn remove_extra_data(width: usize, bytes_per_row: usize, buf: Vec<u8>) -> Vec<u8> {
buf.chunks_exact(bytes_per_row)
.flat_map(|row| row.split_at(width * 4).0.to_owned())
.collect()
pub fn remove_extra_data(
width: usize,
height: usize,
bytes_per_row: usize,
buf: Vec<u8>,
) -> Vec<u8> {
let extra_bytes_per_row = bytes_per_row - width * 4;
let mut result = Vec::with_capacity(buf.len() - extra_bytes_per_row * height);
for row in buf.chunks_exact(bytes_per_row) {
result.extend_from_slice(&row[..width * 4]);
}

result
}

#[cfg(any(target_os = "linux", test))]
Expand Down Expand Up @@ -60,6 +70,7 @@ mod tests {
#[test]
fn extra_data() {
let clean = remove_extra_data(
2,
2,
9,
vec![
Expand Down

0 comments on commit 06c6760

Please sign in to comment.