Anklang-0.3.0.dev835+g24d8ae08 anklang-0.3.0.dev835+g24d8ae08
ASE — Anklang Sound Engine (C++)

« « « Anklang Documentation
Loading...
Searching...
No Matches
main.cc
Go to the documentation of this file.
1 // This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
2#include "main.hh"
3#include "api.hh"
4#include "path.hh"
5#include "utils.hh"
6#include "jsonapi.hh"
7#include "driver.hh"
8#include "project.hh"
9#include "loft.hh"
10#include "compress.hh"
11#include "webui.hh"
12#include "server.hh"
13#include "internal.hh"
14#include "testing.hh"
15
16#include <limits.h>
17#include <stdlib.h>
18#include <unistd.h>
19#include <signal.h>
20#include <malloc.h>
21#include <unistd.h>
22#include <fcntl.h>
23#ifdef ASE_WITH_CPPTRACE
24#include <cpptrace/from_current.hpp>
25#endif
26
27#include "trkn.hh"
28
29#undef B0 // undo pollution from termios.h
30
31#define MDEBUG(...) Ase::debug ("memory", __VA_ARGS__)
32
33namespace Ase {
34
36 MainAppImpl ();
37};
38MainAppImpl main_app;
39const MainApp &App = main_app;
40
41MainAppImpl::MainAppImpl()
42{}
43
44LoopP main_loop = Loop::current();
45static String arg_ui_mode;
46static int arg_unauth_port = 0;
47
48// == JobQueue ==
49static void
50call_main_loop (const std::function<void()> &fun)
51{
52 main_loop->add (fun);
53}
54JobQueue main_jobs (call_main_loop);
55
56// == MainConfig and arguments ==
57static void
58print_usage (bool help)
59{
60 if (!help)
61 {
62 printout ("%s %s\n", executable_name(), ase_version());
63 printout ("Build: %s\n", ase_build_id());
64 return;
65 }
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 (" --list-ui-tests List all TypeScript UI test function names\n");
77 printout (" --norc Prevent loading of any rc files\n");
78 printout (" --ui-test=test Specify TypeScript UI test(s) to run (comma-separated)\n");
79 printout (" --play-autostart Automatically start playback of `project.anklang`\n");
80 printout (" --rand64 Produce 64bit random numbers on stdout\n");
81 printout (" --test[=test] Run specific test(s) (comma-separated)\n");
82 printout (" --unauth-dev=NUM Open an unauthenticated websocket port for testing\n");
83 printout (" --headless[=bool] Run browser in headless mode (default for --ui-test)\n");
84 printout (" --ui <none|chromium|google-chrome|htmlgui>\n");
85 printout (" Open GUI in web browser [htmlgui]\n");
86 printout (" --version Print program version\n");
87 printout (" -M mididriver Force use of <mididriver>\n");
88 printout (" -P pcmdriver Force use of <pcmdriver>\n");
89 printout (" -o wavfile Capture output to OPUS/FLAC/WAV file\n");
90 printout (" -t <time> Automatically play and stop after <time> has passed\n"); // -t <time>[{,|;}tailtime]
91 printout ("Options set via $ASE_DEBUG:\n");
92 printout (" :no-logfile: Disable logging to ~/.cache/anklang/ instead of stderr\n");
93}
94
96static bool
97parse_option_arg (const char *option, char **argv, unsigned *ith, const char **argp)
98{
99 const size_t l = strlen (option);
100 if (strncmp (option, argv[*ith], l) == 0) {
101 *argp = argv[*ith] + l;
102 argv[*ith] = nullptr;
103 if ((*argp)[0] == '=')
104 *argp += 1;
105 else if ((*argp)[0] == 0) {
106 *ith += 1;
107 *argp = argv[*ith] ? argv[*ith] : "";
108 argv[*ith] = nullptr;
109 }
110 return true;
111 }
112 return false;
113}
114
115// 1:ERROR 2:FAILED+REJECT 4:IO 8:MESSAGE 16:GET 256:BINARY
116static constexpr int jsipc_logflags = 1 | 2 | 4 | 8 | 16;
117static constexpr int jsbin_logflags = 1 | 256;
118
119static StringS check_test_names;
120static StringS ui_test_names;
121
122static void
123parse_args (int *argcp, char **argv, MainAppImpl &config)
124{
125 if (0) // allow jsipc logging via ASE_DEBUG ?
126 {
127 config.jsonapi_logflags |= debug_key_enabled ("jsbin") ? jsbin_logflags : 0;
128 config.jsonapi_logflags |= debug_key_enabled ("jsipc") ? jsipc_logflags : 0;
129 }
130
131 config.norc = false;
132 bool sep = false; // -- separator
133 std::string default_ui_mode = "htmlgui";
134 const uint argc = *argcp;
135 for (uint i = 1; i < argc; i++)
136 {
137 const char *optarg = nullptr;
138 if (sep)
139 config.args.push_back (argv[i]);
140 else if (strcmp (argv[i], "--fatal-warnings") == 0 || strcmp (argv[i], "--g-fatal-warnings") == 0)
142 else if (strcmp ("--disable-randomization", argv[i]) == 0)
143 config.allow_randomization = false;
144 else if (strcmp ("--norc", argv[i]) == 0)
145 config.norc = true;
146 else if (strcmp ("--rand64", argv[i]) == 0)
147 {
148 FastRng prng;
149 constexpr int N = 8192;
150 uint64_t buffer[N];
151 while (1)
152 {
153 for (size_t i = 0; i < N; i++)
154 buffer[i] = prng.next();
155 fwrite (buffer, sizeof (buffer[0]), N, stdout);
156 }
157 exit (0);
158 }
159 else if (strcmp ("--check", argv[i]) == 0)
160 {
161 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
163 printerr ("CHECK_INTEGRITY_TESTS…\n");
164 default_ui_mode = "none";
165 }
166 else if (strcmp ("--list-tests", argv[i]) == 0)
167 {
169 for (const auto &t : Test::list_tests())
170 ids.push_back (t.ident);
171 std::sort (ids.begin(), ids.end());
172 for (const auto &t : ids)
173 printout ("%s\n", t);
174 exit (0);
175 }
176 else if (strcmp ("--list-ui-tests", argv[i]) == 0)
177 {
178 const String testfile = anklang_runpath (RPath::INSTALLDIR, "/ui/assets/testcalls-list.txt");
179 if (!Path::check (testfile, "e"))
180 fatal_error ("missing UI test list: %s", testfile);
181 const String content = Path::stringread (testfile);
182 StringS lines = string_split (content, "\n");
183 for (const String &line : lines)
184 if (!line.empty () || string_startswith (line, "#"))
185 printout ("%s\n", line);
186 exit (0);
187 }
188 else if (strcmp ("--ui-test", argv[i]) == 0 || strncmp ("--ui-test=", argv[i], 9) == 0)
189 {
190 const char *eq = strchr (argv[i], '=');
191 const char *arg = eq ? eq + 1 : i+1 < argc ? argv[++i] : nullptr;
192 if (arg) {
193 const auto tests = string_split (arg, ",");
194 for (const auto &t : tests)
195 ui_test_names.push_back (t);
196 } else
197 ui_test_names.push_back ("all");
198 config.headless = true;
199 }
200 else if (strcmp ("--headless", argv[i]) == 0 || strncmp ("--headless=", argv[i], 10) == 0)
201 {
202 const char *eq = strchr (argv[i], '=');
203 config.headless = eq ? string_to_bool (eq + 1) : true;
204 }
205 else if (strcmp ("--test", argv[i]) == 0 || strncmp ("--test=", argv[i], 7) == 0)
206 {
207 const char *eq = strchr (argv[i], '=');
208 const char *arg = eq ? eq + 1 : i+1 < argc ? argv[++i] : nullptr;
209 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
211 if (arg) {
212 const auto tests = string_split (arg, ",");
213 for (const auto &t : tests)
214 check_test_names.push_back (t);
215 }
216 default_ui_mode = "none";
217 }
218 else if (argv[i] == String ("--blake3") && i + 1 < size_t (argc))
219 {
220 argv[i++] = nullptr;
221 String hash = blake3_hash_file (argv[i]);
222 if (hash.empty())
223 printerr ("%s: failed to read: %s\n", argv[i], strerror (errno));
224 else
225 printout ("%s\n", string_to_hex (hash));
226 exit (hash == "");
227 }
228 else if (strcmp ("--jsonts", argv[i]) == 0) {
229 if (getenv ("ASE_JSONTS") == nullptr)
230 fatal_error ("%s: environment must contain ASE_JSONTS for --jsonts", argv[0]);
231 printout ("%s\n", Jsonipc::g_binding_printer->finish());
232 exit (0);
233 } else if (strcmp ("--jsipc", argv[i]) == 0)
234 config.jsonapi_logflags |= jsipc_logflags;
235 else if (strcmp ("--jsbin", argv[i]) == 0)
236 config.jsonapi_logflags |= jsbin_logflags;
237 else if (strcmp ("--list-drivers", argv[i]) == 0)
238 config.list_drivers = true;
239 else if (strcmp ("-M", argv[i]) == 0 && i + 1 < size_t (argc))
240 {
241 argv[i++] = nullptr;
242 config.midi_override = argv[i];
243 }
244 else if (strcmp ("-P", argv[i]) == 0 && i + 1 < size_t (argc))
245 {
246 argv[i++] = nullptr;
247 config.pcm_override = argv[i];
248 }
249 else if (strcmp ("--no-devices", argv[i]) == 0)
250 {
251 config.no_devices = true;
252 }
253 else if (strcmp ("-h", argv[i]) == 0 ||
254 strcmp ("--help", argv[i]) == 0)
255 {
256 print_usage (true);
257 exit (0);
258 }
259 else if (strcmp ("--version", argv[i]) == 0)
260 {
261 print_usage (false);
262 exit (0);
263 }
264 else if (argv[i] == String ("-o") && i + 1 < size_t (argc))
265 {
266 argv[i++] = nullptr;
267 config.outputfile = argv[i];
268 }
269 else if (argv[i] == String ("--play-autostart"))
270 {
271 config.play_autostart = true;
272 default_ui_mode = "none";
273 }
274 else if (parse_option_arg ("--unauth-dev", argv, &i, &optarg))
275 {
276 arg_unauth_port = string_to_int (optarg);
277 default_ui_mode = "wait";
278 }
279 else if (argv[i] == String ("-t") && i + 1 < size_t (argc))
280 {
281 config.play_autostart = true;
282 argv[i++] = nullptr;
283 config.play_autostop = string_to_seconds (argv[i]);
284 default_ui_mode = "none";
285 }
286 else if (parse_option_arg ("--ui", argv, &i, &optarg))
287 {
288 arg_ui_mode = optarg;
289 }
290 else if (argv[i] == String ("--") && !sep)
291 sep = true;
292 else if (argv[i][0] == '-' && !sep)
293 fatal_error ("invalid command line argument: %s", argv[i]);
294 else
295 config.args.push_back (argv[i]);
296 argv[i] = nullptr;
297 }
298 if (arg_ui_mode.empty())
299 arg_ui_mode = default_ui_mode;
300 if (*argcp > 1)
301 {
302 uint e = 1;
303 for (uint i = 1; i < argc; i++)
304 if (argv[i])
305 {
306 argv[e++] = argv[i];
307 if (i >= e)
308 argv[i] = nullptr;
309 }
310 *argcp = e;
311 }
312}
313
314static String
315make_auth_string()
316{
317 const char *const c52 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
318 /* We use WebScoket subprotocol randomization as authentication, so:
319 * a) Authentication happens *before* message interpretation, so an
320 * unauthenticated sender cannot cause crahses via e.g. rapidjson exceptions.
321 * b) To serve as working authentication measure, the subprotocol random string
322 * must be cryptographically-secure.
323 */
324 KeccakCryptoRng csprng;
325 String auth = "sessC";
326 for (size_t i = 0; i < 23; ++i)
327 auth += c52[csprng.random() % 52]; // each step adds 5.7 bits
328 return auth;
329}
330
331static void
332run_tests_and_quit ()
333{
334 if (check_test_names.empty())
335 Test::run();
336 else
337 Test::run (check_test_names);
338 main_loop->quit (0);
339}
340
341void
343{
344 LoopP loop = main_loop;
345 if (loop)
346 loop->wakeup();
347}
348
349static std::atomic<bool> seen_autostop = false;
350
351// Lock and obstruction-free autostop trigger.
352void
354{
355 if (!seen_autostop)
356 {
357 seen_autostop = true;
359 }
360}
361
362static bool
363handle_autostop (const LoopState &state)
364{
365 switch (state.phase)
366 {
367 case LoopState::PREPARE: return seen_autostop;
368 case LoopState::CHECK: return seen_autostop;
369 case LoopState::DISPATCH:
370 info ("Main: stopping playback (auto)");
371 main_loop->quit (0);
372 return true; // keep alive
373 default: ;
374 }
375 return false;
376}
377
378static void
379init_sigpipe()
380{
381 // don't die if we write() data to a process and that process dies (i.e. jackd)
382 sigset_t signal_mask;
383 sigemptyset (&signal_mask);
384 sigaddset (&signal_mask, SIGPIPE);
385
386 int rc = pthread_sigmask (SIG_BLOCK, &signal_mask, NULL);
387 if (rc != 0)
388 Ase::warning ("Ase: pthread_sigmask for SIGPIPE failed: %s\n", strerror (errno));
389}
390
391static std::atomic<bool> loft_needs_preallocation_mt = false;
392
393// handle watermark underrun notifications
394static void
395notify_loft_lowmem ()
396{
397 if (!loft_needs_preallocation_mt)
398 {
399 loft_needs_preallocation_mt = true;
401 }
402}
403
404static size_t last_loft_preallocation = 0;
405
406static void
407preallocate_loft (size_t preallocation)
408{
409 using namespace Ase;
410 last_loft_preallocation = preallocation;
411 LoftConfig loftcfg = {
412 .preallocate = last_loft_preallocation,
413 .watermark = last_loft_preallocation / 2,
414 .flags = Loft::PREFAULT_PAGES,
415 };
416 loft_set_config (loftcfg);
417 loft_set_notifier (notify_loft_lowmem);
418 loft_grow_preallocate();
419}
420
421static bool
422dispatch_loft_lowmem (const Ase::LoopState &lstate)
423{
424 using namespace Ase;
425 const bool keep_alive = lstate.phase == LoopState::DISPATCH;
426 // generally, dispatch logic may only run in LoopState::DISPATCH, but this handler
427 // makes a rare exception, because we try to get ahead of concurrently runnint RT-threads...
428 return_unless (loft_needs_preallocation_mt, keep_alive);
429 loft_needs_preallocation_mt = false;
430 last_loft_preallocation *= 2;
431 const size_t newalloc = loft_grow_preallocate (last_loft_preallocation);
432 LoftConfig config;
433 loft_get_config (config);
434 config.watermark = last_loft_preallocation / 2;
435 loft_set_config (config);
436 if (newalloc > 0)
437 MDEBUG ("Loft preallocation in main thread: %f MB", newalloc / (1024. * 1024));
438 return keep_alive;
439}
440
441static void
442prefault_pages (size_t stacksize, size_t heapsize)
443{
444 const size_t pagesize = sysconf (_SC_PAGESIZE);
445 char *heap = (char*) malloc (heapsize);
446 if (heap)
447 for (size_t i = 0; i < heapsize; i += pagesize)
448 heap[i] = 1;
449 free (heap);
450 char *stack = (char*) alloca (stacksize);
451 if (stack)
452 for (size_t i = 0; i < stacksize; i += pagesize)
453 stack[i] = 1;
454}
455
456static int
457main (int argc, char *argv[])
458{
459 using namespace Ase;
460 using namespace AnsiColors;
461
462 // setup thread identifier
463 TaskRegistry::setup_ase ("AnklangMainProc");
464 // use malloc to serve allocations via sbrk only (avoid mmap)
465 mallopt (M_MMAP_MAX, 0);
466 // avoid releasing sbrk memory back to the system (reduce page faults)
467 mallopt (M_TRIM_THRESHOLD, -1);
468 // reserve large sbrk area and reduce page faults for heap and stack
469 prefault_pages ((1024 + 768) * 1024, 64 * 1024 * 1024);
470 // preallocate memory for lock-free allocator
471 preallocate_loft (64 * 1024 * 1024);
472 // warn if preallocation is not sufficient
473 loft_set_growth_notifier ([] (size_t total, size_t needed)
474 {
475 warning ("Loft.BumpAllocator: growing beyond preallocation: totalmem=%u needed=%d\n", total, needed);
476 });
477
478 // print stack trace for uncaught exceptions
479 logging_handle_terminate();
480
481 // SIGPIPE init: needs to be done before any child thread is created
482 init_sigpipe();
483 if (setpgid (0, 0) < 0)
484 diag ("Main: setpgid failed: %s", ::strerror (errno));
485
486 // apply user locale
487 if (!setlocale (LC_ALL, ""))
488 fatal_error ("setlocale: locale not supported by libc: %s", ::strerror (errno));
489
490 // parse args and config
491 parse_args (&argc, argv, main_app);
492 main_app.ui_tests = ui_test_names;
493 const int socket_port = arg_unauth_port > 0 ? arg_unauth_port : 0;
494 const char *socket_host = "127.0.0.1";
495 const auto socket_info = WebSocketServer::bind_port (socket_host, socket_port);
496 logging_configure (arg_ui_mode != "none" ? string_format ("%u", socket_info.port) : "");
497
498 // handle loft preallocation needs
499 main_loop->exec_dispatcher (dispatch_loft_lowmem, LoopPriority::SYSALLOC);
500
501 // load preferences unless --norc was given
502 if (!App.norc)
503 Preference::load_preferences (true);
504
505 // Ensure Ase server exists
506 ServerImpl::instancep();
507
508 // tracktion initialisation
509 if (!trkn_init (argc, argv, App.no_devices))
510 fatal_error ("Main: failed to initialize tracktion engine");
511
512 const auto B1 = color (BOLD);
513 const auto B0 = color (BOLD_OFF);
514
515 // load drivers and dump device list
517 if (App.list_drivers)
518 {
519 Ase::Driver::EntryVec entries;
520 printout ("%s", _("Available PCM drivers:\n"));
521 entries = Ase::PcmDriver::list_drivers();
522 std::sort (entries.begin(), entries.end(), [] (auto &a, auto &b) { return a.priority < b.priority; });
523 for (const auto &entry : entries)
524 {
525 printout (" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid + ":",
526 entry.readonly ? "Input" : entry.writeonly ? "Output" : "Duplex",
527 entry.priority, entry.device_name,
528 entry.capabilities.empty() ? "" : "\t" + entry.capabilities + "\n",
529 entry.device_info.empty() ? "" : "\t" + entry.device_info + "\n",
530 entry.hints.empty() ? "" : "\t(" + entry.hints + ")\n",
531 entry.notice.empty() ? "" : "\t" + entry.notice + "\n");
532 if (debug_key_enabled ("driver"))
533 printerr (" %08x: %s\n", entry.priority, Driver::priority_string (entry.priority));
534 }
535 printout ("%s", _("Available MIDI drivers:\n"));
536 entries = Ase::MidiDriver::list_drivers();
537 std::sort (entries.begin(), entries.end(), [] (auto &a, auto &b) { return a.priority < b.priority; });
538 for (const auto &entry : entries)
539 {
540 printout (" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid + ":",
541 entry.readonly ? "Input" : entry.writeonly ? "Output" : "Duplex",
542 entry.priority, entry.device_name,
543 entry.capabilities.empty() ? "" : "\t" + entry.capabilities + "\n",
544 entry.device_info.empty() ? "" : "\t" + entry.device_info + "\n",
545 entry.hints.empty() ? "" : "\t(" + entry.hints + ")\n",
546 entry.notice.empty() ? "" : "\t" + entry.notice + "\n");
547 if (debug_key_enabled ("driver"))
548 printerr (" %08x: %s\n", entry.priority, Driver::priority_string (entry.priority));
549 }
550 return 0;
551 }
552
553 // load projects
554 ProjectImplP preload_project;
555 for (const auto &filename : App.args)
556 {
557 preload_project = ProjectImpl::create (Path::basename (filename));
558 Error error = Error::NO_MEMORY;
559 if (preload_project)
560 error = preload_project->load_project (filename);
561 diag ("Main: load project: %s: %s", filename, ase_error_blurb (error));
562 if (!!error)
563 warning ("%s: failed to load project: %s", filename, ase_error_blurb (error));
564 }
565
566 // open Jsonapi socket
567 const String auth_token = arg_unauth_port > 0 ? "" : make_auth_string();
568 auto wss = WebSocketServer::create (jsonapi_make_connection, App.jsonapi_logflags, auth_token);
569 main_app.web_socket_server = &*wss;
570 wss->http_dir (anklang_runpath (RPath::INSTALLDIR, "/ui/"));
571 // wss->http_alias ("/User/Controller", anklang_home_dir ("/Controller"));
572 wss->http_alias ("/Builtin/Controller", anklang_runpath (RPath::INSTALLDIR, "/Controller"));
573 // wss->http_alias ("/User/Scripts", anklang_home_dir ("/Scripts"));
574 wss->http_alias ("/Builtin/Scripts", anklang_runpath (RPath::INSTALLDIR,"/Scripts"));
575 const String subprotocol = ""; // make_auth_string()
576 jsonapi_set_subprotocol (subprotocol);
577 if (App.mode == MainApp::SYNTHENGINE && arg_ui_mode != "none") {
578 wss->listen (socket_info, [] () { main_loop->quit (-1); });
579 std::string webui_url = wss->url();
580 if (!socket_port) {
581 String redirecthtml = webui_create_auth_redirect ("anklang", wss->listen_port(), auth_token, arg_ui_mode);
582 if (errno)
583 fatal_error ("%s: failed to create html redirect file in $HOME", redirecthtml);
584 webui_url = "file://" + redirecthtml;
585 wss->see_other (webui_url);
586 }
587 info ("Main: WebUI address: %s", webui_url);
588
589 WebuiFlags webui_flags = main_app.headless ? WebuiFlags::HEADLESS : WebuiFlags::NONE;
590 if (main_app.ui_tests.size())
591 webui_flags = webui_flags | WebuiFlags::STDIO_REDIRECT | WebuiFlags::CONSOLE_LOGS;
592 auto ereason = webui_start_browser (arg_ui_mode, main_loop, webui_url, [] () { main_loop->quit (0); }, webui_flags);
593
594 if (ereason.error)
595 fatal_error ("Main: failed to run WebUI: %s: %s", ereason.what, ::strerror (ereason.error));
596 }
597
598 // run atquit handler on SIGHUP SIGINT
599 for (int sigid : { SIGHUP, SIGINT, SIGQUIT, SIGABRT, SIGTERM, SIGSYS }) {
600 main_loop->exec_usignal (sigid, [] (int8 sig) {
601 info ("Main: got signal %d: terminate", sig);
602 const pid_t pgid = getpgrp();
603 atquit_terminate (-1, pgid);
604 return false;
605 });
606 USignalSource::install_sigaction (sigid);
607 }
608
609 // catch SIGUSR2 to close sockets
610 main_loop->exec_usignal (SIGUSR2, [wss] (int8 sig) {
611 info ("Main: got signal %d: reset WebSocket", sig);
612 wss->reset();
613 return true;
614 });
615 USignalSource::install_sigaction (SIGUSR2);
616
617 // start output capturing
618 if (App.outputfile)
619 ; // TODO: implement capturing
620
621 // start auto play
622 if (App.play_autostart && preload_project)
623 main_loop->add ([preload_project] ()
624 {
625 info ("Main: starting playback (auto)");
626 preload_project->start_playback (App.play_autostop);
628 // handle automatic shutdown
629 main_loop->exec_dispatcher (handle_autostop);
630
631 // prune old log files after some time
632 main_loop->add ([] ()
633 {
634 logging_prune_old_logs (3.0 * 24.0 * 60.0 * 60.0);
636
637 // run test suite
638 if (App.mode == MainApp::CHECK_INTEGRITY_TESTS)
639 main_loop->add (run_tests_and_quit);
640
641 // run main event loop and catch SIGUSR2
642 const int exitcode = main_loop->run();
643 assert_return (main_loop, -1); // ptr must be kept around
644 diag ("Main: event loop quit: code=%d", exitcode);
645
646 // cleanup
647 wss->shutdown(); // close socket, allow no more calls
648 main_app.web_socket_server = nullptr;
649 wss = nullptr;
650
651 // deactivate any projects, releases Audio resources
652 ProjectImpl::force_shutdown_all();
653
654 // halt audio engine, join its threads, dispatch cleanups
655 main_loop->iterate_pending();
656
657 // shutdown tracktion *after* main loop stopped
658 trkn_shutdown ();
659
660 diag ("Main: exiting: %d", exitcode);
661 return exitcode;
662}
663
664} // Ase
665
666int
667main (int argc, char *argv[])
668{
669 int r = -128;
670#ifdef ASE_WITH_CPPTRACE
671 CPPTRACE_TRY { r = Ase::main (argc, argv); }
672 CPPTRACE_CATCH (const std::exception& e) {
673 std::string msg = "Exception: ";
674 msg += e.what();
675 msg += "\n";
676 fflush (stdout);
677 fputs (msg.c_str(), stderr);
678 fflush (stderr);
679 cpptrace::from_current_exception().print();
680 }
681#else
682 r = Ase::main (argc, argv);
683#endif
684 return r;
685}
T c_str(T... args)
static String priority_string(uint priority)
Return string which represents the given priority mask.
Definition driver.cc:31
static LoopP current()
Return the thread-local singleton loop, created on first call.
Definition loop.cc:306
T empty(T... args)
exit
fflush
fputs
free
fwrite
optarg
getpgrp
#define assert_return(expr,...)
Return from the current function if expr is unmet and issue an assertion warning.
Definition internal.hh:29
#define return_unless(cond,...)
Return silently if cond does not evaluate to true with return value ...
Definition internal.hh:73
#define _(...)
Retrieve the translation of a C or C++ string.
Definition internal.hh:18
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().
Definition platform.cc:191
String basename(const String &path)
Strips all directory components from path and returns the resulting file name.
Definition path.cc:68
bool check(const String &file, const String &mode)
Definition path.cc:625
int run(void)
Run all registered tests.
Definition testing.cc:264
The Anklang C++ API namespace.
Definition api.hh:9
std::string string_format(const char *format, const Args &...args) __attribute__((__format__(__printf__
Format a string similar to sprintf(3) with support for std::string and std::ostringstream convertible...
bool trkn_init(int argc, char *argv[], bool nodevs)
Setup tracktion and tracktion::engine.
Definition trkn.cc:99
StringS string_split(const String &string, const String &splitter, size_t maxn)
Split a string, using splitter as delimiter.
Definition strings.cc:343
String string_to_hex(const String &input)
Convert bytes in string input to hexadecimal numbers.
Definition strings.cc:1171
void logging_prune_old_logs(double age_seconds)
Delete log files older than age seconds.
Definition logging.cc:233
int8_t int8
An 8-bit signed integer.
Definition cxxaux.hh:26
std::vector< String > StringS
Convenience alias for a std::vector<std::string>.
Definition cxxaux.hh:36
JobQueue main_jobs(call_main_loop)
Execute a job callback in the event loop.
Definition main.hh:44
Error
Enum representing Error states.
Definition api.hh:22
const char * ase_error_blurb(Error error)
Describe Error condition.
Definition server.cc:270
std::string anklang_runpath(RPath rpath, const String &segment)
Retrieve various resource paths at runtime.
Definition platform.cc:58
double string_to_seconds(const String &string, double fallback)
Parse string into seconds.
Definition strings.cc:773
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.
Definition strings.cc:578
void main_loop_wakeup()
Wake up the event loop.
Definition main.cc:342
bool logging_fatal_warnings
Global flag to cause the program to abort on warnings.
Definition logging.cc:304
@ IDLE
Mildly important, used for background tasks.
@ SYSALLOC
Internal maintenance, don't use.
const char * ase_version()
Provide a string containing the package version.
Definition platform.cc:803
std::string String
Convenience alias for std::string.
Definition cxxaux.hh:35
std::string executable_name()
Retrieve the name part of executable_path().
Definition platform.cc:742
bool string_to_bool(const String &string, bool fallback)
Interpret a string as boolean value.
Definition strings.cc:467
void main_loop_autostop_mt()
Stop the event loop after a timeout.
Definition main.cc:353
bool debug_key_enabled(const char *conditional) noexcept
Check if conditional is enabled by $ASE_DEBUG.
Definition logging.cc:320
uint32_t uint
Provide 'uint' as convenience type.
Definition cxxaux.hh:18
void load_registered_drivers()
Load all registered drivers.
Definition driver.cc:76
size_t preallocate
Amount of preallocated available memory.
Definition loft.hh:45
size_t watermark
Watermark to trigger async preallocation.
Definition loft.hh:46
bool string_startswith(const String &string, const String &fragment)
Returns whether string starts with fragment.
Definition strings.cc:846
const char * ase_build_id()
Provide a string containing the ASE library build id.
Definition platform.cc:809
Configuration for Loft allocations.
Definition loft.hh:44
size_t hash(size_t seed, const T &v)
pthread_sigmask
T push_back(T... args)
sigaddset
sigemptyset
T size(T... args)
T sort(T... args)
typedef uint64_t
strchr
strlen
typedef pid_t
sysconf
T what(T... args)