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.

3628 lines
122KB

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