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