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.ch1Dead && (state->audio.ch1.envelopeNextStep < 0 ||
107 state->audio.ch1.waveNextStep < 0 ||
108 state->audio.ch1.sweepNextStep < 0 ||
109 state->audio.ch1.nextEvent < 0)) {
110 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 1 register is negative");
111 error = true;
112 }
113 if (!state->audio.ch2Dead && (state->audio.ch2.envelopeNextStep < 0 ||
114 state->audio.ch2.waveNextStep < 0 ||
115 state->audio.ch2.nextEvent < 0)) {
116 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 2 register is negative");
117 error = true;
118 }
119 if (state->audio.ch3.nextEvent < 0) {
120 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 3 register is negative");
121 error = true;
122 }
123 if (!state->audio.ch4Dead && (state->audio.ch4.envelopeNextStep < 0 ||
124 state->audio.ch4.nextEvent < 0)) {
125 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 4 register is negative");
126 error = true;
127 }
128 int region = (state->cpu.gprs[ARM_PC] >> BASE_OFFSET);
129 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) {
130 GBALog(gba, GBA_LOG_WARN, "Savestate created using a differently sized version of the ROM");
131 error = true;
132 }
133 if (error) {
134 return false;
135 }
136 memcpy(gba->cpu->gprs, state->cpu.gprs, sizeof(gba->cpu->gprs));
137 gba->cpu->cpsr = state->cpu.cpsr;
138 gba->cpu->spsr = state->cpu.spsr;
139 gba->cpu->cycles = state->cpu.cycles;
140 gba->cpu->nextEvent = state->cpu.nextEvent;
141 memcpy(gba->cpu->bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
142 memcpy(gba->cpu->bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
143 gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
144 gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
145 if (state->biosPrefetch) {
146 gba->memory.biosPrefetch = state->biosPrefetch;
147 }
148 if (gba->cpu->cpsr.t) {
149 gba->cpu->executionMode = MODE_THUMB;
150 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
151 gba->cpu->prefetch[0] = state->cpuPrefetch[0] & 0xFFFF;
152 gba->cpu->prefetch[1] = state->cpuPrefetch[1] & 0xFFFF;
153 } else {
154 // Maintain backwards compat
155 LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
156 LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
157 }
158 } else {
159 gba->cpu->executionMode = MODE_ARM;
160 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
161 gba->cpu->prefetch[0] = state->cpuPrefetch[0];
162 gba->cpu->prefetch[1] = state->cpuPrefetch[1];
163 } else {
164 // Maintain backwards compat
165 LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
166 LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
167 }
168 }
169
170 GBAMemoryDeserialize(&gba->memory, state);
171 GBAIODeserialize(gba, state);
172 GBAVideoDeserialize(&gba->video, state);
173 GBAAudioDeserialize(&gba->audio, state);
174 GBASavedataDeserialize(&gba->memory.savedata, state, false);
175
176 if (gba->rr) {
177 gba->rr->stateLoaded(gba->rr, state);
178 }
179 return true;
180}
181
182struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
183 char suffix[5] = { '\0' };
184 snprintf(suffix, sizeof(suffix), ".ss%d", slot);
185 return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
186}
187
188#ifdef USE_PNG
189static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
190 unsigned stride;
191 void* pixels = 0;
192 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
193 if (!pixels) {
194 return false;
195 }
196
197 struct GBASerializedState* state = GBAAllocateState();
198 if (!state) {
199 return false;
200 }
201 png_structp png = PNGWriteOpen(vf);
202 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
203 if (!png || !info) {
204 PNGWriteClose(png, info);
205 GBADeallocateState(state);
206 return false;
207 }
208 uLongf len = compressBound(sizeof(*state));
209 void* buffer = malloc(len);
210 if (!buffer) {
211 PNGWriteClose(png, info);
212 GBADeallocateState(state);
213 return false;
214 }
215 GBASerialize(gba, state);
216 compress(buffer, &len, (const Bytef*) state, sizeof(*state));
217 PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
218 PNGWriteCustomChunk(png, "gbAs", len, buffer);
219 PNGWriteClose(png, info);
220 free(buffer);
221 GBADeallocateState(state);
222 return true;
223}
224
225static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
226 if (strcmp((const char*) chunk->name, "gbAs") != 0) {
227 return 0;
228 }
229 struct GBASerializedState state;
230 uLongf len = sizeof(state);
231 uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
232 if (!GBADeserialize(png_get_user_chunk_ptr(png), &state)) {
233 longjmp(png_jmpbuf(png), 1);
234 }
235 return 1;
236}
237
238static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
239 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
240 png_infop info = png_create_info_struct(png);
241 png_infop end = png_create_info_struct(png);
242 if (!png || !info || !end) {
243 PNGReadClose(png, info, end);
244 return false;
245 }
246 uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
247
248 PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
249 bool success = PNGReadHeader(png, info);
250 success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
251 success = success && PNGReadFooter(png, end);
252 PNGReadClose(png, info, end);
253 if (success) {
254 gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
255 GBASyncForceFrame(gba->sync);
256 }
257
258 free(pixels);
259 return success;
260}
261#endif
262
263bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
264 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
265 if (!vf) {
266 return false;
267 }
268 bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
269 vf->close(vf);
270 if (success) {
271 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
272 } else {
273 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
274 }
275 return success;
276}
277
278bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
279 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
280 if (!vf) {
281 return false;
282 }
283 threadContext->rewindBufferSize = 0;
284 bool success = GBALoadStateNamed(threadContext->gba, vf);
285 vf->close(vf);
286 if (success) {
287 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
288 } else {
289 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
290 }
291 return success;
292}
293
294bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
295 if (!screenshot) {
296 vf->truncate(vf, sizeof(struct GBASerializedState));
297 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
298 if (!state) {
299 return false;
300 }
301 GBASerialize(gba, state);
302 vf->unmap(vf, state, sizeof(struct GBASerializedState));
303 return true;
304 }
305#ifdef USE_PNG
306 else {
307 return _savePNGState(gba, vf);
308 }
309#endif
310 return false;
311}
312
313bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
314#ifdef USE_PNG
315 if (isPNG(vf)) {
316 return _loadPNGState(gba, vf);
317 }
318#endif
319 if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
320 return false;
321 }
322 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
323 if (!state) {
324 return false;
325 }
326 bool success = GBADeserialize(gba, state);
327 vf->unmap(vf, state, sizeof(struct GBASerializedState));
328 return success;
329}
330
331struct GBASerializedState* GBAAllocateState(void) {
332 return anonymousMemoryMap(sizeof(struct GBASerializedState));
333}
334
335void GBADeallocateState(struct GBASerializedState* state) {
336 mappedMemoryFree(state, sizeof(struct GBASerializedState));
337}
338
339void GBARecordFrame(struct GBAThread* thread) {
340 int offset = thread->rewindBufferWriteOffset;
341 struct GBASerializedState* state = thread->rewindBuffer[offset];
342 if (!state) {
343 state = GBAAllocateState();
344 thread->rewindBuffer[offset] = state;
345 }
346 GBASerialize(thread->gba, state);
347
348 if (thread->rewindScreenBuffer) {
349 unsigned stride;
350 uint8_t* pixels = 0;
351 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
352 if (pixels) {
353 size_t y;
354 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
355 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);
356 }
357 }
358 }
359 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
360 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
361}
362
363void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
364 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
365 return;
366 }
367 threadContext->rewindBufferInterval = newInterval;
368 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
369 threadContext->rewindBufferSize = 0;
370 if (threadContext->rewindBuffer) {
371 int i;
372 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
373 GBADeallocateState(threadContext->rewindBuffer[i]);
374 }
375 free(threadContext->rewindBuffer);
376 free(threadContext->rewindScreenBuffer);
377 }
378 threadContext->rewindBufferCapacity = newCapacity;
379 if (threadContext->rewindBufferCapacity > 0) {
380 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
381 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
382 } else {
383 threadContext->rewindBuffer = 0;
384 threadContext->rewindScreenBuffer = 0;
385 }
386}
387
388int GBARewind(struct GBAThread* thread, int nStates) {
389 if (nStates > thread->rewindBufferSize || nStates < 0) {
390 nStates = thread->rewindBufferSize;
391 }
392 if (nStates == 0) {
393 return 0;
394 }
395 int offset = thread->rewindBufferWriteOffset - nStates;
396 if (offset < 0) {
397 offset += thread->rewindBufferCapacity;
398 }
399 struct GBASerializedState* state = thread->rewindBuffer[offset];
400 if (!state) {
401 return 0;
402 }
403 thread->rewindBufferSize -= nStates;
404 thread->rewindBufferWriteOffset = offset;
405 GBADeserialize(thread->gba, state);
406 if (thread->rewindScreenBuffer) {
407 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
408 }
409 return nStates;
410}
411
412void GBARewindAll(struct GBAThread* thread) {
413 GBARewind(thread, thread->rewindBufferSize);
414}