Remove juce completely, cleanup
[carla.git] / source / bridges-plugin / CarlaBridgePlugin.cpp
blob843e1188333e95caef5ced06e0fb3772f828ef36
1 /*
2 * Carla Bridge Plugin
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.
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 LONG WINAPI winExceptionFilter(_EXCEPTION_POINTERS*)
89 return EXCEPTION_EXECUTE_HANDLER;
92 static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
94 if (dwCtrlType == CTRL_C_EVENT)
96 gCloseSignal = true;
97 return TRUE;
99 return FALSE;
101 #endif
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);
123 #endif
126 // -------------------------------------------------------------------------
128 static String gProjectFilename;
129 static CarlaHostHandle gHostHandle;
131 static void gIdle()
133 carla_engine_idle(gHostHandle);
135 if (gSaveNow)
137 gSaveNow = false;
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
151 public:
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)
154 : fEngine(nullptr),
155 fUsingBridge(false),
156 fUsingExec(false)
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);
164 if (useBridge)
166 carla_engine_init_bridge(gHostHandle,
167 audioPoolBaseName,
168 rtClientBaseName,
169 nonRtClientBaseName,
170 nonRtServerBaseName,
171 clientName);
173 else if (std::getenv("CARLA_BRIDGE_DUMMY") != nullptr)
175 carla_engine_init(gHostHandle, "Dummy", clientName);
177 else
179 carla_engine_init(gHostHandle, "JACK", clientName);
182 fEngine = carla_get_engine_from_handle(gHostHandle);
185 ~CarlaBridgePlugin()
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;
203 fUsingExec = true;
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");
222 else
223 carla_stderr("Plugin state load failed, error was:\n%s", carla_get_last_error(gHostHandle));
225 else
227 carla_stdout("Previous plugin state in '%s' is non-existent, will start from default state",
228 gProjectFilename.toRawUTF8());
232 gIsInitiated = true;
234 int64_t timeToEnd = 0;
236 if (testing)
238 timeToEnd = water::Time::currentTimeMillis() + 5 * 1000;
239 fEngine->transportPlay();
242 for (; runMainLoopOnce() && ! gCloseBridge;)
244 gIdle();
245 #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
246 // MacOS and Win32 have event-loops to run, so minimize sleep time
247 carla_msleep(1);
248 #else
249 carla_msleep(5);
250 #endif
251 if (testing && timeToEnd - water::Time::currentTimeMillis() < 0)
252 break;
253 if (gCloseSignal && ! fUsingBridge)
254 break;
257 carla_engine_close(gHostHandle);
260 // ---------------------------------------------------------------------
262 protected:
263 void handleCallback(const EngineCallbackOpcode action,
264 const int value1,
265 const int, const int, const float, const char* const)
267 CARLA_BACKEND_USE_NAMESPACE;
269 switch (action)
271 case ENGINE_CALLBACK_ENGINE_STOPPED:
272 case ENGINE_CALLBACK_PLUGIN_REMOVED:
273 case ENGINE_CALLBACK_QUIT:
274 gCloseBridge = gCloseSignal = true;
275 break;
277 case ENGINE_CALLBACK_UI_STATE_CHANGED:
278 if (gIsInitiated && value1 != 1 && ! fUsingBridge)
279 gCloseBridge = gCloseSignal = true;
280 break;
282 default:
283 break;
287 private:
288 CarlaEngine* fEngine;
290 bool fUsingBridge;
291 bool fUsingExec;
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)
308 #endif
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]);
329 return 1;
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");
339 return 1;
341 #endif
343 // ---------------------------------------------------------------------
344 // Get args
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)
352 filename = nullptr;
354 if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
355 label = nullptr;
357 // ---------------------------------------------------------------------
358 // Check binary type
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);
368 return 1;
371 // ---------------------------------------------------------------------
372 // Check plugin type
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);
379 return 1;
382 // ---------------------------------------------------------------------
383 // Set file
385 const File file(filename != nullptr ? filename : "");
387 // ---------------------------------------------------------------------
388 // Set name
390 const char* name(std::getenv("CARLA_CLIENT_NAME"));
392 if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
393 name = nullptr;
395 // ---------------------------------------------------------------------
396 // Setup options
398 const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
400 const bool useBridge = (shmIds != nullptr);
402 // ---------------------------------------------------------------------
403 // Setup bridge ids
405 char audioPoolBaseName[6+1];
406 char rtClientBaseName[6+1];
407 char nonRtClientBaseName[6+1];
408 char nonRtServerBaseName[6+1];
410 if (useBridge)
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);
423 else
425 audioPoolBaseName[0] = '\0';
426 rtClientBaseName[0] = '\0';
427 nonRtClientBaseName[0] = '\0';
428 nonRtServerBaseName[0] = '\0';
429 jackbridge_init();
432 // ---------------------------------------------------------------------
433 // Set client name
435 CarlaString clientName;
437 if (name != nullptr)
439 clientName = name;
441 else if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_LV2)
443 // LV2 requires URI
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]))
453 continue;
455 label2.truncate(i+1);
456 break;
459 // get last used separator
460 bool found;
461 std::size_t septmp, sep = 0;
463 septmp = label2.rfind('#', &found)+1;
464 if (found && septmp > sep)
465 sep = septmp;
467 septmp = label2.rfind('/', &found)+1;
468 if (found && septmp > sep)
469 sep = septmp;
471 septmp = label2.rfind('=', &found)+1;
472 if (found && septmp > sep)
473 sep = septmp;
475 septmp = label2.rfind(':', &found)+1;
476 if (found && septmp > sep)
477 sep = septmp;
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) {}
483 if (*name2 != '\0')
484 clientName = name2;
486 else if (label != nullptr)
488 clientName = label;
490 else
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";
499 // just to be safe
500 clientName.toBasic();
502 // ---------------------------------------------------------------------
503 // Set extraStuff
505 const void* extraStuff = nullptr;
507 if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_SF2)
509 if (label == nullptr)
510 label = clientName;
512 if (std::strstr(label, " (16 outs)") != nullptr)
513 extraStuff = "true";
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;
522 #ifdef CARLA_OS_MAC
523 CARLA_BACKEND_NAMESPACE::initStandaloneApplication();
524 #endif
526 #ifdef CARLA_OS_WIN
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();
533 # endif
534 #endif
536 #ifdef HAVE_X11
537 if (std::getenv("DISPLAY") != nullptr)
538 XInitThreads();
539 #endif
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
553 if (nice(-5) < 0)
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());
566 #endif
568 #ifdef CARLA_OS_WIN
569 if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
570 carla_stderr("Failed to set high priority.");
571 #endif
574 // ---------------------------------------------------------------------
575 // Listen for ctrl+c or sigint/sigterm events
577 initSignalHandler();
579 // ---------------------------------------------------------------------
580 // Init plugin bridge
582 int ret;
585 gHostHandle = carla_standalone_host_init();
587 CarlaBridgePlugin bridge(useBridge, clientName,
588 audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
590 if (! bridge.isOk())
592 carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error(gHostHandle));
593 return 1;
596 if (! useBridge && ! testing)
598 #ifdef HAVE_X11
599 if (std::getenv("DISPLAY") != nullptr)
600 #endif
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),
604 nullptr);
607 // -----------------------------------------------------------------
608 // Init plugin
610 if (carla_add_plugin(gHostHandle,
611 btype, itype,
612 file.getFullPathName().toRawUTF8(), name, label, uniqueId, extraStuff,
613 CARLA_BACKEND_NAMESPACE::PLUGIN_OPTIONS_NULL))
615 ret = 0;
617 if (! useBridge)
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))
626 if (file.exists())
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)
633 #ifdef HAVE_X11
634 if (std::getenv("DISPLAY") != nullptr)
635 #endif
636 if (! testing)
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);
649 else
651 ret = 1;
653 const char* const lastError(carla_get_last_error(gHostHandle));
654 carla_stderr("Plugin failed to load, error was:\n%s", lastError);
656 if (useBridge)
658 // do a single idle so that we can send error message to server
659 gIdle();
661 #ifdef CARLA_OS_UNIX
662 // kill ourselves now if we can't load plugin in bridge mode
663 ::kill(::getpid(), SIGKILL);
664 #endif
669 #ifdef CARLA_OS_WIN
670 #ifndef __WINPTHREADS_VERSION
671 pthread_win32_thread_detach_np();
672 pthread_win32_process_detach_np();
673 #endif
674 CoUninitialize();
675 OleUninitialize();
676 #endif
678 return ret;