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.

3570 lines
120KB

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