23#ifdef ASE_WITH_CPPTRACE
24#include <cpptrace/from_current.hpp>
31#define MDEBUG(...) Ase::debug ("memory", __VA_ARGS__)
41MainAppImpl::MainAppImpl()
46static int arg_unauth_port = 0;
58print_usage (
bool help)
66 printout (
"Usage: %s [OPTIONS] [project.anklang]\n",
executable_name());
67 printout (
" --check Run integrity tests\n");
68 printout (
" --disable-randomization Test mode for deterministic tests\n");
69 printout (
" --fatal-warnings Abort on warnings and failing assertions\n");
70 printout (
" --help Print program usage and options\n");
71 printout (
" --jsbin Print Javascript IPC & binary messages\n");
72 printout (
" --jsipc Print Javascript IPC messages\n");
73 printout (
" --jsonts Print TypeScript bindings\n");
74 printout (
" --list-drivers Print PCM and MIDI drivers\n");
75 printout (
" --list-tests List all test names\n");
76 printout (
" --norc Prevent loading of any rc files\n");
77 printout (
" --play-autostart Automatically start playback of `project.anklang`\n");
78 printout (
" --rand64 Produce 64bit random numbers on stdout\n");
79 printout (
" --test[=test] Run specific tests\n");
80 printout (
" --unauth-dev=NUM Open an unauthenticated websocket port for testing\n");
81 printout (
" --ui <none|chromium|google-chrome|htmlgui>\n");
82 printout (
" Open GUI in web browser [htmlgui]\n");
83 printout (
" --version Print program version\n");
84 printout (
" -M mididriver Force use of <mididriver>\n");
85 printout (
" -P pcmdriver Force use of <pcmdriver>\n");
86 printout (
" -o wavfile Capture output to OPUS/FLAC/WAV file\n");
87 printout (
" -t <time> Automatically play and stop after <time> has passed\n");
88 printout (
"Options set via $ASE_DEBUG:\n");
89 printout (
" :no-logfile: Disable logging to ~/.cache/anklang/ instead of stderr\n");
94parse_option_arg (
const char *option,
char **argv,
unsigned *ith,
const char **argp)
96 const size_t l =
strlen (option);
97 if (strncmp (option, argv[*ith], l) == 0) {
98 *argp = argv[*ith] + l;
100 if ((*argp)[0] ==
'=')
102 else if ((*argp)[0] == 0) {
104 *argp = argv[*ith] ? argv[*ith] :
"";
105 argv[*ith] =
nullptr;
113static constexpr int jsipc_logflags = 1 | 2 | 4 | 8 | 16;
114static constexpr int jsbin_logflags = 1 | 256;
116static StringS check_test_names;
119parse_args (
int *argcp,
char **argv, MainAppImpl &config)
130 const uint argc = *argcp;
131 for (
uint i = 1; i < argc; i++)
133 const char *
optarg =
nullptr;
135 config.args.push_back (argv[i]);
136 else if (strcmp (argv[i],
"--fatal-warnings") == 0 || strcmp (argv[i],
"--g-fatal-warnings") == 0)
138 else if (strcmp (
"--disable-randomization", argv[i]) == 0)
139 config.allow_randomization =
false;
140 else if (strcmp (
"--norc", argv[i]) == 0)
142 else if (strcmp (
"--rand64", argv[i]) == 0)
145 constexpr int N = 8192;
149 for (
size_t i = 0; i < N; i++)
150 buffer[i] = prng.next();
151 fwrite (buffer,
sizeof (buffer[0]), N, stdout);
155 else if (strcmp (
"--check", argv[i]) == 0)
157 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
159 printerr (
"CHECK_INTEGRITY_TESTS…\n");
160 default_ui_mode =
"none";
162 else if (strcmp (
"--list-tests", argv[i]) == 0)
165 for (
const auto &t : Test::list_tests())
166 ids.push_back (t.ident);
168 for (
const auto &t : ids)
169 printout (
"%s\n", t);
172 else if (strcmp (
"--test", argv[i]) == 0 || strncmp (
"--test=", argv[i], 7) == 0)
174 const char *eq =
strchr (argv[i],
'=');
175 const char *arg = eq ? eq + 1 : i+1 < argc ? argv[++i] :
nullptr;
176 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
180 default_ui_mode =
"none";
182 else if (argv[i] ==
String (
"--blake3") && i + 1 <
size_t (argc))
187 printerr (
"%s: failed to read: %s\n", argv[i], strerror (errno));
192 else if (strcmp (
"--jsonts", argv[i]) == 0) {
193 if (getenv (
"ASE_JSONTS") ==
nullptr)
194 fatal_error (
"%s: environment must contain ASE_JSONTS for --jsonts", argv[0]);
195 printout (
"%s\n", Jsonipc::g_binding_printer->finish());
197 }
else if (strcmp (
"--jsipc", argv[i]) == 0)
198 config.jsonapi_logflags |= jsipc_logflags;
199 else if (strcmp (
"--jsbin", argv[i]) == 0)
200 config.jsonapi_logflags |= jsbin_logflags;
201 else if (strcmp (
"--list-drivers", argv[i]) == 0)
202 config.list_drivers =
true;
203 else if (strcmp (
"-M", argv[i]) == 0 && i + 1 <
size_t (argc))
206 config.midi_override = argv[i];
208 else if (strcmp (
"-P", argv[i]) == 0 && i + 1 <
size_t (argc))
211 config.pcm_override = argv[i];
213 else if (strcmp (
"--no-devices", argv[i]) == 0)
215 config.no_devices =
true;
217 else if (strcmp (
"-h", argv[i]) == 0 ||
218 strcmp (
"--help", argv[i]) == 0)
223 else if (strcmp (
"--version", argv[i]) == 0)
228 else if (argv[i] ==
String (
"-o") && i + 1 <
size_t (argc))
231 config.outputfile = argv[i];
233 else if (argv[i] ==
String (
"--play-autostart"))
235 config.play_autostart =
true;
236 default_ui_mode =
"none";
238 else if (parse_option_arg (
"--unauth-dev", argv, &i, &optarg))
241 default_ui_mode =
"wait";
243 else if (argv[i] ==
String (
"-t") && i + 1 <
size_t (argc))
245 config.play_autostart =
true;
248 default_ui_mode =
"none";
250 else if (parse_option_arg (
"--ui", argv, &i, &optarg))
254 else if (argv[i] ==
String (
"--") && !sep)
256 else if (argv[i][0] ==
'-' && !sep)
257 fatal_error (
"invalid command line argument: %s", argv[i]);
259 config.args.push_back (argv[i]);
262 if (arg_ui_mode.
empty())
263 arg_ui_mode = default_ui_mode;
267 for (
uint i = 1; i < argc; i++)
281 const char *
const c52 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
288 KeccakCryptoRng csprng;
290 for (
size_t i = 0; i < 23; ++i)
291 auth += c52[csprng.random() % 52];
298 if (check_test_names.
empty())
308 LoopP loop = main_loop;
321 seen_autostop =
true;
327handle_autostop (
const LoopState &state)
331 case LoopState::PREPARE:
return seen_autostop;
332 case LoopState::CHECK:
return seen_autostop;
333 case LoopState::DISPATCH:
334 info (
"Main: stopping playback (auto)");
346 sigset_t signal_mask;
352 Ase::warning (
"Ase: pthread_sigmask for SIGPIPE failed: %s\n", strerror (errno));
361 if (!loft_needs_preallocation_mt)
363 loft_needs_preallocation_mt =
true;
368static size_t last_loft_preallocation = 0;
371preallocate_loft (
size_t preallocation)
374 last_loft_preallocation = preallocation;
377 .watermark = last_loft_preallocation / 2,
378 .flags = Loft::PREFAULT_PAGES,
380 loft_set_config (loftcfg);
381 loft_set_notifier (notify_loft_lowmem);
382 loft_grow_preallocate();
389 const bool keep_alive = lstate.phase == LoopState::DISPATCH;
393 loft_needs_preallocation_mt =
false;
394 last_loft_preallocation *= 2;
395 const size_t newalloc = loft_grow_preallocate (last_loft_preallocation);
397 loft_get_config (config);
398 config.
watermark = last_loft_preallocation / 2;
399 loft_set_config (config);
401 MDEBUG (
"Loft preallocation in main thread: %f MB", newalloc / (1024. * 1024));
406prefault_pages (
size_t stacksize,
size_t heapsize)
408 const size_t pagesize =
sysconf (_SC_PAGESIZE);
409 char *heap = (
char*) malloc (heapsize);
411 for (
size_t i = 0; i < heapsize; i += pagesize)
414 char *stack = (
char*) alloca (stacksize);
416 for (
size_t i = 0; i < stacksize; i += pagesize)
421main (
int argc,
char *argv[])
424 using namespace AnsiColors;
427 TaskRegistry::setup_ase (
"AnklangMainProc");
429 mallopt (M_MMAP_MAX, 0);
431 mallopt (M_TRIM_THRESHOLD, -1);
433 prefault_pages ((1024 + 768) * 1024, 64 * 1024 * 1024);
435 preallocate_loft (64 * 1024 * 1024);
437 loft_set_growth_notifier ([] (
size_t total,
size_t needed)
439 warning (
"Loft.BumpAllocator: growing beyond preallocation: totalmem=%u needed=%d\n", total, needed);
443 logging_handle_terminate();
447 if (setpgid (0, 0) < 0)
448 diag (
"Main: setpgid failed: %s", ::strerror (errno));
451 if (!setlocale (LC_ALL,
""))
452 fatal_error (
"setlocale: locale not supported by libc: %s", ::strerror (errno));
455 parse_args (&argc, argv, main_app);
456 logging_configure (arg_ui_mode !=
"none");
463 Preference::load_preferences (
true);
466 ServerImpl::instancep();
469 if (!
trkn_init (argc, argv, App.no_devices))
470 fatal_error (
"Main: failed to initialize tracktion engine");
472 const auto B1 =
color (BOLD);
473 const auto B0 =
color (BOLD_OFF);
477 if (App.list_drivers)
479 Ase::Driver::EntryVec entries;
480 printout (
"%s",
_(
"Available PCM drivers:\n"));
481 entries = Ase::PcmDriver::list_drivers();
482 std::sort (entries.begin(), entries.end(), [] (
auto &a,
auto &b) { return a.priority < b.priority; });
483 for (
const auto &entry : entries)
485 printout (
" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid +
":",
486 entry.readonly ?
"Input" : entry.writeonly ?
"Output" :
"Duplex",
487 entry.priority, entry.device_name,
488 entry.capabilities.
empty() ?
"" :
"\t" + entry.capabilities +
"\n",
489 entry.device_info.
empty() ?
"" :
"\t" + entry.device_info +
"\n",
490 entry.hints.
empty() ?
"" :
"\t(" + entry.hints +
")\n",
491 entry.notice.
empty() ?
"" :
"\t" + entry.notice +
"\n");
495 printout (
"%s",
_(
"Available MIDI drivers:\n"));
496 entries = Ase::MidiDriver::list_drivers();
497 std::sort (entries.begin(), entries.end(), [] (
auto &a,
auto &b) { return a.priority < b.priority; });
498 for (
const auto &entry : entries)
500 printout (
" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid +
":",
501 entry.readonly ?
"Input" : entry.writeonly ?
"Output" :
"Duplex",
502 entry.priority, entry.device_name,
503 entry.capabilities.
empty() ?
"" :
"\t" + entry.capabilities +
"\n",
504 entry.device_info.
empty() ?
"" :
"\t" + entry.device_info +
"\n",
505 entry.hints.
empty() ?
"" :
"\t(" + entry.hints +
")\n",
506 entry.notice.
empty() ?
"" :
"\t" + entry.notice +
"\n");
515 for (
const auto &filename : App.args)
517 preload_project = ProjectImpl::create (
Path::basename (filename));
518 Error error = Error::NO_MEMORY;
520 error = preload_project->load_project (filename);
521 diag (
"Main: load project: %s: %s", filename,
ase_error_blurb (error));
523 warning (
"%s: failed to load project: %s", filename,
ase_error_blurb (error));
527 const String auth_token = arg_unauth_port > 0 ?
"" : make_auth_string();
528 auto wss = WebSocketServer::create (jsonapi_make_connection, App.jsonapi_logflags, auth_token);
529 main_app.web_socket_server = &*wss;
532 wss->http_alias (
"/Builtin/Controller",
anklang_runpath (RPath::INSTALLDIR,
"/Controller"));
534 wss->http_alias (
"/Builtin/Scripts",
anklang_runpath (RPath::INSTALLDIR,
"/Scripts"));
535 const int xport = arg_unauth_port > 0 ? arg_unauth_port : 0;
536 const String subprotocol =
"";
537 jsonapi_set_subprotocol (subprotocol);
538 if (App.mode == MainApp::SYNTHENGINE && arg_ui_mode !=
"none") {
539 const char *host =
"127.0.0.1";
540 wss->listen (host, xport, [] () { main_loop->quit (-1); });
543 String redirecthtml = webui_create_auth_redirect (
"anklang", wss->listen_port(), auth_token, arg_ui_mode);
545 fatal_error (
"%s: failed to create html redirect file in $HOME", redirecthtml);
546 webui_url =
"file://" + redirecthtml;
547 wss->see_other (webui_url);
549 info (
"Main: WebUI address: %s", webui_url);
550 auto ereason = webui_start_browser (arg_ui_mode, main_loop, webui_url, [] () { main_loop->quit (0); });
552 fatal_error (
"Main: failed to run WebUI: %s: %s", ereason.what, ::strerror (ereason.error));
556 for (
int sigid : { SIGHUP, SIGINT, SIGQUIT, SIGABRT, SIGTERM, SIGSYS }) {
557 main_loop->exec_usignal (sigid, [] (
int8 sig) {
558 info (
"Main: got signal %d: terminate", sig);
560 atquit_terminate (-1, pgid);
563 USignalSource::install_sigaction (sigid);
567 main_loop->exec_usignal (SIGUSR2, [wss] (
int8 sig) {
568 info (
"Main: got signal %d: reset WebSocket", sig);
572 USignalSource::install_sigaction (SIGUSR2);
579 if (App.play_autostart && preload_project)
580 main_loop->add ([preload_project] ()
582 info (
"Main: starting playback (auto)");
583 preload_project->start_playback (App.play_autostop);
586 main_loop->exec_dispatcher (handle_autostop);
589 if (App.mode == MainApp::CHECK_INTEGRITY_TESTS)
590 main_loop->add (run_tests_and_quit);
593 const int exitcode = main_loop->run();
595 diag (
"Main: event loop quit: code=%d", exitcode);
599 main_app.web_socket_server =
nullptr;
603 ProjectImpl::force_shutdown_all();
606 main_loop->iterate_pending();
611 diag (
"Main: exiting: %d", exitcode);
618main (
int argc,
char *argv[])
621#ifdef ASE_WITH_CPPTRACE
622 CPPTRACE_TRY { r = Ase::main (argc, argv); }
630 cpptrace::from_current_exception().print();
633 r = Ase::main (argc, argv);
static String priority_string(uint priority)
Return string which represents the given priority mask.
static LoopP current()
Return the thread-local singleton loop, created on first call.
#define assert_return(expr,...)
Return from the current function if expr is unmet and issue an assertion warning.
#define return_unless(cond,...)
Return silently if cond does not evaluate to true with return value ...
#define _(...)
Retrieve the translation of a C or C++ string.
std::string color(Colors acolor, Colors c1, Colors c2, Colors c3, Colors c4, Colors c5, Colors c6)
Return ANSI code for the specified color if stdout & stderr should be colorized, see colorize_tty().
String basename(const String &path)
Strips all directory components from path and returns the resulting file name.
int run(void)
Run all registered tests.
The Anklang C++ API namespace.
bool trkn_init(int argc, char *argv[], bool nodevs)
Setup tracktion and tracktion::engine.
String string_to_hex(const String &input)
Convert bytes in string input to hexadecimal numbers.
int8_t int8
An 8-bit signed integer.
std::vector< String > StringS
Convenience alias for a std::vector<std::string>.
JobQueue main_jobs(call_main_loop)
Execute a job callback in the event loop.
Error
Enum representing Error states.
const char * ase_error_blurb(Error error)
Describe Error condition.
std::string anklang_runpath(RPath rpath, const String &segment)
Retrieve various resource paths at runtime.
double string_to_seconds(const String &string, double fallback)
Parse string into seconds.
int64 string_to_int(const String &string, size_t *consumed, uint base)
Parse a string into a 64bit integer, optionally specifying the expected number base.
void main_loop_wakeup()
Wake up the event loop.
bool logging_fatal_warnings
Global flag to cause the program to abort on warnings.
@ IDLE
Mildly important, used for background tasks.
@ SYSALLOC
Internal maintenance, don't use.
const char * ase_version()
Provide a string containing the package version.
std::string String
Convenience alias for std::string.
std::string executable_name()
Retrieve the name part of executable_path().
void main_loop_autostop_mt()
Stop the event loop after a timeout.
bool debug_key_enabled(const char *conditional) noexcept
Check if conditional is enabled by $ASE_DEBUG.
uint32_t uint
Provide 'uint' as convenience type.
void load_registered_drivers()
Load all registered drivers.
size_t preallocate
Amount of preallocated available memory.
size_t watermark
Watermark to trigger async preallocation.
const char * ase_build_id()
Provide a string containing the ASE library build id.
Configuration for Loft allocations.
size_t hash(size_t seed, const T &v)