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 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
269 } else {
270 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
271 }
272 return success;
273}
274
275bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
276 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
277 if (!vf) {
278 return false;
279 }
280 threadContext->rewindBufferSize = 0;
281 bool success = GBALoadStateNamed(threadContext->gba, vf);
282 vf->close(vf);
283 if (success) {
284 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
285 } else {
286 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
287 }
288 return success;
289}
290#endif
291
292bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
293#ifdef USE_PNG
294 if (!screenshot) {
295#else
296 UNUSED(screenshot);
297#endif
298 vf->truncate(vf, sizeof(struct GBASerializedState));
299 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
300 if (!state) {
301 return false;
302 }
303 GBASerialize(gba, state);
304 vf->unmap(vf, state, sizeof(struct GBASerializedState));
305 return true;
306#ifdef USE_PNG
307 }
308 else {
309 return _savePNGState(gba, vf);
310 }
311#endif
312 return false;
313}
314
315bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
316#ifdef USE_PNG
317 if (isPNG(vf)) {
318 return _loadPNGState(gba, vf);
319 }
320#endif
321 if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
322 return false;
323 }
324 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
325 if (!state) {
326 return false;
327 }
328 bool success = GBADeserialize(gba, state);
329 vf->unmap(vf, state, sizeof(struct GBASerializedState));
330 return success;
331}
332
333struct GBASerializedState* GBAAllocateState(void) {
334 return anonymousMemoryMap(sizeof(struct GBASerializedState));
335}
336
337void GBADeallocateState(struct GBASerializedState* state) {
338 mappedMemoryFree(state, sizeof(struct GBASerializedState));
339}
340
341void GBARecordFrame(struct GBAThread* thread) {
342 int offset = thread->rewindBufferWriteOffset;
343 struct GBASerializedState* state = thread->rewindBuffer[offset];
344 if (!state) {
345 state = GBAAllocateState();
346 thread->rewindBuffer[offset] = state;
347 }
348 GBASerialize(thread->gba, state);
349
350 if (thread->rewindScreenBuffer) {
351 unsigned stride;
352 const uint8_t* pixels = 0;
353 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (const void**) &pixels);
354 if (pixels) {
355 size_t y;
356 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
357 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);
358 }
359 }
360 }
361 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
362 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
363}
364
365void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
366 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
367 return;
368 }
369 threadContext->rewindBufferInterval = newInterval;
370 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
371 threadContext->rewindBufferSize = 0;
372 if (threadContext->rewindBuffer) {
373 int i;
374 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
375 GBADeallocateState(threadContext->rewindBuffer[i]);
376 }
377 free(threadContext->rewindBuffer);
378 free(threadContext->rewindScreenBuffer);
379 }
380 threadContext->rewindBufferCapacity = newCapacity;
381 if (threadContext->rewindBufferCapacity > 0) {
382 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
383 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
384 } else {
385 threadContext->rewindBuffer = 0;
386 threadContext->rewindScreenBuffer = 0;
387 }
388}
389
390int GBARewind(struct GBAThread* thread, int nStates) {
391 if (nStates > thread->rewindBufferSize || nStates < 0) {
392 nStates = thread->rewindBufferSize;
393 }
394 if (nStates == 0) {
395 return 0;
396 }
397 int offset = thread->rewindBufferWriteOffset - nStates;
398 if (offset < 0) {
399 offset += thread->rewindBufferCapacity;
400 }
401 struct GBASerializedState* state = thread->rewindBuffer[offset];
402 if (!state) {
403 return 0;
404 }
405 thread->rewindBufferSize -= nStates;
406 thread->rewindBufferWriteOffset = offset;
407 GBADeserialize(thread->gba, state);
408 if (thread->rewindScreenBuffer) {
409 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
410 }
411 return nStates;
412}
413
414void GBARewindAll(struct GBAThread* thread) {
415 GBARewind(thread, thread->rewindBufferSize);
416}
417
418void GBATakeScreenshot(struct GBA* gba, struct VDir* dir) {
419#ifdef USE_PNG
420 unsigned stride;
421 const void* pixels = 0;
422 struct VFile* vf = VDirOptionalOpenIncrementFile(dir, gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
423 bool success = false;
424 if (vf) {
425 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
426 png_structp png = PNGWriteOpen(vf);
427 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
428 success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
429 PNGWriteClose(png, info);
430 vf->close(vf);
431 }
432 if (success) {
433 GBALog(gba, GBA_LOG_STATUS, "Screenshot saved");
434 return;
435 }
436#endif
437 GBALog(gba, GBA_LOG_STATUS, "Failed to take screenshot");
438}