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.

551 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 CARLA_OS_LINUX
  25. # include <sys/prctl.h>
  26. #endif
  27. #ifdef HAVE_X11
  28. # include <X11/Xlib.h>
  29. #endif
  30. #include "jackbridge/JackBridge.hpp"
  31. #include "AppConfig.h"
  32. #include "juce_core/juce_core.h"
  33. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  34. # include "juce_gui_basics/juce_gui_basics.h"
  35. using juce::JUCEApplication;
  36. using juce::JUCEApplicationBase;
  37. using juce::Timer;
  38. #else
  39. # include "juce_events/juce_events.h"
  40. #endif
  41. using CarlaBackend::CarlaEngine;
  42. using CarlaBackend::EngineCallbackOpcode;
  43. using CarlaBackend::EngineCallbackOpcode2Str;
  44. using juce::CharPointer_UTF8;
  45. using juce::File;
  46. using juce::ScopedJuceInitialiser_GUI;
  47. using juce::String;
  48. // -------------------------------------------------------------------------
  49. static bool gIsInitiated = false;
  50. static volatile bool gCloseNow = false;
  51. static volatile bool gSaveNow = false;
  52. #ifdef CARLA_OS_WIN
  53. static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
  54. {
  55. if (dwCtrlType == CTRL_C_EVENT)
  56. {
  57. gCloseNow = true;
  58. return TRUE;
  59. }
  60. return FALSE;
  61. }
  62. #elif defined(CARLA_OS_LINUX)
  63. static void closeSignalHandler(int) noexcept
  64. {
  65. gCloseNow = true;
  66. }
  67. static void saveSignalHandler(int) noexcept
  68. {
  69. gSaveNow = true;
  70. }
  71. #endif
  72. static void initSignalHandler()
  73. {
  74. #ifdef CARLA_OS_WIN
  75. SetConsoleCtrlHandler(winSignalHandler, TRUE);
  76. #elif defined(CARLA_OS_LINUX)
  77. struct sigaction sig;
  78. carla_zeroStruct(sig);
  79. sig.sa_handler = closeSignalHandler;
  80. sig.sa_flags = SA_RESTART;
  81. sigemptyset(&sig.sa_mask);
  82. sigaction(SIGTERM, &sig, nullptr);
  83. sigaction(SIGINT, &sig, nullptr);
  84. sig.sa_handler = saveSignalHandler;
  85. sig.sa_flags = SA_RESTART;
  86. sigemptyset(&sig.sa_mask);
  87. sigaction(SIGUSR1, &sig, 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. const ScopedJuceInitialiser_GUI kJuceInitialiser;
  224. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId, int value1, int value2, float value3, const char* valueStr)
  225. {
  226. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %f, \"%s\")", ptr, action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  227. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  228. CARLA_SAFE_ASSERT_RETURN(pluginId == 0,);
  229. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valueStr);
  230. }
  231. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  232. };
  233. // -------------------------------------------------------------------------
  234. int main(int argc, char* argv[])
  235. {
  236. // ---------------------------------------------------------------------
  237. // Check argument count
  238. if (argc != 4 && argc != 5)
  239. {
  240. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  241. return 1;
  242. }
  243. #if defined(CARLA_OS_WIN) && ! defined(BUILDING_CARLA_FOR_WINDOWS)
  244. // ---------------------------------------------------------------------
  245. // Test if bridge is working
  246. if (! jackbridge_is_ok())
  247. {
  248. carla_stderr("A JACK or Wine library is missing, cannot continue");
  249. return 1;
  250. }
  251. #endif
  252. // ---------------------------------------------------------------------
  253. // Get args
  254. const char* const stype = argv[1];
  255. const char* filename = argv[2];
  256. const char* label = argv[3];
  257. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  258. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  259. filename = nullptr;
  260. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  261. label = nullptr;
  262. // ---------------------------------------------------------------------
  263. // Check binary type
  264. CarlaBackend::BinaryType btype = CarlaBackend::BINARY_NATIVE;
  265. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  266. btype = CarlaBackend::getBinaryTypeFromString(binaryTypeStr);
  267. if (btype == CarlaBackend::BINARY_NONE)
  268. {
  269. carla_stderr("Invalid binary type '%i'", btype);
  270. return 1;
  271. }
  272. // ---------------------------------------------------------------------
  273. // Check plugin type
  274. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  275. if (itype == CarlaBackend::PLUGIN_NONE)
  276. {
  277. carla_stderr("Invalid plugin type '%s'", stype);
  278. return 1;
  279. }
  280. // ---------------------------------------------------------------------
  281. // Set name
  282. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  283. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  284. name = nullptr;
  285. // ---------------------------------------------------------------------
  286. // Setup options
  287. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  288. const bool useBridge = (shmIds != nullptr);
  289. // ---------------------------------------------------------------------
  290. // Setup bridge ids
  291. char audioPoolBaseName[6+1];
  292. char rtClientBaseName[6+1];
  293. char nonRtClientBaseName[6+1];
  294. char nonRtServerBaseName[6+1];
  295. if (useBridge)
  296. {
  297. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  298. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  299. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  300. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  301. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  302. audioPoolBaseName[6] = '\0';
  303. rtClientBaseName[6] = '\0';
  304. nonRtClientBaseName[6] = '\0';
  305. nonRtServerBaseName[6] = '\0';
  306. #ifdef CARLA_OS_LINUX
  307. // terminate ourselves if main carla dies
  308. ::prctl(PR_SET_PDEATHSIG, SIGTERM);
  309. // TODO, osx version too, see https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits
  310. #endif
  311. }
  312. else
  313. {
  314. audioPoolBaseName[0] = '\0';
  315. rtClientBaseName[0] = '\0';
  316. nonRtClientBaseName[0] = '\0';
  317. nonRtServerBaseName[0] = '\0';
  318. jackbridge_init();
  319. }
  320. // ---------------------------------------------------------------------
  321. // Set client name
  322. CarlaString clientName;
  323. if (name != nullptr)
  324. {
  325. clientName = name;
  326. }
  327. else if (itype == CarlaBackend::PLUGIN_LV2)
  328. {
  329. // LV2 requires URI
  330. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  331. // LV2 URI is not usable as client name, create a usable name from URI
  332. CarlaString label2(label);
  333. // truncate until last valid char
  334. for (std::size_t i=label2.length()-1; i != 0; --i)
  335. {
  336. if (! std::isalnum(label2[i]))
  337. continue;
  338. label2.truncate(i+1);
  339. break;
  340. }
  341. // get last used separator
  342. bool found;
  343. std::size_t septmp, sep = 0;
  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. septmp = label2.rfind('=', &found)+1;
  351. if (found && septmp > sep)
  352. sep = septmp;
  353. septmp = label2.rfind(':', &found)+1;
  354. if (found && septmp > sep)
  355. sep = septmp;
  356. // make name starting from the separator and first valid char
  357. const char* name2 = label2.buffer() + sep;
  358. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  359. if (*name2 != '\0')
  360. clientName = name2;
  361. }
  362. else if (label != nullptr)
  363. {
  364. clientName = label;
  365. }
  366. else
  367. {
  368. const String jfilename = String(CharPointer_UTF8(filename));
  369. clientName = File(jfilename).getFileNameWithoutExtension().toRawUTF8();
  370. }
  371. // if we still have no client name by now, use a dummy one
  372. if (clientName.isEmpty())
  373. clientName = "carla-plugin";
  374. // just to be safe
  375. clientName.toBasic();
  376. // ---------------------------------------------------------------------
  377. // Set extraStuff
  378. const void* extraStuff = nullptr;
  379. if (itype == CarlaBackend::PLUGIN_GIG || itype == CarlaBackend::PLUGIN_SF2)
  380. {
  381. if (label == nullptr)
  382. label = clientName;
  383. if (std::strstr(label, " (16 outs)") != nullptr)
  384. extraStuff = "true";
  385. }
  386. #ifdef HAVE_X11
  387. if (std::getenv("DISPLAY") != nullptr)
  388. XInitThreads();
  389. #endif
  390. // ---------------------------------------------------------------------
  391. // Init plugin bridge
  392. CarlaBridgePlugin bridge(useBridge, clientName, audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  393. if (! bridge.isOk())
  394. {
  395. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  396. return 1;
  397. }
  398. // ---------------------------------------------------------------------
  399. // Listen for ctrl+c or sigint/sigterm events
  400. initSignalHandler();
  401. // ---------------------------------------------------------------------
  402. // Init plugin
  403. int ret;
  404. if (carla_add_plugin(btype, itype, filename, name, label, uniqueId, extraStuff, 0x0))
  405. {
  406. ret = 0;
  407. if (! useBridge)
  408. {
  409. carla_set_active(0, true);
  410. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  411. {
  412. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  413. {
  414. #ifdef HAVE_X11
  415. if (std::getenv("DISPLAY") != nullptr)
  416. #endif
  417. carla_show_custom_ui(0, true);
  418. }
  419. }
  420. }
  421. bridge.exec(useBridge, argc, argv);
  422. }
  423. else
  424. {
  425. ret = 1;
  426. const char* const lastError(carla_get_last_error());
  427. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  428. //if (useBridge)
  429. // bridge.sendOscBridgeError(lastError);
  430. }
  431. return ret;
  432. }