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.

673 lines
20KB

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