src/gba/serialize.c (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "serialize.h"
7
8#include "gba/audio.h"
9#include "gba/io.h"
10#include "gba/supervisor/rr.h"
11#include "gba/supervisor/thread.h"
12#include "gba/video.h"
13
14#include "util/memory.h"
15#include "util/vfs.h"
16
17#include <fcntl.h>
18
19#ifdef USE_PNG
20#include "util/png-io.h"
21#include <png.h>
22#include <zlib.h>
23#endif
24
25const uint32_t GBA_SAVESTATE_MAGIC = 0x01000000;
26
27void GBASerialize(struct GBA* gba, struct GBASerializedState* state) {
28 state->versionMagic = GBA_SAVESTATE_MAGIC;
29 state->biosChecksum = gba->biosChecksum;
30 state->romCrc32 = gba->romCrc32;
31
32 if (gba->memory.rom) {
33 state->id = ((struct GBACartridge*) gba->memory.rom)->id;
34 memcpy(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title));
35 } else {
36 state->id = 0;
37 memset(state->title, 0, sizeof(state->title));
38 }
39
40 memcpy(state->cpu.gprs, gba->cpu->gprs, sizeof(state->cpu.gprs));
41 state->cpu.cpsr = gba->cpu->cpsr;
42 state->cpu.spsr = gba->cpu->spsr;
43 state->cpu.cycles = gba->cpu->cycles;
44 state->cpu.nextEvent = gba->cpu->nextEvent;
45 memcpy(state->cpu.bankedRegisters, gba->cpu->bankedRegisters, 6 * 7 * sizeof(int32_t));
46 memcpy(state->cpu.bankedSPSRs, gba->cpu->bankedSPSRs, 6 * sizeof(int32_t));
47
48 state->biosPrefetch = gba->memory.biosPrefetch;
49 state->cpuPrefetch[0] = gba->cpu->prefetch[0];
50 state->cpuPrefetch[1] = gba->cpu->prefetch[1];
51
52 GBAMemorySerialize(&gba->memory, state);
53 GBAIOSerialize(gba, state);
54 GBAVideoSerialize(&gba->video, state);
55 GBAAudioSerialize(&gba->audio, state);
56 GBASavedataSerialize(&gba->memory.savedata, state, false);
57
58 state->associatedStreamId = 0;
59 if (gba->rr) {
60 gba->rr->stateSaved(gba->rr, state);
61 }
62}
63
64bool GBADeserialize(struct GBA* gba, const struct GBASerializedState* state) {
65 bool error = false;
66 if (state->versionMagic != GBA_SAVESTATE_MAGIC) {
67 GBALog(gba, GBA_LOG_WARN, "Invalid or too new savestate");
68 error = true;
69 }
70 if (state->biosChecksum != gba->biosChecksum) {
71 GBALog(gba, GBA_LOG_WARN, "Savestate created using a different version of the BIOS");
72 if (state->cpu.gprs[ARM_PC] < SIZE_BIOS && state->cpu.gprs[ARM_PC] >= 0x20) {
73 error = true;
74 }
75 }
76 if (gba->memory.rom && (state->id != ((struct GBACartridge*) gba->memory.rom)->id || memcmp(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title)))) {
77 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different game");
78 error = true;
79 } else if (!gba->memory.rom && state->id != 0) {
80 GBALog(gba, GBA_LOG_WARN, "Savestate is for a game, but no game loaded");
81 error = true;
82 }
83 if (state->romCrc32 != gba->romCrc32) {
84 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different version of the game");
85 }
86 if (state->cpu.cycles < 0) {
87 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are negative");
88 error = true;
89 }
90 if (state->video.eventDiff < 0) {
91 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: video eventDiff is negative");
92 error = true;
93 }
94 if (state->video.nextHblank - state->video.eventDiff < 0) {
95 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: nextHblank is negative");
96 error = true;
97 }
98 if (state->timers[0].overflowInterval < 0 || state->timers[1].overflowInterval < 0 || state->timers[2].overflowInterval < 0 || state->timers[3].overflowInterval < 0) {
99 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: overflowInterval is negative");
100 error = true;
101 }
102 if (state->audio.eventDiff < 0) {
103 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio eventDiff is negative");
104 error = true;
105 }
106 if (state->audio.ch1.envelopeNextStep < 0 || state->audio.ch1.waveNextStep < 0 || state->audio.ch1.sweepNextStep < 0 || state->audio.ch1.nextEvent < 0) {
107 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 1 register is negative");
108 error = true;
109 }
110 if (state->audio.ch2.envelopeNextStep < 0 || state->audio.ch2.waveNextStep < 0 || state->audio.ch2.nextEvent < 0) {
111 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 2 register is negative");
112 error = true;
113 }
114 if (state->audio.ch3.nextEvent < 0) {
115 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 3 register is negative");
116 error = true;
117 }
118 if (state->audio.ch4.envelopeNextStep < 0 || state->audio.ch4.nextEvent < 0) {
119 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 4 register is negative");
120 error = true;
121 }
122 int region = (state->cpu.gprs[ARM_PC] >> BASE_OFFSET);
123 if ((region == REGION_CART0 || region == REGION_CART1 || region == REGION_CART2) && ((state->cpu.gprs[ARM_PC] - WORD_SIZE_ARM) & SIZE_CART0) >= gba->memory.romSize - WORD_SIZE_ARM) {
124 GBALog(gba, GBA_LOG_WARN, "Savestate created using a differently sized version of the ROM");
125 error = true;
126 }
127 if (error) {
128 return false;
129 }
130 memcpy(gba->cpu->gprs, state->cpu.gprs, sizeof(gba->cpu->gprs));
131 gba->cpu->cpsr = state->cpu.cpsr;
132 gba->cpu->spsr = state->cpu.spsr;
133 gba->cpu->cycles = state->cpu.cycles;
134 gba->cpu->nextEvent = state->cpu.nextEvent;
135 memcpy(gba->cpu->bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
136 memcpy(gba->cpu->bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
137 gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
138 gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
139 if (state->biosPrefetch) {
140 gba->memory.biosPrefetch = state->biosPrefetch;
141 }
142 if (gba->cpu->cpsr.t) {
143 gba->cpu->executionMode = MODE_THUMB;
144 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
145 gba->cpu->prefetch[0] = state->cpuPrefetch[0] & 0xFFFF;
146 gba->cpu->prefetch[1] = state->cpuPrefetch[1] & 0xFFFF;
147 } else {
148 // Maintain backwards compat
149 LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
150 LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
151 }
152 } else {
153 gba->cpu->executionMode = MODE_ARM;
154 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
155 gba->cpu->prefetch[0] = state->cpuPrefetch[0];
156 gba->cpu->prefetch[1] = state->cpuPrefetch[1];
157 } else {
158 // Maintain backwards compat
159 LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
160 LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
161 }
162 }
163
164 GBAMemoryDeserialize(&gba->memory, state);
165 GBAIODeserialize(gba, state);
166 GBAVideoDeserialize(&gba->video, state);
167 GBAAudioDeserialize(&gba->audio, state);
168 GBASavedataDeserialize(&gba->memory.savedata, state, false);
169
170 if (gba->rr) {
171 gba->rr->stateLoaded(gba->rr, state);
172 }
173 return true;
174}
175
176struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
177 char suffix[5] = { '\0' };
178 snprintf(suffix, sizeof(suffix), ".ss%d", slot);
179 return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
180}
181
182#ifdef USE_PNG
183static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
184 unsigned stride;
185 void* pixels = 0;
186 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
187 if (!pixels) {
188 return false;
189 }
190
191 struct GBASerializedState* state = GBAAllocateState();
192 if (!state) {
193 return false;
194 }
195 png_structp png = PNGWriteOpen(vf);
196 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
197 if (!png || !info) {
198 PNGWriteClose(png, info);
199 GBADeallocateState(state);
200 return false;
201 }
202 uLongf len = compressBound(sizeof(*state));
203 void* buffer = malloc(len);
204 if (!buffer) {
205 PNGWriteClose(png, info);
206 GBADeallocateState(state);
207 return false;
208 }
209 GBASerialize(gba, state);
210 compress(buffer, &len, (const Bytef*) state, sizeof(*state));
211 PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
212 PNGWriteCustomChunk(png, "gbAs", len, buffer);
213 PNGWriteClose(png, info);
214 free(buffer);
215 GBADeallocateState(state);
216 return true;
217}
218
219static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
220 if (strcmp((const char*) chunk->name, "gbAs") != 0) {
221 return 0;
222 }
223 struct GBASerializedState state;
224 uLongf len = sizeof(state);
225 uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
226 return GBADeserialize(png_get_user_chunk_ptr(png), &state);
227}
228
229static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
230 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
231 png_infop info = png_create_info_struct(png);
232 png_infop end = png_create_info_struct(png);
233 if (!png || !info || !end) {
234 PNGReadClose(png, info, end);
235 return false;
236 }
237 uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
238
239 PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
240 PNGReadHeader(png, info);
241 PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
242 PNGReadFooter(png, end);
243 PNGReadClose(png, info, end);
244 gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
245 GBASyncForceFrame(gba->sync);
246
247 free(pixels);
248 return true;
249}
250#endif
251
252bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
253 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
254 if (!vf) {
255 return false;
256 }
257 bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
258 vf->close(vf);
259 if (success) {
260 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
261 } else {
262 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
263 }
264 return success;
265}
266
267bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
268 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
269 if (!vf) {
270 return false;
271 }
272 threadContext->rewindBufferSize = 0;
273 bool success = GBALoadStateNamed(threadContext->gba, vf);
274 vf->close(vf);
275 if (success) {
276 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
277 } else {
278 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
279 }
280 return success;
281}
282
283bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
284 if (!screenshot) {
285 vf->truncate(vf, sizeof(struct GBASerializedState));
286 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
287 if (!state) {
288 return false;
289 }
290 GBASerialize(gba, state);
291 vf->unmap(vf, state, sizeof(struct GBASerializedState));
292 return true;
293 }
294 #ifdef USE_PNG
295 else {
296 return _savePNGState(gba, vf);
297 }
298 #endif
299 return false;
300}
301
302bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
303 #ifdef USE_PNG
304 if (isPNG(vf)) {
305 return _loadPNGState(gba, vf);
306 }
307 #endif
308 if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
309 return false;
310 }
311 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
312 if (!state) {
313 return false;
314 }
315 bool success = GBADeserialize(gba, state);
316 vf->unmap(vf, state, sizeof(struct GBASerializedState));
317 return success;
318}
319
320struct GBASerializedState* GBAAllocateState(void) {
321 return anonymousMemoryMap(sizeof(struct GBASerializedState));
322}
323
324void GBADeallocateState(struct GBASerializedState* state) {
325 mappedMemoryFree(state, sizeof(struct GBASerializedState));
326}
327
328void GBARecordFrame(struct GBAThread* thread) {
329 int offset = thread->rewindBufferWriteOffset;
330 struct GBASerializedState* state = thread->rewindBuffer[offset];
331 if (!state) {
332 state = GBAAllocateState();
333 thread->rewindBuffer[offset] = state;
334 }
335 GBASerialize(thread->gba, state);
336
337 if (thread->rewindScreenBuffer) {
338 unsigned stride;
339 uint8_t* pixels = 0;
340 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
341 if (pixels) {
342 size_t y;
343 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
344 memcpy(&thread->rewindScreenBuffer[(offset * VIDEO_VERTICAL_PIXELS + y) * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL], &pixels[y * stride * BYTES_PER_PIXEL], VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
345 }
346 }
347 }
348 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
349 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
350}
351
352void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
353 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
354 return;
355 }
356 threadContext->rewindBufferInterval = newInterval;
357 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
358 threadContext->rewindBufferSize = 0;
359 if (threadContext->rewindBuffer) {
360 int i;
361 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
362 GBADeallocateState(threadContext->rewindBuffer[i]);
363 }
364 free(threadContext->rewindBuffer);
365 free(threadContext->rewindScreenBuffer);
366 }
367 threadContext->rewindBufferCapacity = newCapacity;
368 if (threadContext->rewindBufferCapacity > 0) {
369 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
370 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
371 } else {
372 threadContext->rewindBuffer = 0;
373 threadContext->rewindScreenBuffer = 0;
374 }
375}
376
377int GBARewind(struct GBAThread* thread, int nStates) {
378 if (nStates > thread->rewindBufferSize || nStates < 0) {
379 nStates = thread->rewindBufferSize;
380 }
381 if (nStates == 0) {
382 return 0;
383 }
384 int offset = thread->rewindBufferWriteOffset - nStates;
385 if (offset < 0) {
386 offset += thread->rewindBufferCapacity;
387 }
388 struct GBASerializedState* state = thread->rewindBuffer[offset];
389 if (!state) {
390 return 0;
391 }
392 thread->rewindBufferSize -= nStates;
393 thread->rewindBufferWriteOffset = offset;
394 GBADeserialize(thread->gba, state);
395 if (thread->rewindScreenBuffer) {
396 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
397 }
398 return nStates;
399}
400
401void GBARewindAll(struct GBAThread* thread) {
402 GBARewind(thread, thread->rewindBufferSize);
403}