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