all repos — mgba @ 5caf256631945a8afd679b5ecb742ec50958a2dd

mGBA Game Boy Advance Emulator

src/platform/test/perf-main.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 <mgba/core/blip_buf.h>
  7#include <mgba/core/cheats.h>
  8#include <mgba/core/config.h>
  9#include <mgba/core/core.h>
 10#include <mgba/core/serialize.h>
 11#include <mgba/gb/core.h>
 12#include <mgba/gba/core.h>
 13
 14#include <mgba/feature/commandline.h>
 15#include <mgba-util/socket.h>
 16#include <mgba-util/string.h>
 17#include <mgba-util/vfs.h>
 18
 19#ifdef _3DS
 20#include <3ds.h>
 21#endif
 22#ifdef __SWITCH__
 23#include <switch.h>
 24#endif
 25#ifdef GEKKO
 26#define asm __asm__
 27#include <fat.h>
 28#include <gccore.h>
 29#ifdef FIXED_ROM_BUFFER
 30uint32_t* romBuffer;
 31size_t romBufferSize;
 32#endif
 33#endif
 34
 35#include <errno.h>
 36#include <fcntl.h>
 37#include <signal.h>
 38#include <inttypes.h>
 39#include <sys/time.h>
 40
 41#define PERF_OPTIONS "DF:L:NPS:T"
 42#define PERF_USAGE \
 43	"\nBenchmark options:\n" \
 44	"  -F FRAMES        Run for the specified number of FRAMES before exiting\n" \
 45	"  -N               Disable video rendering entirely\n" \
 46	"  -T               Use threaded video rendering\n" \
 47	"  -P               CSV output, useful for parsing\n" \
 48	"  -S SEC           Run for SEC in-game seconds before exiting\n" \
 49	"  -L FILE          Load a savestate when starting the test\n" \
 50	"  -D               Act as a server"
 51
 52struct PerfOpts {
 53	bool noVideo;
 54	bool threadedVideo;
 55	bool csv;
 56	unsigned duration;
 57	unsigned frames;
 58	char* savestate;
 59	bool server;
 60};
 61
 62#ifdef __SWITCH__
 63TimeType __nx_time_type = TimeType_LocalSystemClock;
 64#endif
 65
 66static void _mPerfRunloop(struct mCore* context, int* frames, bool quiet);
 67static void _mPerfShutdown(int signal);
 68static bool _parsePerfOpts(struct mSubParser* parser, int option, const char* arg);
 69static void _log(struct mLogger*, int, enum mLogLevel, const char*, va_list);
 70static bool _mPerfRunCore(const char* fname, const struct mArguments*, const struct PerfOpts*);
 71static bool _mPerfRunServer(const struct mArguments*, const struct PerfOpts*);
 72
 73static bool _dispatchExiting = false;
 74static struct VFile* _savestate = 0;
 75static void* _outputBuffer = NULL;
 76static Socket _socket = INVALID_SOCKET;
 77static Socket _server = INVALID_SOCKET;
 78
 79int main(int argc, char** argv) {
 80#ifdef _3DS
 81	UNUSED(_mPerfShutdown);
 82    gfxInitDefault();
 83    osSetSpeedupEnable(true);
 84	consoleInit(GFX_BOTTOM, NULL);
 85#elif defined(__SWITCH__)
 86	UNUSED(_mPerfShutdown);
 87	consoleInit(NULL);
 88#elif defined(GEKKO)
 89	VIDEO_Init();
 90	VIDEO_SetBlack(true);
 91	VIDEO_Flush();
 92	VIDEO_WaitVSync();
 93
 94	GXRModeObj* vmode = VIDEO_GetPreferredMode(0);
 95	void* xfb = MEM_K0_TO_K1(SYS_AllocateFramebuffer(vmode));
 96	console_init(xfb, 20, 20, vmode->fbWidth, vmode->xfbHeight, vmode->fbWidth * VI_DISPLAY_PIX_SZ);
 97
 98	VIDEO_Configure(vmode);
 99	VIDEO_SetNextFramebuffer(xfb);
100	VIDEO_SetBlack(false);
101	VIDEO_Flush();
102	VIDEO_WaitVSync();
103	VIDEO_WaitVSync();
104	fatInitDefault();
105
106#ifdef FIXED_ROM_BUFFER
107	romBufferSize = 0x02000000;
108	romBuffer = SYS_GetArena2Lo();
109	SYS_SetArena2Lo((void*)((intptr_t) romBuffer + romBufferSize));
110#endif
111#else
112	signal(SIGINT, _mPerfShutdown);
113#endif
114	int didFail = 0;
115
116	struct mLogger logger = { .log = _log };
117	mLogSetDefaultLogger(&logger);
118
119	struct PerfOpts perfOpts = { false, false, false, 0, 0, 0, false };
120	struct mSubParser subparser = {
121		.usage = PERF_USAGE,
122		.parse = _parsePerfOpts,
123		.extraOptions = PERF_OPTIONS,
124		.opts = &perfOpts
125	};
126
127	struct mArguments args = {};
128	bool parsed = parseArguments(&args, argc, argv, &subparser);
129	if (!args.fname && !perfOpts.server) {
130		parsed = false;
131	}
132	if (!parsed || args.showHelp) {
133		usage(argv[0], PERF_USAGE);
134		didFail = !parsed;
135		goto cleanup;
136	}
137
138	if (args.showVersion) {
139		version(argv[0]);
140		goto cleanup;
141	}
142
143	if (perfOpts.savestate) {
144		_savestate = VFileOpen(perfOpts.savestate, O_RDONLY);
145		free(perfOpts.savestate);
146	}
147
148	_outputBuffer = malloc(256 * 256 * 4);
149	if (perfOpts.csv) {
150		puts("game_code,frames,duration,renderer");
151#ifdef __SWITCH__
152		consoleUpdate(NULL);
153#elif defined(GEKKO)
154		VIDEO_WaitVSync();
155#endif
156	}
157	if (perfOpts.server) {
158		didFail = !_mPerfRunServer(&args, &perfOpts);
159	} else {
160		didFail = !_mPerfRunCore(args.fname, &args, &perfOpts);
161	}
162	free(_outputBuffer);
163
164	if (_savestate) {
165		_savestate->close(_savestate);
166	}
167	cleanup:
168	freeArguments(&args);
169
170#ifdef _3DS
171	gfxExit();
172	acExit();
173#elif defined(__SWITCH__)
174	consoleExit(NULL);
175#elif defined(GEKKO)
176	VIDEO_SetBlack(true);
177	VIDEO_Flush();
178	VIDEO_WaitVSync();
179	VIDEO_WaitVSync();
180#endif
181
182	return didFail;
183}
184
185bool _mPerfRunCore(const char* fname, const struct mArguments* args, const struct PerfOpts* perfOpts) {
186	struct mCore* core = mCoreFind(fname);
187	if (!core) {
188		return false;
189	}
190
191	// TODO: Put back debugger
192	char gameCode[9] = { 0 };
193
194	core->init(core);
195	if (!perfOpts->noVideo) {
196		core->setVideoBuffer(core, _outputBuffer, 256);
197	}
198	mCoreLoadFile(core, fname);
199	mCoreConfigInit(&core->config, "perf");
200	mCoreConfigLoad(&core->config);
201
202	if (perfOpts->threadedVideo) {
203		mCoreConfigSetOverrideIntValue(&core->config, "threadedVideo", 1);
204	} else {
205		mCoreConfigSetOverrideIntValue(&core->config, "threadedVideo", 0);
206	}
207
208	struct mCoreOptions opts = {};
209	mCoreConfigMap(&core->config, &opts);
210	opts.audioSync = false;
211	opts.videoSync = false;
212	applyArguments(args, NULL, &core->config);
213	mCoreConfigLoadDefaults(&core->config, &opts);
214	mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "detect");
215	mCoreLoadConfig(core);
216
217	core->reset(core);
218	if (_savestate) {
219		mCoreLoadStateNamed(core, _savestate, 0);
220	}
221
222	core->getGameCode(core, gameCode);
223
224	int frames = perfOpts->frames;
225	if (!frames) {
226		frames = perfOpts->duration * 60;
227	}
228	struct timeval tv;
229	gettimeofday(&tv, 0);
230	uint64_t start = 1000000LL * tv.tv_sec + tv.tv_usec;
231	_mPerfRunloop(core, &frames, perfOpts->csv);
232	gettimeofday(&tv, 0);
233	uint64_t end = 1000000LL * tv.tv_sec + tv.tv_usec;
234	uint64_t duration = end - start;
235
236	mCoreConfigFreeOpts(&opts);
237	mCoreConfigDeinit(&core->config);
238	core->deinit(core);
239
240	float scaledFrames = frames * 1000000.f;
241	if (perfOpts->csv) {
242		char buffer[256];
243		const char* rendererName;
244		if (perfOpts->noVideo) {
245			rendererName = "none";
246		} else if (perfOpts->threadedVideo) {
247			rendererName = "threaded-software";
248		} else {
249			rendererName = "software";
250		}
251		snprintf(buffer, sizeof(buffer), "%s,%i,%" PRIu64 ",%s\n", gameCode, frames, duration, rendererName);
252		printf("%s", buffer);
253		if (_socket != INVALID_SOCKET) {
254			SocketSend(_socket, buffer, strlen(buffer));
255		}
256	} else {
257		printf("%u frames in %" PRIu64 " microseconds: %g fps (%gx)\n", frames, duration, scaledFrames / duration, scaledFrames / (duration * 60.f));
258	}
259#ifdef __SWITCH__
260	consoleUpdate(NULL);
261#endif
262
263	return true;
264}
265
266static void _mPerfRunloop(struct mCore* core, int* frames, bool quiet) {
267	struct timeval lastEcho;
268	gettimeofday(&lastEcho, 0);
269	int duration = *frames;
270	*frames = 0;
271	int lastFrames = 0;
272	while (!_dispatchExiting) {
273		core->runFrame(core);
274		++*frames;
275		++lastFrames;
276		if (!quiet) {
277			struct timeval currentTime;
278			long timeDiff;
279			gettimeofday(&currentTime, 0);
280			timeDiff = currentTime.tv_sec - lastEcho.tv_sec;
281			timeDiff *= 1000;
282			timeDiff += (currentTime.tv_usec - lastEcho.tv_usec) / 1000;
283			if (timeDiff >= 1000) {
284				printf("\033[2K\rCurrent FPS: %g (%gx)", lastFrames / (timeDiff / 1000.0f), lastFrames / (float) (60 * (timeDiff / 1000.0f)));
285				fflush(stdout);
286#ifdef __SWITCH__
287				consoleUpdate(NULL);
288#endif
289				lastEcho = currentTime;
290				lastFrames = 0;
291			}
292		}
293		if (duration > 0 && *frames == duration) {
294			break;
295		}
296	}
297	if (!quiet) {
298		printf("\033[2K\r");
299	}
300}
301
302static bool _mPerfRunServer(const struct mArguments* args, const struct PerfOpts* perfOpts) {
303	SocketSubsystemInit();
304	_server = SocketOpenTCP(7216, NULL);
305	if (SOCKET_FAILED(_server)) {
306		SocketSubsystemDeinit();
307		return false;
308	}
309	if (SOCKET_FAILED(SocketListen(_server, 0))) {
310		SocketClose(_server);
311		SocketSubsystemDeinit();
312		return false;
313	}
314	_socket = SocketAccept(_server, NULL);
315	if (SOCKET_FAILED(_socket)) {
316		SocketClose(_server);
317		SocketSubsystemDeinit();
318		return false;
319	}
320	if (perfOpts->csv) {
321		const char* header = "game_code,frames,duration,renderer\n";
322		SocketSend(_socket, header, strlen(header));
323	}
324	char path[PATH_MAX];
325	memset(path, 0, sizeof(path));
326	ssize_t i;
327	while ((i = SocketRecv(_socket, path, sizeof(path) - 1)) > 0) {
328		path[i] = '\0';
329		char* nl = strchr(path, '\n');
330		if (nl == path) {
331			break;
332		}
333		if (nl) {
334			nl[0] = '\0';
335		}
336		if (!_mPerfRunCore(path, args, perfOpts)) {
337			break;
338		}
339		memset(path, 0, sizeof(path));
340	}
341	SocketClose(_socket);
342	SocketClose(_server);
343	SocketSubsystemDeinit();
344	return true;
345}
346
347static void _mPerfShutdown(int signal) {
348	UNUSED(signal);
349	_dispatchExiting = true;
350	SocketClose(_socket);
351	SocketClose(_server);
352}
353
354static bool _parsePerfOpts(struct mSubParser* parser, int option, const char* arg) {
355	struct PerfOpts* opts = parser->opts;
356	errno = 0;
357	switch (option) {
358	case 'D':
359		opts->server = true;
360		return true;
361	case 'F':
362		opts->frames = strtoul(arg, 0, 10);
363		return !errno;
364	case 'N':
365		opts->noVideo = true;
366		return true;
367	case 'P':
368		opts->csv = true;
369		return true;
370	case 'S':
371		opts->duration = strtoul(arg, 0, 10);
372		return !errno;
373	case 'T':
374		opts->threadedVideo = true;
375		return true;
376	case 'L':
377		opts->savestate = strdup(arg);
378		return true;
379	default:
380		return false;
381	}
382}
383
384static void _log(struct mLogger* log, int category, enum mLogLevel level, const char* format, va_list args) {
385	UNUSED(log);
386	UNUSED(category);
387	UNUSED(level);
388	UNUSED(format);
389	UNUSED(args);
390}