all repos — mgba @ c0818c3a0c68b872441d0f4b6ddf491f47736bc1

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