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.

506 lines
14KB

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