Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

666 lines
20KB

  1. // SPDX-FileCopyrightText: 2011-2025 Filipe Coelho <falktx@falktx.com>
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #ifndef BUILD_BRIDGE
  4. # error This file should not be compiled if not building bridge
  5. #endif
  6. #include "CarlaEngine.hpp"
  7. #include "CarlaHost.h"
  8. #include "CarlaUtils.h"
  9. #include "CarlaBackendUtils.hpp"
  10. #include "CarlaJuceUtils.hpp"
  11. #include "CarlaMainLoop.hpp"
  12. #include "CarlaMIDI.h"
  13. #ifdef CARLA_OS_MAC
  14. # include "CarlaMacUtils.hpp"
  15. #endif
  16. #ifdef CARLA_OS_UNIX
  17. # include <signal.h>
  18. #endif
  19. #ifdef CARLA_OS_LINUX
  20. # include <sched.h>
  21. # define SCHED_RESET_ON_FORK 0x40000000
  22. #endif
  23. #ifdef CARLA_OS_WIN
  24. # include <pthread.h>
  25. # include <objbase.h>
  26. #endif
  27. #ifdef HAVE_X11
  28. # include <X11/Xlib.h>
  29. #endif
  30. #include "distrho/extra/Sleep.hpp"
  31. #include "water/files/File.h"
  32. #include "water/misc/Time.h"
  33. // must be last
  34. #include "jackbridge/JackBridge.hpp"
  35. using CARLA_BACKEND_NAMESPACE::CarlaEngine;
  36. using CARLA_BACKEND_NAMESPACE::EngineCallbackOpcode;
  37. using CARLA_BACKEND_NAMESPACE::EngineCallbackOpcode2Str;
  38. using CARLA_BACKEND_NAMESPACE::runMainLoopOnce;
  39. using water::CharPointer_UTF8;
  40. using water::File;
  41. // -------------------------------------------------------------------------
  42. static bool gIsInitiated = false;
  43. static volatile bool gCloseBridge = false;
  44. static volatile bool gCloseSignal = false;
  45. static volatile bool gSaveNow = false;
  46. #if defined(CARLA_OS_UNIX)
  47. static void closeSignalHandler(int) noexcept
  48. {
  49. gCloseSignal = true;
  50. }
  51. static void saveSignalHandler(int) noexcept
  52. {
  53. gSaveNow = true;
  54. }
  55. #elif defined(CARLA_OS_WIN)
  56. static LONG WINAPI winExceptionFilter(_EXCEPTION_POINTERS*)
  57. {
  58. return EXCEPTION_EXECUTE_HANDLER;
  59. }
  60. static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
  61. {
  62. if (dwCtrlType == CTRL_C_EVENT)
  63. {
  64. gCloseSignal = true;
  65. return TRUE;
  66. }
  67. return FALSE;
  68. }
  69. #endif
  70. static void initSignalHandler()
  71. {
  72. #if defined(CARLA_OS_UNIX)
  73. struct sigaction sig;
  74. carla_zeroStruct(sig);
  75. sig.sa_handler = closeSignalHandler;
  76. sig.sa_flags = SA_RESTART;
  77. sigemptyset(&sig.sa_mask);
  78. sigaction(SIGTERM, &sig, nullptr);
  79. sigaction(SIGINT, &sig, nullptr);
  80. sig.sa_handler = saveSignalHandler;
  81. sig.sa_flags = SA_RESTART;
  82. sigemptyset(&sig.sa_mask);
  83. sigaction(SIGUSR1, &sig, nullptr);
  84. #elif defined(CARLA_OS_WIN)
  85. SetConsoleCtrlHandler(winSignalHandler, TRUE);
  86. SetErrorMode(SEM_NOGPFAULTERRORBOX);
  87. SetUnhandledExceptionFilter(winExceptionFilter);
  88. #endif
  89. }
  90. // -------------------------------------------------------------------------
  91. static CarlaHostHandle gHostHandle;
  92. static String gProjectFilename;
  93. static void gIdle()
  94. {
  95. carla_engine_idle(gHostHandle);
  96. if (gSaveNow)
  97. {
  98. gSaveNow = false;
  99. if (gProjectFilename.isNotEmpty())
  100. {
  101. if (! carla_save_plugin_state(gHostHandle, 0, gProjectFilename))
  102. carla_stderr("Plugin preset save failed, error was:\n%s", carla_get_last_error(gHostHandle));
  103. }
  104. }
  105. }
  106. // -------------------------------------------------------------------------
  107. class CarlaBridgePlugin
  108. {
  109. public:
  110. CarlaBridgePlugin(const bool useBridge, const char* const clientName, const char* const audioPoolBaseName,
  111. const char* const rtClientBaseName, const char* const nonRtClientBaseName, const char* const nonRtServerBaseName)
  112. : fEngine(nullptr),
  113. fUsingBridge(false),
  114. fUsingExec(false)
  115. {
  116. CARLA_ASSERT(clientName != nullptr && clientName[0] != '\0');
  117. carla_debug("CarlaBridgePlugin::CarlaBridgePlugin(%s, \"%s\", %s, %s, %s, %s)",
  118. bool2str(useBridge), clientName, audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  119. carla_set_engine_callback(gHostHandle, callback, this);
  120. if (useBridge)
  121. {
  122. carla_engine_init_bridge(gHostHandle,
  123. audioPoolBaseName,
  124. rtClientBaseName,
  125. nonRtClientBaseName,
  126. nonRtServerBaseName,
  127. clientName);
  128. }
  129. else if (std::getenv("CARLA_BRIDGE_DUMMY") != nullptr)
  130. {
  131. carla_engine_init(gHostHandle, "Dummy", clientName);
  132. }
  133. else
  134. {
  135. carla_engine_init(gHostHandle, "JACK", clientName);
  136. }
  137. fEngine = carla_get_engine_from_handle(gHostHandle);
  138. }
  139. ~CarlaBridgePlugin()
  140. {
  141. carla_debug("CarlaBridgePlugin::~CarlaBridgePlugin()");
  142. if (fEngine != nullptr && ! fUsingExec)
  143. carla_engine_close(gHostHandle);
  144. }
  145. bool isOk() const noexcept
  146. {
  147. return (fEngine != nullptr);
  148. }
  149. // ---------------------------------------------------------------------
  150. void exec(const bool useBridge)
  151. {
  152. fUsingBridge = useBridge;
  153. fUsingExec = true;
  154. const bool testing = std::getenv("CARLA_BRIDGE_TESTING") != nullptr;
  155. if (! useBridge && ! testing)
  156. {
  157. const CarlaPluginInfo* const pInfo = carla_get_plugin_info(gHostHandle, 0);
  158. CARLA_SAFE_ASSERT_RETURN(pInfo != nullptr,);
  159. gProjectFilename = pInfo->name;
  160. gProjectFilename += ".carxs";
  161. if (! File::isAbsolutePath(gProjectFilename))
  162. gProjectFilename = File::getCurrentWorkingDirectory().getChildFile(gProjectFilename).getFullPathName().toRawUTF8();
  163. if (File(gProjectFilename).existsAsFile())
  164. {
  165. if (carla_load_plugin_state(gHostHandle, 0, gProjectFilename))
  166. carla_stdout("Plugin state loaded successfully");
  167. else
  168. carla_stderr("Plugin state load failed, error was:\n%s", carla_get_last_error(gHostHandle));
  169. }
  170. else
  171. {
  172. carla_stdout("Previous plugin state in '%s' is non-existent, will start from default state",
  173. gProjectFilename.buffer());
  174. }
  175. }
  176. gIsInitiated = true;
  177. int64_t timeToEnd = 0;
  178. if (testing)
  179. {
  180. timeToEnd = water::Time::currentTimeMillis() + 5 * 1000;
  181. fEngine->transportPlay();
  182. }
  183. for (; runMainLoopOnce() && ! gCloseBridge;)
  184. {
  185. gIdle();
  186. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  187. // MacOS and Win32 have event-loops to run, so minimize sleep time
  188. d_msleep(1);
  189. #else
  190. d_msleep(5);
  191. #endif
  192. if (testing && timeToEnd - water::Time::currentTimeMillis() < 0)
  193. break;
  194. if (gCloseSignal && ! fUsingBridge)
  195. break;
  196. }
  197. carla_engine_close(gHostHandle);
  198. }
  199. // ---------------------------------------------------------------------
  200. protected:
  201. void handleCallback(const EngineCallbackOpcode action,
  202. const int value1,
  203. const int, const int, const float, const char* const)
  204. {
  205. CARLA_BACKEND_USE_NAMESPACE;
  206. switch (action)
  207. {
  208. case ENGINE_CALLBACK_ENGINE_STOPPED:
  209. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  210. case ENGINE_CALLBACK_QUIT:
  211. gCloseBridge = gCloseSignal = true;
  212. break;
  213. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  214. if (gIsInitiated && value1 != 1 && ! fUsingBridge)
  215. gCloseBridge = gCloseSignal = true;
  216. break;
  217. default:
  218. break;
  219. }
  220. }
  221. private:
  222. CarlaEngine* fEngine;
  223. bool fUsingBridge;
  224. bool fUsingExec;
  225. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId,
  226. int value1, int value2, int value3,
  227. float valuef, const char* valueStr)
  228. {
  229. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  230. ptr, action, EngineCallbackOpcode2Str(action),
  231. pluginId, value1, value2, value3, static_cast<double>(valuef), valueStr);
  232. // ptr must not be null
  233. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  234. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  235. // pluginId must be 0 (first), except for patchbay things
  236. if (action < CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED ||
  237. action > CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED)
  238. #endif
  239. {
  240. CARLA_SAFE_ASSERT_UINT_RETURN(pluginId == 0, pluginId,);
  241. }
  242. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valuef, valueStr);
  243. }
  244. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  245. };
  246. // -------------------------------------------------------------------------
  247. int main(int argc, char* argv[])
  248. {
  249. // ---------------------------------------------------------------------
  250. // Check argument count
  251. if (argc != 4 && argc != 5)
  252. {
  253. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  254. return 1;
  255. }
  256. #if defined(CARLA_OS_WIN) && defined(BUILDING_CARLA_FOR_WINE)
  257. // ---------------------------------------------------------------------
  258. // Test if bridge is working
  259. if (! jackbridge_is_ok())
  260. {
  261. carla_stderr("A JACK or Wine library is missing, cannot continue");
  262. return 1;
  263. }
  264. #endif
  265. // ---------------------------------------------------------------------
  266. // Get args
  267. const char* const stype = argv[1];
  268. const char* filename = argv[2];
  269. const char* label = argv[3];
  270. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  271. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  272. filename = nullptr;
  273. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  274. label = nullptr;
  275. // ---------------------------------------------------------------------
  276. // Check binary type
  277. CARLA_BACKEND_NAMESPACE::BinaryType btype = CARLA_BACKEND_NAMESPACE::BINARY_NATIVE;
  278. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  279. btype = CARLA_BACKEND_NAMESPACE::getBinaryTypeFromString(binaryTypeStr);
  280. if (btype == CARLA_BACKEND_NAMESPACE::BINARY_NONE)
  281. {
  282. carla_stderr("Invalid binary type '%i'", btype);
  283. return 1;
  284. }
  285. // ---------------------------------------------------------------------
  286. // Check plugin type
  287. CARLA_BACKEND_NAMESPACE::PluginType itype = CARLA_BACKEND_NAMESPACE::getPluginTypeFromString(stype);
  288. if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_NONE)
  289. {
  290. carla_stderr("Invalid plugin type '%s'", stype);
  291. return 1;
  292. }
  293. // ---------------------------------------------------------------------
  294. // Set file
  295. const File file(filename != nullptr ? filename : "");
  296. // ---------------------------------------------------------------------
  297. // Set name
  298. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  299. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  300. name = nullptr;
  301. // ---------------------------------------------------------------------
  302. // Setup options
  303. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  304. const bool useBridge = (shmIds != nullptr);
  305. // ---------------------------------------------------------------------
  306. // Setup bridge ids
  307. char audioPoolBaseName[6+1];
  308. char rtClientBaseName[6+1];
  309. char nonRtClientBaseName[6+1];
  310. char nonRtServerBaseName[6+1];
  311. if (useBridge)
  312. {
  313. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  314. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  315. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  316. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  317. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  318. audioPoolBaseName[6] = '\0';
  319. rtClientBaseName[6] = '\0';
  320. nonRtClientBaseName[6] = '\0';
  321. nonRtServerBaseName[6] = '\0';
  322. jackbridge_parent_deathsig(false);
  323. }
  324. else
  325. {
  326. audioPoolBaseName[0] = '\0';
  327. rtClientBaseName[0] = '\0';
  328. nonRtClientBaseName[0] = '\0';
  329. nonRtServerBaseName[0] = '\0';
  330. jackbridge_init();
  331. }
  332. // ---------------------------------------------------------------------
  333. // Set client name
  334. String clientName;
  335. if (name != nullptr)
  336. {
  337. clientName = name;
  338. }
  339. else if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_LV2)
  340. {
  341. // LV2 requires URI
  342. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  343. // LV2 URI is not usable as client name, create a usable name from URI
  344. String label2(label);
  345. // truncate until last valid char
  346. for (std::size_t i=label2.length()-1; i != 0; --i)
  347. {
  348. if (! std::isalnum(label2[i]))
  349. continue;
  350. label2.truncate(i+1);
  351. break;
  352. }
  353. // get last used separator
  354. bool found;
  355. std::size_t septmp, sep = 0;
  356. septmp = label2.rfind('#', &found)+1;
  357. if (found && septmp > sep)
  358. sep = septmp;
  359. septmp = label2.rfind('/', &found)+1;
  360. if (found && septmp > sep)
  361. sep = septmp;
  362. septmp = label2.rfind('=', &found)+1;
  363. if (found && septmp > sep)
  364. sep = septmp;
  365. septmp = label2.rfind(':', &found)+1;
  366. if (found && septmp > sep)
  367. sep = septmp;
  368. // make name starting from the separator and first valid char
  369. const char* name2 = label2.buffer() + sep;
  370. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  371. if (*name2 != '\0')
  372. clientName = name2;
  373. }
  374. else if (label != nullptr)
  375. {
  376. clientName = label;
  377. }
  378. else
  379. {
  380. clientName = file.getFileNameWithoutExtension().toRawUTF8();
  381. }
  382. // if we still have no client name by now, use a dummy one
  383. if (clientName.isEmpty())
  384. clientName = "carla-plugin";
  385. // just to be safe
  386. clientName.toBasic();
  387. // ---------------------------------------------------------------------
  388. // Set extraStuff
  389. const void* extraStuff = nullptr;
  390. if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_SF2)
  391. {
  392. if (label == nullptr)
  393. label = clientName;
  394. if (std::strstr(label, " (16 outs)") != nullptr)
  395. extraStuff = "true";
  396. }
  397. // ---------------------------------------------------------------------
  398. // Initialize OS features
  399. const bool dummy = std::getenv("CARLA_BRIDGE_DUMMY") != nullptr;
  400. const bool testing = std::getenv("CARLA_BRIDGE_TESTING") != nullptr;
  401. #ifdef CARLA_OS_MAC
  402. CARLA_BACKEND_NAMESPACE::initStandaloneApplication();
  403. #endif
  404. #ifdef CARLA_OS_WIN
  405. OleInitialize(nullptr);
  406. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  407. # ifndef __WINPTHREADS_VERSION
  408. // (non-portable) initialization of statically linked pthread library
  409. pthread_win32_process_attach_np();
  410. pthread_win32_thread_attach_np();
  411. # endif
  412. #endif
  413. #ifdef HAVE_X11
  414. if (std::getenv("DISPLAY") != nullptr)
  415. XInitThreads();
  416. #endif
  417. // ---------------------------------------------------------------------
  418. // Set ourselves with high priority
  419. if (!dummy && !testing)
  420. {
  421. #ifdef CARLA_OS_LINUX
  422. // reset scheduler to normal mode
  423. struct sched_param sparam;
  424. carla_zeroStruct(sparam);
  425. sched_setscheduler(0, SCHED_OTHER|SCHED_RESET_ON_FORK, &sparam);
  426. // try niceness first, if it fails, try SCHED_RR
  427. if (nice(-5) < 0)
  428. {
  429. sparam.sched_priority = (sched_get_priority_max(SCHED_RR) + sched_get_priority_min(SCHED_RR*7)) / 8;
  430. if (sparam.sched_priority > 0)
  431. {
  432. if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &sparam) < 0)
  433. {
  434. String error(std::strerror(errno));
  435. carla_stderr("Failed to set high priority, error %i: %s", errno, error.buffer());
  436. }
  437. }
  438. }
  439. #endif
  440. #ifdef CARLA_OS_WIN
  441. if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
  442. carla_stderr("Failed to set high priority.");
  443. #endif
  444. }
  445. // ---------------------------------------------------------------------
  446. // Listen for ctrl+c or sigint/sigterm events
  447. initSignalHandler();
  448. // ---------------------------------------------------------------------
  449. // Init plugin bridge
  450. int ret;
  451. {
  452. gHostHandle = carla_standalone_host_init();
  453. CarlaBridgePlugin bridge(useBridge, clientName,
  454. audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  455. if (! bridge.isOk())
  456. {
  457. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error(gHostHandle));
  458. return 1;
  459. }
  460. if (! useBridge && ! testing)
  461. {
  462. #ifdef HAVE_X11
  463. if (std::getenv("DISPLAY") != nullptr)
  464. #endif
  465. carla_set_engine_option(gHostHandle,
  466. CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_FRONTEND_UI_SCALE,
  467. static_cast<int>(carla_get_desktop_scale_factor()*1000+0.5),
  468. nullptr);
  469. }
  470. // -----------------------------------------------------------------
  471. // Init plugin
  472. if (carla_add_plugin(gHostHandle,
  473. btype, itype,
  474. file.getFullPathName().toRawUTF8(), name, label, uniqueId, extraStuff,
  475. CARLA_BACKEND_NAMESPACE::PLUGIN_OPTIONS_NULL))
  476. {
  477. ret = 0;
  478. if (! useBridge)
  479. {
  480. carla_set_active(gHostHandle, 0, true);
  481. carla_set_engine_option(gHostHandle, CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_PLUGINS_ARE_STANDALONE, 1, nullptr);
  482. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(gHostHandle, 0))
  483. {
  484. if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_INTERNAL && (std::strcmp(label, "audiofile") == 0 || std::strcmp(label, "midifile") == 0))
  485. {
  486. if (file.exists())
  487. carla_set_custom_data(gHostHandle, 0,
  488. CARLA_BACKEND_NAMESPACE::CUSTOM_DATA_TYPE_STRING,
  489. "file", file.getFullPathName().toRawUTF8());
  490. }
  491. else if (pluginInfo->hints & CARLA_BACKEND_NAMESPACE::PLUGIN_HAS_CUSTOM_UI)
  492. {
  493. #ifdef HAVE_X11
  494. if (std::getenv("DISPLAY") != nullptr)
  495. #endif
  496. if (! testing)
  497. carla_show_custom_ui(gHostHandle, 0, true);
  498. }
  499. // on standalone usage, enable everything that makes sense
  500. const uint optsAvailable = pluginInfo->optionsAvailable;
  501. if (optsAvailable & CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS)
  502. carla_set_option(gHostHandle, 0, CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS, true);
  503. }
  504. }
  505. bridge.exec(useBridge);
  506. }
  507. else
  508. {
  509. ret = 1;
  510. const char* const lastError(carla_get_last_error(gHostHandle));
  511. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  512. if (useBridge)
  513. {
  514. // do a single idle so that we can send error message to server
  515. gIdle();
  516. #ifdef CARLA_OS_UNIX
  517. // kill ourselves now if we can't load plugin in bridge mode
  518. ::kill(::getpid(), SIGKILL);
  519. #endif
  520. }
  521. }
  522. }
  523. #ifdef CARLA_OS_WIN
  524. #ifndef __WINPTHREADS_VERSION
  525. pthread_win32_thread_detach_np();
  526. pthread_win32_process_detach_np();
  527. #endif
  528. CoUninitialize();
  529. OleUninitialize();
  530. #endif
  531. return ret;
  532. }