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.

667 lines
19KB

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