all repos — mgba @ 22245617f434049f4646916d1b2930d376503b0d

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