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

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