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.

3487 lines
118KB

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