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.

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