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.

564 lines
16KB

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