all repos — mgba @ 376ccd4a306a1282cc76f4db8aaff7f88b4d95d1

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
190struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
191	char suffix[5] = { '\0' };
192	snprintf(suffix, sizeof(suffix), ".ss%d", slot);
193	return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
194}
195
196#ifdef USE_PNG
197static bool _savePNGState(struct GBA* gba, struct VFile* vf) {
198	unsigned stride;
199	void* pixels = 0;
200	gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
201	if (!pixels) {
202		return false;
203	}
204
205	struct GBASerializedState* state = GBAAllocateState();
206	if (!state) {
207		return false;
208	}
209	png_structp png = PNGWriteOpen(vf);
210	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
211	if (!png || !info) {
212		PNGWriteClose(png, info);
213		GBADeallocateState(state);
214		return false;
215	}
216	uLongf len = compressBound(sizeof(*state));
217	void* buffer = malloc(len);
218	if (!buffer) {
219		PNGWriteClose(png, info);
220		GBADeallocateState(state);
221		return false;
222	}
223	GBASerialize(gba, state);
224	compress(buffer, &len, (const Bytef*) state, sizeof(*state));
225	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
226	PNGWriteCustomChunk(png, "gbAs", len, buffer);
227	PNGWriteClose(png, info);
228	free(buffer);
229	GBADeallocateState(state);
230	return true;
231}
232
233static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
234	if (strcmp((const char*) chunk->name, "gbAs") != 0) {
235		return 0;
236	}
237	struct GBASerializedState state;
238	uLongf len = sizeof(state);
239	uncompress((Bytef*) &state, &len, chunk->data, chunk->size);
240	if (!GBADeserialize(png_get_user_chunk_ptr(png), &state)) {
241		longjmp(png_jmpbuf(png), 1);
242	}
243	return 1;
244}
245
246static bool _loadPNGState(struct GBA* gba, struct VFile* vf) {
247	png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
248	png_infop info = png_create_info_struct(png);
249	png_infop end = png_create_info_struct(png);
250	if (!png || !info || !end) {
251		PNGReadClose(png, info, end);
252		return false;
253	}
254	uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
255
256	PNGInstallChunkHandler(png, gba, _loadPNGChunkHandler, "gbAs");
257	bool success = PNGReadHeader(png, info);
258	success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
259	success = success && PNGReadFooter(png, end);
260	PNGReadClose(png, info, end);
261	if (success) {
262		gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, pixels);
263		GBASyncForceFrame(gba->sync);
264	}
265
266	free(pixels);
267	return success;
268}
269#endif
270
271#ifndef _3DS
272bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, bool screenshot) {
273	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
274	if (!vf) {
275		return false;
276	}
277	bool success = GBASaveStateNamed(threadContext->gba, vf, screenshot);
278	vf->close(vf);
279	if (success) {
280		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
281	} else {
282		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
283	}
284	return success;
285}
286
287bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot) {
288	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
289	if (!vf) {
290		return false;
291	}
292	threadContext->rewindBufferSize = 0;
293	bool success = GBALoadStateNamed(threadContext->gba, vf);
294	vf->close(vf);
295	if (success) {
296		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
297	} else {
298		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
299	}
300	return success;
301}
302#endif
303
304bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, bool screenshot) {
305#ifdef USE_PNG
306	if (!screenshot) {
307#else
308	UNUSED(screenshot);
309#endif
310		vf->truncate(vf, sizeof(struct GBASerializedState));
311		struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
312		if (!state) {
313			return false;
314		}
315		GBASerialize(gba, state);
316		vf->unmap(vf, state, sizeof(struct GBASerializedState));
317		return true;
318#ifdef USE_PNG
319	}
320	else {
321		return _savePNGState(gba, vf);
322	}
323#endif
324	return false;
325}
326
327bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf) {
328#ifdef USE_PNG
329	if (isPNG(vf)) {
330		return _loadPNGState(gba, vf);
331	}
332#endif
333	if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
334		return false;
335	}
336	struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_READ);
337	if (!state) {
338		return false;
339	}
340	bool success = GBADeserialize(gba, state);
341	vf->unmap(vf, state, sizeof(struct GBASerializedState));
342	return success;
343}
344
345struct GBASerializedState* GBAAllocateState(void) {
346	return anonymousMemoryMap(sizeof(struct GBASerializedState));
347}
348
349void GBADeallocateState(struct GBASerializedState* state) {
350	mappedMemoryFree(state, sizeof(struct GBASerializedState));
351}
352
353void GBARecordFrame(struct GBAThread* thread) {
354	int offset = thread->rewindBufferWriteOffset;
355	struct GBASerializedState* state = thread->rewindBuffer[offset];
356	if (!state) {
357		state = GBAAllocateState();
358		thread->rewindBuffer[offset] = state;
359	}
360	GBASerialize(thread->gba, state);
361
362	if (thread->rewindScreenBuffer) {
363		unsigned stride;
364		uint8_t* pixels = 0;
365		thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (void*) &pixels);
366		if (pixels) {
367			size_t y;
368			for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
369				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);
370			}
371		}
372	}
373	thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
374	thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
375}
376
377void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
378	if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
379		return;
380	}
381	threadContext->rewindBufferInterval = newInterval;
382	threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
383	threadContext->rewindBufferSize = 0;
384	if (threadContext->rewindBuffer) {
385		int i;
386		for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
387			GBADeallocateState(threadContext->rewindBuffer[i]);
388		}
389		free(threadContext->rewindBuffer);
390		free(threadContext->rewindScreenBuffer);
391	}
392	threadContext->rewindBufferCapacity = newCapacity;
393	if (threadContext->rewindBufferCapacity > 0) {
394		threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
395		threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
396	} else {
397		threadContext->rewindBuffer = 0;
398		threadContext->rewindScreenBuffer = 0;
399	}
400}
401
402int GBARewind(struct GBAThread* thread, int nStates) {
403	if (nStates > thread->rewindBufferSize || nStates < 0) {
404		nStates = thread->rewindBufferSize;
405	}
406	if (nStates == 0) {
407		return 0;
408	}
409	int offset = thread->rewindBufferWriteOffset - nStates;
410	if (offset < 0) {
411		offset += thread->rewindBufferCapacity;
412	}
413	struct GBASerializedState* state = thread->rewindBuffer[offset];
414	if (!state) {
415		return 0;
416	}
417	thread->rewindBufferSize -= nStates;
418	thread->rewindBufferWriteOffset = offset;
419	GBADeserialize(thread->gba, state);
420	if (thread->rewindScreenBuffer) {
421		thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
422	}
423	return nStates;
424}
425
426void GBARewindAll(struct GBAThread* thread) {
427	GBARewind(thread, thread->rewindBufferSize);
428}