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.

637 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. juce::JUCEApplicationBase::createInstance = &juce_CreateApplication;
  208. juce::JUCEApplicationBase::main(JUCE_MAIN_FUNCTION_ARGS);
  209. #else
  210. for (; runMainLoopOnce() && ! gCloseNow;)
  211. {
  212. gIdle();
  213. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  214. // MacOS and Win32 have event-loops to run, so minimize sleep time
  215. carla_msleep(1);
  216. # else
  217. carla_msleep(5);
  218. # endif
  219. }
  220. #endif
  221. carla_engine_close();
  222. }
  223. // ---------------------------------------------------------------------
  224. protected:
  225. void handleCallback(const EngineCallbackOpcode action, const int value1, const int, const float, const char* const)
  226. {
  227. CARLA_BACKEND_USE_NAMESPACE;
  228. switch (action)
  229. {
  230. case ENGINE_CALLBACK_ENGINE_STOPPED:
  231. case ENGINE_CALLBACK_PLUGIN_REMOVED:
  232. case ENGINE_CALLBACK_QUIT:
  233. gCloseNow = true;
  234. break;
  235. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  236. if (gIsInitiated && value1 != 1 && ! fUsingBridge)
  237. gCloseNow = true;
  238. break;
  239. default:
  240. break;
  241. }
  242. }
  243. private:
  244. const CarlaEngine* fEngine;
  245. bool fUsingBridge;
  246. bool fUsingExec;
  247. #ifdef USING_JUCE
  248. const juce::ScopedJuceInitialiser_GUI sJuceInitialiser;
  249. #endif
  250. static void callback(void* ptr, EngineCallbackOpcode action, unsigned int pluginId, int value1, int value2, float value3, const char* valueStr)
  251. {
  252. carla_debug("CarlaBridgePlugin::callback(%p, %i:%s, %i, %i, %i, %f, \"%s\")", ptr, action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  253. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  254. CARLA_SAFE_ASSERT_RETURN(pluginId == 0,);
  255. return ((CarlaBridgePlugin*)ptr)->handleCallback(action, value1, value2, value3, valueStr);
  256. }
  257. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaBridgePlugin)
  258. };
  259. // -------------------------------------------------------------------------
  260. int main(int argc, char* argv[])
  261. {
  262. // ---------------------------------------------------------------------
  263. // Check argument count
  264. if (argc != 4 && argc != 5)
  265. {
  266. carla_stdout("usage: %s <type> <filename> <label> [uniqueId]", argv[0]);
  267. return 1;
  268. }
  269. #if defined(CARLA_OS_WIN) && ! defined(BUILDING_CARLA_FOR_WINDOWS)
  270. // ---------------------------------------------------------------------
  271. // Test if bridge is working
  272. if (! jackbridge_is_ok())
  273. {
  274. carla_stderr("A JACK or Wine library is missing, cannot continue");
  275. return 1;
  276. }
  277. #endif
  278. // ---------------------------------------------------------------------
  279. // Get args
  280. const char* const stype = argv[1];
  281. const char* filename = argv[2];
  282. const char* label = argv[3];
  283. const int64_t uniqueId = (argc == 5) ? static_cast<int64_t>(std::atoll(argv[4])) : 0;
  284. if (filename[0] == '\0' || std::strcmp(filename, "(none)") == 0)
  285. filename = nullptr;
  286. if (label[0] == '\0' || std::strcmp(label, "(none)") == 0)
  287. label = nullptr;
  288. // ---------------------------------------------------------------------
  289. // Check binary type
  290. CarlaBackend::BinaryType btype = CarlaBackend::BINARY_NATIVE;
  291. if (const char* const binaryTypeStr = std::getenv("CARLA_BRIDGE_PLUGIN_BINARY_TYPE"))
  292. btype = CarlaBackend::getBinaryTypeFromString(binaryTypeStr);
  293. if (btype == CarlaBackend::BINARY_NONE)
  294. {
  295. carla_stderr("Invalid binary type '%i'", btype);
  296. return 1;
  297. }
  298. // ---------------------------------------------------------------------
  299. // Check plugin type
  300. CarlaBackend::PluginType itype(CarlaBackend::getPluginTypeFromString(stype));
  301. if (itype == CarlaBackend::PLUGIN_NONE)
  302. {
  303. carla_stderr("Invalid plugin type '%s'", stype);
  304. return 1;
  305. }
  306. // ---------------------------------------------------------------------
  307. // Set file
  308. const File file(filename != nullptr ? filename : "");
  309. // ---------------------------------------------------------------------
  310. // Set name
  311. const char* name(std::getenv("CARLA_CLIENT_NAME"));
  312. if (name != nullptr && (name[0] == '\0' || std::strcmp(name, "(none)") == 0))
  313. name = nullptr;
  314. // ---------------------------------------------------------------------
  315. // Setup options
  316. const char* const shmIds(std::getenv("ENGINE_BRIDGE_SHM_IDS"));
  317. const bool useBridge = (shmIds != nullptr);
  318. // ---------------------------------------------------------------------
  319. // Setup bridge ids
  320. char audioPoolBaseName[6+1];
  321. char rtClientBaseName[6+1];
  322. char nonRtClientBaseName[6+1];
  323. char nonRtServerBaseName[6+1];
  324. if (useBridge)
  325. {
  326. CARLA_SAFE_ASSERT_RETURN(std::strlen(shmIds) == 6*4, 1);
  327. std::strncpy(audioPoolBaseName, shmIds+6*0, 6);
  328. std::strncpy(rtClientBaseName, shmIds+6*1, 6);
  329. std::strncpy(nonRtClientBaseName, shmIds+6*2, 6);
  330. std::strncpy(nonRtServerBaseName, shmIds+6*3, 6);
  331. audioPoolBaseName[6] = '\0';
  332. rtClientBaseName[6] = '\0';
  333. nonRtClientBaseName[6] = '\0';
  334. nonRtServerBaseName[6] = '\0';
  335. #ifdef CARLA_OS_LINUX
  336. // terminate ourselves if main carla dies
  337. ::prctl(PR_SET_PDEATHSIG, SIGTERM);
  338. // TODO, osx version too, see https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits
  339. #endif
  340. }
  341. else
  342. {
  343. audioPoolBaseName[0] = '\0';
  344. rtClientBaseName[0] = '\0';
  345. nonRtClientBaseName[0] = '\0';
  346. nonRtServerBaseName[0] = '\0';
  347. jackbridge_init();
  348. }
  349. // ---------------------------------------------------------------------
  350. // Set client name
  351. CarlaString clientName;
  352. if (name != nullptr)
  353. {
  354. clientName = name;
  355. }
  356. else if (itype == CarlaBackend::PLUGIN_LV2)
  357. {
  358. // LV2 requires URI
  359. CARLA_SAFE_ASSERT_RETURN(label != nullptr && label[0] != '\0', 1);
  360. // LV2 URI is not usable as client name, create a usable name from URI
  361. CarlaString label2(label);
  362. // truncate until last valid char
  363. for (std::size_t i=label2.length()-1; i != 0; --i)
  364. {
  365. if (! std::isalnum(label2[i]))
  366. continue;
  367. label2.truncate(i+1);
  368. break;
  369. }
  370. // get last used separator
  371. bool found;
  372. std::size_t septmp, sep = 0;
  373. septmp = label2.rfind('#', &found)+1;
  374. if (found && septmp > sep)
  375. sep = septmp;
  376. septmp = label2.rfind('/', &found)+1;
  377. if (found && septmp > sep)
  378. sep = septmp;
  379. septmp = label2.rfind('=', &found)+1;
  380. if (found && septmp > sep)
  381. sep = septmp;
  382. septmp = label2.rfind(':', &found)+1;
  383. if (found && septmp > sep)
  384. sep = septmp;
  385. // make name starting from the separator and first valid char
  386. const char* name2 = label2.buffer() + sep;
  387. for (; *name2 != '\0' && ! std::isalnum(*name2); ++name2) {}
  388. if (*name2 != '\0')
  389. clientName = name2;
  390. }
  391. else if (label != nullptr)
  392. {
  393. clientName = label;
  394. }
  395. else
  396. {
  397. clientName = file.getFileNameWithoutExtension().toRawUTF8();
  398. }
  399. // if we still have no client name by now, use a dummy one
  400. if (clientName.isEmpty())
  401. clientName = "carla-plugin";
  402. // just to be safe
  403. clientName.toBasic();
  404. // ---------------------------------------------------------------------
  405. // Set extraStuff
  406. const void* extraStuff = nullptr;
  407. if (itype == CarlaBackend::PLUGIN_SF2)
  408. {
  409. if (label == nullptr)
  410. label = clientName;
  411. if (std::strstr(label, " (16 outs)") != nullptr)
  412. extraStuff = "true";
  413. }
  414. // ---------------------------------------------------------------------
  415. // Initialize OS features
  416. #ifdef CARLA_OS_WIN
  417. OleInitialize(nullptr);
  418. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  419. # ifndef __WINPTHREADS_VERSION
  420. // (non-portable) initialization of statically linked pthread library
  421. pthread_win32_process_attach_np();
  422. pthread_win32_thread_attach_np();
  423. # endif
  424. #endif
  425. #ifdef HAVE_X11
  426. if (std::getenv("DISPLAY") != nullptr)
  427. XInitThreads();
  428. #endif
  429. // ---------------------------------------------------------------------
  430. // Set ourselves with high priority
  431. #ifdef CARLA_OS_LINUX
  432. // reset scheduler to normal mode
  433. struct sched_param sparam;
  434. carla_zeroStruct(sparam);
  435. sched_setscheduler(0, SCHED_OTHER|SCHED_RESET_ON_FORK, &sparam);
  436. // try niceness first, if it fails, try SCHED_RR
  437. if (nice(-5) < 0)
  438. {
  439. sparam.sched_priority = (sched_get_priority_max(SCHED_RR) + sched_get_priority_min(SCHED_RR*7)) / 8;
  440. if (sparam.sched_priority > 0)
  441. {
  442. if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &sparam) < 0)
  443. {
  444. CarlaString error(std::strerror(errno));
  445. carla_stderr("Failed to set high priority, error %i: %s", errno, error.buffer());
  446. }
  447. }
  448. }
  449. #endif
  450. #ifdef CARLA_OS_WIN
  451. if (! SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
  452. carla_stderr("Failed to set high priority.");
  453. #endif
  454. // ---------------------------------------------------------------------
  455. // Listen for ctrl+c or sigint/sigterm events
  456. initSignalHandler();
  457. // ---------------------------------------------------------------------
  458. // Init plugin bridge
  459. int ret;
  460. {
  461. CarlaBridgePlugin bridge(useBridge, clientName,
  462. audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  463. if (! bridge.isOk())
  464. {
  465. carla_stderr("Failed to init engine, error was:\n%s", carla_get_last_error());
  466. return 1;
  467. }
  468. // -----------------------------------------------------------------
  469. // Init plugin
  470. if (carla_add_plugin(btype, itype, file.getFullPathName().toRawUTF8(), name, label, uniqueId, extraStuff, 0x0))
  471. {
  472. ret = 0;
  473. if (! useBridge)
  474. {
  475. carla_set_active(0, true);
  476. carla_set_option(0, CarlaBackend::PLUGIN_OPTION_SEND_CONTROL_CHANGES, true);
  477. if (const CarlaPluginInfo* const pluginInfo = carla_get_plugin_info(0))
  478. {
  479. if (pluginInfo->hints & CarlaBackend::PLUGIN_HAS_CUSTOM_UI)
  480. {
  481. #ifdef HAVE_X11
  482. if (std::getenv("DISPLAY") != nullptr)
  483. #endif
  484. carla_show_custom_ui(0, true);
  485. }
  486. }
  487. }
  488. bridge.exec(useBridge);
  489. }
  490. else
  491. {
  492. ret = 1;
  493. const char* const lastError(carla_get_last_error());
  494. carla_stderr("Plugin failed to load, error was:\n%s", lastError);
  495. //if (useBridge)
  496. // bridge.sendOscBridgeError(lastError);
  497. }
  498. }
  499. #ifdef CARLA_OS_WIN
  500. #ifndef __WINPTHREADS_VERSION
  501. pthread_win32_thread_detach_np();
  502. pthread_win32_process_detach_np();
  503. #endif
  504. CoUninitialize();
  505. OleUninitialize();
  506. #endif
  507. return ret;
  508. }