all repos — mgba @ d243e93c15133bc25969dc35d5cd0929eccfb46b

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