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->video.nextEvent < state->cpu.cycles) {
103 uint16_t dispstat = state->io[REG_DISPSTAT >> 1];
104 if (GBARegisterDISPSTATIsInHblank(dispstat) && state->video.eventDiff + state->cpu.cycles > state->video.nextHblank) {
105 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: nextHblank will be negative");
106 error = true;
107 }
108 if (!GBARegisterDISPSTATIsInHblank(dispstat) && state->video.eventDiff + state->cpu.cycles > state->video.lastHblank + VIDEO_HBLANK_LENGTH) {
109 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: nextHblank will be negative");
110 error = true;
111 }
112 }
113 if (state->timers[0].overflowInterval < 0 || state->timers[1].overflowInterval < 0 || state->timers[2].overflowInterval < 0 || state->timers[3].overflowInterval < 0) {
114 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: overflowInterval is negative");
115 error = true;
116 }
117 if (state->timers[0].nextEvent < 0 || state->timers[1].nextEvent < 0 || state->timers[2].nextEvent < 0 || state->timers[3].nextEvent < 0) {
118 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: timer nextEvent is negative");
119 error = true;
120 }
121 if (state->dma[0].nextEvent < 0 || state->dma[1].nextEvent < 0 || state->dma[2].nextEvent < 0 || state->dma[3].nextEvent < 0) {
122 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: DMA nextEvent is negative");
123 error = true;
124 }
125 if (state->audio.eventDiff < 0) {
126 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio eventDiff is negative");
127 error = true;
128 }
129 if (!state->audio.ch1Dead && (state->audio.ch1.envelopeNextStep < 0 ||
130 state->audio.ch1.waveNextStep < 0 ||
131 state->audio.ch1.sweepNextStep < 0 ||
132 state->audio.ch1.nextEvent < 0)) {
133 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 1 register is negative");
134 error = true;
135 }
136 if (!state->audio.ch2Dead && (state->audio.ch2.envelopeNextStep < 0 ||
137 state->audio.ch2.waveNextStep < 0 ||
138 state->audio.ch2.nextEvent < 0)) {
139 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 2 register is negative");
140 error = true;
141 }
142 if (state->audio.ch3.nextEvent < 0) {
143 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 3 register is negative");
144 error = true;
145 }
146 if (!state->audio.ch4Dead && (state->audio.ch4.envelopeNextStep < 0 ||
147 state->audio.ch4.nextEvent < 0)) {
148 GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: audio channel 4 register is negative");
149 error = true;
150 }
151 int region = (state->cpu.gprs[ARM_PC] >> BASE_OFFSET);
152 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) {
153 GBALog(gba, GBA_LOG_WARN, "Savestate created using a differently sized version of the ROM");
154 error = true;
155 }
156 if (error) {
157 return false;
158 }
159 memcpy(gba->cpu->gprs, state->cpu.gprs, sizeof(gba->cpu->gprs));
160 gba->cpu->cpsr = state->cpu.cpsr;
161 gba->cpu->spsr = state->cpu.spsr;
162 gba->cpu->cycles = state->cpu.cycles;
163 gba->cpu->nextEvent = state->cpu.nextEvent;
164 memcpy(gba->cpu->bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
165 memcpy(gba->cpu->bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
166 gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
167 gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
168 if (state->biosPrefetch) {
169 gba->memory.biosPrefetch = state->biosPrefetch;
170 }
171 if (gba->cpu->cpsr.t) {
172 gba->cpu->executionMode = MODE_THUMB;
173 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
174 gba->cpu->prefetch[0] = state->cpuPrefetch[0] & 0xFFFF;
175 gba->cpu->prefetch[1] = state->cpuPrefetch[1] & 0xFFFF;
176 } else {
177 // Maintain backwards compat
178 LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
179 LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
180 }
181 } else {
182 gba->cpu->executionMode = MODE_ARM;
183 if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
184 gba->cpu->prefetch[0] = state->cpuPrefetch[0];
185 gba->cpu->prefetch[1] = state->cpuPrefetch[1];
186 } else {
187 // Maintain backwards compat
188 LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
189 LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
190 }
191 }
192
193 GBAMemoryDeserialize(&gba->memory, state);
194 GBAIODeserialize(gba, state);
195 GBAVideoDeserialize(&gba->video, state);
196 GBAAudioDeserialize(&gba->audio, state);
197 GBASavedataDeserialize(&gba->memory.savedata, state, false);
198
199 if (gba->rr) {
200 gba->rr->stateLoaded(gba->rr, state);
201 }
202 return true;
203}
204
205struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
206 char suffix[5] = { '\0' };
207 snprintf(suffix, sizeof(suffix), ".ss%d", slot);
208 return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
209}
210
211#ifdef USE_PNG
212static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
213 unsigned stride;
214 void* pixels = 0;
215 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
216 if (!pixels) {
217 return false;
218 }
219
220 struct GBASerializedState* state = GBAAllocateState();
221 if (!state) {
222 return false;
223 }
224 GBASerialize(gba, state);
225 uLongf len = compressBound(sizeof(*state));
226 void* buffer = malloc(len);
227 if (!buffer) {
228 GBADeallocateState(state);
229 return false;
230 }
231 compress(buffer, &len, (const Bytef*) state, sizeof(*state));
232 GBADeallocateState(state);
233
234 png_structp png = PNGWriteOpen(vf);
235 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
236 if (!png || !info) {
237 PNGWriteClose(png, info);
238 free(buffer);
239 return false;
240 }
241 PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
242 PNGWriteCustomChunk(png, "gbAs", len, buffer);
243 PNGWriteClose(png, info);
244 free(buffer);
245 return true;
246}
247
248static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
249 if (strcmp((const char*) chunk->name, "gbAs") != 0) {
250 return 0;
251 }
252 struct GBASerializedState* state = GBAAllocateState();
253 uLongf len = sizeof(*state);
254 uncompress((Bytef*) state, &len, chunk->data, chunk->size);
255 if (!GBADeserialize(png_get_user_chunk_ptr(png), state)) {
256 GBADeallocateState(state);
257 longjmp(png_jmpbuf(png), 1);
258 }
259 GBADeallocateState(state);
260 return 1;
261}
262
263static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
264 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
265 png_infop info = png_create_info_struct(png);
266 png_infop end = png_create_info_struct(png);
267 if (!png || !info || !end) {
268 PNGReadClose(png, info, end);
269 return false;
270 }
271 uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
272 if (!pixels) {
273 PNGReadClose(png, info, end);
274 return false;
275 }
276
277 PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
278 bool success = PNGReadHeader(png, info);
279 success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
280 success = success && PNGReadFooter(png, end);
281 PNGReadClose(png, info, end);
282 if (success) {
283 gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
284 GBASyncForceFrame(gba->sync);
285 }
286
287 free(pixels);
288 return success;
289}
290#endif
291
292bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
293 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
294 if (!vf) {
295 return false;
296 }
297 bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
298 vf->close(vf);
299 if (success) {
300 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
301 } else {
302 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
303 }
304 return success;
305}
306
307bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
308 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
309 if (!vf) {
310 return false;
311 }
312 threadContext->rewindBufferSize = 0;
313 bool success = GBALoadStateNamed(threadContext->gba, vf);
314 vf->close(vf);
315 if (success) {
316 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
317 } else {
318 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
319 }
320 return success;
321}
322
323bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
324#ifdef USE_PNG
325 if (!screenshot) {
326#else
327 UNUSED(screenshot);
328#endif
329 vf->truncate(vf, sizeof(struct GBASerializedState));
330 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
331 if (!state) {
332 return false;
333 }
334 GBASerialize(gba, state);
335 vf->unmap(vf, state, sizeof(struct GBASerializedState));
336 return true;
337#ifdef USE_PNG
338 }
339 else {
340 return _savePNGState(gba, vf);
341 }
342#endif
343 return false;
344}
345
346bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
347#ifdef USE_PNG
348 if (isPNG(vf)) {
349 return _loadPNGState(gba, vf);
350 }
351#endif
352 if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
353 return false;
354 }
355 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
356 if (!state) {
357 return false;
358 }
359 bool success = GBADeserialize(gba, state);
360 vf->unmap(vf, state, sizeof(struct GBASerializedState));
361 return success;
362}
363
364struct GBASerializedState* GBAAllocateState(void) {
365 return anonymousMemoryMap(sizeof(struct GBASerializedState));
366}
367
368void GBADeallocateState(struct GBASerializedState* state) {
369 mappedMemoryFree(state, sizeof(struct GBASerializedState));
370}
371
372void GBARecordFrame(struct GBAThread* thread) {
373 int offset = thread->rewindBufferWriteOffset;
374 struct GBASerializedState* state = thread->rewindBuffer[offset];
375 if (!state) {
376 state = GBAAllocateState();
377 thread->rewindBuffer[offset] = state;
378 }
379 GBASerialize(thread->gba, state);
380
381 if (thread->rewindScreenBuffer) {
382 unsigned stride;
383 uint8_t* pixels = 0;
384 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
385 if (pixels) {
386 size_t y;
387 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
388 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);
389 }
390 }
391 }
392 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
393 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
394}
395
396void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
397 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
398 return;
399 }
400 threadContext->rewindBufferInterval = newInterval;
401 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
402 threadContext->rewindBufferSize = 0;
403 if (threadContext->rewindBuffer) {
404 int i;
405 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
406 GBADeallocateState(threadContext->rewindBuffer[i]);
407 }
408 free(threadContext->rewindBuffer);
409 free(threadContext->rewindScreenBuffer);
410 }
411 threadContext->rewindBufferCapacity = newCapacity;
412 if (threadContext->rewindBufferCapacity > 0) {
413 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
414 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
415 } else {
416 threadContext->rewindBuffer = 0;
417 threadContext->rewindScreenBuffer = 0;
418 }
419}
420
421int GBARewind(struct GBAThread* thread, int nStates) {
422 if (nStates > thread->rewindBufferSize || nStates < 0) {
423 nStates = thread->rewindBufferSize;
424 }
425 if (nStates == 0) {
426 return 0;
427 }
428 int offset = thread->rewindBufferWriteOffset - nStates;
429 if (offset < 0) {
430 offset += thread->rewindBufferCapacity;
431 }
432 struct GBASerializedState* state = thread->rewindBuffer[offset];
433 if (!state) {
434 return 0;
435 }
436 thread->rewindBufferSize -= nStates;
437 thread->rewindBufferWriteOffset = offset;
438 GBADeserialize(thread->gba, state);
439 if (thread->rewindScreenBuffer) {
440 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
441 }
442 return nStates;
443}
444
445void GBARewindAll(struct GBAThread* thread) {
446 GBARewind(thread, thread->rewindBufferSize);
447}