all repos — mgba @ e732448aa4d7edb24095dd4c4ae2ad434c9effa2

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