3 * Copyright (C) 2012-2024 Filipe Coelho <falktx@falktx.com>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of
8 * the License, or any later version.
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.
15 * For a full copy of the GNU General Public License see the doc/GPL.txt file.
19 # error This file should not be compiled if not building bridge
22 #include "CarlaEngine.hpp"
23 #include "CarlaHost.h"
24 #include "CarlaUtils.h"
26 #include "CarlaBackendUtils.hpp"
27 #include "CarlaJuceUtils.hpp"
28 #include "CarlaMainLoop.hpp"
29 #include "CarlaTimeUtils.hpp"
31 #include "CarlaMIDI.h"
34 # include "CarlaMacUtils.hpp"
43 # define SCHED_RESET_ON_FORK 0x40000000
52 # include <X11/Xlib.h>
55 #include "water/files/File.h"
56 #include "water/misc/Time.h"
59 #include "jackbridge/JackBridge.hpp"
61 using CARLA_BACKEND_NAMESPACE::CarlaEngine
;
62 using CARLA_BACKEND_NAMESPACE::EngineCallbackOpcode
;
63 using CARLA_BACKEND_NAMESPACE::EngineCallbackOpcode2Str
;
64 using CARLA_BACKEND_NAMESPACE::runMainLoopOnce
;
66 using water::CharPointer_UTF8
;
70 // -------------------------------------------------------------------------
72 static bool gIsInitiated
= false;
73 static volatile bool gCloseBridge
= false;
74 static volatile bool gCloseSignal
= false;
75 static volatile bool gSaveNow
= false;
77 #if defined(CARLA_OS_UNIX)
78 static void closeSignalHandler(int) noexcept
82 static void saveSignalHandler(int) noexcept
86 #elif defined(CARLA_OS_WIN)
87 static LONG WINAPI
winExceptionFilter(_EXCEPTION_POINTERS
*)
89 return EXCEPTION_EXECUTE_HANDLER
;
92 static BOOL WINAPI
winSignalHandler(DWORD dwCtrlType
) noexcept
94 if (dwCtrlType
== CTRL_C_EVENT
)
103 static void initSignalHandler()
105 #if defined(CARLA_OS_UNIX)
106 struct sigaction sig
;
107 carla_zeroStruct(sig
);
109 sig
.sa_handler
= closeSignalHandler
;
110 sig
.sa_flags
= SA_RESTART
;
111 sigemptyset(&sig
.sa_mask
);
112 sigaction(SIGTERM
, &sig
, nullptr);
113 sigaction(SIGINT
, &sig
, nullptr);
115 sig
.sa_handler
= saveSignalHandler
;
116 sig
.sa_flags
= SA_RESTART
;
117 sigemptyset(&sig
.sa_mask
);
118 sigaction(SIGUSR1
, &sig
, nullptr);
119 #elif defined(CARLA_OS_WIN)
120 SetConsoleCtrlHandler(winSignalHandler
, TRUE
);
121 SetErrorMode(SEM_NOGPFAULTERRORBOX
);
122 SetUnhandledExceptionFilter(winExceptionFilter
);
126 // -------------------------------------------------------------------------
128 static String gProjectFilename
;
129 static CarlaHostHandle gHostHandle
;
133 carla_engine_idle(gHostHandle
);
139 if (gProjectFilename
.isNotEmpty())
141 if (! carla_save_plugin_state(gHostHandle
, 0, gProjectFilename
.toRawUTF8()))
142 carla_stderr("Plugin preset save failed, error was:\n%s", carla_get_last_error(gHostHandle
));
147 // -------------------------------------------------------------------------
149 class CarlaBridgePlugin
152 CarlaBridgePlugin(const bool useBridge
, const char* const clientName
, const char* const audioPoolBaseName
,
153 const char* const rtClientBaseName
, const char* const nonRtClientBaseName
, const char* const nonRtServerBaseName
)
158 CARLA_ASSERT(clientName
!= nullptr && clientName
[0] != '\0');
159 carla_debug("CarlaBridgePlugin::CarlaBridgePlugin(%s, \"%s\", %s, %s, %s, %s)",
160 bool2str(useBridge
), clientName
, audioPoolBaseName
, rtClientBaseName
, nonRtClientBaseName
, nonRtServerBaseName
);
162 carla_set_engine_callback(gHostHandle
, callback
, this);
166 carla_engine_init_bridge(gHostHandle
,
173 else if (std::getenv("CARLA_BRIDGE_DUMMY") != nullptr)
175 carla_engine_init(gHostHandle
, "Dummy", clientName
);
179 carla_engine_init(gHostHandle
, "JACK", clientName
);
182 fEngine
= carla_get_engine_from_handle(gHostHandle
);
187 carla_debug("CarlaBridgePlugin::~CarlaBridgePlugin()");
189 if (fEngine
!= nullptr && ! fUsingExec
)
190 carla_engine_close(gHostHandle
);
193 bool isOk() const noexcept
195 return (fEngine
!= nullptr);
198 // ---------------------------------------------------------------------
200 void exec(const bool useBridge
)
202 fUsingBridge
= useBridge
;
205 const bool testing
= std::getenv("CARLA_BRIDGE_TESTING") != nullptr;
207 if (! useBridge
&& ! testing
)
209 const CarlaPluginInfo
* const pInfo
= carla_get_plugin_info(gHostHandle
, 0);
210 CARLA_SAFE_ASSERT_RETURN(pInfo
!= nullptr,);
212 gProjectFilename
= CharPointer_UTF8(pInfo
->name
);
213 gProjectFilename
+= ".carxs";
215 if (! File::isAbsolutePath(gProjectFilename
))
216 gProjectFilename
= File::getCurrentWorkingDirectory().getChildFile(gProjectFilename
).getFullPathName();
218 if (File(gProjectFilename
).existsAsFile())
220 if (carla_load_plugin_state(gHostHandle
, 0, gProjectFilename
.toRawUTF8()))
221 carla_stdout("Plugin state loaded successfully");
223 carla_stderr("Plugin state load failed, error was:\n%s", carla_get_last_error(gHostHandle
));
227 carla_stdout("Previous plugin state in '%s' is non-existent, will start from default state",
228 gProjectFilename
.toRawUTF8());
234 int64_t timeToEnd
= 0;
238 timeToEnd
= water::Time::currentTimeMillis() + 5 * 1000;
239 fEngine
->transportPlay();
242 for (; runMainLoopOnce() && ! gCloseBridge
;)
245 #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
246 // MacOS and Win32 have event-loops to run, so minimize sleep time
251 if (testing
&& timeToEnd
- water::Time::currentTimeMillis() < 0)
253 if (gCloseSignal
&& ! fUsingBridge
)
257 carla_engine_close(gHostHandle
);
260 // ---------------------------------------------------------------------
263 void handleCallback(const EngineCallbackOpcode action
,
265 const int, const int, const float, const char* const)
267 CARLA_BACKEND_USE_NAMESPACE
;
271 case ENGINE_CALLBACK_ENGINE_STOPPED
:
272 case ENGINE_CALLBACK_PLUGIN_REMOVED
:
273 case ENGINE_CALLBACK_QUIT
:
274 gCloseBridge
= gCloseSignal
= true;
277 case ENGINE_CALLBACK_UI_STATE_CHANGED
:
278 if (gIsInitiated
&& value1
!= 1 && ! fUsingBridge
)
279 gCloseBridge
= gCloseSignal
= true;
288 CarlaEngine
* fEngine
;
293 static void callback(void* ptr
, EngineCallbackOpcode action
, unsigned int pluginId
,
294 int value1
, int value2
, int value3
,
295 float valuef
, const char* valueStr
)
297 carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
298 ptr
, action
, EngineCallbackOpcode2Str(action
),
299 pluginId
, value1
, value2
, value3
, static_cast<double>(valuef
), valueStr
);
301 // ptr must not be null
302 CARLA_SAFE_ASSERT_RETURN(ptr
!= nullptr,);
304 #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
305 // pluginId must be 0 (first), except for patchbay things
306 if (action
< CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED
||
307 action
> CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED
)
310 CARLA_SAFE_ASSERT_UINT_RETURN(pluginId
== 0, pluginId
,);
313 return ((CarlaBridgePlugin
*)ptr
)->handleCallback(action
, value1
, value2
, value3
, valuef
, valueStr
);
316 CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin
)
319 // -------------------------------------------------------------------------
321 int main(int argc
, char* argv
[])
323 // ---------------------------------------------------------------------
324 // Check argument count
326 if (argc
!= 4 && argc
!= 5)
328 carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv
[0]);
332 #if defined(CARLA_OS_WIN) && defined(BUILDING_CARLA_FOR_WINE)
333 // ---------------------------------------------------------------------
334 // Test if bridge is working
336 if (! jackbridge_is_ok())
338 carla_stderr("A JACK or Wine library is missing, cannot continue");
343 // ---------------------------------------------------------------------
346 const char* const stype
= argv
[1];
347 const char* filename
= argv
[2];
348 const char* label
= argv
[3];
349 const int64_t uniqueId
= (argc
== 5) ? static_cast<int64_t>(std::atoll(argv
[4])) : 0;
351 if (filename
[0] == '\0' || std::strcmp(filename
, "(none)") == 0)
354 if (label
[0] == '\0' || std::strcmp(label
, "(none)") == 0)
357 // ---------------------------------------------------------------------
360 CARLA_BACKEND_NAMESPACE::BinaryType btype
= CARLA_BACKEND_NAMESPACE::BINARY_NATIVE
;
362 if (const char* const binaryTypeStr
= std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
363 btype
= CARLA_BACKEND_NAMESPACE::getBinaryTypeFromString(binaryTypeStr
);
365 if (btype
== CARLA_BACKEND_NAMESPACE::BINARY_NONE
)
367 carla_stderr("Invalid binary type '%i'", btype
);
371 // ---------------------------------------------------------------------
374 CARLA_BACKEND_NAMESPACE::PluginType itype
= CARLA_BACKEND_NAMESPACE::getPluginTypeFromString(stype
);
376 if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_NONE
)
378 carla_stderr("Invalid plugin type '%s'", stype
);
382 // ---------------------------------------------------------------------
385 const File
file(filename
!= nullptr ? filename
: "");
387 // ---------------------------------------------------------------------
390 const char* name(std::getenv("CARLA_CLIENT_NAME"));
392 if (name
!= nullptr && (name
[0] == '\0' || std::strcmp(name
, "(none)") == 0))
395 // ---------------------------------------------------------------------
398 const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
400 const bool useBridge
= (shmIds
!= nullptr);
402 // ---------------------------------------------------------------------
405 char audioPoolBaseName
[6+1];
406 char rtClientBaseName
[6+1];
407 char nonRtClientBaseName
[6+1];
408 char nonRtServerBaseName
[6+1];
412 CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds
) == 6*4, 1);
413 std::strncpy(audioPoolBaseName
, shmIds
+6*0, 6);
414 std::strncpy(rtClientBaseName
, shmIds
+6*1, 6);
415 std::strncpy(nonRtClientBaseName
, shmIds
+6*2, 6);
416 std::strncpy(nonRtServerBaseName
, shmIds
+6*3, 6);
417 audioPoolBaseName
[6] = '\0';
418 rtClientBaseName
[6] = '\0';
419 nonRtClientBaseName
[6] = '\0';
420 nonRtServerBaseName
[6] = '\0';
421 jackbridge_parent_deathsig(false);
425 audioPoolBaseName
[0] = '\0';
426 rtClientBaseName
[0] = '\0';
427 nonRtClientBaseName
[0] = '\0';
428 nonRtServerBaseName
[0] = '\0';
432 // ---------------------------------------------------------------------
435 CarlaString clientName
;
441 else if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_LV2
)
444 CARLA_SAFE_ASSERT_RETURN(label
!= nullptr && label
[0] != '\0', 1);
446 // LV2 URI is not usable as client name, create a usable name from URI
447 CarlaString
label2(label
);
449 // truncate until last valid char
450 for (std::size_t i
=label2
.length()-1; i
!= 0; --i
)
452 if (! std::isalnum(label2
[i
]))
455 label2
.truncate(i
+1);
459 // get last used separator
461 std::size_t septmp
, sep
= 0;
463 septmp
= label2
.rfind('#', &found
)+1;
464 if (found
&& septmp
> sep
)
467 septmp
= label2
.rfind('/', &found
)+1;
468 if (found
&& septmp
> sep
)
471 septmp
= label2
.rfind('=', &found
)+1;
472 if (found
&& septmp
> sep
)
475 septmp
= label2
.rfind(':', &found
)+1;
476 if (found
&& septmp
> sep
)
479 // make name starting from the separator and first valid char
480 const char* name2
= label2
.buffer() + sep
;
481 for (; *name2
!= '\0' && ! std::isalnum(*name2
); ++name2
) {}
486 else if (label
!= nullptr)
492 clientName
= file
.getFileNameWithoutExtension().toRawUTF8();
495 // if we still have no client name by now, use a dummy one
496 if (clientName
.isEmpty())
497 clientName
= "carla-plugin";
500 clientName
.toBasic();
502 // ---------------------------------------------------------------------
505 const void* extraStuff
= nullptr;
507 if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_SF2
)
509 if (label
== nullptr)
512 if (std::strstr(label
, " (16 outs)") != nullptr)
516 // ---------------------------------------------------------------------
517 // Initialize OS features
519 const bool dummy
= std::getenv("CARLA_BRIDGE_DUMMY") != nullptr;
520 const bool testing
= std::getenv("CARLA_BRIDGE_TESTING") != nullptr;
523 CARLA_BACKEND_NAMESPACE::initStandaloneApplication();
527 OleInitialize(nullptr);
528 CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED
);
529 # ifndef __WINPTHREADS_VERSION
530 // (non-portable) initialization of statically linked pthread library
531 pthread_win32_process_attach_np();
532 pthread_win32_thread_attach_np();
537 if (std::getenv("DISPLAY") != nullptr)
541 // ---------------------------------------------------------------------
542 // Set ourselves with high priority
544 if (!dummy
&& !testing
)
546 #ifdef CARLA_OS_LINUX
547 // reset scheduler to normal mode
548 struct sched_param sparam
;
549 carla_zeroStruct(sparam
);
550 sched_setscheduler(0, SCHED_OTHER
|SCHED_RESET_ON_FORK
, &sparam
);
552 // try niceness first, if it fails, try SCHED_RR
555 sparam
.sched_priority
= (sched_get_priority_max(SCHED_RR
) + sched_get_priority_min(SCHED_RR
*7)) / 8;
557 if (sparam
.sched_priority
> 0)
559 if (sched_setscheduler(0, SCHED_RR
|SCHED_RESET_ON_FORK
, &sparam
) < 0)
561 CarlaString
error(std::strerror(errno
));
562 carla_stderr("Failed to set high priority, error %i: %s", errno
, error
.buffer());
569 if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS
))
570 carla_stderr("Failed to set high priority.");
574 // ---------------------------------------------------------------------
575 // Listen for ctrl+c or sigint/sigterm events
579 // ---------------------------------------------------------------------
580 // Init plugin bridge
585 gHostHandle
= carla_standalone_host_init();
587 CarlaBridgePlugin
bridge(useBridge
, clientName
,
588 audioPoolBaseName
, rtClientBaseName
, nonRtClientBaseName
, nonRtServerBaseName
);
592 carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error(gHostHandle
));
596 if (! useBridge
&& ! testing
)
599 if (std::getenv("DISPLAY") != nullptr)
601 carla_set_engine_option(gHostHandle
,
602 CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_FRONTEND_UI_SCALE
,
603 static_cast<int>(carla_get_desktop_scale_factor()*1000+0.5),
607 // -----------------------------------------------------------------
610 if (carla_add_plugin(gHostHandle
,
612 file
.getFullPathName().toRawUTF8(), name
, label
, uniqueId
, extraStuff
,
613 CARLA_BACKEND_NAMESPACE::PLUGIN_OPTIONS_NULL
))
619 carla_set_active(gHostHandle
, 0, true);
620 carla_set_engine_option(gHostHandle
, CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_PLUGINS_ARE_STANDALONE
, 1, nullptr);
622 if (const CarlaPluginInfo
* const pluginInfo
= carla_get_plugin_info(gHostHandle
, 0))
624 if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_INTERNAL
&& (std::strcmp(label
, "audiofile") == 0 || std::strcmp(label
, "midifile") == 0))
627 carla_set_custom_data(gHostHandle
, 0,
628 CARLA_BACKEND_NAMESPACE::CUSTOM_DATA_TYPE_STRING
,
629 "file", file
.getFullPathName().toRawUTF8());
631 else if (pluginInfo
->hints
& CARLA_BACKEND_NAMESPACE::PLUGIN_HAS_CUSTOM_UI
)
634 if (std::getenv("DISPLAY") != nullptr)
637 carla_show_custom_ui(gHostHandle
, 0, true);
640 // on standalone usage, enable everything that makes sense
641 const uint optsAvailable
= pluginInfo
->optionsAvailable
;
642 if (optsAvailable
& CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS
)
643 carla_set_option(gHostHandle
, 0, CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS
, true);
647 bridge
.exec(useBridge
);
653 const char* const lastError(carla_get_last_error(gHostHandle
));
654 carla_stderr("Plugin failed to load, error was:\n%s", lastError
);
658 // do a single idle so that we can send error message to server
662 // kill ourselves now if we can't load plugin in bridge mode
663 ::kill(::getpid(), SIGKILL
);
670 #ifndef __WINPTHREADS_VERSION
671 pthread_win32_thread_detach_np();
672 pthread_win32_process_detach_np();