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;
73RtJobQueue::operator+= (
const RtCall &call)
77 calljob->loftptr = std::move (loftptr);
78 const bool was_empty = main_rt_jobs_.push (calljob);
86 return !main_rt_jobs_.empty();
92 RtCallJob *calljob = main_rt_jobs_.pop_reversed();
95 calljob = calljob->next;
96 loftptr->call.invoke();
102print_usage (
bool help)
110 printout (
"Usage: %s [OPTIONS] [project.anklang]\n",
executable_name());
111 printout (
" --check Run integrity tests\n");
112 printout (
" --disable-randomization Test mode for deterministic tests\n");
113 printout (
" --fatal-warnings Abort on warnings and failing assertions\n");
114 printout (
" --help Print program usage and options\n");
115 printout (
" --jsbin Print Javascript IPC & binary messages\n");
116 printout (
" --jsipc Print Javascript IPC messages\n");
117 printout (
" --jsonts Print TypeScript bindings\n");
118 printout (
" --list-drivers Print PCM and MIDI drivers\n");
119 printout (
" --list-tests List all test names\n");
120 printout (
" --norc Prevent loading of any rc files\n");
121 printout (
" --play-autostart Automatically start playback of `project.anklang`\n");
122 printout (
" --rand64 Produce 64bit random numbers on stdout\n");
123 printout (
" --test[=test] Run specific tests\n");
124 printout (
" --unauth-dev=NUM Open an unauthenticated websocket port for testing\n");
125 printout (
" --ui <none|chromium|google-chrome|htmlgui>\n");
126 printout (
" Open GUI in web browser [htmlgui]\n");
127 printout (
" --version Print program version\n");
128 printout (
" -M mididriver Force use of <mididriver>\n");
129 printout (
" -P pcmdriver Force use of <pcmdriver>\n");
130 printout (
" -o wavfile Capture output to OPUS/FLAC/WAV file\n");
131 printout (
" -t <time> Automatically play and stop after <time> has passed\n");
132 printout (
"Options set via $ASE_DEBUG:\n");
133 printout (
" :no-logfile: Disable logging to ~/.cache/anklang/ instead of stderr\n");
138parse_option_arg (
const char *option,
char **argv,
unsigned *ith,
const char **argp)
140 const size_t l =
strlen (option);
141 if (strncmp (option, argv[*ith], l) == 0) {
142 *argp = argv[*ith] + l;
143 argv[*ith] =
nullptr;
144 if ((*argp)[0] ==
'=')
146 else if ((*argp)[0] == 0) {
148 *argp = argv[*ith] ? argv[*ith] :
"";
149 argv[*ith] =
nullptr;
157static constexpr int jsipc_logflags = 1 | 2 | 4 | 8 | 16;
158static constexpr int jsbin_logflags = 1 | 256;
160static StringS check_test_names;
163parse_args (
int *argcp,
char **argv,
MainAppImpl &config)
174 const uint argc = *argcp;
175 for (
uint i = 1; i < argc; i++)
177 const char *
optarg =
nullptr;
180 else if (strcmp (argv[i],
"--fatal-warnings") == 0 || strcmp (argv[i],
"--g-fatal-warnings") == 0)
182 else if (strcmp (
"--disable-randomization", argv[i]) == 0)
183 config.allow_randomization =
false;
184 else if (strcmp (
"--norc", argv[i]) == 0)
186 else if (strcmp (
"--rand64", argv[i]) == 0)
189 constexpr int N = 8192;
193 for (
size_t i = 0; i < N; i++)
194 buffer[i] = prng.next();
195 fwrite (buffer,
sizeof (buffer[0]), N, stdout);
199 else if (strcmp (
"--check", argv[i]) == 0)
201 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
203 printerr (
"CHECK_INTEGRITY_TESTS…\n");
204 default_ui_mode =
"none";
206 else if (strcmp (
"--list-tests", argv[i]) == 0)
209 for (
const auto &t : Test::list_tests())
210 ids.push_back (t.ident);
212 for (
const auto &t : ids)
213 printout (
"%s\n", t);
216 else if (strcmp (
"--test", argv[i]) == 0 || strncmp (
"--test=", argv[i], 7) == 0)
218 const char *eq =
strchr (argv[i],
'=');
219 const char *arg = eq ? eq + 1 : i+1 < argc ? argv[++i] :
nullptr;
220 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
224 default_ui_mode =
"none";
226 else if (argv[i] ==
String (
"--blake3") && i + 1 <
size_t (argc))
231 printerr (
"%s: failed to read: %s\n", argv[i], strerror (errno));
236 else if (strcmp (
"--jsonts", argv[i]) == 0) {
237 if (getenv (
"ASE_JSONTS") ==
nullptr)
238 fatal_error (
"%s: environment must contain ASE_JSONTS for --jsonts", argv[0]);
239 printout (
"%s\n", Jsonipc::g_binding_printer->finish());
241 }
else if (strcmp (
"--jsipc", argv[i]) == 0)
242 config.jsonapi_logflags |= jsipc_logflags;
243 else if (strcmp (
"--jsbin", argv[i]) == 0)
244 config.jsonapi_logflags |= jsbin_logflags;
245 else if (strcmp (
"--list-drivers", argv[i]) == 0)
246 config.list_drivers =
true;
247 else if (strcmp (
"-M", argv[i]) == 0 && i + 1 <
size_t (argc))
250 config.midi_override = argv[i];
252 else if (strcmp (
"-P", argv[i]) == 0 && i + 1 <
size_t (argc))
255 config.pcm_override = argv[i];
257 else if (strcmp (
"--no-devices", argv[i]) == 0)
259 config.no_devices =
true;
261 else if (strcmp (
"-h", argv[i]) == 0 ||
262 strcmp (
"--help", argv[i]) == 0)
267 else if (strcmp (
"--version", argv[i]) == 0)
272 else if (argv[i] ==
String (
"-o") && i + 1 <
size_t (argc))
275 config.outputfile = argv[i];
277 else if (argv[i] ==
String (
"--play-autostart"))
279 config.play_autostart =
true;
280 default_ui_mode =
"none";
282 else if (parse_option_arg (
"--unauth-dev", argv, &i, &optarg))
285 default_ui_mode =
"wait";
287 else if (argv[i] ==
String (
"-t") && i + 1 <
size_t (argc))
289 config.play_autostart =
true;
292 default_ui_mode =
"none";
294 else if (parse_option_arg (
"--ui", argv, &i, &optarg))
298 else if (argv[i] ==
String (
"--") && !sep)
300 else if (argv[i][0] ==
'-' && !sep)
301 fatal_error (
"invalid command line argument: %s", argv[i]);
306 if (arg_ui_mode.
empty())
307 arg_ui_mode = default_ui_mode;
311 for (
uint i = 1; i < argc; i++)
325 const char *
const c52 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
334 for (
size_t i = 0; i < 23; ++i)
335 auth += c52[csprng.
random() % 52];
342 if (check_test_names.
empty())
352 LoopP loop = main_loop;
365 seen_autostop =
true;
375 case LoopState::PREPARE:
return seen_autostop;
376 case LoopState::CHECK:
return seen_autostop;
377 case LoopState::DISPATCH:
378 info (
"Main: stopping playback (auto)");
390 sigset_t signal_mask;
396 Ase::warning (
"Ase: pthread_sigmask for SIGPIPE failed: %s\n", strerror (errno));
405 if (!loft_needs_preallocation_mt)
407 loft_needs_preallocation_mt =
true;
412static size_t last_loft_preallocation = 0;
415preallocate_loft (
size_t preallocation)
418 last_loft_preallocation = preallocation;
421 .watermark = last_loft_preallocation / 2,
422 .flags = Loft::PREFAULT_PAGES,
424 loft_set_config (loftcfg);
425 loft_set_notifier (notify_loft_lowmem);
426 loft_grow_preallocate();
433 const bool keep_alive = lstate.phase == LoopState::DISPATCH;
437 loft_needs_preallocation_mt =
false;
438 last_loft_preallocation *= 2;
439 const size_t newalloc = loft_grow_preallocate (last_loft_preallocation);
441 loft_get_config (config);
442 config.
watermark = last_loft_preallocation / 2;
443 loft_set_config (config);
445 MDEBUG (
"Loft preallocation in main thread: %f MB", newalloc / (1024. * 1024));
450prefault_pages (
size_t stacksize,
size_t heapsize)
452 const size_t pagesize =
sysconf (_SC_PAGESIZE);
453 char *heap = (
char*) malloc (heapsize);
455 for (
size_t i = 0; i < heapsize; i += pagesize)
458 char *stack = (
char*) alloca (stacksize);
460 for (
size_t i = 0; i < stacksize; i += pagesize)
465main (
int argc,
char *argv[])
468 using namespace AnsiColors;
471 TaskRegistry::setup_ase (
"AnklangMainProc");
473 mallopt (M_MMAP_MAX, 0);
475 mallopt (M_TRIM_THRESHOLD, -1);
477 prefault_pages ((1024 + 768) * 1024, 64 * 1024 * 1024);
479 preallocate_loft (64 * 1024 * 1024);
481 loft_set_growth_notifier ([] (
size_t total,
size_t needed)
483 warning (
"Loft.BumpAllocator: growing beyond preallocation: totalmem=%u needed=%d\n", total, needed);
487 logging_handle_terminate();
491 if (setpgid (0, 0) < 0)
492 diag (
"Main: setpgid failed: %s", ::strerror (errno));
495 if (!setlocale (LC_ALL,
""))
496 fatal_error (
"setlocale: locale not supported by libc: %s", ::strerror (errno));
499 parse_args (&argc, argv, main_app);
500 logging_configure (arg_ui_mode !=
"none");
507 Preference::load_preferences (
true);
510 if (!
trkn_init (argc, argv, App.no_devices))
511 fatal_error (
"Main: failed to initialize tracktion engine");
513 const auto B1 =
color (BOLD);
514 const auto B0 =
color (BOLD_OFF);
518 if (App.list_drivers)
520 Ase::Driver::EntryVec entries;
521 printout (
"%s",
_(
"Available PCM drivers:\n"));
522 entries = Ase::PcmDriver::list_drivers();
523 std::sort (entries.begin(), entries.end(), [] (
auto &a,
auto &b) { return a.priority < b.priority; });
524 for (
const auto &entry : entries)
526 printout (
" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid +
":",
527 entry.readonly ?
"Input" : entry.writeonly ?
"Output" :
"Duplex",
528 entry.priority, entry.device_name,
529 entry.capabilities.
empty() ?
"" :
"\t" + entry.capabilities +
"\n",
530 entry.device_info.
empty() ?
"" :
"\t" + entry.device_info +
"\n",
531 entry.hints.
empty() ?
"" :
"\t(" + entry.hints +
")\n",
532 entry.notice.
empty() ?
"" :
"\t" + entry.notice +
"\n");
536 printout (
"%s",
_(
"Available MIDI drivers:\n"));
537 entries = Ase::MidiDriver::list_drivers();
538 std::sort (entries.begin(), entries.end(), [] (
auto &a,
auto &b) { return a.priority < b.priority; });
539 for (
const auto &entry : entries)
541 printout (
" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid +
":",
542 entry.readonly ?
"Input" : entry.writeonly ?
"Output" :
"Duplex",
543 entry.priority, entry.device_name,
544 entry.capabilities.
empty() ?
"" :
"\t" + entry.capabilities +
"\n",
545 entry.device_info.
empty() ?
"" :
"\t" + entry.device_info +
"\n",
546 entry.hints.
empty() ?
"" :
"\t(" + entry.hints +
")\n",
547 entry.notice.
empty() ?
"" :
"\t" + entry.notice +
"\n");
556 main_app.engine = &audio_engine;
557 audio_engine.start_threads ();
559 main_loop->exec_dispatcher ([&audio_engine] (
const LoopState &state) ->
bool {
562 case LoopState::PREPARE:
563 return main_rt_jobs_pending() || audio_engine.ipc_pending();
564 case LoopState::CHECK:
565 return main_rt_jobs_pending() || audio_engine.ipc_pending();
566 case LoopState::DISPATCH:
567 audio_engine.ipc_dispatch();
568 main_rt_jobs_process();
577 for (
const auto &filename : App.args)
579 preload_project = ProjectImpl::create (
Path::basename (filename));
580 Error error = Error::NO_MEMORY;
582 error = preload_project->load_project (filename);
583 diag (
"Main: load project: %s: %s", filename,
ase_error_blurb (error));
585 warning (
"%s: failed to load project: %s", filename,
ase_error_blurb (error));
589 const String auth_token = arg_unauth_port > 0 ?
"" : make_auth_string();
590 auto wss = WebSocketServer::create (jsonapi_make_connection, App.jsonapi_logflags, auth_token);
591 main_app.web_socket_server = &*wss;
594 wss->http_alias (
"/Builtin/Controller",
anklang_runpath (RPath::INSTALLDIR,
"/Controller"));
596 wss->http_alias (
"/Builtin/Scripts",
anklang_runpath (RPath::INSTALLDIR,
"/Scripts"));
597 const int xport = arg_unauth_port > 0 ? arg_unauth_port : 0;
598 const String subprotocol =
"";
599 jsonapi_set_subprotocol (subprotocol);
600 if (App.mode == MainApp::SYNTHENGINE && arg_ui_mode !=
"none") {
601 const char *host =
"127.0.0.1";
602 wss->listen (host, xport, [] () { main_loop->quit (-1); });
605 String redirecthtml = webui_create_auth_redirect (
"anklang", wss->listen_port(), auth_token, arg_ui_mode);
607 fatal_error (
"%s: failed to create html redirect file in $HOME", redirecthtml);
608 webui_url =
"file://" + redirecthtml;
609 wss->see_other (webui_url);
611 info (
"Main: WebUI address: %s", webui_url);
612 auto ereason = webui_start_browser (arg_ui_mode, main_loop, webui_url, [] () { main_loop->quit (0); });
614 fatal_error (
"Main: failed to run WebUI: %s: %s", ereason.what, ::strerror (ereason.error));
618 for (
int sigid : { SIGHUP, SIGINT, SIGQUIT, SIGABRT, SIGTERM, SIGSYS }) {
619 main_loop->exec_usignal (sigid, [] (
int8 sig) {
620 info (
"Main: got signal %d: terminate", sig);
622 atquit_terminate (-1, pgid);
625 USignalSource::install_sigaction (sigid);
629 main_loop->exec_usignal (SIGUSR2, [wss] (
int8 sig) {
630 info (
"Main: got signal %d: reset WebSocket", sig);
634 USignalSource::install_sigaction (SIGUSR2);
640 info (
"Main: Start caputure: %s", App.outputfile);
641 App.engine->queue_capture_start (*callbacks, App.outputfile,
true);
642 auto job = [callbacks] () {
643 for (
const auto &callback : *callbacks)
650 if (App.play_autostart && preload_project)
651 main_loop->add ([preload_project] ()
653 info (
"Main: starting playback (auto)");
654 preload_project->start_playback (App.play_autostop);
657 main_loop->exec_dispatcher (handle_autostop);
660 if (App.mode == MainApp::CHECK_INTEGRITY_TESTS)
661 main_loop->add (run_tests_and_quit);
664 const int exitcode = main_loop->run();
666 diag (
"Main: event loop quit: code=%d", exitcode);
670 main_app.web_socket_server =
nullptr;
674 ProjectImpl::force_shutdown_all();
677 audio_engine.set_project (
nullptr);
678 audio_engine.stop_threads();
679 main_loop->iterate_pending();
680 main_app.engine =
nullptr;
685 diag (
"Main: exiting: %d", exitcode);
692main (
int argc,
char *argv[])
695#ifdef ASE_WITH_CPPTRACE
696 CPPTRACE_TRY { r = Ase::main (argc, argv); }
704 cpptrace::from_current_exception().print();
707 r = Ase::main (argc, argv);
715extern "C" __attribute__ ((__noinline__))
void
718 debug (
"foo: %s+%d", s, 0x11111111);
721extern "C" __attribute__ ((__noinline__))
void
724 debug (
"foo: %s+%d", s, 0x11111111);
731 bool seen_engine_job =
false, seen_deleter =
false;
740 seen_engine_job =
true;
744 main_rt_jobs +=
RtCall ([]() { printerr (
" job_queue_tests: Hello %s!\n",
"void()"); });
745 main_rt_jobs +=
RtCall ((
void(*)(
const char*)) [] (
const char *a) { printerr (
" job_queue_tests: Hello %s!\n", a); },
"RtJobQueue");
746 struct Test1 {
const char *a_;
void print() { printerr (
" job_queue_tests: Hello %s!\n", a_); } };
747 static Test1 test1 {
"MemFn" };
753 main_loop->iterate (
false);
Lock-free stack with atomic push() and pop_all operations.
Main handle for AudioProcessor administration and audio rendering.
JobQueue async_jobs
Executed asynchronously, may modify AudioProcessor objects.
static String priority_string(uint priority)
Return string which represents the given priority mask.
KeccakCryptoRng - A KeccakF1600 based cryptographic quality pseudo-random number generator.
uint64_t random()
Generate uniformly distributed 64 bit pseudo random number.
static LoopP current()
Return the thread-local singleton loop, created on first call.
Marsaglia multiply-with-carry generator, period ca 2^255.
#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.
#define TEST_INTEGRITY(FUNC)
Register func as an integrity test.
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.
uint64_t uint64
A 64-bit unsigned integer, use PRI*64 in format strings.
String string_to_hex(const String &input)
Convert bytes in string input to hexadecimal numbers.
int8_t int8
An 8-bit signed integer.
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 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.
RtJobQueue main_rt_jobs
Queue a callback for the event loop without invoking malloc(), addition is obstruction free.
size_t preallocate
Amount of preallocated available memory.
uint64 timestamp_realtime()
Return the current time as uint64 in µseconds.
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)
Wrap simple callback pointers, without using malloc (obstruction free).
Add a simple callback to the event loop, without using malloc (obstruction free).