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.

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