all repos — mgba @ 3af3fab3cf6af8c8575978239c9182c5f40fd499

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	if (state->cpu.cycles < 0) {
 78		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are negative");
 79		return;
 80	}
 81	if (state->video.nextHblank - state->video.eventDiff < 0) {
 82		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: nextHblank is negative");
 83		return;
 84	}
 85	if (state->video.lastHblank - state->video.eventDiff < -VIDEO_HBLANK_LENGTH) {
 86		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: lastHblank is negative");
 87		return;
 88	}
 89	if (state->timers[0].overflowInterval < 0 || state->timers[1].overflowInterval < 0 || state->timers[2].overflowInterval < 0 || state->timers[3].overflowInterval < 0) {
 90		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: overflowInterval is negative");
 91		return;
 92	}
 93	memcpy(gba->cpu->gprs, state->cpu.gprs, sizeof(gba->cpu->gprs));
 94	gba->cpu->cpsr = state->cpu.cpsr;
 95	gba->cpu->spsr = state->cpu.spsr;
 96	gba->cpu->cycles = state->cpu.cycles;
 97	gba->cpu->nextEvent = state->cpu.nextEvent;
 98	memcpy(gba->cpu->bankedRegisters, state->cpu.bankedRegisters, 6 * 7 * sizeof(int32_t));
 99	memcpy(gba->cpu->bankedSPSRs, state->cpu.bankedSPSRs, 6 * sizeof(int32_t));
100	gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
101	gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
102	if (state->biosPrefetch) {
103		gba->memory.biosPrefetch = state->biosPrefetch;
104	}
105	if (gba->cpu->cpsr.t) {
106		gba->cpu->executionMode = MODE_THUMB;
107		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
108			gba->cpu->prefetch[0] = state->cpuPrefetch[0] & 0xFFFF;
109			gba->cpu->prefetch[1] = state->cpuPrefetch[1] & 0xFFFF;
110		} else {
111			// Maintain backwards compat
112			LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
113			LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
114		}
115	} else {
116		gba->cpu->executionMode = MODE_ARM;
117		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
118			gba->cpu->prefetch[0] = state->cpuPrefetch[0];
119			gba->cpu->prefetch[1] = state->cpuPrefetch[1];
120		} else {
121			// Maintain backwards compat
122			LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
123			LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
124		}
125	}
126
127	GBAMemoryDeserialize(&gba->memory, state);
128	GBAIODeserialize(gba, state);
129	GBAVideoDeserialize(&gba->video, state);
130	GBAAudioDeserialize(&gba->audio, state);
131	GBASavedataDeserialize(&gba->memory.savedata, state, false);
132
133	if (gba->rr) {
134		gba->rr->stateLoaded(gba->rr, state);
135	}
136}
137
138struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
139	char suffix[5] = { '\0' };
140	snprintf(suffix, sizeof(suffix), ".ss%d", slot);
141	return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
142}
143
144#ifdef USE_PNG
145static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
146	unsigned stride;
147	void* pixels = 0;
148	gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
149	if (!pixels) {
150		return false;
151	}
152
153	struct GBASerializedState* state = GBAAllocateState();
154	if (!state) {
155		return false;
156	}
157	png_structp png = PNGWriteOpen(vf);
158	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
159	if (!png || !info) {
160		PNGWriteClose(png, info);
161		GBADeallocateState(state);
162		return false;
163	}
164	uLongf len = compressBound(sizeof(*state));
165	void* buffer = malloc(len);
166	if (!buffer) {
167		PNGWriteClose(png, info);
168		GBADeallocateState(state);
169		return false;
170	}
171	GBASerialize(gba, state);
172	compress(buffer, &len, (const Bytef*) state, sizeof(*state));
173	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
174	PNGWriteCustomChunk(png, "gbAs", len, buffer);
175	PNGWriteClose(png, info);
176	free(buffer);
177	GBADeallocateState(state);
178	return true;
179}
180
181static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
182	if (strcmp((const char*) chunk->name, "gbAs") != 0) {
183		return 0;
184	}
185	struct GBASerializedState state;
186	uLongf len = sizeof(state);
187	uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
188	GBADeserialize(png_get_user_chunk_ptr(png), &state);
189	return 1;
190}
191
192static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
193	png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
194	png_infop info = png_create_info_struct(png);
195	png_infop end = png_create_info_struct(png);
196	if (!png || !info || !end) {
197		PNGReadClose(png, info, end);
198		return false;
199	}
200	uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
201
202	PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
203	PNGReadHeader(png, info);
204	PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
205	PNGReadFooter(png, end);
206	PNGReadClose(png, info, end);
207	gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
208	GBASyncForceFrame(gba->sync);
209
210	free(pixels);
211	return true;
212}
213#endif
214
215bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
216	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
217	if (!vf) {
218		return false;
219	}
220	bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
221	vf->close(vf);
222	if (success) {
223		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
224	}
225	return success;
226}
227
228bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
229	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
230	if (!vf) {
231		return false;
232	}
233	threadContext->rewindBufferSize = 0;
234	bool success = GBALoadStateNamed(threadContext->gba, vf);
235	vf->close(vf);
236	if (success) {
237		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
238	}
239	return success;
240}
241
242bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
243	if (!screenshot) {
244		vf->truncate(vf, sizeof(struct GBASerializedState));
245		struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
246		if (!state) {
247			return false;
248		}
249		GBASerialize(gba, state);
250		vf->unmap(vf, state, sizeof(struct GBASerializedState));
251		return true;
252	}
253	#ifdef USE_PNG
254	else {
255		return _savePNGState(gba, vf);
256	}
257	#endif
258	return false;
259}
260
261bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
262	#ifdef USE_PNG
263	if (isPNG(vf)) {
264		return _loadPNGState(gba, vf);
265	}
266	#endif
267	if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
268		return false;
269	}
270	struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
271	if (!state) {
272		return false;
273	}
274	GBADeserialize(gba, state);
275	vf->unmap(vf, state, sizeof(struct GBASerializedState));
276	return true;
277}
278
279struct GBASerializedState* GBAAllocateState(void) {
280	return anonymousMemoryMap(sizeof(struct GBASerializedState));
281}
282
283void GBADeallocateState(struct GBASerializedState* state) {
284	mappedMemoryFree(state, sizeof(struct GBASerializedState));
285}
286
287void GBARecordFrame(struct GBAThread* thread) {
288	int offset = thread->rewindBufferWriteOffset;
289	struct GBASerializedState* state = thread->rewindBuffer[offset];
290	if (!state) {
291		state = GBAAllocateState();
292		thread->rewindBuffer[offset] = state;
293	}
294	GBASerialize(thread->gba, state);
295
296	if (thread->rewindScreenBuffer) {
297		unsigned stride;
298		uint8_t* pixels = 0;
299		thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
300		if (pixels) {
301			size_t y;
302			for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
303				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);
304			}
305		}
306	}
307	thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
308	thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
309}
310
311void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
312	if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
313		return;
314	}
315	threadContext->rewindBufferInterval = newInterval;
316	threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
317	threadContext->rewindBufferSize = 0;
318	if (threadContext->rewindBuffer) {
319		int i;
320		for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
321			GBADeallocateState(threadContext->rewindBuffer[i]);
322		}
323		free(threadContext->rewindBuffer);
324		free(threadContext->rewindScreenBuffer);
325	}
326	threadContext->rewindBufferCapacity = newCapacity;
327	if (threadContext->rewindBufferCapacity > 0) {
328		threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
329		threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
330	} else {
331		threadContext->rewindBuffer = 0;
332		threadContext->rewindScreenBuffer = 0;
333	}
334}
335
336int GBARewind(struct GBAThread* thread, int nStates) {
337	if (nStates > thread->rewindBufferSize || nStates < 0) {
338		nStates = thread->rewindBufferSize;
339	}
340	if (nStates == 0) {
341		return 0;
342	}
343	int offset = thread->rewindBufferWriteOffset - nStates;
344	if (offset < 0) {
345		offset += thread->rewindBufferCapacity;
346	}
347	struct GBASerializedState* state = thread->rewindBuffer[offset];
348	if (!state) {
349		return 0;
350	}
351	thread->rewindBufferSize -= nStates;
352	thread->rewindBufferWriteOffset = offset;
353	GBADeserialize(thread->gba, state);
354	if (thread->rewindScreenBuffer) {
355		thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
356	}
357	return nStates;
358}
359
360void GBARewindAll(struct GBAThread* thread) {
361	GBARewind(thread, thread->rewindBufferSize);
362}