Debian Codegraph @

android/app/jni/src/main.cpp

raw
1 /**
2 * Furnace Tracker - multi-system chiptune tracker
3 * Copyright (C) 2021-2025 tildearrow and contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include <stdio.h>
21 #include <stdint.h>
22 #include "pch.h"
23 #ifdef HAVE_SDL2
24 #include "SDL_events.h"
25 #endif
26 #include "ta-log.h"
27 #include "fileutils.h"
28 #include "engine/engine.h"
29
30 #ifdef _WIN32
31 #include <windows.h>
32 #include <combaseapi.h>
33 #include <shellapi.h>
34 #if defined(HAVE_SDL2) && !defined(SUPPORT_XP)
35 #include <versionhelpers.h>
36 #endif
37 #include "utfutils.h"
38 #include "gui/shellScalingStub.h"
39
40 typedef HRESULT (WINAPI *SPDA)(PROCESS_DPI_AWARENESS);
41 #else
42 #include <signal.h>
43 #include <unistd.h>
44
45 struct sigaction termsa;
46 #endif
47
48 #ifdef SUPPORT_XP
49 #define TUT_INTRO_PLAYED true
50 #else
51 #define TUT_INTRO_PLAYED false
52 #endif
53
54 #ifdef HAVE_LOCALE
55 #ifdef HAVE_MOMO
56 #define TA_BINDTEXTDOMAIN momo_bindtextdomain
57 #define TA_TEXTDOMAIN momo_textdomain
58 #else
59 #define TA_BINDTEXTDOMAIN bindtextdomain
60 #define TA_TEXTDOMAIN textdomain
61 #endif
62
63 #ifdef HAVE_SETLOCALE
64 #include <locale.h>
65 #endif
66
67 #ifndef LC_CTYPE
68 #define LC_CTYPE 0
69 #endif
70 #ifndef LC_MESSAGES
71 #define LC_MESSAGES 1
72 #endif
73 #endif
74
75 #include "cli/cli.h"
76
77 #ifdef HAVE_GUI
78 #include "gui/gui.h"
79 #endif
80
81 DivEngine e;
82
83 #ifdef HAVE_GUI
84 FurnaceGUI g;
85 #endif
86
87 FurnaceCLI cli;
88
89 String outName;
90 String vgmOutName;
91 String cmdOutName;
92 String romOutName;
93 String txtOutName;
94 int benchMode=0;
95 int subsong=-1;
96 DivCSOptions csExportOptions;
97 DivAudioExportOptions exportOptions;
98 DivConfig romExportConfig;
99
100 #ifdef HAVE_GUI
101 bool consoleMode=false;
102 #else
103 bool consoleMode=true;
104 #endif
105
106 bool consoleNoStatus=false;
107 bool consoleNoControls=false;
108
109 bool displayEngineFailError=false;
110 bool displayLocaleFailError=false;
111 bool vgmOutDirect=false;
112
113 bool safeMode=false;
114 bool safeModeWithAudio=false;
115
116 bool infoMode=false;
117
118 bool noReportError=false;
119
120 std::vector<TAParam> params;
121
122 #ifdef HAVE_LOCALE
123 char reqLocaleCopy[64];
124 char localeDir[4096];
125
126 const char* localeDirs[]={
127 #ifdef __APPLE__
128 "../Resources/locale",
129 #endif
130 "locale",
131 ".." DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale",
132 ".." DIR_SEPARATOR_STR "po" DIR_SEPARATOR_STR "locale",
133 #ifdef LOCALE_DIR
134 LOCALE_DIR,
135 #endif
136 NULL
137 };
138 #endif
139
140 bool getExePath(char* argv0, char* exePath, size_t maxSize) {
141 if (argv0==NULL) return false;
142 #ifdef _WIN32
143 wchar_t exePathW[4096];
144 WString argv0W=utf8To16(argv0);
145 if (GetFullPathNameW(argv0W.c_str(),4095,exePathW,NULL)==0) return false;
146 String exePathS=utf16To8(exePathW);
147 strncpy(exePath,exePathS.c_str(),maxSize);
148 #else
149 if (realpath(argv0,exePath)==NULL) return false;
150 #endif
151 char* lastChar=strrchr(exePath,DIR_SEPARATOR);
152 if (lastChar==NULL) return false;
153 *lastChar=0;
154 return true;
155 }
156
157 TAParamResult pHelp(String) {
158 printf("usage: furnace [params] [filename]\n"
159 "you may specify the following parameters:\n");
160 for (auto& i: params) {
161 if (i.value) {
162 printf(" -%s %s: %s\n",i.name.c_str(),i.valName.c_str(),i.desc.c_str());
163 } else {
164 printf(" -%s: %s\n",i.name.c_str(),i.desc.c_str());
165 }
166 }
167 return TA_PARAM_QUIT;
168 }
169
170 TAParamResult pAudio(String val) {
171 if (outName!="") {
172 logE("can't use -audio and -output at the same time.");
173 return TA_PARAM_ERROR;
174 }
175 if (val=="jack") {
176 e.setAudio(DIV_AUDIO_JACK);
177 } else if (val=="sdl") {
178 e.setAudio(DIV_AUDIO_SDL);
179 } else if (val=="portaudio") {
180 e.setAudio(DIV_AUDIO_PORTAUDIO);
181 } else if (val=="pipe") {
182 e.setAudio(DIV_AUDIO_PIPE);
183 changeLogOutput(stderr);
184 } else {
185 logE("invalid value for audio engine! valid values are: jack, sdl, portaudio, pipe.");
186 return TA_PARAM_ERROR;
187 }
188 return TA_PARAM_SUCCESS;
189 }
190
191 TAParamResult pView(String val) {
192 if (val=="pattern") {
193 e.setView(DIV_STATUS_PATTERN);
194 } else if (val=="commands") {
195 e.setView(DIV_STATUS_COMMANDS);
196 } else if (val=="nothing") {
197 e.setView(DIV_STATUS_NOTHING);
198 } else {
199 logE("invalid value for view type! valid values are: pattern, commands, nothing.");
200 return TA_PARAM_ERROR;
201 }
202 return TA_PARAM_SUCCESS;
203 }
204
205 TAParamResult pConsole(String val) {
206 consoleMode=true;
207 return TA_PARAM_SUCCESS;
208 }
209
210 TAParamResult pQuiet(String val) {
211 noReportError=true;
212 return TA_PARAM_SUCCESS;
213 }
214
215 TAParamResult pNoStatus(String val) {
216 consoleNoStatus=true;
217 return TA_PARAM_SUCCESS;
218 }
219
220 TAParamResult pNoControls(String val) {
221 consoleNoControls=true;
222 return TA_PARAM_SUCCESS;
223 }
224
225 TAParamResult pSafeMode(String val) {
226 #ifdef HAVE_GUI
227 safeMode=true;
228 return TA_PARAM_SUCCESS;
229 #else
230 logE("Furnace was compiled without the GUI. safe mode is pointless.");
231 return TA_PARAM_ERROR;
232 #endif
233 }
234
235 TAParamResult pSafeModeAudio(String val) {
236 #ifdef HAVE_GUI
237 safeMode=true;
238 safeModeWithAudio=true;
239 return TA_PARAM_SUCCESS;
240 #else
241 logE("Furnace was compiled without the GUI. safe mode is pointless.");
242 return TA_PARAM_ERROR;
243 #endif
244 }
245
246 TAParamResult pDirect(String val) {
247 vgmOutDirect=true;
248 return TA_PARAM_SUCCESS;
249 }
250
251 TAParamResult pInfo(String val) {
252 infoMode=true;
253 return TA_PARAM_SUCCESS;
254 }
255
256 TAParamResult pLogLevel(String val) {
257 if (val=="trace") {
258 logLevel=LOGLEVEL_TRACE;
259 } else if (val=="debug") {
260 logLevel=LOGLEVEL_DEBUG;
261 } else if (val=="info") {
262 logLevel=LOGLEVEL_INFO;
263 } else if (val=="warning") {
264 logLevel=LOGLEVEL_WARN;
265 } else if (val=="error") {
266 logLevel=LOGLEVEL_ERROR;
267 } else {
268 logE("invalid value for loglevel! valid values are: trace, debug, info, warning, error.");
269 return TA_PARAM_ERROR;
270 }
271 return TA_PARAM_SUCCESS;
272 }
273
274 TAParamResult pVersion(String) {
275 printf("Furnace version " DIV_VERSION ".\n\n");
276 printf("copyright (C) 2021-2025 tildearrow and contributors.\n");
277 printf("licensed under the GNU General Public License version 2 or later\n");
278 printf("<https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.\n\n");
279 printf("this is free software with ABSOLUTELY NO WARRANTY.\n");
280 printf("pass the -warranty parameter for more information.\n\n");
281 printf("DISCLAIMER: this program is not affiliated with Delek in any form.\n");
282 printf("\n");
283 printf("furnace is powered by:\n");
284 printf("- libsndfile by Erik de Castro Lopo and rest of libsndfile team (LGPLv2.1)\n");
285 printf("- SDL2 by Sam Lantinga (zlib license)\n");
286 printf("- zlib by Jean-loup Gailly and Mark Adler (zlib license)\n");
287 printf("- PortAudio (PortAudio license)\n");
288 printf("- Weak-JACK by x42 (GPLv2)\n");
289 printf("- RtMidi by Gary P. Scavone (RtMidi license)\n");
290 printf("- backward-cpp by Google (MIT)\n");
291 printf("- Dear ImGui by Omar Cornut (MIT)\n");
292 #ifdef HAVE_FREETYPE
293 printf("- FreeType (GPLv2)\n");
294 #endif
295 printf("- Portable File Dialogs by Sam Hocevar (WTFPL)\n");
296 printf("- Native File Dialog (modified version) by Frogtoss Games (zlib license)\n");
297 printf("- FFTW by Matteo Frigo and Steven G. Johnson (GPLv2)\n");
298 printf("- Nuked-OPM by nukeykt (LGPLv2.1)\n");
299 printf("- Nuked-OPN2 by nukeykt (LGPLv2.1)\n");
300 printf("- Nuked-OPL3 by nukeykt (LGPLv2.1)\n");
301 printf("- Nuked-OPLL by nukeykt (GPLv2)\n");
302 printf("- Nuked-PSG (modified version) by nukeykt (GPLv2)\n");
303 printf("- YM3812-LLE by nukeykt (GPLv2)\n");
304 printf("- YMF262-LLE by nukeykt (GPLv2)\n");
305 printf("- YMF276-LLE by nukeykt (GPLv2)\n");
306 printf("- YM2608-LLE by nukeykt (GPLv2)\n");
307 printf("- ESFMu (modified version) by Kagamiin~ (LGPLv2.1)\n");
308 printf("- ymfm by Aaron Giles (BSD 3-clause)\n");
309 printf("- emu2413 by Digital Sound Antiques (MIT)\n");
310 printf("- adpcm by superctr (public domain)\n");
311 printf("- adpcm-xq by David Bryant (BSD 3-clause)\n");
312 printf("- MAME SN76496 emulation core by Nicola Salmoria (BSD 3-clause)\n");
313 printf("- MAME AY-3-8910 emulation core by Couriersud (BSD 3-clause)\n");
314 printf("- MAME SAA1099 emulation core by Juergen Buchmueller and Manuel Abadia (BSD 3-clause)\n");
315 printf("- MAME Namco WSG by Nicola Salmoria and Aaron Giles (BSD 3-clause)\n");
316 printf("- MAME RF5C68 core by Olivier Galibert and Aaron Giles (BSD 3-clause)\n");
317 printf("- MAME MSM5232 core by Jarek Burczynski and Hiromitsu Shioya (GPLv2)\n");
318 printf("- MAME MSM6258 core by Barry Rodewald (BSD 3-clause)\n");
319 printf("- MAME YMZ280B core by Aaron Giles (BSD 3-clause)\n");
320 printf("- MAME GA20 core (modified version) by Acho A. Tang, R. Belmont and Valley Bell (BSD 3-clause)\n");
321 printf("- MAME SegaPCM core by Hiromitsu Shioya and Olivier Galibert (BSD 3-clause)\n");
322 printf("- MAME µPD1771C-017 HLE core by David Viens (BSD 3-clause)\n");
323 printf("- QSound core by superctr (BSD 3-clause)\n");
324 printf("- VICE VIC-20 by Rami Rasanen and viznut (GPLv2)\n");
325 printf("- VICE TED by Andreas Boose, Tibor Biczo and Marco van den Heuvel (GPLv2)\n");
326 printf("- VERA core by Frank van den Hoef (BSD 2-clause)\n");
327 printf("- SAASound by Dave Hooper and Simon Owen (BSD 3-clause)\n");
328 printf("- SameBoy by Lior Halphon (MIT)\n");
329 printf("- Mednafen PCE, WonderSwan and Virtual Boy by Mednafen Team (GPLv2)\n");
330 printf("- Mednafen T6W28 (modified version) by Blargg (GPLv2)\n");
331 printf("- WonderSwan new core by asiekierka (zlib license)\n");
332 printf("- SNES DSP core by Blargg (LGPLv2.1)\n");
333 printf("- puNES (modified version) by FHorse (GPLv2)\n");
334 printf("- NSFPlay by Brad Smith and Brezza (unknown open-source license)\n");
335 printf("- reSID by Dag Lem (GPLv2)\n");
336 printf("- reSIDfp by Dag Lem, Antti Lankila and Leandro Nini (GPLv2)\n");
337 printf("- dSID by DefleMask Team (based on jsSID by Hermit) (MIT)\n");
338 printf("- Stella by Stella Team (GPLv2)\n");
339 printf("- vgsound_emu (second version, modified version) by cam900 (zlib license)\n");
340 printf("- Impulse Tracker GUS volume table by Jeffrey Lim (BSD 3-clause)\n");
341 printf("- Schism Tracker IT sample decompression (GPLv2)\n");
342 printf("- Atari800 mzpokeysnd POKEY emulator by Michael Borisov (GPLv2)\n");
343 printf("- ASAP POKEY emulator by Piotr Fusik ported to C++ by laoo (GPLv2)\n");
344 printf("- SM8521 emulator (modified version) by cam900 (zlib license)\n");
345 printf("- D65010G031 emulator (modified version) by cam900 (zlib license)\n");
346 printf("- C140/C219 emulator (modified version) by cam900 (zlib license)\n");
347 printf("- PowerNoise emulator by scratchminer (MIT)\n");
348 printf("- ep128emu by Istvan Varga (GPLv2)\n");
349 printf("- NDS sound emulator by cam900 (zlib license)\n");
350 printf("- SID2 emulator by LTVA (GPLv2, modification of reSID emulator)\n");
351 printf("- SID3 emulator by LTVA (MIT)\n");
352 printf("- openMSX YMF278 emulator (modified version) by the openMSX developers (GPLv2)\n");
353 return TA_PARAM_QUIT;
354 }
355
356 TAParamResult pWarranty(String) {
357 printf("This program is free software; you can redistribute it and/or\n"
358 "modify it under the terms of the GNU General Public License\n"
359 "as published by the Free Software Foundation; either version 2\n"
360 "of the License, or (at your option) any later version.\n\n"
361
362 "This program is distributed in the hope that it will be useful,\n"
363 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
364 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
365 "GNU General Public License for more details.\n\n"
366
367 "You should have received a copy of the GNU General Public License\n"
368 "along with this program; if not, write to the Free Software\n"
369 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n");
370 return TA_PARAM_QUIT;
371 }
372
373 TAParamResult pLoops(String val) {
374 try {
375 int count=std::stoi(val);
376 if (count<0) {
377 exportOptions.loops=0;
378 } else {
379 exportOptions.loops=count;
380 }
381 } catch (std::exception& e) {
382 logE("loop count shall be a number.");
383 return TA_PARAM_ERROR;
384 }
385 return TA_PARAM_SUCCESS;
386 }
387
388 TAParamResult pSubSong(String val) {
389 try {
390 int v=std::stoi(val);
391 if (v<0) {
392 logE("sub-song shall be 0 or higher.");
393 return TA_PARAM_ERROR;
394 }
395 subsong=v;
396 } catch (std::exception& e) {
397 logE("sub-song shall be a number.");
398 return TA_PARAM_ERROR;
399 }
400 return TA_PARAM_SUCCESS;
401 }
402
403 TAParamResult pOutMode(String val) {
404 if (val=="one") {
405 exportOptions.mode=DIV_EXPORT_MODE_ONE;
406 } else if (val=="persys") {
407 exportOptions.mode=DIV_EXPORT_MODE_MANY_SYS;
408 } else if (val=="perchan") {
409 exportOptions.mode=DIV_EXPORT_MODE_MANY_CHAN;
410 } else {
411 logE("invalid value for outmode! valid values are: one, persys and perchan.");
412 return TA_PARAM_ERROR;
413 }
414 return TA_PARAM_SUCCESS;
415 }
416
417 TAParamResult pBenchmark(String val) {
418 if (val=="render") {
419 benchMode=1;
420 } else if (val=="seek") {
421 benchMode=2;
422 } else {
423 logE("invalid value for benchmark! valid values are: render and seek.");
424 return TA_PARAM_ERROR;
425 }
426 e.setAudio(DIV_AUDIO_DUMMY);
427 return TA_PARAM_SUCCESS;
428 }
429
430 TAParamResult pOutput(String val) {
431 outName=val;
432 e.setAudio(DIV_AUDIO_DUMMY);
433 return TA_PARAM_SUCCESS;
434 }
435
436 TAParamResult pVGMOut(String val) {
437 vgmOutName=val;
438 e.setAudio(DIV_AUDIO_DUMMY);
439 return TA_PARAM_SUCCESS;
440 }
441
442 TAParamResult pCmdOut(String val) {
443 cmdOutName=val;
444 e.setAudio(DIV_AUDIO_DUMMY);
445 return TA_PARAM_SUCCESS;
446 }
447
448 TAParamResult pROMOut(String val) {
449 romOutName=val;
450 e.setAudio(DIV_AUDIO_DUMMY);
451 return TA_PARAM_SUCCESS;
452 }
453
454 TAParamResult pROMConf(String val) {
455 size_t eqSplit=val.find_first_of('=');
456 if (eqSplit==String::npos) {
457 logE("invalid romconf parameter, must contain '=' as in: <key>=<value>");
458 return TA_PARAM_ERROR;
459 }
460 String key=val.substr(0,eqSplit);
461 String param=val.substr(eqSplit+1);
462 romExportConfig.set(key,param);
463 return TA_PARAM_SUCCESS;
464 }
465
466 TAParamResult pTxtOut(String val) {
467 txtOutName=val;
468 e.setAudio(DIV_AUDIO_DUMMY);
469 return TA_PARAM_SUCCESS;
470 }
471
472 bool needsValue(String param) {
473 for (size_t i=0; i<params.size(); i++) {
474 if (params[i].name==param) {
475 return params[i].value;
476 }
477 }
478 return false;
479 }
480
481 void initParams() {
482 params.push_back(TAParam("h","help",false,pHelp,"","display this help"));
483
484 params.push_back(TAParam("a","audio",true,pAudio,"jack|sdl|portaudio|pipe","set audio engine (SDL by default)"));
485 params.push_back(TAParam("o","output",true,pOutput,"<filename>","output audio to file"));
486 params.push_back(TAParam("O","vgmout",true,pVGMOut,"<filename>","output .vgm data"));
487 params.push_back(TAParam("D","direct",false,pDirect,"","set VGM export direct stream mode"));
488 params.push_back(TAParam("C","cmdout",true,pCmdOut,"<filename>","output command stream"));
489 params.push_back(TAParam("r","romout",true,pROMOut,"<filename|path>","export ROM file, or path for multi-file export"));
490 params.push_back(TAParam("R","romconf",true,pROMConf,"<key>=<value>","set configuration parameter for ROM export"));
491 params.push_back(TAParam("t","txtout",true,pTxtOut,"<filename>","export as text file"));
492 params.push_back(TAParam("L","loglevel",true,pLogLevel,"debug|info|warning|error","set the log level (info by default)"));
493 params.push_back(TAParam("v","view",true,pView,"pattern|commands|nothing","set visualization (nothing by default)"));
494 params.push_back(TAParam("i","info",false,pInfo,"","get info about a song"));
495 params.push_back(TAParam("c","console",false,pConsole,"","enable console mode"));
496 params.push_back(TAParam("q","noreport",false,pQuiet,"","do not display message box on error"));
497 params.push_back(TAParam("n","nostatus",false,pNoStatus,"","disable playback status in console mode"));
498 params.push_back(TAParam("N","nocontrols",false,pNoControls,"","disable standard input controls in console mode"));
499
500 params.push_back(TAParam("l","loops",true,pLoops,"<count>","set number of loops"));
501 params.push_back(TAParam("s","subsong",true,pSubSong,"<number>","set sub-song"));
502 params.push_back(TAParam("o","outmode",true,pOutMode,"one|persys|perchan","set file output mode"));
503 params.push_back(TAParam("S","safemode",false,pSafeMode,"","enable safe mode (software rendering and no audio)"));
504 params.push_back(TAParam("A","safeaudio",false,pSafeModeAudio,"","enable safe mode (with audio"));
505
506 params.push_back(TAParam("B","benchmark",true,pBenchmark,"render|seek","run performance test"));
507
508 params.push_back(TAParam("V","version",false,pVersion,"","view information about Furnace."));
509 params.push_back(TAParam("W","warranty",false,pWarranty,"","view warranty disclaimer."));
510 }
511
512 #ifdef _WIN32
513 void reportError(String what) {
514 logE("%s",what);
515 if (!noReportError) {
516 MessageBox(NULL,what.c_str(),"Furnace",MB_OK|MB_ICONERROR);
517 }
518 }
519 #elif defined(ANDROID) || defined(__APPLE__)
520 void reportError(String what) {
521 logE("%s",what);
522 #ifdef HAVE_SDL2
523 if (!noReportError) {
524 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,"Error",what.c_str(),NULL);
525 }
526 #endif
527 }
528 #else
529 void reportError(String what) {
530 logE("%s",what);
531 if (!noReportError) {
532 // dummy
533 }
534 }
535 #endif
536
537 #ifndef _WIN32
538 #ifdef HAVE_GUI
539 static void handleTermGUI(int) {
540 g.requestQuit();
541 }
542 #endif
543 #endif
544
545 // TODO: CoInitializeEx on Windows?
546 // TODO: add crash log
547 int main(int argc, char** argv) {
548 // Windows console thing - thanks dj.tuBIG/MaliceX
549 #ifdef _WIN32
550 #ifndef TA_SUBSYSTEM_CONSOLE
551 #ifndef SUPPORT_XP
552 if (AttachConsole(ATTACH_PARENT_PROCESS)) {
553 freopen("CONOUT$", "w", stdout);
554 freopen("CONOUT$", "w", stderr);
555 freopen("CONIN$", "r", stdin);
556 }
557 #endif
558 #endif
559 #endif
560
561 srand(time(NULL));
562
563 initLog(stdout);
564 #ifdef _WIN32
565 // set DPI awareness
566 HMODULE shcore=LoadLibraryW(L"shcore.dll");
567 if (shcore!=NULL) {
568 SPDA ta_SetProcessDpiAwareness=(SPDA)GetProcAddress(shcore,"SetProcessDpiAwareness");
569 if (ta_SetProcessDpiAwareness!=NULL) {
570 HRESULT result=ta_SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
571 if (result!=S_OK) {
572 // ???
573 }
574 }
575 if (!FreeLibrary(shcore)) {
576 // ???
577 }
578 }
579
580 // co initialize ex
581 HRESULT coResult=CoInitializeEx(NULL,COINIT_MULTITHREADED);
582 if (coResult!=S_OK) {
583 logE("CoInitializeEx failed!");
584 }
585 #endif
586 outName="";
587 vgmOutName="";
588 cmdOutName="";
589 romOutName="";
590 txtOutName="";
591
592 // load config for locale
593 e.prePreInit();
594
595 #ifdef HAVE_LOCALE
596 String reqLocale=e.getConfString("locale","");
597 if (!reqLocale.empty()) {
598 if (reqLocale.find(".")==String::npos) {
599 reqLocale+=".UTF-8";
600 }
601 }
602 strncpy(reqLocaleCopy,reqLocale.c_str(),63);
603 if (reqLocale!="en_US.UTF-8") {
604 const char* localeRet=NULL;
605 #ifdef HAVE_SETLOCALE
606 if ((localeRet=setlocale(LC_CTYPE,reqLocaleCopy))==NULL) {
607 logE("could not set locale (CTYPE)!");
608 displayLocaleFailError=true;
609 } else {
610 logV("locale: %s",localeRet);
611 }
612 if ((localeRet=setlocale(LC_MESSAGES,reqLocaleCopy))==NULL) {
613 logE("could not set locale (MESSAGES)!");
614 displayLocaleFailError=true;
615 #ifdef HAVE_MOMO
616 if (momo_setlocale(LC_MESSAGES,reqLocaleCopy)==NULL) {
617 logV("Momo: could not set locale!");
618 }
619 #endif
620 } else {
621 logV("locale: %s",localeRet);
622 #ifdef HAVE_MOMO
623 if (momo_setlocale(LC_MESSAGES,localeRet)==NULL) {
624 logV("Momo: could not set locale!");
625 }
626 #endif
627 }
628 #else
629 if ((localeRet=momo_setlocale(LC_MESSAGES,reqLocaleCopy))==NULL) {
630 logV("Momo: could not set locale!");
631 } else {
632 logV("locale: %s",localeRet);
633 }
634 #endif
635
636 char exePath[4096];
637 memset(exePath,0,4096);
638 #ifndef ANDROID
639 if (!getExePath(argv[0],exePath,4095)) memset(exePath,0,4096);
640 #endif
641
642 memset(localeDir,0,4096);
643
644 bool textDomainBound=false;
645 for (int i=0; localeDirs[i]; i++) {
646 #ifdef ANDROID
647 strncpy(localeDir,localeDirs[i],4095);
648 #else
649 if (exePath[0]!=0 && localeDirs[i][0]!=DIR_SEPARATOR) {
650 // do you NOT understand what memset IS
651 char* i_s=exePath;
652 for (int i_i=0; i_i<4095; i_i++) {
653 localeDir[i_i]=*i_s;
654 if ((*i_s)==0) break;
655 i_s++;
656 }
657 strncat(localeDir,DIR_SEPARATOR_STR,4095);
658 strncat(localeDir,localeDirs[i],4095);
659 } else {
660 strncpy(localeDir,localeDirs[i],4095);
661 }
662 #endif
663 logV("bind text domain: %s",localeDir);
664 #ifndef ANDROID
665 if (!dirExists(localeDir)) continue;
666 #endif
667 if ((localeRet=TA_BINDTEXTDOMAIN("furnace",localeDir))==NULL) {
668 continue;
669 } else {
670 textDomainBound=true;
671 logV("text domain 1: %s",localeRet);
672 break;
673 }
674 }
675 if (!textDomainBound) {
676 logE("could not bind text domain!");
677 } else {
678 if ((localeRet=TA_TEXTDOMAIN("furnace"))==NULL) {
679 logE("could not text domain!");
680 } else {
681 logV("text domain 2: %s",localeRet);
682 }
683 }
684 }
685 #endif
686
687 initParams();
688
689 // parse arguments
690 String arg, val, fileName;
691 size_t eqSplit, argStart;
692 for (int i=1; i<argc; i++) {
693 arg=""; val="";
694 if (argv[i][0]=='-') {
695 if (argv[i][1]=='-') {
696 argStart=2;
697 } else {
698 argStart=1;
699 }
700 arg=&argv[i][argStart];
701 eqSplit=arg.find_first_of('=');
702 if (eqSplit==String::npos) {
703 if (needsValue(arg)) {
704 if ((i+1)<argc) {
705 val=argv[i+1];
706 i++;
707 } else {
708 reportError(fmt::sprintf(_("incomplete param %s."),arg.c_str()));
709 return 1;
710 }
711 }
712 } else {
713 val=arg.substr(eqSplit+1);
714 arg=arg.substr(0,eqSplit);
715 }
716 for (size_t j=0; j<params.size(); j++) {
717 if (params[j].name==arg || (params[j].shortName!="" && params[j].shortName==arg)) {
718 switch (params[j].func(val)) {
719 case TA_PARAM_ERROR:
720 return 1;
721 break;
722 case TA_PARAM_SUCCESS:
723 break;
724 case TA_PARAM_QUIT:
725 return 0;
726 break;
727 }
728 break;
729 }
730 }
731 } else {
732 fileName=argv[i];
733 }
734 }
735
736 e.setConsoleMode(consoleMode,!consoleNoStatus);
737
738 #ifdef _WIN32
739 if (consoleMode) {
740 HANDLE winin=GetStdHandle(STD_INPUT_HANDLE);
741 HANDLE winout=GetStdHandle(STD_OUTPUT_HANDLE);
742 int termprop=0;
743 int termpropi=0;
744 GetConsoleMode(winout,(LPDWORD)&termprop);
745 GetConsoleMode(winin,(LPDWORD)&termpropi);
746 termprop|=ENABLE_VIRTUAL_TERMINAL_PROCESSING;
747 termpropi&=~ENABLE_LINE_INPUT;
748 SetConsoleMode(winout,termprop);
749 SetConsoleMode(winin,termpropi);
750 }
751 #endif
752
753 if (fileName.empty() && consoleMode) {
754 logI("usage: %s file",argv[0]);
755 return 1;
756 }
757
758 const bool outputMode = outName!="" || vgmOutName!="" || cmdOutName!="" || romOutName!="" || txtOutName!="";
759
760 if (fileName.empty() && (benchMode || infoMode || outputMode)) {
761 logE("provide a file!");
762 return 1;
763 }
764
765 #if defined(HAVE_SDL2) && defined(_WIN32) && !defined(SUPPORT_XP)
766 if (!IsWindows7OrGreater()) {
767 SDL_SetHint(SDL_HINT_AUDIODRIVER,"winmm");
768 }
769 #endif
770
771 #ifdef HAVE_GUI
772 if (e.preInit(consoleMode || benchMode || infoMode || outputMode)) {
773 if (consoleMode || benchMode || infoMode || outputMode) {
774 logW("engine wants safe mode, but Furnace GUI is not going to start.");
775 } else {
776 safeMode=true;
777 }
778 }
779 #else
780 if (e.preInit(true)) {
781 logW("engine wants safe mode, but Furnace GUI is not available.");
782 }
783 #endif
784
785 if (safeMode && (consoleMode || benchMode || infoMode || outputMode)) {
786 logE("you can't use safe mode and console/export mode together.");
787 return 1;
788 }
789
790 if (safeMode && !safeModeWithAudio) {
791 e.setAudio(DIV_AUDIO_DUMMY);
792 }
793
794 #if defined(HAVE_SDL2) && defined(ANDROID)
795 if (e.getConfInt("backgroundPlay",0)!=0) {
796 SDL_SetHint(SDL_HINT_ANDROID_BLOCK_ON_PAUSE,"0");
797 SDL_SetHint(SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO,"0");
798 }
799 #endif
800
801 if (!fileName.empty() && ((!e.getConfBool("tutIntroPlayed",TUT_INTRO_PLAYED)) || e.getConfInt("alwaysPlayIntro",0)!=3 || consoleMode || benchMode || infoMode || outputMode)) {
802 logI("loading module...");
803 FILE* f=ps_fopen(fileName.c_str(),"rb");
804 if (f==NULL) {
805 reportError(fmt::sprintf(_("couldn't open file! (%s)"),strerror(errno)));
806 e.everythingOK();
807 finishLogFile();
808 return 1;
809 }
810 if (fseek(f,0,SEEK_END)<0) {
811 reportError(fmt::sprintf(_("couldn't open file! (couldn't get file size: %s)"),strerror(errno)));
812 e.everythingOK();
813 fclose(f);
814 finishLogFile();
815 return 1;
816 }
817 ssize_t len=ftell(f);
818 if (len==(SIZE_MAX>>1)) {
819 reportError(fmt::sprintf(_("couldn't open file! (couldn't get file length: %s)"),strerror(errno)));
820 e.everythingOK();
821 fclose(f);
822 finishLogFile();
823 return 1;
824 }
825 if (len<1) {
826 if (len==0) {
827 reportError(_("that file is empty!"));
828 } else {
829 reportError(fmt::sprintf(_("couldn't open file! (tell error: %s)"),strerror(errno)));
830 }
831 e.everythingOK();
832 fclose(f);
833 finishLogFile();
834 return 1;
835 }
836 unsigned char* file=new unsigned char[len];
837 if (fseek(f,0,SEEK_SET)<0) {
838 reportError(fmt::sprintf(_("couldn't open file! (size error: %s)"),strerror(errno)));
839 e.everythingOK();
840 fclose(f);
841 delete[] file;
842 finishLogFile();
843 return 1;
844 }
845 if (fread(file,1,(size_t)len,f)!=(size_t)len) {
846 reportError(fmt::sprintf(_("couldn't open file! (read error: %s)"),strerror(errno)));
847 e.everythingOK();
848 fclose(f);
849 delete[] file;
850 finishLogFile();
851 return 1;
852 }
853 fclose(f);
854 if (!e.load(file,(size_t)len,fileName.c_str())) {
855 reportError(fmt::sprintf(_("could not open file! (%s)"),e.getLastError()));
856 e.everythingOK();
857 finishLogFile();
858 return 1;
859 }
860 }
861 if (infoMode) {
862 e.dumpSongInfo();
863 finishLogFile();
864 return 0;
865 }
866
867 if (!e.init()) {
868 if (consoleMode) {
869 reportError(_("could not initialize engine!"));
870 finishLogFile();
871 return 1;
872 } else {
873 logE("could not initialize engine!");
874 displayEngineFailError=true;
875 }
876 }
877
878 if (subsong!=-1) {
879 e.changeSongP(subsong);
880 }
881
882 if (benchMode) {
883 logI("starting benchmark!");
884 if (benchMode==2) {
885 e.benchmarkSeek();
886 } else {
887 e.benchmarkPlayback();
888 }
889 finishLogFile();
890 return 0;
891 }
892
893 if (outputMode) {
894 if (cmdOutName!="") {
895 SafeWriter* w=e.saveCommand(NULL);
896 if (w!=NULL) {
897 FILE* f=ps_fopen(cmdOutName.c_str(),"wb");
898 if (f!=NULL) {
899 fwrite(w->getFinalBuf(),1,w->size(),f);
900 fclose(f);
901 } else {
902 reportError(fmt::sprintf(_("could not open file! (%s)"),strerror(errno)));
903 }
904 w->finish();
905 delete w;
906 } else {
907 reportError(_("could not write command stream!"));
908 }
909 }
910 if (vgmOutName!="") {
911 SafeWriter* w=e.saveVGM(NULL,true,0x171,false,vgmOutDirect);
912 if (w!=NULL) {
913 FILE* f=ps_fopen(vgmOutName.c_str(),"wb");
914 if (f!=NULL) {
915 fwrite(w->getFinalBuf(),1,w->size(),f);
916 fclose(f);
917 } else {
918 reportError(fmt::sprintf(_("could not open file! (%s)"),strerror(errno)));
919 }
920 w->finish();
921 delete w;
922 } else {
923 reportError(_("could not write VGM!"));
924 }
925 }
926 if (outName!="") {
927 e.setConsoleMode(true);
928 e.saveAudio(outName.c_str(),exportOptions);
929 e.waitAudioFile();
930 }
931 if (romOutName!="") {
932 e.setConsoleMode(true);
933 // select ROM target type
934 DivROMExportOptions romTarget = DIV_ROM_ABSTRACT;
935 String lowerCase=romOutName;
936 for (char& i: lowerCase) {
937 if (i>='A' && i<='Z') i+='a'-'A';
938 }
939 for (int i=0; i<DIV_ROM_MAX; i++) {
940 DivROMExportOptions opt = (DivROMExportOptions)i;
941 if (e.isROMExportViable(opt)) {
942 const DivROMExportDef* newDef=e.getROMExportDef((DivROMExportOptions)i);
943 if (newDef->fileExt &&
944 lowerCase.length()>=strlen(newDef->fileExt) &&
945 lowerCase.substr(lowerCase.length()-strlen(newDef->fileExt))==newDef->fileExt) {
946 romTarget = opt;
947 break; // extension matched, stop searching
948 }
949 if (romTarget == DIV_ROM_ABSTRACT) {
950 romTarget = opt; // use first viable, but keep searching for extension match
951 }
952 }
953 }
954 if (romTarget > DIV_ROM_ABSTRACT && romTarget < DIV_ROM_MAX) {
955 DivROMExport* pendingExport = e.buildROM(romTarget);
956 if (pendingExport==NULL) {
957 reportError(_("could not create exporter! you may want to report this issue..."));
958 } else {
959 pendingExport->setConf(romExportConfig);
960 if (pendingExport->go(&e)) {
961 pendingExport->wait();
962 if (!pendingExport->hasFailed()) {
963 for (DivROMExportOutput& i: pendingExport->getResult()) {
964 String path=romOutName;
965 if (e.getROMExportDef(romTarget)->multiOutput) {
966 path+=DIR_SEPARATOR_STR;
967 path+=i.name;
968 }
969 FILE* f=ps_fopen(path.c_str(),"wb");
970 if (f!=NULL) {
971 fwrite(i.data->getFinalBuf(),1,i.data->size(),f);
972 fclose(f);
973 } else {
974 reportError(fmt::sprintf(_("could not open file! (%s)"),strerror(errno)));
975 }
976 }
977 } else {
978 reportError(fmt::sprintf(_("ROM export failed! (%s)"),e.getLastError()));
979 }
980 } else {
981 reportError(_("could not begin exporting process! TODO: elaborate"));
982 }
983 }
984 } else {
985 reportError(_("no matching ROM export target is available."));
986 }
987 }
988 if (txtOutName!="") {
989 e.setConsoleMode(true);
990 SafeWriter* w=e.saveText(false);
991 if (w!=NULL) {
992 FILE* f=ps_fopen(txtOutName.c_str(),"wb");
993 if (f!=NULL) {
994 fwrite(w->getFinalBuf(),1,w->size(),f);
995 fclose(f);
996 } else {
997 reportError(fmt::sprintf(_("could not open file! (%s)"),strerror(errno)));
998 }
999 w->finish();
1000 delete w;
1001 } else {
1002 reportError(_("could not write text!"));
1003 }
1004 }
1005 finishLogFile();
1006 return 0;
1007 }
1008
1009 if (consoleMode) {
1010 bool cliSuccess=false;
1011 if (consoleNoStatus) {
1012 cli.noStatus();
1013 }
1014 if (consoleNoControls) {
1015 cli.noControls();
1016 }
1017 cli.bindEngine(&e);
1018 if (!cli.init()) {
1019 reportError(_("error while starting CLI!"));
1020 } else {
1021 cliSuccess=true;
1022 }
1023 logI(_("playing..."));
1024 e.play();
1025 if (cliSuccess) {
1026 cli.loop();
1027 cli.finish();
1028 e.quit();
1029 finishLogFile();
1030 return 0;
1031 } else {
1032 #ifdef HAVE_SDL2
1033 SDL_Event ev;
1034 while (true) {
1035 SDL_WaitEvent(&ev);
1036 if (ev.type==SDL_QUIT) break;
1037 }
1038 e.quit();
1039 finishLogFile();
1040 return 0;
1041 #else
1042 while (true) {
1043 #ifdef _WIN32
1044 Sleep(500);
1045 #else
1046 usleep(500000);
1047 #endif
1048 }
1049 #endif
1050 }
1051 }
1052
1053 #ifdef HAVE_GUI
1054 if (safeMode) g.enableSafeMode();
1055 g.bindEngine(&e);
1056 if (!g.init()) {
1057 reportError(g.getLastError());
1058 finishLogFile();
1059 e.everythingOK();
1060 return 1;
1061 }
1062
1063 if (displayEngineFailError) {
1064 logE(_("displaying engine fail error."));
1065 g.showError(_("error while initializing audio!"));
1066 }
1067
1068 if (displayLocaleFailError) {
1069 #ifndef HAVE_MOMO
1070 #ifdef __unix__
1071 g.showError("could not load language!\napparently your system does not support this language correctly.\nmake sure you've generated language data by editing /etc/locale.gen\nand then running locale-gen as root.");
1072 #else
1073 g.showError("could not load language!\nthis is a bug!");
1074 #endif
1075 #endif
1076 }
1077
1078 if (!fileName.empty()) {
1079 g.setFileName(fileName);
1080 }
1081
1082 #ifndef _WIN32
1083 sigemptyset(&termsa.sa_mask);
1084 termsa.sa_flags=0;
1085 termsa.sa_handler=handleTermGUI;
1086 sigaction(SIGTERM,&termsa,NULL);
1087 #endif
1088
1089 g.loop();
1090 logI("closing GUI.");
1091 g.finish(true);
1092 #else
1093 logE("GUI requested but GUI not compiled!");
1094 #endif
1095
1096 logI("stopping engine.");
1097 e.quit(false);
1098
1099 finishLogFile();
1100
1101 #ifdef _WIN32
1102 if (coResult==S_OK || coResult==S_FALSE) {
1103 CoUninitialize();
1104 }
1105 #endif
1106 e.everythingOK();
1107
1108 #ifdef HAVE_SDL2
1109 SDL_Quit();
1110 #endif
1111
1112 return 0;
1113 }