Anklang-0.3.0.dev595+g65331842 anklang-0.3.0.dev595+g65331842
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 "engine.hh"
9#include "project.hh"
10#include "loft.hh"
11#include "compress.hh"
12#include "webui.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#undef B0 // undo pollution from termios.h
28
29#define MDEBUG(...) Ase::debug ("memory", __VA_ARGS__)
30
31namespace Ase {
32
34 MainAppImpl ();
35};
36MainAppImpl main_app;
37const MainApp &App = main_app;
38
39MainAppImpl::MainAppImpl()
40{}
41
42MainLoopP main_loop;
43static String arg_ui_mode;
44static int arg_unauth_port = 0;
45
46// == JobQueue ==
47static void
48call_main_loop (const std::function<void()> &fun)
49{
50 main_loop->exec_callback (fun);
51}
52JobQueue main_jobs (call_main_loop);
53
54// == RtCall::Callable ==
55struct RtCallJob {
56 explicit RtCallJob (const RtCall &ucall) : call (ucall) {}
57 LoftPtr<RtCallJob> loftptr;
58 std::atomic<RtCallJob*> next = nullptr;
59 RtCall call;
60};
61static inline std::atomic<RtCallJob*>&
62atomic_next_ptrref (RtCallJob *j)
63{
64 return j->next;
65}
66
67static AtomicIntrusiveStack<RtCallJob> main_rt_jobs_;
69
70void
71RtJobQueue::operator+= (const RtCall &call)
72{
73 LoftPtr<RtCallJob> loftptr = loft_make_unique<RtCallJob> (call);
74 RtCallJob *const calljob = &*loftptr;
75 calljob->loftptr = std::move (loftptr); // keeps itself alive
76 const bool was_empty = main_rt_jobs_.push (calljob);
77 if (was_empty)
78 main_loop_wakeup();
79}
80
81static bool
82main_rt_jobs_pending()
83{
84 return !main_rt_jobs_.empty();
85}
86
87static void
88main_rt_jobs_process()
89{
90 RtCallJob *calljob = main_rt_jobs_.pop_reversed();
91 while (calljob) {
92 LoftPtr<RtCallJob> loftptr = std::move (calljob->loftptr); // assume ownership
93 calljob = calljob->next;
94 loftptr->call.invoke();
95 }
96}
97
98// == MainConfig and arguments ==
99static void
100print_usage (bool help)
101{
102 if (!help)
103 {
104 printout ("%s %s\n", executable_name(), ase_version());
105 printout ("Build: %s\n", ase_build_id());
106 return;
107 }
108 printout ("Usage: %s [OPTIONS] [project.anklang]\n", executable_name());
109 printout (" --check Run integrity tests\n");
110 printout (" --disable-randomization Test mode for deterministic tests\n");
111 printout (" --fatal-warnings Abort on warnings and failing assertions\n");
112 printout (" --help Print program usage and options\n");
113 printout (" --jsbin Print Javascript IPC & binary messages\n");
114 printout (" --jsipc Print Javascript IPC messages\n");
115 printout (" --jsonts Print TypeScript bindings\n");
116 printout (" --list-drivers Print PCM and MIDI drivers\n");
117 printout (" --list-tests List all test names\n");
118 printout (" --norc Prevent loading of any rc files\n");
119 printout (" --play-autostart Automatically start playback of `project.anklang`\n");
120 printout (" --rand64 Produce 64bit random numbers on stdout\n");
121 printout (" --test[=test] Run specific tests\n");
122 printout (" --unauth-dev=NUM Open an unauthenticated websocket port for testing\n");
123 printout (" --ui <none|chromium|google-chrome|htmlgui>\n");
124 printout (" Open GUI in web browser [htmlgui]\n");
125 printout (" --version Print program version\n");
126 printout (" -M mididriver Force use of <mididriver>\n");
127 printout (" -P pcmdriver Force use of <pcmdriver>\n");
128 printout (" -o wavfile Capture output to OPUS/FLAC/WAV file\n");
129 printout (" -t <time> Automatically play and stop after <time> has passed\n"); // -t <time>[{,|;}tailtime]
130 printout ("Options set via $ASE_DEBUG:\n");
131 printout (" :no-logfile: Disable logging to ~/.cache/anklang/ instead of stderr\n");
132}
133
135static bool
136parse_option_arg (const char *option, char **argv, unsigned *ith, const char **argp)
137{
138 const size_t l = strlen (option);
139 if (strncmp (option, argv[*ith], l) == 0) {
140 *argp = argv[*ith] + l;
141 argv[*ith] = nullptr;
142 if ((*argp)[0] == '=')
143 *argp += 1;
144 else if ((*argp)[0] == 0) {
145 *ith += 1;
146 *argp = argv[*ith] ? argv[*ith] : "";
147 argv[*ith] = nullptr;
148 }
149 return true;
150 }
151 return false;
152}
153
154// 1:ERROR 2:FAILED+REJECT 4:IO 8:MESSAGE 16:GET 256:BINARY
155static constexpr int jsipc_logflags = 1 | 2 | 4 | 8 | 16;
156static constexpr int jsbin_logflags = 1 | 256;
157
158static StringS check_test_names;
159
160static void
161parse_args (int *argcp, char **argv, MainAppImpl &config)
162{
163 if (0) // allow jsipc logging via ASE_DEBUG ?
164 {
165 config.jsonapi_logflags |= debug_key_enabled ("jsbin") ? jsbin_logflags : 0;
166 config.jsonapi_logflags |= debug_key_enabled ("jsipc") ? jsipc_logflags : 0;
167 }
168
169 config.norc = false;
170 bool sep = false; // -- separator
171 std::string default_ui_mode = "htmlgui";
172 const uint argc = *argcp;
173 for (uint i = 1; i < argc; i++)
174 {
175 const char *optarg = nullptr;
176 if (sep)
177 config.args.push_back (argv[i]);
178 else if (strcmp (argv[i], "--fatal-warnings") == 0 || strcmp (argv[i], "--g-fatal-warnings") == 0)
180 else if (strcmp ("--disable-randomization", argv[i]) == 0)
181 config.allow_randomization = false;
182 else if (strcmp ("--norc", argv[i]) == 0)
183 config.norc = true;
184 else if (strcmp ("--rand64", argv[i]) == 0)
185 {
186 FastRng prng;
187 constexpr int N = 8192;
188 uint64_t buffer[N];
189 while (1)
190 {
191 for (size_t i = 0; i < N; i++)
192 buffer[i] = prng.next();
193 fwrite (buffer, sizeof (buffer[0]), N, stdout);
194 }
195 exit (0);
196 }
197 else if (strcmp ("--check", argv[i]) == 0)
198 {
199 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
201 printerr ("CHECK_INTEGRITY_TESTS…\n");
202 default_ui_mode = "none";
203 }
204 else if (strcmp ("--list-tests", argv[i]) == 0)
205 {
207 for (const auto &t : Test::list_tests())
208 ids.push_back (t.ident);
209 std::sort (ids.begin(), ids.end());
210 for (const auto &t : ids)
211 printout ("%s\n", t);
212 exit (0);
213 }
214 else if (strcmp ("--test", argv[i]) == 0 || strncmp ("--test=", argv[i], 7) == 0)
215 {
216 const char *eq = strchr (argv[i], '=');
217 const char *arg = eq ? eq + 1 : i+1 < argc ? argv[++i] : nullptr;
218 config.mode = MainApp::CHECK_INTEGRITY_TESTS;
220 if (arg)
221 check_test_names.push_back (arg);
222 default_ui_mode = "none";
223 }
224 else if (argv[i] == String ("--blake3") && i + 1 < size_t (argc))
225 {
226 argv[i++] = nullptr;
227 String hash = blake3_hash_file (argv[i]);
228 if (hash.empty())
229 printerr ("%s: failed to read: %s\n", argv[i], strerror (errno));
230 else
231 printout ("%s\n", string_to_hex (hash));
232 exit (hash == "");
233 }
234 else if (strcmp ("--jsonts", argv[i]) == 0) {
235 if (getenv ("ASE_JSONTS") == nullptr)
236 fatal_error ("%s: environment must contain ASE_JSONTS for --jsonts", argv[0]);
237 printout ("%s\n", Jsonipc::g_binding_printer->finish());
238 exit (0);
239 } else if (strcmp ("--jsipc", argv[i]) == 0)
240 config.jsonapi_logflags |= jsipc_logflags;
241 else if (strcmp ("--jsbin", argv[i]) == 0)
242 config.jsonapi_logflags |= jsbin_logflags;
243 else if (strcmp ("--list-drivers", argv[i]) == 0)
244 config.list_drivers = true;
245 else if (strcmp ("-M", argv[i]) == 0 && i + 1 < size_t (argc))
246 {
247 argv[i++] = nullptr;
248 config.midi_override = argv[i];
249 }
250 else if (strcmp ("-P", argv[i]) == 0 && i + 1 < size_t (argc))
251 {
252 argv[i++] = nullptr;
253 config.pcm_override = argv[i];
254 }
255 else if (strcmp ("-h", argv[i]) == 0 ||
256 strcmp ("--help", argv[i]) == 0)
257 {
258 print_usage (true);
259 exit (0);
260 }
261 else if (strcmp ("--version", argv[i]) == 0)
262 {
263 print_usage (false);
264 exit (0);
265 }
266 else if (argv[i] == String ("-o") && i + 1 < size_t (argc))
267 {
268 argv[i++] = nullptr;
269 config.outputfile = argv[i];
270 }
271 else if (argv[i] == String ("--play-autostart"))
272 {
273 config.play_autostart = true;
274 default_ui_mode = "none";
275 }
276 else if (parse_option_arg ("--unauth-dev", argv, &i, &optarg))
277 {
278 arg_unauth_port = string_to_int (optarg);
279 default_ui_mode = "wait";
280 }
281 else if (argv[i] == String ("-t") && i + 1 < size_t (argc))
282 {
283 config.play_autostart = true;
284 argv[i++] = nullptr;
285 config.play_autostop = string_to_seconds (argv[i]);
286 default_ui_mode = "none";
287 }
288 else if (parse_option_arg ("--ui", argv, &i, &optarg))
289 {
290 arg_ui_mode = optarg;
291 }
292 else if (argv[i] == String ("--") && !sep)
293 sep = true;
294 else if (argv[i][0] == '-' && !sep)
295 fatal_error ("invalid command line argument: %s", argv[i]);
296 else
297 config.args.push_back (argv[i]);
298 argv[i] = nullptr;
299 }
300 if (arg_ui_mode.empty())
301 arg_ui_mode = default_ui_mode;
302 if (*argcp > 1)
303 {
304 uint e = 1;
305 for (uint i = 1; i < argc; i++)
306 if (argv[i])
307 {
308 argv[e++] = argv[i];
309 if (i >= e)
310 argv[i] = nullptr;
311 }
312 *argcp = e;
313 }
314}
315
316static String
317make_auth_string()
318{
319 const char *const c52 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
320 /* We use WebScoket subprotocol randomization as authentication, so:
321 * a) Authentication happens *before* message interpretation, so an
322 * unauthenticated sender cannot cause crahses via e.g. rapidjson exceptions.
323 * b) To serve as working authentication measure, the subprotocol random string
324 * must be cryptographically-secure.
325 */
326 KeccakCryptoRng csprng;
327 String auth = "sessC";
328 for (size_t i = 0; i < 23; ++i)
329 auth += c52[csprng.random() % 52]; // each step adds 5.7 bits
330 return auth;
331}
332
333static void
334run_tests_and_quit ()
335{
336 if (check_test_names.empty())
337 Test::run();
338 else
339 Test::run (check_test_names);
340 main_loop->quit (0);
341}
342
343void
344main_loop_wakeup ()
345{
346 MainLoopP loop = main_loop;
347 if (loop)
348 loop->wakeup();
349}
350
351static std::atomic<bool> seen_autostop = false;
352
353// Lock and obstruction-free autostop trigger.
354void
355main_loop_autostop_mt()
356{
357 if (!seen_autostop)
358 {
359 seen_autostop = true;
360 main_loop_wakeup();
361 }
362}
363
364static bool
365handle_autostop (const LoopState &state)
366{
367 switch (state.phase)
368 {
369 case LoopState::PREPARE: return seen_autostop;
370 case LoopState::CHECK: return seen_autostop;
371 case LoopState::DISPATCH:
372 info ("Main: stopping playback (auto)");
373 main_loop->quit (0);
374 return true; // keep alive
375 default: ;
376 }
377 return false;
378}
379
380static void
381init_sigpipe()
382{
383 // don't die if we write() data to a process and that process dies (i.e. jackd)
384 sigset_t signal_mask;
385 sigemptyset (&signal_mask);
386 sigaddset (&signal_mask, SIGPIPE);
387
388 int rc = pthread_sigmask (SIG_BLOCK, &signal_mask, NULL);
389 if (rc != 0)
390 Ase::warning ("Ase: pthread_sigmask for SIGPIPE failed: %s\n", strerror (errno));
391}
392
393static std::atomic<bool> loft_needs_preallocation_mt = false;
394
395// handle watermark underrun notifications
396static void
397notify_loft_lowmem ()
398{
399 if (!loft_needs_preallocation_mt)
400 {
401 loft_needs_preallocation_mt = true;
402 Ase::main_loop_wakeup();
403 }
404}
405
406static size_t last_loft_preallocation = 0;
407
408static void
409preallocate_loft (size_t preallocation)
410{
411 using namespace Ase;
412 last_loft_preallocation = preallocation;
413 LoftConfig loftcfg = {
414 .preallocate = last_loft_preallocation,
415 .watermark = last_loft_preallocation / 2,
416 .flags = Loft::PREFAULT_PAGES,
417 };
418 loft_set_config (loftcfg);
419 loft_set_notifier (notify_loft_lowmem);
420 loft_grow_preallocate();
421}
422
423static bool
424dispatch_loft_lowmem (const Ase::LoopState &lstate)
425{
426 using namespace Ase;
427 const bool keep_alive = lstate.phase == LoopState::DISPATCH;
428 // generally, dispatch logic may only run in LoopState::DISPATCH, but this handler
429 // makes a rare exception, because we try to get ahead of concurrently runnint RT-threads...
430 return_unless (loft_needs_preallocation_mt, keep_alive);
431 loft_needs_preallocation_mt = false;
432 last_loft_preallocation *= 2;
433 const size_t newalloc = loft_grow_preallocate (last_loft_preallocation);
434 LoftConfig config;
435 loft_get_config (config);
436 config.watermark = last_loft_preallocation / 2;
437 loft_set_config (config);
438 if (newalloc > 0)
439 MDEBUG ("Loft preallocation in main thread: %f MB", newalloc / (1024. * 1024));
440 return keep_alive;
441}
442
443static void
444prefault_pages (size_t stacksize, size_t heapsize)
445{
446 const size_t pagesize = sysconf (_SC_PAGESIZE);
447 char *heap = (char*) malloc (heapsize);
448 if (heap)
449 for (size_t i = 0; i < heapsize; i += pagesize)
450 heap[i] = 1;
451 free (heap);
452 char *stack = (char*) alloca (stacksize);
453 if (stack)
454 for (size_t i = 0; i < stacksize; i += pagesize)
455 stack[i] = 1;
456}
457
458static int
459main (int argc, char *argv[])
460{
461 using namespace Ase;
462 using namespace AnsiColors;
463
464 // setup thread identifier
465 TaskRegistry::setup_ase ("AnklangMainProc");
466 // use malloc to serve allocations via sbrk only (avoid mmap)
467 mallopt (M_MMAP_MAX, 0);
468 // avoid releasing sbrk memory back to the system (reduce page faults)
469 mallopt (M_TRIM_THRESHOLD, -1);
470 // reserve large sbrk area and reduce page faults for heap and stack
471 prefault_pages ((1024 + 768) * 1024, 64 * 1024 * 1024);
472 // preallocate memory for lock-free allocator
473 preallocate_loft (64 * 1024 * 1024);
474
475 // print stack trace for uncaught exceptions
476 logging_handle_terminate();
477
478 // SIGPIPE init: needs to be done before any child thread is created
479 init_sigpipe();
480 if (setpgid (0, 0) < 0)
481 diag ("Main: setpgid failed: %s", ::strerror (errno));
482
483 // apply user locale
484 if (!setlocale (LC_ALL, ""))
485 fatal_error ("setlocale: locale not supported by libc: %s", ::strerror (errno));
486
487 // parse args and config
488 parse_args (&argc, argv, main_app);
489 logging_configure (arg_ui_mode != "none");
490
491 // prepare main event loop (needed before parse_args)
492 main_loop = MainLoop::create();
493 // handle loft preallocation needs
494 main_loop->exec_dispatcher (dispatch_loft_lowmem, EventLoop::PRIORITY_CEILING);
495
496 // load preferences unless --norc was given
497 if (!App.norc)
498 Preference::load_preferences (true);
499
500 const auto B1 = color (BOLD);
501 const auto B0 = color (BOLD_OFF);
502
503 // load drivers and dump device list
505 if (App.list_drivers)
506 {
507 Ase::Driver::EntryVec entries;
508 printout ("%s", _("Available PCM drivers:\n"));
509 entries = Ase::PcmDriver::list_drivers();
510 std::sort (entries.begin(), entries.end(), [] (auto &a, auto &b) { return a.priority < b.priority; });
511 for (const auto &entry : entries)
512 {
513 printout (" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid + ":",
514 entry.readonly ? "Input" : entry.writeonly ? "Output" : "Duplex",
515 entry.priority, entry.device_name,
516 entry.capabilities.empty() ? "" : "\t" + entry.capabilities + "\n",
517 entry.device_info.empty() ? "" : "\t" + entry.device_info + "\n",
518 entry.hints.empty() ? "" : "\t(" + entry.hints + ")\n",
519 entry.notice.empty() ? "" : "\t" + entry.notice + "\n");
520 if (debug_key_enabled ("driver"))
521 printerr (" %08x: %s\n", entry.priority, Driver::priority_string (entry.priority));
522 }
523 printout ("%s", _("Available MIDI drivers:\n"));
524 entries = Ase::MidiDriver::list_drivers();
525 std::sort (entries.begin(), entries.end(), [] (auto &a, auto &b) { return a.priority < b.priority; });
526 for (const auto &entry : entries)
527 {
528 printout (" %-30s (%s, %08x)\n\t%s\n%s%s%s%s", entry.devid + ":",
529 entry.readonly ? "Input" : entry.writeonly ? "Output" : "Duplex",
530 entry.priority, entry.device_name,
531 entry.capabilities.empty() ? "" : "\t" + entry.capabilities + "\n",
532 entry.device_info.empty() ? "" : "\t" + entry.device_info + "\n",
533 entry.hints.empty() ? "" : "\t(" + entry.hints + ")\n",
534 entry.notice.empty() ? "" : "\t" + entry.notice + "\n");
535 if (debug_key_enabled ("driver"))
536 printerr (" %08x: %s\n", entry.priority, Driver::priority_string (entry.priority));
537 }
538 return 0;
539 }
540
541 // start audio engine
542 AudioEngine &audio_engine = make_audio_engine (main_loop_wakeup, 48000, SpeakerArrangement::STEREO);
543 main_app.engine = &audio_engine;
544 audio_engine.start_threads ();
545 /*const uint loopdispatcherid =*/
546 main_loop->exec_dispatcher ([&audio_engine] (const LoopState &state) -> bool {
547 switch (state.phase)
548 {
549 case LoopState::PREPARE:
550 return main_rt_jobs_pending() || audio_engine.ipc_pending();
551 case LoopState::CHECK:
552 return main_rt_jobs_pending() || audio_engine.ipc_pending();
553 case LoopState::DISPATCH:
554 audio_engine.ipc_dispatch();
555 main_rt_jobs_process();
556 return true;
557 default:
558 return false;
559 }
560 });
561
562 // load projects
563 ProjectImplP preload_project;
564 for (const auto &filename : App.args)
565 {
566 preload_project = ProjectImpl::create (Path::basename (filename));
567 Error error = Error::NO_MEMORY;
568 if (preload_project)
569 error = preload_project->load_project (filename);
570 diag ("Main: load project: %s: %s", filename, ase_error_blurb (error));
571 if (!!error)
572 warning ("%s: failed to load project: %s", filename, ase_error_blurb (error));
573 }
574
575 // open Jsonapi socket
576 const String auth_token = arg_unauth_port > 0 ? "" : make_auth_string();
577 auto wss = WebSocketServer::create (jsonapi_make_connection, App.jsonapi_logflags, auth_token);
578 main_app.web_socket_server = &*wss;
579 wss->http_dir (anklang_runpath (RPath::INSTALLDIR, "/ui/"));
580 // wss->http_alias ("/User/Controller", anklang_home_dir ("/Controller"));
581 wss->http_alias ("/Builtin/Controller", anklang_runpath (RPath::INSTALLDIR, "/Controller"));
582 // wss->http_alias ("/User/Scripts", anklang_home_dir ("/Scripts"));
583 wss->http_alias ("/Builtin/Scripts", anklang_runpath (RPath::INSTALLDIR,"/Scripts"));
584 const int xport = arg_unauth_port > 0 ? arg_unauth_port : 0;
585 const String subprotocol = ""; // make_auth_string()
586 jsonapi_set_subprotocol (subprotocol);
587 if (App.mode == MainApp::SYNTHENGINE && arg_ui_mode != "none") {
588 const char *host = "127.0.0.1";
589 wss->listen (host, xport, [] () { main_loop->quit (-1); });
590 std::string webui_url = wss->url();
591 if (!xport) {
592 String redirecthtml = webui_create_auth_redirect ("anklang", wss->listen_port(), auth_token, arg_ui_mode);
593 if (errno)
594 fatal_error ("%s: failed to create html redirect file in $HOME", redirecthtml);
595 webui_url = "file://" + redirecthtml;
596 wss->see_other (webui_url);
597 }
598 info ("Main: WebUI address: %s", webui_url);
599 auto ereason = webui_start_browser (arg_ui_mode, main_loop, webui_url, [] () { main_loop->quit (0); });
600 if (ereason.error)
601 fatal_error ("Main: failed to run WebUI: %s: %s", ereason.what, ::strerror (ereason.error));
602 }
603
604 // run atquit handler on SIGHUP SIGINT
605 for (int sigid : { SIGHUP, SIGINT, SIGQUIT, SIGABRT, SIGTERM, SIGSYS }) {
606 main_loop->exec_usignal (sigid, [] (int8 sig) {
607 info ("Main: got signal %d: terminate", sig);
608 const pid_t pgid = getpgrp();
609 atquit_terminate (-1, pgid);
610 return false;
611 });
612 USignalSource::install_sigaction (sigid);
613 }
614
615 // catch SIGUSR2 to close sockets
616 main_loop->exec_usignal (SIGUSR2, [wss] (int8 sig) {
617 info ("Main: got signal %d: reset WebSocket", sig);
618 wss->reset();
619 return true;
620 });
621 USignalSource::install_sigaction (SIGUSR2);
622
623 // start output capturing
624 if (App.outputfile)
625 {
627 info ("Main: Start caputure: %s", App.outputfile);
628 App.engine->queue_capture_start (*callbacks, App.outputfile, true);
629 auto job = [callbacks] () {
630 for (const auto &callback : *callbacks)
631 callback();
632 };
633 App.engine->async_jobs += job;
634 }
635
636 // start auto play
637 if (App.play_autostart && preload_project)
638 main_loop->exec_idle ([preload_project] () {
639 info ("Main: starting playback (auto)");
640 preload_project->start_playback (App.play_autostop);
641 });
642 // handle automatic shutdown
643 main_loop->exec_dispatcher (handle_autostop);
644
645 // run test suite
646 if (App.mode == MainApp::CHECK_INTEGRITY_TESTS)
647 main_loop->exec_now (run_tests_and_quit);
648
649 // run main event loop and catch SIGUSR2
650 const int exitcode = main_loop->run();
651 assert_return (main_loop, -1); // ptr must be kept around
652 diag ("Main: event loop quit: code=%d", exitcode);
653
654 // cleanup
655 wss->shutdown(); // close socket, allow no more calls
656 main_app.web_socket_server = nullptr;
657 wss = nullptr;
658
659 // halt audio engine, join its threads, dispatch cleanups
660 audio_engine.set_project (nullptr);
661 audio_engine.stop_threads();
662 main_loop->iterate_pending();
663 main_app.engine = nullptr;
664
665 diag ("Main: exiting: %d", exitcode);
666 return exitcode;
667}
668
669} // Ase
670
671int
672main (int argc, char *argv[])
673{
674 int r = -128;
675#ifdef ASE_WITH_CPPTRACE
676 CPPTRACE_TRY { r = Ase::main (argc, argv); }
677 CPPTRACE_CATCH (const std::exception& e) {
678 std::string msg = "Exception: ";
679 msg += e.what();
680 msg += "\n";
681 fflush (stdout);
682 fputs (msg.c_str(), stderr);
683 fflush (stderr);
684 cpptrace::from_current_exception().print();
685 }
686#else
687 r = Ase::main (argc, argv);
688#endif
689 return r;
690}
691
692namespace { // Anon
693using namespace Ase;
694
695extern "C" __attribute__ ((__noinline__)) void
696tlog1 (const char *s)
697{
698 debug ("foo: %s+%d", s, 0x11111111);
699}
700
701extern "C" __attribute__ ((__noinline__)) void
702tlog2 (const char *s)
703{
704 debug ("foo: %s+%d", s, 0x11111111);
705}
706
707TEST_INTEGRITY (job_queue_tests);
708static void
709job_queue_tests()
710{
711 bool seen_engine_job = false, seen_deleter = false;
712 // enqueue job with deleter into engine
713 AudioEngine *e = App.engine;
714 std::shared_ptr<void> vp = { nullptr, [e,&seen_deleter] (void*) {
715 printerr (" job_queue_tests: Run Deleter (in_engine=%d)\n", e->thread_id == std::this_thread::get_id());
716 seen_deleter = true;
717 } };
718 e->async_jobs += [e,vp,&seen_engine_job] () {
719 printerr (" job_queue_tests: Run Handler (in_engine=%d)\n", e->thread_id == std::this_thread::get_id());
720 seen_engine_job = true;
721 };
722 vp.reset(); // required to allow deleter execution further down
723 // enqueue jobs into main loop
724 main_rt_jobs += RtCall ([]() { printerr (" job_queue_tests: Hello %s!\n", "void()"); });
725 main_rt_jobs += RtCall ((void(*)(const char*)) [] (const char *a) { printerr (" job_queue_tests: Hello %s!\n", a); }, "RtJobQueue");
726 struct Test1 { const char *a_; void print() { printerr (" job_queue_tests: Hello %s!\n", a_); } };
727 static Test1 test1 { "MemFn" };
728 main_rt_jobs += RtCall (test1, &Test1::print);
729 // lame busy looping to give the engine a chance at the job queue
730 uint64 start_usecs = timestamp_realtime();
731 do {
732 usleep (1500); // give the audio engine some time
733 main_loop->iterate (false);
734 } while (timestamp_realtime() < start_usecs + 1871 * 1000 && !seen_deleter);
735 assert_return (seen_engine_job == true);
736 assert_return (seen_deleter == true);
737}
738
739} // Anon
T c_str(T... args)
Lock-free stack with atomic push() and pop_all operations.
Definition atomics.hh:21
Main handle for AudioProcessor administration and audio rendering.
Definition engine.hh:21
JobQueue async_jobs
Executed asynchronously, may modify AudioProcessor objects.
Definition engine.hh:65
static String priority_string(uint priority)
Return string which represents the given priority mask.
Definition driver.cc:31
static const int16 PRIORITY_CEILING
Internal upper limit, don't use.
Definition loop.hh:88
KeccakCryptoRng - A KeccakF1600 based cryptographic quality pseudo-random number generator.
uint64_t random()
Generate uniformly distributed 64 bit pseudo random number.
static MainLoopP create()
Create a MainLoop shared pointer handle.
Definition loop.cc:379
Marsaglia multiply-with-carry generator, period ca 2^255.
Definition randomhash.hh:37
T empty(T... args)
exit
fflush
fputs
free
fwrite
T get_id(T... args)
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
#define TEST_INTEGRITY(FUNC)
Register func as an integrity test.
Definition internal.hh:79
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
int run(void)
Run all registered tests.
Definition testing.cc:264
The Anklang C++ API namespace.
Definition api.hh:9
uint64_t uint64
A 64-bit unsigned integer, use PRI*64 in format strings.
Definition cxxaux.hh:25
String string_to_hex(const String &input)
Convert bytes in string input to hexadecimal numbers.
Definition strings.cc:1171
int8_t int8
An 8-bit signed integer.
Definition cxxaux.hh:26
JobQueue main_jobs(call_main_loop)
Execute a job callback in the Ase main loop.
Definition main.hh:39
Error
Enum representing Error states.
Definition api.hh:22
const char * ase_error_blurb(Error error)
Describe Error condition.
Definition server.cc:227
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
bool logging_fatal_warnings
Global flag to cause the program to abort on warnings.
Definition logging.cc:281
const char * ase_version()
Provide a string containing the package version.
Definition platform.cc:803
std::string executable_name()
Retrieve the name part of executable_path().
Definition platform.cc:742
bool debug_key_enabled(const char *conditional) noexcept
Check if conditional is enabled by $ASE_DEBUG.
Definition logging.cc:297
uint32_t uint
Provide 'uint' as convenience type.
Definition cxxaux.hh:18
void load_registered_drivers()
Load all registered drivers.
Definition driver.cc:76
RtJobQueue main_rt_jobs
Queue a callback for the main_loop without invoking malloc(), addition is obstruction free.
Definition main.cc:68
size_t preallocate
Amount of preallocated available memory.
Definition loft.hh:45
uint64 timestamp_realtime()
Return the current time as uint64 in µseconds.
Definition platform.cc:579
size_t watermark
Watermark to trigger async preallocation.
Definition loft.hh:46
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
pthread_sigmask
T push_back(T... args)
sigaddset
sigemptyset
T sort(T... args)
typedef uint64_t
strchr
strlen
Wrap simple callback pointers, without using malloc (obstruction free).
Definition callback.hh:91
Add a simple callback to the main event loop, without using malloc (obstruction free).
Definition main.hh:42
typedef pid_t
sysconf
T what(T... args)