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.

541 lines
15KB

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