all repos — mgba @ 3b29ba1aa29e9c303385b090aaaa6cc2733ad367

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