all repos — mgba @ f9e79a1a4280b99e3abf0a83de005fd33211a539

mGBA Game Boy Advance Emulator

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

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