Skip to content

Commit 651e390

Browse files
only21milclaudemaria-rcks
authored
perf(desktop): speed up Hyprland and KDE SnapShots (#23137)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 85133dc commit 651e390

4 files changed

Lines changed: 100 additions & 15 deletions

File tree

‎native/hyprland-snap-shot/src/capture.rs‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use smithay_client_toolkit::{
2525
};
2626
use std::{
2727
fs::OpenOptions,
28-
io::BufWriter,
28+
io::Write,
2929
os::unix::fs::OpenOptionsExt,
3030
path::Path,
3131
time::{Duration, Instant},
@@ -140,18 +140,36 @@ pub(super) fn capture_on(connection: Connection, address: u64, directory: &Path)
140140
pixels.format,
141141
state.inverted,
142142
)?;
143-
let file = OpenOptions::new()
143+
let png = encode_png(&rgba, pixels.width, pixels.height, MAX_PNG_BYTES)?;
144+
OpenOptions::new()
144145
.write(true)
145146
.create_new(true)
146147
.mode(0o600)
147-
.open(directory.join("capture.png"))?;
148-
let mut encoder = png::Encoder::new(BufWriter::new(file), pixels.width, pixels.height);
149-
encoder.set_color(png::ColorType::Rgba);
150-
encoder.set_depth(png::BitDepth::Eight);
151-
encoder.write_header()?.write_image_data(&rgba)?;
148+
.open(directory.join("capture.png"))?
149+
.write_all(&png)?;
152150
Ok(())
153151
}
154152

153+
/// The desktop app rejects larger capture PNGs (`linuxCaptureSession.ts`).
154+
const MAX_PNG_BYTES: usize = 32 * 1024 * 1024;
155+
156+
/// Level 6 dominated capture time, so encode at the much faster level 2 and fall back
157+
/// to level 6 only when level 2's slightly larger output would be rejected.
158+
fn encode_png(rgba: &[u8], width: u32, height: u32, limit: usize) -> Result<Vec<u8>> {
159+
for level in [2, 6] {
160+
let mut png = Vec::new();
161+
let mut encoder = png::Encoder::new(&mut png, width, height);
162+
encoder.set_color(png::ColorType::Rgba);
163+
encoder.set_depth(png::BitDepth::Eight);
164+
encoder.set_deflate_compression(png::DeflateCompression::Level(level));
165+
encoder.write_header()?.write_image_data(rgba)?;
166+
if png.len() <= limit {
167+
return Ok(png);
168+
}
169+
}
170+
Err("Capture is too large.".into())
171+
}
172+
155173
fn image_size(width: u32, height: u32, stride: u32) -> Result<usize> {
156174
if width == 0 || height == 0 || width > 16384 || height > 16384 || stride < width * 4 {
157175
return Err("Invalid capture dimensions.".into());
@@ -331,4 +349,25 @@ mod tests {
331349
);
332350
assert!(to_rgba(&bytes[..2], 1, 1, 4, wl_shm::Format::Argb8888, false).is_err());
333351
}
352+
#[test]
353+
fn falls_back_to_smaller_png_when_fast_encode_exceeds_limit() {
354+
let (width, height) = (256, 256);
355+
let rgba: Vec<u8> = (0..width * height * 4)
356+
.map(|i| (((i / 4) % 251) ^ (i % 7)) as u8)
357+
.collect();
358+
let decode = |png: &[u8]| {
359+
let mut reader = png::Decoder::new(std::io::Cursor::new(png))
360+
.read_info()
361+
.unwrap();
362+
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
363+
reader.next_frame(&mut pixels).unwrap();
364+
pixels
365+
};
366+
let fast = encode_png(&rgba, width, height, usize::MAX).unwrap();
367+
let fallback = encode_png(&rgba, width, height, fast.len() - 1).unwrap();
368+
assert!(fallback.len() < fast.len());
369+
assert_eq!(decode(&fast), rgba);
370+
assert_eq!(decode(&fallback), rgba);
371+
assert!(encode_png(&rgba, width, height, fallback.len() - 1).is_err());
372+
}
334373
}

‎native/hyprland-snap-shot/src/transport_tests.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,10 @@ fn exports_exact_window_over_real_fd_transport() {
363363
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
364364
reader.next_frame(&mut pixels).unwrap();
365365
assert_eq!(pixels, [10, 20, 30, 255, 40, 50, 60, 255]);
366+
let png = std::fs::read(directory.path().join("capture.png")).unwrap();
367+
let idat = png.windows(4).position(|tag| tag == b"IDAT").unwrap();
368+
// zlib FLEVEL 1 selects levels 2-5; the slow default level 6 reports 2.
369+
assert_eq!(png[idat + 5] >> 6, 1);
366370
}
367371
#[test]
368372
fn failed_export_produces_no_image_and_no_second_capture() {

‎native/kde-snap-shot/src/main.rs‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,26 @@ fn rgba(raw: &[u8], width: usize, height: usize, stride: usize, format: usize) -
261261
Ok(output)
262262
}
263263

264+
/// The desktop app rejects larger capture PNGs (`linuxCaptureSession.ts`).
265+
const MAX_PNG_BYTES: usize = 32 * 1024 * 1024;
266+
267+
/// Level 6 dominated capture time, so encode at the much faster level 2 and fall back
268+
/// to level 6 only when level 2's slightly larger output would be rejected.
269+
fn encode_png(rgba: &[u8], width: u32, height: u32, limit: usize) -> Result<Vec<u8>> {
270+
for level in [2, 6] {
271+
let mut png = Vec::new();
272+
let mut encoder = png::Encoder::new(&mut png, width, height);
273+
encoder.set_color(png::ColorType::Rgba);
274+
encoder.set_depth(png::BitDepth::Eight);
275+
encoder.set_deflate_compression(png::DeflateCompression::Level(level));
276+
encoder.write_header()?.write_image_data(rgba)?;
277+
if png.len() <= limit {
278+
return Ok(png);
279+
}
280+
}
281+
Err("Screenshot too large".into())
282+
}
283+
264284
fn capture(connection: &Connection, directory: &Path) -> Result<Option<Window>> {
265285
// Lack of scripting only loses identity/text; never guess which app was captured.
266286
let before = window(connection, directory, None).ok().flatten();
@@ -299,16 +319,12 @@ fn capture(connection: &Connection, directory: &Path) -> Result<Option<Window>>
299319
let mut raw = vec![0; bytes];
300320
reader.read_exact(&mut raw)?;
301321
let pixels = rgba(&raw, width, height, stride, uint(&metadata, "format")?)?;
302-
let image = OpenOptions::new()
322+
let png = encode_png(&pixels, width as u32, height as u32, MAX_PNG_BYTES)?;
323+
OpenOptions::new()
303324
.write(true)
304325
.create_new(true)
305-
.open(directory.join("capture.png"))?;
306-
let mut encoder = png::Encoder::new(image, width as u32, height as u32);
307-
encoder.set_color(png::ColorType::Rgba);
308-
encoder.set_depth(png::BitDepth::Eight);
309-
let mut image = encoder.write_header()?;
310-
image.write_image_data(&pixels)?;
311-
image.finish()?;
326+
.open(directory.join("capture.png"))?
327+
.write_all(&png)?;
312328
let identity = before.filter(|before| {
313329
window(connection, directory, Some(&before.id))
314330
.ok()
@@ -453,6 +469,28 @@ mod tests {
453469
}
454470
}
455471

472+
#[test]
473+
fn falls_back_to_smaller_png_when_fast_encode_exceeds_limit() {
474+
let (width, height) = (256, 256);
475+
let rgba: Vec<u8> = (0..width * height * 4)
476+
.map(|i| (((i / 4) % 251) ^ (i % 7)) as u8)
477+
.collect();
478+
let decode = |png: &[u8]| {
479+
let mut reader = png::Decoder::new(std::io::Cursor::new(png))
480+
.read_info()
481+
.unwrap();
482+
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
483+
reader.next_frame(&mut pixels).unwrap();
484+
pixels
485+
};
486+
let fast = encode_png(&rgba, width, height, usize::MAX).unwrap();
487+
let fallback = encode_png(&rgba, width, height, fast.len() - 1).unwrap();
488+
assert!(fallback.len() < fast.len());
489+
assert_eq!(decode(&fast), rgba);
490+
assert_eq!(decode(&fallback), rgba);
491+
assert!(encode_png(&rgba, width, height, fallback.len() - 1).is_err());
492+
}
493+
456494
#[test]
457495
fn decodes_native_argb_and_row_padding() {
458496
let raw = [0xff112233_u32.to_ne_bytes(), [0; 4]].concat();

‎native/kde-snap-shot/src/transport_tests.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,10 @@ fn captures_pinned_window_through_real_fd_and_cleans_scripts() {
247247
let mut pixels = vec![0; decoder.output_buffer_size().unwrap()];
248248
decoder.next_frame(&mut pixels).unwrap();
249249
assert_eq!(pixels, [0x11, 0x22, 0x33, 255, 0x44, 0x55, 0x66, 255]);
250+
let png = std::fs::read(f.directory.join("capture.png")).unwrap();
251+
let idat = png.windows(4).position(|tag| tag == b"IDAT").unwrap();
252+
// zlib FLEVEL 1 selects levels 2-5; the slow default level 6 reports 2.
253+
assert_eq!(png[idat + 5] >> 6, 1);
250254
}
251255

252256
#[test]

0 commit comments

Comments
 (0)