Skip to main content

gasm_host/
headless.rs

1//! Headless runs: N frames with virtual time, scripted input and (optionally)
2//! hashes of everything the guest presents. Reproducible: the same module and
3//! options give the same hashes on every runner (runners/web/headless.mjs).
4
5use std::time::{Duration, Instant};
6
7use crate::gfx::{Gfx, HEADLESS_SIZE};
8use crate::host::{Stop, VirtualClock};
9use crate::present::Present;
10use crate::script::{Script, ScriptState};
11use crate::session::Session;
12
13pub struct Options {
14    pub frames: u64,
15    /// render on the GPU (offscreen) and write the last frame as PNG
16    pub screenshot: Option<String>,
17    /// also write the last 2D frame as the window would show it: `present` at `window` size
18    pub screenshot_filtered: Option<String>,
19    pub present: Present,
20    pub window: (u32, u32),
21    pub script: Script,
22    /// pace frames at the guest's rate
23    pub realtime: bool,
24    pub hash: bool,
25}
26
27/// What a run produced (`print` writes the hash lines scripts compare).
28pub struct Report {
29    pub frames: u64,
30    pub presented: u64,
31    pub size: (usize, usize),
32    pub video_hash: u32,
33    pub audio_hash: u32,
34    pub audio_frames: u64,
35    pub frame_rate: f64,
36    pub seconds: f64,
37    /// the guest called proc_exit(code)
38    pub exit: Option<i32>,
39}
40
41impl Report {
42    /// The hash lines (stdout): a contract between runners and scripts.
43    pub fn print(&self) {
44        println!("frames={} presented={} size={}x{}", self.frames, self.presented, self.size.0, self.size.1);
45        println!("video_fnv32={:08x} audio_fnv32={:08x} audio_frames={}", self.video_hash, self.audio_hash, self.audio_frames);
46    }
47}
48
49pub fn run(session: Session, opts: &Options) -> Result<Report, String> {
50    // Render on the GPU only when a screenshot is wanted; otherwise a null backend.
51    let gpu = opts.screenshot.is_some() || opts.screenshot_filtered.is_some();
52    // a gasm:gl game can't use gasm:gfx: no wgpu for it (ANGLE renders below)
53    let uses_gl = session.uses_gl();
54    let gfx = match gpu && !uses_gl {
55        true => Gfx::offscreen(HEADLESS_SIZE.0, HEADLESS_SIZE.1).unwrap_or_else(|e| {
56            eprintln!("[gasm] no GPU for screenshots ({e}); gfx output will be blank");
57            Gfx::null()
58        }),
59        false => Gfx::null(),
60    };
61    if let Some(t) = crate::host::static_title(&session.wasm) {
62        eprintln!("[gasm] title: {t} (gasm.title)");
63    }
64    // gasm:gl games render with ANGLE offscreen for screenshots (the hashes don't change)
65    let gl = match gpu && uses_gl {
66        true => session.open_gl(None, HEADLESS_SIZE).map_err(|e| eprintln!("[gasm] no GL for screenshots ({e}); gl output will be blank")).ok(),
67        false => None,
68    };
69    let mut game = match session.start(None, gfx, gl, true, opts.hash) {
70        Ok(g) => g,
71        Err(Stop::Exit(code)) => {
72            return Ok(Report { frames: 0, presented: 0, size: (0, 0), video_hash: 0x811c_9dc5, audio_hash: 0x811c_9dc5, audio_frames: 0, frame_rate: 60.0, seconds: 0.0, exit: Some(code) });
73        }
74        Err(Stop::Trap(e)) => return Err(e),
75    };
76    let t0 = Instant::now();
77    let mut exit = None;
78    let mut ran = 0;
79    let mut clock = VirtualClock::default();
80    let mut script_state = ScriptState::default();
81    for i in 0..opts.frames {
82        // between frames the host is reached through with_host (a gasm_run guest owns it)
83        game.with_host(|host| {
84            let rate = host.frame_rate;
85            host.virtual_time_ms = Some(clock.at(i, rate));
86            host.pads = [opts.script.pad(i), 0, 0, 0];
87            host.text = Some(opts.script.text(i));
88            let (w, h) = host.gfx.size();
89            let mode = host.input_mode;
90            host.input = opts.script.raw(i, &mut script_state, (w as f32, h as f32), mode);
91            host.show_frame = gpu && i + 1 == opts.frames;
92        });
93        ran = i + 1;
94        let result = game.frame();
95        game.with_host(|h| { let show = h.show_frame; h.gl.end_frame(show) });
96        if let Some(t) = game.with_host(|host| std::mem::take(&mut host.title_changed).then(|| host.title.clone())) {
97            eprintln!("[gasm] title: {}", t.as_deref().unwrap_or("(default)"));
98        }
99        match result {
100            Ok(()) => {}
101            Err(Stop::Exit(code)) => {
102                exit = Some(code);
103                break;
104            }
105            Err(Stop::Trap(e)) => return Err(format!("frame {i}: {e}")),
106        }
107        if opts.realtime {
108            let due = t0 + Duration::from_secs_f64((i + 1) as f64 / game.with_host(|h| h.frame_rate));
109            if let Some(wait) = due.checked_duration_since(Instant::now()) {
110                std::thread::sleep(wait);
111            }
112        }
113    }
114    if exit.is_none() {
115        game.exit();
116    }
117    if let Some(path) = &opts.screenshot_filtered {
118        let h = game.host_mut();
119        let img = match h.gfx.used {
120            _ if h.gl.has_backend() => h.gl.read_frame(),
121            true => h.gfx.read_offscreen(), // gfx guests render at drawable size: no filter
122            false if h.width > 0 => {
123                let rgba = std::mem::take(&mut h.rgba);
124                h.gfx.present = opts.present;
125                let img = h.gfx.render_video(&rgba, h.width as u32, h.height as u32, h.aspect, opts.window);
126                h.rgba = rgba;
127                img
128            }
129            false => None,
130        };
131        if let Some((w, hgt, rgba)) = img {
132            write_png(path, w, hgt, &rgba)?;
133            eprintln!("[gasm] wrote {path}");
134        }
135    }
136    let h = game.host();
137    if let Some(path) = &opts.screenshot {
138        let (w, hgt, rgba) = match h.gfx.read_offscreen() {
139            _ if h.gl.has_backend() => h.gl.read_frame().unwrap_or_default(),
140            Some(img) if h.gfx.used => img,
141            _ => (h.width as u32, h.height as u32, h.rgba.clone()),
142        };
143        if w > 0 {
144            write_png(path, w, hgt, &rgba)?;
145            eprintln!("[gasm] wrote {path}");
146        }
147    }
148    Ok(Report {
149        frames: ran,
150        presented: h.frames_presented,
151        size: (h.width, h.height),
152        video_hash: h.video_hash.0,
153        audio_hash: h.audio_hash.0,
154        audio_frames: h.audio_frames,
155        frame_rate: h.frame_rate,
156        seconds: t0.elapsed().as_secs_f64(),
157        exit,
158    })
159}
160
161/// A PNG as RGBA8 (any color type and depth is expanded): (pixels, width, height).
162pub fn decode_png(bytes: &[u8]) -> Result<(Vec<u8>, u32, u32), String> {
163    let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
164    dec.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA);
165    let mut reader = dec.read_info().map_err(|e| format!("not a PNG: {e}"))?;
166    let mut buf = vec![0; reader.output_buffer_size().ok_or("PNG too large")?];
167    let info = reader.next_frame(&mut buf).map_err(|e| format!("PNG: {e}"))?;
168    buf.truncate(info.buffer_size());
169    let rgba = match info.color_type {
170        png::ColorType::Rgba => buf,
171        png::ColorType::GrayscaleAlpha => buf.chunks(2).flat_map(|p| [p[0], p[0], p[0], p[1]]).collect(),
172        other => return Err(format!("PNG color type {other:?} after expansion")),
173    };
174    Ok((rgba, info.width, info.height))
175}
176
177pub fn write_png(path: &str, w: u32, h: u32, rgba: &[u8]) -> Result<(), String> {
178    let file = std::fs::File::create(path).map_err(|e| format!("{path}: {e}"))?;
179    let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w, h);
180    enc.set_color(png::ColorType::Rgba);
181    enc.set_depth(png::BitDepth::Eight);
182    let mut writer = enc.write_header().map_err(|e| e.to_string())?;
183    writer.write_image_data(rgba).map_err(|e| e.to_string())
184}
185
186#[cfg(test)]
187mod png_tests {
188    #[test]
189    fn png_round_trip() {
190        let path = std::env::temp_dir().join(format!("gasm-png-{}.png", std::process::id()));
191        let rgba: Vec<u8> = (0..2 * 3 * 4).map(|i| i as u8 * 9).collect();
192        super::write_png(path.to_str().unwrap(), 2, 3, &rgba).unwrap();
193        let (back, w, h) = super::decode_png(&std::fs::read(&path).unwrap()).unwrap();
194        assert_eq!((back, w, h), (rgba, 2, 3));
195        let _ = std::fs::remove_file(path);
196    }
197}