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.

683 lines
20KB

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