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/rr/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 const 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
292#ifndef _3DS
293bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
294 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
295 if (!vf) {
296 return false;
297 }
298 bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
299 vf->close(vf);
300 if (success) {
301 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
302 } else {
303 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
304 }
305 return success;
306}
307
308bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
309 struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
310 if (!vf) {
311 return false;
312 }
313 threadContext->rewindBufferSize = 0;
314 bool success = GBALoadStateNamed(threadContext->gba, vf);
315 vf->close(vf);
316 if (success) {
317 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
318 } else {
319 GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
320 }
321 return success;
322}
323#endif
324
325bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
326#ifdef USE_PNG
327 if (!screenshot) {
328#else
329 UNUSED(screenshot);
330#endif
331 vf->truncate(vf, sizeof(struct GBASerializedState));
332 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
333 if (!state) {
334 return false;
335 }
336 GBASerialize(gba, state);
337 vf->unmap(vf, state, sizeof(struct GBASerializedState));
338 return true;
339#ifdef USE_PNG
340 }
341 else {
342 return _savePNGState(gba, vf);
343 }
344#endif
345 return false;
346}
347
348bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
349#ifdef USE_PNG
350 if (isPNG(vf)) {
351 return _loadPNGState(gba, vf);
352 }
353#endif
354 if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
355 return false;
356 }
357 struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
358 if (!state) {
359 return false;
360 }
361 bool success = GBADeserialize(gba, state);
362 vf->unmap(vf, state, sizeof(struct GBASerializedState));
363 return success;
364}
365
366struct GBASerializedState* GBAAllocateState(void) {
367 return anonymousMemoryMap(sizeof(struct GBASerializedState));
368}
369
370void GBADeallocateState(struct GBASerializedState* state) {
371 mappedMemoryFree(state, sizeof(struct GBASerializedState));
372}
373
374void GBARecordFrame(struct GBAThread* thread) {
375 int offset = thread->rewindBufferWriteOffset;
376 struct GBASerializedState* state = thread->rewindBuffer[offset];
377 if (!state) {
378 state = GBAAllocateState();
379 thread->rewindBuffer[offset] = state;
380 }
381 GBASerialize(thread->gba, state);
382
383 if (thread->rewindScreenBuffer) {
384 unsigned stride;
385 const uint8_t* pixels = 0;
386 thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (const void**) &pixels);
387 if (pixels) {
388 size_t y;
389 for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
390 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);
391 }
392 }
393 }
394 thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
395 thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
396}
397
398void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
399 if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
400 return;
401 }
402 threadContext->rewindBufferInterval = newInterval;
403 threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
404 threadContext->rewindBufferSize = 0;
405 if (threadContext->rewindBuffer) {
406 int i;
407 for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
408 GBADeallocateState(threadContext->rewindBuffer[i]);
409 }
410 free(threadContext->rewindBuffer);
411 free(threadContext->rewindScreenBuffer);
412 }
413 threadContext->rewindBufferCapacity = newCapacity;
414 if (threadContext->rewindBufferCapacity > 0) {
415 threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
416 threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
417 } else {
418 threadContext->rewindBuffer = 0;
419 threadContext->rewindScreenBuffer = 0;
420 }
421}
422
423int GBARewind(struct GBAThread* thread, int nStates) {
424 if (nStates > thread->rewindBufferSize || nStates < 0) {
425 nStates = thread->rewindBufferSize;
426 }
427 if (nStates == 0) {
428 return 0;
429 }
430 int offset = thread->rewindBufferWriteOffset - nStates;
431 if (offset < 0) {
432 offset += thread->rewindBufferCapacity;
433 }
434 struct GBASerializedState* state = thread->rewindBuffer[offset];
435 if (!state) {
436 return 0;
437 }
438 thread->rewindBufferSize -= nStates;
439 thread->rewindBufferWriteOffset = offset;
440 GBADeserialize(thread->gba, state);
441 if (thread->rewindScreenBuffer) {
442 thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
443 }
444 return nStates;
445}
446
447void GBARewindAll(struct GBAThread* thread) {
448 GBARewind(thread, thread->rewindBufferSize);
449}
450
451void GBATakeScreenshot(struct GBA* gba, struct VDir* dir) {
452#ifdef USE_PNG
453 unsigned stride;
454 const void* pixels = 0;
455 struct VFile* vf = VDirOptionalOpenIncrementFile(dir, gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
456 bool success = false;
457 if (vf) {
458 gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
459 png_structp png = PNGWriteOpen(vf);
460 png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
461 success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
462 PNGWriteClose(png, info);
463 vf->close(vf);
464 }
465 if (success) {
466 GBALog(gba, GBA_LOG_STATUS, "Screenshot saved");
467 return;
468 }
469#endif
470 GBALog(gba, GBA_LOG_STATUS, "Failed to take screenshot");
471}