src/gba/serialize.c (view raw)
1/* Copyright (c) 2013-2015 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 "serialize.h"
7
8#include "gba/audio.h"
9#include "gba/io.h"
10#include "gba/supervisor/rr.h"
11#include "gba/supervisor/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 if (gba->memory.rom) {
33 state->id = ((struct GBACartridge*) gba->memory.rom)->id;
34 memcpy(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title));
35 } else {
36 state->id = 0;
37 memset(state->title, 0, sizeof(state->title));
38 }
39
40 memcpy(state->cpu.gprs, gba->cpu->gprs, sizeof(state->cpu.gprs));
41 state->cpu.cpsr = gba->cpu->cpsr;
42 state->cpu.spsr = gba->cpu->spsr;
43 state->cpu.cycles = gba->cpu->cycles;
44 state->cpu.nextEvent = gba->cpu->nextEvent;
45 memcpy(state->cpu.bankedRegisters, gba->cpu->bankedRegisters, 6 * 7 * sizeof(int32_t));
46 memcpy(state->cpu.bankedSPSRs, gba->cpu->bankedSPSRs, 6 * sizeof(int32_t));
47
48 state->biosPrefetch = gba->memory.biosPrefetch;
49 state->cpuPrefetch[0] = gba->cpu->prefetch[0];
50 state->cpuPrefetch[1] = gba->cpu->prefetch[1];
51
52 GBAMemorySerialize(&gba->memory, state);
53 GBAIOSerialize(gba, state);
54 GBAVideoSerialize(&gba->video, state);
55 GBAAudioSerialize(&gba->audio, state);
56 GBASavedataSerialize(&gba->memory.savedata, state, false);
57
58 state->associatedStreamId = 0;
59 if (gba->rr) {
60 gba->rr->stateSaved(gba->rr, state);
61 }
62}
63
64bool GBADeserialize(struct GBA* gba, const struct GBASerializedState* state) {
65 bool error = false;
66 if (state->versionMagic != GBA_SAVESTATE_MAGIC) {
67 GBALog(gba, GBA_LOG_WARN, "Invalid or too new savestate");
68 error = true;
69 }
70 if (state->biosChecksum != gba->biosChecksum) {
71 GBALog(gba, GBA_LOG_WARN, "Savestate created using a different version of the BIOS");
72 if (state->cpu.gprs[ARM_PC] < SIZE_BIOS && state->cpu.gprs[ARM_PC] >= 0x20) {
73 error = true;
74 }
75 }
76 if (gba->memory.rom && (state->id != ((struct GBACartridge*) gba->memory.rom)->id || memcmp(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title)))) {
77 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different game");
78 error = true;
79 } else if (!gba->memory.rom && state->id != 0) {
80 GBALog(gba, GBA_LOG_WARN, "Savestate is for a game, but no game loaded");
81 error = true;
82 }
83 if (state->romCrc32 != gba->romCrc32) {
84 GBALog(gba, GBA_LOG_WARN, "Savestate is for a different version of the game");
85 }
86 if (state->cpu.cycles < 0) {
87 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are negative");
88 error = true;
89 }
90 if (state->cpu.nextEvent < 0) {
91 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: Next event is negative");
92 error = true;
93 }
94 if (state->video.eventDiff < 0) {
95 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: video eventDiff is negative");
96 error = true;
97 }
98 if (state->video.nextHblank - state->video.eventDiff < 0) {
99 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: nextHblank is negative");
100 error = true;
101 }
102 if (state->timers[0].overflowInterval < 0 || state->timers[1].overflowInterval < 0 || state->timers[2].overflowInterval < 0 || state->timers[3].overflowInterval < 0) {
103 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: overflowInterval is negative");
104 error = true;
105 }
106 if (state->audio.eventDiff < 0) {
107 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio eventDiff is negative");
108 error = true;
109 }
110 if (!state->audio.ch1Dead && (state->audio.ch1.envelopeNextStep < 0 ||
111 state->audio.ch1.waveNextStep < 0 ||
112 state->audio.ch1.sweepNextStep < 0 ||
113 state->audio.ch1.nextEvent < 0)) {
114 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 1 register is negative");
115 error = true;
116 }
117 if (!state->audio.ch2Dead && (state->audio.ch2.envelopeNextStep < 0 ||
118 state->audio.ch2.waveNextStep < 0 ||
119 state->audio.ch2.nextEvent < 0)) {
120 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 2 register is negative");
121 error = true;
122 }
123 if (state->audio.ch3.nextEvent < 0) {
124 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 3 register is negative");
125 error = true;
126 }
127 if (!state->audio.ch4Dead && (state->audio.ch4.envelopeNextStep < 0 ||
128 state->audio.ch4.nextEvent < 0)) {
129 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 4 register is negative");
130 error = true;
131 }
132 int region = (state->cpu.gprs[ARM_PC] >> BASE_OFFSET);
133 if ((region == REGION_CART0 || region == REGION_CART1 || region == REGION_CART2) && ((state->cpu.gprs[ARM_PC] - WORD_SIZE_ARM) & SIZE_CART0) >= gba->memory.romSize - WORD_SIZE_ARM) {
134 GBALog(gba, GBA_LOG_WARN, "Savestate created using a differently sized version of the ROM");
135 error = true;
136 }
137 if (error) {
138 return false;
139 }
140 memcpy(gba->cpu->gprs, state->cpu.gprs, sizeof(gba->cpu->gprs));
141 gba->cpu->cpsr = state->cpu.cpsr;
142 gba->cpu->spsr = state->cpu.spsr;
143 gba->cpu->cycles = state->cpu.cycles;
144 gba->cpu->nextEvent = state->cpu.nextEvent;
145 memcpy(gba->cpu->bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
146 memcpy(gba->cpu->bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
147 gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
148 gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
149 if (state->biosPrefetch) {
150 gba->memory.biosPrefetch = state->biosPrefetch;
151 }
152 if (gba->cpu->cpsr.t) {
153 gba->cpu->executionMode = MODE_THUMB;
154 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
155 gba->cpu->prefetch[0] = state->cpuPrefetch[0] & 0xFFFF;
156 gba->cpu->prefetch[1] = state->cpuPrefetch[1] & 0xFFFF;
157 } else {
158 // Maintain backwards compat
159 LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
160 LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
161 }
162 } else {
163 gba->cpu->executionMode = MODE_ARM;
164 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
165 gba->cpu->prefetch[0] = state->cpuPrefetch[0];
166 gba->cpu->prefetch[1] = state->cpuPrefetch[1];
167 } else {
168 // Maintain backwards compat
169 LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
170 LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
171 }
172 }
173
174 GBAMemoryDeserialize(&gba->memory, state);
175 GBAIODeserialize(gba, state);
176 GBAVideoDeserialize(&gba->video, state);
177 GBAAudioDeserialize(&gba->audio, state);
178 GBASavedataDeserialize(&gba->memory.savedata, state, false);
179
180 if (gba->rr) {
181 gba->rr->stateLoaded(gba->rr, state);
182 }
183 return true;
184}
185
186struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
187 char suffix[5] = { '\0' };
188 snprintf(suffix, sizeof(suffix), ".ss%d", slot);
189 return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
190}
191
192#ifdef USE_PNG
193static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
194 unsigned stride;
195 void* pixels = 0;
196 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
197 if (!pixels) {
198 return false;
199 }
200
201 struct GBASerializedState* state = GBAAllocateState();
202 if (!state) {
203 return false;
204 }
205 png_structp png = PNGWriteOpen(vf);
206 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
207 if (!png || !info) {
208 PNGWriteClose(png, info);
209 GBADeallocateState(state);
210 return false;
211 }
212 uLongf len = compressBound(sizeof(*state));
213 void* buffer = malloc(len);
214 if (!buffer) {
215 PNGWriteClose(png, info);
216 GBADeallocateState(state);
217 return false;
218 }
219 GBASerialize(gba, state);
220 compress(buffer, &len, (const Bytef*) state, sizeof(*state));
221 PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
222 PNGWriteCustomChunk(png, "gbAs", len, buffer);
223 PNGWriteClose(png, info);
224 free(buffer);
225 GBADeallocateState(state);
226 return true;
227}
228
229static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
230 if (strcmp((const char*) chunk->name, "gbAs") != 0) {
231 return 0;
232 }
233 struct GBASerializedState state;
234 uLongf len = sizeof(state);
235 uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
236 if (!GBADeserialize(png_get_user_chunk_ptr(png), &state)) {
237 longjmp(png_jmpbuf(png), 1);
238 }
239 return 1;
240}
241
242static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
243 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
244 png_infop info = png_create_info_struct(png);
245 png_infop end = png_create_info_struct(png);
246 if (!png || !info || !end) {
247 PNGReadClose(png, info, end);
248 return false;
249 }
250 uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
251
252 PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
253 bool success = PNGReadHeader(png, info);
254 success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
255 success = success && PNGReadFooter(png, end);
256 PNGReadClose(png, info, end);
257 if (success) {
258 gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
259 GBASyncForceFrame(gba->sync);
260 }
261
262 free(pixels);
263 return success;
264}
265#endif
266
267bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
268 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
269 if (!vf) {
270 return false;
271 }
272 bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
273 vf->close(vf);
274 if (success) {
275 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
276 } else {
277 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
278 }
279 return success;
280}
281
282bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
283 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
284 if (!vf) {
285 return false;
286 }
287 threadContext->rewindBufferSize = 0;
288 bool success = GBALoadStateNamed(threadContext->gba, vf);
289 vf->close(vf);
290 if (success) {
291 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
292 } else {
293 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
294 }
295 return success;
296}
297
298bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
299 if (!screenshot) {
300 vf->truncate(vf, sizeof(struct GBASerializedState));
301 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
302 if (!state) {
303 return false;
304 }
305 GBASerialize(gba, state);
306 vf->unmap(vf, state, sizeof(struct GBASerializedState));
307 return true;
308 }
309#ifdef USE_PNG
310 else {
311 return _savePNGState(gba, vf);
312 }
313#endif
314 return false;
315}
316
317bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
318#ifdef USE_PNG
319 if (isPNG(vf)) {
320 return _loadPNGState(gba, vf);
321 }
322#endif
323 if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
324 return false;
325 }
326 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
327 if (!state) {
328 return false;
329 }
330 bool success = GBADeserialize(gba, state);
331 vf->unmap(vf, state, sizeof(struct GBASerializedState));
332 return success;
333}
334
335struct GBASerializedState* GBAAllocateState(void) {
336 return anonymousMemoryMap(sizeof(struct GBASerializedState));
337}
338
339void GBADeallocateState(struct GBASerializedState* state) {
340 mappedMemoryFree(state, sizeof(struct GBASerializedState));
341}
342
343void GBARecordFrame(struct GBAThread* thread) {
344 int offset = thread->rewindBufferWriteOffset;
345 struct GBASerializedState* state = thread->rewindBuffer[offset];
346 if (!state) {
347 state = GBAAllocateState();
348 thread->rewindBuffer[offset] = state;
349 }
350 GBASerialize(thread->gba, state);
351
352 if (thread->rewindScreenBuffer) {
353 unsigned stride;
354 uint8_t* pixels = 0;
355 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
356 if (pixels) {
357 size_t y;
358 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
359 memcpy(&thread->rewindScreenBuffer[(offset * VIDEO_VERTICAL_PIXELS + y) * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL], &pixels[y * stride * BYTES_PER_PIXEL], VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
360 }
361 }
362 }
363 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
364 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
365}
366
367void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
368 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
369 return;
370 }
371 threadContext->rewindBufferInterval = newInterval;
372 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
373 threadContext->rewindBufferSize = 0;
374 if (threadContext->rewindBuffer) {
375 int i;
376 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
377 GBADeallocateState(threadContext->rewindBuffer[i]);
378 }
379 free(threadContext->rewindBuffer);
380 free(threadContext->rewindScreenBuffer);
381 }
382 threadContext->rewindBufferCapacity = newCapacity;
383 if (threadContext->rewindBufferCapacity > 0) {
384 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
385 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
386 } else {
387 threadContext->rewindBuffer = 0;
388 threadContext->rewindScreenBuffer = 0;
389 }
390}
391
392int GBARewind(struct GBAThread* thread, int nStates) {
393 if (nStates > thread->rewindBufferSize || nStates < 0) {
394 nStates = thread->rewindBufferSize;
395 }
396 if (nStates == 0) {
397 return 0;
398 }
399 int offset = thread->rewindBufferWriteOffset - nStates;
400 if (offset < 0) {
401 offset += thread->rewindBufferCapacity;
402 }
403 struct GBASerializedState* state = thread->rewindBuffer[offset];
404 if (!state) {
405 return 0;
406 }
407 thread->rewindBufferSize -= nStates;
408 thread->rewindBufferWriteOffset = offset;
409 GBADeserialize(thread->gba, state);
410 if (thread->rewindScreenBuffer) {
411 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
412 }
413 return nStates;
414}
415
416void GBARewindAll(struct GBAThread* thread) {
417 GBARewind(thread, thread->rewindBufferSize);
418}