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/rr/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 int32_t check;
67 uint32_t ucheck;
68 LOAD_32(ucheck, 0, &state->versionMagic);
69 if (ucheck != GBA_SAVESTATE_MAGIC) {
70 GBALog(gba, GBA_LOG_WARN, "Invalid or too new savestate: expected %08X, got %08X", GBA_SAVESTATE_MAGIC, ucheck);
71 error = true;
72 }
73 LOAD_32(ucheck, 0, &state->biosChecksum);
74 if (ucheck != gba->biosChecksum) {
75 GBALog(gba, GBA_LOG_WARN, "Savestate created using a different version of the BIOS: expected %08X, got %08X", gba->biosChecksum, ucheck);
76 uint32_t pc;
77 LOAD_32(pc, ARM_PC * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
78 if (pc < SIZE_BIOS && pc >= 0x20) {
79 error = true;
80 }
81 }
82 if (gba->memory.rom && (state->id != ((struct GBACartridge*) gba->memory.rom)->id || memcmp(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title)))) {
83 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different game");
84 error = true;
85 } else if (!gba->memory.rom && state->id != 0) {
86 GBALog(gba, GBA_LOG_WARN, "Savestate is for a game, but no game loaded");
87 error = true;
88 }
89 LOAD_32(ucheck, 0, &state->romCrc32);
90 if (ucheck != gba->romCrc32) {
91 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different version of the game");
92 }
93 LOAD_32(check, 0, &state->cpu.cycles);
94 if (check < 0) {
95 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are negative");
96 error = true;
97 }
98 if (check >= (int32_t) GBA_ARM7TDMI_FREQUENCY) {
99 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are too high");
100 error = true;
101 }
102 LOAD_32(check, 0, &state->video.eventDiff);
103 if (check < 0) {
104 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: video eventDiff is negative");
105 error = true;
106 }
107 LOAD_32(check, ARM_PC * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
108 int region = (check >> BASE_OFFSET);
109 if ((region == REGION_CART0 || region == REGION_CART1 || region == REGION_CART2) && ((check - WORD_SIZE_ARM) & SIZE_CART0) >= gba->memory.romSize - WORD_SIZE_ARM) {
110 GBALog(gba, GBA_LOG_WARN, "Savestate created using a differently sized version of the ROM");
111 error = true;
112 }
113 if (error) {
114 return false;
115 }
116 size_t i;
117 for (i = 0; i < 16; ++i) {
118 LOAD_32(gba->cpu->gprs[i], i * sizeof(gba->cpu->gprs[0]), state->cpu.gprs);
119 }
120 LOAD_32(gba->cpu->cpsr.packed, 0, &state->cpu.cpsr.packed);
121 LOAD_32(gba->cpu->spsr.packed, 0, &state->cpu.spsr.packed);
122 LOAD_32(gba->cpu->cycles, 0, &state->cpu.cycles);
123 LOAD_32(gba->cpu->nextEvent, 0, &state->cpu.nextEvent);
124 for (i = 0; i < 6; ++i) {
125 int j;
126 for (j = 0; j < 7; ++j) {
127 LOAD_32(gba->cpu->bankedRegisters[i][j], (i * 7 + j) * sizeof(gba->cpu->bankedRegisters[0][0]), state->cpu.bankedRegisters);
128 }
129 LOAD_32(gba->cpu->bankedSPSRs[i], i * sizeof(gba->cpu->bankedSPSRs[0]), state->cpu.bankedSPSRs);
130 }
131 gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
132 gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
133 if (state->biosPrefetch) {
134 LOAD_32(gba->memory.biosPrefetch, 0, &state->biosPrefetch);
135 }
136 if (gba->cpu->cpsr.t) {
137 gba->cpu->executionMode = MODE_THUMB;
138 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
139 LOAD_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
140 LOAD_32(gba->cpu->prefetch[1], 2, state->cpuPrefetch);
141 gba->cpu->prefetch[0] &= 0xFFFF;
142 gba->cpu->prefetch[1] &= 0xFFFF;
143 } else {
144 // Maintain backwards compat
145 LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
146 LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
147 }
148 } else {
149 gba->cpu->executionMode = MODE_ARM;
150 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
151 LOAD_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
152 LOAD_32(gba->cpu->prefetch[1], 2, state->cpuPrefetch);
153 } else {
154 // Maintain backwards compat
155 LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
156 LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
157 }
158 }
159
160 GBAMemoryDeserialize(&gba->memory, state);
161 GBAIODeserialize(gba, state);
162 GBAVideoDeserialize(&gba->video, state);
163 GBAAudioDeserialize(&gba->audio, state);
164 GBASavedataDeserialize(&gba->memory.savedata, state, false);
165
166 if (gba->rr) {
167 gba->rr->stateLoaded(gba->rr, state);
168 }
169 return true;
170}
171
172struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
173 char suffix[5] = { '\0' };
174 snprintf(suffix, sizeof(suffix), ".ss%d", slot);
175 return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
176}
177
178#ifdef USE_PNG
179static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
180 unsigned stride;
181 const void* pixels = 0;
182 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
183 if (!pixels) {
184 return false;
185 }
186
187 struct GBASerializedState* state = GBAAllocateState();
188 if (!state) {
189 return false;
190 }
191 GBASerialize(gba, state);
192 uLongf len = compressBound(sizeof(*state));
193 void* buffer = malloc(len);
194 if (!buffer) {
195 GBADeallocateState(state);
196 return false;
197 }
198 compress(buffer, &len, (const Bytef*) state, sizeof(*state));
199 GBADeallocateState(state);
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 free(buffer);
206 return false;
207 }
208 PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
209 PNGWriteCustomChunk(png, "gbAs", len, buffer);
210 PNGWriteClose(png, info);
211 free(buffer);
212 return true;
213}
214
215static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
216 if (strcmp((const char*) chunk->name, "gbAs") != 0) {
217 return 0;
218 }
219 struct GBASerializedState* state = GBAAllocateState();
220 uLongf len = sizeof(*state);
221 uncompress((Bytef*) state, &len, chunk->data, chunk->size);
222 if (!GBADeserialize(png_get_user_chunk_ptr(png), state)) {
223 GBADeallocateState(state);
224 longjmp(png_jmpbuf(png), 1);
225 }
226 GBADeallocateState(state);
227 return 1;
228}
229
230static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
231 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
232 png_infop info = png_create_info_struct(png);
233 png_infop end = png_create_info_struct(png);
234 if (!png || !info || !end) {
235 PNGReadClose(png, info, end);
236 return false;
237 }
238 uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
239 if (!pixels) {
240 PNGReadClose(png, info, end);
241 return false;
242 }
243
244 PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
245 bool success = PNGReadHeader(png, info);
246 success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
247 success = success && PNGReadFooter(png, end);
248 PNGReadClose(png, info, end);
249 if (success) {
250 gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
251 GBASyncForceFrame(gba->sync);
252 }
253
254 free(pixels);
255 return success;
256}
257#endif
258
259#ifndef _3DS
260bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
261 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
262 if (!vf) {
263 return false;
264 }
265 bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
266 vf->close(vf);
267 if (success) {
268#if SAVESTATE_DEBUG
269 vf = GBAGetState(threadContext->gba, dir, slot, false);
270 if (vf) {
271 struct GBA* backup = anonymousMemoryMap(sizeof(*backup));
272 memcpy(backup, threadContext->gba, sizeof(*backup));
273 memset(threadContext->gba->memory.io, 0, sizeof(threadContext->gba->memory.io));
274 memset(threadContext->gba->timers, 0, sizeof(threadContext->gba->timers));
275 GBALoadStateNamed(threadContext->gba, vf);
276 if (memcmp(backup, threadContext->gba, sizeof(*backup))) {
277 char suffix[16] = { '\0' };
278 struct VFile* vf2;
279 snprintf(suffix, sizeof(suffix), ".dump.0.%d", slot);
280 vf2 = VDirOptionalOpenFile(dir, threadContext->gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
281 if (vf2) {
282 vf2->write(vf2, backup, sizeof(*backup));
283 vf2->close(vf2);
284 }
285 snprintf(suffix, sizeof(suffix), ".dump.1.%d", slot);
286 vf2 = VDirOptionalOpenFile(dir, threadContext->gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
287 if (vf2) {
288 vf2->write(vf2, threadContext->gba, sizeof(*threadContext->gba));
289 vf2->close(vf2);
290 }
291 }
292 mappedMemoryFree(backup, sizeof(*backup));
293 vf->close(vf);
294 }
295#endif
296 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
297 } else {
298 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
299 }
300
301 return success;
302}
303
304bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
305 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
306 if (!vf) {
307 return false;
308 }
309 threadContext->rewindBufferSize = 0;
310 bool success = GBALoadStateNamed(threadContext->gba, vf);
311 vf->close(vf);
312 if (success) {
313 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
314 } else {
315 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
316 }
317 return success;
318}
319#endif
320
321bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
322#ifdef USE_PNG
323 if (!screenshot) {
324#else
325 UNUSED(screenshot);
326#endif
327 vf->truncate(vf, sizeof(struct GBASerializedState));
328 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
329 if (!state) {
330 return false;
331 }
332 GBASerialize(gba, state);
333 vf->unmap(vf, state, sizeof(struct GBASerializedState));
334 return true;
335#ifdef USE_PNG
336 }
337 else {
338 return _savePNGState(gba, vf);
339 }
340#endif
341 return false;
342}
343
344bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
345#ifdef USE_PNG
346 if (isPNG(vf)) {
347 return _loadPNGState(gba, vf);
348 }
349#endif
350 if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
351 return false;
352 }
353 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
354 if (!state) {
355 return false;
356 }
357 bool success = GBADeserialize(gba, state);
358 vf->unmap(vf, state, sizeof(struct GBASerializedState));
359 return success;
360}
361
362struct GBASerializedState* GBAAllocateState(void) {
363 return anonymousMemoryMap(sizeof(struct GBASerializedState));
364}
365
366void GBADeallocateState(struct GBASerializedState* state) {
367 mappedMemoryFree(state, sizeof(struct GBASerializedState));
368}
369
370void GBARecordFrame(struct GBAThread* thread) {
371 int offset = thread->rewindBufferWriteOffset;
372 struct GBASerializedState* state = thread->rewindBuffer[offset];
373 if (!state) {
374 state = GBAAllocateState();
375 thread->rewindBuffer[offset] = state;
376 }
377 GBASerialize(thread->gba, state);
378
379 if (thread->rewindScreenBuffer) {
380 unsigned stride;
381 const uint8_t* pixels = 0;
382 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (const void**) &pixels);
383 if (pixels) {
384 size_t y;
385 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
386 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);
387 }
388 }
389 }
390 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
391 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
392}
393
394void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
395 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
396 return;
397 }
398 threadContext->rewindBufferInterval = newInterval;
399 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
400 threadContext->rewindBufferSize = 0;
401 if (threadContext->rewindBuffer) {
402 int i;
403 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
404 GBADeallocateState(threadContext->rewindBuffer[i]);
405 }
406 free(threadContext->rewindBuffer);
407 free(threadContext->rewindScreenBuffer);
408 }
409 threadContext->rewindBufferCapacity = newCapacity;
410 if (threadContext->rewindBufferCapacity > 0) {
411 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
412 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
413 } else {
414 threadContext->rewindBuffer = 0;
415 threadContext->rewindScreenBuffer = 0;
416 }
417}
418
419int GBARewind(struct GBAThread* thread, int nStates) {
420 if (nStates > thread->rewindBufferSize || nStates < 0) {
421 nStates = thread->rewindBufferSize;
422 }
423 if (nStates == 0) {
424 return 0;
425 }
426 int offset = thread->rewindBufferWriteOffset - nStates;
427 if (offset < 0) {
428 offset += thread->rewindBufferCapacity;
429 }
430 struct GBASerializedState* state = thread->rewindBuffer[offset];
431 if (!state) {
432 return 0;
433 }
434 thread->rewindBufferSize -= nStates;
435 thread->rewindBufferWriteOffset = offset;
436 GBADeserialize(thread->gba, state);
437 if (thread->rewindScreenBuffer) {
438 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
439 }
440 return nStates;
441}
442
443void GBARewindAll(struct GBAThread* thread) {
444 GBARewind(thread, thread->rewindBufferSize);
445}
446
447void GBATakeScreenshot(struct GBA* gba, struct VDir* dir) {
448#ifdef USE_PNG
449 unsigned stride;
450 const void* pixels = 0;
451 struct VFile* vf = VDirOptionalOpenIncrementFile(dir, gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
452 bool success = false;
453 if (vf) {
454 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
455 png_structp png = PNGWriteOpen(vf);
456 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
457 success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
458 PNGWriteClose(png, info);
459 vf->close(vf);
460 }
461 if (success) {
462 GBALog(gba, GBA_LOG_STATUS, "Screenshot saved");
463 return;
464 }
465#endif
466 GBALog(gba, GBA_LOG_STATUS, "Failed to take screenshot");
467}