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