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