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