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.

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