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.

718 lines
21KB

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