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.

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