all repos — mgba @ 6ad402170c148bf6668e49767eceee040342a540

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