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.

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