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