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.

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