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