TypeScript
perf(desktop): speed up Hyprland and KDE SnapShots (#23137)
Victor Vogel651e390ad262
diff --git a/native/hyprland-snap-shot/src/capture.rs b/native/hyprland-snap-shot/src/capture.rsindex 9e8e74bed67..5519b4249e9 100644--- a/native/hyprland-snap-shot/src/capture.rs+++ b/native/hyprland-snap-shot/src/capture.rs@@ -25,7 +25,7 @@ use smithay_client_toolkit::{};use std::{fs::OpenOptions,- io::BufWriter,+ io::Write,os::unix::fs::OpenOptionsExt,path::Path,time::{Duration, Instant},@@ -140,18 +140,36 @@ pub(super) fn capture_on(connection: Connection, address: u64, directory: &Path)pixels.format,state.inverted,)?;- let file = OpenOptions::new()+ let png = encode_png(&rgba, pixels.width, pixels.height, MAX_PNG_BYTES)?;+ OpenOptions::new().write(true).create_new(true).mode(0o600)- .open(directory.join("capture.png"))?;- let mut encoder = png::Encoder::new(BufWriter::new(file), pixels.width, pixels.height);- encoder.set_color(png::ColorType::Rgba);- encoder.set_depth(png::BitDepth::Eight);- encoder.write_header()?.write_image_data(&rgba)?;+ .open(directory.join("capture.png"))?+ .write_all(&png)?;Ok(())}+/// The desktop app rejects larger capture PNGs (`linuxCaptureSession.ts`).+const MAX_PNG_BYTES: usize = 32 * 1024 * 1024;++/// Level 6 dominated capture time, so encode at the much faster level 2 and fall back+/// to level 6 only when level 2's slightly larger output would be rejected.+fn encode_png(rgba: &[u8], width: u32, height: u32, limit: usize) -> Result<Vec<u8>> {+ for level in [2, 6] {+ let mut png = Vec::new();+ let mut encoder = png::Encoder::new(&mut png, width, height);+ encoder.set_color(png::ColorType::Rgba);+ encoder.set_depth(png::BitDepth::Eight);+ encoder.set_deflate_compression(png::DeflateCompression::Level(level));+ encoder.write_header()?.write_image_data(rgba)?;+ if png.len() <= limit {+ return Ok(png);+ }+ }+ Err("Capture is too large.".into())+}+fn image_size(width: u32, height: u32, stride: u32) -> Result<usize> {if width == 0 || height == 0 || width > 16384 || height > 16384 || stride < width * 4 {return Err("Invalid capture dimensions.".into());@@ -331,4 +349,25 @@ mod tests {);assert!(to_rgba(&bytes[..2], 1, 1, 4, wl_shm::Format::Argb8888, false).is_err());}+ #[test]+ fn falls_back_to_smaller_png_when_fast_encode_exceeds_limit() {+ let (width, height) = (256, 256);+ let rgba: Vec<u8> = (0..width * height * 4)+ .map(|i| (((i / 4) % 251) ^ (i % 7)) as u8)+ .collect();+ let decode = |png: &[u8]| {+ let mut reader = png::Decoder::new(std::io::Cursor::new(png))+ .read_info()+ .unwrap();+ let mut pixels = vec![0; reader.output_buffer_size().unwrap()];+ reader.next_frame(&mut pixels).unwrap();+ pixels+ };+ let fast = encode_png(&rgba, width, height, usize::MAX).unwrap();+ let fallback = encode_png(&rgba, width, height, fast.len() - 1).unwrap();+ assert!(fallback.len() < fast.len());+ assert_eq!(decode(&fast), rgba);+ assert_eq!(decode(&fallback), rgba);+ assert!(encode_png(&rgba, width, height, fallback.len() - 1).is_err());+ }}diff --git a/native/hyprland-snap-shot/src/transport_tests.rs b/native/hyprland-snap-shot/src/transport_tests.rsindex e215cabcfe3..2f9da9764d9 100644--- a/native/hyprland-snap-shot/src/transport_tests.rs+++ b/native/hyprland-snap-shot/src/transport_tests.rs@@ -363,6 +363,10 @@ fn exports_exact_window_over_real_fd_transport() {let mut pixels = vec![0; reader.output_buffer_size().unwrap()];reader.next_frame(&mut pixels).unwrap();assert_eq!(pixels, [10, 20, 30, 255, 40, 50, 60, 255]);+ let png = std::fs::read(directory.path().join("capture.png")).unwrap();+ let idat = png.windows(4).position(|tag| tag == b"IDAT").unwrap();+ // zlib FLEVEL 1 selects levels 2-5; the slow default level 6 reports 2.+ assert_eq!(png[idat + 5] >> 6, 1);}#[test]fn failed_export_produces_no_image_and_no_second_capture() {diff --git a/native/kde-snap-shot/src/main.rs b/native/kde-snap-shot/src/main.rsindex 49b85a3bb49..ec125677939 100644--- a/native/kde-snap-shot/src/main.rs+++ b/native/kde-snap-shot/src/main.rs@@ -261,6 +261,26 @@ fn rgba(raw: &[u8], width: usize, height: usize, stride: usize, format: usize) -Ok(output)}+/// The desktop app rejects larger capture PNGs (`linuxCaptureSession.ts`).+const MAX_PNG_BYTES: usize = 32 * 1024 * 1024;++/// Level 6 dominated capture time, so encode at the much faster level 2 and fall back+/// to level 6 only when level 2's slightly larger output would be rejected.+fn encode_png(rgba: &[u8], width: u32, height: u32, limit: usize) -> Result<Vec<u8>> {+ for level in [2, 6] {+ let mut png = Vec::new();+ let mut encoder = png::Encoder::new(&mut png, width, height);+ encoder.set_color(png::ColorType::Rgba);+ encoder.set_depth(png::BitDepth::Eight);+ encoder.set_deflate_compression(png::DeflateCompression::Level(level));+ encoder.write_header()?.write_image_data(rgba)?;+ if png.len() <= limit {+ return Ok(png);+ }+ }+ Err("Screenshot too large".into())+}+fn capture(connection: &Connection, directory: &Path) -> Result<Option<Window>> {// Lack of scripting only loses identity/text; never guess which app was captured.let before = window(connection, directory, None).ok().flatten();@@ -299,16 +319,12 @@ fn capture(connection: &Connection, directory: &Path) -> Result<Option<Window>>let mut raw = vec![0; bytes];reader.read_exact(&mut raw)?;let pixels = rgba(&raw, width, height, stride, uint(&metadata, "format")?)?;- let image = OpenOptions::new()+ let png = encode_png(&pixels, width as u32, height as u32, MAX_PNG_BYTES)?;+ OpenOptions::new().write(true).create_new(true)- .open(directory.join("capture.png"))?;- let mut encoder = png::Encoder::new(image, width as u32, height as u32);- encoder.set_color(png::ColorType::Rgba);- encoder.set_depth(png::BitDepth::Eight);- let mut image = encoder.write_header()?;- image.write_image_data(&pixels)?;- image.finish()?;+ .open(directory.join("capture.png"))?+ .write_all(&png)?;let identity = before.filter(|before| {window(connection, directory, Some(&before.id)).ok()@@ -453,6 +469,28 @@ mod tests {}}+ #[test]+ fn falls_back_to_smaller_png_when_fast_encode_exceeds_limit() {+ let (width, height) = (256, 256);+ let rgba: Vec<u8> = (0..width * height * 4)+ .map(|i| (((i / 4) % 251) ^ (i % 7)) as u8)+ .collect();+ let decode = |png: &[u8]| {+ let mut reader = png::Decoder::new(std::io::Cursor::new(png))+ .read_info()+ .unwrap();+ let mut pixels = vec![0; reader.output_buffer_size().unwrap()];+ reader.next_frame(&mut pixels).unwrap();+ pixels+ };+ let fast = encode_png(&rgba, width, height, usize::MAX).unwrap();+ let fallback = encode_png(&rgba, width, height, fast.len() - 1).unwrap();+ assert!(fallback.len() < fast.len());+ assert_eq!(decode(&fast), rgba);+ assert_eq!(decode(&fallback), rgba);+ assert!(encode_png(&rgba, width, height, fallback.len() - 1).is_err());+ }+#[test]fn decodes_native_argb_and_row_padding() {let raw = [0xff112233_u32.to_ne_bytes(), [0; 4]].concat();diff --git a/native/kde-snap-shot/src/transport_tests.rs b/native/kde-snap-shot/src/transport_tests.rsindex efc737a1cd5..83e72556c0d 100644--- a/native/kde-snap-shot/src/transport_tests.rs+++ b/native/kde-snap-shot/src/transport_tests.rs@@ -247,6 +247,10 @@ fn captures_pinned_window_through_real_fd_and_cleans_scripts() {let mut pixels = vec![0; decoder.output_buffer_size().unwrap()];decoder.next_frame(&mut pixels).unwrap();assert_eq!(pixels, [0x11, 0x22, 0x33, 255, 0x44, 0x55, 0x66, 255]);+ let png = std::fs::read(f.directory.join("capture.png")).unwrap();+ let idat = png.windows(4).position(|tag| tag == b"IDAT").unwrap();+ // zlib FLEVEL 1 selects levels 2-5; the slow default level 6 reports 2.+ assert_eq!(png[idat + 5] >> 6, 1);}#[test]