Skip to main content

xue/encode/
poster.rs

1//! First-frame posters: one tiny artifact per variable so a variable switch
2//! can paint immediately while the real stream loads.
3
4use std::io::Write;
5
6use flate2::write::ZlibEncoder;
7use flate2::Compression;
8
9use crate::encode::errors::{EncodeError, Result};
10use crate::encode::grid::GridInfo;
11
12/// Encode one quantized plane as a small first-frame poster.
13///
14/// The plane is decimated 2x in both axes (row/column 0, 2, 4, … — for the
15/// 721-row grid the last row still lands exactly on the south pole), rows are
16/// delta-filtered against the previous row (PNG "Up", uint8 wraparound), and
17/// the result is zlib-deflated so the browser can inflate it with the native
18/// `DecompressionStream("deflate")` — no WASM on the poster path.
19pub fn encode_poster(codes: &[u8], grid: &GridInfo) -> Result<(Vec<u8>, GridInfo)> {
20    let poster_grid = grid.decimated();
21    let mut plane = Vec::with_capacity(poster_grid.width * poster_grid.height);
22    for row in (0..grid.height).step_by(2) {
23        for column in (0..grid.width).step_by(2) {
24            plane.push(codes[row * grid.width + column]);
25        }
26    }
27    let mut filtered = plane.clone();
28    for row in (1..poster_grid.height).rev() {
29        let (previous, current) = (row - 1, row);
30        for column in 0..poster_grid.width {
31            filtered[current * poster_grid.width + column] = plane
32                [current * poster_grid.width + column]
33                .wrapping_sub(plane[previous * poster_grid.width + column]);
34        }
35    }
36    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::new(9));
37    encoder
38        .write_all(&filtered)
39        .and_then(|()| encoder.finish())
40        .map(|payload| (payload, poster_grid))
41        .map_err(|error| EncodeError::conversion(format!("poster deflate failed: {error}")))
42}