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.

CarlaBridgePlugin.cpp 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 "CarlaOscUtils.hpp"
  21. #include "CarlaMIDI.h"
  22. #ifdef CARLA_OS_UNIX
  23. # include <signal.h>
  24. #endif
  25. #include "juce_core.h"
  26. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  27. # include "juce_gui_basics.h"
  28. using juce::JUCEApplication;
  29. using juce::JUCEApplicationBase;
  30. using juce::Timer;
  31. #endif
  32. using CarlaBackend::CarlaEngine;
  33. using CarlaBackend::EngineCallbackOpcode;
  34. using CarlaBackend::EngineCallbackOpcode2Str;
  35. using juce::File;
  36. using juce::String;
  37. // -------------------------------------------------------------------------
  38. static bool gIsInitiated = false;
  39. static volatile bool gCloseNow = false;
  40. static volatile bool gSaveNow = false;
  41. #ifdef CARLA_OS_WIN
  42. static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
  43. {
  44. if (dwCtrlType == CTRL_C_EVENT)
  45. {
  46. gCloseNow = true;
  47. return TRUE;
  48. }
  49. return FALSE;
  50. }
  51. #elif defined(CARLA_OS_LINUX)
  52. static void closeSignalHandler(int) noexcept
  53. {
  54. gCloseNow = true;
  55. }
  56. static void saveSignalHandler(int) noexcept
  57. {
  58. gSaveNow = true;
  59. }
  60. #endif
  61. static void initSignalHandler()
  62. {
  63. #ifdef CARLA_OS_WIN
  64. SetConsoleCtrlHandler(winSignalHandler, TRUE);
  65. #elif defined(CARLA_OS_LINUX)
  66. struct sigaction sint;
  67. struct sigaction sterm;
  68. struct sigaction susr1;
  69. sint.sa_handler = closeSignalHandler;
  70. sint.sa_flags = SA_RESTART;
  71. sint.sa_restorer = nullptr;
  72. sigemptyset(&sint.sa_mask);
  73. sigaction(SIGINT, &sint, nullptr);
  74. sterm.sa_handler = closeSignalHandler;
  75. sterm.sa_flags = SA_RESTART;
  76. sterm.sa_restorer = nullptr;
  77. sigemptyset(&sterm.sa_mask);
  78. sigaction(SIGTERM, &sterm, nullptr);
  79. susr1.sa_handler = saveSignalHandler;
  80. susr1.sa_flags = SA_RESTART;
  81. susr1.sa_restorer = nullptr;
  82. sigemptyset(&susr1.sa_mask);
  83. sigaction(SIGUSR1, &susr1, nullptr);
  84. #endif
  85. }
  86. // -------------------------------------------------------------------------
  87. static CarlaString gProjectFilename;
  88. static void gIdle()
  89. {
  90. carla_engine_idle();
  91. if (gSaveNow)
  92. {
  93. gSaveNow = false;
  94. if (gProjectFilename.isNotEmpty())
  95. {
  96. if (! carla_save_plugin_state(0, gProjectFilename))
  97. carla_stderr("Plugin preset save failed, error was:\n%s", carla_get_last_error());
  98. }
  99. }
  100. }
  101. // -------------------------------------------------------------------------
  102. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  103. class CarlaJuceApp : public JUCEApplication,
  104. private Timer
  105. {
  106. public:
  107. CarlaJuceApp() {}
  108. ~CarlaJuceApp() {}
  109. void initialise(const String&) override
  110. {
  111. startTimer(30);
  112. }
  113. void shutdown() override
  114. {
  115. gCloseNow = true;
  116. stopTimer();
  117. }
  118. const String getApplicationName() override
  119. {
  120. return "CarlaPlugin";
  121. }
  122. const String getApplicationVersion() override
  123. {
  124. return CARLA_VERSION_STRING;
  125. }
  126. void timerCallback() override
  127. {
  128. gIdle();
  129. if (gCloseNow)
  130. {
  131. quit();
  132. gCloseNow = false;
  133. }
  134. }
  135. };
  136. static JUCEApplicationBase* juce_CreateApplication() { return new CarlaJuceApp(); }
  137. #endif
  138. // -------------------------------------------------------------------------
  139. class CarlaBridgePlugin
  140. {
  141. public:
  142. CarlaBridgePlugin(const bool useBridge, const char* const clientName, const char* const audioBaseName, const char* const controlBaseName, const char* const timeBaseName)
  143. : fEngine(nullptr),
  144. fOscServerThread(nullptr)
  145. {
  146. CARLA_ASSERT(clientName != nullptr && clientName[0] != '\0');
  147. carla_debug("CarlaBridgePlugin::CarlaBridgePlugin(%s, \"%s\", %s, %s, %s)", bool2str(useBridge), clientName, audioBaseName, controlBaseName, timeBaseName);
  148. carla_set_engine_callback(callback, this);
  149. if (useBridge)
  150. carla_engine_init_bridge(audioBaseName, controlBaseName, timeBaseName, clientName);
  151. else
  152. carla_engine_init("JACK", clientName);
  153. fEngine = carla_get_engine();
  154. }
  155. ~CarlaBridgePlugin()
  156. {
  157. carla_debug("CarlaBridgePlugin::~CarlaBridgePlugin()");
  158. carla_engine_close();
  159. }
  160. bool isOk() const noexcept
  161. {
  162. return (fEngine != nullptr);
  163. }
  164. // ---------------------------------------------------------------------
  165. void oscInit(const char* const url)
  166. {
  167. fOscServerThread = lo_server_thread_new_with_proto(nullptr, LO_UDP, osc_error_handler);
  168. CARLA_SAFE_ASSERT_RETURN(fOscServerThread != nullptr,)
  169. {
  170. char* const host = lo_url_get_hostname(url);
  171. char* const port = lo_url_get_port(url);
  172. fOscControlData.path = carla_strdup_free(lo_url_get_path(url));
  173. fOscControlData.target = lo_address_new_with_proto(LO_UDP, host, port);
  174. std::free(host);
  175. std::free(port);
  176. }
  177. if (char* const tmpServerPath = lo_server_thread_get_url(fOscServerThread))
  178. {
  179. std::srand((uint)(uintptr_t)this);
  180. std::srand((uint)(uintptr_t)&url);
  181. CarlaString oscName("plug-" + CarlaString(std::rand() % 99999));
  182. fOscServerPath = tmpServerPath;
  183. fOscServerPath += oscName;
  184. std::free(tmpServerPath);
  185. }
  186. lo_server_thread_start(fOscServerThread);
  187. fEngine->setOscBridgeData(&fOscControlData);
  188. }
  189. void oscClose()
  190. {
  191. lo_server_thread_stop(fOscServerThread);
  192. fEngine->setOscBridgeData(nullptr);
  193. if (fOscServerThread != nullptr)
  194. {
  195. lo_server_thread_free(fOscServerThread);
  196. fOscServerThread = nullptr;
  197. }
  198. fOscControlData.clear();
  199. fOscServerPath.clear();
  200. }
  201. // ---------------------------------------------------------------------
  202. void sendOscUpdate() const noexcept
  203. {
  204. if (fOscControlData.target != nullptr)
  205. osc_send_update(fOscControlData, fOscServerPath);
  206. }
  207. void sendOscBridgeUpdate() const noexcept
  208. {
  209. if (fOscControlData.target != nullptr)
  210. osc_send_bridge_update(fOscControlData, fOscControlData.path);
  211. }
  212. void sendOscBridgeError(const char* const error) const noexcept
  213. {
  214. if (fOscControlData.target != nullptr)
  215. osc_send_bridge_error(fOscControlData, error);
  216. }
  217. // ---------------------------------------------------------------------
  218. void exec(const bool useOsc, int argc, char* argv[])
  219. {
  220. if (! useOsc)
  221. {
  222. const CarlaPluginInfo* const pInfo(carla_get_plugin_info(0));
  223. CARLA_SAFE_ASSERT_RETURN(pInfo != nullptr,);
  224. fProjFilename = pInfo->name;
  225. fProjFilename += ".carxs";
  226. if (! File::isAbsolutePath(fProjFilename))
  227. fProjFilename = File::getCurrentWorkingDirectory().getChildFile(fProjFilename).getFullPathName();
  228. if (File(fProjFilename).existsAsFile() && ! carla_load_plugin_state(0, fProjFilename.toRawUTF8()))
  229. carla_stderr("Plugin preset load failed, error was:\n%s", carla_get_last_error());
  230. }
  231. gIsInitiated = true;
  232. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  233. JUCEApplicationBase::createInstance = &juce_CreateApplication;
  234. JUCEApplicationBase::main(JUCE_MAIN_FUNCTION_ARGS);
  235. #else
  236. for (; ! gCloseNow;)
  237. {
  238. gIdle();
  239. carla_msleep(25);
  240. }
  241. #endif
  242. carla_set_engine_about_to_close();
  243. carla_remove_plugin(0);
  244. // may be unused
  245. return; (void)argc; (void)argv;
  246. }
  247. // ---------------------------------------------------------------------
  248. protected:
  249. void handleCallback(const EngineCallbackOpcode action, const int value1, const int value2, const float value3, const char* const valueStr)
  250. {
  251. CARLA_BACKEND_USE_NAMESPACE;
  252. // TODO
  253. switch (action)
  254. {
  255. case ENGINE_CALLBACK_ENGINE_STOPPED:
  256. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  257. gCloseNow = true;
  258. break;
  259. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  260. if (gIsInitiated && value1 != 1 && fOscControlData.target == nullptr)
  261. gCloseNow = true;
  262. break;
  263. default:
  264. break;
  265. }
  266. return;
  267. (void)value2;
  268. (void)value3;
  269. (void)valueStr;
  270. }
  271. private:
  272. const CarlaEngine* fEngine;
  273. String fProjFilename;
  274. CarlaOscData fOscControlData;
  275. CarlaString fOscServerPath;
  276. lo_server_thread fOscServerThread;
  277. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId, int value1, int value2, float value3, const char* valueStr)
  278. {
  279. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %f, \"%s\")", ptr, action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  280. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  281. CARLA_SAFE_ASSERT_RETURN(pluginId == 0,);
  282. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valueStr);
  283. }
  284. static void osc_error_handler(int num, const char* msg, const char* path)
  285. {
  286. carla_stderr("CarlaBridgePlugin::osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
  287. }
  288. };
  289. #if 0
  290. int CarlaBridgeOsc::handleMsgPluginSetChunk(CARLA_BRIDGE_OSC_HANDLE_ARGS)
  291. {
  292. CARLA_BRIDGE_OSC_CHECK_OSC_TYPES(1, "s");
  293. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, 1);
  294. carla_debug("CarlaBridgeOsc::handleMsgPluginSetChunk()");
  295. const char* const chunkFilePathTry = (const char*)&argv[0]->s;
  296. CARLA_SAFE_ASSERT_RETURN(chunkFilePathTry != nullptr && chunkFilePathTry[0] != '\0', 0);
  297. String chunkFilePath(chunkFilePathTry);
  298. #ifdef CARLA_OS_WIN
  299. if (chunkFilePath.startsWith("/"))
  300. {
  301. // running under Wine, posix host
  302. chunkFilePath = chunkFilePath.replaceSection(0, 1, "Z:\\");
  303. chunkFilePath = chunkFilePath.replace("/", "\\");
  304. }
  305. #endif
  306. File chunkFile(chunkFilePath);
  307. CARLA_SAFE_ASSERT_RETURN(chunkFile.existsAsFile(), 0);
  308. String chunkData(chunkFile.loadFileAsString());
  309. chunkFile.deleteFile();
  310. CARLA_SAFE_ASSERT_RETURN(chunkData.isNotEmpty(), 0);
  311. carla_set_chunk_data(0, chunkData.toRawUTF8());
  312. return 0;
  313. }
  314. #endif
  315. // -------------------------------------------------------------------------
  316. int main(int argc, char* argv[])
  317. {
  318. // ---------------------------------------------------------------------
  319. // Check argument count
  320. if (argc != 7)
  321. {
  322. carla_stdout("usage: %s <osc-url|\"null\"> <type> <filename> <name|\"(none)\"> <label> <uniqueId>", argv[0]);
  323. return 1;
  324. }
  325. // ---------------------------------------------------------------------
  326. // Get args
  327. const char* const oscUrl = argv[1];
  328. const char* const stype = argv[2];
  329. const char* const filename = argv[3];
  330. const char* name = argv[4];
  331. const char* label = argv[5];
  332. const int64_t uniqueId = static_cast<int64_t>(std::atoll(argv[6]));
  333. // ---------------------------------------------------------------------
  334. // Check plugin type
  335. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  336. if (itype == CarlaBackend::PLUGIN_NONE)
  337. {
  338. carla_stderr("Invalid plugin type '%s'", stype);
  339. return 1;
  340. }
  341. // ---------------------------------------------------------------------
  342. // Set name as null if invalid
  343. if (std::strlen(name) == 0 || std::strcmp(name, "(none)") == 0)
  344. name = nullptr;
  345. // ---------------------------------------------------------------------
  346. // Setup options
  347. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  348. const bool useBridge = (shmIds != nullptr);
  349. const bool useOsc = (std::strcmp(oscUrl, "null") != 0 && std::strcmp(oscUrl, "(null)") != 0 && std::strcmp(oscUrl, "NULL") != 0);
  350. // ---------------------------------------------------------------------
  351. // Setup bridge ids
  352. char bridgeBaseAudioName[6+1];
  353. char bridgeBaseControlName[6+1];
  354. char bridgeBaseTimeName[6+1];
  355. if (useBridge)
  356. {
  357. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*3, 1);
  358. std::strncpy(bridgeBaseAudioName, shmIds, 6);
  359. std::strncpy(bridgeBaseControlName, shmIds+6, 6);
  360. std::strncpy(bridgeBaseTimeName, shmIds+12, 6);
  361. bridgeBaseAudioName[6] = '\0';
  362. bridgeBaseControlName[6] = '\0';
  363. bridgeBaseTimeName[6] = '\0';
  364. }
  365. else
  366. {
  367. bridgeBaseAudioName[0] = '\0';
  368. bridgeBaseControlName[0] = '\0';
  369. bridgeBaseTimeName[0] = '\0';
  370. }
  371. // ---------------------------------------------------------------------
  372. // Set client name
  373. CarlaString clientName((name != nullptr) ? name : label);
  374. if (clientName.isEmpty())
  375. clientName = juce::File(filename).getFileNameWithoutExtension().toRawUTF8();
  376. // ---------------------------------------------------------------------
  377. // Set extraStuff
  378. const void* extraStuff = nullptr;
  379. if (itype == CarlaBackend::PLUGIN_GIG || itype == CarlaBackend::PLUGIN_SF2)
  380. {
  381. if (label == nullptr)
  382. label = clientName;
  383. if (std::strstr(label, " (16 outs)") == 0)
  384. extraStuff = "true";
  385. }
  386. // ---------------------------------------------------------------------
  387. // Init plugin bridge
  388. CarlaBridgePlugin bridge(useBridge, clientName, bridgeBaseAudioName, bridgeBaseControlName, bridgeBaseTimeName);
  389. if (! bridge.isOk())
  390. {
  391. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  392. return 1;
  393. }
  394. // ---------------------------------------------------------------------
  395. // Init OSC
  396. if (useOsc)
  397. bridge.oscInit(oscUrl);
  398. // ---------------------------------------------------------------------
  399. // Listen for ctrl+c or sigint/sigterm events
  400. initSignalHandler();
  401. // ---------------------------------------------------------------------
  402. // Init plugin
  403. int ret;
  404. if (carla_add_plugin(CarlaBackend::BINARY_NATIVE, itype, filename, name, label, uniqueId, extraStuff))
  405. {
  406. ret = 0;
  407. if (useOsc)
  408. {
  409. bridge.sendOscUpdate();
  410. bridge.sendOscBridgeUpdate();
  411. }
  412. else
  413. {
  414. carla_set_active(0, true);
  415. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  416. {
  417. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  418. carla_show_custom_ui(0, true);
  419. }
  420. }
  421. bridge.exec(useOsc, argc, argv);
  422. }
  423. else
  424. {
  425. ret = 1;
  426. const char* const lastError(carla_get_last_error());
  427. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  428. if (useOsc)
  429. bridge.sendOscBridgeError(lastError);
  430. }
  431. // ---------------------------------------------------------------------
  432. // Close OSC
  433. if (useOsc)
  434. bridge.oscClose();
  435. return ret;
  436. }