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.

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