all repos — mgba @ 933a6c4f36bb4ebf3eeab126093c798128541fd9

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