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 state->id = ((struct GBACartridge*) gba->memory.rom)->id;
33 memcpy(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title));
34
35 memcpy(state->cpu.gprs, gba->cpu->gprs, sizeof(state->cpu.gprs));
36 state->cpu.cpsr = gba->cpu->cpsr;
37 state->cpu.spsr = gba->cpu->spsr;
38 state->cpu.cycles = gba->cpu->cycles;
39 state->cpu.nextEvent = gba->cpu->nextEvent;
40 memcpy(state->cpu.bankedRegisters, gba->cpu->bankedRegisters, 6 * 7 * sizeof(int32_t));
41 memcpy(state->cpu.bankedSPSRs, gba->cpu->bankedSPSRs, 6 * sizeof(int32_t));
42
43 state->biosPrefetch = gba->memory.biosPrefetch;
44 state->cpuPrefetch[0] = gba->cpu->prefetch[0];
45 state->cpuPrefetch[1] = gba->cpu->prefetch[1];
46
47 GBAMemorySerialize(&gba->memory, state);
48 GBAIOSerialize(gba, state);
49 GBAVideoSerialize(&gba->video, state);
50 GBAAudioSerialize(&gba->audio, state);
51 GBASavedataSerialize(&gba->memory.savedata, state, false);
52
53 state->associatedStreamId = 0;
54 if (gba->rr) {
55 gba->rr->stateSaved(gba->rr, state);
56 }
57}
58
59void GBADeserialize(struct GBA* gba, const struct GBASerializedState* state) {
60 if (state->versionMagic != GBA_SAVESTATE_MAGIC) {
61 GBALog(gba, GBA_LOG_WARN, "Invalid or too new savestate");
62 return;
63 }
64 if (state->biosChecksum != gba->biosChecksum) {
65 GBALog(gba, GBA_LOG_WARN, "Savestate created using a different version of the BIOS");
66 if (state->cpu.gprs[ARM_PC] < SIZE_BIOS && state->cpu.gprs[ARM_PC] >= 0x20) {
67 return;
68 }
69 }
70 if (state->id != ((struct GBACartridge*) gba->memory.rom)->id || memcmp(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title))) {
71 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different game");
72 return;
73 }
74 if (state->romCrc32 != gba->romCrc32) {
75 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different version of the game");
76 }
77 memcpy(gba->cpu->gprs, state->cpu.gprs, sizeof(gba->cpu->gprs));
78 gba->cpu->cpsr = state->cpu.cpsr;
79 gba->cpu->spsr = state->cpu.spsr;
80 gba->cpu->cycles = state->cpu.cycles;
81 gba->cpu->nextEvent = state->cpu.nextEvent;
82 memcpy(gba->cpu->bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
83 memcpy(gba->cpu->bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
84 gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
85 gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
86 if (state->biosPrefetch) {
87 gba->memory.biosPrefetch = state->biosPrefetch;
88 }
89 if (gba->cpu->cpsr.t) {
90 gba->cpu->executionMode = MODE_THUMB;
91 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
92 gba->cpu->prefetch[0] = state->cpuPrefetch[0] & 0xFFFF;
93 gba->cpu->prefetch[1] = state->cpuPrefetch[1] & 0xFFFF;
94 } else {
95 // Maintain backwards compat
96 LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
97 LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
98 }
99 } else {
100 gba->cpu->executionMode = MODE_ARM;
101 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
102 gba->cpu->prefetch[0] = state->cpuPrefetch[0];
103 gba->cpu->prefetch[1] = state->cpuPrefetch[1];
104 } else {
105 // Maintain backwards compat
106 LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
107 LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
108 }
109 }
110
111 GBAMemoryDeserialize(&gba->memory, state);
112 GBAIODeserialize(gba, state);
113 GBAVideoDeserialize(&gba->video, state);
114 GBAAudioDeserialize(&gba->audio, state);
115 GBASavedataDeserialize(&gba->memory.savedata, state, false);
116
117 if (gba->rr) {
118 gba->rr->stateLoaded(gba->rr, state);
119 }
120}
121
122struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
123 char suffix[5] = { '\0' };
124 snprintf(suffix, sizeof(suffix), ".ss%d", slot);
125 return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
126}
127
128#ifdef USE_PNG
129static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
130 unsigned stride;
131 void* pixels = 0;
132 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
133 if (!pixels) {
134 return false;
135 }
136
137 struct GBASerializedState* state = GBAAllocateState();
138 png_structp png = PNGWriteOpen(vf);
139 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
140 uLongf len = compressBound(sizeof(*state));
141 void* buffer = malloc(len);
142 if (state && png && info && buffer) {
143 GBASerialize(gba, state);
144 compress(buffer, &len, (const Bytef*) state, sizeof(*state));
145 PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
146 PNGWriteCustomChunk(png, "gbAs", len, buffer);
147 }
148 PNGWriteClose(png, info);
149 free(buffer);
150 GBADeallocateState(state);
151 return state && png && info && buffer;
152}
153
154static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
155 if (strcmp((const char*) chunk->name, "gbAs") != 0) {
156 return 0;
157 }
158 struct GBASerializedState state;
159 uLongf len = sizeof(state);
160 uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
161 GBADeserialize(png_get_user_chunk_ptr(png), &state);
162 return 1;
163}
164
165static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
166 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
167 png_infop info = png_create_info_struct(png);
168 png_infop end = png_create_info_struct(png);
169 if (!png || !info || !end) {
170 PNGReadClose(png, info, end);
171 return false;
172 }
173 uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
174
175 PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
176 PNGReadHeader(png, info);
177 PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
178 PNGReadFooter(png, end);
179 PNGReadClose(png, info, end);
180 gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
181 GBASyncForceFrame(gba->sync);
182
183 free(pixels);
184 return true;
185}
186#endif
187
188bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
189 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
190 if (!vf) {
191 return false;
192 }
193 bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
194 vf->close(vf);
195 return success;
196}
197
198bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
199 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
200 if (!vf) {
201 return false;
202 }
203 threadContext->rewindBufferSize = 0;
204 bool success = GBALoadStateNamed(threadContext->gba, vf);
205 vf->close(vf);
206 return success;
207}
208
209bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
210 if (!screenshot) {
211 vf->truncate(vf, sizeof(struct GBASerializedState));
212 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
213 if (!state) {
214 return false;
215 }
216 GBASerialize(gba, state);
217 vf->unmap(vf, state, sizeof(struct GBASerializedState));
218 return true;
219 }
220 #ifdef USE_PNG
221 else {
222 return _savePNGState(gba, vf);
223 }
224 #endif
225 return false;
226}
227
228bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
229 #ifdef USE_PNG
230 if (isPNG(vf)) {
231 return _loadPNGState(gba, vf);
232 }
233 #endif
234 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
235 if (!state) {
236 return false;
237 }
238 GBADeserialize(gba, state);
239 vf->unmap(vf, state, sizeof(struct GBASerializedState));
240 return true;
241}
242
243struct GBASerializedState* GBAAllocateState(void) {
244 return anonymousMemoryMap(sizeof(struct GBASerializedState));
245}
246
247void GBADeallocateState(struct GBASerializedState* state) {
248 mappedMemoryFree(state, sizeof(struct GBASerializedState));
249}
250
251void GBARecordFrame(struct GBAThread* thread) {
252 int offset = thread->rewindBufferWriteOffset;
253 struct GBASerializedState* state = thread->rewindBuffer[offset];
254 if (!state) {
255 state = GBAAllocateState();
256 thread->rewindBuffer[offset] = state;
257 }
258 GBASerialize(thread->gba, state);
259
260 if (thread->rewindScreenBuffer) {
261 unsigned stride;
262 uint8_t* pixels = 0;
263 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
264 if (pixels) {
265 size_t y;
266 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
267 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);
268 }
269 }
270 }
271 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
272 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
273}
274
275void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
276 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
277 return;
278 }
279 threadContext->rewindBufferInterval = newInterval;
280 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
281 threadContext->rewindBufferSize = 0;
282 if (threadContext->rewindBuffer) {
283 int i;
284 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
285 GBADeallocateState(threadContext->rewindBuffer[i]);
286 }
287 free(threadContext->rewindBuffer);
288 free(threadContext->rewindScreenBuffer);
289 }
290 threadContext->rewindBufferCapacity = newCapacity;
291 if (threadContext->rewindBufferCapacity > 0) {
292 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
293 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
294 } else {
295 threadContext->rewindBuffer = 0;
296 threadContext->rewindScreenBuffer = 0;
297 }
298}
299
300void GBARewind(struct GBAThread* thread, int nStates) {
301 if (nStates > thread->rewindBufferSize || nStates < 0) {
302 nStates = thread->rewindBufferSize;
303 }
304 if (nStates == 0) {
305 return;
306 }
307 int offset = thread->rewindBufferWriteOffset - nStates;
308 if (offset < 0) {
309 offset += thread->rewindBufferCapacity;
310 }
311 struct GBASerializedState* state = thread->rewindBuffer[offset];
312 if (!state) {
313 return;
314 }
315 thread->rewindBufferSize -= nStates;
316 thread->rewindBufferWriteOffset = offset;
317 GBADeserialize(thread->gba, state);
318 if (thread->rewindScreenBuffer) {
319 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
320 }
321}
322
323void GBARewindAll(struct GBAThread* thread) {
324 GBARewind(thread, thread->rewindBufferSize);
325}