pcengine_rust/
state.rs

1//! Save states (`state.py`): the whole console between two instructions, as bytes, and back.
2//!
3//! As in the reference, a state is everything that changes as the console runs: the CPU
4//! (huc6280-rust's `CpuState`), the board's clock and lines, the VDCs, the VCE, the PSG, the
5//! timer and the interrupt registers, work RAM, the card's mapper and its RAM, the capture and
6//! the mixer, and whatever an add-on has plugged in. It is *not* the wiring: a state is loaded
7//! into a `System` built the same way (the same machine row, the same card, the same add-on),
8//! which keeps its configuration, its page table and its devices.
9//!
10//! **Equivalence** is the test (tests/state.rs, `pce-state-roundtrip`): a run saved at some
11//! instruction boundary and loaded into another system continues exactly as the run that was
12//! never interrupted, bus cycle for bus cycle; and the loaded system, saved at once, gives the
13//! same bytes back.
14//!
15//! **Refused**, with an error and the system untouched: bytes that are not a state of this
16//! format and version, another machine row, another card (its identity is the SHA-1 and length
17//! of the image: no ROM byte is in a state), a system built another way (a device in a socket
18//! the state has empty, or another device there, or other media in it). A state refused further
19//! in (a device that cannot read its part) may have written part of itself, and the system
20//! should be rebuilt.
21//!
22//! Differences forced by Rust:
23//!
24//! - **The format is this crate's own**: a magic and a version, then zlib of the bincode of a
25//!   header and the body. The reference's is tagged JSON of a walk of the object graph, which
26//!   Rust cannot make; a state is not portable to the reference or back. What holds is the
27//!   reference's property.
28//! - **Devices behind a socket trait save themselves** (`sockets::DeviceState`): bytes out,
29//!   bytes in, and an identity. The reference reaches them by the same walk.
30//! - **The named switches**: the reference saves instance attributes (the VDC's `vblank_dots`,
31//!   `vertical_at_line_start`, the DMA's `resume`) and so does this; its class attributes (the
32//!   PSG's switches, the timer's window) are not in a state there, and a loaded state keeps
33//!   the system's own here too, with the VCE's host-side `rgb_table`.
34//! - **Old states are refused, not converted.** The reference's JSON names each field, so it
35//!   loads a state of 0.1.0 with the CPU's new `polled_irq_lines` as `None` (pcengine-python
36//!   0.2.0). bincode names nothing: a body of version 1 does not decode as version 2, and the
37//!   version check refuses it first, with the system untouched (tests/state.rs). A converter
38//!   would carry the old layouts of the CPU and the PSG for states nobody keeps (the crate has
39//!   no users who save yet); a state is for the build that made it.
40//! - **A snapshot pair** the reference does not have: `save_snapshot` / `load_snapshot`, the
41//!   body alone with no header, no check and no compression, for run-ahead (a state taken and
42//!   put back within one run of one system). Loading a snapshot into a system built another
43//!   way is not detected.
44
45use std::borrow::Cow;
46use std::io::{Read, Write};
47
48use huc6280::CpuState;
49use serde::{Deserialize, Serialize};
50
51use crate::cpu_io::{IoBuffer, IrqController, Timer};
52use crate::mixer::Mixer;
53use crate::pagetable::Ram;
54use crate::psg::Psg;
55use crate::sockets::{IrqLine, VideoTiming};
56use crate::system::System;
57use crate::vce::Vce;
58use crate::vdc::Vdc;
59use crate::video::{Capture, Timeline};
60
61pub const MAGIC: &[u8; 8] = b"PCERSTAT";
62/// 2 since 0.2.0: the CPU's state gained `polled_irq_lines` (huc6280-rust 0.2.0), the PSG lost
63/// `acc_steps` and gained `levels_units`. A state of version 1 is refused, not converted (see the
64/// module's notes).
65pub const VERSION: u32 = 2;
66
67/// huc6280-rust's `CpuState`, field for field (it does not derive serde).
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69struct Cpu {
70    a: u8,
71    x: u8,
72    y: u8,
73    s: u8,
74    pc: u16,
75    p: u8,
76    mpr: [u8; 8],
77    high_speed: bool,
78    mpr_latch: u8,
79    irq1: bool,
80    irq2: bool,
81    tiq: bool,
82    irq_disable: u8,
83    halted: bool,
84    reset_pending: bool,
85    maskable_interrupt_pending: bool,
86    non_maskable_interrupt_pending: bool,
87    polled_i: Option<bool>,
88    polled_maskable_interrupt: Option<bool>,
89    polled_non_maskable_interrupt: Option<bool>,
90    skipped_poll: bool,
91    /// huc6280-rust 0.2.0 (huc6280-python 0.4.0, its issue 0005)
92    polled_irq_lines: Option<u8>,
93}
94
95impl From<CpuState> for Cpu {
96    fn from(s: CpuState) -> Cpu {
97        Cpu {
98            a: s.a,
99            x: s.x,
100            y: s.y,
101            s: s.s,
102            pc: s.pc,
103            p: s.p,
104            mpr: s.mpr,
105            high_speed: s.high_speed,
106            mpr_latch: s.mpr_latch,
107            irq1: s.irq1,
108            irq2: s.irq2,
109            tiq: s.tiq,
110            irq_disable: s.irq_disable,
111            halted: s.halted,
112            reset_pending: s.reset_pending,
113            maskable_interrupt_pending: s.maskable_interrupt_pending,
114            non_maskable_interrupt_pending: s.non_maskable_interrupt_pending,
115            polled_i: s.polled_i,
116            polled_maskable_interrupt: s.polled_maskable_interrupt,
117            polled_non_maskable_interrupt: s.polled_non_maskable_interrupt,
118            skipped_poll: s.skipped_poll,
119            polled_irq_lines: s.polled_irq_lines, // saved
120        }
121    }
122}
123
124impl From<&Cpu> for CpuState {
125    fn from(s: &Cpu) -> CpuState {
126        CpuState {
127            a: s.a,
128            x: s.x,
129            y: s.y,
130            s: s.s,
131            pc: s.pc,
132            p: s.p,
133            mpr: s.mpr,
134            high_speed: s.high_speed,
135            mpr_latch: s.mpr_latch,
136            irq1: s.irq1,
137            irq2: s.irq2,
138            tiq: s.tiq,
139            irq_disable: s.irq_disable,
140            halted: s.halted,
141            reset_pending: s.reset_pending,
142            maskable_interrupt_pending: s.maskable_interrupt_pending,
143            non_maskable_interrupt_pending: s.non_maskable_interrupt_pending,
144            polled_i: s.polled_i,
145            polled_maskable_interrupt: s.polled_maskable_interrupt,
146            polled_non_maskable_interrupt: s.polled_non_maskable_interrupt,
147            skipped_poll: s.skipped_poll,
148            polled_irq_lines: s.polled_irq_lines,
149        }
150    }
151}
152
153/// What a state is a state of: checked before anything is written.
154#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
155struct Header {
156    machine: String,
157    card: Option<String>,
158    port: Option<String>,
159    pad: Option<String>,
160    pixel_path: String,
161    audio_sources: Vec<String>,
162}
163
164fn header(system: &System) -> Header {
165    let board = system.board();
166    Header {
167        machine: board.machine.name.to_string(),
168        card: board.slot.card.as_ref().map(|card| card.state_identity()),
169        port: board.port.as_ref().map(|port| port.state_identity()),
170        pad: board
171            .cpu_io
172            .port
173            .device
174            .as_ref()
175            .map(|pad| pad.state_identity()),
176        pixel_path: board.pixel_path.state_identity(),
177        audio_sources: board
178            .audio_sources
179            .iter()
180            .map(|source| source.state_identity())
181            .collect(),
182    }
183}
184
185#[derive(Serialize, Deserialize)]
186struct Body<'a> {
187    cpu: Cpu,
188    mclk: i64,
189    held: i64,
190    lines: (bool, bool, bool),
191    row_end: Option<i64>,
192    row_timing: Option<VideoTiming>,
193    irq2: Cow<'a, IrqLine>,
194    vce: Cow<'a, Vce>,
195    vdcs: Cow<'a, [Vdc]>,
196    psg: Cow<'a, Psg>,
197    buffer: IoBuffer,
198    timer: Timer,
199    irq: IrqController,
200    latch: u8,
201    ram: Cow<'a, Ram>,
202    mixer: Cow<'a, Mixer>,
203    timeline: Cow<'a, Timeline>,
204    capture: Cow<'a, Capture>,
205    card: Option<Vec<u8>>,
206    port: Option<Vec<u8>>,
207    pad: Option<Vec<u8>>,
208    pixel_path: Vec<u8>,
209    audio_sources: Vec<Vec<u8>>,
210}
211
212fn body(system: &System) -> Body<'_> {
213    let board = system.board();
214    Body {
215        cpu: system.cpu.capture_state().into(),
216        mclk: board.mclk,
217        held: board.held,
218        lines: board.lines,
219        row_end: board.row_end,
220        row_timing: board.row_timing,
221        irq2: Cow::Borrowed(&board.irq2),
222        vce: Cow::Borrowed(&board.vce),
223        vdcs: Cow::Borrowed(&board.vdcs[..]),
224        psg: Cow::Borrowed(&board.psg),
225        buffer: board.cpu_io.buffer,
226        timer: board.cpu_io.timer,
227        irq: board.cpu_io.irq,
228        latch: board.cpu_io.port.latch,
229        ram: Cow::Borrowed(&board.ram),
230        mixer: Cow::Borrowed(&board.mixer),
231        timeline: Cow::Borrowed(&board.timeline),
232        capture: Cow::Borrowed(&board.capture),
233        card: board.slot.card.as_ref().map(|card| card.save_state()),
234        port: board.port.as_ref().map(|port| port.save_state()),
235        pad: board
236            .cpu_io
237            .port
238            .device
239            .as_ref()
240            .map(|pad| pad.save_state()),
241        pixel_path: board.pixel_path.save_state(),
242        audio_sources: board
243            .audio_sources
244            .iter()
245            .map(|source| source.save_state())
246            .collect(),
247    }
248}
249
250/// Write a decoded body into the system. The sockets were checked (or, for a snapshot, are
251/// the system's own).
252fn apply(system: &mut System, body: Body) -> Result<(), String> {
253    let board = system.board();
254    if body.vdcs.len() != board.vdcs.len() || body.ram.data.len() != board.ram.data.len() {
255        return Err("a state of a machine built another way (VDCs, work RAM)".to_string());
256    }
257    if body.audio_sources.len() != board.audio_sources.len()
258        || body.card.is_some() != board.slot.card.is_some()
259        || body.port.is_some() != board.port.is_some()
260        || body.pad.is_some() != board.cpu_io.port.device.is_some()
261    {
262        return Err("a state of a machine built another way (the sockets)".to_string());
263    }
264    system.cpu.restore_state(&CpuState::from(&body.cpu))?;
265    let board = system.board_mut();
266    board.mclk = body.mclk;
267    board.held = body.held;
268    board.lines = body.lines;
269    board.row_end = body.row_end;
270    board.row_timing = body.row_timing;
271    board.irq2 = body.irq2.into_owned();
272    let rgb_table = std::mem::take(&mut board.vce.rgb_table);
273    board.vce = body.vce.into_owned();
274    board.vce.rgb_table = rgb_table;
275    let wiring: Vec<bool> = board.vdcs.iter().map(|vdc| vdc.serve).collect();
276    board.vdcs = body.vdcs.into_owned();
277    for (vdc, serve) in board.vdcs.iter_mut().zip(wiring) {
278        vdc.serve = serve; // wiring, not state
279    }
280    let mut psg = body.psg.into_owned();
281    psg.keep_configuration(&board.psg);
282    board.psg = psg;
283    board.cpu_io.buffer = body.buffer;
284    let window = board.cpu_io.timer.underflow_window_mclk;
285    board.cpu_io.timer = body.timer;
286    board.cpu_io.timer.underflow_window_mclk = window;
287    board.cpu_io.irq = body.irq;
288    board.cpu_io.port.latch = body.latch;
289    board.ram = body.ram.into_owned();
290    board.mixer = body.mixer.into_owned();
291    board.timeline = body.timeline.into_owned();
292    board.capture = body.capture.into_owned();
293    if let (Some(card), Some(data)) = (board.slot.card.as_mut(), body.card.as_ref()) {
294        card.load_state(data)?;
295    }
296    if let (Some(port), Some(data)) = (board.port.as_mut(), body.port.as_ref()) {
297        port.load_state(data)?;
298    }
299    if let (Some(pad), Some(data)) = (board.cpu_io.port.device.as_mut(), body.pad.as_ref()) {
300        pad.load_state(data)?;
301    }
302    board.pixel_path.load_state(&body.pixel_path)?;
303    for (source, data) in board.audio_sources.iter_mut().zip(&body.audio_sources) {
304        source.load_state(data)?;
305    }
306    Ok(())
307}
308
309/// The state of `system` as bytes (between two of its steps).
310pub fn save_state(system: &System) -> Vec<u8> {
311    let mut out = MAGIC.to_vec();
312    out.extend_from_slice(&VERSION.to_le_bytes());
313    let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(6));
314    let header = bincode::serialize(&header(system)).expect("a header serialises");
315    encoder
316        .write_all(&(header.len() as u32).to_le_bytes())
317        .and_then(|_| encoder.write_all(&header))
318        .expect("writing to memory");
319    bincode::serialize_into(&mut encoder, &body(system)).expect("a state serialises");
320    encoder.finish().expect("writing to memory")
321}
322
323/// Put `system` in the state `data` was saved from (the same machine, card and add-on).
324pub fn load_state(system: &mut System, data: &[u8]) -> Result<(), String> {
325    if data.len() < MAGIC.len() + 4 || &data[..MAGIC.len()] != MAGIC {
326        return Err("not a pcengine-rust state".to_string());
327    }
328    let version = u32::from_le_bytes(data[MAGIC.len()..MAGIC.len() + 4].try_into().unwrap());
329    if version != VERSION {
330        return Err(format!(
331            "a pcengine-rust state of version {version}, not {VERSION}"
332        ));
333    }
334    let mut plain = Vec::new();
335    flate2::read::ZlibDecoder::new(&data[MAGIC.len() + 4..])
336        .read_to_end(&mut plain)
337        .map_err(|error| format!("not a save state: {error}"))?;
338    if plain.len() < 4 {
339        return Err("not a save state: too short".to_string());
340    }
341    let length = u32::from_le_bytes(plain[..4].try_into().unwrap()) as usize;
342    if plain.len() < 4 + length {
343        return Err("not a save state: too short".to_string());
344    }
345    let saved: Header = bincode::deserialize(&plain[4..4 + length])
346        .map_err(|error| format!("not a save state: {error}"))?;
347    let ours = header(system);
348    if saved.machine != ours.machine {
349        return Err(format!(
350            "a state of the {}, not the {}",
351            saved.machine, ours.machine
352        ));
353    }
354    if saved.card != ours.card {
355        return Err("a state of another ROM image (another card?)".to_string());
356    }
357    if saved.port != ours.port {
358        return Err(
359            "a state made with another expansion device or other media (another disc?)".to_string(),
360        );
361    }
362    if saved != ours {
363        return Err("a state of a machine built another way".to_string());
364    }
365    let body: Body = bincode::deserialize(&plain[4 + length..])
366        .map_err(|error| format!("not a save state: {error}"))?;
367    apply(system, body)
368}
369
370/// The state of `system` for `load_snapshot` on the same system later: no header, no
371/// compression, nothing hashed.
372pub fn save_snapshot(system: &System) -> Vec<u8> {
373    bincode::serialize(&body(system)).expect("a state serialises")
374}
375
376/// Put `system` back where `save_snapshot` found it (the system the snapshot was taken from,
377/// or one built the same way: nothing is checked).
378pub fn load_snapshot(system: &mut System, data: &[u8]) -> Result<(), String> {
379    let body: Body =
380        bincode::deserialize(data).map_err(|error| format!("not a snapshot: {error}"))?;
381    apply(system, body)
382}