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.

CarlaBridgePlugin.cpp 18KB

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