Skip to content

Commit e193e8d

Browse files
only21milclaude
andcommitted
fix(desktop): retry Linux capture PNGs at level 6 when level 2 is too big
The desktop app rejects capture PNGs over 32 MiB. Level 2 output is a few percent larger than level 6, so a capture that fit before could now fail in the app. Both helpers now encode to memory at level 2, re-encode at level 6 only when that exceeds 32 MiB, and return an error before writing capture.png if level 6 is still too large. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b764c12 commit e193e8d

2 files changed

Lines changed: 92 additions & 19 deletions

File tree

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

Lines changed: 46 additions & 9 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,20 +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-
// The default level 6 dominated capture time. Level 2 is lossless and much faster.
152-
encoder.set_deflate_compression(png::DeflateCompression::Level(2));
153-
encoder.write_header()?.write_image_data(&rgba)?;
148+
.open(directory.join("capture.png"))?
149+
.write_all(&png)?;
154150
Ok(())
155151
}
156152

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+
157173
fn image_size(width: u32, height: u32, stride: u32) -> Result<usize> {
158174
if width == 0 || height == 0 || width > 16384 || height > 16384 || stride < width * 4 {
159175
return Err("Invalid capture dimensions.".into());
@@ -333,4 +349,25 @@ mod tests {
333349
);
334350
assert!(to_rgba(&bytes[..2], 1, 1, 4, wl_shm::Format::Argb8888, false).is_err());
335351
}
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+
}
336373
}

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

Lines changed: 46 additions & 10 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,18 +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-
// The default level 6 dominated capture time. Level 2 is lossless and much faster.
310-
encoder.set_deflate_compression(png::DeflateCompression::Level(2));
311-
let mut image = encoder.write_header()?;
312-
image.write_image_data(&pixels)?;
313-
image.finish()?;
326+
.open(directory.join("capture.png"))?
327+
.write_all(&png)?;
314328
let identity = before.filter(|before| {
315329
window(connection, directory, Some(&before.id))
316330
.ok()
@@ -455,6 +469,28 @@ mod tests {
455469
}
456470
}
457471

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+
458494
#[test]
459495
fn decodes_native_argb_and_row_padding() {
460496
let raw = [0xff112233_u32.to_ne_bytes(), [0; 4]].concat();

0 commit comments

Comments
 (0)