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 if (success) {
196 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
197 }
198 return success;
199}
200
201bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
202 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
203 if (!vf) {
204 return false;
205 }
206 threadContext->rewindBufferSize = 0;
207 bool success = GBALoadStateNamed(threadContext->gba, vf);
208 vf->close(vf);
209 if (success) {
210 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
211 }
212 return success;
213}
214
215bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
216 if (!screenshot) {
217 vf->truncate(vf, sizeof(struct GBASerializedState));
218 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
219 if (!state) {
220 return false;
221 }
222 GBASerialize(gba, state);
223 vf->unmap(vf, state, sizeof(struct GBASerializedState));
224 return true;
225 }
226 #ifdef USE_PNG
227 else {
228 return _savePNGState(gba, vf);
229 }
230 #endif
231 return false;
232}
233
234bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
235 #ifdef USE_PNG
236 if (isPNG(vf)) {
237 return _loadPNGState(gba, vf);
238 }
239 #endif
240 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
241 if (!state) {
242 return false;
243 }
244 GBADeserialize(gba, state);
245 vf->unmap(vf, state, sizeof(struct GBASerializedState));
246 return true;
247}
248
249struct GBASerializedState* GBAAllocateState(void) {
250 return anonymousMemoryMap(sizeof(struct GBASerializedState));
251}
252
253void GBADeallocateState(struct GBASerializedState* state) {
254 mappedMemoryFree(state, sizeof(struct GBASerializedState));
255}
256
257void GBARecordFrame(struct GBAThread* thread) {
258 int offset = thread->rewindBufferWriteOffset;
259 struct GBASerializedState* state = thread->rewindBuffer[offset];
260 if (!state) {
261 state = GBAAllocateState();
262 thread->rewindBuffer[offset] = state;
263 }
264 GBASerialize(thread->gba, state);
265
266 if (thread->rewindScreenBuffer) {
267 unsigned stride;
268 uint8_t* pixels = 0;
269 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
270 if (pixels) {
271 size_t y;
272 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
273 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);
274 }
275 }
276 }
277 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
278 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
279}
280
281void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
282 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
283 return;
284 }
285 threadContext->rewindBufferInterval = newInterval;
286 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
287 threadContext->rewindBufferSize = 0;
288 if (threadContext->rewindBuffer) {
289 int i;
290 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
291 GBADeallocateState(threadContext->rewindBuffer[i]);
292 }
293 free(threadContext->rewindBuffer);
294 free(threadContext->rewindScreenBuffer);
295 }
296 threadContext->rewindBufferCapacity = newCapacity;
297 if (threadContext->rewindBufferCapacity > 0) {
298 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
299 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
300 } else {
301 threadContext->rewindBuffer = 0;
302 threadContext->rewindScreenBuffer = 0;
303 }
304}
305
306void GBARewind(struct GBAThread* thread, int nStates) {
307 if (nStates > thread->rewindBufferSize || nStates < 0) {
308 nStates = thread->rewindBufferSize;
309 }
310 if (nStates == 0) {
311 return;
312 }
313 int offset = thread->rewindBufferWriteOffset - nStates;
314 if (offset < 0) {
315 offset += thread->rewindBufferCapacity;
316 }
317 struct GBASerializedState* state = thread->rewindBuffer[offset];
318 if (!state) {
319 return;
320 }
321 thread->rewindBufferSize -= nStates;
322 thread->rewindBufferWriteOffset = offset;
323 GBADeserialize(thread->gba, state);
324 if (thread->rewindScreenBuffer) {
325 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
326 }
327}
328
329void GBARewindAll(struct GBAThread* thread) {
330 GBARewind(thread, thread->rewindBufferSize);
331}