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.

482 lines
13KB

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