all repos — mgba @ eb81fc3c65f918c16f0e9ddeeb6cbea662155731

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