all repos — mgba @ e212157d2fea8ef782be199c6f7a500185364e7e

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#include <sys/time.h>
 19
 20#ifdef USE_PNG
 21#include "util/png-io.h"
 22#include <png.h>
 23#include <zlib.h>
 24#endif
 25
 26const uint32_t GBA_SAVESTATE_MAGIC = 0x01000000;
 27
 28struct GBABundledState {
 29	struct GBASerializedState* state;
 30	struct GBAExtdata* extdata;
 31};
 32
 33struct GBAExtdataHeader {
 34	uint32_t tag;
 35	int32_t size;
 36	int64_t offset;
 37};
 38
 39void GBASerialize(struct GBA* gba, struct GBASerializedState* state) {
 40	STORE_32(GBA_SAVESTATE_MAGIC, 0, &state->versionMagic);
 41	STORE_32(gba->biosChecksum, 0, &state->biosChecksum);
 42	STORE_32(gba->romCrc32, 0, &state->romCrc32);
 43
 44	if (gba->memory.rom) {
 45		state->id = ((struct GBACartridge*) gba->memory.rom)->id;
 46		memcpy(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title));
 47	} else {
 48		state->id = 0;
 49		memset(state->title, 0, sizeof(state->title));
 50	}
 51
 52	int i;
 53	for (i = 0; i < 16; ++i) {
 54		STORE_32(gba->cpu->gprs[i], i * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
 55	}
 56	STORE_32(gba->cpu->cpsr.packed, 0, &state->cpu.cpsr.packed);
 57	STORE_32(gba->cpu->spsr.packed, 0, &state->cpu.spsr.packed);
 58	STORE_32(gba->cpu->cycles, 0, &state->cpu.cycles);
 59	STORE_32(gba->cpu->nextEvent, 0, &state->cpu.nextEvent);
 60	for (i = 0; i < 6; ++i) {
 61		int j;
 62		for (j = 0; j < 7; ++j) {
 63			STORE_32(gba->cpu->bankedRegisters[i][j], (i * 7 + j) * sizeof(gba->cpu->bankedRegisters[0][0]), state->cpu.bankedRegisters);
 64		}
 65		STORE_32(gba->cpu->bankedSPSRs[i], i * sizeof(gba->cpu->bankedSPSRs[0]), state->cpu.bankedSPSRs);
 66	}
 67
 68	state->biosPrefetch = gba->memory.biosPrefetch;
 69	STORE_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
 70	STORE_32(gba->cpu->prefetch[1], 4, state->cpuPrefetch);
 71
 72	GBAMemorySerialize(&gba->memory, state);
 73	GBAIOSerialize(gba, state);
 74	GBAVideoSerialize(&gba->video, state);
 75	GBAAudioSerialize(&gba->audio, state);
 76	GBASavedataSerialize(&gba->memory.savedata, state);
 77
 78	struct timeval tv;
 79	if (!gettimeofday(&tv, 0)) {
 80		uint64_t usec = tv.tv_usec;
 81		usec += tv.tv_sec * 1000000LL;
 82		STORE_64(usec, 0, &state->creationUsec);
 83	} else {
 84		state->creationUsec = 0;
 85	}
 86	state->associatedStreamId = 0;
 87	if (gba->rr) {
 88		gba->rr->stateSaved(gba->rr, state);
 89	}
 90}
 91
 92bool GBADeserialize(struct GBA* gba, const struct GBASerializedState* state) {
 93	bool error = false;
 94	int32_t check;
 95	uint32_t ucheck;
 96	LOAD_32(ucheck, 0, &state->versionMagic);
 97	if (ucheck != GBA_SAVESTATE_MAGIC) {
 98		GBALog(gba, GBA_LOG_WARN, "Invalid or too new savestate: expected %08X, got %08X", GBA_SAVESTATE_MAGIC, ucheck);
 99		error = true;
100	}
101	LOAD_32(ucheck, 0, &state->biosChecksum);
102	if (ucheck != gba->biosChecksum) {
103		GBALog(gba, GBA_LOG_WARN, "Savestate created using a different version of the BIOS: expected %08X, got %08X", gba->biosChecksum, ucheck);
104		uint32_t pc;
105		LOAD_32(pc, ARM_PC * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
106		if (pc < SIZE_BIOS && pc >= 0x20) {
107			error = true;
108		}
109	}
110	if (gba->memory.rom && (state->id != ((struct GBACartridge*) gba->memory.rom)->id || memcmp(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title)))) {
111		GBALog(gba, GBA_LOG_WARN, "Savestate is for a different game");
112		error = true;
113	} else if (!gba->memory.rom && state->id != 0) {
114		GBALog(gba, GBA_LOG_WARN, "Savestate is for a game, but no game loaded");
115		error = true;
116	}
117	LOAD_32(ucheck, 0, &state->romCrc32);
118	if (ucheck != gba->romCrc32) {
119		GBALog(gba, GBA_LOG_WARN, "Savestate is for a different version of the game");
120	}
121	LOAD_32(check, 0, &state->cpu.cycles);
122	if (check < 0) {
123		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are negative");
124		error = true;
125	}
126	if (check >= (int32_t) GBA_ARM7TDMI_FREQUENCY) {
127		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: CPU cycles are too high");
128		error = true;
129	}
130	LOAD_32(check, 0, &state->video.eventDiff);
131	if (check < 0) {
132		GBALog(gba, GBA_LOG_WARN, "Savestate is corrupted: video eventDiff is negative");
133		error = true;
134	}
135	LOAD_32(check, ARM_PC * sizeof(state->cpu.gprs[0]), state->cpu.gprs);
136	int region = (check >> BASE_OFFSET);
137	if ((region == REGION_CART0 || region == REGION_CART1 || region == REGION_CART2) && ((check - 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	size_t i;
145	for (i = 0; i < 16; ++i) {
146		LOAD_32(gba->cpu->gprs[i], i * sizeof(gba->cpu->gprs[0]), state->cpu.gprs);
147	}
148	LOAD_32(gba->cpu->cpsr.packed, 0, &state->cpu.cpsr.packed);
149	LOAD_32(gba->cpu->spsr.packed, 0, &state->cpu.spsr.packed);
150	LOAD_32(gba->cpu->cycles, 0, &state->cpu.cycles);
151	LOAD_32(gba->cpu->nextEvent, 0, &state->cpu.nextEvent);
152	for (i = 0; i < 6; ++i) {
153		int j;
154		for (j = 0; j < 7; ++j) {
155			LOAD_32(gba->cpu->bankedRegisters[i][j], (i * 7 + j) * sizeof(gba->cpu->bankedRegisters[0][0]), state->cpu.bankedRegisters);
156		}
157		LOAD_32(gba->cpu->bankedSPSRs[i], i * sizeof(gba->cpu->bankedSPSRs[0]), state->cpu.bankedSPSRs);
158	}
159	gba->cpu->privilegeMode = gba->cpu->cpsr.priv;
160	gba->cpu->memory.setActiveRegion(gba->cpu, gba->cpu->gprs[ARM_PC]);
161	if (state->biosPrefetch) {
162		LOAD_32(gba->memory.biosPrefetch, 0, &state->biosPrefetch);
163	}
164	if (gba->cpu->cpsr.t) {
165		gba->cpu->executionMode = MODE_THUMB;
166		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
167			LOAD_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
168			LOAD_32(gba->cpu->prefetch[1], 4, state->cpuPrefetch);
169			gba->cpu->prefetch[0] &= 0xFFFF;
170			gba->cpu->prefetch[1] &= 0xFFFF;
171		} else {
172			// Maintain backwards compat
173			LOAD_16(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_THUMB) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
174			LOAD_16(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
175		}
176	} else {
177		gba->cpu->executionMode = MODE_ARM;
178		if (state->cpuPrefetch[0] && state->cpuPrefetch[1]) {
179			LOAD_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch);
180			LOAD_32(gba->cpu->prefetch[1], 4, state->cpuPrefetch);
181		} else {
182			// Maintain backwards compat
183			LOAD_32(gba->cpu->prefetch[0], (gba->cpu->gprs[ARM_PC] - WORD_SIZE_ARM) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
184			LOAD_32(gba->cpu->prefetch[1], (gba->cpu->gprs[ARM_PC]) & gba->cpu->memory.activeMask, gba->cpu->memory.activeRegion);
185		}
186	}
187
188	GBAMemoryDeserialize(&gba->memory, state);
189	GBAIODeserialize(gba, state);
190	GBAVideoDeserialize(&gba->video, state);
191	GBAAudioDeserialize(&gba->audio, state);
192	GBASavedataDeserialize(&gba->memory.savedata, state);
193
194	if (gba->rr) {
195		gba->rr->stateLoaded(gba->rr, state);
196	}
197	return true;
198}
199
200struct VFile* GBAGetState(struct GBA* gba, struct VDir* dir, int slot, bool write) {
201	char suffix[5] = { '\0' };
202	snprintf(suffix, sizeof(suffix), ".ss%d", slot);
203	return VDirOptionalOpenFile(dir, gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
204}
205
206#ifdef USE_PNG
207static bool _savePNGState(struct GBA* gba, struct VFile* vf, struct GBAExtdata* extdata) {
208	unsigned stride;
209	const void* pixels = 0;
210	gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
211	if (!pixels) {
212		return false;
213	}
214
215	struct GBASerializedState* state = GBAAllocateState();
216	if (!state) {
217		return false;
218	}
219	GBASerialize(gba, state);
220	uLongf len = compressBound(sizeof(*state));
221	void* buffer = malloc(len);
222	if (!buffer) {
223		GBADeallocateState(state);
224		return false;
225	}
226	compress(buffer, &len, (const Bytef*) state, sizeof(*state));
227	GBADeallocateState(state);
228
229	png_structp png = PNGWriteOpen(vf);
230	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
231	if (!png || !info) {
232		PNGWriteClose(png, info);
233		free(buffer);
234		return false;
235	}
236	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
237	PNGWriteCustomChunk(png, "gbAs", len, buffer);
238	if (extdata) {
239		uint32_t i;
240		for (i = 1; i < EXTDATA_MAX; ++i) {
241			if (!extdata->data[i].data) {
242				continue;
243			}
244			uLongf len = compressBound(extdata->data[i].size) + sizeof(uint32_t) * 2;
245			uint32_t* data = malloc(len);
246			if (!data) {
247				continue;
248			}
249			STORE_32(i, 0, data);
250			STORE_32(extdata->data[i].size, sizeof(uint32_t), data);
251			compress((Bytef*) (data + 2), &len, extdata->data[i].data, extdata->data[i].size);
252			PNGWriteCustomChunk(png, "gbAx", len + sizeof(uint32_t) * 2, data);
253			free(data);
254		}
255	}
256	PNGWriteClose(png, info);
257	free(buffer);
258	return true;
259}
260
261static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
262	struct GBABundledState* bundle = png_get_user_chunk_ptr(png);
263	if (!bundle) {
264		return 0;
265	}
266	if (!strcmp((const char*) chunk->name, "gbAs")) {
267		struct GBASerializedState* state = bundle->state;
268		if (!state) {
269			return 0;
270		}
271		uLongf len = sizeof(*state);
272		uncompress((Bytef*) state, &len, chunk->data, chunk->size);
273		return 1;
274	}
275	if (!strcmp((const char*) chunk->name, "gbAx")) {
276		struct GBAExtdata* extdata = bundle->extdata;
277		if (!extdata) {
278			return 0;
279		}
280		struct GBAExtdataItem item;
281		if (chunk->size < sizeof(uint32_t) * 2) {
282			return 0;
283		}
284		uint32_t tag;
285		LOAD_32(tag, 0, chunk->data);
286		LOAD_32(item.size, sizeof(uint32_t), chunk->data);
287		uLongf len = item.size;
288		if (item.size < 0) {
289			return 0;
290		}
291		item.data = malloc(item.size);
292		item.clean = free;
293		if (!item.data) {
294			return 0;
295		}
296		const uint8_t* data = chunk->data;
297		data += sizeof(uint32_t) * 2;
298		uncompress((Bytef*) item.data, &len, data, chunk->size);
299		item.size = len;
300		GBAExtdataPut(extdata, tag, &item);
301		return 1;
302	}
303	return 0;
304}
305
306static struct GBASerializedState* _loadPNGState(struct VFile* vf, struct GBAExtdata* extdata) {
307	png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
308	png_infop info = png_create_info_struct(png);
309	png_infop end = png_create_info_struct(png);
310	if (!png || !info || !end) {
311		PNGReadClose(png, info, end);
312		return false;
313	}
314	uint32_t* pixels = malloc(VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4);
315	if (!pixels) {
316		PNGReadClose(png, info, end);
317		return false;
318	}
319
320	struct GBASerializedState* state = GBAAllocateState();
321	struct GBABundledState bundle = {
322		.state = state,
323		.extdata = extdata
324	};
325
326	PNGInstallChunkHandler(png, &bundle, _loadPNGChunkHandler, "gbAs gbAx");
327	bool success = PNGReadHeader(png, info);
328	success = success && PNGReadPixels(png, info, pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS);
329	success = success && PNGReadFooter(png, end);
330	PNGReadClose(png, info, end);
331
332	if (success) {
333		struct GBAExtdataItem item = {
334			.size = VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4,
335			.data = pixels,
336			.clean = free
337		};
338		GBAExtdataPut(extdata, EXTDATA_SCREENSHOT, &item);
339	} else {
340		free(pixels);
341		GBADeallocateState(state);
342		return 0;
343	}
344	return state;
345}
346#endif
347
348bool GBASaveState(struct GBAThread* threadContext, struct VDir* dir, int slot, int flags) {
349	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, true);
350	if (!vf) {
351		return false;
352	}
353	bool success = GBASaveStateNamed(threadContext->gba, vf, flags);
354	vf->close(vf);
355	if (success) {
356#if SAVESTATE_DEBUG
357		vf = GBAGetState(threadContext->gba, dir, slot, false);
358		if (vf) {
359			struct GBA* backup = anonymousMemoryMap(sizeof(*backup));
360			memcpy(backup, threadContext->gba, sizeof(*backup));
361			memset(threadContext->gba->memory.io, 0, sizeof(threadContext->gba->memory.io));
362			memset(threadContext->gba->timers, 0, sizeof(threadContext->gba->timers));
363			GBALoadStateNamed(threadContext->gba, vf, flags);
364			if (memcmp(backup, threadContext->gba, sizeof(*backup))) {
365				char suffix[16] = { '\0' };
366				struct VFile* vf2;
367				snprintf(suffix, sizeof(suffix), ".dump.0.%d", slot);
368				vf2 = VDirOptionalOpenFile(dir, threadContext->gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
369				if (vf2) {
370					vf2->write(vf2, backup, sizeof(*backup));
371					vf2->close(vf2);
372				}
373				snprintf(suffix, sizeof(suffix), ".dump.1.%d", slot);
374				vf2 = VDirOptionalOpenFile(dir, threadContext->gba->activeFile, "savestate", suffix, write ? (O_CREAT | O_TRUNC | O_RDWR) : O_RDONLY);
375				if (vf2) {
376					vf2->write(vf2, threadContext->gba, sizeof(*threadContext->gba));
377					vf2->close(vf2);
378				}
379			}
380			mappedMemoryFree(backup, sizeof(*backup));
381			vf->close(vf);
382		}
383#endif
384		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i saved", slot);
385	} else {
386		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to save", slot);
387	}
388
389	return success;
390}
391
392bool GBALoadState(struct GBAThread* threadContext, struct VDir* dir, int slot, int flags) {
393	struct VFile* vf = GBAGetState(threadContext->gba, dir, slot, false);
394	if (!vf) {
395		return false;
396	}
397	threadContext->rewindBufferSize = 0;
398	bool success = GBALoadStateNamed(threadContext->gba, vf, flags);
399	vf->close(vf);
400	if (success) {
401		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i loaded", slot);
402	} else {
403		GBALog(threadContext->gba, GBA_LOG_STATUS, "State %i failed to load", slot);
404	}
405	return success;
406}
407
408bool GBASaveStateNamed(struct GBA* gba, struct VFile* vf, int flags) {
409	struct GBAExtdata extdata;
410	GBAExtdataInit(&extdata);
411	if (flags & SAVESTATE_SAVEDATA) {
412		// TODO: A better way to do this would be nice
413		void* sram = malloc(SIZE_CART_FLASH1M);
414		struct VFile* svf = VFileFromMemory(sram, SIZE_CART_FLASH1M);
415		if (GBASavedataClone(&gba->memory.savedata, svf)) {
416			struct GBAExtdataItem item = {
417				.size = svf->seek(svf, 0, SEEK_CUR),
418				.data = sram,
419				.clean = free
420			};
421			GBAExtdataPut(&extdata, EXTDATA_SAVEDATA, &item);
422		} else {
423			free(sram);
424		}
425		svf->close(svf);
426	}
427#ifdef USE_PNG
428	if (!(flags & SAVESTATE_SCREENSHOT)) {
429#else
430	UNUSED(flags);
431#endif
432		vf->truncate(vf, sizeof(struct GBASerializedState));
433		struct GBASerializedState* state = vf->map(vf, sizeof(struct GBASerializedState), MAP_WRITE);
434		if (!state) {
435			GBAExtdataDeinit(&extdata);
436			return false;
437		}
438		GBASerialize(gba, state);
439		vf->unmap(vf, state, sizeof(struct GBASerializedState));
440		vf->seek(vf, sizeof(struct GBASerializedState), SEEK_SET);
441		GBAExtdataSerialize(&extdata, vf);
442		GBAExtdataDeinit(&extdata);
443		return true;
444#ifdef USE_PNG
445	}
446	else {
447		bool success = _savePNGState(gba, vf, &extdata);
448		GBAExtdataDeinit(&extdata);
449		return success;
450	}
451#endif
452	GBAExtdataDeinit(&extdata);
453	return false;
454}
455
456struct GBASerializedState* GBAExtractState(struct VFile* vf, struct GBAExtdata* extdata) {
457#ifdef USE_PNG
458	if (isPNG(vf)) {
459		return _loadPNGState(vf, extdata);
460	}
461#endif
462	if (vf->size(vf) < (ssize_t) sizeof(struct GBASerializedState)) {
463		return false;
464	}
465	struct GBASerializedState* state = GBAAllocateState();
466	if (vf->read(vf, state, sizeof(*state)) != sizeof(*state)) {
467		GBADeallocateState(state);
468		return 0;
469	}
470	if (extdata) {
471		GBAExtdataDeserialize(extdata, vf);
472	}
473	return state;
474}
475
476bool GBALoadStateNamed(struct GBA* gba, struct VFile* vf, int flags) {
477	struct GBAExtdata extdata;
478	GBAExtdataInit(&extdata);
479	struct GBASerializedState* state = GBAExtractState(vf, &extdata);
480	if (!state) {
481		return false;
482	}
483	bool success = GBADeserialize(gba, state);
484	GBADeallocateState(state);
485
486	struct GBAExtdataItem item;
487	if (flags & SAVESTATE_SCREENSHOT && GBAExtdataGet(&extdata, EXTDATA_SCREENSHOT, &item)) {
488		if (item.size >= VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * 4) {
489			gba->video.renderer->putPixels(gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, item.data);
490			GBASyncForceFrame(gba->sync);
491		} else {
492			GBALog(gba, GBA_LOG_WARN, "Savestate includes invalid screenshot");
493		}
494	}
495	if (flags & SAVESTATE_SAVEDATA && GBAExtdataGet(&extdata, EXTDATA_SAVEDATA, &item)) {
496		struct VFile* svf = VFileFromMemory(item.data, item.size);
497		if (svf) {
498			GBASavedataLoad(&gba->memory.savedata, svf);
499			svf->close(svf);
500		}
501	}
502	GBAExtdataDeinit(&extdata);
503	return success;
504}
505
506bool GBAExtdataInit(struct GBAExtdata* extdata) {
507	memset(extdata->data, 0, sizeof(extdata->data));
508	return true;
509}
510
511void GBAExtdataDeinit(struct GBAExtdata* extdata) {
512	size_t i;
513	for (i = 1; i < EXTDATA_MAX; ++i) {
514		if (extdata->data[i].data && extdata->data[i].clean) {
515			extdata->data[i].clean(extdata->data[i].data);
516		}
517	}
518}
519
520void GBAExtdataPut(struct GBAExtdata* extdata, enum GBAExtdataTag tag, struct GBAExtdataItem* item) {
521	if (tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
522		return;
523	}
524
525	if (extdata->data[tag].data && extdata->data[tag].clean) {
526		extdata->data[tag].clean(extdata->data[tag].data);
527	}
528	extdata->data[tag] = *item;
529}
530
531bool GBAExtdataGet(struct GBAExtdata* extdata, enum GBAExtdataTag tag, struct GBAExtdataItem* item) {
532	if (tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
533		return false;
534	}
535
536	*item = extdata->data[tag];
537	return true;
538}
539
540bool GBAExtdataSerialize(struct GBAExtdata* extdata, struct VFile* vf) {
541	ssize_t position = vf->seek(vf, 0, SEEK_CUR);
542	ssize_t size = 2;
543	size_t i = 0;
544	for (i = 1; i < EXTDATA_MAX; ++i) {
545		if (extdata->data[i].data) {
546			size += sizeof(uint64_t) * 2;
547		}
548	}
549	if (size == 2) {
550		return true;
551	}
552	struct GBAExtdataHeader* header = malloc(size);
553	position += size;
554
555	size_t j;
556	for (i = 1, j = 0; i < EXTDATA_MAX; ++i) {
557		if (extdata->data[i].data) {
558			STORE_32(i, offsetof(struct GBAExtdataHeader, tag), &header[j]);
559			STORE_32(extdata->data[i].size, offsetof(struct GBAExtdataHeader, size), &header[j]);
560			STORE_64(position, offsetof(struct GBAExtdataHeader, offset), &header[j]);
561			position += extdata->data[i].size;
562			++j;
563		}
564	}
565	header[j].tag = 0;
566	header[j].size = 0;
567	header[j].offset = 0;
568
569	if (vf->write(vf, header, size) != size) {
570		free(header);
571		return false;
572	}
573	free(header);
574
575	for (i = 1; i < EXTDATA_MAX; ++i) {
576		if (extdata->data[i].data) {
577			if (vf->write(vf, extdata->data[i].data, extdata->data[i].size) != extdata->data[i].size) {
578				return false;
579			}
580		}
581	}
582	return true;
583}
584
585bool GBAExtdataDeserialize(struct GBAExtdata* extdata, struct VFile* vf) {
586	while (true) {
587		struct GBAExtdataHeader buffer, header;
588		if (vf->read(vf, &buffer, sizeof(buffer)) != sizeof(buffer)) {
589			return false;
590		}
591		LOAD_32(header.tag, 0, &buffer.tag);
592		LOAD_32(header.size, 0, &buffer.size);
593		LOAD_64(header.offset, 0, &buffer.offset);
594
595		if (header.tag == EXTDATA_NONE) {
596			break;
597		}
598		if (header.tag >= EXTDATA_MAX) {
599			continue;
600		}
601		ssize_t position = vf->seek(vf, 0, SEEK_CUR);
602		if (vf->seek(vf, header.offset, SEEK_SET) < 0) {
603			return false;
604		}
605		struct GBAExtdataItem item = {
606			.data = malloc(header.size),
607			.size = header.size,
608			.clean = free
609		};
610		if (!item.data) {
611			continue;
612		}
613		if (vf->read(vf, item.data, header.size) != header.size) {
614			free(item.data);
615			continue;
616		}
617		GBAExtdataPut(extdata, header.tag, &item);
618		vf->seek(vf, position, SEEK_SET);
619	};
620	return true;
621}
622
623struct GBASerializedState* GBAAllocateState(void) {
624	return anonymousMemoryMap(sizeof(struct GBASerializedState));
625}
626
627void GBADeallocateState(struct GBASerializedState* state) {
628	mappedMemoryFree(state, sizeof(struct GBASerializedState));
629}
630
631void GBARecordFrame(struct GBAThread* thread) {
632	int offset = thread->rewindBufferWriteOffset;
633	struct GBASerializedState* state = thread->rewindBuffer[offset];
634	if (!state) {
635		state = GBAAllocateState();
636		thread->rewindBuffer[offset] = state;
637	}
638	GBASerialize(thread->gba, state);
639
640	if (thread->rewindScreenBuffer) {
641		unsigned stride;
642		const uint8_t* pixels = 0;
643		thread->gba->video.renderer->getPixels(thread->gba->video.renderer, &stride, (const void**) &pixels);
644		if (pixels) {
645			size_t y;
646			for (y = 0; y < VIDEO_VERTICAL_PIXELS; ++y) {
647				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);
648			}
649		}
650	}
651	thread->rewindBufferSize = thread->rewindBufferSize == thread->rewindBufferCapacity ? thread->rewindBufferCapacity : thread->rewindBufferSize + 1;
652	thread->rewindBufferWriteOffset = (offset + 1) % thread->rewindBufferCapacity;
653}
654
655void GBARewindSettingsChanged(struct GBAThread* threadContext, int newCapacity, int newInterval) {
656	if (newCapacity == threadContext->rewindBufferCapacity && newInterval == threadContext->rewindBufferInterval) {
657		return;
658	}
659	threadContext->rewindBufferInterval = newInterval;
660	threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
661	threadContext->rewindBufferSize = 0;
662	if (threadContext->rewindBuffer) {
663		int i;
664		for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
665			GBADeallocateState(threadContext->rewindBuffer[i]);
666		}
667		free(threadContext->rewindBuffer);
668		free(threadContext->rewindScreenBuffer);
669	}
670	threadContext->rewindBufferCapacity = newCapacity;
671	if (threadContext->rewindBufferCapacity > 0) {
672		threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(struct GBASerializedState*));
673		threadContext->rewindScreenBuffer = calloc(threadContext->rewindBufferCapacity, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
674	} else {
675		threadContext->rewindBuffer = 0;
676		threadContext->rewindScreenBuffer = 0;
677	}
678}
679
680int GBARewind(struct GBAThread* thread, int nStates) {
681	if (nStates > thread->rewindBufferSize || nStates < 0) {
682		nStates = thread->rewindBufferSize;
683	}
684	if (nStates == 0) {
685		return 0;
686	}
687	int offset = thread->rewindBufferWriteOffset - nStates;
688	if (offset < 0) {
689		offset += thread->rewindBufferCapacity;
690	}
691	struct GBASerializedState* state = thread->rewindBuffer[offset];
692	if (!state) {
693		return 0;
694	}
695	thread->rewindBufferSize -= nStates;
696	thread->rewindBufferWriteOffset = offset;
697	GBADeserialize(thread->gba, state);
698	if (thread->rewindScreenBuffer) {
699		thread->gba->video.renderer->putPixels(thread->gba->video.renderer, VIDEO_HORIZONTAL_PIXELS, &thread->rewindScreenBuffer[offset * VIDEO_HORIZONTAL_PIXELS * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL]);
700	}
701	return nStates;
702}
703
704void GBARewindAll(struct GBAThread* thread) {
705	GBARewind(thread, thread->rewindBufferSize);
706}
707
708void GBATakeScreenshot(struct GBA* gba, struct VDir* dir) {
709#ifdef USE_PNG
710	unsigned stride;
711	const void* pixels = 0;
712	struct VFile* vf = VDirOptionalOpenIncrementFile(dir, gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
713	bool success = false;
714	if (vf) {
715		gba->video.renderer->getPixels(gba->video.renderer, &stride, &pixels);
716		png_structp png = PNGWriteOpen(vf);
717		png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
718		success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
719		PNGWriteClose(png, info);
720		vf->close(vf);
721	}
722	if (success) {
723		GBALog(gba, GBA_LOG_STATUS, "Screenshot saved");
724		return;
725	}
726#endif
727	GBALog(gba, GBA_LOG_STATUS, "Failed to take screenshot");
728}