all repos — mgba @ 7950fac9e509672005e80d2b78887363b76785f2

mGBA Game Boy Advance Emulator

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	state->id = ((struct GBACartridge*) gba->memory.rom)->id;
 33	memcpy(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title));
 34
 35	memcpy(state->cpu.gprs, gba->cpu->gprs, sizeof(state->cpu.gprs));
 36	state->cpu.cpsr = gba->cpu->cpsr;
 37	state->cpu.spsr = gba->cpu->spsr;
 38	state->cpu.cycles = gba->cpu->cycles;
 39	state->cpu.nextEvent = gba->cpu->nextEvent;
 40	memcpy(state->cpu.bankedRegisters, gba->cpu->bankedRegisters, 6 * 7 * sizeof(int32_t));
 41	memcpy(state->cpu.bankedSPSRs, gba->cpu->bankedSPSRs, 6 * sizeof(int32_t));
 42
 43	state->biosPrefetch = gba->memory.biosPrefetch;
 44	state->cpuPrefetch[0] = gba->cpu->prefetch[0];
 45	state->cpuPrefetch[1] = gba->cpu->prefetch[1];
 46
 47	GBAMemorySerialize(&gba->memory, state);
 48	GBAIOSerialize(gba, state);
 49	GBAVideoSerialize(&gba->video, state);
 50	GBAAudioSerialize(&gba->audio, state);
 51	GBASavedataSerialize(&gba->memory.savedata, state, false);
 52
 53	state->associatedStreamId = 0;
 54	if (gba->rr) {
 55		gba->rr->stateSaved(gba->rr, state);
 56	}
 57}
 58
 59void GBADeserialize(struct GBA* gba, const struct GBASerializedState* state) {
 60	if (state->versionMagic != GBA_SAVESTATE_MAGIC) {
 61		GBALog(gba, GBA_LOG_WARN, "Invalid or too new savestate");
 62		return;
 63	}
 64	if (state->biosChecksum != gba->biosChecksum) {
 65		GBALog(gba, GBA_LOG_WARN, "Savestate created using a different version of the BIOS");
 66		if (state->cpu.gprs[ARM_PC] < SIZE_BIOS && state->cpu.gprs[ARM_PC] >= 0x20) {
 67			return;
 68		}
 69	}
 70	if (state->id != ((struct GBACartridge*) gba->memory.rom)->id || memcmp(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title))) {
 71		GBALog(gba, GBA_LOG_WARN, "Savestate is for a different game");
 72		return;
 73	}
 74	if (state->romCrc32 != gba->romCrc32) {
 75		GBALog(gba, GBA_LOG_WARN, "Savestate is for a different version of the game");
 76	}
 77	memcpy(gba->cpu->gprs, state->cpu.gprs, sizeof(gba->cpu->gprs));
 78	gba->cpu->cpsr = state->cpu.cpsr;
 79	gba->cpu->spsr = state->cpu.spsr;
 80	gba->cpu->cycles = state->cpu.cycles;
 81	gba->cpu->nextEvent = state->cpu.nextEvent;
 82	memcpy(gba->cpu->bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
 83	memcpy(gba->cpu->bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
 84	gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
 85	gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
 86	if (state->biosPrefetch) {
 87		gba->memory.biosPrefetch = state->biosPrefetch;
 88	}
 89	if (gba->cpu->cpsr.t) {
 90		gba->cpu->executionMode = MODE_THUMB;
 91		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
 92			gba->cpu->prefetch[0] = state->cpuPrefetch[0] & 0xFFFF;
 93			gba->cpu->prefetch[1] = state->cpuPrefetch[1] & 0xFFFF;
 94		} else {
 95			// Maintain backwards compat
 96			LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
 97			LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
 98		}
 99	} else {
100		gba->cpu->executionMode = MODE_ARM;
101		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
102			gba->cpu->prefetch[0] = state->cpuPrefetch[0];
103			gba->cpu->prefetch[1] = state->cpuPrefetch[1];
104		} else {
105			// Maintain backwards compat
106			LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
107			LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
108		}
109	}
110
111	GBAMemoryDeserialize(&gba->memory, state);
112	GBAIODeserialize(gba, state);
113	GBAVideoDeserialize(&gba->video, state);
114	GBAAudioDeserialize(&gba->audio, state);
115	GBASavedataDeserialize(&gba->memory.savedata, state, false);
116
117	if (gba->rr) {
118		gba->rr->stateLoaded(gba->rr, state);
119	}
120}
121
122struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
123	char suffix[5] = { '\0' };
124	snprintf(suffix, sizeof(suffix), ".ss%d", slot);
125	return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
126}
127
128#ifdef USE_PNG
129static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
130	unsigned stride;
131	void* pixels = 0;
132	gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
133	if (!pixels) {
134		return false;
135	}
136
137	struct GBASerializedState* state = GBAAllocateState();
138	png_structp png = PNGWriteOpen(vf);
139	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
140	uLongf len = compressBound(sizeof(*state));
141	void* buffer = malloc(len);
142	if (state && png && info && buffer) {
143		GBASerialize(gba, state);
144		compress(buffer, &len, (const Bytef*) state, sizeof(*state));
145		PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
146		PNGWriteCustomChunk(png, "gbAs", len, buffer);
147	}
148	PNGWriteClose(png, info);
149	free(buffer);
150	GBADeallocateState(state);
151	return state && png && info && buffer;
152}
153
154static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
155	if (strcmp((const char*) chunk->name, "gbAs") != 0) {
156		return 0;
157	}
158	struct GBASerializedState state;
159	uLongf len = sizeof(state);
160	uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
161	GBADeserialize(png_get_user_chunk_ptr(png), &state);
162	return 1;
163}
164
165static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
166	png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
167	png_infop info = png_create_info_struct(png);
168	png_infop end = png_create_info_struct(png);
169	if (!png || !info || !end) {
170		PNGReadClose(png, info, end);
171		return false;
172	}
173	uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
174
175	PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
176	PNGReadHeader(png, info);
177	PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
178	PNGReadFooter(png, end);
179	PNGReadClose(png, info, end);
180	gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
181	bool videoFrameWait = gba->sync->videoFrameWait;
182	gba->sync->videoFrameWait = false;
183	GBASyncPostFrame(gba->sync);
184	gba->sync->videoFrameWait = videoFrameWait;
185
186	free(pixels);
187	return true;
188}
189#endif
190
191bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
192	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
193	if (!vf) {
194		return false;
195	}
196	bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
197	vf->close(vf);
198	return success;
199}
200
201bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
202	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
203	if (!vf) {
204		return false;
205	}
206	threadContext->rewindBufferSize = 0;
207	bool success = GBALoadStateNamed(threadContext->gba, vf);
208	vf->close(vf);
209	return success;
210}
211
212bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
213	if (!screenshot) {
214		vf->truncate(vf, sizeof(struct GBASerializedState));
215		struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
216		if (!state) {
217			return false;
218		}
219		GBASerialize(gba, state);
220		vf->unmap(vf, state, sizeof(struct GBASerializedState));
221		return true;
222	}
223	#ifdef USE_PNG
224	else {
225		return _savePNGState(gba, vf);
226	}
227	#endif
228	return false;
229}
230
231bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
232	#ifdef USE_PNG
233	if (isPNG(vf)) {
234		return _loadPNGState(gba, vf);
235	}
236	#endif
237	struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
238	if (!state) {
239		return false;
240	}
241	GBADeserialize(gba, state);
242	vf->unmap(vf, state, sizeof(struct GBASerializedState));
243	return true;
244}
245
246struct GBASerializedState* GBAAllocateState(void) {
247	return anonymousMemoryMap(sizeof(struct GBASerializedState));
248}
249
250void GBADeallocateState(struct GBASerializedState* state) {
251	mappedMemoryFree(state, sizeof(struct GBASerializedState));
252}
253
254void GBARecordFrame(struct GBAThread* thread) {
255	int offset = thread->rewindBufferWriteOffset;
256	struct GBASerializedState* state = thread->rewindBuffer[offset];
257	if (!state) {
258		state = GBAAllocateState();
259		thread->rewindBuffer[offset] = state;
260	}
261	GBASerialize(thread->gba, state);
262	thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
263	thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
264}
265
266void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
267	if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
268		return;
269	}
270	threadContext->rewindBufferInterval = newInterval;
271	threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
272	threadContext->rewindBufferSize = 0;
273	if (threadContext->rewindBuffer) {
274		int i;
275		for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
276			GBADeallocateState(threadContext->rewindBuffer[i]);
277		}
278		free(threadContext->rewindBuffer);
279	}
280	threadContext->rewindBufferCapacity = newCapacity;
281	if (threadContext->rewindBufferCapacity > 0) {
282		threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
283	} else {
284		threadContext->rewindBuffer = 0;
285	}
286}
287
288void GBARewind(struct GBAThread* thread, int nStates) {
289	if (nStates > thread->rewindBufferSize || nStates < 0) {
290		nStates = thread->rewindBufferSize;
291	}
292	if (nStates == 0) {
293		return;
294	}
295	int offset = thread->rewindBufferWriteOffset - nStates;
296	if (offset < 0) {
297		offset += thread->rewindBufferCapacity;
298	}
299	struct GBASerializedState* state = thread->rewindBuffer[offset];
300	if (!state) {
301		return;
302	}
303	thread->rewindBufferSize -= nStates;
304	thread->rewindBufferWriteOffset = offset;
305	GBADeserialize(thread->gba, state);
306}
307
308void GBARewindAll(struct GBAThread* thread) {
309	GBARewind(thread, thread->rewindBufferSize);
310}