Skip to main content

agentmux_srv/server/streamed_browser/screen/
frames.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A frame of the virtual screen as the pane wants it: the same kind byte and JPEG the streamed browser sends
5//! (`pane.rs`), made only when the screen changed since the last one that was sent. The screen says which part of it changed
6//! (the damage extension), so only that part is read; the picture of the whole screen is kept here and each change is written into it.
7
8use std::io::Cursor;
9
10/// The first byte of a frame message (the pane's `FRAME`).
11pub const FRAME: u8 = 1;
12/// The same quality as the streamed browser's screencast.
13const JPEG_QUALITY: u8 = 70;
14
15/// A part of the screen, in pixels.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct Rect {
18    pub x: u16,
19    pub y: u16,
20    pub w: u16,
21    pub h: u16,
22}
23
24impl Rect {
25    /// The whole screen.
26    pub fn whole(w: u16, h: u16) -> Self {
27        Self { x: 0, y: 0, w, h }
28    }
29
30    /// A rectangle as the damage extension reports it, cut to a screen of `screen_w` by `screen_h`; none when nothing of it is on the screen.
31    pub fn clipped(x: i16, y: i16, w: u16, h: u16, screen_w: u16, screen_h: u16) -> Option<Self> {
32        let (x0, y0) = (i32::from(x).max(0), i32::from(y).max(0));
33        let (x1, y1) = ((i32::from(x) + i32::from(w)).min(i32::from(screen_w)), (i32::from(y) + i32::from(h)).min(i32::from(screen_h)));
34        if x1 <= x0 || y1 <= y0 {
35            return None;
36        }
37        Some(Self { x: x0 as u16, y: y0 as u16, w: (x1 - x0) as u16, h: (y1 - y0) as u16 })
38    }
39
40    /// The smallest rectangle that holds both.
41    pub fn union(self, other: Self) -> Self {
42        let (x0, y0) = (self.x.min(other.x), self.y.min(other.y));
43        let (x1, y1) = ((self.x + self.w).max(other.x + other.w), (self.y + self.h).max(other.y + other.h));
44        Self { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
45    }
46}
47
48/// The picture of the whole screen as last read: four bytes a pixel (blue, green, red, one unused), row after row. A part that was read
49/// again is written in, and says whether it was different.
50pub struct Picture {
51    w: usize,
52    h: usize,
53    px: Vec<u8>,
54}
55
56impl Picture {
57    pub fn new(w: u16, h: u16) -> Self {
58        Self { w: usize::from(w), h: usize::from(h), px: vec![0; usize::from(w) * usize::from(h) * 4] }
59    }
60
61    /// The whole picture.
62    pub fn pixels(&self) -> &[u8] {
63        &self.px
64    }
65
66    /// Write `part` (the pixels of `at`, row after row) into the picture. True when any pixel of that part was different; a part that does not
67    /// fit the picture, or came back short, is not written and is not a change.
68    pub fn update(&mut self, at: Rect, part: &[u8]) -> bool {
69        let (x, y, w, h) = (usize::from(at.x), usize::from(at.y), usize::from(at.w), usize::from(at.h));
70        if x + w > self.w || y + h > self.h || part.len() < w * h * 4 {
71            return false;
72        }
73        let mut changed = false;
74        for row in 0..h {
75            let (from, to) = (row * w * 4, ((y + row) * self.w + x) * 4);
76            let (new, old) = (&part[from..from + w * 4], &mut self.px[to..to + w * 4]);
77            if new != old {
78                old.copy_from_slice(new);
79                changed = true;
80            }
81        }
82        changed
83    }
84}
85
86/// The screen's pixels as the X server hands them (blue, green, red, one unused byte per pixel) as one frame message:
87/// the kind byte, then a JPEG.
88pub fn frame_message(bgrx: &[u8], w: u32, h: u32) -> Result<Vec<u8>, String> {
89    let pixels = (w as usize) * (h as usize);
90    if bgrx.len() < pixels * 4 {
91        return Err(format!("the screen came back with {} bytes, not {}", bgrx.len(), pixels * 4));
92    }
93    let mut rgb = Vec::with_capacity(pixels * 3);
94    for p in bgrx[..pixels * 4].chunks_exact(4) {
95        rgb.extend_from_slice(&[p[2], p[1], p[0]]);
96    }
97    let mut out = Cursor::new(vec![FRAME]);
98    out.set_position(1);
99    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY)
100        .encode(&rgb, w, h, image::ExtendedColorType::Rgb8)
101        .map_err(|e| format!("a frame could not be made: {e}"))?;
102    Ok(out.into_inner())
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    fn screen(w: u32, h: u32, bgrx: [u8; 4]) -> Vec<u8> {
110        bgrx.iter().copied().cycle().take((w * h * 4) as usize).collect()
111    }
112
113    #[test]
114    fn a_part_that_is_the_same_is_no_change_and_one_that_differs_is_written_in() {
115        let mut p = Picture::new(4, 4);
116        let all = Rect::whole(4, 4);
117        assert!(p.update(all, &screen(4, 4, [0, 0, 255, 0])), "the first read of a coloured screen is a change from the blank picture");
118        assert!(!p.update(all, &screen(4, 4, [0, 0, 255, 0])), "the same screen is not a change");
119        let part = Rect { x: 1, y: 2, w: 2, h: 1 };
120        assert!(p.update(part, &screen(2, 1, [0, 255, 0, 0])));
121        assert!(!p.update(part, &screen(2, 1, [0, 255, 0, 0])));
122        let px = p.pixels();
123        let at = |x: usize, y: usize| &px[(y * 4 + x) * 4..(y * 4 + x) * 4 + 3];
124        assert_eq!(at(1, 2), [0, 255, 0], "the part is written where it was read");
125        assert_eq!(at(2, 2), [0, 255, 0]);
126        assert_eq!(at(0, 2), [0, 0, 255], "what is around it is untouched");
127        assert_eq!(at(3, 2), [0, 0, 255]);
128        assert_eq!(at(1, 1), [0, 0, 255]);
129    }
130
131    #[test]
132    fn a_part_that_does_not_fit_or_came_back_short_is_ignored() {
133        let mut p = Picture::new(4, 4);
134        assert!(!p.update(Rect { x: 3, y: 3, w: 2, h: 2 }, &screen(2, 2, [1, 2, 3, 0])), "off the screen");
135        assert!(!p.update(Rect::whole(4, 4), &[1, 2, 3]), "short");
136        assert!(p.pixels().iter().all(|b| *b == 0));
137    }
138
139    #[test]
140    fn damage_is_cut_to_the_screen_and_joined_into_one_rectangle() {
141        assert_eq!(Rect::clipped(-5, -5, 10, 10, 100, 80), Some(Rect { x: 0, y: 0, w: 5, h: 5 }));
142        assert_eq!(Rect::clipped(90, 70, 50, 50, 100, 80), Some(Rect { x: 90, y: 70, w: 10, h: 10 }));
143        assert_eq!(Rect::clipped(100, 0, 10, 10, 100, 80), None, "right of the screen");
144        assert_eq!(Rect::clipped(0, 0, 0, 10, 100, 80), None, "empty");
145        let a = Rect { x: 10, y: 10, w: 5, h: 5 };
146        let b = Rect { x: 30, y: 2, w: 4, h: 4 };
147        assert_eq!(a.union(b), Rect { x: 10, y: 2, w: 24, h: 13 });
148        assert_eq!(a.union(a), a);
149    }
150
151    #[test]
152    fn a_frame_is_the_kind_byte_and_a_jpeg_of_the_right_colour_and_size() {
153        // The server's order is blue, green, red: this screen is red.
154        let m = frame_message(&screen(16, 8, [0, 0, 255, 0]), 16, 8).unwrap();
155        assert_eq!(m[0], FRAME);
156        let img = image::load_from_memory_with_format(&m[1..], image::ImageFormat::Jpeg).unwrap().to_rgb8();
157        assert_eq!((img.width(), img.height()), (16, 8));
158        let p = img.get_pixel(8, 4);
159        assert!(p[0] > 200 && p[1] < 60 && p[2] < 60, "{p:?} is not red");
160    }
161
162    #[test]
163    fn a_short_screen_is_refused_in_words() {
164        let e = frame_message(&[0; 10], 4, 4).unwrap_err();
165        assert!(e.contains("not 64"), "{e}");
166    }
167}