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.

542 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.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. {
  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 exec(const bool useBridge, int argc, char* argv[])
  171. {
  172. fUsingBridge = useBridge;
  173. if (! useBridge)
  174. {
  175. const CarlaPluginInfo* const pInfo(carla_get_plugin_info(0));
  176. CARLA_SAFE_ASSERT_RETURN(pInfo != nullptr,);
  177. gProjectFilename = CharPointer_UTF8(pInfo->name);
  178. gProjectFilename += ".carxs";
  179. if (! File::isAbsolutePath(gProjectFilename))
  180. gProjectFilename = File::getCurrentWorkingDirectory().getChildFile(gProjectFilename).getFullPathName();
  181. if (File(gProjectFilename).existsAsFile() && ! carla_load_plugin_state(0, gProjectFilename.toRawUTF8()))
  182. carla_stderr("Plugin preset load failed, error was:\n%s", carla_get_last_error());
  183. }
  184. gIsInitiated = true;
  185. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  186. JUCEApplicationBase::createInstance = &juce_CreateApplication;
  187. JUCEApplicationBase::main(JUCE_MAIN_FUNCTION_ARGS);
  188. #else
  189. for (; ! gCloseNow;)
  190. {
  191. gIdle();
  192. carla_msleep(8);
  193. }
  194. #endif
  195. carla_set_engine_about_to_close();
  196. carla_remove_plugin(0);
  197. // may be unused
  198. return; (void)argc; (void)argv;
  199. }
  200. // ---------------------------------------------------------------------
  201. protected:
  202. void handleCallback(const EngineCallbackOpcode action, const int value1, const int, const float, const char* const)
  203. {
  204. CARLA_BACKEND_USE_NAMESPACE;
  205. switch (action)
  206. {
  207. case ENGINE_CALLBACK_ENGINE_STOPPED:
  208. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  209. case ENGINE_CALLBACK_QUIT:
  210. gCloseNow = true;
  211. break;
  212. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  213. if (gIsInitiated && value1 != 1 && ! fUsingBridge)
  214. gCloseNow = true;
  215. break;
  216. default:
  217. break;
  218. }
  219. }
  220. private:
  221. const CarlaEngine* fEngine;
  222. bool fUsingBridge;
  223. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId, int value1, int value2, float value3, const char* valueStr)
  224. {
  225. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %f, \"%s\")", ptr, action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  226. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  227. CARLA_SAFE_ASSERT_RETURN(pluginId == 0,);
  228. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valueStr);
  229. }
  230. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  231. };
  232. // -------------------------------------------------------------------------
  233. int main(int argc, char* argv[])
  234. {
  235. // ---------------------------------------------------------------------
  236. // Check argument count
  237. if (argc != 4 && argc != 5)
  238. {
  239. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  240. return 1;
  241. }
  242. #if defined(CARLA_OS_WIN) && ! defined(BUILDING_CARLA_FOR_WINDOWS)
  243. // ---------------------------------------------------------------------
  244. // Test if bridge is working
  245. if (! jackbridge_is_ok())
  246. {
  247. carla_stderr("A JACK or Wine library is missing, cannot continue");
  248. return 1;
  249. }
  250. #endif
  251. // ---------------------------------------------------------------------
  252. // Get args
  253. const char* const stype = argv[1];
  254. const char* filename = argv[2];
  255. const char* label = argv[3];
  256. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  257. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  258. filename = nullptr;
  259. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  260. label = nullptr;
  261. // ---------------------------------------------------------------------
  262. // Check binary type
  263. CarlaBackend::BinaryType btype = CarlaBackend::BINARY_NATIVE;
  264. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  265. btype = CarlaBackend::getBinaryTypeFromString(binaryTypeStr);
  266. if (btype == CarlaBackend::BINARY_NONE)
  267. {
  268. carla_stderr("Invalid binary type '%i'", btype);
  269. return 1;
  270. }
  271. // ---------------------------------------------------------------------
  272. // Check plugin type
  273. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  274. if (itype == CarlaBackend::PLUGIN_NONE)
  275. {
  276. carla_stderr("Invalid plugin type '%s'", stype);
  277. return 1;
  278. }
  279. // ---------------------------------------------------------------------
  280. // Set name
  281. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  282. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  283. name = nullptr;
  284. // ---------------------------------------------------------------------
  285. // Setup options
  286. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  287. const bool useBridge = (shmIds != nullptr);
  288. // ---------------------------------------------------------------------
  289. // Setup bridge ids
  290. char audioPoolBaseName[6+1];
  291. char rtClientBaseName[6+1];
  292. char nonRtClientBaseName[6+1];
  293. char nonRtServerBaseName[6+1];
  294. if (useBridge)
  295. {
  296. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  297. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  298. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  299. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  300. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  301. audioPoolBaseName[6] = '\0';
  302. rtClientBaseName[6] = '\0';
  303. nonRtClientBaseName[6] = '\0';
  304. nonRtServerBaseName[6] = '\0';
  305. }
  306. else
  307. {
  308. audioPoolBaseName[0] = '\0';
  309. rtClientBaseName[0] = '\0';
  310. nonRtClientBaseName[0] = '\0';
  311. nonRtServerBaseName[0] = '\0';
  312. jackbridge_init();
  313. }
  314. // ---------------------------------------------------------------------
  315. // Set client name
  316. CarlaString clientName;
  317. if (name != nullptr)
  318. {
  319. clientName = name;
  320. }
  321. else if (itype == CarlaBackend::PLUGIN_LV2)
  322. {
  323. // LV2 requires URI
  324. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  325. // LV2 URI is not usable as client name, create a usable name from URI
  326. CarlaString label2(label);
  327. // truncate until last valid char
  328. for (std::size_t i=label2.length()-1; i != 0; --i)
  329. {
  330. if (! std::isalnum(label2[i]))
  331. continue;
  332. label2.truncate(i+1);
  333. break;
  334. }
  335. // get last used separator
  336. bool found;
  337. std::size_t septmp, sep = 0;
  338. septmp = label2.rfind('#', &found)+1;
  339. if (found && septmp > sep)
  340. sep = septmp;
  341. septmp = label2.rfind('/', &found)+1;
  342. if (found && septmp > sep)
  343. sep = septmp;
  344. septmp = label2.rfind('=', &found)+1;
  345. if (found && septmp > sep)
  346. sep = septmp;
  347. septmp = label2.rfind(':', &found)+1;
  348. if (found && septmp > sep)
  349. sep = septmp;
  350. // make name starting from the separator and first valid char
  351. const char* name2 = label2.buffer() + sep;
  352. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  353. if (*name2 != '\0')
  354. clientName = name2;
  355. }
  356. else if (label != nullptr)
  357. {
  358. clientName = label;
  359. }
  360. else
  361. {
  362. const String jfilename = String(CharPointer_UTF8(filename));
  363. clientName = File(jfilename).getFileNameWithoutExtension().toRawUTF8();
  364. }
  365. // if we still have no client name by now, use a dummy one
  366. if (clientName.isEmpty())
  367. clientName = "carla-plugin";
  368. // just to be safe
  369. clientName.toBasic();
  370. // ---------------------------------------------------------------------
  371. // Set extraStuff
  372. const void* extraStuff = nullptr;
  373. if (itype == CarlaBackend::PLUGIN_GIG || itype == CarlaBackend::PLUGIN_SF2)
  374. {
  375. if (label == nullptr)
  376. label = clientName;
  377. if (std::strstr(label, " (16 outs)") != nullptr)
  378. extraStuff = "true";
  379. }
  380. #ifdef HAVE_X11
  381. if (std::getenv("DISPLAY") != nullptr)
  382. XInitThreads();
  383. #endif
  384. // ---------------------------------------------------------------------
  385. // Init plugin bridge
  386. CarlaBridgePlugin bridge(useBridge, clientName, audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  387. if (! bridge.isOk())
  388. {
  389. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  390. return 1;
  391. }
  392. // ---------------------------------------------------------------------
  393. // Listen for ctrl+c or sigint/sigterm events
  394. initSignalHandler();
  395. // ---------------------------------------------------------------------
  396. // Init plugin
  397. int ret;
  398. if (carla_add_plugin(btype, itype, filename, name, label, uniqueId, extraStuff, 0x0))
  399. {
  400. ret = 0;
  401. if (! useBridge)
  402. {
  403. carla_set_active(0, true);
  404. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  405. {
  406. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  407. {
  408. #ifdef HAVE_X11
  409. if (std::getenv("DISPLAY") != nullptr)
  410. #endif
  411. carla_show_custom_ui(0, true);
  412. }
  413. }
  414. }
  415. bridge.exec(useBridge, argc, argv);
  416. }
  417. else
  418. {
  419. ret = 1;
  420. const char* const lastError(carla_get_last_error());
  421. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  422. //if (useBridge)
  423. // bridge.sendOscBridgeError(lastError);
  424. }
  425. return ret;
  426. }