all repos — mgba @ 42b011a68ba30aa5720ef6601efc72e256a2de9a

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