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.

3572 lines
122KB

  1. // SPDX-FileCopyrightText: 2011-2024 Filipe Coelho <falktx@falktx.com>
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. /* TODO:
  4. * - complete processRack(): carefully add to input, sorted events
  5. * - implement processPatchbay()
  6. * - implement oscSend_control_switch_plugins()
  7. * - something about the peaks?
  8. */
  9. #include "CarlaEngineClient.hpp"
  10. #include "CarlaEngineInit.hpp"
  11. #include "CarlaEngineInternal.hpp"
  12. #include "CarlaPlugin.hpp"
  13. #include "CarlaBackendUtils.hpp"
  14. #include "CarlaBinaryUtils.hpp"
  15. #include "CarlaEngineUtils.hpp"
  16. #include "CarlaMathUtils.hpp"
  17. #include "CarlaPipeUtils.hpp"
  18. #include "CarlaProcessUtils.hpp"
  19. #include "CarlaScopeUtils.hpp"
  20. #include "CarlaStateUtils.hpp"
  21. #include "CarlaMIDI.h"
  22. #include "jackbridge/JackBridge.hpp"
  23. #include "water/files/File.h"
  24. #include "water/streams/MemoryOutputStream.h"
  25. #include "water/xml/XmlDocument.h"
  26. #include "water/xml/XmlElement.h"
  27. #ifdef CARLA_OS_MAC
  28. # include "CarlaMacUtils.hpp"
  29. # if defined(CARLA_OS_64BIT) && defined(HAVE_LIBMAGIC) && ! defined(BUILD_BRIDGE_ALTERNATIVE_ARCH)
  30. # define ADAPT_FOR_APPLE_SILLICON
  31. # endif
  32. #endif
  33. #include <map>
  34. // FIXME Remove on 2.1 release
  35. #include "lv2/atom.h"
  36. using water::Array;
  37. using water::CharPointer_UTF8;
  38. using water::File;
  39. using water::MemoryOutputStream;
  40. using water::String;
  41. using water::StringArray;
  42. using water::XmlDocument;
  43. using water::XmlElement;
  44. // #define SFZ_FILES_USING_SFIZZ
  45. CARLA_BACKEND_START_NAMESPACE
  46. // -----------------------------------------------------------------------
  47. // Carla Engine
  48. CarlaEngine::CarlaEngine()
  49. : pData(new ProtectedData(this))
  50. {
  51. carla_debug("CarlaEngine::CarlaEngine()");
  52. }
  53. CarlaEngine::~CarlaEngine()
  54. {
  55. carla_debug("CarlaEngine::~CarlaEngine()");
  56. delete pData;
  57. }
  58. // -----------------------------------------------------------------------
  59. // Static calls
  60. uint CarlaEngine::getDriverCount()
  61. {
  62. carla_debug("CarlaEngine::getDriverCount()");
  63. using namespace EngineInit;
  64. uint count = 0;
  65. #ifdef HAVE_JACK
  66. if (jackbridge_is_ok())
  67. ++count;
  68. #endif
  69. #ifdef USING_RTAUDIO
  70. count += getRtAudioApiCount();
  71. #endif
  72. #ifdef HAVE_SDL
  73. ++count;
  74. #endif
  75. return count;
  76. }
  77. const char* CarlaEngine::getDriverName(const uint index)
  78. {
  79. carla_debug("CarlaEngine::getDriverName(%u)", index);
  80. using namespace EngineInit;
  81. uint index2 = index;
  82. #ifdef HAVE_JACK
  83. if (jackbridge_is_ok())
  84. {
  85. if (index2 == 0)
  86. return "JACK";
  87. --index2;
  88. }
  89. #endif
  90. #ifdef USING_RTAUDIO
  91. if (const uint count = getRtAudioApiCount())
  92. {
  93. if (index2 < count)
  94. return getRtAudioApiName(index2);
  95. index2 -= count;
  96. }
  97. #endif
  98. #ifdef HAVE_SDL
  99. if (index2 == 0)
  100. return "SDL";
  101. --index2;
  102. #endif
  103. carla_stderr("CarlaEngine::getDriverName(%u) - invalid index %u", index, index2);
  104. return nullptr;
  105. }
  106. const char* const* CarlaEngine::getDriverDeviceNames(const uint index)
  107. {
  108. carla_debug("CarlaEngine::getDriverDeviceNames(%u)", index);
  109. using namespace EngineInit;
  110. uint index2 = index;
  111. #ifdef HAVE_JACK
  112. if (jackbridge_is_ok())
  113. {
  114. if (index2 == 0)
  115. {
  116. static const char* ret[3] = { "Auto-Connect ON", "Auto-Connect OFF", nullptr };
  117. return ret;
  118. }
  119. --index2;
  120. }
  121. #endif
  122. #ifdef USING_RTAUDIO
  123. if (const uint count = getRtAudioApiCount())
  124. {
  125. if (index2 < count)
  126. return getRtAudioApiDeviceNames(index2);
  127. index2 -= count;
  128. }
  129. #endif
  130. #ifdef HAVE_SDL
  131. if (index2 == 0)
  132. return getSDLDeviceNames();
  133. --index2;
  134. #endif
  135. carla_stderr("CarlaEngine::getDriverDeviceNames(%u) - invalid index %u", index, index2);
  136. return nullptr;
  137. }
  138. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index, const char* const deviceName)
  139. {
  140. carla_debug("CarlaEngine::getDriverDeviceInfo(%u, \"%s\")", index, deviceName);
  141. using namespace EngineInit;
  142. uint index2 = index;
  143. #ifdef HAVE_JACK
  144. if (jackbridge_is_ok())
  145. {
  146. if (index2 == 0)
  147. {
  148. static EngineDriverDeviceInfo devInfo;
  149. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  150. devInfo.bufferSizes = nullptr;
  151. devInfo.sampleRates = nullptr;
  152. return &devInfo;
  153. }
  154. --index2;
  155. }
  156. #endif
  157. #ifdef USING_RTAUDIO
  158. if (const uint count = getRtAudioApiCount())
  159. {
  160. if (index2 < count)
  161. return getRtAudioDeviceInfo(index2, deviceName);
  162. index2 -= count;
  163. }
  164. #endif
  165. #ifdef HAVE_SDL
  166. if (index2 == 0)
  167. {
  168. static uint32_t sdlBufferSizes[] = { 512, 1024, 2048, 4096, 8192, 0 };
  169. static double sdlSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 0.0 };
  170. static EngineDriverDeviceInfo devInfo;
  171. devInfo.hints = 0x0;
  172. devInfo.bufferSizes = sdlBufferSizes;
  173. devInfo.sampleRates = sdlSampleRates;
  174. return &devInfo;
  175. }
  176. --index2;
  177. #endif
  178. carla_stderr("CarlaEngine::getDriverDeviceInfo(%u, \"%s\") - invalid index %u", index, deviceName, index2);
  179. return nullptr;
  180. }
  181. bool CarlaEngine::showDriverDeviceControlPanel(const uint index, const char* const deviceName)
  182. {
  183. carla_debug("CarlaEngine::showDriverDeviceControlPanel(%u, \"%s\")", index, deviceName);
  184. using namespace EngineInit;
  185. uint index2 = index;
  186. #ifdef HAVE_JACK
  187. if (jackbridge_is_ok())
  188. {
  189. if (index2 == 0)
  190. return false;
  191. --index2;
  192. }
  193. #endif
  194. #ifdef USING_RTAUDIO
  195. if (const uint count = getRtAudioApiCount())
  196. {
  197. if (index2 < count)
  198. return false;
  199. index2 -= count;
  200. }
  201. #endif
  202. #ifdef HAVE_SDL
  203. if (index2 == 0)
  204. return false;
  205. --index2;
  206. #endif
  207. carla_stderr("CarlaEngine::showDriverDeviceControlPanel(%u, \"%s\") - invalid index %u", index, deviceName, index2);
  208. return false;
  209. }
  210. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  211. {
  212. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  213. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  214. using namespace EngineInit;
  215. #ifdef HAVE_JACK
  216. if (std::strcmp(driverName, "JACK") == 0)
  217. return newJack();
  218. #endif
  219. #if !(defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) || defined(CARLA_OS_WASM) || defined(CARLA_PLUGIN_BUILD) || defined(STATIC_PLUGIN_TARGET))
  220. if (std::strcmp(driverName, "Dummy") == 0)
  221. return newDummy();
  222. #endif
  223. #ifdef USING_RTAUDIO
  224. // -------------------------------------------------------------------
  225. // common
  226. if (std::strncmp(driverName, "JACK ", 5) == 0)
  227. return newRtAudio(AUDIO_API_JACK);
  228. if (std::strcmp(driverName, "OSS") == 0)
  229. return newRtAudio(AUDIO_API_OSS);
  230. // -------------------------------------------------------------------
  231. // linux
  232. if (std::strcmp(driverName, "ALSA") == 0)
  233. return newRtAudio(AUDIO_API_ALSA);
  234. if (std::strcmp(driverName, "PulseAudio") == 0)
  235. return newRtAudio(AUDIO_API_PULSEAUDIO);
  236. // -------------------------------------------------------------------
  237. // macos
  238. if (std::strcmp(driverName, "CoreAudio") == 0)
  239. return newRtAudio(AUDIO_API_COREAUDIO);
  240. // -------------------------------------------------------------------
  241. // windows
  242. if (std::strcmp(driverName, "ASIO") == 0)
  243. return newRtAudio(AUDIO_API_ASIO);
  244. if (std::strcmp(driverName, "DirectSound") == 0)
  245. return newRtAudio(AUDIO_API_DIRECTSOUND);
  246. if (std::strcmp(driverName, "WASAPI") == 0)
  247. return newRtAudio(AUDIO_API_WASAPI);
  248. #endif
  249. #ifdef HAVE_SDL
  250. if (std::strcmp(driverName, "SDL") == 0)
  251. return newSDL();
  252. #endif
  253. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  254. return nullptr;
  255. }
  256. // -----------------------------------------------------------------------
  257. // Constant values
  258. uint CarlaEngine::getMaxClientNameSize() const noexcept
  259. {
  260. return STR_MAX/2;
  261. }
  262. uint CarlaEngine::getMaxPortNameSize() const noexcept
  263. {
  264. return STR_MAX;
  265. }
  266. uint CarlaEngine::getCurrentPluginCount() const noexcept
  267. {
  268. return pData->curPluginCount;
  269. }
  270. uint CarlaEngine::getMaxPluginNumber() const noexcept
  271. {
  272. return pData->maxPluginNumber;
  273. }
  274. // -----------------------------------------------------------------------
  275. // Virtual, per-engine type calls
  276. bool CarlaEngine::close()
  277. {
  278. carla_debug("CarlaEngine::close()");
  279. if (pData->curPluginCount != 0)
  280. {
  281. pData->aboutToClose = true;
  282. removeAllPlugins();
  283. }
  284. pData->close();
  285. callback(true, true, ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0, 0.0f, nullptr);
  286. return true;
  287. }
  288. bool CarlaEngine::usesConstantBufferSize() const noexcept
  289. {
  290. return true;
  291. }
  292. void CarlaEngine::idle() noexcept
  293. {
  294. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  295. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  296. CARLA_SAFE_ASSERT_RETURN(getType() != kEngineTypePlugin,);
  297. const bool engineNotRunning = !isRunning();
  298. const bool engineHasIdleOnMainThread = hasIdleOnMainThread();
  299. for (uint i=0; i < pData->curPluginCount; ++i)
  300. {
  301. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  302. {
  303. if (plugin->isEnabled())
  304. {
  305. const uint hints = plugin->getHints();
  306. if (engineNotRunning)
  307. {
  308. try {
  309. plugin->idle();
  310. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin idle");
  311. if (hints & PLUGIN_HAS_CUSTOM_UI)
  312. {
  313. try {
  314. plugin->uiIdle();
  315. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  316. }
  317. }
  318. else
  319. {
  320. if (engineHasIdleOnMainThread && (hints & PLUGIN_NEEDS_MAIN_THREAD_IDLE) != 0)
  321. {
  322. try {
  323. plugin->idle();
  324. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin idle");
  325. }
  326. if ((hints & PLUGIN_HAS_CUSTOM_UI) != 0 && (hints & PLUGIN_NEEDS_UI_MAIN_THREAD) != 0)
  327. {
  328. try {
  329. plugin->uiIdle();
  330. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  331. }
  332. }
  333. }
  334. }
  335. }
  336. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  337. pData->osc.idle();
  338. #endif
  339. pData->deletePluginsAsNeeded();
  340. }
  341. CarlaEngineClient* CarlaEngine::addClient(CarlaPluginPtr plugin)
  342. {
  343. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  344. return new CarlaEngineClientForStandalone(*this, pData->graph, plugin);
  345. #else
  346. return new CarlaEngineClientForBridge(*this);
  347. // unused
  348. (void)plugin;
  349. #endif
  350. }
  351. float CarlaEngine::getDSPLoad() const noexcept
  352. {
  353. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  354. return pData->dspLoad;
  355. #else
  356. return 0.0f;
  357. #endif
  358. }
  359. uint32_t CarlaEngine::getTotalXruns() const noexcept
  360. {
  361. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  362. return pData->xruns;
  363. #else
  364. return 0;
  365. #endif
  366. }
  367. void CarlaEngine::clearXruns() const noexcept
  368. {
  369. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  370. pData->xruns = 0;
  371. #endif
  372. }
  373. bool CarlaEngine::showDeviceControlPanel() const noexcept
  374. {
  375. return false;
  376. }
  377. bool CarlaEngine::setBufferSizeAndSampleRate(const uint, const double)
  378. {
  379. return false;
  380. }
  381. // -----------------------------------------------------------------------
  382. // Plugin management
  383. bool CarlaEngine::addPlugin(const BinaryType btype,
  384. const PluginType ptype,
  385. const char* const filename,
  386. const char* const name,
  387. const char* const label,
  388. const int64_t uniqueId,
  389. const void* const extra,
  390. const uint options)
  391. {
  392. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  393. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  394. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  395. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  396. #endif
  397. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  398. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  399. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  400. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  401. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p, %u)",
  402. btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra, options);
  403. #ifndef CARLA_OS_WIN
  404. if (ptype != PLUGIN_JACK && ptype != PLUGIN_LV2 && filename != nullptr && filename[0] != '\0') {
  405. CARLA_SAFE_ASSERT_RETURN_ERR(filename[0] == CARLA_OS_SEP || filename[0] == '.' || filename[0] == '~', "Invalid plugin filename");
  406. }
  407. #endif
  408. uint id;
  409. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  410. CarlaPluginPtr oldPlugin;
  411. if (pData->nextPluginId < pData->curPluginCount)
  412. {
  413. id = pData->nextPluginId;
  414. pData->nextPluginId = pData->maxPluginNumber;
  415. oldPlugin = pData->plugins[id].plugin;
  416. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin.get() != nullptr, "Invalid replace plugin Id");
  417. }
  418. else
  419. #endif
  420. {
  421. id = pData->curPluginCount;
  422. if (id == pData->maxPluginNumber)
  423. {
  424. setLastError("Maximum number of plugins reached");
  425. return false;
  426. }
  427. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  428. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin.get() == nullptr, "Invalid engine internal data");
  429. #endif
  430. }
  431. CarlaPlugin::Initializer initializer = {
  432. this,
  433. id,
  434. filename,
  435. name,
  436. label,
  437. uniqueId,
  438. options
  439. };
  440. CarlaPluginPtr plugin;
  441. CarlaString bridgeBinary(pData->options.binaryDir);
  442. if (bridgeBinary.isNotEmpty())
  443. {
  444. #ifndef CARLA_OS_WIN
  445. if (btype == BINARY_NATIVE)
  446. {
  447. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  448. }
  449. else
  450. #endif
  451. {
  452. switch (btype)
  453. {
  454. case BINARY_POSIX32:
  455. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  456. break;
  457. case BINARY_POSIX64:
  458. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  459. break;
  460. case BINARY_WIN32:
  461. #if defined(CARLA_OS_WIN) && !defined(CARLA_OS_64BIT)
  462. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native.exe";
  463. #else
  464. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  465. #endif
  466. break;
  467. case BINARY_WIN64:
  468. #if defined(CARLA_OS_WIN) && defined(CARLA_OS_64BIT)
  469. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native.exe";
  470. #else
  471. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  472. #endif
  473. break;
  474. default:
  475. bridgeBinary.clear();
  476. break;
  477. }
  478. }
  479. if (! File(bridgeBinary.buffer()).existsAsFile())
  480. bridgeBinary.clear();
  481. }
  482. const bool canBeBridged = ptype != PLUGIN_INTERNAL
  483. && ptype != PLUGIN_DLS
  484. && ptype != PLUGIN_GIG
  485. && ptype != PLUGIN_SF2
  486. && ptype != PLUGIN_SFZ
  487. && ptype != PLUGIN_JSFX
  488. && ptype != PLUGIN_JACK;
  489. // Prefer bridges for some specific plugins
  490. bool preferBridges = pData->options.preferPluginBridges;
  491. const char* needsArchBridge = nullptr;
  492. #ifdef CARLA_OS_MAC
  493. // Plugin might be in quarentine due to Apple stupid notarization rules, let's remove that if possible
  494. if (canBeBridged && ptype != PLUGIN_LV2 && ptype != PLUGIN_AU)
  495. removeFileFromQuarantine(filename);
  496. #endif
  497. #ifndef BUILD_BRIDGE
  498. if (canBeBridged && ! preferBridges)
  499. {
  500. /*
  501. if (ptype == PLUGIN_LV2 && label != nullptr)
  502. {
  503. if (std::strncmp(label, "http://calf.sourceforge.net/plugins/", 36) == 0 ||
  504. std::strcmp(label, "http://factorial.hu/plugins/lv2/ir") == 0 ||
  505. std::strstr(label, "v1.sourceforge.net/lv2") != nullptr)
  506. {
  507. preferBridges = true;
  508. }
  509. }
  510. */
  511. #ifdef ADAPT_FOR_APPLE_SILLICON
  512. // see if this binary needs bridging
  513. if (ptype == PLUGIN_VST2 || ptype == PLUGIN_VST3)
  514. {
  515. if (const char* const vst2Binary = findBinaryInBundle(filename))
  516. {
  517. const CarlaMagic magic;
  518. if (const char* const output = magic.getFileDescription(vst2Binary))
  519. {
  520. carla_stdout("VST binary magic output is '%s'", output);
  521. #ifdef __aarch64__
  522. if (std::strstr(output, "arm64") == nullptr && std::strstr(output, "x86_64") != nullptr)
  523. needsArchBridge = "x86_64";
  524. #else
  525. if (std::strstr(output, "x86_64") == nullptr && std::strstr(output, "arm64") != nullptr)
  526. needsArchBridge = "arm64";
  527. #endif
  528. }
  529. else
  530. {
  531. carla_stdout("VST binary magic output is null");
  532. }
  533. }
  534. else
  535. {
  536. carla_stdout("Search for binary in VST bundle failed");
  537. }
  538. }
  539. #endif // ADAPT_FOR_APPLE_SILLICON
  540. }
  541. #endif // ! BUILD_BRIDGE
  542. #if defined(CARLA_PLUGIN_ONLY_BRIDGE)
  543. if (bridgeBinary.isNotEmpty())
  544. {
  545. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, needsArchBridge, bridgeBinary);
  546. }
  547. else
  548. {
  549. setLastError("Cannot load plugin, the required plugin bridge is not available");
  550. return false;
  551. }
  552. #elif !defined(CARLA_OS_WASM)
  553. if (canBeBridged && (needsArchBridge || btype != BINARY_NATIVE || (preferBridges && bridgeBinary.isNotEmpty())))
  554. {
  555. if (bridgeBinary.isNotEmpty())
  556. {
  557. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, needsArchBridge, bridgeBinary);
  558. }
  559. else
  560. {
  561. setLastError("This Carla build cannot handle this binary");
  562. return false;
  563. }
  564. }
  565. else
  566. #endif
  567. #ifndef CARLA_PLUGIN_ONLY_BRIDGE
  568. {
  569. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  570. bool use16Outs;
  571. #endif
  572. setLastError("Invalid or unsupported plugin type");
  573. // Some stupid plugins mess up with global signals, err!!
  574. const CarlaSignalRestorer csr;
  575. switch (ptype)
  576. {
  577. case PLUGIN_NONE:
  578. case PLUGIN_TYPE_COUNT:
  579. break;
  580. case PLUGIN_LADSPA:
  581. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  582. break;
  583. case PLUGIN_DSSI:
  584. plugin = CarlaPlugin::newDSSI(initializer);
  585. break;
  586. case PLUGIN_LV2:
  587. plugin = CarlaPlugin::newLV2(initializer);
  588. break;
  589. case PLUGIN_VST2:
  590. plugin = CarlaPlugin::newVST2(initializer);
  591. break;
  592. case PLUGIN_VST3:
  593. plugin = CarlaPlugin::newVST3(initializer);
  594. break;
  595. case PLUGIN_CLAP:
  596. plugin = CarlaPlugin::newCLAP(initializer);
  597. break;
  598. case PLUGIN_AU:
  599. plugin = CarlaPlugin::newAU(initializer);
  600. break;
  601. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  602. case PLUGIN_INTERNAL:
  603. plugin = CarlaPlugin::newNative(initializer);
  604. break;
  605. case PLUGIN_DLS:
  606. case PLUGIN_GIG:
  607. case PLUGIN_SF2:
  608. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  609. plugin = CarlaPlugin::newFluidSynth(initializer, ptype, use16Outs);
  610. break;
  611. case PLUGIN_SFZ:
  612. #ifdef SFZ_FILES_USING_SFIZZ
  613. {
  614. CarlaPlugin::Initializer sfizzInitializer = {
  615. this,
  616. id,
  617. name,
  618. "",
  619. "http://sfztools.github.io/sfizz",
  620. 0,
  621. options
  622. };
  623. plugin = CarlaPlugin::newLV2(sfizzInitializer);
  624. }
  625. #else
  626. plugin = CarlaPlugin::newSFZero(initializer);
  627. #endif
  628. break;
  629. case PLUGIN_JSFX:
  630. plugin = CarlaPlugin::newJSFX(initializer);
  631. break;
  632. case PLUGIN_JACK:
  633. #ifdef HAVE_JACK
  634. plugin = CarlaPlugin::newJackApp(initializer);
  635. #else
  636. setLastError("JACK plugin target is not available");
  637. #endif
  638. break;
  639. #else
  640. case PLUGIN_INTERNAL:
  641. case PLUGIN_DLS:
  642. case PLUGIN_GIG:
  643. case PLUGIN_SF2:
  644. case PLUGIN_SFZ:
  645. case PLUGIN_JACK:
  646. case PLUGIN_JSFX:
  647. setLastError("Plugin bridges cannot handle this binary");
  648. break;
  649. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  650. }
  651. }
  652. #endif // CARLA_PLUGIN_ONLY_BRIDGE
  653. if (plugin.get() == nullptr)
  654. return false;
  655. plugin->reload();
  656. #ifdef SFZ_FILES_USING_SFIZZ
  657. if (ptype == PLUGIN_SFZ && plugin->getType() == PLUGIN_LV2)
  658. {
  659. plugin->setCustomData(LV2_ATOM__Path,
  660. "http://sfztools.github.io/sfizz:sfzfile",
  661. filename,
  662. false);
  663. plugin->restoreLV2State(true);
  664. }
  665. #endif
  666. bool canRun = true;
  667. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  668. {
  669. /**/ if (plugin->getMidiInCount() > 1 || plugin->getMidiOutCount() > 1)
  670. {
  671. setLastError("Carla's patchbay mode cannot work with plugins that have multiple MIDI ports, sorry!");
  672. canRun = false;
  673. }
  674. }
  675. if (! canRun)
  676. {
  677. return false;
  678. }
  679. EnginePluginData& pluginData(pData->plugins[id]);
  680. pluginData.plugin = plugin;
  681. carla_zeroFloats(pluginData.peaks, 4);
  682. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  683. if (oldPlugin.get() != nullptr)
  684. {
  685. CARLA_SAFE_ASSERT(! pData->loadingProject);
  686. const ScopedRunnerStopper srs(this);
  687. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  688. pData->graph.replacePlugin(oldPlugin, plugin);
  689. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  690. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  691. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  692. oldPlugin->prepareForDeletion();
  693. {
  694. const CarlaMutexLocker cml(pData->pluginsToDeleteMutex);
  695. pData->pluginsToDelete.push_back(oldPlugin);
  696. }
  697. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  698. plugin->setDryWet(oldDryWet, true, true);
  699. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  700. plugin->setVolume(oldVolume, true, true);
  701. plugin->setActive(wasActive, true, true);
  702. plugin->setEnabled(true);
  703. callback(true, true, ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0, 0.0f, nullptr);
  704. }
  705. else if (! pData->loadingProject)
  706. #endif
  707. {
  708. plugin->setEnabled(true);
  709. ++pData->curPluginCount;
  710. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, id, plugin->getType(), 0, 0, 0.0f, plugin->getName());
  711. if (getType() != kEngineTypeBridge)
  712. plugin->setActive(true, true, true);
  713. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  714. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  715. pData->graph.addPlugin(plugin);
  716. #endif
  717. }
  718. return true;
  719. #if defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) || defined(CARLA_PLUGIN_ONLY_BRIDGE)
  720. // unused
  721. (void)extra;
  722. #endif
  723. }
  724. bool CarlaEngine::addPlugin(const PluginType ptype,
  725. const char* const filename,
  726. const char* const name,
  727. const char* const label,
  728. const int64_t uniqueId,
  729. const void* const extra)
  730. {
  731. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra, PLUGIN_OPTIONS_NULL);
  732. }
  733. bool CarlaEngine::removePlugin(const uint id)
  734. {
  735. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  736. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  737. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  738. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  739. #else
  740. CARLA_SAFE_ASSERT_RETURN_ERR(id == 0, "Invalid engine internal data");
  741. #endif
  742. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  743. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  744. carla_debug("CarlaEngine::removePlugin(%i)", id);
  745. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  746. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to remove");
  747. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  748. const ScopedRunnerStopper srs(this);
  749. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  750. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  751. pData->graph.removePlugin(plugin);
  752. const ScopedActionLock sal(this, kEnginePostActionRemovePlugin, id, 0);
  753. /*
  754. for (uint i=id; i < pData->curPluginCount; ++i)
  755. {
  756. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  757. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  758. plugin2->updateOscURL();
  759. }
  760. */
  761. #else
  762. pData->curPluginCount = 0;
  763. pData->plugins[0].plugin.reset();
  764. carla_zeroStruct(pData->plugins[0].peaks);
  765. #endif
  766. plugin->prepareForDeletion();
  767. {
  768. const CarlaMutexLocker cml(pData->pluginsToDeleteMutex);
  769. pData->pluginsToDelete.push_back(plugin);
  770. }
  771. callback(true, true, ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0, 0.0f, nullptr);
  772. return true;
  773. }
  774. bool CarlaEngine::removeAllPlugins()
  775. {
  776. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  777. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  778. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  779. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  780. #endif
  781. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  782. carla_debug("CarlaEngine::removeAllPlugins()");
  783. if (pData->curPluginCount == 0)
  784. return true;
  785. const ScopedRunnerStopper srs(this);
  786. const uint curPluginCount = pData->curPluginCount;
  787. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  788. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  789. pData->graph.removeAllPlugins(pData->aboutToClose);
  790. #endif
  791. const ScopedActionLock sal(this, kEnginePostActionZeroCount, 0, 0);
  792. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  793. for (uint i=0; i < curPluginCount; ++i)
  794. {
  795. const uint id = curPluginCount - i - 1;
  796. EnginePluginData& pluginData(pData->plugins[id]);
  797. pluginData.plugin->prepareForDeletion();
  798. {
  799. const CarlaMutexLocker cml(pData->pluginsToDeleteMutex);
  800. pData->pluginsToDelete.push_back(pluginData.plugin);
  801. }
  802. pluginData.plugin.reset();
  803. carla_zeroStruct(pluginData.peaks);
  804. callback(true, true, ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0, 0.0f, nullptr);
  805. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  806. }
  807. return true;
  808. }
  809. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  810. bool CarlaEngine::renamePlugin(const uint id, const char* const newName)
  811. {
  812. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  813. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  814. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  815. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  816. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  817. CARLA_SAFE_ASSERT_RETURN_ERR(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  818. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  819. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  820. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to rename");
  821. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  822. const char* const uniqueName(getUniquePluginName(newName));
  823. CARLA_SAFE_ASSERT_RETURN_ERR(uniqueName != nullptr, "Unable to get new unique plugin name");
  824. plugin->setName(uniqueName);
  825. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  826. pData->graph.renamePlugin(plugin, uniqueName);
  827. callback(true, true, ENGINE_CALLBACK_PLUGIN_RENAMED, id, 0, 0, 0, 0.0f, uniqueName);
  828. delete[] uniqueName;
  829. return true;
  830. }
  831. bool CarlaEngine::clonePlugin(const uint id)
  832. {
  833. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  834. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  835. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  836. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  837. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  838. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  839. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  840. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to clone");
  841. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  842. char label[STR_MAX+1];
  843. carla_zeroChars(label, STR_MAX+1);
  844. if (! plugin->getLabel(label))
  845. label[0] = '\0';
  846. const uint pluginCountBefore(pData->curPluginCount);
  847. if (! addPlugin(plugin->getBinaryType(), plugin->getType(),
  848. plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(),
  849. plugin->getExtraStuff(), plugin->getOptionsEnabled()))
  850. return false;
  851. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  852. if (const CarlaPluginPtr newPlugin = pData->plugins[pluginCountBefore].plugin)
  853. {
  854. if (newPlugin->getType() == PLUGIN_LV2)
  855. newPlugin->cloneLV2Files(*plugin);
  856. newPlugin->loadStateSave(plugin->getStateSave(true));
  857. }
  858. return true;
  859. }
  860. bool CarlaEngine::replacePlugin(const uint id) noexcept
  861. {
  862. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  863. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  864. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  865. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  866. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  867. // might use this to reset
  868. if (id == pData->maxPluginNumber)
  869. {
  870. pData->nextPluginId = pData->maxPluginNumber;
  871. return true;
  872. }
  873. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  874. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  875. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to replace");
  876. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  877. pData->nextPluginId = id;
  878. return true;
  879. }
  880. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  881. {
  882. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  883. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  884. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  885. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  886. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  887. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  888. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  889. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  890. const CarlaPluginPtr pluginA = pData->plugins[idA].plugin;
  891. const CarlaPluginPtr pluginB = pData->plugins[idB].plugin;
  892. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA.get() != nullptr, "Could not find plugin to switch");
  893. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB.get() != nullptr, "Could not find plugin to switch");
  894. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  895. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  896. const ScopedRunnerStopper srs(this);
  897. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  898. pData->graph.switchPlugins(pluginA, pluginB);
  899. const ScopedActionLock sal(this, kEnginePostActionSwitchPlugins, idA, idB);
  900. // TODO
  901. /*
  902. pluginA->updateOscURL();
  903. pluginB->updateOscURL();
  904. if (isOscControlRegistered())
  905. oscSend_control_switch_plugins(idA, idB);
  906. */
  907. return true;
  908. }
  909. #endif
  910. void CarlaEngine::touchPluginParameter(const uint, const uint32_t, const bool) noexcept
  911. {
  912. }
  913. CarlaPluginPtr CarlaEngine::getPlugin(const uint id) const noexcept
  914. {
  915. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  916. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  917. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  918. #endif
  919. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  920. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  921. return pData->plugins[id].plugin;
  922. }
  923. CarlaPluginPtr CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  924. {
  925. return pData->plugins[id].plugin;
  926. }
  927. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  928. {
  929. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  930. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  931. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  932. CarlaString sname;
  933. sname = name;
  934. if (sname.isEmpty())
  935. {
  936. sname = "(No name)";
  937. return sname.dup();
  938. }
  939. const std::size_t maxNameSize(carla_minConstrained<uint>(getMaxClientNameSize(), 0xff, 6U) - 6); // 6 = strlen(" (10)") + 1
  940. if (maxNameSize == 0 || ! isRunning())
  941. return sname.dup();
  942. sname.truncate(maxNameSize);
  943. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  944. sname.replace('/', '.'); // '/' is used by us for client name prefix
  945. for (uint i=0; i < pData->curPluginCount; ++i)
  946. {
  947. const CarlaPluginPtr plugin = pData->plugins[i].plugin;
  948. CARLA_SAFE_ASSERT_BREAK(plugin.use_count() > 0);
  949. // Check if unique name doesn't exist
  950. if (const char* const pluginName = plugin->getName())
  951. {
  952. if (sname != pluginName)
  953. continue;
  954. }
  955. // Check if string has already been modified
  956. {
  957. const std::size_t len(sname.length());
  958. // 1 digit, ex: " (2)"
  959. if (len > 4 && sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  960. {
  961. const int number = sname[len-2] - '0';
  962. if (number == 9)
  963. {
  964. // next number is 10, 2 digits
  965. sname.truncate(len-4);
  966. sname += " (10)";
  967. //sname.replace(" (9)", " (10)");
  968. }
  969. else
  970. sname[len-2] = char('0' + number + 1);
  971. continue;
  972. }
  973. // 2 digits, ex: " (11)"
  974. if (len > 5 && sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  975. {
  976. char n2 = sname[len-2];
  977. char n3 = sname[len-3];
  978. if (n2 == '9')
  979. {
  980. n2 = '0';
  981. n3 = static_cast<char>(n3 + 1);
  982. }
  983. else
  984. n2 = static_cast<char>(n2 + 1);
  985. sname[len-2] = n2;
  986. sname[len-3] = n3;
  987. continue;
  988. }
  989. }
  990. // Modify string if not
  991. sname += " (2)";
  992. }
  993. return sname.dup();
  994. }
  995. // -----------------------------------------------------------------------
  996. // Project management
  997. bool CarlaEngine::loadFile(const char* const filename)
  998. {
  999. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  1000. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1001. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  1002. const String jfilename = String(CharPointer_UTF8(filename));
  1003. File file(jfilename);
  1004. CARLA_SAFE_ASSERT_RETURN_ERR(file.exists(), "Requested file does not exist or is not a readable");
  1005. CarlaString baseName(file.getFileNameWithoutExtension().toRawUTF8());
  1006. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  1007. const uint curPluginId(pData->nextPluginId < pData->curPluginCount ? pData->nextPluginId : pData->curPluginCount);
  1008. // -------------------------------------------------------------------
  1009. // NOTE: please keep in sync with carla_get_supported_file_extensions!!
  1010. if (extension == "carxp" || extension == "carxs")
  1011. return loadProject(filename, false);
  1012. // -------------------------------------------------------------------
  1013. if (extension == "dls")
  1014. return addPlugin(PLUGIN_DLS, filename, baseName, baseName, 0, nullptr);
  1015. if (extension == "gig")
  1016. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  1017. if (extension == "sf2" || extension == "sf3")
  1018. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  1019. if (extension == "sfz")
  1020. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  1021. if (extension == "jsfx")
  1022. return addPlugin(PLUGIN_JSFX, filename, baseName, baseName, 0, nullptr);
  1023. // -------------------------------------------------------------------
  1024. if (
  1025. extension == "mp3" ||
  1026. #ifdef HAVE_SNDFILE
  1027. extension == "aif" ||
  1028. extension == "aifc" ||
  1029. extension == "aiff" ||
  1030. extension == "au" ||
  1031. extension == "bwf" ||
  1032. extension == "flac" ||
  1033. extension == "htk" ||
  1034. extension == "iff" ||
  1035. extension == "mat4" ||
  1036. extension == "mat5" ||
  1037. extension == "oga" ||
  1038. extension == "ogg" ||
  1039. extension == "opus" ||
  1040. extension == "paf" ||
  1041. extension == "pvf" ||
  1042. extension == "pvf5" ||
  1043. extension == "sd2" ||
  1044. extension == "sf" ||
  1045. extension == "snd" ||
  1046. extension == "svx" ||
  1047. extension == "vcc" ||
  1048. extension == "w64" ||
  1049. extension == "wav" ||
  1050. extension == "xi" ||
  1051. #endif
  1052. #ifdef HAVE_FFMPEG
  1053. extension == "3g2" ||
  1054. extension == "3gp" ||
  1055. extension == "aac" ||
  1056. extension == "ac3" ||
  1057. extension == "amr" ||
  1058. extension == "ape" ||
  1059. extension == "mp2" ||
  1060. extension == "mpc" ||
  1061. extension == "wma" ||
  1062. # ifndef HAVE_SNDFILE
  1063. // FFmpeg without sndfile
  1064. extension == "flac" ||
  1065. extension == "oga" ||
  1066. extension == "ogg" ||
  1067. extension == "w64" ||
  1068. extension == "wav" ||
  1069. # endif
  1070. #endif
  1071. false
  1072. )
  1073. {
  1074. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  1075. {
  1076. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  1077. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  1078. return true;
  1079. }
  1080. return false;
  1081. }
  1082. // -------------------------------------------------------------------
  1083. if (extension == "mid" || extension == "midi")
  1084. {
  1085. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  1086. {
  1087. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  1088. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  1089. return true;
  1090. }
  1091. return false;
  1092. }
  1093. // -------------------------------------------------------------------
  1094. // ZynAddSubFX
  1095. if (extension == "xmz" || extension == "xiz")
  1096. {
  1097. #ifdef HAVE_ZYN_DEPS
  1098. CarlaString nicerName("Zyn - ");
  1099. const std::size_t sep(baseName.find('-')+1);
  1100. if (sep < baseName.length())
  1101. nicerName += baseName.buffer()+sep;
  1102. else
  1103. nicerName += baseName;
  1104. if (addPlugin(PLUGIN_INTERNAL, nullptr, nicerName, "zynaddsubfx", 0, nullptr))
  1105. {
  1106. callback(true, true, ENGINE_CALLBACK_UI_STATE_CHANGED, curPluginId, 0, 0, 0, 0.0f, nullptr);
  1107. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  1108. {
  1109. const char* const ext = (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2";
  1110. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, ext, filename, true);
  1111. }
  1112. return true;
  1113. }
  1114. return false;
  1115. #else
  1116. setLastError("This Carla build does not have ZynAddSubFX support");
  1117. return false;
  1118. #endif
  1119. }
  1120. // -------------------------------------------------------------------
  1121. // Direct plugin binaries
  1122. #ifdef CARLA_OS_MAC
  1123. if (extension == "component")
  1124. return addPlugin(PLUGIN_AU, filename, nullptr, nullptr, 0, nullptr);
  1125. if (extension == "vst")
  1126. return addPlugin(PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  1127. #else
  1128. if (extension == "dll" || extension == "so")
  1129. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  1130. #endif
  1131. if (extension == "vst3")
  1132. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST3, filename, nullptr, nullptr, 0, nullptr);
  1133. if (extension == "clap")
  1134. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_CLAP, filename, nullptr, nullptr, 0, nullptr);
  1135. // -------------------------------------------------------------------
  1136. setLastError("Unknown file extension");
  1137. return false;
  1138. }
  1139. bool CarlaEngine::loadProject(const char* const filename, const bool setAsCurrentProject)
  1140. {
  1141. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  1142. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1143. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  1144. const String jfilename = String(CharPointer_UTF8(filename));
  1145. const File file(jfilename);
  1146. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  1147. if (setAsCurrentProject)
  1148. {
  1149. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1150. if (pData->currentProjectFilename != filename)
  1151. {
  1152. pData->currentProjectFilename = filename;
  1153. bool found;
  1154. const size_t r = pData->currentProjectFilename.rfind(CARLA_OS_SEP, &found);
  1155. if (found)
  1156. {
  1157. pData->currentProjectFolder = filename;
  1158. pData->currentProjectFolder[r] = '\0';
  1159. }
  1160. else
  1161. {
  1162. pData->currentProjectFolder.clear();
  1163. }
  1164. }
  1165. #endif
  1166. }
  1167. XmlDocument xml(file);
  1168. return loadProjectInternal(xml, !setAsCurrentProject);
  1169. }
  1170. bool CarlaEngine::saveProject(const char* const filename, const bool setAsCurrentProject)
  1171. {
  1172. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1173. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  1174. if (setAsCurrentProject)
  1175. {
  1176. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1177. if (pData->currentProjectFilename != filename)
  1178. {
  1179. pData->currentProjectFilename = filename;
  1180. bool found;
  1181. const size_t r = pData->currentProjectFilename.rfind(CARLA_OS_SEP, &found);
  1182. if (found)
  1183. {
  1184. pData->currentProjectFolder = filename;
  1185. pData->currentProjectFolder[r] = '\0';
  1186. }
  1187. else
  1188. {
  1189. pData->currentProjectFolder.clear();
  1190. }
  1191. }
  1192. #endif
  1193. }
  1194. MemoryOutputStream out;
  1195. saveProjectInternal(out);
  1196. const String jfilename = String(CharPointer_UTF8(filename));
  1197. File file(jfilename);
  1198. if (file.replaceWithData(out.getData(), out.getDataSize()))
  1199. return true;
  1200. setLastError("Failed to write file");
  1201. return false;
  1202. }
  1203. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1204. const char* CarlaEngine::getCurrentProjectFolder() const noexcept
  1205. {
  1206. return pData->currentProjectFolder.isNotEmpty() ? pData->currentProjectFolder.buffer()
  1207. : nullptr;
  1208. }
  1209. const char* CarlaEngine::getCurrentProjectFilename() const noexcept
  1210. {
  1211. return pData->currentProjectFilename;
  1212. }
  1213. void CarlaEngine::clearCurrentProjectFilename() noexcept
  1214. {
  1215. pData->currentProjectFilename.clear();
  1216. pData->currentProjectFolder.clear();
  1217. }
  1218. #endif
  1219. // -----------------------------------------------------------------------
  1220. // Information (base)
  1221. uint32_t CarlaEngine::getBufferSize() const noexcept
  1222. {
  1223. return pData->bufferSize;
  1224. }
  1225. double CarlaEngine::getSampleRate() const noexcept
  1226. {
  1227. return pData->sampleRate;
  1228. }
  1229. const char* CarlaEngine::getName() const noexcept
  1230. {
  1231. return pData->name;
  1232. }
  1233. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  1234. {
  1235. return pData->options.processMode;
  1236. }
  1237. const EngineOptions& CarlaEngine::getOptions() const noexcept
  1238. {
  1239. return pData->options;
  1240. }
  1241. EngineTimeInfo CarlaEngine::getTimeInfo() const noexcept
  1242. {
  1243. return pData->timeInfo;
  1244. }
  1245. // -----------------------------------------------------------------------
  1246. // Information (peaks)
  1247. const float* CarlaEngine::getPeaks(const uint pluginId) const noexcept
  1248. {
  1249. static const float kFallback[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
  1250. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1251. {
  1252. // get peak from first plugin, if available
  1253. if (const uint count = pData->curPluginCount)
  1254. {
  1255. pData->peaks[0] = pData->plugins[0].peaks[0];
  1256. pData->peaks[1] = pData->plugins[0].peaks[1];
  1257. pData->peaks[2] = pData->plugins[count-1].peaks[2];
  1258. pData->peaks[3] = pData->plugins[count-1].peaks[3];
  1259. }
  1260. else
  1261. {
  1262. carla_zeroFloats(pData->peaks, 4);
  1263. }
  1264. return pData->peaks;
  1265. }
  1266. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, kFallback);
  1267. return pData->plugins[pluginId].peaks;
  1268. }
  1269. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  1270. {
  1271. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1272. {
  1273. // get peak from first plugin, if available
  1274. if (pData->curPluginCount > 0)
  1275. return pData->plugins[0].peaks[isLeft ? 0 : 1];
  1276. return 0.0f;
  1277. }
  1278. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1279. return pData->plugins[pluginId].peaks[isLeft ? 0 : 1];
  1280. }
  1281. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  1282. {
  1283. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1284. {
  1285. // get peak from last plugin, if available
  1286. if (pData->curPluginCount > 0)
  1287. return pData->plugins[pData->curPluginCount-1].peaks[isLeft ? 2 : 3];
  1288. return 0.0f;
  1289. }
  1290. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1291. return pData->plugins[pluginId].peaks[isLeft ? 2 : 3];
  1292. }
  1293. // -----------------------------------------------------------------------
  1294. // Callback
  1295. void CarlaEngine::callback(const bool sendHost, const bool sendOSC,
  1296. const EngineCallbackOpcode action, const uint pluginId,
  1297. const int value1, const int value2, const int value3,
  1298. const float valuef, const char* const valueStr) noexcept
  1299. {
  1300. #ifdef DEBUG
  1301. if (pData->isIdling)
  1302. carla_stdout("CarlaEngine::callback [while idling] (%s, %s, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1303. bool2str(sendHost), bool2str(sendOSC),
  1304. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3,
  1305. static_cast<double>(valuef), valueStr);
  1306. else if (action != ENGINE_CALLBACK_IDLE && action != ENGINE_CALLBACK_NOTE_ON && action != ENGINE_CALLBACK_NOTE_OFF)
  1307. carla_debug("CarlaEngine::callback(%s, %s, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1308. bool2str(sendHost), bool2str(sendOSC),
  1309. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3,
  1310. static_cast<double>(valuef), valueStr);
  1311. #endif
  1312. if (sendHost && pData->callback != nullptr)
  1313. {
  1314. if (action == ENGINE_CALLBACK_IDLE)
  1315. ++pData->isIdling;
  1316. try {
  1317. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valuef, valueStr);
  1318. } CARLA_SAFE_EXCEPTION("callback")
  1319. if (action == ENGINE_CALLBACK_IDLE)
  1320. --pData->isIdling;
  1321. }
  1322. if (sendOSC)
  1323. {
  1324. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1325. if (pData->osc.isControlRegisteredForTCP())
  1326. {
  1327. switch (action)
  1328. {
  1329. case ENGINE_CALLBACK_RELOAD_INFO:
  1330. {
  1331. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1332. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1333. pData->osc.sendPluginInfo(plugin);
  1334. break;
  1335. }
  1336. case ENGINE_CALLBACK_RELOAD_PARAMETERS:
  1337. {
  1338. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1339. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1340. pData->osc.sendPluginPortCount(plugin);
  1341. if (const uint32_t count = plugin->getParameterCount())
  1342. {
  1343. for (uint32_t i=0; i<count; ++i)
  1344. pData->osc.sendPluginParameterInfo(plugin, i);
  1345. }
  1346. break;
  1347. }
  1348. case ENGINE_CALLBACK_RELOAD_PROGRAMS:
  1349. {
  1350. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1351. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1352. pData->osc.sendPluginProgramCount(plugin);
  1353. if (const uint32_t count = plugin->getProgramCount())
  1354. {
  1355. for (uint32_t i=0; i<count; ++i)
  1356. pData->osc.sendPluginProgram(plugin, i);
  1357. }
  1358. if (const uint32_t count = plugin->getMidiProgramCount())
  1359. {
  1360. for (uint32_t i=0; i<count; ++i)
  1361. pData->osc.sendPluginMidiProgram(plugin, i);
  1362. }
  1363. break;
  1364. }
  1365. case ENGINE_CALLBACK_PLUGIN_ADDED:
  1366. case ENGINE_CALLBACK_RELOAD_ALL:
  1367. {
  1368. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1369. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1370. pData->osc.sendPluginInfo(plugin);
  1371. pData->osc.sendPluginPortCount(plugin);
  1372. pData->osc.sendPluginDataCount(plugin);
  1373. if (const uint32_t count = plugin->getParameterCount())
  1374. {
  1375. for (uint32_t i=0; i<count; ++i)
  1376. pData->osc.sendPluginParameterInfo(plugin, i);
  1377. }
  1378. if (const uint32_t count = plugin->getProgramCount())
  1379. {
  1380. for (uint32_t i=0; i<count; ++i)
  1381. pData->osc.sendPluginProgram(plugin, i);
  1382. }
  1383. if (const uint32_t count = plugin->getMidiProgramCount())
  1384. {
  1385. for (uint32_t i=0; i<count; ++i)
  1386. pData->osc.sendPluginMidiProgram(plugin, i);
  1387. }
  1388. if (const uint32_t count = plugin->getCustomDataCount())
  1389. {
  1390. for (uint32_t i=0; i<count; ++i)
  1391. pData->osc.sendPluginCustomData(plugin, i);
  1392. }
  1393. pData->osc.sendPluginInternalParameterValues(plugin);
  1394. break;
  1395. }
  1396. case ENGINE_CALLBACK_IDLE:
  1397. return;
  1398. default:
  1399. break;
  1400. }
  1401. pData->osc.sendCallback(action, pluginId, value1, value2, value3, valuef, valueStr);
  1402. }
  1403. #endif
  1404. }
  1405. }
  1406. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1407. {
  1408. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1409. pData->callback = func;
  1410. pData->callbackPtr = ptr;
  1411. }
  1412. // -----------------------------------------------------------------------
  1413. // File Callback
  1414. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1415. {
  1416. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1417. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1418. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1419. const char* ret = nullptr;
  1420. if (pData->fileCallback != nullptr)
  1421. {
  1422. try {
  1423. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1424. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1425. }
  1426. return ret;
  1427. }
  1428. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1429. {
  1430. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1431. pData->fileCallback = func;
  1432. pData->fileCallbackPtr = ptr;
  1433. }
  1434. // -----------------------------------------------------------------------
  1435. // Transport
  1436. void CarlaEngine::transportPlay() noexcept
  1437. {
  1438. pData->timeInfo.playing = true;
  1439. pData->time.setNeedsReset();
  1440. }
  1441. void CarlaEngine::transportPause() noexcept
  1442. {
  1443. if (pData->timeInfo.playing)
  1444. pData->time.pause();
  1445. else
  1446. pData->time.setNeedsReset();
  1447. }
  1448. void CarlaEngine::transportBPM(const double bpm) noexcept
  1449. {
  1450. CARLA_SAFE_ASSERT_RETURN(bpm >= 20.0,)
  1451. try {
  1452. pData->time.setBPM(bpm);
  1453. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1454. }
  1455. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1456. {
  1457. pData->time.relocate(frame);
  1458. }
  1459. // -----------------------------------------------------------------------
  1460. // Error handling
  1461. const char* CarlaEngine::getLastError() const noexcept
  1462. {
  1463. return pData->lastError;
  1464. }
  1465. void CarlaEngine::setLastError(const char* const error) const noexcept
  1466. {
  1467. pData->lastError = error;
  1468. }
  1469. // -----------------------------------------------------------------------
  1470. // Misc
  1471. bool CarlaEngine::isAboutToClose() const noexcept
  1472. {
  1473. return pData->aboutToClose;
  1474. }
  1475. bool CarlaEngine::setAboutToClose() noexcept
  1476. {
  1477. carla_debug("CarlaEngine::setAboutToClose()");
  1478. pData->aboutToClose = true;
  1479. return (pData->isIdling == 0);
  1480. }
  1481. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1482. bool CarlaEngine::isLoadingProject() const noexcept
  1483. {
  1484. return pData->loadingProject;
  1485. }
  1486. #endif
  1487. void CarlaEngine::setActionCanceled(const bool canceled) noexcept
  1488. {
  1489. pData->actionCanceled = canceled;
  1490. }
  1491. bool CarlaEngine::wasActionCanceled() const noexcept
  1492. {
  1493. return pData->actionCanceled;
  1494. }
  1495. // -----------------------------------------------------------------------
  1496. // Global options
  1497. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1498. {
  1499. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1500. if (isRunning())
  1501. {
  1502. switch (option)
  1503. {
  1504. case ENGINE_OPTION_PROCESS_MODE:
  1505. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1506. case ENGINE_OPTION_AUDIO_DRIVER:
  1507. case ENGINE_OPTION_AUDIO_DEVICE:
  1508. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!",
  1509. option, EngineOption2Str(option), value, valueStr);
  1510. default:
  1511. break;
  1512. }
  1513. }
  1514. // do not un-force stereo for rack mode
  1515. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1516. return;
  1517. switch (option)
  1518. {
  1519. case ENGINE_OPTION_DEBUG:
  1520. break;
  1521. case ENGINE_OPTION_PROCESS_MODE:
  1522. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1523. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1524. break;
  1525. case ENGINE_OPTION_TRANSPORT_MODE:
  1526. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1527. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1528. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1529. delete[] pData->options.transportExtra;
  1530. if (value >= ENGINE_TRANSPORT_MODE_DISABLED && valueStr != nullptr)
  1531. pData->options.transportExtra = carla_strdup_safe(valueStr);
  1532. else
  1533. pData->options.transportExtra = nullptr;
  1534. pData->time.setNeedsReset();
  1535. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1536. // enable link now if needed
  1537. {
  1538. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1539. pData->time.enableLink(linkEnabled);
  1540. }
  1541. #endif
  1542. break;
  1543. case ENGINE_OPTION_FORCE_STEREO:
  1544. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1545. pData->options.forceStereo = (value != 0);
  1546. break;
  1547. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1548. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1549. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1550. #else
  1551. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1552. #endif
  1553. pData->options.preferPluginBridges = (value != 0);
  1554. break;
  1555. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1556. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1557. pData->options.preferUiBridges = (value != 0);
  1558. break;
  1559. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1560. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1561. pData->options.uisAlwaysOnTop = (value != 0);
  1562. break;
  1563. case ENGINE_OPTION_MAX_PARAMETERS:
  1564. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1565. pData->options.maxParameters = static_cast<uint>(value);
  1566. break;
  1567. case ENGINE_OPTION_RESET_XRUNS:
  1568. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1569. pData->options.resetXruns = (value != 0);
  1570. break;
  1571. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1572. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1573. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1574. break;
  1575. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1576. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1577. pData->options.audioBufferSize = static_cast<uint>(value);
  1578. break;
  1579. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1580. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1581. pData->options.audioSampleRate = static_cast<uint>(value);
  1582. break;
  1583. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1584. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1585. pData->options.audioTripleBuffer = (value != 0);
  1586. break;
  1587. case ENGINE_OPTION_AUDIO_DRIVER:
  1588. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1589. if (pData->options.audioDriver != nullptr)
  1590. delete[] pData->options.audioDriver;
  1591. pData->options.audioDriver = carla_strdup_safe(valueStr);
  1592. break;
  1593. case ENGINE_OPTION_AUDIO_DEVICE:
  1594. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1595. if (pData->options.audioDevice != nullptr)
  1596. delete[] pData->options.audioDevice;
  1597. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1598. break;
  1599. #ifndef BUILD_BRIDGE
  1600. case ENGINE_OPTION_OSC_ENABLED:
  1601. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1602. pData->options.oscEnabled = (value != 0);
  1603. break;
  1604. case ENGINE_OPTION_OSC_PORT_TCP:
  1605. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1606. pData->options.oscPortTCP = value;
  1607. break;
  1608. case ENGINE_OPTION_OSC_PORT_UDP:
  1609. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1610. pData->options.oscPortUDP = value;
  1611. break;
  1612. #endif
  1613. case ENGINE_OPTION_FILE_PATH:
  1614. CARLA_SAFE_ASSERT_RETURN(value > FILE_NONE,);
  1615. CARLA_SAFE_ASSERT_RETURN(value <= FILE_MIDI,);
  1616. switch (value)
  1617. {
  1618. case FILE_AUDIO:
  1619. if (pData->options.pathAudio != nullptr)
  1620. delete[] pData->options.pathAudio;
  1621. if (valueStr != nullptr)
  1622. pData->options.pathAudio = carla_strdup_safe(valueStr);
  1623. else
  1624. pData->options.pathAudio = nullptr;
  1625. break;
  1626. case FILE_MIDI:
  1627. if (pData->options.pathMIDI != nullptr)
  1628. delete[] pData->options.pathMIDI;
  1629. if (valueStr != nullptr)
  1630. pData->options.pathMIDI = carla_strdup_safe(valueStr);
  1631. else
  1632. pData->options.pathMIDI = nullptr;
  1633. break;
  1634. default:
  1635. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid file type",
  1636. option, EngineOption2Str(option), value, valueStr);
  1637. break;
  1638. }
  1639. break;
  1640. case ENGINE_OPTION_PLUGIN_PATH:
  1641. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1642. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_TYPE_COUNT,);
  1643. switch (value)
  1644. {
  1645. case PLUGIN_LADSPA:
  1646. if (pData->options.pathLADSPA != nullptr)
  1647. delete[] pData->options.pathLADSPA;
  1648. if (valueStr != nullptr)
  1649. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1650. else
  1651. pData->options.pathLADSPA = nullptr;
  1652. break;
  1653. case PLUGIN_DSSI:
  1654. if (pData->options.pathDSSI != nullptr)
  1655. delete[] pData->options.pathDSSI;
  1656. if (valueStr != nullptr)
  1657. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1658. else
  1659. pData->options.pathDSSI = nullptr;
  1660. break;
  1661. case PLUGIN_LV2:
  1662. if (pData->options.pathLV2 != nullptr)
  1663. delete[] pData->options.pathLV2;
  1664. if (valueStr != nullptr)
  1665. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1666. else
  1667. pData->options.pathLV2 = nullptr;
  1668. break;
  1669. case PLUGIN_VST2:
  1670. if (pData->options.pathVST2 != nullptr)
  1671. delete[] pData->options.pathVST2;
  1672. if (valueStr != nullptr)
  1673. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1674. else
  1675. pData->options.pathVST2 = nullptr;
  1676. break;
  1677. case PLUGIN_VST3:
  1678. if (pData->options.pathVST3 != nullptr)
  1679. delete[] pData->options.pathVST3;
  1680. if (valueStr != nullptr)
  1681. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1682. else
  1683. pData->options.pathVST3 = nullptr;
  1684. break;
  1685. case PLUGIN_SF2:
  1686. if (pData->options.pathSF2 != nullptr)
  1687. delete[] pData->options.pathSF2;
  1688. if (valueStr != nullptr)
  1689. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1690. else
  1691. pData->options.pathSF2 = nullptr;
  1692. break;
  1693. case PLUGIN_SFZ:
  1694. if (pData->options.pathSFZ != nullptr)
  1695. delete[] pData->options.pathSFZ;
  1696. if (valueStr != nullptr)
  1697. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1698. else
  1699. pData->options.pathSFZ = nullptr;
  1700. break;
  1701. case PLUGIN_JSFX:
  1702. if (pData->options.pathJSFX != nullptr)
  1703. delete[] pData->options.pathJSFX;
  1704. if (valueStr != nullptr)
  1705. pData->options.pathJSFX = carla_strdup_safe(valueStr);
  1706. else
  1707. pData->options.pathJSFX = nullptr;
  1708. break;
  1709. case PLUGIN_CLAP:
  1710. if (pData->options.pathCLAP != nullptr)
  1711. delete[] pData->options.pathCLAP;
  1712. if (valueStr != nullptr)
  1713. pData->options.pathCLAP = carla_strdup_safe(valueStr);
  1714. else
  1715. pData->options.pathCLAP = nullptr;
  1716. break;
  1717. default:
  1718. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type",
  1719. option, EngineOption2Str(option), value, valueStr);
  1720. break;
  1721. }
  1722. break;
  1723. case ENGINE_OPTION_PATH_BINARIES:
  1724. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1725. if (pData->options.binaryDir != nullptr)
  1726. delete[] pData->options.binaryDir;
  1727. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1728. break;
  1729. case ENGINE_OPTION_PATH_RESOURCES:
  1730. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1731. if (pData->options.resourceDir != nullptr)
  1732. delete[] pData->options.resourceDir;
  1733. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1734. break;
  1735. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1736. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1737. #ifdef CARLA_OS_LINUX
  1738. const ScopedEngineEnvironmentLocker _seel(this);
  1739. if (value != 0)
  1740. {
  1741. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1742. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1743. }
  1744. else
  1745. {
  1746. ::unsetenv("LD_PRELOAD");
  1747. }
  1748. #endif
  1749. } break;
  1750. case ENGINE_OPTION_FRONTEND_BACKGROUND_COLOR:
  1751. pData->options.bgColor = static_cast<uint>(value);
  1752. break;
  1753. case ENGINE_OPTION_FRONTEND_FOREGROUND_COLOR:
  1754. pData->options.fgColor = static_cast<uint>(value);
  1755. break;
  1756. case ENGINE_OPTION_FRONTEND_UI_SCALE:
  1757. CARLA_SAFE_ASSERT_RETURN(value > 0,);
  1758. pData->options.uiScale = static_cast<float>(value) / 1000;
  1759. break;
  1760. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1761. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1762. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1763. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1764. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1765. } break;
  1766. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1767. case ENGINE_OPTION_WINE_EXECUTABLE:
  1768. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1769. if (pData->options.wine.executable != nullptr)
  1770. delete[] pData->options.wine.executable;
  1771. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1772. break;
  1773. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1774. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1775. pData->options.wine.autoPrefix = (value != 0);
  1776. break;
  1777. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1778. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1779. if (pData->options.wine.fallbackPrefix != nullptr)
  1780. delete[] pData->options.wine.fallbackPrefix;
  1781. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1782. break;
  1783. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1784. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1785. pData->options.wine.rtPrio = (value != 0);
  1786. break;
  1787. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1788. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1789. pData->options.wine.baseRtPrio = value;
  1790. break;
  1791. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1792. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1793. pData->options.wine.serverRtPrio = value;
  1794. break;
  1795. #endif
  1796. #ifndef BUILD_BRIDGE
  1797. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1798. break;
  1799. #endif
  1800. case ENGINE_OPTION_CLIENT_NAME_PREFIX:
  1801. if (pData->options.clientNamePrefix != nullptr)
  1802. delete[] pData->options.clientNamePrefix;
  1803. pData->options.clientNamePrefix = valueStr != nullptr && valueStr[0] != '\0'
  1804. ? carla_strdup_safe(valueStr)
  1805. : nullptr;
  1806. break;
  1807. case ENGINE_OPTION_PLUGINS_ARE_STANDALONE:
  1808. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1809. pData->options.pluginsAreStandalone = (value != 0);
  1810. break;
  1811. }
  1812. }
  1813. #ifndef BUILD_BRIDGE
  1814. // -----------------------------------------------------------------------
  1815. // OSC Stuff
  1816. bool CarlaEngine::isOscControlRegistered() const noexcept
  1817. {
  1818. # ifdef HAVE_LIBLO
  1819. return pData->osc.isControlRegisteredForTCP();
  1820. # else
  1821. return false;
  1822. # endif
  1823. }
  1824. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1825. {
  1826. # ifdef HAVE_LIBLO
  1827. return pData->osc.getServerPathTCP();
  1828. # else
  1829. return nullptr;
  1830. # endif
  1831. }
  1832. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1833. {
  1834. # ifdef HAVE_LIBLO
  1835. return pData->osc.getServerPathUDP();
  1836. # else
  1837. return nullptr;
  1838. # endif
  1839. }
  1840. #endif
  1841. // -----------------------------------------------------------------------
  1842. // Internal stuff
  1843. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1844. {
  1845. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1846. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1847. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1848. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1849. {
  1850. pData->graph.setBufferSize(newBufferSize);
  1851. }
  1852. #endif
  1853. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1854. for (uint i=0; i < pData->curPluginCount; ++i)
  1855. {
  1856. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1857. {
  1858. if (plugin->isEnabled() && plugin->tryLock(true))
  1859. {
  1860. plugin->bufferSizeChanged(newBufferSize);
  1861. plugin->unlock();
  1862. }
  1863. }
  1864. }
  1865. callback(true, true, ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0, 0.0f, nullptr);
  1866. }
  1867. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1868. {
  1869. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1870. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1871. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1872. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1873. {
  1874. pData->graph.setSampleRate(newSampleRate);
  1875. }
  1876. #endif
  1877. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1878. for (uint i=0; i < pData->curPluginCount; ++i)
  1879. {
  1880. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1881. {
  1882. if (plugin->isEnabled() && plugin->tryLock(true))
  1883. {
  1884. plugin->sampleRateChanged(newSampleRate);
  1885. plugin->unlock();
  1886. }
  1887. }
  1888. }
  1889. callback(true, true, ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1890. }
  1891. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1892. {
  1893. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1894. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1895. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1896. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1897. {
  1898. pData->graph.setOffline(isOfflineNow);
  1899. }
  1900. #endif
  1901. for (uint i=0; i < pData->curPluginCount; ++i)
  1902. {
  1903. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1904. if (plugin->isEnabled())
  1905. plugin->offlineModeChanged(isOfflineNow);
  1906. }
  1907. }
  1908. void CarlaEngine::setPluginPeaksRT(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1909. {
  1910. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1911. pluginData.peaks[0] = inPeaks[0];
  1912. pluginData.peaks[1] = inPeaks[1];
  1913. pluginData.peaks[2] = outPeaks[0];
  1914. pluginData.peaks[3] = outPeaks[1];
  1915. }
  1916. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1917. {
  1918. // send initial prepareForSave first, giving time for bridges to act
  1919. for (uint i=0; i < pData->curPluginCount; ++i)
  1920. {
  1921. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1922. {
  1923. if (plugin->isEnabled())
  1924. {
  1925. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1926. // deactivate bridge client-side ping check, since some plugins block during save
  1927. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1928. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1929. #endif
  1930. plugin->prepareForSave(false);
  1931. }
  1932. }
  1933. }
  1934. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1935. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1936. outStream << "<CARLA-PROJECT VERSION='" CARLA_VERSION_STRMIN "'";
  1937. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1938. if (pData->ignoreClientPrefix)
  1939. outStream << " IgnoreClientPrefix='true'";
  1940. #endif
  1941. outStream << ">\n";
  1942. const bool isPlugin(getType() == kEngineTypePlugin);
  1943. const EngineOptions& options(pData->options);
  1944. {
  1945. MemoryOutputStream outSettings(1024);
  1946. outSettings << " <EngineSettings>\n";
  1947. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1948. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1949. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1950. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1951. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1952. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1953. if (isPlugin)
  1954. {
  1955. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1956. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1957. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1958. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1959. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1960. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1961. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1962. outSettings << " <JSFX_PATH>" << xmlSafeString(options.pathJSFX, true) << "</JSFX_PATH>\n";
  1963. outSettings << " <CLAP_PATH>" << xmlSafeString(options.pathCLAP, true) << "</CLAP_PATH>\n";
  1964. }
  1965. outSettings << " </EngineSettings>\n";
  1966. outStream << outSettings;
  1967. }
  1968. if (pData->timeInfo.bbt.valid && ! isPlugin)
  1969. {
  1970. MemoryOutputStream outTransport(128);
  1971. outTransport << "\n <Transport>\n";
  1972. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  1973. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  1974. outTransport << " </Transport>\n";
  1975. outStream << outTransport;
  1976. }
  1977. char strBuf[STR_MAX+1];
  1978. carla_zeroChars(strBuf, STR_MAX+1);
  1979. for (uint i=0; i < pData->curPluginCount; ++i)
  1980. {
  1981. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1982. {
  1983. if (plugin->isEnabled())
  1984. {
  1985. MemoryOutputStream outPlugin(4096), streamPlugin;
  1986. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1987. outPlugin << "\n";
  1988. if (plugin->getRealName(strBuf))
  1989. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1990. outPlugin << " <Plugin>\n";
  1991. outPlugin << streamPlugin;
  1992. outPlugin << " </Plugin>\n";
  1993. outStream << outPlugin;
  1994. }
  1995. }
  1996. }
  1997. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1998. // tell bridges we're done saving
  1999. for (uint i=0; i < pData->curPluginCount; ++i)
  2000. {
  2001. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2002. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2003. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2004. }
  2005. // save internal connections
  2006. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2007. {
  2008. uint posCount = 0;
  2009. const char* const* const patchbayConns = getPatchbayConnections(false);
  2010. const PatchbayPosition* const patchbayPos = getPatchbayPositions(false, posCount);
  2011. if (patchbayConns != nullptr || patchbayPos != nullptr)
  2012. {
  2013. MemoryOutputStream outPatchbay(2048);
  2014. outPatchbay << "\n <Patchbay>\n";
  2015. if (patchbayConns != nullptr)
  2016. {
  2017. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i)
  2018. {
  2019. const char* const connSource(patchbayConns[i]);
  2020. const char* const connTarget(patchbayConns[i+1]);
  2021. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  2022. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  2023. outPatchbay << " <Connection>\n";
  2024. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  2025. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  2026. outPatchbay << " </Connection>\n";
  2027. }
  2028. }
  2029. if (patchbayPos != nullptr && posCount != 0)
  2030. {
  2031. outPatchbay << " <Positions>\n";
  2032. for (uint i=0; i<posCount; ++i)
  2033. {
  2034. const PatchbayPosition& ppos(patchbayPos[i]);
  2035. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  2036. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  2037. if (ppos.x2 != 0 || ppos.y2 != 0)
  2038. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  2039. if (ppos.pluginId >= 0)
  2040. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  2041. outPatchbay << "\">\n";
  2042. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  2043. outPatchbay << " </Position>\n";
  2044. if (ppos.dealloc)
  2045. delete[] ppos.name;
  2046. }
  2047. outPatchbay << " </Positions>\n";
  2048. }
  2049. outPatchbay << " </Patchbay>\n";
  2050. outStream << outPatchbay;
  2051. delete[] patchbayPos;
  2052. }
  2053. }
  2054. // if we're running inside some session-manager (and using JACK), let them handle the connections
  2055. bool saveExternalConnections, saveExternalPositions = true;
  2056. /**/ if (isPlugin)
  2057. {
  2058. saveExternalConnections = false;
  2059. saveExternalPositions = false;
  2060. }
  2061. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2062. {
  2063. saveExternalConnections = true;
  2064. }
  2065. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2066. {
  2067. saveExternalConnections = false;
  2068. }
  2069. else
  2070. {
  2071. saveExternalConnections = true;
  2072. }
  2073. if (saveExternalConnections || saveExternalPositions)
  2074. {
  2075. uint posCount = 0;
  2076. const char* const* const patchbayConns = saveExternalConnections
  2077. ? getPatchbayConnections(true)
  2078. : nullptr;
  2079. const PatchbayPosition* const patchbayPos = saveExternalPositions
  2080. ? getPatchbayPositions(true, posCount)
  2081. : nullptr;
  2082. if (patchbayConns != nullptr || patchbayPos != nullptr)
  2083. {
  2084. MemoryOutputStream outPatchbay(2048);
  2085. outPatchbay << "\n <ExternalPatchbay>\n";
  2086. if (patchbayConns != nullptr)
  2087. {
  2088. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  2089. {
  2090. const char* const connSource(patchbayConns[i]);
  2091. const char* const connTarget(patchbayConns[i+1]);
  2092. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  2093. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  2094. outPatchbay << " <Connection>\n";
  2095. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  2096. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  2097. outPatchbay << " </Connection>\n";
  2098. }
  2099. }
  2100. if (patchbayPos != nullptr && posCount != 0)
  2101. {
  2102. outPatchbay << " <Positions>\n";
  2103. for (uint i=0; i<posCount; ++i)
  2104. {
  2105. const PatchbayPosition& ppos(patchbayPos[i]);
  2106. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  2107. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  2108. if (ppos.x2 != 0 || ppos.y2 != 0)
  2109. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  2110. if (ppos.pluginId >= 0)
  2111. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  2112. outPatchbay << "\">\n";
  2113. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  2114. outPatchbay << " </Position>\n";
  2115. if (ppos.dealloc)
  2116. delete[] ppos.name;
  2117. }
  2118. outPatchbay << " </Positions>\n";
  2119. }
  2120. outPatchbay << " </ExternalPatchbay>\n";
  2121. outStream << outPatchbay;
  2122. }
  2123. }
  2124. #endif
  2125. outStream << "</CARLA-PROJECT>\n";
  2126. }
  2127. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  2128. {
  2129. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  2130. // try direct filename first
  2131. String jbinary(binary);
  2132. // adjust for current platform
  2133. #ifdef CARLA_OS_WIN
  2134. if (jbinary[0] == '/')
  2135. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  2136. #else
  2137. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  2138. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  2139. #endif
  2140. String filename = File(jbinary).getFileName();
  2141. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  2142. if (filename.endsWithIgnoreCase(".vst3"))
  2143. searchFlags |= File::findDirectories;
  2144. #ifdef CARLA_OS_MAC
  2145. else if (filename.endsWithIgnoreCase(".vst"))
  2146. searchFlags |= File::findDirectories;
  2147. #endif
  2148. std::vector<File> results;
  2149. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2150. {
  2151. const File path(*it);
  2152. results.clear();
  2153. path.findChildFiles(results, searchFlags, true, filename);
  2154. if (!results.empty())
  2155. return results.front().getFullPathName();
  2156. }
  2157. // try changing extension
  2158. #if defined(CARLA_OS_MAC)
  2159. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  2160. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  2161. #elif defined(CARLA_OS_WIN)
  2162. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  2163. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  2164. #else
  2165. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  2166. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  2167. #endif
  2168. else
  2169. return String();
  2170. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2171. {
  2172. const File path(*it);
  2173. results.clear();
  2174. path.findChildFiles(results, searchFlags, true, filename);
  2175. if (!results.empty())
  2176. return results.front().getFullPathName();
  2177. }
  2178. return String();
  2179. }
  2180. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc, const bool alwaysLoadConnections)
  2181. {
  2182. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - START", &xmlDoc, bool2str(alwaysLoadConnections));
  2183. CarlaScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  2184. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  2185. const String& xmlType(xmlElement->getTagName());
  2186. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  2187. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  2188. {
  2189. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2190. setLastError("Not a valid Carla project or preset file");
  2191. return false;
  2192. }
  2193. pData->actionCanceled = false;
  2194. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 1, 0, 0, 0.0f, "Loading project");
  2195. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2196. if (pData->options.clientNamePrefix != nullptr)
  2197. {
  2198. if (carla_isEqual(xmlElement->getDoubleAttribute("VERSION", 0.0), 2.0) ||
  2199. xmlElement->getBoolAttribute("IgnoreClientPrefix", false))
  2200. {
  2201. carla_stdout("Loading project in compatibility mode, will ignore client name prefix");
  2202. pData->ignoreClientPrefix = true;
  2203. setOption(ENGINE_OPTION_CLIENT_NAME_PREFIX, 0, "");
  2204. }
  2205. }
  2206. const CarlaScopedValueSetter<bool> csvs(pData->loadingProject, true, false);
  2207. #endif
  2208. // completely load file
  2209. xmlElement = xmlDoc.getDocumentElement(false);
  2210. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  2211. if (pData->aboutToClose)
  2212. return true;
  2213. if (pData->actionCanceled)
  2214. {
  2215. setLastError("Project load canceled");
  2216. return false;
  2217. }
  2218. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2219. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2220. const bool isMultiClient = pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  2221. const bool isPatchbay = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY;
  2222. #endif
  2223. const bool isPlugin = getType() == kEngineTypePlugin;
  2224. // load engine settings first of all
  2225. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  2226. {
  2227. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  2228. {
  2229. const String& tag(settElem->getTagName());
  2230. const String text(settElem->getAllSubText().trim());
  2231. /** some settings might be incorrect or require extra work,
  2232. so we call setOption rather than modifying them direly */
  2233. int option = -1;
  2234. int value = 0;
  2235. const char* valueStr = nullptr;
  2236. /**/ if (tag == "ForceStereo")
  2237. {
  2238. option = ENGINE_OPTION_FORCE_STEREO;
  2239. value = text == "true" ? 1 : 0;
  2240. }
  2241. else if (tag == "PreferPluginBridges")
  2242. {
  2243. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  2244. value = text == "true" ? 1 : 0;
  2245. }
  2246. else if (tag == "PreferUiBridges")
  2247. {
  2248. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  2249. value = text == "true" ? 1 : 0;
  2250. }
  2251. else if (tag == "UIsAlwaysOnTop")
  2252. {
  2253. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  2254. value = text == "true" ? 1 : 0;
  2255. }
  2256. else if (tag == "MaxParameters")
  2257. {
  2258. option = ENGINE_OPTION_MAX_PARAMETERS;
  2259. value = text.getIntValue();
  2260. }
  2261. else if (tag == "UIBridgesTimeout")
  2262. {
  2263. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  2264. value = text.getIntValue();
  2265. }
  2266. else if (isPlugin)
  2267. {
  2268. /**/ if (tag == "LADSPA_PATH")
  2269. {
  2270. option = ENGINE_OPTION_PLUGIN_PATH;
  2271. value = PLUGIN_LADSPA;
  2272. valueStr = text.toRawUTF8();
  2273. }
  2274. else if (tag == "DSSI_PATH")
  2275. {
  2276. option = ENGINE_OPTION_PLUGIN_PATH;
  2277. value = PLUGIN_DSSI;
  2278. valueStr = text.toRawUTF8();
  2279. }
  2280. else if (tag == "LV2_PATH")
  2281. {
  2282. option = ENGINE_OPTION_PLUGIN_PATH;
  2283. value = PLUGIN_LV2;
  2284. valueStr = text.toRawUTF8();
  2285. }
  2286. else if (tag == "VST2_PATH")
  2287. {
  2288. option = ENGINE_OPTION_PLUGIN_PATH;
  2289. value = PLUGIN_VST2;
  2290. valueStr = text.toRawUTF8();
  2291. }
  2292. else if (tag.equalsIgnoreCase("VST3_PATH"))
  2293. {
  2294. option = ENGINE_OPTION_PLUGIN_PATH;
  2295. value = PLUGIN_VST3;
  2296. valueStr = text.toRawUTF8();
  2297. }
  2298. else if (tag == "SF2_PATH")
  2299. {
  2300. option = ENGINE_OPTION_PLUGIN_PATH;
  2301. value = PLUGIN_SF2;
  2302. valueStr = text.toRawUTF8();
  2303. }
  2304. else if (tag == "SFZ_PATH")
  2305. {
  2306. option = ENGINE_OPTION_PLUGIN_PATH;
  2307. value = PLUGIN_SFZ;
  2308. valueStr = text.toRawUTF8();
  2309. }
  2310. else if (tag == "JSFX_PATH")
  2311. {
  2312. option = ENGINE_OPTION_PLUGIN_PATH;
  2313. value = PLUGIN_JSFX;
  2314. valueStr = text.toRawUTF8();
  2315. }
  2316. else if (tag == "CLAP_PATH")
  2317. {
  2318. option = ENGINE_OPTION_PLUGIN_PATH;
  2319. value = PLUGIN_CLAP;
  2320. valueStr = text.toRawUTF8();
  2321. }
  2322. }
  2323. if (option == -1)
  2324. {
  2325. // check old stuff, unhandled now
  2326. if (tag == "GIG_PATH")
  2327. continue;
  2328. // ignored tags
  2329. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  2330. continue;
  2331. if (tag == "VST3_PATH" || tag == "AU_PATH")
  2332. continue;
  2333. if (tag == "SF2_PATH" || tag == "SFZ_PATH" || tag == "JSFX_PATH" || tag == "CLAP_PATH")
  2334. continue;
  2335. // hmm something is wrong..
  2336. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  2337. continue;
  2338. }
  2339. setOption(static_cast<EngineOption>(option), value, valueStr);
  2340. }
  2341. if (pData->aboutToClose)
  2342. return true;
  2343. if (pData->actionCanceled)
  2344. {
  2345. setLastError("Project load canceled");
  2346. return false;
  2347. }
  2348. }
  2349. // now setup transport
  2350. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  2351. {
  2352. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  2353. {
  2354. const String bpmText(bpmElem->getAllSubText().trim());
  2355. const double bpm = bpmText.getDoubleValue();
  2356. // some sane limits
  2357. if (bpm >= 20.0 && bpm < 400.0)
  2358. pData->time.setBPM(bpm);
  2359. if (pData->aboutToClose)
  2360. return true;
  2361. if (pData->actionCanceled)
  2362. {
  2363. setLastError("Project load canceled");
  2364. return false;
  2365. }
  2366. }
  2367. }
  2368. // and we handle plugins
  2369. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2370. {
  2371. const String& tagName(elem->getTagName());
  2372. if (isPreset || tagName == "Plugin")
  2373. {
  2374. CarlaStateSave stateSave;
  2375. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  2376. if (pData->aboutToClose)
  2377. return true;
  2378. if (pData->actionCanceled)
  2379. {
  2380. setLastError("Project load canceled");
  2381. return false;
  2382. }
  2383. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  2384. #if !(defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) || defined(CARLA_PLUGIN_ONLY_BRIDGE))
  2385. // compatibility code to load projects with GIG files
  2386. // FIXME Remove on 2.1 release
  2387. if (std::strcmp(stateSave.type, "GIG") == 0)
  2388. {
  2389. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  2390. {
  2391. const uint pluginId = pData->curPluginCount;
  2392. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2393. {
  2394. if (pData->aboutToClose)
  2395. return true;
  2396. if (pData->actionCanceled)
  2397. {
  2398. setLastError("Project load canceled");
  2399. return false;
  2400. }
  2401. String lsState;
  2402. lsState << "0.35\n";
  2403. lsState << "18 0 Chromatic\n";
  2404. lsState << "18 1 Drum Kits\n";
  2405. lsState << "20 0\n";
  2406. lsState << "0 1 " << stateSave.binary << "\n";
  2407. lsState << "0 0 0 0 1 0 GIG\n";
  2408. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  2409. plugin->restoreLV2State(true);
  2410. plugin->setDryWet(stateSave.dryWet, true, true);
  2411. plugin->setVolume(stateSave.volume, true, true);
  2412. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2413. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2414. plugin->setPanning(stateSave.panning, true, true);
  2415. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2416. plugin->setActive(stateSave.active, true, true);
  2417. plugin->setEnabled(true);
  2418. ++pData->curPluginCount;
  2419. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, plugin->getType(),
  2420. 0, 0, 0.0f,
  2421. plugin->getName());
  2422. if (isPatchbay)
  2423. pData->graph.addPlugin(plugin);
  2424. }
  2425. else
  2426. {
  2427. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2428. }
  2429. }
  2430. else
  2431. {
  2432. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  2433. }
  2434. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2435. continue;
  2436. }
  2437. #ifdef SFZ_FILES_USING_SFIZZ
  2438. if (std::strcmp(stateSave.type, "SFZ") == 0)
  2439. {
  2440. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://sfztools.github.io/sfizz", 0, nullptr))
  2441. {
  2442. const uint pluginId = pData->curPluginCount;
  2443. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2444. {
  2445. if (pData->aboutToClose)
  2446. return true;
  2447. if (pData->actionCanceled)
  2448. {
  2449. setLastError("Project load canceled");
  2450. return false;
  2451. }
  2452. plugin->setCustomData(LV2_ATOM__Path,
  2453. "http://sfztools.github.io/sfizz:sfzfile",
  2454. stateSave.binary,
  2455. false);
  2456. plugin->restoreLV2State(true);
  2457. plugin->setDryWet(stateSave.dryWet, true, true);
  2458. plugin->setVolume(stateSave.volume, true, true);
  2459. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2460. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2461. plugin->setPanning(stateSave.panning, true, true);
  2462. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2463. plugin->setActive(stateSave.active, true, true);
  2464. plugin->setEnabled(true);
  2465. ++pData->curPluginCount;
  2466. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, plugin->getType(),
  2467. 0, 0, 0.0f,
  2468. plugin->getName());
  2469. if (isPatchbay)
  2470. pData->graph.addPlugin(plugin);
  2471. }
  2472. else
  2473. {
  2474. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2475. }
  2476. }
  2477. else
  2478. {
  2479. carla_stderr2("Failed to load a sfizz LV2 plugin, SFZ file won't be loaded");
  2480. }
  2481. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2482. continue;
  2483. }
  2484. #endif
  2485. #endif
  2486. const void* extraStuff = nullptr;
  2487. static const char kTrue[] = "true";
  2488. const PluginType ptype = getPluginTypeFromString(stateSave.type);
  2489. switch (ptype)
  2490. {
  2491. case PLUGIN_SF2:
  2492. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  2493. extraStuff = kTrue;
  2494. // fall through
  2495. case PLUGIN_LADSPA:
  2496. case PLUGIN_DSSI:
  2497. case PLUGIN_VST2:
  2498. case PLUGIN_VST3:
  2499. case PLUGIN_SFZ:
  2500. case PLUGIN_JSFX:
  2501. case PLUGIN_CLAP:
  2502. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  2503. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  2504. {
  2505. const char* searchPath;
  2506. switch (ptype)
  2507. {
  2508. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  2509. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  2510. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  2511. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  2512. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  2513. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  2514. case PLUGIN_JSFX: searchPath = pData->options.pathJSFX; break;
  2515. case PLUGIN_CLAP: searchPath = pData->options.pathCLAP; break;
  2516. default: searchPath = nullptr; break;
  2517. }
  2518. if (searchPath != nullptr && searchPath[0] != '\0')
  2519. {
  2520. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  2521. stateSave.binary);
  2522. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2523. if (result.isEmpty())
  2524. {
  2525. switch (ptype)
  2526. {
  2527. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  2528. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  2529. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  2530. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  2531. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  2532. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  2533. case PLUGIN_JSFX: searchPath = std::getenv("JSFX_PATH"); break;
  2534. case PLUGIN_CLAP: searchPath = std::getenv("CLAP_PATH"); break;
  2535. default: searchPath = nullptr; break;
  2536. }
  2537. if (searchPath != nullptr && searchPath[0] != '\0')
  2538. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2539. }
  2540. if (result.isNotEmpty())
  2541. {
  2542. delete[] stateSave.binary;
  2543. stateSave.binary = carla_strdup(result.toRawUTF8());
  2544. carla_stderr("Found it! :)");
  2545. }
  2546. else
  2547. {
  2548. carla_stderr("Damn, we failed... :(");
  2549. }
  2550. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2551. }
  2552. }
  2553. break;
  2554. default:
  2555. break;
  2556. }
  2557. BinaryType btype;
  2558. switch (ptype)
  2559. {
  2560. case PLUGIN_LADSPA:
  2561. case PLUGIN_DSSI:
  2562. case PLUGIN_LV2:
  2563. case PLUGIN_VST2:
  2564. case PLUGIN_VST3:
  2565. case PLUGIN_CLAP:
  2566. case PLUGIN_AU:
  2567. btype = getBinaryTypeFromFile(stateSave.binary);
  2568. break;
  2569. default:
  2570. btype = BINARY_NATIVE;
  2571. break;
  2572. }
  2573. if (addPlugin(btype, ptype, stateSave.binary,
  2574. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  2575. {
  2576. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2577. const uint pluginId = pData->curPluginCount;
  2578. #else
  2579. const uint pluginId = 0;
  2580. #endif
  2581. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2582. {
  2583. if (pData->aboutToClose)
  2584. return true;
  2585. if (pData->actionCanceled)
  2586. {
  2587. setLastError("Project load canceled");
  2588. return false;
  2589. }
  2590. // deactivate bridge client-side ping check, since some plugins block during load
  2591. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  2592. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  2593. plugin->loadStateSave(stateSave);
  2594. /* NOTE: The following code is the same as the end of addPlugin().
  2595. * When project is loading we do not enable the plugin right away,
  2596. * as we want to load state first.
  2597. */
  2598. plugin->setEnabled(true);
  2599. ++pData->curPluginCount;
  2600. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, plugin->getType(),
  2601. 0, 0, 0.0f,
  2602. plugin->getName());
  2603. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2604. if (isPatchbay)
  2605. pData->graph.addPlugin(plugin);
  2606. #endif
  2607. }
  2608. else
  2609. {
  2610. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2611. }
  2612. }
  2613. else
  2614. {
  2615. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  2616. }
  2617. if (! isPreset)
  2618. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2619. }
  2620. if (isPreset)
  2621. {
  2622. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2623. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2624. return true;
  2625. }
  2626. }
  2627. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2628. // tell bridges we're done loading
  2629. for (uint i=0; i < pData->curPluginCount; ++i)
  2630. {
  2631. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2632. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2633. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2634. }
  2635. if (pData->aboutToClose)
  2636. return true;
  2637. if (pData->actionCanceled)
  2638. {
  2639. setLastError("Project load canceled");
  2640. return false;
  2641. }
  2642. // now we handle positions
  2643. bool loadingAsExternal;
  2644. std::map<water::String, water::String> mapGroupNamesInternal, mapGroupNamesExternal;
  2645. bool hasInternalPositions = false;
  2646. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("Patchbay"))
  2647. {
  2648. hasInternalPositions = true;
  2649. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2650. {
  2651. String name;
  2652. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2653. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2654. {
  2655. const String& patchTag(patchElem->getTagName());
  2656. if (patchTag != "Position")
  2657. continue;
  2658. XmlElement* const patchName = patchElem->getChildByName("Name");
  2659. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2660. const String nameText(patchName->getAllSubText().trim());
  2661. name = xmlSafeString(nameText, false);
  2662. ppos.name = name.toRawUTF8();
  2663. ppos.x1 = patchElem->getIntAttribute("x1");
  2664. ppos.y1 = patchElem->getIntAttribute("y1");
  2665. ppos.x2 = patchElem->getIntAttribute("x2");
  2666. ppos.y2 = patchElem->getIntAttribute("y2");
  2667. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2668. ppos.dealloc = false;
  2669. loadingAsExternal = ppos.pluginId >= 0 && isMultiClient;
  2670. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2671. {
  2672. if (name != ppos.name)
  2673. {
  2674. carla_stdout("Converted client name '%s' to '%s' for this session",
  2675. name.toRawUTF8(), ppos.name);
  2676. if (loadingAsExternal)
  2677. mapGroupNamesExternal[name] = ppos.name;
  2678. else
  2679. mapGroupNamesInternal[name] = ppos.name;
  2680. }
  2681. if (ppos.dealloc)
  2682. std::free(const_cast<char*>(ppos.name));
  2683. }
  2684. }
  2685. if (pData->aboutToClose)
  2686. return true;
  2687. if (pData->actionCanceled)
  2688. {
  2689. setLastError("Project load canceled");
  2690. return false;
  2691. }
  2692. }
  2693. }
  2694. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("ExternalPatchbay"))
  2695. {
  2696. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2697. {
  2698. String name;
  2699. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2700. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2701. {
  2702. const String& patchTag(patchElem->getTagName());
  2703. if (patchTag != "Position")
  2704. continue;
  2705. XmlElement* const patchName = patchElem->getChildByName("Name");
  2706. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2707. const String nameText(patchName->getAllSubText().trim());
  2708. name = xmlSafeString(nameText, false);
  2709. ppos.name = name.toRawUTF8();
  2710. ppos.x1 = patchElem->getIntAttribute("x1");
  2711. ppos.y1 = patchElem->getIntAttribute("y1");
  2712. ppos.x2 = patchElem->getIntAttribute("x2");
  2713. ppos.y2 = patchElem->getIntAttribute("y2");
  2714. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2715. ppos.dealloc = false;
  2716. loadingAsExternal = ppos.pluginId < 0 || hasInternalPositions || !isPatchbay;
  2717. carla_debug("loadingAsExternal: %i because %i %i %i",
  2718. loadingAsExternal, ppos.pluginId < 0, hasInternalPositions, !isPatchbay);
  2719. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2720. {
  2721. if (name != ppos.name)
  2722. {
  2723. carla_stdout("Converted client name '%s' to '%s' for this session",
  2724. name.toRawUTF8(), ppos.name);
  2725. if (loadingAsExternal)
  2726. mapGroupNamesExternal[name] = ppos.name;
  2727. else
  2728. mapGroupNamesInternal[name] = ppos.name;
  2729. }
  2730. if (ppos.dealloc)
  2731. std::free(const_cast<char*>(ppos.name));
  2732. }
  2733. }
  2734. if (pData->aboutToClose)
  2735. return true;
  2736. if (pData->actionCanceled)
  2737. {
  2738. setLastError("Project load canceled");
  2739. return false;
  2740. }
  2741. }
  2742. }
  2743. bool hasInternalConnections = false;
  2744. // and now we handle connections (internal)
  2745. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  2746. {
  2747. hasInternalConnections = true;
  2748. if (isPatchbay)
  2749. {
  2750. water::String sourcePort, targetPort;
  2751. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2752. {
  2753. const String& patchTag(patchElem->getTagName());
  2754. if (patchTag != "Connection")
  2755. continue;
  2756. sourcePort.clear();
  2757. targetPort.clear();
  2758. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2759. {
  2760. const String& tag(connElem->getTagName());
  2761. const String text(connElem->getAllSubText().trim());
  2762. /**/ if (tag == "Source")
  2763. sourcePort = xmlSafeString(text, false);
  2764. else if (tag == "Target")
  2765. targetPort = xmlSafeString(text, false);
  2766. }
  2767. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2768. {
  2769. std::map<water::String, water::String>& map(mapGroupNamesInternal);
  2770. std::map<water::String, water::String>::iterator it;
  2771. if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2772. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2773. if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2774. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2775. restorePatchbayConnection(false, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2776. }
  2777. }
  2778. if (pData->aboutToClose)
  2779. return true;
  2780. if (pData->actionCanceled)
  2781. {
  2782. setLastError("Project load canceled");
  2783. return false;
  2784. }
  2785. }
  2786. }
  2787. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2788. bool loadExternalConnections;
  2789. if (alwaysLoadConnections)
  2790. {
  2791. loadExternalConnections = true;
  2792. }
  2793. else
  2794. {
  2795. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2796. loadExternalConnections = true;
  2797. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2798. loadExternalConnections = false;
  2799. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2800. loadExternalConnections = false;
  2801. else if (std::getenv("NSM_URL") != nullptr)
  2802. loadExternalConnections = false;
  2803. else
  2804. loadExternalConnections = true;
  2805. }
  2806. // plus external connections too
  2807. if (loadExternalConnections)
  2808. {
  2809. bool isExternal;
  2810. loadingAsExternal = hasInternalConnections &&
  2811. (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || isPatchbay);
  2812. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2813. {
  2814. const String& tagName(elem->getTagName());
  2815. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2816. if (tagName == "Patchbay")
  2817. {
  2818. if (isPatchbay)
  2819. continue;
  2820. isExternal = false;
  2821. loadingAsExternal = true;
  2822. }
  2823. // or load external patchbay connections
  2824. else if (tagName == "ExternalPatchbay")
  2825. {
  2826. if (! isPatchbay)
  2827. loadingAsExternal = true;
  2828. isExternal = true;
  2829. }
  2830. else
  2831. {
  2832. continue;
  2833. }
  2834. water::String sourcePort, targetPort;
  2835. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2836. {
  2837. const String& patchTag(patchElem->getTagName());
  2838. if (patchTag != "Connection")
  2839. continue;
  2840. sourcePort.clear();
  2841. targetPort.clear();
  2842. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2843. {
  2844. const String& tag(connElem->getTagName());
  2845. const String text(connElem->getAllSubText().trim());
  2846. /**/ if (tag == "Source")
  2847. sourcePort = xmlSafeString(text, false);
  2848. else if (tag == "Target")
  2849. targetPort = xmlSafeString(text, false);
  2850. }
  2851. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2852. {
  2853. std::map<water::String, water::String>& map(loadingAsExternal ? mapGroupNamesExternal
  2854. : mapGroupNamesInternal);
  2855. std::map<water::String, water::String>::iterator it;
  2856. if (isExternal && isPatchbay && !loadingAsExternal && sourcePort.startsWith("system:capture_"))
  2857. {
  2858. water::String internalPort = sourcePort.trimCharactersAtStart("system:capture_");
  2859. if (pData->graph.getNumAudioOuts() < 3)
  2860. {
  2861. /**/ if (internalPort == "1")
  2862. internalPort = "Audio Input:Left";
  2863. else if (internalPort == "2")
  2864. internalPort = "Audio Input:Right";
  2865. else if (internalPort == "3")
  2866. internalPort = "Audio Input:Sidechain";
  2867. else
  2868. continue;
  2869. }
  2870. else
  2871. {
  2872. internalPort = "Audio Input:Capture " + internalPort;
  2873. }
  2874. carla_stdout("Converted port name '%s' to '%s' for this session",
  2875. sourcePort.toRawUTF8(), internalPort.toRawUTF8());
  2876. sourcePort = internalPort;
  2877. }
  2878. else if (!isExternal && isMultiClient && sourcePort.startsWith("Audio Input:"))
  2879. {
  2880. water::String externalPort = sourcePort.trimCharactersAtStart("Audio Input:");
  2881. /**/ if (externalPort == "Left")
  2882. externalPort = "system:capture_1";
  2883. else if (externalPort == "Right")
  2884. externalPort = "system:capture_2";
  2885. else if (externalPort == "Sidechain")
  2886. externalPort = "system:capture_3";
  2887. else
  2888. externalPort = "system:capture_ " + externalPort.trimCharactersAtStart("Capture ");
  2889. carla_stdout("Converted port name '%s' to '%s' for this session",
  2890. sourcePort.toRawUTF8(), externalPort.toRawUTF8());
  2891. sourcePort = externalPort;
  2892. }
  2893. else if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2894. {
  2895. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2896. }
  2897. if (isExternal && isPatchbay && !loadingAsExternal && targetPort.startsWith("system:playback_"))
  2898. {
  2899. water::String internalPort = targetPort.trimCharactersAtStart("system:playback_");
  2900. if (pData->graph.getNumAudioOuts() < 3)
  2901. {
  2902. /**/ if (internalPort == "1")
  2903. internalPort = "Audio Output:Left";
  2904. else if (internalPort == "2")
  2905. internalPort = "Audio Output:Right";
  2906. else
  2907. continue;
  2908. }
  2909. else
  2910. {
  2911. internalPort = "Audio Input:Playback " + internalPort;
  2912. }
  2913. carla_stdout("Converted port name '%s' to '%s' for this session",
  2914. targetPort.toRawUTF8(), internalPort.toRawUTF8());
  2915. targetPort = internalPort;
  2916. }
  2917. else if (!isExternal && isMultiClient && targetPort.startsWith("Audio Output:"))
  2918. {
  2919. water::String externalPort = targetPort.trimCharactersAtStart("Audio Output:");
  2920. /**/ if (externalPort == "Left")
  2921. externalPort = "system:playback_1";
  2922. else if (externalPort == "Right")
  2923. externalPort = "system:playback_2";
  2924. else
  2925. externalPort = "system:playback_ " + externalPort.trimCharactersAtStart("Playback ");
  2926. carla_stdout("Converted port name '%s' to '%s' for this session",
  2927. targetPort.toRawUTF8(), externalPort.toRawUTF8());
  2928. targetPort = externalPort;
  2929. }
  2930. else if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2931. {
  2932. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2933. }
  2934. restorePatchbayConnection(loadingAsExternal, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2935. }
  2936. }
  2937. break;
  2938. }
  2939. }
  2940. #endif
  2941. if (pData->options.resetXruns)
  2942. clearXruns();
  2943. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2944. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2945. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - END", &xmlDoc, bool2str(alwaysLoadConnections));
  2946. return true;
  2947. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2948. // unused
  2949. (void)alwaysLoadConnections;
  2950. #endif
  2951. }
  2952. // -----------------------------------------------------------------------
  2953. CARLA_BACKEND_END_NAMESPACE