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 GBARRIncrementStream(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 GBARRLoadStream(gba->rr, state->associatedStreamId);
84 GBARRIncrementStream(gba->rr);
85 } else if (GBARRIsPlaying(gba->rr)) {
86 GBARRLoadStream(gba->rr, state->associatedStreamId);
87 GBARRSkipSegment(gba->rr);
88 }
89}
90
91static struct VFile* _getStateVf(struct GBA* gba, struct VDir* dir, int slot, bool write) {
92 char path[PATH_MAX];
93 path[PATH_MAX - 1] = '\0';
94 struct VFile* vf;
95 if (!dir) {
96 snprintf(path, PATH_MAX - 1, "%s.ss%d", gba->activeFile, slot);
97 vf = VFileOpen(path, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
98 } else {
99 snprintf(path, PATH_MAX - 1, "savestate.ss%d", slot);
100 vf = dir->openFile(dir, path, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
101 }
102 return vf;
103}
104
105static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
106 unsigned stride;
107 void* pixels = 0;
108 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
109 if (!pixels) {
110 return false;
111 }
112
113 struct GBASerializedState* state = GBAAllocateState();
114 png_structp png = PNGWriteOpen(vf);
115 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
116 uLongf len = compressBound(sizeof(*state));
117 void* buffer = malloc(len);
118 if (state && png && info && buffer) {
119 GBASerialize(gba, state);
120 compress(buffer, &len, (const Bytef*) state, sizeof(*state));
121 PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
122 PNGWriteCustomChunk(png, "gbAs", len, buffer);
123 }
124 PNGWriteClose(png, info);
125 free(buffer);
126 GBADeallocateState(state);
127 return state && png && info && buffer;
128}
129
130static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
131 if (strcmp((const char*) chunk->name, "gbAs") != 0) {
132 return 0;
133 }
134 struct GBASerializedState state;
135 uLongf len = sizeof(state);
136 uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
137 GBADeserialize(png_get_user_chunk_ptr(png), &state);
138 return 1;
139}
140
141static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
142 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
143 png_infop info = png_create_info_struct(png);
144 png_infop end = png_create_info_struct(png);
145 if (!png || !info || !end) {
146 PNGReadClose(png, info, end);
147 return false;
148 }
149 uint32_t pixels[VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4];
150
151 PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
152 PNGReadHeader(png, info);
153 PNGReadPixels(png, info, &pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
154 PNGReadFooter(png, end);
155 PNGReadClose(png, info, end);
156 gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
157 GBASyncPostFrame(gba->sync);
158 return true;
159}
160
161bool GBASaveState(struct GBA* gba, struct VDir* dir, int slot, bool screenshot) {
162 struct VFile* vf = _getStateVf(gba, dir, slot, true);
163 if (!vf) {
164 return false;
165 }
166 bool success = true;
167 if (!screenshot) {
168 vf->truncate(vf, sizeof(struct GBASerializedState));
169 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
170 GBASerialize(gba, state);
171 vf->unmap(vf, state, sizeof(struct GBASerializedState));
172 } else {
173 _savePNGState(gba, vf);
174 }
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 if (!isPNG(vf)) {
185 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
186 GBADeserialize(gba, state);
187 vf->unmap(vf, state, sizeof(struct GBASerializedState));
188 } else {
189 _loadPNGState(gba, vf);
190 }
191 vf->close(vf);
192 return true;
193}
194
195struct GBASerializedState* GBAAllocateState(void) {
196 return anonymousMemoryMap(sizeof(struct GBASerializedState));
197}
198
199void GBADeallocateState(struct GBASerializedState* state) {
200 mappedMemoryFree(state, sizeof(struct GBASerializedState));
201}
202
203void GBARecordFrame(struct GBAThread* thread) {
204 int offset = thread->rewindBufferWriteOffset;
205 struct GBASerializedState* state = thread->rewindBuffer[offset];
206 if (!state) {
207 state = GBAAllocateState();
208 thread->rewindBuffer[offset] = state;
209 }
210 GBASerialize(thread->gba, state);
211 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
212 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
213}
214
215void GBARewind(struct GBAThread* thread, int nStates) {
216 if (nStates > thread->rewindBufferSize || nStates < 0) {
217 nStates = thread->rewindBufferSize;
218 }
219 if (nStates == 0) {
220 return;
221 }
222 int offset = thread->rewindBufferWriteOffset - nStates;
223 if (offset < 0) {
224 offset += thread->rewindBufferSize;
225 }
226 struct GBASerializedState* state = thread->rewindBuffer[offset];
227 if (!state) {
228 return;
229 }
230 thread->rewindBufferSize -= nStates;
231 thread->rewindBufferWriteOffset = (offset + thread->rewindBufferCapacity - nStates) % thread->rewindBufferCapacity;
232 GBADeserialize(thread->gba, state);
233}