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