Skip to main content

crabshell_render/
capture.rs

1//! Captured frames: a compositor's buffer turned into the frame a
2//! screencopy view keeps, scaled down so a small view of a large output
3//! keeps a small frame.
4
5use std::rc::Rc;
6
7use crabshell_ui::{CaptureFrame, Fit};
8use tiny_skia::PixmapRef;
9
10use crate::PixelFormat;
11use crate::icons::halve;
12use crate::images;
13
14/// How the compositor turned a captured buffer, as `wl_output.transform`
15/// says: rotated counter-clockwise by a quarter turn or more, and flipped
16/// around the vertical axis before that.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18pub struct Turn {
19  /// Quarter turns counter-clockwise, 0 to 3.
20  pub quarters: u8,
21  /// Flipped around the vertical axis first.
22  pub flipped: bool,
23}
24
25impl Turn {
26  /// Whether the buffer's sides are swapped against what shows.
27  fn sideways(self) -> bool {
28    self.quarters % 2 == 1
29  }
30}
31
32/// The frame a view keeps of a `width` by `height` buffer of premultiplied
33/// pixels in `format`, which the compositor `turn`ed. With `opaque`, as in
34/// `XRGB8888` and `XBGR8888`, the fourth byte is ignored. The frame is
35/// turned back upright and scaled down to [`frame_size`] for `cover`. Its
36/// logical size is the source's upright size in pixels, for the platform
37/// to replace with the source's logical one. `None` if `pixels` doesn't
38/// hold `width * height` pixels.
39pub fn capture_frame(
40  pixels: &[u8],
41  width: u32,
42  height: u32,
43  format: PixelFormat,
44  opaque: bool,
45  turn: Turn,
46  cover: (u32, u32),
47) -> Option<CaptureFrame> {
48  let source = PixmapRef::from_bytes(pixels, width, height)?;
49  // Scaled while still turned, so the box is turned to match.
50  let cover = if turn.sideways() {
51    (cover.1, cover.0)
52  } else {
53    cover
54  };
55  let (kept_width, kept_height) = frame_size((width, height), cover);
56  // Halving averages, so the fourth byte can be filled in after it, in
57  // a quarter of the pixels; bicubic scaling would clamp to it first.
58  let mut first = if kept_width * 2 <= width && kept_height * 2 <= height {
59    halve(source).ok()?
60  } else {
61    source.to_owned()
62  };
63  if opaque {
64    for pixel in first.data_mut().as_chunks_mut::<4>().0 {
65      pixel[3] = 255;
66    }
67  }
68  // Scaling treats the four channels alike, so the pixels are swapped
69  // into RGBA only once they are few.
70  let mut kept = if (first.width(), first.height()) == (kept_width, kept_height) {
71    first
72  } else {
73    images::scale(first.as_ref(), kept_width, kept_height, Fit::Fill).ok()?
74  };
75  if format == PixelFormat::Argb8888 {
76    for pixel in kept.data_mut().as_chunks_mut::<4>().0 {
77      pixel.swap(0, 2);
78    }
79  }
80  let (logical_width, logical_height) = match turn.sideways() {
81    true => (height, width),
82    false => (width, height),
83  };
84  let (width, height, rgba) = upright(kept_width, kept_height, kept.take(), turn);
85  Some(CaptureFrame {
86    width,
87    height,
88    logical_width,
89    logical_height,
90    rgba: Rc::from(rgba),
91  })
92}
93
94/// A `width` by `height` image the compositor `turn`ed, turned back.
95fn upright(width: u32, height: u32, rgba: Vec<u8>, turn: Turn) -> (u32, u32, Vec<u8>) {
96  if turn == Turn::default() {
97    return (width, height, rgba);
98  }
99  let (w, h) = (width as usize, height as usize);
100  let (out_w, out_h) = if turn.sideways() { (h, w) } else { (w, h) };
101  let mut out = vec![0; rgba.len()];
102  for y in 0..out_h {
103    for x in 0..out_w {
104      // Where the shown pixel is in the buffer: undoing the turn is the
105      // turn's inverse, then the flip, as the protocol applies the flip
106      // first.
107      let (bx, by) = match turn.quarters % 4 {
108        0 => (x, y),
109        1 => (y, h - 1 - x),
110        2 => (w - 1 - x, h - 1 - y),
111        _ => (w - 1 - y, x),
112      };
113      let bx = if turn.flipped { w - 1 - bx } else { bx };
114      let (from, to) = ((by * w + bx) * 4, (y * out_w + x) * 4);
115      out[to..to + 4].copy_from_slice(&rgba[from..from + 4]);
116    }
117  }
118  (out_w as u32, out_h as u32, out)
119}
120
121/// The size a `source` sized frame is kept at to show in a box of
122/// `cover` pixels: scaled down, keeping its shape, to the smallest size
123/// that still covers the box, so any fit draws it without scaling up. It
124/// is never scaled up, and keeps at least one pixel a side.
125pub fn frame_size(source: (u32, u32), cover: (u32, u32)) -> (u32, u32) {
126  let across = f64::from(cover.0) / f64::from(source.0.max(1));
127  let down = f64::from(cover.1) / f64::from(source.1.max(1));
128  let factor = across.max(down).min(1.0);
129  // `as` saturates, and the factor is at most 1, so this stays in range.
130  let side = |length: u32| ((f64::from(length) * factor).round() as u32).max(1);
131  (side(source.0), side(source.1))
132}