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.

547 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 "CarlaMIDI.h"
  21. #ifdef CARLA_OS_UNIX
  22. # include <signal.h>
  23. #endif
  24. #ifdef HAVE_X11
  25. # include <X11/Xlib.h>
  26. #endif
  27. #include "jackbridge/JackBridge.hpp"
  28. #include "juce_core/juce_core.h"
  29. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  30. # include "juce_gui_basics/juce_gui_basics.h"
  31. using juce::JUCEApplication;
  32. using juce::JUCEApplicationBase;
  33. using juce::ScopedJuceInitialiser_GUI;
  34. using juce::Timer;
  35. #endif
  36. using CarlaBackend::CarlaEngine;
  37. using CarlaBackend::EngineCallbackOpcode;
  38. using CarlaBackend::EngineCallbackOpcode2Str;
  39. using juce::CharPointer_UTF8;
  40. using juce::File;
  41. using juce::String;
  42. // -------------------------------------------------------------------------
  43. static bool gIsInitiated = false;
  44. static volatile bool gCloseNow = false;
  45. static volatile bool gSaveNow = false;
  46. #ifdef CARLA_OS_WIN
  47. static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
  48. {
  49. if (dwCtrlType == CTRL_C_EVENT)
  50. {
  51. gCloseNow = true;
  52. return TRUE;
  53. }
  54. return FALSE;
  55. }
  56. #elif defined(CARLA_OS_LINUX)
  57. static void closeSignalHandler(int) noexcept
  58. {
  59. gCloseNow = true;
  60. }
  61. static void saveSignalHandler(int) noexcept
  62. {
  63. gSaveNow = true;
  64. }
  65. #endif
  66. static void initSignalHandler()
  67. {
  68. #ifdef CARLA_OS_WIN
  69. SetConsoleCtrlHandler(winSignalHandler, TRUE);
  70. #elif defined(CARLA_OS_LINUX)
  71. struct sigaction sint;
  72. struct sigaction sterm;
  73. struct sigaction susr1;
  74. sint.sa_handler = closeSignalHandler;
  75. sint.sa_flags = SA_RESTART;
  76. sint.sa_restorer = nullptr;
  77. sigemptyset(&sint.sa_mask);
  78. sigaction(SIGINT, &sint, nullptr);
  79. sterm.sa_handler = closeSignalHandler;
  80. sterm.sa_flags = SA_RESTART;
  81. sterm.sa_restorer = nullptr;
  82. sigemptyset(&sterm.sa_mask);
  83. sigaction(SIGTERM, &sterm, nullptr);
  84. susr1.sa_handler = saveSignalHandler;
  85. susr1.sa_flags = SA_RESTART;
  86. susr1.sa_restorer = nullptr;
  87. sigemptyset(&susr1.sa_mask);
  88. sigaction(SIGUSR1, &susr1, nullptr);
  89. #endif
  90. }
  91. // -------------------------------------------------------------------------
  92. static String gProjectFilename;
  93. static void gIdle()
  94. {
  95. carla_engine_idle();
  96. if (gSaveNow)
  97. {
  98. gSaveNow = false;
  99. if (gProjectFilename.isNotEmpty())
  100. {
  101. if (! carla_save_plugin_state(0, gProjectFilename.toRawUTF8()))
  102. carla_stderr("Plugin preset save failed, error was:\n%s", carla_get_last_error());
  103. }
  104. }
  105. }
  106. // -------------------------------------------------------------------------
  107. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  108. class CarlaJuceApp : public JUCEApplication,
  109. private Timer
  110. {
  111. public:
  112. CarlaJuceApp() {}
  113. ~CarlaJuceApp() {}
  114. void initialise(const String&) override
  115. {
  116. startTimer(8);
  117. }
  118. void shutdown() override
  119. {
  120. gCloseNow = true;
  121. stopTimer();
  122. }
  123. const String getApplicationName() override
  124. {
  125. return "CarlaPlugin";
  126. }
  127. const String getApplicationVersion() override
  128. {
  129. return CARLA_VERSION_STRING;
  130. }
  131. void timerCallback() override
  132. {
  133. gIdle();
  134. if (gCloseNow)
  135. {
  136. quit();
  137. gCloseNow = false;
  138. }
  139. }
  140. };
  141. static JUCEApplicationBase* juce_CreateApplication() { return new CarlaJuceApp(); }
  142. #endif
  143. // -------------------------------------------------------------------------
  144. class CarlaBridgePlugin
  145. {
  146. public:
  147. CarlaBridgePlugin(const bool useBridge, const char* const clientName, const char* const audioPoolBaseName,
  148. const char* const rtClientBaseName, const char* const nonRtClientBaseName, const char* const nonRtServerBaseName)
  149. : fEngine(nullptr),
  150. fUsingBridge(false)
  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. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  225. const ScopedJuceInitialiser_GUI kJuceInitialiser;
  226. #endif
  227. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId, int value1, int value2, float value3, const char* valueStr)
  228. {
  229. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %f, \"%s\")", ptr, action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  230. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  231. CARLA_SAFE_ASSERT_RETURN(pluginId == 0,);
  232. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valueStr);
  233. }
  234. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  235. };
  236. // -------------------------------------------------------------------------
  237. int main(int argc, char* argv[])
  238. {
  239. // ---------------------------------------------------------------------
  240. // Check argument count
  241. if (argc != 4 && argc != 5)
  242. {
  243. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  244. return 1;
  245. }
  246. #if defined(CARLA_OS_WIN) && ! defined(BUILDING_CARLA_FOR_WINDOWS)
  247. // ---------------------------------------------------------------------
  248. // Test if bridge is working
  249. if (! jackbridge_is_ok())
  250. {
  251. carla_stderr("A JACK or Wine library is missing, cannot continue");
  252. return 1;
  253. }
  254. #endif
  255. // ---------------------------------------------------------------------
  256. // Get args
  257. const char* const stype = argv[1];
  258. const char* filename = argv[2];
  259. const char* label = argv[3];
  260. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  261. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  262. filename = nullptr;
  263. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  264. label = nullptr;
  265. // ---------------------------------------------------------------------
  266. // Check binary type
  267. CarlaBackend::BinaryType btype = CarlaBackend::BINARY_NATIVE;
  268. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  269. btype = CarlaBackend::getBinaryTypeFromString(binaryTypeStr);
  270. if (btype == CarlaBackend::BINARY_NONE)
  271. {
  272. carla_stderr("Invalid binary type '%i'", btype);
  273. return 1;
  274. }
  275. // ---------------------------------------------------------------------
  276. // Check plugin type
  277. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  278. if (itype == CarlaBackend::PLUGIN_NONE)
  279. {
  280. carla_stderr("Invalid plugin type '%s'", stype);
  281. return 1;
  282. }
  283. // ---------------------------------------------------------------------
  284. // Set name
  285. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  286. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  287. name = nullptr;
  288. // ---------------------------------------------------------------------
  289. // Setup options
  290. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  291. const bool useBridge = (shmIds != nullptr);
  292. // ---------------------------------------------------------------------
  293. // Setup bridge ids
  294. char audioPoolBaseName[6+1];
  295. char rtClientBaseName[6+1];
  296. char nonRtClientBaseName[6+1];
  297. char nonRtServerBaseName[6+1];
  298. if (useBridge)
  299. {
  300. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  301. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  302. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  303. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  304. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  305. audioPoolBaseName[6] = '\0';
  306. rtClientBaseName[6] = '\0';
  307. nonRtClientBaseName[6] = '\0';
  308. nonRtServerBaseName[6] = '\0';
  309. }
  310. else
  311. {
  312. audioPoolBaseName[0] = '\0';
  313. rtClientBaseName[0] = '\0';
  314. nonRtClientBaseName[0] = '\0';
  315. nonRtServerBaseName[0] = '\0';
  316. jackbridge_init();
  317. }
  318. // ---------------------------------------------------------------------
  319. // Set client name
  320. CarlaString clientName;
  321. if (name != nullptr)
  322. {
  323. clientName = name;
  324. }
  325. else if (itype == CarlaBackend::PLUGIN_LV2)
  326. {
  327. // LV2 requires URI
  328. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  329. // LV2 URI is not usable as client name, create a usable name from URI
  330. CarlaString label2(label);
  331. // truncate until last valid char
  332. for (std::size_t i=label2.length()-1; i != 0; --i)
  333. {
  334. if (! std::isalnum(label2[i]))
  335. continue;
  336. label2.truncate(i+1);
  337. break;
  338. }
  339. // get last used separator
  340. bool found;
  341. std::size_t septmp, sep = 0;
  342. septmp = label2.rfind('#', &found)+1;
  343. if (found && septmp > sep)
  344. sep = septmp;
  345. septmp = label2.rfind('/', &found)+1;
  346. if (found && septmp > sep)
  347. sep = septmp;
  348. septmp = label2.rfind('=', &found)+1;
  349. if (found && septmp > sep)
  350. sep = septmp;
  351. septmp = label2.rfind(':', &found)+1;
  352. if (found && septmp > sep)
  353. sep = septmp;
  354. // make name starting from the separator and first valid char
  355. const char* name2 = label2.buffer() + sep;
  356. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  357. if (*name2 != '\0')
  358. clientName = name2;
  359. }
  360. else if (label != nullptr)
  361. {
  362. clientName = label;
  363. }
  364. else
  365. {
  366. const String jfilename = String(CharPointer_UTF8(filename));
  367. clientName = File(jfilename).getFileNameWithoutExtension().toRawUTF8();
  368. }
  369. // if we still have no client name by now, use a dummy one
  370. if (clientName.isEmpty())
  371. clientName = "carla-plugin";
  372. // just to be safe
  373. clientName.toBasic();
  374. // ---------------------------------------------------------------------
  375. // Set extraStuff
  376. const void* extraStuff = nullptr;
  377. if (itype == CarlaBackend::PLUGIN_GIG || itype == CarlaBackend::PLUGIN_SF2)
  378. {
  379. if (label == nullptr)
  380. label = clientName;
  381. if (std::strstr(label, " (16 outs)") != nullptr)
  382. extraStuff = "true";
  383. }
  384. #ifdef HAVE_X11
  385. if (std::getenv("DISPLAY") != nullptr)
  386. XInitThreads();
  387. #endif
  388. // ---------------------------------------------------------------------
  389. // Init plugin bridge
  390. CarlaBridgePlugin bridge(useBridge, clientName, audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  391. if (! bridge.isOk())
  392. {
  393. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  394. return 1;
  395. }
  396. // ---------------------------------------------------------------------
  397. // Listen for ctrl+c or sigint/sigterm events
  398. initSignalHandler();
  399. // ---------------------------------------------------------------------
  400. // Init plugin
  401. int ret;
  402. if (carla_add_plugin(btype, itype, filename, name, label, uniqueId, extraStuff, 0x0))
  403. {
  404. ret = 0;
  405. if (! useBridge)
  406. {
  407. carla_set_active(0, true);
  408. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  409. {
  410. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  411. {
  412. #ifdef HAVE_X11
  413. if (std::getenv("DISPLAY") != nullptr)
  414. #endif
  415. carla_show_custom_ui(0, true);
  416. }
  417. }
  418. }
  419. bridge.exec(useBridge, argc, argv);
  420. }
  421. else
  422. {
  423. ret = 1;
  424. const char* const lastError(carla_get_last_error());
  425. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  426. //if (useBridge)
  427. // bridge.sendOscBridgeError(lastError);
  428. }
  429. return ret;
  430. }