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