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.

3591 lines
121KB

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