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.

533 lines
15KB

  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(15);
  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 audioPoolBaseName, const char* const rtBaseName, const char* const nonRtBaseName)
  143. : fEngine(nullptr),
  144. fProjFilename(),
  145. fOscControlData(),
  146. fOscServerPath(),
  147. fOscServerThread(nullptr),
  148. leakDetector_CarlaBridgePlugin()
  149. {
  150. CARLA_ASSERT(clientName != nullptr && clientName[0] != '\0');
  151. carla_debug("CarlaBridgePlugin::CarlaBridgePlugin(%s, \"%s\", %s, %s, %s)", bool2str(useBridge), clientName, audioPoolBaseName, rtBaseName, nonRtBaseName);
  152. carla_set_engine_callback(callback, this);
  153. if (useBridge)
  154. carla_engine_init_bridge(audioPoolBaseName, rtBaseName, nonRtBaseName, clientName);
  155. else
  156. carla_engine_init("JACK", clientName);
  157. fEngine = carla_get_engine();
  158. }
  159. ~CarlaBridgePlugin()
  160. {
  161. carla_debug("CarlaBridgePlugin::~CarlaBridgePlugin()");
  162. carla_engine_close();
  163. }
  164. bool isOk() const noexcept
  165. {
  166. return (fEngine != nullptr);
  167. }
  168. // ---------------------------------------------------------------------
  169. void oscInit(const char* const url)
  170. {
  171. fOscServerThread = lo_server_thread_new_with_proto(nullptr, LO_UDP, osc_error_handler);
  172. CARLA_SAFE_ASSERT_RETURN(fOscServerThread != nullptr,)
  173. {
  174. char* const host = lo_url_get_hostname(url);
  175. char* const port = lo_url_get_port(url);
  176. fOscControlData.path = carla_strdup_free(lo_url_get_path(url));
  177. fOscControlData.target = lo_address_new_with_proto(LO_UDP, host, port);
  178. std::free(host);
  179. std::free(port);
  180. }
  181. if (char* const tmpServerPath = lo_server_thread_get_url(fOscServerThread))
  182. {
  183. std::srand((uint)(uintptr_t)this);
  184. std::srand((uint)(uintptr_t)&url);
  185. CarlaString oscName("plug-" + CarlaString(std::rand() % 99999));
  186. fOscServerPath = tmpServerPath;
  187. fOscServerPath += oscName;
  188. std::free(tmpServerPath);
  189. }
  190. lo_server_thread_start(fOscServerThread);
  191. fEngine->setOscBridgeData(&fOscControlData);
  192. }
  193. void oscClose()
  194. {
  195. lo_server_thread_stop(fOscServerThread);
  196. fEngine->setOscBridgeData(nullptr);
  197. if (fOscServerThread != nullptr)
  198. {
  199. lo_server_thread_free(fOscServerThread);
  200. fOscServerThread = nullptr;
  201. }
  202. fOscControlData.clear();
  203. fOscServerPath.clear();
  204. }
  205. // ---------------------------------------------------------------------
  206. void sendOscUpdate() const noexcept
  207. {
  208. if (fOscControlData.target != nullptr)
  209. osc_send_update(fOscControlData, fOscServerPath);
  210. }
  211. void sendOscBridgeUpdate() const noexcept
  212. {
  213. if (fOscControlData.target != nullptr)
  214. osc_send_bridge_ready(fOscControlData, fOscControlData.path);
  215. }
  216. void sendOscBridgeError(const char* const error) const noexcept
  217. {
  218. if (fOscControlData.target != nullptr)
  219. osc_send_bridge_error(fOscControlData, error);
  220. }
  221. // ---------------------------------------------------------------------
  222. void exec(const bool useOsc, int argc, char* argv[])
  223. {
  224. if (! useOsc)
  225. {
  226. const CarlaPluginInfo* const pInfo(carla_get_plugin_info(0));
  227. CARLA_SAFE_ASSERT_RETURN(pInfo != nullptr,);
  228. fProjFilename = pInfo->name;
  229. fProjFilename += ".carxs";
  230. if (! File::isAbsolutePath(fProjFilename))
  231. fProjFilename = File::getCurrentWorkingDirectory().getChildFile(fProjFilename).getFullPathName();
  232. if (File(fProjFilename).existsAsFile() && ! carla_load_plugin_state(0, fProjFilename.toRawUTF8()))
  233. carla_stderr("Plugin preset load failed, error was:\n%s", carla_get_last_error());
  234. }
  235. gIsInitiated = true;
  236. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  237. JUCEApplicationBase::createInstance = &juce_CreateApplication;
  238. JUCEApplicationBase::main(JUCE_MAIN_FUNCTION_ARGS);
  239. #else
  240. for (; ! gCloseNow;)
  241. {
  242. gIdle();
  243. carla_msleep(15);
  244. }
  245. #endif
  246. carla_set_engine_about_to_close();
  247. carla_remove_plugin(0);
  248. // may be unused
  249. return; (void)argc; (void)argv;
  250. }
  251. // ---------------------------------------------------------------------
  252. protected:
  253. void handleCallback(const EngineCallbackOpcode action, const int value1, const int value2, const float value3, const char* const valueStr)
  254. {
  255. CARLA_BACKEND_USE_NAMESPACE;
  256. // TODO
  257. switch (action)
  258. {
  259. case ENGINE_CALLBACK_ENGINE_STOPPED:
  260. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  261. gCloseNow = true;
  262. break;
  263. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  264. if (gIsInitiated && value1 != 1 && fOscControlData.target == nullptr)
  265. gCloseNow = true;
  266. break;
  267. default:
  268. break;
  269. }
  270. return;
  271. (void)value2;
  272. (void)value3;
  273. (void)valueStr;
  274. }
  275. private:
  276. const CarlaEngine* fEngine;
  277. String fProjFilename;
  278. CarlaOscData fOscControlData;
  279. CarlaString fOscServerPath;
  280. lo_server_thread fOscServerThread;
  281. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId, int value1, int value2, float value3, const char* valueStr)
  282. {
  283. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %f, \"%s\")", ptr, action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  284. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  285. CARLA_SAFE_ASSERT_RETURN(pluginId == 0,);
  286. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valueStr);
  287. }
  288. static void osc_error_handler(int num, const char* msg, const char* path)
  289. {
  290. carla_stderr("CarlaBridgePlugin::osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
  291. }
  292. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  293. };
  294. // -------------------------------------------------------------------------
  295. int main(int argc, char* argv[])
  296. {
  297. // ---------------------------------------------------------------------
  298. // Check argument count
  299. if (argc != 7)
  300. {
  301. carla_stdout("usage: %s <osc-url|\"null\"> <type> <filename> <name|\"(none)\"> <label> <uniqueId>", argv[0]);
  302. return 1;
  303. }
  304. // ---------------------------------------------------------------------
  305. // Get args
  306. const char* const oscUrl = argv[1];
  307. const char* const stype = argv[2];
  308. const char* const filename = argv[3];
  309. const char* name = argv[4];
  310. const char* label = argv[5];
  311. const int64_t uniqueId = static_cast<int64_t>(std::atoll(argv[6]));
  312. // ---------------------------------------------------------------------
  313. // Check plugin type
  314. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  315. if (itype == CarlaBackend::PLUGIN_NONE)
  316. {
  317. carla_stderr("Invalid plugin type '%s'", stype);
  318. return 1;
  319. }
  320. // ---------------------------------------------------------------------
  321. // Set name as null if invalid
  322. if (std::strlen(name) == 0 || std::strcmp(name, "(none)") == 0)
  323. name = nullptr;
  324. // ---------------------------------------------------------------------
  325. // Setup options
  326. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  327. const bool useBridge = (shmIds != nullptr);
  328. const bool useOsc = (std::strcmp(oscUrl, "null") != 0 && std::strcmp(oscUrl, "(null)") != 0 && std::strcmp(oscUrl, "NULL") != 0);
  329. // ---------------------------------------------------------------------
  330. // Setup bridge ids
  331. char bridgeBaseAudioName[6+1];
  332. char bridgeBaseControlName[6+1];
  333. char bridgeBaseTimeName[6+1];
  334. if (useBridge)
  335. {
  336. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*3, 1);
  337. std::strncpy(bridgeBaseAudioName, shmIds, 6);
  338. std::strncpy(bridgeBaseControlName, shmIds+6, 6);
  339. std::strncpy(bridgeBaseTimeName, shmIds+12, 6);
  340. bridgeBaseAudioName[6] = '\0';
  341. bridgeBaseControlName[6] = '\0';
  342. bridgeBaseTimeName[6] = '\0';
  343. }
  344. else
  345. {
  346. bridgeBaseAudioName[0] = '\0';
  347. bridgeBaseControlName[0] = '\0';
  348. bridgeBaseTimeName[0] = '\0';
  349. }
  350. // ---------------------------------------------------------------------
  351. // Set client name
  352. CarlaString clientName((name != nullptr && name[0] != '\0') ? name : label);
  353. if (clientName.isEmpty())
  354. clientName = juce::File(filename).getFileNameWithoutExtension().toRawUTF8();
  355. // ---------------------------------------------------------------------
  356. // Set extraStuff
  357. const void* extraStuff = nullptr;
  358. if (itype == CarlaBackend::PLUGIN_GIG || itype == CarlaBackend::PLUGIN_SF2)
  359. {
  360. if (label == nullptr)
  361. label = clientName;
  362. if (std::strstr(label, " (16 outs)") == 0)
  363. extraStuff = "true";
  364. }
  365. // ---------------------------------------------------------------------
  366. // Init plugin bridge
  367. CarlaBridgePlugin bridge(useBridge, clientName, bridgeBaseAudioName, bridgeBaseControlName, bridgeBaseTimeName);
  368. if (! bridge.isOk())
  369. {
  370. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  371. return 1;
  372. }
  373. // ---------------------------------------------------------------------
  374. // Init OSC
  375. if (useOsc)
  376. bridge.oscInit(oscUrl);
  377. // ---------------------------------------------------------------------
  378. // Listen for ctrl+c or sigint/sigterm events
  379. initSignalHandler();
  380. // ---------------------------------------------------------------------
  381. // Init plugin
  382. int ret;
  383. if (carla_add_plugin(CarlaBackend::BINARY_NATIVE, itype, filename, name, label, uniqueId, extraStuff))
  384. {
  385. ret = 0;
  386. if (useOsc)
  387. {
  388. bridge.sendOscUpdate();
  389. bridge.sendOscBridgeUpdate();
  390. }
  391. else
  392. {
  393. carla_set_active(0, true);
  394. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  395. {
  396. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  397. carla_show_custom_ui(0, true);
  398. }
  399. }
  400. bridge.exec(useOsc, argc, argv);
  401. }
  402. else
  403. {
  404. ret = 1;
  405. const char* const lastError(carla_get_last_error());
  406. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  407. if (useOsc)
  408. bridge.sendOscBridgeError(lastError);
  409. }
  410. // ---------------------------------------------------------------------
  411. // Close OSC
  412. if (useOsc)
  413. bridge.oscClose();
  414. return ret;
  415. }