pixel8-player 0.1.0

Pixel8 cart player over the console runtime: a windowed desktop backend or a static-musl KMS/evdev/ALSA backend for handhelds
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! The player's mode logic: the cart shelf, running a cart, and the error screen. Written
//! against the `Platform` trait so it runs identically on KMS, on a TTY, or headless in tests.

use crate::{
    picker,
    platform::{InputSnapshot, Platform},
};
use anyhow::Result;
use pixel8_runtime::{
    audio::AudioHandle,
    cart,
    fb::{Framebuffer, HEIGHT},
    palette::col,
    storage::Storage,
    ui,
    vm::{GameVm, UI_FPS},
};
use std::{
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

/// Folds per-frame input snapshots into high-level actions: the universal hold-O+X exit,
/// Select/Start handling, and the fps toggle. Shared by every backend, tested headless.
#[derive(Default)]
pub struct Controls {
    combo_frames: u32,
}

/// What `Controls` decided this frame.
pub enum ControlAction {
    None,
    BackToPicker,
    Quit,
    ToggleFps,
}

impl Controls {
    /// `fps` is the current logical frame rate, so the ~1s hold scales with it.
    pub fn update(&mut self, snap: &InputSnapshot, fps: u32) -> ControlAction {
        if snap.quit_requested {
            return ControlAction::Quit;
        }
        if snap.select && snap.start {
            return ControlAction::Quit;
        }
        if snap.select {
            return ControlAction::BackToPicker;
        }
        if snap.fps_toggle {
            return ControlAction::ToggleFps;
        }
        if snap.buttons[4] && snap.buttons[5] {
            self.combo_frames += 1;
            if self.combo_frames >= fps.max(1) {
                self.combo_frames = 0;
                return ControlAction::BackToPicker;
            }
        } else {
            self.combo_frames = 0;
        }
        ControlAction::None
    }
}

/// What a finished game/picker loop wants to happen next.
pub enum Flow {
    Quit,
    BackToPicker,
}

/// One frame's wall-clock budget at a given logical frame rate.
fn frame_duration(fps: u32) -> Duration {
    Duration::from_nanos(1_000_000_000 / fps.max(1) as u64)
}

pub struct App {
    platform: Box<dyn Platform>,
    /// The synth the running cart writes and the platform's audio thread reads. Held here so a
    /// single handle is shared; `KmsPlatform` is constructed from a clone of it.
    audio: AudioHandle,
    /// Run only this many frames, then exit (CI smoke mode).
    smoke: Option<u32>,
}

impl App {
    pub fn new(platform: Box<dyn Platform>, audio: AudioHandle, smoke: Option<u32>) -> App {
        App {
            platform,
            audio,
            smoke,
        }
    }

    /// The cart shelf: list carts in a directory, pick one, play it.
    pub fn picker(&mut self, dir: &Path) -> Result<()> {
        loop {
            let carts = picker::scan_carts(dir)?;
            match self.picker_loop(dir, &carts)? {
                Some(path) => match self.play(&path) {
                    Ok(Flow::BackToPicker) => continue,
                    Ok(Flow::Quit) => return Ok(()),
                    Err(e) => {
                        eprintln!("pixel8-player: {e:#}");
                        continue;
                    }
                },
                None => return Ok(()),
            }
        }
    }

    /// Run one cart until the player backs out or quits.
    pub fn play(&mut self, path: &Path) -> Result<Flow> {
        eprintln!("pixel8-player: loading {}", path.display());
        let cart = match cart::load_png(path) {
            Ok(c) => c,
            Err(e) => return self.show_error(&format!("load failed\n{e}")),
        };
        // Stop any audio from a previous cart before loading the new VM.
        self.audio.stop_all();
        // The cart's save file, keyed by its name; saved when the VM drops.
        let storage = Storage::for_cart(&cart.assets.meta.name);
        // The VM writes into the same synth the platform's audio thread reads.
        let mut vm = match GameVm::load(&cart.wasm, &cart.assets, self.audio.clone(), storage) {
            Ok(vm) => Some(vm),
            Err(e) => return self.show_error(&format!("boot failed\n{e}")),
        };
        let fps = vm.as_ref().map(GameVm::fps).unwrap_or(UI_FPS);
        let frame = frame_duration(fps);
        eprintln!("pixel8-player: running {}", path.display());

        let mut controls = Controls::default();
        let mut error_fb: Option<Framebuffer> = None;
        let mut next = Instant::now();
        let mut frames = 0u32;
        let mut show_fps = false;
        let mut fps_frames = 0u32;
        let mut fps_t0 = Instant::now();
        let mut fps_val = 0.0f32;

        loop {
            let snap = self.platform.poll();
            match controls.update(&snap, fps) {
                ControlAction::Quit => {
                    self.audio.stop_all();
                    return Ok(Flow::Quit);
                }
                ControlAction::BackToPicker => {
                    self.audio.stop_all();
                    return Ok(Flow::BackToPicker);
                }
                ControlAction::ToggleFps => show_fps = !show_fps,
                ControlAction::None => {}
            }
            if let Some(v) = vm.as_mut() {
                let input = &mut v.state_mut().input;
                for (b, pressed) in snap.buttons.iter().enumerate() {
                    input.set_button(b, *pressed);
                }
            }

            if let Some(v) = vm.as_mut() {
                v.state_mut().set_measured_fps(fps_val);
            }
            if let Some(v) = vm.as_mut() {
                if let Err(e) = v.call_update().and_then(|()| v.call_draw()) {
                    eprintln!("pixel8-player: runtime error: {e}");
                    self.audio.stop_all();
                    let mut fb = ui::error_screen(&e.to_string());
                    fb.print("hold o+x to exit", 2, HEIGHT - 7, col::LIGHT_GREY);
                    error_fb = Some(fb);
                    vm = None;
                }
            }
            if show_fps {
                if let Some(v) = vm.as_mut() {
                    picker::draw_fps_overlay(&mut v.state_mut().fb, fps_val, fps);
                }
            }
            if let Some(v) = &vm {
                self.platform.present(&v.state().fb)?;
            } else if let Some(fb) = &error_fb {
                self.platform.present(fb)?;
            }

            frames += 1;
            if self.smoke.is_some_and(|n| frames >= n) {
                return Ok(Flow::Quit);
            }
            self.pace(&mut next, frame, &mut fps_frames, &mut fps_t0, &mut fps_val);
        }
    }

    /// Show a Pixel8 error screen until the player presses back.
    fn show_error(&mut self, message: &str) -> Result<Flow> {
        eprintln!("pixel8-player: {}", message.replace('\n', ": "));
        self.audio.stop_all();
        let mut fb = ui::error_screen(message);
        fb.print("select/b: back", 2, HEIGHT - 7, col::LIGHT_GREY);
        let mut controls = Controls::default();
        let mut next = Instant::now();
        let mut shown = 0u32;
        loop {
            let snap = self.platform.poll();
            match controls.update(&snap, UI_FPS) {
                ControlAction::Quit => return Ok(Flow::Quit),
                ControlAction::BackToPicker => return Ok(Flow::BackToPicker),
                _ => {}
            }
            // Any face button also leaves the error screen, back to the picker.
            if snap.buttons[4] || snap.buttons[5] {
                return Ok(Flow::BackToPicker);
            }
            self.platform.present(&fb)?;
            shown += 1;
            if self.smoke.is_some_and(|n| shown >= n) {
                return Ok(Flow::Quit);
            }
            Self::sleep_until(&mut next, frame_duration(UI_FPS));
        }
    }

    fn picker_loop(&mut self, dir: &Path, carts: &[PathBuf]) -> Result<Option<PathBuf>> {
        let mut sel = 0usize;
        let mut frame = 0u32;
        let mut next = Instant::now();
        // `None` until the first frame establishes a baseline, so a button still held from the
        // previous screen (e.g. the in-game hold-O+X exit) is not read as a fresh press here.
        let mut prev: Option<InputSnapshot> = None;
        let quit_row = carts.len();
        loop {
            let snap = self.platform.poll();
            if snap.quit_requested || snap.select {
                return Ok(None);
            }
            if let Some(p) = &prev {
                // Edge-detect d-pad up/down and any face button (select / launch).
                let edge = |i: usize| snap.buttons[i] && !p.buttons[i];
                if edge(2) {
                    sel = sel.saturating_sub(1);
                }
                if edge(3) {
                    sel = (sel + 1).min(quit_row);
                }
                if edge(4) || edge(5) {
                    if sel == quit_row {
                        return Ok(None);
                    }
                    return Ok(Some(carts[sel].clone()));
                }
            }
            prev = Some(snap);

            let fb = picker::draw_picker(dir, carts, sel, frame);
            self.platform.present(&fb)?;
            frame += 1;
            if self.smoke.is_some_and(|n| frame >= n) {
                return Ok(None);
            }
            Self::sleep_until(&mut next, frame_duration(UI_FPS));
        }
    }

    fn pace(
        &self,
        next: &mut Instant,
        frame: Duration,
        fps_frames: &mut u32,
        fps_t0: &mut Instant,
        fps_val: &mut f32,
    ) {
        let now = Instant::now();
        *fps_frames += 1;
        let elapsed = now.duration_since(*fps_t0);
        if elapsed >= Duration::from_millis(500) {
            *fps_val = *fps_frames as f32 / elapsed.as_secs_f32();
            *fps_frames = 0;
            *fps_t0 = now;
        }
        Self::sleep_until(next, frame);
    }

    fn sleep_until(next: &mut Instant, frame: Duration) {
        *next += frame;
        let now = Instant::now();
        if *next > now {
            std::thread::sleep(*next - now);
        } else {
            *next = now;
        }
    }
}

#[cfg(test)]
mod controls_tests {
    use super::*;
    use crate::platform::InputSnapshot;

    fn snap(buttons: [bool; 6]) -> InputSnapshot {
        InputSnapshot {
            buttons,
            ..Default::default()
        }
    }

    #[test]
    fn hold_o_and_x_returns_to_picker_after_one_second() {
        let mut c = Controls::default();
        let held = snap([false, false, false, false, true, true]); // O + X
        for _ in 0..59 {
            assert!(matches!(c.update(&held, 60), ControlAction::None));
        }
        assert!(matches!(c.update(&held, 60), ControlAction::BackToPicker));
    }

    #[test]
    fn releasing_o_or_x_resets_the_combo() {
        let mut c = Controls::default();
        let both = snap([false, false, false, false, true, true]);
        let one = snap([false, false, false, false, true, false]);
        for _ in 0..30 {
            c.update(&both, 60);
        }
        c.update(&one, 60); // release X
        for _ in 0..59 {
            assert!(matches!(c.update(&both, 60), ControlAction::None));
        }
        assert!(matches!(c.update(&both, 60), ControlAction::BackToPicker));
    }

    #[test]
    fn select_plus_start_quits() {
        let mut c = Controls::default();
        let s = InputSnapshot {
            select: true,
            start: true,
            ..Default::default()
        };
        assert!(matches!(c.update(&s, 60), ControlAction::Quit));
    }

    #[test]
    fn select_alone_returns_to_picker() {
        let mut c = Controls::default();
        let s = InputSnapshot {
            select: true,
            ..Default::default()
        };
        assert!(matches!(c.update(&s, 60), ControlAction::BackToPicker));
    }

    #[test]
    fn fps_toggle_is_an_edge() {
        let mut c = Controls::default();
        let on = InputSnapshot {
            fps_toggle: true,
            ..Default::default()
        };
        assert!(matches!(c.update(&on, 60), ControlAction::ToggleFps));
    }
}

#[cfg(test)]
mod app_tests {
    use super::*;
    use crate::platform::{null::NullPlatform, InputSnapshot};

    #[test]
    fn smoke_picker_presents_then_quits() {
        // Empty dir: picker_loop should present `smoke` frames and return None.
        let dir = std::env::temp_dir().join(format!("pixel8_app_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(Box::new(NullPlatform::new()), AudioHandle::dummy(), Some(3));
        app.picker(&dir).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn quit_requested_leaves_picker_immediately() {
        let dir = std::env::temp_dir().join(format!("pixel8_app2_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let snap = InputSnapshot {
            quit_requested: true,
            ..Default::default()
        };
        let platform = Box::new(NullPlatform::scripted(vec![snap]));
        let mut app = App::new(platform, AudioHandle::dummy(), None);
        app.picker(&dir).unwrap(); // returns without hanging
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A button still held when re-entering the picker (e.g. the in-game hold-O+X exit) must
    /// NOT be treated as a fresh press. The first frame establishes the baseline; held buttons
    /// only act on a subsequent rising edge.
    #[test]
    fn held_face_button_on_entry_does_not_launch() {
        let dir = std::env::temp_dir().join(format!("pixel8_app3_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        // Create a dummy cart so carts list is non-empty.
        std::fs::write(dir.join("test.png"), b"dummy").unwrap();

        // Button 4 (O) held on every frame — no release, no rising edge.
        let held = InputSnapshot {
            buttons: [false, false, false, false, true, false],
            ..Default::default()
        };
        let frames = vec![held, held, held];
        let platform = Box::new(NullPlatform::scripted(frames));
        // smoke=3 so the loop exits via the smoke limit, not a launch.
        let mut app = App::new(platform, AudioHandle::dummy(), Some(3));
        let carts = vec![dir.join("test.png")];
        // With the OLD code this returns Ok(Some(..)) on frame 0 (false positive launch).
        // With the fix it returns Ok(None) (exits via smoke, no cart launched).
        let result = app.picker_loop(&dir, &carts).unwrap();
        assert!(
            result.is_none(),
            "held button on entry must not launch a cart (got {result:?})"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn empty_dir_quit_row_exits() {
        // No carts: the only selectable entry is "-- quit --"; a fresh face press exits.
        let pressed = InputSnapshot {
            buttons: [false, false, false, false, true, false],
            ..Default::default()
        };
        // Baseline frame, then a fresh press on the quit row.
        let frames = vec![InputSnapshot::default(), pressed];
        let platform = Box::new(NullPlatform::scripted(frames));
        let mut app = App::new(platform, AudioHandle::dummy(), Some(10));
        let result = app
            .picker_loop(Path::new("/tmp/pixel8-empty"), &[])
            .unwrap();
        assert!(
            result.is_none(),
            "pressing on the quit row exits the picker"
        );
    }

    #[test]
    fn navigating_to_quit_row_exits() {
        let carts = vec![PathBuf::from("a.png"), PathBuf::from("b.png")]; // quit_row = 2.
        let down = InputSnapshot {
            buttons: [false, false, false, true, false, false],
            ..Default::default()
        };
        let none = InputSnapshot::default();
        let press = InputSnapshot {
            buttons: [false, false, false, false, true, false],
            ..Default::default()
        };
        // Baseline, two down-edges to reach the quit row, then a face press.
        let frames = vec![none, down, none, down, none, press];
        let platform = Box::new(NullPlatform::scripted(frames));
        let mut app = App::new(platform, AudioHandle::dummy(), Some(20));
        let result = app
            .picker_loop(Path::new("/tmp/pixel8-carts"), &carts)
            .unwrap();
        assert!(
            result.is_none(),
            "navigating to the quit row and pressing exits"
        );
    }

    /// A genuine button press that happens AFTER a full release cycle still launches.
    #[test]
    fn fresh_press_after_release_launches() {
        let dir = std::env::temp_dir().join(format!("pixel8_app4_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("test.png"), b"dummy").unwrap();

        let held = InputSnapshot {
            buttons: [false, false, false, false, true, false],
            ..Default::default()
        };
        let released = InputSnapshot::default();
        // Sequence: held, held, released, held (fresh press).
        let frames = vec![held, held, released, held];
        let platform = Box::new(NullPlatform::scripted(frames));
        let mut app = App::new(platform, AudioHandle::dummy(), Some(10));
        let carts = vec![dir.join("test.png")];
        let result = app.picker_loop(&dir, &carts).unwrap();
        assert_eq!(
            result,
            Some(carts[0].clone()),
            "genuine press after release must launch the selected cart"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }
}