all repos — mgba @ d37cf5f0c3f7af64fee221317d1a05a482a07184

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	if (!state) {
139		return false;
140	}
141	png_structp png = PNGWriteOpen(vf);
142	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
143	if (!png || !info) {
144		PNGWriteClose(png, info);
145		GBADeallocateState(state);
146		return false;
147	}
148	uLongf len = compressBound(sizeof(*state));
149	void* buffer = malloc(len);
150	if (!buffer) {
151		PNGWriteClose(png, info);
152		GBADeallocateState(state);
153		return false;
154	}
155	GBASerialize(gba, state);
156	compress(buffer, &len, (const Bytef*) state, sizeof(*state));
157	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
158	PNGWriteCustomChunk(png, "gbAs", len, buffer);
159	PNGWriteClose(png, info);
160	free(buffer);
161	GBADeallocateState(state);
162	return true;
163}
164
165static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
166	if (strcmp((const char*) chunk->name, "gbAs") != 0) {
167		return 0;
168	}
169	struct GBASerializedState state;
170	uLongf len = sizeof(state);
171	uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
172	GBADeserialize(png_get_user_chunk_ptr(png), &state);
173	return 1;
174}
175
176static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
177	png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
178	png_infop info = png_create_info_struct(png);
179	png_infop end = png_create_info_struct(png);
180	if (!png || !info || !end) {
181		PNGReadClose(png, info, end);
182		return false;
183	}
184	uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
185
186	PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
187	PNGReadHeader(png, info);
188	PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
189	PNGReadFooter(png, end);
190	PNGReadClose(png, info, end);
191	gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
192	GBASyncForceFrame(gba->sync);
193
194	free(pixels);
195	return true;
196}
197#endif
198
199bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
200	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
201	if (!vf) {
202		return false;
203	}
204	bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
205	vf->close(vf);
206	if (success) {
207		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
208	}
209	return success;
210}
211
212bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
213	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
214	if (!vf) {
215		return false;
216	}
217	threadContext->rewindBufferSize = 0;
218	bool success = GBALoadStateNamed(threadContext->gba, vf);
219	vf->close(vf);
220	if (success) {
221		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
222	}
223	return success;
224}
225
226bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
227	if (!screenshot) {
228		vf->truncate(vf, sizeof(struct GBASerializedState));
229		struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
230		if (!state) {
231			return false;
232		}
233		GBASerialize(gba, state);
234		vf->unmap(vf, state, sizeof(struct GBASerializedState));
235		return true;
236	}
237	#ifdef USE_PNG
238	else {
239		return _savePNGState(gba, vf);
240	}
241	#endif
242	return false;
243}
244
245bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
246	#ifdef USE_PNG
247	if (isPNG(vf)) {
248		return _loadPNGState(gba, vf);
249	}
250	#endif
251	struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
252	if (!state) {
253		return false;
254	}
255	GBADeserialize(gba, state);
256	vf->unmap(vf, state, sizeof(struct GBASerializedState));
257	return true;
258}
259
260struct GBASerializedState* GBAAllocateState(void) {
261	return anonymousMemoryMap(sizeof(struct GBASerializedState));
262}
263
264void GBADeallocateState(struct GBASerializedState* state) {
265	mappedMemoryFree(state, sizeof(struct GBASerializedState));
266}
267
268void GBARecordFrame(struct GBAThread* thread) {
269	int offset = thread->rewindBufferWriteOffset;
270	struct GBASerializedState* state = thread->rewindBuffer[offset];
271	if (!state) {
272		state = GBAAllocateState();
273		thread->rewindBuffer[offset] = state;
274	}
275	GBASerialize(thread->gba, state);
276
277	if (thread->rewindScreenBuffer) {
278		unsigned stride;
279		uint8_t* pixels = 0;
280		thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
281		if (pixels) {
282			size_t y;
283			for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
284				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);
285			}
286		}
287	}
288	thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
289	thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
290}
291
292void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
293	if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
294		return;
295	}
296	threadContext->rewindBufferInterval = newInterval;
297	threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
298	threadContext->rewindBufferSize = 0;
299	if (threadContext->rewindBuffer) {
300		int i;
301		for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
302			GBADeallocateState(threadContext->rewindBuffer[i]);
303		}
304		free(threadContext->rewindBuffer);
305		free(threadContext->rewindScreenBuffer);
306	}
307	threadContext->rewindBufferCapacity = newCapacity;
308	if (threadContext->rewindBufferCapacity > 0) {
309		threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
310		threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
311	} else {
312		threadContext->rewindBuffer = 0;
313		threadContext->rewindScreenBuffer = 0;
314	}
315}
316
317void GBARewind(struct GBAThread* thread, int nStates) {
318	if (nStates > thread->rewindBufferSize || nStates < 0) {
319		nStates = thread->rewindBufferSize;
320	}
321	if (nStates == 0) {
322		return;
323	}
324	int offset = thread->rewindBufferWriteOffset - nStates;
325	if (offset < 0) {
326		offset += thread->rewindBufferCapacity;
327	}
328	struct GBASerializedState* state = thread->rewindBuffer[offset];
329	if (!state) {
330		return;
331	}
332	thread->rewindBufferSize -= nStates;
333	thread->rewindBufferWriteOffset = offset;
334	GBADeserialize(thread->gba, state);
335	if (thread->rewindScreenBuffer) {
336		thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
337	}
338}
339
340void GBARewindAll(struct GBAThread* thread) {
341	GBARewind(thread, thread->rewindBufferSize);
342}