3 * Copyright (C) 2012-2023 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 BOOL WINAPI
winSignalHandler(DWORD dwCtrlType
) noexcept
89 if (dwCtrlType
== CTRL_C_EVENT
)
98 static void initSignalHandler()
100 #if defined(CARLA_OS_UNIX)
101 struct sigaction sig
;
102 carla_zeroStruct(sig
);
104 sig
.sa_handler
= closeSignalHandler
;
105 sig
.sa_flags
= SA_RESTART
;
106 sigemptyset(&sig
.sa_mask
);
107 sigaction(SIGTERM
, &sig
, nullptr);
108 sigaction(SIGINT
, &sig
, nullptr);
110 sig
.sa_handler
= saveSignalHandler
;
111 sig
.sa_flags
= SA_RESTART
;
112 sigemptyset(&sig
.sa_mask
);
113 sigaction(SIGUSR1
, &sig
, nullptr);
114 #elif defined(CARLA_OS_WIN)
115 SetConsoleCtrlHandler(winSignalHandler
, TRUE
);
119 // -------------------------------------------------------------------------
121 static String gProjectFilename
;
122 static CarlaHostHandle gHostHandle
;
126 carla_engine_idle(gHostHandle
);
132 if (gProjectFilename
.isNotEmpty())
134 if (! carla_save_plugin_state(gHostHandle
, 0, gProjectFilename
.toRawUTF8()))
135 carla_stderr("Plugin preset save failed, error was:\n%s", carla_get_last_error(gHostHandle
));
140 // -------------------------------------------------------------------------
142 class CarlaBridgePlugin
145 CarlaBridgePlugin(const bool useBridge
, const char* const clientName
, const char* const audioPoolBaseName
,
146 const char* const rtClientBaseName
, const char* const nonRtClientBaseName
, const char* const nonRtServerBaseName
)
151 CARLA_ASSERT(clientName
!= nullptr && clientName
[0] != '\0');
152 carla_debug("CarlaBridgePlugin::CarlaBridgePlugin(%s, \"%s\", %s, %s, %s, %s)",
153 bool2str(useBridge
), clientName
, audioPoolBaseName
, rtClientBaseName
, nonRtClientBaseName
, nonRtServerBaseName
);
155 carla_set_engine_callback(gHostHandle
, callback
, this);
159 carla_engine_init_bridge(gHostHandle
,
166 else if (std::getenv("CARLA_BRIDGE_DUMMY") != nullptr)
168 carla_engine_init(gHostHandle
, "Dummy", clientName
);
172 carla_engine_init(gHostHandle
, "JACK", clientName
);
175 fEngine
= carla_get_engine_from_handle(gHostHandle
);
180 carla_debug("CarlaBridgePlugin::~CarlaBridgePlugin()");
182 if (fEngine
!= nullptr && ! fUsingExec
)
183 carla_engine_close(gHostHandle
);
186 bool isOk() const noexcept
188 return (fEngine
!= nullptr);
191 // ---------------------------------------------------------------------
193 void exec(const bool useBridge
)
195 fUsingBridge
= useBridge
;
198 const bool testing
= std::getenv("CARLA_BRIDGE_TESTING") != nullptr;
200 if (! useBridge
&& ! testing
)
202 const CarlaPluginInfo
* const pInfo
= carla_get_plugin_info(gHostHandle
, 0);
203 CARLA_SAFE_ASSERT_RETURN(pInfo
!= nullptr,);
205 gProjectFilename
= CharPointer_UTF8(pInfo
->name
);
206 gProjectFilename
+= ".carxs";
208 if (! File::isAbsolutePath(gProjectFilename
))
209 gProjectFilename
= File::getCurrentWorkingDirectory().getChildFile(gProjectFilename
).getFullPathName();
211 if (File(gProjectFilename
).existsAsFile())
213 if (carla_load_plugin_state(gHostHandle
, 0, gProjectFilename
.toRawUTF8()))
214 carla_stdout("Plugin state loaded successfully");
216 carla_stderr("Plugin state load failed, error was:\n%s", carla_get_last_error(gHostHandle
));
220 carla_stdout("Previous plugin state in '%s' is non-existent, will start from default state",
221 gProjectFilename
.toRawUTF8());
227 int64_t timeToEnd
= 0;
231 timeToEnd
= water::Time::currentTimeMillis() + 5 * 1000;
232 fEngine
->transportPlay();
235 for (; runMainLoopOnce() && ! gCloseBridge
;)
238 #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
239 // MacOS and Win32 have event-loops to run, so minimize sleep time
244 if (testing
&& timeToEnd
- water::Time::currentTimeMillis() < 0)
246 if (gCloseSignal
&& ! fUsingBridge
)
250 carla_engine_close(gHostHandle
);
253 // ---------------------------------------------------------------------
256 void handleCallback(const EngineCallbackOpcode action
,
258 const int, const int, const float, const char* const)
260 CARLA_BACKEND_USE_NAMESPACE
;
264 case ENGINE_CALLBACK_ENGINE_STOPPED
:
265 case ENGINE_CALLBACK_PLUGIN_REMOVED
:
266 case ENGINE_CALLBACK_QUIT
:
267 gCloseBridge
= gCloseSignal
= true;
270 case ENGINE_CALLBACK_UI_STATE_CHANGED
:
271 if (gIsInitiated
&& value1
!= 1 && ! fUsingBridge
)
272 gCloseBridge
= gCloseSignal
= true;
281 CarlaEngine
* fEngine
;
286 static void callback(void* ptr
, EngineCallbackOpcode action
, unsigned int pluginId
,
287 int value1
, int value2
, int value3
,
288 float valuef
, const char* valueStr
)
290 carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
291 ptr
, action
, EngineCallbackOpcode2Str(action
),
292 pluginId
, value1
, value2
, value3
, static_cast<double>(valuef
), valueStr
);
294 // ptr must not be null
295 CARLA_SAFE_ASSERT_RETURN(ptr
!= nullptr,);
297 #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
298 // pluginId must be 0 (first), except for patchbay things
299 if (action
< CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED
||
300 action
> CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED
)
303 CARLA_SAFE_ASSERT_UINT_RETURN(pluginId
== 0, pluginId
,);
306 return ((CarlaBridgePlugin
*)ptr
)->handleCallback(action
, value1
, value2
, value3
, valuef
, valueStr
);
309 CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin
)
312 // -------------------------------------------------------------------------
314 int main(int argc
, char* argv
[])
316 // ---------------------------------------------------------------------
317 // Check argument count
319 if (argc
!= 4 && argc
!= 5)
321 carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv
[0]);
325 #if defined(CARLA_OS_WIN) && defined(BUILDING_CARLA_FOR_WINE)
326 // ---------------------------------------------------------------------
327 // Test if bridge is working
329 if (! jackbridge_is_ok())
331 carla_stderr("A JACK or Wine library is missing, cannot continue");
336 // ---------------------------------------------------------------------
339 const char* const stype
= argv
[1];
340 const char* filename
= argv
[2];
341 const char* label
= argv
[3];
342 const int64_t uniqueId
= (argc
== 5) ? static_cast<int64_t>(std::atoll(argv
[4])) : 0;
344 if (filename
[0] == '\0' || std::strcmp(filename
, "(none)") == 0)
347 if (label
[0] == '\0' || std::strcmp(label
, "(none)") == 0)
350 // ---------------------------------------------------------------------
353 CARLA_BACKEND_NAMESPACE::BinaryType btype
= CARLA_BACKEND_NAMESPACE::BINARY_NATIVE
;
355 if (const char* const binaryTypeStr
= std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
356 btype
= CARLA_BACKEND_NAMESPACE::getBinaryTypeFromString(binaryTypeStr
);
358 if (btype
== CARLA_BACKEND_NAMESPACE::BINARY_NONE
)
360 carla_stderr("Invalid binary type '%i'", btype
);
364 // ---------------------------------------------------------------------
367 CARLA_BACKEND_NAMESPACE::PluginType itype
= CARLA_BACKEND_NAMESPACE::getPluginTypeFromString(stype
);
369 if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_NONE
)
371 carla_stderr("Invalid plugin type '%s'", stype
);
375 // ---------------------------------------------------------------------
378 const File
file(filename
!= nullptr ? filename
: "");
380 // ---------------------------------------------------------------------
383 const char* name(std::getenv("CARLA_CLIENT_NAME"));
385 if (name
!= nullptr && (name
[0] == '\0' || std::strcmp(name
, "(none)") == 0))
388 // ---------------------------------------------------------------------
391 const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
393 const bool useBridge
= (shmIds
!= nullptr);
395 // ---------------------------------------------------------------------
398 char audioPoolBaseName
[6+1];
399 char rtClientBaseName
[6+1];
400 char nonRtClientBaseName
[6+1];
401 char nonRtServerBaseName
[6+1];
405 CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds
) == 6*4, 1);
406 std::strncpy(audioPoolBaseName
, shmIds
+6*0, 6);
407 std::strncpy(rtClientBaseName
, shmIds
+6*1, 6);
408 std::strncpy(nonRtClientBaseName
, shmIds
+6*2, 6);
409 std::strncpy(nonRtServerBaseName
, shmIds
+6*3, 6);
410 audioPoolBaseName
[6] = '\0';
411 rtClientBaseName
[6] = '\0';
412 nonRtClientBaseName
[6] = '\0';
413 nonRtServerBaseName
[6] = '\0';
414 jackbridge_parent_deathsig(false);
418 audioPoolBaseName
[0] = '\0';
419 rtClientBaseName
[0] = '\0';
420 nonRtClientBaseName
[0] = '\0';
421 nonRtServerBaseName
[0] = '\0';
425 // ---------------------------------------------------------------------
428 CarlaString clientName
;
434 else if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_LV2
)
437 CARLA_SAFE_ASSERT_RETURN(label
!= nullptr && label
[0] != '\0', 1);
439 // LV2 URI is not usable as client name, create a usable name from URI
440 CarlaString
label2(label
);
442 // truncate until last valid char
443 for (std::size_t i
=label2
.length()-1; i
!= 0; --i
)
445 if (! std::isalnum(label2
[i
]))
448 label2
.truncate(i
+1);
452 // get last used separator
454 std::size_t septmp
, sep
= 0;
456 septmp
= label2
.rfind('#', &found
)+1;
457 if (found
&& septmp
> sep
)
460 septmp
= label2
.rfind('/', &found
)+1;
461 if (found
&& septmp
> sep
)
464 septmp
= label2
.rfind('=', &found
)+1;
465 if (found
&& septmp
> sep
)
468 septmp
= label2
.rfind(':', &found
)+1;
469 if (found
&& septmp
> sep
)
472 // make name starting from the separator and first valid char
473 const char* name2
= label2
.buffer() + sep
;
474 for (; *name2
!= '\0' && ! std::isalnum(*name2
); ++name2
) {}
479 else if (label
!= nullptr)
485 clientName
= file
.getFileNameWithoutExtension().toRawUTF8();
488 // if we still have no client name by now, use a dummy one
489 if (clientName
.isEmpty())
490 clientName
= "carla-plugin";
493 clientName
.toBasic();
495 // ---------------------------------------------------------------------
498 const void* extraStuff
= nullptr;
500 if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_SF2
)
502 if (label
== nullptr)
505 if (std::strstr(label
, " (16 outs)") != nullptr)
509 // ---------------------------------------------------------------------
510 // Initialize OS features
512 const bool dummy
= std::getenv("CARLA_BRIDGE_DUMMY") != nullptr;
513 const bool testing
= std::getenv("CARLA_BRIDGE_TESTING") != nullptr;
516 CARLA_BACKEND_NAMESPACE::initStandaloneApplication();
520 OleInitialize(nullptr);
521 CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED
);
522 # ifndef __WINPTHREADS_VERSION
523 // (non-portable) initialization of statically linked pthread library
524 pthread_win32_process_attach_np();
525 pthread_win32_thread_attach_np();
530 if (std::getenv("DISPLAY") != nullptr)
534 // ---------------------------------------------------------------------
535 // Set ourselves with high priority
537 if (!dummy
&& !testing
)
539 #ifdef CARLA_OS_LINUX
540 // reset scheduler to normal mode
541 struct sched_param sparam
;
542 carla_zeroStruct(sparam
);
543 sched_setscheduler(0, SCHED_OTHER
|SCHED_RESET_ON_FORK
, &sparam
);
545 // try niceness first, if it fails, try SCHED_RR
548 sparam
.sched_priority
= (sched_get_priority_max(SCHED_RR
) + sched_get_priority_min(SCHED_RR
*7)) / 8;
550 if (sparam
.sched_priority
> 0)
552 if (sched_setscheduler(0, SCHED_RR
|SCHED_RESET_ON_FORK
, &sparam
) < 0)
554 CarlaString
error(std::strerror(errno
));
555 carla_stderr("Failed to set high priority, error %i: %s", errno
, error
.buffer());
562 if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS
))
563 carla_stderr("Failed to set high priority.");
567 // ---------------------------------------------------------------------
568 // Listen for ctrl+c or sigint/sigterm events
572 // ---------------------------------------------------------------------
573 // Init plugin bridge
578 gHostHandle
= carla_standalone_host_init();
580 CarlaBridgePlugin
bridge(useBridge
, clientName
,
581 audioPoolBaseName
, rtClientBaseName
, nonRtClientBaseName
, nonRtServerBaseName
);
585 carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error(gHostHandle
));
589 if (! useBridge
&& ! testing
)
592 if (std::getenv("DISPLAY") != nullptr)
594 carla_set_engine_option(gHostHandle
,
595 CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_FRONTEND_UI_SCALE
,
596 static_cast<int>(carla_get_desktop_scale_factor()*1000+0.5),
600 // -----------------------------------------------------------------
603 if (carla_add_plugin(gHostHandle
,
605 file
.getFullPathName().toRawUTF8(), name
, label
, uniqueId
, extraStuff
,
606 CARLA_BACKEND_NAMESPACE::PLUGIN_OPTIONS_NULL
))
612 carla_set_active(gHostHandle
, 0, true);
613 carla_set_engine_option(gHostHandle
, CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_PLUGINS_ARE_STANDALONE
, 1, nullptr);
615 if (const CarlaPluginInfo
* const pluginInfo
= carla_get_plugin_info(gHostHandle
, 0))
617 if (itype
== CARLA_BACKEND_NAMESPACE::PLUGIN_INTERNAL
&& (std::strcmp(label
, "audiofile") == 0 || std::strcmp(label
, "midifile") == 0))
620 carla_set_custom_data(gHostHandle
, 0,
621 CARLA_BACKEND_NAMESPACE::CUSTOM_DATA_TYPE_STRING
,
622 "file", file
.getFullPathName().toRawUTF8());
624 else if (pluginInfo
->hints
& CARLA_BACKEND_NAMESPACE::PLUGIN_HAS_CUSTOM_UI
)
627 if (std::getenv("DISPLAY") != nullptr)
630 carla_show_custom_ui(gHostHandle
, 0, true);
633 // on standalone usage, enable everything that makes sense
634 const uint optsAvailable
= pluginInfo
->optionsAvailable
;
635 if (optsAvailable
& CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS
)
636 carla_set_option(gHostHandle
, 0, CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS
, true);
640 bridge
.exec(useBridge
);
646 const char* const lastError(carla_get_last_error(gHostHandle
));
647 carla_stderr("Plugin failed to load, error was:\n%s", lastError
);
651 // do a single idle so that we can send error message to server
655 // kill ourselves now if we can't load plugin in bridge mode
656 ::kill(::getpid(), SIGKILL
);
663 #ifndef __WINPTHREADS_VERSION
664 pthread_win32_thread_detach_np();
665 pthread_win32_process_detach_np();