1use std::borrow::Cow;
40use std::io::{Read, Write};
41
42use huc6280::CpuState;
43use serde::{Deserialize, Serialize};
44
45use crate::cpu_io::{IoBuffer, IrqController, Timer};
46use crate::mixer::Mixer;
47use crate::pagetable::Ram;
48use crate::psg::Psg;
49use crate::sockets::{IrqLine, VideoTiming};
50use crate::system::System;
51use crate::vce::Vce;
52use crate::vdc::Vdc;
53use crate::video::{Capture, Timeline};
54
55pub const MAGIC: &[u8; 8] = b"PCERSTAT";
56pub const VERSION: u32 = 1;
57
58#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60struct Cpu {
61 a: u8,
62 x: u8,
63 y: u8,
64 s: u8,
65 pc: u16,
66 p: u8,
67 mpr: [u8; 8],
68 high_speed: bool,
69 mpr_latch: u8,
70 irq1: bool,
71 irq2: bool,
72 tiq: bool,
73 irq_disable: u8,
74 halted: bool,
75 reset_pending: bool,
76 maskable_interrupt_pending: bool,
77 non_maskable_interrupt_pending: bool,
78 polled_i: Option<bool>,
79 polled_maskable_interrupt: Option<bool>,
80 polled_non_maskable_interrupt: Option<bool>,
81 skipped_poll: bool,
82}
83
84impl From<CpuState> for Cpu {
85 fn from(s: CpuState) -> Cpu {
86 Cpu {
87 a: s.a,
88 x: s.x,
89 y: s.y,
90 s: s.s,
91 pc: s.pc,
92 p: s.p,
93 mpr: s.mpr,
94 high_speed: s.high_speed,
95 mpr_latch: s.mpr_latch,
96 irq1: s.irq1,
97 irq2: s.irq2,
98 tiq: s.tiq,
99 irq_disable: s.irq_disable,
100 halted: s.halted,
101 reset_pending: s.reset_pending,
102 maskable_interrupt_pending: s.maskable_interrupt_pending,
103 non_maskable_interrupt_pending: s.non_maskable_interrupt_pending,
104 polled_i: s.polled_i,
105 polled_maskable_interrupt: s.polled_maskable_interrupt,
106 polled_non_maskable_interrupt: s.polled_non_maskable_interrupt,
107 skipped_poll: s.skipped_poll,
108 }
109 }
110}
111
112impl From<&Cpu> for CpuState {
113 fn from(s: &Cpu) -> CpuState {
114 CpuState {
115 a: s.a,
116 x: s.x,
117 y: s.y,
118 s: s.s,
119 pc: s.pc,
120 p: s.p,
121 mpr: s.mpr,
122 high_speed: s.high_speed,
123 mpr_latch: s.mpr_latch,
124 irq1: s.irq1,
125 irq2: s.irq2,
126 tiq: s.tiq,
127 irq_disable: s.irq_disable,
128 halted: s.halted,
129 reset_pending: s.reset_pending,
130 maskable_interrupt_pending: s.maskable_interrupt_pending,
131 non_maskable_interrupt_pending: s.non_maskable_interrupt_pending,
132 polled_i: s.polled_i,
133 polled_maskable_interrupt: s.polled_maskable_interrupt,
134 polled_non_maskable_interrupt: s.polled_non_maskable_interrupt,
135 skipped_poll: s.skipped_poll,
136 }
137 }
138}
139
140#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
142struct Header {
143 machine: String,
144 card: Option<String>,
145 port: Option<String>,
146 pad: Option<String>,
147 pixel_path: String,
148 audio_sources: Vec<String>,
149}
150
151fn header(system: &System) -> Header {
152 let board = system.board();
153 Header {
154 machine: board.machine.name.to_string(),
155 card: board.slot.card.as_ref().map(|card| card.state_identity()),
156 port: board.port.as_ref().map(|port| port.state_identity()),
157 pad: board
158 .cpu_io
159 .port
160 .device
161 .as_ref()
162 .map(|pad| pad.state_identity()),
163 pixel_path: board.pixel_path.state_identity(),
164 audio_sources: board
165 .audio_sources
166 .iter()
167 .map(|source| source.state_identity())
168 .collect(),
169 }
170}
171
172#[derive(Serialize, Deserialize)]
173struct Body<'a> {
174 cpu: Cpu,
175 mclk: i64,
176 held: i64,
177 lines: (bool, bool, bool),
178 row_end: Option<i64>,
179 row_timing: Option<VideoTiming>,
180 irq2: Cow<'a, IrqLine>,
181 vce: Cow<'a, Vce>,
182 vdcs: Cow<'a, [Vdc]>,
183 psg: Cow<'a, Psg>,
184 buffer: IoBuffer,
185 timer: Timer,
186 irq: IrqController,
187 latch: u8,
188 ram: Cow<'a, Ram>,
189 mixer: Cow<'a, Mixer>,
190 timeline: Cow<'a, Timeline>,
191 capture: Cow<'a, Capture>,
192 card: Option<Vec<u8>>,
193 port: Option<Vec<u8>>,
194 pad: Option<Vec<u8>>,
195 pixel_path: Vec<u8>,
196 audio_sources: Vec<Vec<u8>>,
197}
198
199fn body(system: &System) -> Body<'_> {
200 let board = system.board();
201 Body {
202 cpu: system.cpu.capture_state().into(),
203 mclk: board.mclk,
204 held: board.held,
205 lines: board.lines,
206 row_end: board.row_end,
207 row_timing: board.row_timing,
208 irq2: Cow::Borrowed(&board.irq2),
209 vce: Cow::Borrowed(&board.vce),
210 vdcs: Cow::Borrowed(&board.vdcs[..]),
211 psg: Cow::Borrowed(&board.psg),
212 buffer: board.cpu_io.buffer,
213 timer: board.cpu_io.timer,
214 irq: board.cpu_io.irq,
215 latch: board.cpu_io.port.latch,
216 ram: Cow::Borrowed(&board.ram),
217 mixer: Cow::Borrowed(&board.mixer),
218 timeline: Cow::Borrowed(&board.timeline),
219 capture: Cow::Borrowed(&board.capture),
220 card: board.slot.card.as_ref().map(|card| card.save_state()),
221 port: board.port.as_ref().map(|port| port.save_state()),
222 pad: board
223 .cpu_io
224 .port
225 .device
226 .as_ref()
227 .map(|pad| pad.save_state()),
228 pixel_path: board.pixel_path.save_state(),
229 audio_sources: board
230 .audio_sources
231 .iter()
232 .map(|source| source.save_state())
233 .collect(),
234 }
235}
236
237fn apply(system: &mut System, body: Body) -> Result<(), String> {
240 let board = system.board();
241 if body.vdcs.len() != board.vdcs.len() || body.ram.data.len() != board.ram.data.len() {
242 return Err("a state of a machine built another way (VDCs, work RAM)".to_string());
243 }
244 if body.audio_sources.len() != board.audio_sources.len()
245 || body.card.is_some() != board.slot.card.is_some()
246 || body.port.is_some() != board.port.is_some()
247 || body.pad.is_some() != board.cpu_io.port.device.is_some()
248 {
249 return Err("a state of a machine built another way (the sockets)".to_string());
250 }
251 system.cpu.restore_state(&CpuState::from(&body.cpu))?;
252 let board = system.board_mut();
253 board.mclk = body.mclk;
254 board.held = body.held;
255 board.lines = body.lines;
256 board.row_end = body.row_end;
257 board.row_timing = body.row_timing;
258 board.irq2 = body.irq2.into_owned();
259 let rgb_table = std::mem::take(&mut board.vce.rgb_table);
260 board.vce = body.vce.into_owned();
261 board.vce.rgb_table = rgb_table;
262 board.vdcs = body.vdcs.into_owned();
263 let mut psg = body.psg.into_owned();
264 psg.keep_configuration(&board.psg);
265 board.psg = psg;
266 board.cpu_io.buffer = body.buffer;
267 let window = board.cpu_io.timer.underflow_window_mclk;
268 board.cpu_io.timer = body.timer;
269 board.cpu_io.timer.underflow_window_mclk = window;
270 board.cpu_io.irq = body.irq;
271 board.cpu_io.port.latch = body.latch;
272 board.ram = body.ram.into_owned();
273 board.mixer = body.mixer.into_owned();
274 board.timeline = body.timeline.into_owned();
275 board.capture = body.capture.into_owned();
276 if let (Some(card), Some(data)) = (board.slot.card.as_mut(), body.card.as_ref()) {
277 card.load_state(data)?;
278 }
279 if let (Some(port), Some(data)) = (board.port.as_mut(), body.port.as_ref()) {
280 port.load_state(data)?;
281 }
282 if let (Some(pad), Some(data)) = (board.cpu_io.port.device.as_mut(), body.pad.as_ref()) {
283 pad.load_state(data)?;
284 }
285 board.pixel_path.load_state(&body.pixel_path)?;
286 for (source, data) in board.audio_sources.iter_mut().zip(&body.audio_sources) {
287 source.load_state(data)?;
288 }
289 Ok(())
290}
291
292pub fn save_state(system: &System) -> Vec<u8> {
294 let mut out = MAGIC.to_vec();
295 out.extend_from_slice(&VERSION.to_le_bytes());
296 let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(6));
297 let header = bincode::serialize(&header(system)).expect("a header serialises");
298 encoder
299 .write_all(&(header.len() as u32).to_le_bytes())
300 .and_then(|_| encoder.write_all(&header))
301 .expect("writing to memory");
302 bincode::serialize_into(&mut encoder, &body(system)).expect("a state serialises");
303 encoder.finish().expect("writing to memory")
304}
305
306pub fn load_state(system: &mut System, data: &[u8]) -> Result<(), String> {
308 if data.len() < MAGIC.len() + 4 || &data[..MAGIC.len()] != MAGIC {
309 return Err("not a pcengine-rust state".to_string());
310 }
311 let version = u32::from_le_bytes(data[MAGIC.len()..MAGIC.len() + 4].try_into().unwrap());
312 if version != VERSION {
313 return Err(format!(
314 "a pcengine-rust state of version {version}, not {VERSION}"
315 ));
316 }
317 let mut plain = Vec::new();
318 flate2::read::ZlibDecoder::new(&data[MAGIC.len() + 4..])
319 .read_to_end(&mut plain)
320 .map_err(|error| format!("not a save state: {error}"))?;
321 if plain.len() < 4 {
322 return Err("not a save state: too short".to_string());
323 }
324 let length = u32::from_le_bytes(plain[..4].try_into().unwrap()) as usize;
325 if plain.len() < 4 + length {
326 return Err("not a save state: too short".to_string());
327 }
328 let saved: Header = bincode::deserialize(&plain[4..4 + length])
329 .map_err(|error| format!("not a save state: {error}"))?;
330 let ours = header(system);
331 if saved.machine != ours.machine {
332 return Err(format!(
333 "a state of the {}, not the {}",
334 saved.machine, ours.machine
335 ));
336 }
337 if saved.card != ours.card {
338 return Err("a state of another ROM image (another card?)".to_string());
339 }
340 if saved.port != ours.port {
341 return Err(
342 "a state made with another expansion device or other media (another disc?)".to_string(),
343 );
344 }
345 if saved != ours {
346 return Err("a state of a machine built another way".to_string());
347 }
348 let body: Body = bincode::deserialize(&plain[4 + length..])
349 .map_err(|error| format!("not a save state: {error}"))?;
350 apply(system, body)
351}
352
353pub fn save_snapshot(system: &System) -> Vec<u8> {
356 bincode::serialize(&body(system)).expect("a state serialises")
357}
358
359pub fn load_snapshot(system: &mut System, data: &[u8]) -> Result<(), String> {
362 let body: Body =
363 bincode::deserialize(data).map_err(|error| format!("not a snapshot: {error}"))?;
364 apply(system, body)
365}