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.

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