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::ScopedJuceInitialiser_GUI;
  35. using juce::Timer;
  36. #endif
  37. using CarlaBackend::CarlaEngine;
  38. using CarlaBackend::EngineCallbackOpcode;
  39. using CarlaBackend::EngineCallbackOpcode2Str;
  40. using juce::CharPointer_UTF8;
  41. using juce::File;
  42. using juce::String;
  43. // -------------------------------------------------------------------------
  44. static bool gIsInitiated = false;
  45. static volatile bool gCloseNow = false;
  46. static volatile bool gSaveNow = false;
  47. #ifdef CARLA_OS_WIN
  48. static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
  49. {
  50. if (dwCtrlType == CTRL_C_EVENT)
  51. {
  52. gCloseNow = true;
  53. return TRUE;
  54. }
  55. return FALSE;
  56. }
  57. #elif defined(CARLA_OS_LINUX)
  58. static void closeSignalHandler(int) noexcept
  59. {
  60. gCloseNow = true;
  61. }
  62. static void saveSignalHandler(int) noexcept
  63. {
  64. gSaveNow = true;
  65. }
  66. #endif
  67. static void initSignalHandler()
  68. {
  69. #ifdef CARLA_OS_WIN
  70. SetConsoleCtrlHandler(winSignalHandler, TRUE);
  71. #elif defined(CARLA_OS_LINUX)
  72. struct sigaction sig;
  73. carla_zeroStruct(sig);
  74. sig.sa_handler = closeSignalHandler;
  75. sig.sa_flags = SA_RESTART;
  76. sigemptyset(&sig.sa_mask);
  77. sigaction(SIGTERM, &sig, nullptr);
  78. sigaction(SIGINT, &sig, nullptr);
  79. sig.sa_handler = saveSignalHandler;
  80. sig.sa_flags = SA_RESTART;
  81. sigemptyset(&sig.sa_mask);
  82. sigaction(SIGUSR1, &sig, nullptr);
  83. #endif
  84. }
  85. // -------------------------------------------------------------------------
  86. static String gProjectFilename;
  87. static void gIdle()
  88. {
  89. carla_engine_idle();
  90. if (gSaveNow)
  91. {
  92. gSaveNow = false;
  93. if (gProjectFilename.isNotEmpty())
  94. {
  95. if (! carla_save_plugin_state(0, gProjectFilename.toRawUTF8()))
  96. carla_stderr("Plugin preset save failed, error was:\n%s", carla_get_last_error());
  97. }
  98. }
  99. }
  100. // -------------------------------------------------------------------------
  101. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  102. class CarlaJuceApp : public JUCEApplication,
  103. private Timer
  104. {
  105. public:
  106. CarlaJuceApp() {}
  107. ~CarlaJuceApp() {}
  108. void initialise(const String&) override
  109. {
  110. startTimer(8);
  111. }
  112. void shutdown() override
  113. {
  114. gCloseNow = true;
  115. stopTimer();
  116. }
  117. const String getApplicationName() override
  118. {
  119. return "CarlaPlugin";
  120. }
  121. const String getApplicationVersion() override
  122. {
  123. return CARLA_VERSION_STRING;
  124. }
  125. void timerCallback() override
  126. {
  127. gIdle();
  128. if (gCloseNow)
  129. {
  130. quit();
  131. gCloseNow = false;
  132. }
  133. }
  134. };
  135. static JUCEApplicationBase* juce_CreateApplication() { return new CarlaJuceApp(); }
  136. #endif
  137. // -------------------------------------------------------------------------
  138. class CarlaBridgePlugin
  139. {
  140. public:
  141. CarlaBridgePlugin(const bool useBridge, const char* const clientName, const char* const audioPoolBaseName,
  142. const char* const rtClientBaseName, const char* const nonRtClientBaseName, const char* const nonRtServerBaseName)
  143. : fEngine(nullptr),
  144. fUsingBridge(false)
  145. {
  146. CARLA_ASSERT(clientName != nullptr && clientName[0] != '\0');
  147. carla_debug("CarlaBridgePlugin::CarlaBridgePlugin(%s, \"%s\", %s, %s, %s, %s)", bool2str(useBridge), clientName, audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  148. carla_set_engine_callback(callback, this);
  149. if (useBridge)
  150. carla_engine_init_bridge(audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName, clientName);
  151. else
  152. carla_engine_init("JACK", clientName);
  153. fEngine = carla_get_engine();
  154. }
  155. ~CarlaBridgePlugin()
  156. {
  157. carla_debug("CarlaBridgePlugin::~CarlaBridgePlugin()");
  158. carla_engine_close();
  159. }
  160. bool isOk() const noexcept
  161. {
  162. return (fEngine != nullptr);
  163. }
  164. // ---------------------------------------------------------------------
  165. void exec(const bool useBridge, int argc, char* argv[])
  166. {
  167. fUsingBridge = useBridge;
  168. if (! useBridge)
  169. {
  170. const CarlaPluginInfo* const pInfo(carla_get_plugin_info(0));
  171. CARLA_SAFE_ASSERT_RETURN(pInfo != nullptr,);
  172. gProjectFilename = CharPointer_UTF8(pInfo->name);
  173. gProjectFilename += ".carxs";
  174. if (! File::isAbsolutePath(gProjectFilename))
  175. gProjectFilename = File::getCurrentWorkingDirectory().getChildFile(gProjectFilename).getFullPathName();
  176. if (File(gProjectFilename).existsAsFile() && ! carla_load_plugin_state(0, gProjectFilename.toRawUTF8()))
  177. carla_stderr("Plugin preset load failed, error was:\n%s", carla_get_last_error());
  178. }
  179. gIsInitiated = true;
  180. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  181. JUCEApplicationBase::createInstance = &juce_CreateApplication;
  182. JUCEApplicationBase::main(JUCE_MAIN_FUNCTION_ARGS);
  183. #else
  184. for (; ! gCloseNow;)
  185. {
  186. gIdle();
  187. carla_msleep(8);
  188. }
  189. #endif
  190. carla_set_engine_about_to_close();
  191. carla_remove_plugin(0);
  192. // may be unused
  193. return; (void)argc; (void)argv;
  194. }
  195. // ---------------------------------------------------------------------
  196. protected:
  197. void handleCallback(const EngineCallbackOpcode action, const int value1, const int, const float, const char* const)
  198. {
  199. CARLA_BACKEND_USE_NAMESPACE;
  200. switch (action)
  201. {
  202. case ENGINE_CALLBACK_ENGINE_STOPPED:
  203. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  204. case ENGINE_CALLBACK_QUIT:
  205. gCloseNow = true;
  206. break;
  207. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  208. if (gIsInitiated && value1 != 1 && ! fUsingBridge)
  209. gCloseNow = true;
  210. break;
  211. default:
  212. break;
  213. }
  214. }
  215. private:
  216. const CarlaEngine* fEngine;
  217. bool fUsingBridge;
  218. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  219. const ScopedJuceInitialiser_GUI kJuceInitialiser;
  220. #endif
  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. }