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.

689 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 successfully");
  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, static_cast<double>(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. #endif
  297. {
  298. CARLA_SAFE_ASSERT_UINT_RETURN(pluginId == 0, pluginId,);
  299. }
  300. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valuef, valueStr);
  301. }
  302. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  303. };
  304. // -------------------------------------------------------------------------
  305. int main(int argc, char* argv[])
  306. {
  307. // ---------------------------------------------------------------------
  308. // Check argument count
  309. if (argc != 4 && argc != 5)
  310. {
  311. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  312. return 1;
  313. }
  314. #if defined(CARLA_OS_WIN) && ! defined(BUILDING_CARLA_FOR_WINDOWS)
  315. // ---------------------------------------------------------------------
  316. // Test if bridge is working
  317. if (! jackbridge_is_ok())
  318. {
  319. carla_stderr("A JACK or Wine library is missing, cannot continue");
  320. return 1;
  321. }
  322. #endif
  323. // ---------------------------------------------------------------------
  324. // Get args
  325. const char* const stype = argv[1];
  326. const char* filename = argv[2];
  327. const char* label = argv[3];
  328. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  329. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  330. filename = nullptr;
  331. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  332. label = nullptr;
  333. // ---------------------------------------------------------------------
  334. // Check binary type
  335. CarlaBackend::BinaryType btype = CarlaBackend::BINARY_NATIVE;
  336. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  337. btype = CarlaBackend::getBinaryTypeFromString(binaryTypeStr);
  338. if (btype == CarlaBackend::BINARY_NONE)
  339. {
  340. carla_stderr("Invalid binary type '%i'", btype);
  341. return 1;
  342. }
  343. // ---------------------------------------------------------------------
  344. // Check plugin type
  345. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  346. if (itype == CarlaBackend::PLUGIN_NONE)
  347. {
  348. carla_stderr("Invalid plugin type '%s'", stype);
  349. return 1;
  350. }
  351. // ---------------------------------------------------------------------
  352. // Set file
  353. const File file(filename != nullptr ? filename : "");
  354. // ---------------------------------------------------------------------
  355. // Set name
  356. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  357. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  358. name = nullptr;
  359. // ---------------------------------------------------------------------
  360. // Setup options
  361. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  362. const bool useBridge = (shmIds != nullptr);
  363. // ---------------------------------------------------------------------
  364. // Setup bridge ids
  365. char audioPoolBaseName[6+1];
  366. char rtClientBaseName[6+1];
  367. char nonRtClientBaseName[6+1];
  368. char nonRtServerBaseName[6+1];
  369. if (useBridge)
  370. {
  371. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  372. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  373. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  374. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  375. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  376. audioPoolBaseName[6] = '\0';
  377. rtClientBaseName[6] = '\0';
  378. nonRtClientBaseName[6] = '\0';
  379. nonRtServerBaseName[6] = '\0';
  380. jackbridge_parent_deathsig(false);
  381. }
  382. else
  383. {
  384. audioPoolBaseName[0] = '\0';
  385. rtClientBaseName[0] = '\0';
  386. nonRtClientBaseName[0] = '\0';
  387. nonRtServerBaseName[0] = '\0';
  388. jackbridge_init();
  389. }
  390. // ---------------------------------------------------------------------
  391. // Set client name
  392. CarlaString clientName;
  393. if (name != nullptr)
  394. {
  395. clientName = name;
  396. }
  397. else if (itype == CarlaBackend::PLUGIN_LV2)
  398. {
  399. // LV2 requires URI
  400. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  401. // LV2 URI is not usable as client name, create a usable name from URI
  402. CarlaString label2(label);
  403. // truncate until last valid char
  404. for (std::size_t i=label2.length()-1; i != 0; --i)
  405. {
  406. if (! std::isalnum(label2[i]))
  407. continue;
  408. label2.truncate(i+1);
  409. break;
  410. }
  411. // get last used separator
  412. bool found;
  413. std::size_t septmp, sep = 0;
  414. septmp = label2.rfind('#', &found)+1;
  415. if (found && septmp > sep)
  416. sep = septmp;
  417. septmp = label2.rfind('/', &found)+1;
  418. if (found && septmp > sep)
  419. sep = septmp;
  420. septmp = label2.rfind('=', &found)+1;
  421. if (found && septmp > sep)
  422. sep = septmp;
  423. septmp = label2.rfind(':', &found)+1;
  424. if (found && septmp > sep)
  425. sep = septmp;
  426. // make name starting from the separator and first valid char
  427. const char* name2 = label2.buffer() + sep;
  428. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  429. if (*name2 != '\0')
  430. clientName = name2;
  431. }
  432. else if (label != nullptr)
  433. {
  434. clientName = label;
  435. }
  436. else
  437. {
  438. clientName = file.getFileNameWithoutExtension().toRawUTF8();
  439. }
  440. // if we still have no client name by now, use a dummy one
  441. if (clientName.isEmpty())
  442. clientName = "carla-plugin";
  443. // just to be safe
  444. clientName.toBasic();
  445. // ---------------------------------------------------------------------
  446. // Set extraStuff
  447. const void* extraStuff = nullptr;
  448. if (itype == CarlaBackend::PLUGIN_SF2)
  449. {
  450. if (label == nullptr)
  451. label = clientName;
  452. if (std::strstr(label, " (16 outs)") != nullptr)
  453. extraStuff = "true";
  454. }
  455. // ---------------------------------------------------------------------
  456. // Initialize OS features
  457. #ifdef CARLA_OS_WIN
  458. OleInitialize(nullptr);
  459. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  460. # ifndef __WINPTHREADS_VERSION
  461. // (non-portable) initialization of statically linked pthread library
  462. pthread_win32_process_attach_np();
  463. pthread_win32_thread_attach_np();
  464. # endif
  465. #endif
  466. #ifdef HAVE_X11
  467. if (std::getenv("DISPLAY") != nullptr)
  468. XInitThreads();
  469. #endif
  470. // ---------------------------------------------------------------------
  471. // Set ourselves with high priority
  472. #ifdef CARLA_OS_LINUX
  473. // reset scheduler to normal mode
  474. struct sched_param sparam;
  475. carla_zeroStruct(sparam);
  476. sched_setscheduler(0, SCHED_OTHER|SCHED_RESET_ON_FORK, &sparam);
  477. // try niceness first, if it fails, try SCHED_RR
  478. if (nice(-5) < 0)
  479. {
  480. sparam.sched_priority = (sched_get_priority_max(SCHED_RR) + sched_get_priority_min(SCHED_RR*7)) / 8;
  481. if (sparam.sched_priority > 0)
  482. {
  483. if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &sparam) < 0)
  484. {
  485. CarlaString error(std::strerror(errno));
  486. carla_stderr("Failed to set high priority, error %i: %s", errno, error.buffer());
  487. }
  488. }
  489. }
  490. #endif
  491. #ifdef CARLA_OS_WIN
  492. if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
  493. carla_stderr("Failed to set high priority.");
  494. #endif
  495. // ---------------------------------------------------------------------
  496. // Listen for ctrl+c or sigint/sigterm events
  497. initSignalHandler();
  498. // ---------------------------------------------------------------------
  499. // Init plugin bridge
  500. int ret;
  501. {
  502. CarlaBridgePlugin bridge(useBridge, clientName,
  503. audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  504. if (! bridge.isOk())
  505. {
  506. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  507. return 1;
  508. }
  509. // -----------------------------------------------------------------
  510. // Init plugin
  511. if (carla_add_plugin(btype, itype, file.getFullPathName().toRawUTF8(), name, label, uniqueId, extraStuff, 0x0))
  512. {
  513. ret = 0;
  514. if (! useBridge)
  515. {
  516. carla_set_active(0, true);
  517. carla_set_option(0, CarlaBackend::PLUGIN_OPTION_SEND_CONTROL_CHANGES, true);
  518. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  519. {
  520. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  521. {
  522. #ifdef HAVE_X11
  523. if (std::getenv("DISPLAY") != nullptr)
  524. #endif
  525. carla_show_custom_ui(0, true);
  526. }
  527. }
  528. }
  529. bridge.exec(useBridge);
  530. }
  531. else
  532. {
  533. ret = 1;
  534. const char* const lastError(carla_get_last_error());
  535. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  536. if (useBridge)
  537. {
  538. // do a single idle so that we can send error message to server
  539. gIdle();
  540. #ifdef CARLA_OS_UNIX
  541. // kill ourselves now if we can't load plugin in bridge mode
  542. ::kill(::getpid(), SIGKILL);
  543. #endif
  544. }
  545. }
  546. }
  547. #ifdef CARLA_OS_WIN
  548. #ifndef __WINPTHREADS_VERSION
  549. pthread_win32_thread_detach_np();
  550. pthread_win32_process_detach_np();
  551. #endif
  552. CoUninitialize();
  553. OleUninitialize();
  554. #endif
  555. return ret;
  556. }