1use 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";
62pub const VERSION: u32 = 2;
66
67#[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 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, }
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#[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
250fn 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; }
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
309pub 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
323pub 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
370pub fn save_snapshot(system: &System) -> Vec<u8> {
373 bincode::serialize(&body(system)).expect("a state serialises")
374}
375
376pub 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}