all repos — mgba @ ab028c9d80363fa61f2b7b77c22ad66f93303671

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