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.

3579 lines
121KB

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