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.

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