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