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