Skip to main content

brep_app/stream/
encode.rs

1//! The picture side of the stream: 64 px tiles, damage generations, and the
2//! per-client plan of which tiles to send in which codec.
3use std::time::{Duration, Instant};
4
5pub const TILE: u32 = 64;
6pub const CODEC_PNG: u8 = 1;
7pub const CODEC_JPEG: u8 = 2;
8/// The 3D viewport counts as moving this long after its tiles last changed;
9/// after that its lossy tiles are re-sent lossless.
10pub const SETTLE: Duration = Duration::from_millis(150);
11
12/// The latest frame, cut into tiles, with the generation each tile last
13/// changed in. Generations only grow, across sizes too, so a client's
14/// record of what it holds stays comparable.
15pub struct Screen {
16    pub w: u32,
17    pub h: u32,
18    /// Straight RGBA, row-major.
19    pub rgba: Vec<u8>,
20    cols: u32,
21    rows: u32,
22    pub gens: Vec<u64>,
23    gen: u64,
24    /// Generation at which the size last changed: a client holding less
25    /// gets a keyframe.
26    pub size_gen: u64,
27    /// The 3D viewport in pixels `[x0, y0, x1, y1]`.
28    view: Option<[u32; 4]>,
29    /// Until when the viewport counts as moving.
30    moving_until: Option<Instant>,
31    /// When each tile last changed: a lossy copy of it is refreshed once it
32    /// has been still for [`SETTLE`].
33    changed_at: Vec<Instant>,
34    /// When the last change of any tile settles (the host wakes for refreshes then).
35    settle_at: Option<Instant>,
36}
37
38/// On a slow link, at most this many lossless refresh tiles go in one frame:
39/// a frame that answers input never waits behind a large refresh.
40pub const SLOW_REFRESH_TILES: usize = 6;
41
42impl Default for Screen {
43    fn default() -> Self {
44        Screen {
45            w: 0,
46            h: 0,
47            rgba: Vec::new(),
48            cols: 0,
49            rows: 0,
50            gens: Vec::new(),
51            gen: 0,
52            size_gen: 0,
53            view: None,
54            moving_until: None,
55            changed_at: Vec::new(),
56            settle_at: None,
57        }
58    }
59}
60
61impl Screen {
62    pub fn tiles(&self) -> usize {
63        (self.cols * self.rows) as usize
64    }
65
66    pub fn has_frame(&self) -> bool {
67        self.w > 0 && self.h > 0
68    }
69
70    /// `(x, y, w, h)` of tile `i` in pixels.
71    pub fn rect(&self, i: usize) -> (u32, u32, u32, u32) {
72        let (cx, cy) = (i as u32 % self.cols, i as u32 / self.cols);
73        let (x, y) = (cx * TILE, cy * TILE);
74        (x, y, TILE.min(self.w - x), TILE.min(self.h - y))
75    }
76
77    fn in_view(&self, i: usize) -> bool {
78        let Some([x0, y0, x1, y1]) = self.view else { return false };
79        let (x, y, w, h) = self.rect(i);
80        x >= x0 && y >= y0 && x + w <= x1 && y + h <= y1
81    }
82
83    /// Whether the viewport is still moving at `now`.
84    pub fn moving(&self, now: Instant) -> bool {
85        self.moving_until.is_some_and(|t| now < t)
86    }
87
88    /// When the last change settles (lossy tiles are then refreshed).
89    pub fn settles_at(&self) -> Option<Instant> {
90        self.settle_at
91    }
92
93    /// Whether tile `i` has been still long enough for a lossless refresh.
94    fn settled(&self, i: usize, now: Instant) -> bool {
95        now >= self.changed_at[i] + SETTLE && !(self.in_view(i) && self.moving(now))
96    }
97
98    /// Take a new frame; returns how many tiles changed.
99    pub fn update(&mut self, w: u32, h: u32, rgba: Vec<u8>, view: Option<[u32; 4]>, now: Instant) -> usize {
100        debug_assert_eq!(rgba.len(), (w * h * 4) as usize);
101        self.gen += 1;
102        self.view = view;
103        if w != self.w || h != self.h {
104            self.w = w;
105            self.h = h;
106            self.cols = w.div_ceil(TILE);
107            self.rows = h.div_ceil(TILE);
108            self.gens = vec![self.gen; self.tiles()];
109            self.changed_at = vec![now; self.tiles()];
110            self.settle_at = Some(now + SETTLE);
111            self.size_gen = self.gen;
112            self.rgba = rgba;
113            return self.tiles();
114        }
115        let mut changed = 0;
116        let mut view_changed = false;
117        let stride = (w * 4) as usize;
118        for i in 0..self.tiles() {
119            let (x, y, tw, th) = self.rect(i);
120            let differs = (y..y + th).any(|row| {
121                let a = row as usize * stride + x as usize * 4;
122                let b = a + tw as usize * 4;
123                self.rgba[a..b] != rgba[a..b]
124            });
125            if differs {
126                self.gens[i] = self.gen;
127                self.changed_at[i] = now;
128                changed += 1;
129                view_changed |= self.in_view(i);
130            }
131        }
132        if view_changed {
133            self.moving_until = Some(now + SETTLE);
134        }
135        if changed > 0 {
136            self.settle_at = Some(now + SETTLE);
137        }
138        self.rgba = rgba;
139        changed
140    }
141
142    /// Encode tile `i`.
143    pub fn encode(&self, i: usize, codec: u8, jpeg_quality: u8) -> Vec<u8> {
144        let (x, y, w, h) = self.rect(i);
145        let stride = (self.w * 4) as usize;
146        let mut out = Vec::new();
147        if codec == CODEC_JPEG {
148            let mut rgb = Vec::with_capacity((w * h * 3) as usize);
149            for row in y..y + h {
150                let a = row as usize * stride + x as usize * 4;
151                for px in self.rgba[a..a + w as usize * 4].chunks_exact(4) {
152                    rgb.extend_from_slice(&px[..3]);
153                }
154            }
155            let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, jpeg_quality.clamp(1, 100));
156            let _ = image::ImageEncoder::write_image(encoder, &rgb, w, h, image::ExtendedColorType::Rgb8);
157        } else {
158            let mut px = Vec::with_capacity((w * h * 4) as usize);
159            for row in y..y + h {
160                let a = row as usize * stride + x as usize * 4;
161                px.extend_from_slice(&self.rgba[a..a + w as usize * 4]);
162            }
163            let encoder = image::codecs::png::PngEncoder::new_with_quality(&mut out, image::codecs::png::CompressionType::Fast, image::codecs::png::FilterType::Sub);
164            let _ = image::ImageEncoder::write_image(encoder, &px, w, h, image::ExtendedColorType::Rgba8);
165        }
166        out
167    }
168}
169
170/// What one client holds: per tile, the generation it was sent and whether
171/// that copy was lossy.
172#[derive(Default)]
173pub struct Held {
174    have: Vec<u64>,
175    lossy: Vec<bool>,
176    size_gen: u64,
177}
178
179impl Held {
180    /// Whether this client holds lossy tiles a settled viewport owes it.
181    pub fn owes_refresh(&self) -> bool {
182        self.lossy.iter().any(|l| *l)
183    }
184
185    /// Plan the next frame for this client and record it as held: the tiles
186    /// newer than what it has (all of them after a size change or for a new
187    /// client), plus a lossless copy of each lossy tile once the viewport
188    /// settled. Returns `(keyframe, [(tile, codec)])`.
189    pub fn plan(&mut self, screen: &Screen, now: Instant, slow: bool) -> (bool, Vec<(usize, u8)>) {
190        let n = screen.tiles();
191        let keyframe = self.size_gen != screen.size_gen || self.have.len() != n;
192        if keyframe {
193            self.have = vec![0; n];
194            self.lossy = vec![false; n];
195            self.size_gen = screen.size_gen;
196        }
197        let moving = screen.moving(now);
198        let mut tiles = Vec::new();
199        let mut refreshes = 0;
200        for i in 0..n {
201            let stale = screen.gens[i] > self.have[i];
202            let mut refresh = !stale && self.lossy[i] && screen.settled(i, now);
203            if refresh && slow {
204                // In chunks: an input's frame waits behind one chunk at most.
205                refresh = refreshes < SLOW_REFRESH_TILES;
206                refreshes += usize::from(refresh);
207            }
208            if !stale && !refresh {
209                continue;
210            }
211            // Lossy: the moving 3D view, and on a slow link every change
212            // (refreshed lossless once it has been still).
213            let lossy = stale && (slow || (moving && !keyframe && screen.in_view(i)));
214            let codec = if lossy { CODEC_JPEG } else { CODEC_PNG };
215            self.have[i] = screen.gens[i];
216            self.lossy[i] = lossy;
217            tiles.push((i, codec));
218        }
219        (keyframe, tiles)
220    }
221}
222
223/// The binary frame message.
224pub fn frame_message(screen: &Screen, seq: u32, keyframe: bool, tiles: &[(usize, u8, std::sync::Arc<Vec<u8>>)]) -> Vec<u8> {
225    let size: usize = tiles.iter().map(|t| 14 + t.2.len()).sum();
226    let mut m = Vec::with_capacity(12 + size);
227    m.push(1u8);
228    m.push(u8::from(keyframe));
229    m.extend_from_slice(&(tiles.len() as u16).to_le_bytes());
230    m.extend_from_slice(&seq.to_le_bytes());
231    m.extend_from_slice(&(screen.w as u16).to_le_bytes());
232    m.extend_from_slice(&(screen.h as u16).to_le_bytes());
233    for (i, codec, bytes) in tiles {
234        let (x, y, w, h) = screen.rect(*i);
235        for v in [x, y, w, h] {
236            m.extend_from_slice(&(v as u16).to_le_bytes());
237        }
238        m.push(*codec);
239        m.push(0);
240        m.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
241        m.extend_from_slice(bytes);
242    }
243    m
244}
245