src/core/serialize.c (view raw)
1/* Copyright (c) 2013-2016 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 <mgba/core/serialize.h>
7
8#include <mgba/core/core.h>
9#include <mgba/core/cheats.h>
10#include <mgba/core/interface.h>
11#include <mgba-util/memory.h>
12#include <mgba-util/vfs.h>
13
14#ifdef USE_PNG
15#include <mgba-util/png-io.h>
16#include <png.h>
17#include <zlib.h>
18#endif
19
20mLOG_DEFINE_CATEGORY(SAVESTATE, "Savestate", "core.serialize");
21
22struct mBundledState {
23 size_t stateSize;
24 void* state;
25 struct mStateExtdata* extdata;
26};
27
28struct mStateExtdataHeader {
29 uint32_t tag;
30 int32_t size;
31 int64_t offset;
32};
33
34bool mStateExtdataInit(struct mStateExtdata* extdata) {
35 memset(extdata->data, 0, sizeof(extdata->data));
36 return true;
37}
38
39void mStateExtdataDeinit(struct mStateExtdata* extdata) {
40 size_t i;
41 for (i = 1; i < EXTDATA_MAX; ++i) {
42 if (extdata->data[i].data && extdata->data[i].clean) {
43 extdata->data[i].clean(extdata->data[i].data);
44 }
45 }
46}
47
48void mStateExtdataPut(struct mStateExtdata* extdata, enum mStateExtdataTag tag, struct mStateExtdataItem* item) {
49 if (tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
50 return;
51 }
52
53 if (extdata->data[tag].data && extdata->data[tag].clean) {
54 extdata->data[tag].clean(extdata->data[tag].data);
55 }
56 extdata->data[tag] = *item;
57}
58
59bool mStateExtdataGet(struct mStateExtdata* extdata, enum mStateExtdataTag tag, struct mStateExtdataItem* item) {
60 if (tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
61 return false;
62 }
63
64 *item = extdata->data[tag];
65 return true;
66}
67
68bool mStateExtdataSerialize(struct mStateExtdata* extdata, struct VFile* vf) {
69 ssize_t position = vf->seek(vf, 0, SEEK_CUR);
70 ssize_t size = sizeof(struct mStateExtdataHeader);
71 size_t i = 0;
72 for (i = 1; i < EXTDATA_MAX; ++i) {
73 if (extdata->data[i].data) {
74 size += sizeof(struct mStateExtdataHeader);
75 }
76 }
77 if (size == sizeof(struct mStateExtdataHeader)) {
78 return true;
79 }
80 struct mStateExtdataHeader* header = malloc(size);
81 position += size;
82
83 size_t j;
84 for (i = 1, j = 0; i < EXTDATA_MAX; ++i) {
85 if (extdata->data[i].data) {
86 STORE_32LE(i, offsetof(struct mStateExtdataHeader, tag), &header[j]);
87 STORE_32LE(extdata->data[i].size, offsetof(struct mStateExtdataHeader, size), &header[j]);
88 STORE_64LE(position, offsetof(struct mStateExtdataHeader, offset), &header[j]);
89 position += extdata->data[i].size;
90 ++j;
91 }
92 }
93 header[j].tag = 0;
94 header[j].size = 0;
95 header[j].offset = 0;
96
97 if (vf->write(vf, header, size) != size) {
98 free(header);
99 return false;
100 }
101 free(header);
102
103 for (i = 1; i < EXTDATA_MAX; ++i) {
104 if (extdata->data[i].data) {
105 if (vf->write(vf, extdata->data[i].data, extdata->data[i].size) != extdata->data[i].size) {
106 return false;
107 }
108 }
109 }
110 return true;
111}
112
113bool mStateExtdataDeserialize(struct mStateExtdata* extdata, struct VFile* vf) {
114 while (true) {
115 struct mStateExtdataHeader buffer, header;
116 if (vf->read(vf, &buffer, sizeof(buffer)) != sizeof(buffer)) {
117 return false;
118 }
119 LOAD_32LE(header.tag, 0, &buffer.tag);
120 LOAD_32LE(header.size, 0, &buffer.size);
121 LOAD_64LE(header.offset, 0, &buffer.offset);
122
123 if (header.tag == EXTDATA_NONE) {
124 break;
125 }
126 if (header.tag >= EXTDATA_MAX) {
127 continue;
128 }
129 ssize_t position = vf->seek(vf, 0, SEEK_CUR);
130 if (vf->seek(vf, header.offset, SEEK_SET) < 0) {
131 return false;
132 }
133 struct mStateExtdataItem item = {
134 .data = malloc(header.size),
135 .size = header.size,
136 .clean = free
137 };
138 if (!item.data) {
139 continue;
140 }
141 if (vf->read(vf, item.data, header.size) != header.size) {
142 free(item.data);
143 continue;
144 }
145 mStateExtdataPut(extdata, header.tag, &item);
146 vf->seek(vf, position, SEEK_SET);
147 };
148 return true;
149}
150
151#ifdef USE_PNG
152static bool _savePNGState(struct mCore* core, struct VFile* vf, struct mStateExtdata* extdata) {
153 size_t stride;
154 const void* pixels = 0;
155
156 core->getPixels(core, &pixels, &stride);
157 if (!pixels) {
158 return false;
159 }
160
161 size_t stateSize = core->stateSize(core);
162 void* state = anonymousMemoryMap(stateSize);
163 if (!state || !core->saveState(core, state)) {
164 return false;
165 }
166
167 uLongf len = compressBound(stateSize);
168 void* buffer = malloc(len);
169 if (!buffer) {
170 mappedMemoryFree(state, stateSize);
171 return false;
172 }
173 compress(buffer, &len, (const Bytef*) state, stateSize);
174 mappedMemoryFree(state, stateSize);
175
176 unsigned width, height;
177 core->desiredVideoDimensions(core, &width, &height);
178 png_structp png = PNGWriteOpen(vf);
179 png_infop info = PNGWriteHeader(png, width, height);
180 if (!png || !info) {
181 PNGWriteClose(png, info);
182 free(buffer);
183 return false;
184 }
185 PNGWritePixels(png, width, height, stride, pixels);
186 PNGWriteCustomChunk(png, "gbAs", len, buffer);
187 if (extdata) {
188 uint32_t i;
189 for (i = 1; i < EXTDATA_MAX; ++i) {
190 if (!extdata->data[i].data) {
191 continue;
192 }
193 uLongf len = compressBound(extdata->data[i].size) + sizeof(uint32_t) * 2;
194 uint32_t* data = malloc(len);
195 if (!data) {
196 continue;
197 }
198 STORE_32LE(i, 0, data);
199 STORE_32LE(extdata->data[i].size, sizeof(uint32_t), data);
200 compress((Bytef*) (data + 2), &len, extdata->data[i].data, extdata->data[i].size);
201 PNGWriteCustomChunk(png, "gbAx", len + sizeof(uint32_t) * 2, data);
202 free(data);
203 }
204 }
205 PNGWriteClose(png, info);
206 free(buffer);
207 return true;
208}
209
210static int _loadPNGChunkHandler(png_structp png, png_unknown_chunkp chunk) {
211 struct mBundledState* bundle = png_get_user_chunk_ptr(png);
212 if (!bundle) {
213 return 0;
214 }
215 if (!strcmp((const char*) chunk->name, "gbAs")) {
216 void* state = bundle->state;
217 if (!state) {
218 return 0;
219 }
220 uLongf len = bundle->stateSize;
221 uncompress((Bytef*) state, &len, chunk->data, chunk->size);
222 return 1;
223 }
224 if (!strcmp((const char*) chunk->name, "gbAx")) {
225 struct mStateExtdata* extdata = bundle->extdata;
226 if (!extdata) {
227 return 0;
228 }
229 struct mStateExtdataItem item;
230 if (chunk->size < sizeof(uint32_t) * 2) {
231 return 0;
232 }
233 uint32_t tag;
234 LOAD_32LE(tag, 0, chunk->data);
235 LOAD_32LE(item.size, sizeof(uint32_t), chunk->data);
236 uLongf len = item.size;
237 if (item.size < 0 || tag == EXTDATA_NONE || tag >= EXTDATA_MAX) {
238 return 0;
239 }
240 item.data = malloc(item.size);
241 item.clean = free;
242 if (!item.data) {
243 return 0;
244 }
245 const uint8_t* data = chunk->data;
246 data += sizeof(uint32_t) * 2;
247 uncompress((Bytef*) item.data, &len, data, chunk->size);
248 item.size = len;
249 mStateExtdataPut(extdata, tag, &item);
250 return 1;
251 }
252 return 0;
253}
254
255static void* _loadPNGState(struct mCore* core, struct VFile* vf, struct mStateExtdata* extdata) {
256 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
257 png_infop info = png_create_info_struct(png);
258 png_infop end = png_create_info_struct(png);
259 if (!png || !info || !end) {
260 PNGReadClose(png, info, end);
261 return false;
262 }
263 unsigned width, height;
264 core->desiredVideoDimensions(core, &width, &height);
265 uint32_t* pixels = malloc(width * height * 4);
266 if (!pixels) {
267 PNGReadClose(png, info, end);
268 return false;
269 }
270
271 size_t stateSize = core->stateSize(core);
272 void* state = anonymousMemoryMap(stateSize);
273 struct mBundledState bundle = {
274 .stateSize = stateSize,
275 .state = state,
276 .extdata = extdata
277 };
278
279 PNGInstallChunkHandler(png, &bundle, _loadPNGChunkHandler, "gbAs gbAx");
280 bool success = PNGReadHeader(png, info);
281 success = success && PNGReadPixels(png, info, pixels, width, height, width);
282 success = success && PNGReadFooter(png, end);
283 PNGReadClose(png, info, end);
284
285 if (success) {
286 struct mStateExtdataItem item = {
287 .size = width * height * 4,
288 .data = pixels,
289 .clean = free
290 };
291 mStateExtdataPut(extdata, EXTDATA_SCREENSHOT, &item);
292 } else {
293 free(pixels);
294 mappedMemoryFree(state, stateSize);
295 return 0;
296 }
297 return state;
298}
299#endif
300
301bool mCoreSaveStateNamed(struct mCore* core, struct VFile* vf, int flags) {
302 struct mStateExtdata extdata;
303 mStateExtdataInit(&extdata);
304 size_t stateSize = core->stateSize(core);
305
306 if (flags & SAVESTATE_METADATA) {
307 uint64_t creationUsec;
308#ifndef _MSC_VER
309 struct timeval tv;
310 if (!gettimeofday(&tv, 0)) {
311 uint64_t usec = tv.tv_usec;
312 usec += tv.tv_sec * 1000000LL;
313 STORE_64LE(usec, 0, &creationUsec);
314 }
315#else
316 struct timespec ts;
317 if (timespec_get(&ts, TIME_UTC)) {
318 uint64_t usec = ts.tv_nsec / 1000;
319 usec += ts.tv_sec * 1000000LL;
320 STORE_64LE(usec, 0, &creationUsec);
321 }
322#endif
323 else {
324 creationUsec = 0;
325 }
326
327 struct mStateExtdataItem item = {
328 .size = sizeof(creationUsec),
329 .data = &creationUsec,
330 .clean = NULL
331 };
332 mStateExtdataPut(&extdata, EXTDATA_META_TIME, &item);
333 }
334
335 if (flags & SAVESTATE_SAVEDATA) {
336 void* sram = NULL;
337 size_t size = core->savedataClone(core, &sram);
338 if (size) {
339 struct mStateExtdataItem item = {
340 .size = size,
341 .data = sram,
342 .clean = free
343 };
344 mStateExtdataPut(&extdata, EXTDATA_SAVEDATA, &item);
345 }
346 }
347 struct VFile* cheatVf = 0;
348 struct mCheatDevice* device;
349 if (flags & SAVESTATE_CHEATS && (device = core->cheatDevice(core))) {
350 cheatVf = VFileMemChunk(0, 0);
351 if (cheatVf) {
352 mCheatSaveFile(device, cheatVf);
353 struct mStateExtdataItem item = {
354 .size = cheatVf->size(cheatVf),
355 .data = cheatVf->map(cheatVf, cheatVf->size(cheatVf), MAP_READ),
356 .clean = 0
357 };
358 mStateExtdataPut(&extdata, EXTDATA_CHEATS, &item);
359 }
360 }
361 if (flags & SAVESTATE_RTC) {
362 mLOG(SAVESTATE, INFO, "Loading RTC");
363 struct mStateExtdataItem item;
364 if (core->rtc.d.serialize) {
365 core->rtc.d.serialize(&core->rtc.d, &item);
366 mStateExtdataPut(&extdata, EXTDATA_RTC, &item);
367 }
368 }
369#ifdef USE_PNG
370 if (!(flags & SAVESTATE_SCREENSHOT)) {
371#else
372 UNUSED(flags);
373#endif
374 vf->truncate(vf, stateSize);
375 void* state = vf->map(vf, stateSize, MAP_WRITE);
376 if (!state || !core->saveState(core, state)) {
377 mStateExtdataDeinit(&extdata);
378 if (cheatVf) {
379 cheatVf->close(cheatVf);
380 }
381 return false;
382 }
383 vf->unmap(vf, state, stateSize);
384 vf->seek(vf, stateSize, SEEK_SET);
385 mStateExtdataSerialize(&extdata, vf);
386 mStateExtdataDeinit(&extdata);
387 if (cheatVf) {
388 cheatVf->close(cheatVf);
389 }
390 return true;
391#ifdef USE_PNG
392 }
393 else {
394 bool success = _savePNGState(core, vf, &extdata);
395 mStateExtdataDeinit(&extdata);
396 return success;
397 }
398#endif
399 mStateExtdataDeinit(&extdata);
400 return false;
401}
402
403void* mCoreExtractState(struct mCore* core, struct VFile* vf, struct mStateExtdata* extdata) {
404#ifdef USE_PNG
405 if (isPNG(vf)) {
406 return _loadPNGState(core, vf, extdata);
407 }
408#endif
409 ssize_t stateSize = core->stateSize(core);
410 void* state = anonymousMemoryMap(stateSize);
411 vf->seek(vf, 0, SEEK_SET);
412 if (vf->read(vf, state, stateSize) != stateSize) {
413 mappedMemoryFree(state, stateSize);
414 return 0;
415 }
416 if (extdata) {
417 mStateExtdataDeserialize(extdata, vf);
418 }
419 return state;
420}
421
422bool mCoreLoadStateNamed(struct mCore* core, struct VFile* vf, int flags) {
423 struct mStateExtdata extdata;
424 mStateExtdataInit(&extdata);
425 void* state = mCoreExtractState(core, vf, &extdata);
426 if (!state) {
427 return false;
428 }
429 bool success = core->loadState(core, state);
430 mappedMemoryFree(state, core->stateSize(core));
431
432 unsigned width, height;
433 core->desiredVideoDimensions(core, &width, &height);
434
435 struct mStateExtdataItem item;
436 if (flags & SAVESTATE_SCREENSHOT && mStateExtdataGet(&extdata, EXTDATA_SCREENSHOT, &item)) {
437 mLOG(SAVESTATE, INFO, "Loading screenshot");
438 if (item.size >= (int) (width * height) * 4) {
439 core->putPixels(core, item.data, width);
440 } else {
441 mLOG(SAVESTATE, WARN, "Savestate includes invalid screenshot");
442 }
443 }
444 if (mStateExtdataGet(&extdata, EXTDATA_SAVEDATA, &item)) {
445 mLOG(SAVESTATE, INFO, "Loading savedata");
446 if (item.data) {
447 core->savedataRestore(core, item.data, item.size, flags & SAVESTATE_SAVEDATA);
448 }
449 }
450 struct mCheatDevice* device;
451 if (flags & SAVESTATE_CHEATS && (device = core->cheatDevice(core)) && mStateExtdataGet(&extdata, EXTDATA_CHEATS, &item)) {
452 mLOG(SAVESTATE, INFO, "Loading cheats");
453 if (item.size) {
454 struct VFile* svf = VFileFromMemory(item.data, item.size);
455 if (svf) {
456 mCheatDeviceClear(device);
457 mCheatParseFile(device, svf);
458 svf->close(svf);
459 }
460 }
461 }
462 if (flags & SAVESTATE_RTC && mStateExtdataGet(&extdata, EXTDATA_RTC, &item)) {
463 mLOG(SAVESTATE, INFO, "Loading RTC");
464 if (core->rtc.d.deserialize) {
465 core->rtc.d.deserialize(&core->rtc.d, &item);
466 }
467 }
468 mStateExtdataDeinit(&extdata);
469 return success;
470}
471