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.

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