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.

639 lines
18KB

  1. /*
  2. * Carla Bridge Plugin
  3. * Copyright (C) 2012-2019 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. #ifndef BUILD_BRIDGE
  18. # error This file should not be compiled if not building bridge
  19. #endif
  20. #include "CarlaEngine.hpp"
  21. #include "CarlaHost.h"
  22. #include "CarlaBackendUtils.hpp"
  23. #include "CarlaMainLoop.hpp"
  24. #include "CarlaMIDI.h"
  25. #ifdef CARLA_OS_LINUX
  26. # include <sched.h>
  27. # include <signal.h>
  28. # include <sys/prctl.h>
  29. # define SCHED_RESET_ON_FORK 0x40000000
  30. #endif
  31. #ifdef CARLA_OS_WIN
  32. # include <pthread.h>
  33. # include <objbase.h>
  34. #endif
  35. #ifdef HAVE_X11
  36. # include <X11/Xlib.h>
  37. #endif
  38. #ifdef USING_JUCE
  39. # include "AppConfig.h"
  40. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  41. # include "juce_gui_basics/juce_gui_basics.h"
  42. # else
  43. # include "juce_events/juce_events.h"
  44. # endif
  45. #endif
  46. #include "jackbridge/JackBridge.hpp"
  47. #include "water/files/File.h"
  48. using CarlaBackend::CarlaEngine;
  49. using CarlaBackend::EngineCallbackOpcode;
  50. using CarlaBackend::EngineCallbackOpcode2Str;
  51. using CarlaBackend::runMainLoopOnce;
  52. using water::CharPointer_UTF8;
  53. using water::File;
  54. using water::String;
  55. // -------------------------------------------------------------------------
  56. static bool gIsInitiated = false;
  57. static volatile bool gCloseNow = false;
  58. static volatile bool gSaveNow = false;
  59. #if 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. #elif defined(CARLA_OS_WIN)
  69. static BOOL WINAPI winSignalHandler(DWORD dwCtrlType) noexcept
  70. {
  71. if (dwCtrlType == CTRL_C_EVENT)
  72. {
  73. gCloseNow = true;
  74. return TRUE;
  75. }
  76. return FALSE;
  77. }
  78. #endif
  79. static void initSignalHandler()
  80. {
  81. #if defined(CARLA_OS_LINUX)
  82. struct sigaction sig;
  83. carla_zeroStruct(sig);
  84. sig.sa_handler = closeSignalHandler;
  85. sig.sa_flags = SA_RESTART;
  86. sigemptyset(&sig.sa_mask);
  87. sigaction(SIGTERM, &sig, nullptr);
  88. sigaction(SIGINT, &sig, nullptr);
  89. sig.sa_handler = saveSignalHandler;
  90. sig.sa_flags = SA_RESTART;
  91. sigemptyset(&sig.sa_mask);
  92. sigaction(SIGUSR1, &sig, nullptr);
  93. #elif defined(CARLA_OS_WIN)
  94. SetConsoleCtrlHandler(winSignalHandler, TRUE);
  95. #endif
  96. }
  97. // -------------------------------------------------------------------------
  98. static String gProjectFilename;
  99. static void gIdle()
  100. {
  101. carla_engine_idle();
  102. if (gSaveNow)
  103. {
  104. gSaveNow = false;
  105. if (gProjectFilename.isNotEmpty())
  106. {
  107. if (! carla_save_plugin_state(0, gProjectFilename.toRawUTF8()))
  108. carla_stderr("Plugin preset save failed, error was:\n%s", carla_get_last_error());
  109. }
  110. }
  111. }
  112. // -------------------------------------------------------------------------
  113. #if defined(USING_JUCE) && (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  114. class CarlaJuceApp : public juce::JUCEApplication,
  115. private juce::Timer
  116. {
  117. public:
  118. CarlaJuceApp() {}
  119. ~CarlaJuceApp() {}
  120. void initialise(const juce::String&) override
  121. {
  122. startTimer(8);
  123. }
  124. void shutdown() override
  125. {
  126. gCloseNow = true;
  127. stopTimer();
  128. }
  129. const juce::String getApplicationName() override
  130. {
  131. return "CarlaPlugin";
  132. }
  133. const juce::String getApplicationVersion() override
  134. {
  135. return CARLA_VERSION_STRING;
  136. }
  137. void timerCallback() override
  138. {
  139. gIdle();
  140. if (gCloseNow)
  141. {
  142. quit();
  143. gCloseNow = false;
  144. }
  145. }
  146. };
  147. static juce::JUCEApplicationBase* juce_CreateApplication() { return new CarlaJuceApp(); }
  148. #endif
  149. // -------------------------------------------------------------------------
  150. class CarlaBridgePlugin
  151. {
  152. public:
  153. CarlaBridgePlugin(const bool useBridge, const char* const clientName, const char* const audioPoolBaseName,
  154. const char* const rtClientBaseName, const char* const nonRtClientBaseName, const char* const nonRtServerBaseName)
  155. : fEngine(nullptr),
  156. fUsingBridge(false),
  157. fUsingExec(false)
  158. {
  159. CARLA_ASSERT(clientName != nullptr && clientName[0] != '\0');
  160. carla_debug("CarlaBridgePlugin::CarlaBridgePlugin(%s, \"%s\", %s, %s, %s, %s)",
  161. bool2str(useBridge), clientName, audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  162. carla_set_engine_callback(callback, this);
  163. if (useBridge)
  164. carla_engine_init_bridge(audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName, clientName);
  165. else
  166. carla_engine_init("JACK", clientName);
  167. fEngine = carla_get_engine();
  168. }
  169. ~CarlaBridgePlugin()
  170. {
  171. carla_debug("CarlaBridgePlugin::~CarlaBridgePlugin()");
  172. if (! fUsingExec)
  173. carla_engine_close();
  174. }
  175. bool isOk() const noexcept
  176. {
  177. return (fEngine != nullptr);
  178. }
  179. // ---------------------------------------------------------------------
  180. void exec(const bool useBridge)
  181. {
  182. fUsingBridge = useBridge;
  183. fUsingExec = true;
  184. if (! useBridge)
  185. {
  186. const CarlaPluginInfo* const pInfo(carla_get_plugin_info(0));
  187. CARLA_SAFE_ASSERT_RETURN(pInfo != nullptr,);
  188. gProjectFilename = CharPointer_UTF8(pInfo->name);
  189. gProjectFilename += ".carxs";
  190. if (! File::isAbsolutePath(gProjectFilename))
  191. gProjectFilename = File::getCurrentWorkingDirectory().getChildFile(gProjectFilename).getFullPathName();
  192. if (File(gProjectFilename).existsAsFile())
  193. {
  194. if (carla_load_plugin_state(0, gProjectFilename.toRawUTF8()))
  195. carla_stdout("Plugin state loaded sucessfully");
  196. else
  197. carla_stderr("Plugin state load failed, error was:\n%s", carla_get_last_error());
  198. }
  199. else
  200. {
  201. carla_stdout("Previous plugin state in '%s' is non-existent, will start from default state",
  202. gProjectFilename.toRawUTF8());
  203. }
  204. }
  205. gIsInitiated = true;
  206. #if defined(USING_JUCE) && (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  207. static const int argc = 0;
  208. static const char* argv[] = {};
  209. juce::JUCEApplicationBase::createInstance = &juce_CreateApplication;
  210. juce::JUCEApplicationBase::main(JUCE_MAIN_FUNCTION_ARGS);
  211. #else
  212. for (; runMainLoopOnce() && ! gCloseNow;)
  213. {
  214. gIdle();
  215. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  216. // MacOS and Win32 have event-loops to run, so minimize sleep time
  217. carla_msleep(1);
  218. # else
  219. carla_msleep(5);
  220. # endif
  221. }
  222. #endif
  223. carla_engine_close();
  224. }
  225. // ---------------------------------------------------------------------
  226. protected:
  227. void handleCallback(const EngineCallbackOpcode action, const int value1, const int, const float, const char* const)
  228. {
  229. CARLA_BACKEND_USE_NAMESPACE;
  230. switch (action)
  231. {
  232. case ENGINE_CALLBACK_ENGINE_STOPPED:
  233. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  234. case ENGINE_CALLBACK_QUIT:
  235. gCloseNow = true;
  236. break;
  237. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  238. if (gIsInitiated && value1 != 1 && ! fUsingBridge)
  239. gCloseNow = true;
  240. break;
  241. default:
  242. break;
  243. }
  244. }
  245. private:
  246. const CarlaEngine* fEngine;
  247. bool fUsingBridge;
  248. bool fUsingExec;
  249. #ifdef USING_JUCE
  250. const juce::ScopedJuceInitialiser_GUI sJuceInitialiser;
  251. #endif
  252. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId, int value1, int value2, float value3, const char* valueStr)
  253. {
  254. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %f, \"%s\")", ptr, action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  255. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  256. CARLA_SAFE_ASSERT_RETURN(pluginId == 0,);
  257. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valueStr);
  258. }
  259. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  260. };
  261. // -------------------------------------------------------------------------
  262. int main(int argc, char* argv[])
  263. {
  264. // ---------------------------------------------------------------------
  265. // Check argument count
  266. if (argc != 4 && argc != 5)
  267. {
  268. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  269. return 1;
  270. }
  271. #if defined(CARLA_OS_WIN) && ! defined(BUILDING_CARLA_FOR_WINDOWS)
  272. // ---------------------------------------------------------------------
  273. // Test if bridge is working
  274. if (! jackbridge_is_ok())
  275. {
  276. carla_stderr("A JACK or Wine library is missing, cannot continue");
  277. return 1;
  278. }
  279. #endif
  280. // ---------------------------------------------------------------------
  281. // Get args
  282. const char* const stype = argv[1];
  283. const char* filename = argv[2];
  284. const char* label = argv[3];
  285. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  286. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  287. filename = nullptr;
  288. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  289. label = nullptr;
  290. // ---------------------------------------------------------------------
  291. // Check binary type
  292. CarlaBackend::BinaryType btype = CarlaBackend::BINARY_NATIVE;
  293. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  294. btype = CarlaBackend::getBinaryTypeFromString(binaryTypeStr);
  295. if (btype == CarlaBackend::BINARY_NONE)
  296. {
  297. carla_stderr("Invalid binary type '%i'", btype);
  298. return 1;
  299. }
  300. // ---------------------------------------------------------------------
  301. // Check plugin type
  302. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  303. if (itype == CarlaBackend::PLUGIN_NONE)
  304. {
  305. carla_stderr("Invalid plugin type '%s'", stype);
  306. return 1;
  307. }
  308. // ---------------------------------------------------------------------
  309. // Set file
  310. const File file(filename != nullptr ? filename : "");
  311. // ---------------------------------------------------------------------
  312. // Set name
  313. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  314. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  315. name = nullptr;
  316. // ---------------------------------------------------------------------
  317. // Setup options
  318. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  319. const bool useBridge = (shmIds != nullptr);
  320. // ---------------------------------------------------------------------
  321. // Setup bridge ids
  322. char audioPoolBaseName[6+1];
  323. char rtClientBaseName[6+1];
  324. char nonRtClientBaseName[6+1];
  325. char nonRtServerBaseName[6+1];
  326. if (useBridge)
  327. {
  328. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  329. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  330. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  331. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  332. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  333. audioPoolBaseName[6] = '\0';
  334. rtClientBaseName[6] = '\0';
  335. nonRtClientBaseName[6] = '\0';
  336. nonRtServerBaseName[6] = '\0';
  337. #ifdef CARLA_OS_LINUX
  338. // terminate ourselves if main carla dies
  339. ::prctl(PR_SET_PDEATHSIG, SIGTERM);
  340. // TODO, osx version too, see https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits
  341. #endif
  342. }
  343. else
  344. {
  345. audioPoolBaseName[0] = '\0';
  346. rtClientBaseName[0] = '\0';
  347. nonRtClientBaseName[0] = '\0';
  348. nonRtServerBaseName[0] = '\0';
  349. jackbridge_init();
  350. }
  351. // ---------------------------------------------------------------------
  352. // Set client name
  353. CarlaString clientName;
  354. if (name != nullptr)
  355. {
  356. clientName = name;
  357. }
  358. else if (itype == CarlaBackend::PLUGIN_LV2)
  359. {
  360. // LV2 requires URI
  361. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  362. // LV2 URI is not usable as client name, create a usable name from URI
  363. CarlaString label2(label);
  364. // truncate until last valid char
  365. for (std::size_t i=label2.length()-1; i != 0; --i)
  366. {
  367. if (! std::isalnum(label2[i]))
  368. continue;
  369. label2.truncate(i+1);
  370. break;
  371. }
  372. // get last used separator
  373. bool found;
  374. std::size_t septmp, sep = 0;
  375. septmp = label2.rfind('#', &found)+1;
  376. if (found && septmp > sep)
  377. sep = septmp;
  378. septmp = label2.rfind('/', &found)+1;
  379. if (found && septmp > sep)
  380. sep = septmp;
  381. septmp = label2.rfind('=', &found)+1;
  382. if (found && septmp > sep)
  383. sep = septmp;
  384. septmp = label2.rfind(':', &found)+1;
  385. if (found && septmp > sep)
  386. sep = septmp;
  387. // make name starting from the separator and first valid char
  388. const char* name2 = label2.buffer() + sep;
  389. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  390. if (*name2 != '\0')
  391. clientName = name2;
  392. }
  393. else if (label != nullptr)
  394. {
  395. clientName = label;
  396. }
  397. else
  398. {
  399. clientName = file.getFileNameWithoutExtension().toRawUTF8();
  400. }
  401. // if we still have no client name by now, use a dummy one
  402. if (clientName.isEmpty())
  403. clientName = "carla-plugin";
  404. // just to be safe
  405. clientName.toBasic();
  406. // ---------------------------------------------------------------------
  407. // Set extraStuff
  408. const void* extraStuff = nullptr;
  409. if (itype == CarlaBackend::PLUGIN_SF2)
  410. {
  411. if (label == nullptr)
  412. label = clientName;
  413. if (std::strstr(label, " (16 outs)") != nullptr)
  414. extraStuff = "true";
  415. }
  416. // ---------------------------------------------------------------------
  417. // Initialize OS features
  418. #ifdef CARLA_OS_WIN
  419. OleInitialize(nullptr);
  420. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  421. # ifndef __WINPTHREADS_VERSION
  422. // (non-portable) initialization of statically linked pthread library
  423. pthread_win32_process_attach_np();
  424. pthread_win32_thread_attach_np();
  425. # endif
  426. #endif
  427. #ifdef HAVE_X11
  428. if (std::getenv("DISPLAY") != nullptr)
  429. XInitThreads();
  430. #endif
  431. // ---------------------------------------------------------------------
  432. // Set ourselves with high priority
  433. #ifdef CARLA_OS_LINUX
  434. // reset scheduler to normal mode
  435. struct sched_param sparam;
  436. carla_zeroStruct(sparam);
  437. sched_setscheduler(0, SCHED_OTHER|SCHED_RESET_ON_FORK, &sparam);
  438. // try niceness first, if it fails, try SCHED_RR
  439. if (nice(-5) < 0)
  440. {
  441. sparam.sched_priority = (sched_get_priority_max(SCHED_RR) + sched_get_priority_min(SCHED_RR*7)) / 8;
  442. if (sparam.sched_priority > 0)
  443. {
  444. if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &sparam) < 0)
  445. {
  446. CarlaString error(std::strerror(errno));
  447. carla_stderr("Failed to set high priority, error %i: %s", errno, error.buffer());
  448. }
  449. }
  450. }
  451. #endif
  452. #ifdef CARLA_OS_WIN
  453. if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
  454. carla_stderr("Failed to set high priority.");
  455. #endif
  456. // ---------------------------------------------------------------------
  457. // Listen for ctrl+c or sigint/sigterm events
  458. initSignalHandler();
  459. // ---------------------------------------------------------------------
  460. // Init plugin bridge
  461. int ret;
  462. {
  463. CarlaBridgePlugin bridge(useBridge, clientName,
  464. audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  465. if (! bridge.isOk())
  466. {
  467. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  468. return 1;
  469. }
  470. // -----------------------------------------------------------------
  471. // Init plugin
  472. if (carla_add_plugin(btype, itype, file.getFullPathName().toRawUTF8(), name, label, uniqueId, extraStuff, 0x0))
  473. {
  474. ret = 0;
  475. if (! useBridge)
  476. {
  477. carla_set_active(0, true);
  478. carla_set_option(0, CarlaBackend::PLUGIN_OPTION_SEND_CONTROL_CHANGES, true);
  479. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  480. {
  481. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  482. {
  483. #ifdef HAVE_X11
  484. if (std::getenv("DISPLAY") != nullptr)
  485. #endif
  486. carla_show_custom_ui(0, true);
  487. }
  488. }
  489. }
  490. bridge.exec(useBridge);
  491. }
  492. else
  493. {
  494. ret = 1;
  495. const char* const lastError(carla_get_last_error());
  496. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  497. //if (useBridge)
  498. // bridge.sendOscBridgeError(lastError);
  499. }
  500. }
  501. #ifdef CARLA_OS_WIN
  502. #ifndef __WINPTHREADS_VERSION
  503. pthread_win32_thread_detach_np();
  504. pthread_win32_process_detach_np();
  505. #endif
  506. CoUninitialize();
  507. OleUninitialize();
  508. #endif
  509. return ret;
  510. }