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.

3629 lines
123KB

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