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