all repos — mgba @ e9a2b2a57c4f478fb3600fe9d87e1b97804d73de

mGBA Game Boy Advance Emulator

src/gba/gba-serialize.c (view raw)

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