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.

686 lines
21KB

  1. /*
  2. * Carla Bridge Plugin
  3. * Copyright (C) 2012-2022 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 "CarlaMIDI.h"
  27. #ifdef CARLA_OS_MAC
  28. # include "CarlaMacUtils.hpp"
  29. #endif
  30. #ifdef CARLA_OS_UNIX
  31. # include <signal.h>
  32. #endif
  33. #ifdef CARLA_OS_LINUX
  34. # include <sched.h>
  35. # define SCHED_RESET_ON_FORK 0x40000000
  36. #endif
  37. #ifdef CARLA_OS_WIN
  38. # include <pthread.h>
  39. # include <objbase.h>
  40. #endif
  41. #ifdef HAVE_X11
  42. # include <X11/Xlib.h>
  43. #endif
  44. #ifdef USING_JUCE
  45. # include "carla_juce/carla_juce.h"
  46. #endif
  47. #include "water/files/File.h"
  48. #include "water/misc/Time.h"
  49. // must be last
  50. #include "jackbridge/JackBridge.hpp"
  51. using CARLA_BACKEND_NAMESPACE::CarlaEngine;
  52. using CARLA_BACKEND_NAMESPACE::EngineCallbackOpcode;
  53. using CARLA_BACKEND_NAMESPACE::EngineCallbackOpcode2Str;
  54. using CARLA_BACKEND_NAMESPACE::runMainLoopOnce;
  55. using water::CharPointer_UTF8;
  56. using water::File;
  57. using water::String;
  58. // -------------------------------------------------------------------------
  59. static bool gIsInitiated = false;
  60. static volatile bool gCloseBridge = false;
  61. static volatile bool gCloseSignal = false;
  62. static volatile bool gSaveNow = false;
  63. #if defined(CARLA_OS_UNIX)
  64. static void closeSignalHandler(int) noexcept
  65. {
  66. gCloseSignal = 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. gCloseSignal = 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, &gCloseSignal);
  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() && ! gCloseBridge;)
  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. if (gCloseSignal && ! fUsingBridge)
  212. break;
  213. }
  214. #endif
  215. carla_engine_close(gHostHandle);
  216. }
  217. // ---------------------------------------------------------------------
  218. protected:
  219. void handleCallback(const EngineCallbackOpcode action,
  220. const int value1,
  221. const int, const int, const float, const char* const)
  222. {
  223. CARLA_BACKEND_USE_NAMESPACE;
  224. switch (action)
  225. {
  226. case ENGINE_CALLBACK_ENGINE_STOPPED:
  227. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  228. case ENGINE_CALLBACK_QUIT:
  229. gCloseBridge = gCloseSignal = true;
  230. break;
  231. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  232. if (gIsInitiated && value1 != 1 && ! fUsingBridge)
  233. gCloseBridge = gCloseSignal = true;
  234. break;
  235. default:
  236. break;
  237. }
  238. }
  239. private:
  240. CarlaEngine* fEngine;
  241. #ifdef USING_JUCE
  242. const CarlaJUCE::ScopedJuceInitialiser_GUI fJuceInitialiser;
  243. #endif
  244. bool fUsingBridge;
  245. bool fUsingExec;
  246. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId,
  247. int value1, int value2, int value3,
  248. float valuef, const char* valueStr)
  249. {
  250. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  251. ptr, action, EngineCallbackOpcode2Str(action),
  252. pluginId, value1, value2, value3, static_cast<double>(valuef), valueStr);
  253. // ptr must not be null
  254. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  255. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  256. // pluginId must be 0 (first), except for patchbay things
  257. if (action < CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED ||
  258. action > CARLA_BACKEND_NAMESPACE::ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED)
  259. #endif
  260. {
  261. CARLA_SAFE_ASSERT_UINT_RETURN(pluginId == 0, pluginId,);
  262. }
  263. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valuef, valueStr);
  264. }
  265. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  266. };
  267. // -------------------------------------------------------------------------
  268. int main(int argc, char* argv[])
  269. {
  270. // ---------------------------------------------------------------------
  271. // Check argument count
  272. if (argc != 4 && argc != 5)
  273. {
  274. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  275. return 1;
  276. }
  277. #if defined(CARLA_OS_WIN) && defined(BUILDING_CARLA_FOR_WINE)
  278. // ---------------------------------------------------------------------
  279. // Test if bridge is working
  280. if (! jackbridge_is_ok())
  281. {
  282. carla_stderr("A JACK or Wine library is missing, cannot continue");
  283. return 1;
  284. }
  285. #endif
  286. // ---------------------------------------------------------------------
  287. // Get args
  288. const char* const stype = argv[1];
  289. const char* filename = argv[2];
  290. const char* label = argv[3];
  291. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  292. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  293. filename = nullptr;
  294. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  295. label = nullptr;
  296. // ---------------------------------------------------------------------
  297. // Check binary type
  298. CARLA_BACKEND_NAMESPACE::BinaryType btype = CARLA_BACKEND_NAMESPACE::BINARY_NATIVE;
  299. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  300. btype = CARLA_BACKEND_NAMESPACE::getBinaryTypeFromString(binaryTypeStr);
  301. if (btype == CARLA_BACKEND_NAMESPACE::BINARY_NONE)
  302. {
  303. carla_stderr("Invalid binary type '%i'", btype);
  304. return 1;
  305. }
  306. // ---------------------------------------------------------------------
  307. // Check plugin type
  308. CARLA_BACKEND_NAMESPACE::PluginType itype = CARLA_BACKEND_NAMESPACE::getPluginTypeFromString(stype);
  309. if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_NONE)
  310. {
  311. carla_stderr("Invalid plugin type '%s'", stype);
  312. return 1;
  313. }
  314. // ---------------------------------------------------------------------
  315. // Set file
  316. const File file(filename != nullptr ? filename : "");
  317. // ---------------------------------------------------------------------
  318. // Set name
  319. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  320. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  321. name = nullptr;
  322. // ---------------------------------------------------------------------
  323. // Setup options
  324. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  325. const bool useBridge = (shmIds != nullptr);
  326. // ---------------------------------------------------------------------
  327. // Setup bridge ids
  328. char audioPoolBaseName[6+1];
  329. char rtClientBaseName[6+1];
  330. char nonRtClientBaseName[6+1];
  331. char nonRtServerBaseName[6+1];
  332. if (useBridge)
  333. {
  334. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  335. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  336. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  337. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  338. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  339. audioPoolBaseName[6] = '\0';
  340. rtClientBaseName[6] = '\0';
  341. nonRtClientBaseName[6] = '\0';
  342. nonRtServerBaseName[6] = '\0';
  343. jackbridge_parent_deathsig(false);
  344. }
  345. else
  346. {
  347. audioPoolBaseName[0] = '\0';
  348. rtClientBaseName[0] = '\0';
  349. nonRtClientBaseName[0] = '\0';
  350. nonRtServerBaseName[0] = '\0';
  351. jackbridge_init();
  352. }
  353. // ---------------------------------------------------------------------
  354. // Set client name
  355. CarlaString clientName;
  356. if (name != nullptr)
  357. {
  358. clientName = name;
  359. }
  360. else if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_LV2)
  361. {
  362. // LV2 requires URI
  363. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  364. // LV2 URI is not usable as client name, create a usable name from URI
  365. CarlaString label2(label);
  366. // truncate until last valid char
  367. for (std::size_t i=label2.length()-1; i != 0; --i)
  368. {
  369. if (! std::isalnum(label2[i]))
  370. continue;
  371. label2.truncate(i+1);
  372. break;
  373. }
  374. // get last used separator
  375. bool found;
  376. std::size_t septmp, sep = 0;
  377. septmp = label2.rfind('#', &found)+1;
  378. if (found && septmp > sep)
  379. sep = septmp;
  380. septmp = label2.rfind('/', &found)+1;
  381. if (found && septmp > sep)
  382. sep = septmp;
  383. septmp = label2.rfind('=', &found)+1;
  384. if (found && septmp > sep)
  385. sep = septmp;
  386. septmp = label2.rfind(':', &found)+1;
  387. if (found && septmp > sep)
  388. sep = septmp;
  389. // make name starting from the separator and first valid char
  390. const char* name2 = label2.buffer() + sep;
  391. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  392. if (*name2 != '\0')
  393. clientName = name2;
  394. }
  395. else if (label != nullptr)
  396. {
  397. clientName = label;
  398. }
  399. else
  400. {
  401. clientName = file.getFileNameWithoutExtension().toRawUTF8();
  402. }
  403. // if we still have no client name by now, use a dummy one
  404. if (clientName.isEmpty())
  405. clientName = "carla-plugin";
  406. // just to be safe
  407. clientName.toBasic();
  408. // ---------------------------------------------------------------------
  409. // Set extraStuff
  410. const void* extraStuff = nullptr;
  411. if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_SF2)
  412. {
  413. if (label == nullptr)
  414. label = clientName;
  415. if (std::strstr(label, " (16 outs)") != nullptr)
  416. extraStuff = "true";
  417. }
  418. // ---------------------------------------------------------------------
  419. // Initialize OS features
  420. const bool dummy = std::getenv("CARLA_BRIDGE_DUMMY") != nullptr;
  421. const bool testing = std::getenv("CARLA_BRIDGE_TESTING") != nullptr;
  422. #ifdef CARLA_OS_MAC
  423. CARLA_BACKEND_NAMESPACE::initStandaloneApplication();
  424. #endif
  425. #ifdef CARLA_OS_WIN
  426. OleInitialize(nullptr);
  427. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  428. # ifndef __WINPTHREADS_VERSION
  429. // (non-portable) initialization of statically linked pthread library
  430. pthread_win32_process_attach_np();
  431. pthread_win32_thread_attach_np();
  432. # endif
  433. #endif
  434. #ifdef HAVE_X11
  435. if (std::getenv("DISPLAY") != nullptr)
  436. XInitThreads();
  437. #endif
  438. // ---------------------------------------------------------------------
  439. // Set ourselves with high priority
  440. if (!dummy && !testing)
  441. {
  442. #ifdef CARLA_OS_LINUX
  443. // reset scheduler to normal mode
  444. struct sched_param sparam;
  445. carla_zeroStruct(sparam);
  446. sched_setscheduler(0, SCHED_OTHER|SCHED_RESET_ON_FORK, &sparam);
  447. // try niceness first, if it fails, try SCHED_RR
  448. if (nice(-5) < 0)
  449. {
  450. sparam.sched_priority = (sched_get_priority_max(SCHED_RR) + sched_get_priority_min(SCHED_RR*7)) / 8;
  451. if (sparam.sched_priority > 0)
  452. {
  453. if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &sparam) < 0)
  454. {
  455. CarlaString error(std::strerror(errno));
  456. carla_stderr("Failed to set high priority, error %i: %s", errno, error.buffer());
  457. }
  458. }
  459. }
  460. #endif
  461. #ifdef CARLA_OS_WIN
  462. if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
  463. carla_stderr("Failed to set high priority.");
  464. #endif
  465. }
  466. // ---------------------------------------------------------------------
  467. // Listen for ctrl+c or sigint/sigterm events
  468. initSignalHandler();
  469. // ---------------------------------------------------------------------
  470. // Init plugin bridge
  471. int ret;
  472. {
  473. gHostHandle = carla_standalone_host_init();
  474. CarlaBridgePlugin bridge(useBridge, clientName,
  475. audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  476. if (! bridge.isOk())
  477. {
  478. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error(gHostHandle));
  479. return 1;
  480. }
  481. if (! useBridge && ! testing)
  482. {
  483. #ifdef HAVE_X11
  484. if (std::getenv("DISPLAY") != nullptr)
  485. #endif
  486. carla_set_engine_option(gHostHandle,
  487. CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_FRONTEND_UI_SCALE,
  488. static_cast<int>(carla_get_desktop_scale_factor()*1000+0.5),
  489. nullptr);
  490. }
  491. // -----------------------------------------------------------------
  492. // Init plugin
  493. if (carla_add_plugin(gHostHandle,
  494. btype, itype,
  495. file.getFullPathName().toRawUTF8(), name, label, uniqueId, extraStuff,
  496. CARLA_BACKEND_NAMESPACE::PLUGIN_OPTIONS_NULL))
  497. {
  498. ret = 0;
  499. if (! useBridge)
  500. {
  501. carla_set_active(gHostHandle, 0, true);
  502. carla_set_engine_option(gHostHandle, CARLA_BACKEND_NAMESPACE::ENGINE_OPTION_PLUGINS_ARE_STANDALONE, 1, nullptr);
  503. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(gHostHandle, 0))
  504. {
  505. if (itype == CARLA_BACKEND_NAMESPACE::PLUGIN_INTERNAL && (std::strcmp(label, "audiofile") == 0 || std::strcmp(label, "midifile") == 0))
  506. {
  507. if (file.exists())
  508. carla_set_custom_data(gHostHandle, 0,
  509. CARLA_BACKEND_NAMESPACE::CUSTOM_DATA_TYPE_STRING,
  510. "file", file.getFullPathName().toRawUTF8());
  511. }
  512. else if (pluginInfo->hints & CARLA_BACKEND_NAMESPACE::PLUGIN_HAS_CUSTOM_UI)
  513. {
  514. #ifdef HAVE_X11
  515. if (std::getenv("DISPLAY") != nullptr)
  516. #endif
  517. if (! testing)
  518. carla_show_custom_ui(gHostHandle, 0, true);
  519. }
  520. // on standalone usage, enable everything that makes sense
  521. const uint optsAvailable = pluginInfo->optionsAvailable;
  522. if (optsAvailable & CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS)
  523. carla_set_option(gHostHandle, 0, CARLA_BACKEND_NAMESPACE::PLUGIN_OPTION_FIXED_BUFFERS, true);
  524. }
  525. }
  526. bridge.exec(useBridge);
  527. }
  528. else
  529. {
  530. ret = 1;
  531. const char* const lastError(carla_get_last_error(gHostHandle));
  532. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  533. if (useBridge)
  534. {
  535. // do a single idle so that we can send error message to server
  536. gIdle();
  537. #ifdef CARLA_OS_UNIX
  538. // kill ourselves now if we can't load plugin in bridge mode
  539. ::kill(::getpid(), SIGKILL);
  540. #endif
  541. }
  542. }
  543. }
  544. #ifdef CARLA_OS_WIN
  545. #ifndef __WINPTHREADS_VERSION
  546. pthread_win32_thread_detach_np();
  547. pthread_win32_process_detach_np();
  548. #endif
  549. CoUninitialize();
  550. OleUninitialize();
  551. #endif
  552. return ret;
  553. }