all repos — mgba @ f57b47b3f24063d409d0a50f5fedacdd80ccc1f7

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, (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
 86	} else {
 87		gba->cpu->executionMode = MODE_ARM;
 88		LOAD_32(gba->cpu->prefetch, (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
 89	}
 90
 91	GBAMemoryDeserialize(&gba->memory, state);
 92	GBAIODeserialize(gba, state);
 93	GBAVideoDeserialize(&gba->video, state);
 94	GBAAudioDeserialize(&gba->audio, state);
 95
 96	if (GBARRIsRecording(gba->rr)) {
 97		if (state->associatedStreamId != gba->rr->streamId) {
 98			GBARRLoadStream(gba->rr, state->associatedStreamId);
 99			GBARRIncrementStream(gba->rr, true);
100		} else {
101			GBARRFinishSegment(gba->rr);
102		}
103		GBARRMarkRerecord(gba->rr);
104	} else if (GBARRIsPlaying(gba->rr)) {
105		GBARRLoadStream(gba->rr, state->associatedStreamId);
106		GBARRSkipSegment(gba->rr);
107	}
108}
109
110struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
111	char suffix[5] = { '\0' };
112	snprintf(suffix, sizeof(suffix), ".ss%d", slot);
113	return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
114}
115
116#ifdef USE_PNG
117static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
118	unsigned stride;
119	void* pixels = 0;
120	gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
121	if (!pixels) {
122		return false;
123	}
124
125	struct GBASerializedState* state = GBAAllocateState();
126	png_structp png = PNGWriteOpen(vf);
127	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
128	uLongf len = compressBound(sizeof(*state));
129	void* buffer = malloc(len);
130	if (state && png && info && buffer) {
131		GBASerialize(gba, state);
132		compress(buffer, &len, (const Bytef*) state, sizeof(*state));
133		PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
134		PNGWriteCustomChunk(png, "gbAs", len, buffer);
135	}
136	PNGWriteClose(png, info);
137	free(buffer);
138	GBADeallocateState(state);
139	return state && png && info && buffer;
140}
141
142static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
143	if (strcmp((const char*) chunk->name, "gbAs") != 0) {
144		return 0;
145	}
146	struct GBASerializedState state;
147	uLongf len = sizeof(state);
148	uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
149	GBADeserialize(png_get_user_chunk_ptr(png), &state);
150	return 1;
151}
152
153static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
154	png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
155	png_infop info = png_create_info_struct(png);
156	png_infop end = png_create_info_struct(png);
157	if (!png || !info || !end) {
158		PNGReadClose(png, info, end);
159		return false;
160	}
161	uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
162
163	PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
164	PNGReadHeader(png, info);
165	PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
166	PNGReadFooter(png, end);
167	PNGReadClose(png, info, end);
168	gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
169	GBASyncPostFrame(gba->sync);
170
171	free(pixels);
172	return true;
173}
174#endif
175
176bool GBASaveState(struct GBA* gba, struct VDir* dir, int slot, bool screenshot) {
177	struct VFile* vf = GBAGetState(gba, dir, slot, true);
178	if (!vf) {
179		return false;
180	}
181	bool success = GBASaveStateNamed(gba, vf, screenshot);
182	vf->close(vf);
183	return success;
184}
185
186bool GBALoadState(struct GBA* gba, struct VDir* dir, int slot) {
187	struct VFile* vf = GBAGetState(gba, dir, slot, false);
188	if (!vf) {
189		return false;
190	}
191	bool success = GBALoadStateNamed(gba, vf);
192	vf->close(vf);
193	return success;
194}
195
196bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
197	if (!screenshot) {
198		vf->truncate(vf, sizeof(struct GBASerializedState));
199		struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
200		if (!state) {
201			return false;
202		}
203		GBASerialize(gba, state);
204		vf->unmap(vf, state, sizeof(struct GBASerializedState));
205		return true;
206	}
207	#ifdef USE_PNG
208	else {
209		return _savePNGState(gba, vf);
210	}
211	#endif
212	return false;
213}
214
215bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
216	#ifdef USE_PNG
217	if (isPNG(vf)) {
218		return _loadPNGState(gba, vf);
219	}
220	#endif
221	struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
222	if (!state) {
223		return false;
224	}
225	GBADeserialize(gba, state);
226	vf->unmap(vf, state, sizeof(struct GBASerializedState));
227	return true;
228}
229
230struct GBASerializedState* GBAAllocateState(void) {
231	return anonymousMemoryMap(sizeof(struct GBASerializedState));
232}
233
234void GBADeallocateState(struct GBASerializedState* state) {
235	mappedMemoryFree(state, sizeof(struct GBASerializedState));
236}
237
238void GBARecordFrame(struct GBAThread* thread) {
239	int offset = thread->rewindBufferWriteOffset;
240	struct GBASerializedState* state = thread->rewindBuffer[offset];
241	if (!state) {
242		state = GBAAllocateState();
243		thread->rewindBuffer[offset] = state;
244	}
245	GBASerialize(thread->gba, state);
246	thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
247	thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
248}
249
250void GBARewind(struct GBAThread* thread, int nStates) {
251	if (nStates > thread->rewindBufferSize || nStates < 0) {
252		nStates = thread->rewindBufferSize;
253	}
254	if (nStates == 0) {
255		return;
256	}
257	int offset = thread->rewindBufferWriteOffset - nStates;
258	if (offset < 0) {
259		offset += thread->rewindBufferSize;
260	}
261	struct GBASerializedState* state = thread->rewindBuffer[offset];
262	if (!state) {
263		return;
264	}
265	thread->rewindBufferSize -= nStates;
266	thread->rewindBufferWriteOffset = (offset + thread->rewindBufferCapacity - nStates) % thread->rewindBufferCapacity;
267	GBADeserialize(thread->gba, state);
268}