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
19KB

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