all repos — mgba @ 5fcba6a8b2ae695721a697449ffc9043abe8ce8b

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