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
105struct VFile* GBAGetState(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 = malloc(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
166 free(pixels);
167 return true;
168}
169#endif
170
171bool GBASaveState(struct GBA* gba, struct VDir* dir, int slot, bool screenshot) {
172 struct VFile* vf = GBAGetState(gba, dir, slot, true);
173 if (!vf) {
174 return false;
175 }
176 bool success = GBASaveStateNamed(gba, vf, screenshot);
177 vf->close(vf);
178 return success;
179}
180
181bool GBALoadState(struct GBA* gba, struct VDir* dir, int slot) {
182 struct VFile* vf = GBAGetState(gba, dir, slot, false);
183 if (!vf) {
184 return false;
185 }
186 bool success = GBALoadStateNamed(gba, vf);
187 vf->close(vf);
188 return success;
189}
190
191bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
192 if (!screenshot) {
193 vf->truncate(vf, sizeof(struct GBASerializedState));
194 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
195 if (!state) {
196 return false;
197 }
198 GBASerialize(gba, state);
199 vf->unmap(vf, state, sizeof(struct GBASerializedState));
200 return true;
201 }
202 #ifdef USE_PNG
203 else {
204 return _savePNGState(gba, vf);
205 }
206 #endif
207 return false;
208}
209
210bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
211 #ifdef USE_PNG
212 if (isPNG(vf)) {
213 return _loadPNGState(gba, vf);
214 }
215 #endif
216 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
217 if (!state) {
218 return false;
219 }
220 GBADeserialize(gba, state);
221 vf->unmap(vf, state, sizeof(struct GBASerializedState));
222 return true;
223}
224
225struct GBASerializedState* GBAAllocateState(void) {
226 return anonymousMemoryMap(sizeof(struct GBASerializedState));
227}
228
229void GBADeallocateState(struct GBASerializedState* state) {
230 mappedMemoryFree(state, sizeof(struct GBASerializedState));
231}
232
233void GBARecordFrame(struct GBAThread* thread) {
234 int offset = thread->rewindBufferWriteOffset;
235 struct GBASerializedState* state = thread->rewindBuffer[offset];
236 if (!state) {
237 state = GBAAllocateState();
238 thread->rewindBuffer[offset] = state;
239 }
240 GBASerialize(thread->gba, state);
241 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
242 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
243}
244
245void GBARewind(struct GBAThread* thread, int nStates) {
246 if (nStates > thread->rewindBufferSize || nStates < 0) {
247 nStates = thread->rewindBufferSize;
248 }
249 if (nStates == 0) {
250 return;
251 }
252 int offset = thread->rewindBufferWriteOffset - nStates;
253 if (offset < 0) {
254 offset += thread->rewindBufferSize;
255 }
256 struct GBASerializedState* state = thread->rewindBuffer[offset];
257 if (!state) {
258 return;
259 }
260 thread->rewindBufferSize -= nStates;
261 thread->rewindBufferWriteOffset = (offset + thread->rewindBufferCapacity - nStates) % thread->rewindBufferCapacity;
262 GBADeserialize(thread->gba, state);
263}