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.

3514 lines
119KB

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