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.

3596 lines
121KB

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