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.

688 lines
21KB

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