Fix last commit
[carla.git] / source / bridges-plugin / CarlaBridgePlugin.cpp
blobabc9b35d1b5bfd3eec407253bc1df9ccc98122f5
1 /*
2 * Carla Bridge Plugin
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.
18 #ifndef BUILD_BRIDGE
19 # error This file should not be compiled if not building bridge
20 #endif
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"
33 #ifdef CARLA_OS_MAC
34 # include "CarlaMacUtils.hpp"
35 #endif
37 #ifdef CARLA_OS_UNIX
38 # include <signal.h>
39 #endif
41 #ifdef CARLA_OS_LINUX
42 # include <sched.h>
43 # define SCHED_RESET_ON_FORK 0x40000000
44 #endif
46 #ifdef CARLA_OS_WIN
47 # include <pthread.h>
48 # include <objbase.h>
49 #endif
51 #ifdef HAVE_X11
52 # include <X11/Xlib.h>
53 #endif
55 #include "water/files/File.h"
56 #include "water/misc/Time.h"
58 // must be last
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;
67 using water::File;
68 using water::String;
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
80 gCloseSignal = true;
82 static void saveSignalHandler(int) noexcept
84 gSaveNow = true;
86 #elif defined(CARLA_OS_WIN)
87 static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
89 if (dwCtrlType == CTRL_C_EVENT)
91 gCloseSignal = true;
92 return TRUE;
94 return FALSE;
96 #endif
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);
116 #endif
119 // -------------------------------------------------------------------------
121 static String gProjectFilename;
122 static CarlaHostHandle gHostHandle;
124 static void gIdle()
126 carla_engine_idle(gHostHandle);
128 if (gSaveNow)
130 gSaveNow = false;
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
144 public:
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)
147 : fEngine(nullptr),
148 fUsingBridge(false),
149 fUsingExec(false)
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);
157 if (useBridge)
159 carla_engine_init_bridge(gHostHandle,
160 audioPoolBaseName,
161 rtClientBaseName,
162 nonRtClientBaseName,
163 nonRtServerBaseName,
164 clientName);
166 else if (std::getenv("CARLA_BRIDGE_DUMMY") != nullptr)
168 carla_engine_init(gHostHandle, "Dummy", clientName);
170 else
172 carla_engine_init(gHostHandle, "JACK", clientName);
175 fEngine = carla_get_engine_from_handle(gHostHandle);
178 ~CarlaBridgePlugin()
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;
196 fUsingExec = true;
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");
215 else
216 carla_stderr("Plugin state load failed, error was:\n%s", carla_get_last_error(gHostHandle));
218 else
220 carla_stdout("Previous plugin state in '%s' is non-existent, will start from default state",
221 gProjectFilename.toRawUTF8());
225 gIsInitiated = true;
227 int64_t timeToEnd = 0;
229 if (testing)
231 timeToEnd = water::Time::currentTimeMillis() + 5 * 1000;
232 fEngine->transportPlay();
235 for (; runMainLoopOnce() && ! gCloseBridge;)
237 gIdle();
238 #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
239 // MacOS and Win32 have event-loops to run, so minimize sleep time
240 carla_msleep(1);
241 #else
242 carla_msleep(5);
243 #endif
244 if (testing && timeToEnd - water::Time::currentTimeMillis() < 0)
245 break;
246 if (gCloseSignal && ! fUsingBridge)
247 break;
250 carla_engine_close(gHostHandle);
253 // ---------------------------------------------------------------------
255 protected:
256 void handleCallback(const EngineCallbackOpcode action,
257 const int value1,
258 const int, const int, const float, const char* const)
260 CARLA_BACKEND_USE_NAMESPACE;
262 switch (action)
264 case ENGINE_CALLBACK_ENGINE_STOPPED:
265 case ENGINE_CALLBACK_PLUGIN_REMOVED:
266 case ENGINE_CALLBACK_QUIT:
267 gCloseBridge = gCloseSignal = true;
268 break;
270 case ENGINE_CALLBACK_UI_STATE_CHANGED:
271 if (gIsInitiated && value1 != 1 && ! fUsingBridge)
272 gCloseBridge = gCloseSignal = true;
273 break;
275 default:
276 break;
280 private:
281 CarlaEngine* fEngine;
283 bool fUsingBridge;
284 bool fUsingExec;
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)
301 #endif
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]);
322 return 1;
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");
332 return 1;
334 #endif
336 // ---------------------------------------------------------------------
337 // Get args
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)
345 filename = nullptr;
347 if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
348 label = nullptr;
350 // ---------------------------------------------------------------------
351 // Check binary type
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);
361 return 1;
364 // ---------------------------------------------------------------------
365 // Check plugin type
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);
372 return 1;
375 // ---------------------------------------------------------------------
376 // Set file
378 const File file(filename != nullptr ? filename : "");
380 // ---------------------------------------------------------------------
381 // Set name
383 const char* name(std::getenv("CARLA_CLIENT_NAME"));
385 if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
386 name = nullptr;
388 // ---------------------------------------------------------------------
389 // Setup options
391 const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
393 const bool useBridge = (shmIds != nullptr);
395 // ---------------------------------------------------------------------
396 // Setup bridge ids
398 char audioPoolBaseName[6+1];
399 char rtClientBaseName[6+1];
400 char nonRtClientBaseName[6+1];
401 char nonRtServerBaseName[6+1];
403 if (useBridge)
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);
416 else
418 audioPoolBaseName[0] = '\0';
419 rtClientBaseName[0] = '\0';
420 nonRtClientBaseName[0] = '\0';
421 nonRtServerBaseName[0] = '\0';
422 jackbridge_init();
425 // ---------------------------------------------------------------------
426 // Set client name
428 CarlaString clientName;
430 if (name != nullptr)
432 clientName = name;
434 else if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_LV2)
436 // LV2 requires URI
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]))
446 continue;
448 label2.truncate(i+1);
449 break;
452 // get last used separator
453 bool found;
454 std::size_t septmp, sep = 0;
456 septmp = label2.rfind('#', &found)+1;
457 if (found && septmp > sep)
458 sep = septmp;
460 septmp = label2.rfind('/', &found)+1;
461 if (found && septmp > sep)
462 sep = septmp;
464 septmp = label2.rfind('=', &found)+1;
465 if (found && septmp > sep)
466 sep = septmp;
468 septmp = label2.rfind(':', &found)+1;
469 if (found && septmp > sep)
470 sep = septmp;
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) {}
476 if (*name2 != '\0')
477 clientName = name2;
479 else if (label != nullptr)
481 clientName = label;
483 else
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";
492 // just to be safe
493 clientName.toBasic();
495 // ---------------------------------------------------------------------
496 // Set extraStuff
498 const void* extraStuff = nullptr;
500 if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_SF2)
502 if (label == nullptr)
503 label = clientName;
505 if (std::strstr(label, " (16 outs)") != nullptr)
506 extraStuff = "true";
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;
515 #ifdef CARLA_OS_MAC
516 CARLA_BACKEND_NAMESPACE::initStandaloneApplication();
517 #endif
519 #ifdef CARLA_OS_WIN
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();
526 # endif
527 #endif
529 #ifdef HAVE_X11
530 if (std::getenv("DISPLAY") != nullptr)
531 XInitThreads();
532 #endif
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
546 if (nice(-5) < 0)
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());
559 #endif
561 #ifdef CARLA_OS_WIN
562 if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
563 carla_stderr("Failed to set high priority.");
564 #endif
567 // ---------------------------------------------------------------------
568 // Listen for ctrl+c or sigint/sigterm events
570 initSignalHandler();
572 // ---------------------------------------------------------------------
573 // Init plugin bridge
575 int ret;
578 gHostHandle = carla_standalone_host_init();
580 CarlaBridgePlugin bridge(useBridge, clientName,
581 audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
583 if (! bridge.isOk())
585 carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error(gHostHandle));
586 return 1;
589 if (! useBridge && ! testing)
591 #ifdef HAVE_X11
592 if (std::getenv("DISPLAY") != nullptr)
593 #endif
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),
597 nullptr);
600 // -----------------------------------------------------------------
601 // Init plugin
603 if (carla_add_plugin(gHostHandle,
604 btype, itype,
605 file.getFullPathName().toRawUTF8(), name, label, uniqueId, extraStuff,
606 CARLA_BACKEND_NAMESPACE::PLUGIN_OPTIONS_NULL))
608 ret = 0;
610 if (! useBridge)
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))
619 if (file.exists())
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)
626 #ifdef HAVE_X11
627 if (std::getenv("DISPLAY") != nullptr)
628 #endif
629 if (! testing)
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);
642 else
644 ret = 1;
646 const char* const lastError(carla_get_last_error(gHostHandle));
647 carla_stderr("Plugin failed to load, error was:\n%s", lastError);
649 if (useBridge)
651 // do a single idle so that we can send error message to server
652 gIdle();
654 #ifdef CARLA_OS_UNIX
655 // kill ourselves now if we can't load plugin in bridge mode
656 ::kill(::getpid(), SIGKILL);
657 #endif
662 #ifdef CARLA_OS_WIN
663 #ifndef __WINPTHREADS_VERSION
664 pthread_win32_thread_detach_np();
665 pthread_win32_process_detach_np();
666 #endif
667 CoUninitialize();
668 OleUninitialize();
669 #endif
671 return ret;