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.

2675 lines
88KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2019 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 "CarlaEngineInternal.hpp"
  24. #include "CarlaPlugin.hpp"
  25. #include "CarlaBackendUtils.hpp"
  26. #include "CarlaBinaryUtils.hpp"
  27. #include "CarlaEngineUtils.hpp"
  28. #include "CarlaMathUtils.hpp"
  29. #include "CarlaPipeUtils.hpp"
  30. #include "CarlaProcessUtils.hpp"
  31. #include "CarlaStateUtils.hpp"
  32. #include "CarlaMIDI.h"
  33. #include "jackbridge/JackBridge.hpp"
  34. #include "water/files/File.h"
  35. #include "water/streams/MemoryOutputStream.h"
  36. #include "water/xml/XmlDocument.h"
  37. #include "water/xml/XmlElement.h"
  38. // FIXME Remove on 2.1 release
  39. #include "lv2/atom.h"
  40. using water::Array;
  41. using water::CharPointer_UTF8;
  42. using water::File;
  43. using water::MemoryOutputStream;
  44. using water::String;
  45. using water::StringArray;
  46. using water::XmlDocument;
  47. using water::XmlElement;
  48. CARLA_BACKEND_START_NAMESPACE
  49. // -----------------------------------------------------------------------
  50. // Carla Engine
  51. CarlaEngine::CarlaEngine()
  52. : pData(new ProtectedData(this))
  53. {
  54. carla_debug("CarlaEngine::CarlaEngine()");
  55. }
  56. CarlaEngine::~CarlaEngine()
  57. {
  58. carla_debug("CarlaEngine::~CarlaEngine()");
  59. delete pData;
  60. }
  61. // -----------------------------------------------------------------------
  62. // Static calls
  63. uint CarlaEngine::getDriverCount()
  64. {
  65. carla_debug("CarlaEngine::getDriverCount()");
  66. uint count = 0;
  67. if (jackbridge_is_ok())
  68. count += 1;
  69. #ifndef BUILD_BRIDGE
  70. # ifdef USING_JUCE
  71. count += getJuceApiCount();
  72. # else
  73. count += getRtAudioApiCount();
  74. # endif
  75. #endif
  76. return count;
  77. }
  78. const char* CarlaEngine::getDriverName(const uint index2)
  79. {
  80. carla_debug("CarlaEngine::getDriverName(%i)", index2);
  81. uint index = index2;
  82. if (jackbridge_is_ok() && index-- == 0)
  83. return "JACK";
  84. #ifndef BUILD_BRIDGE
  85. # ifdef USING_JUCE
  86. if (const uint count = getJuceApiCount())
  87. {
  88. if (index < count)
  89. return getJuceApiName(index);
  90. index -= count;
  91. }
  92. # else
  93. if (const uint count = getRtAudioApiCount())
  94. {
  95. if (index < count)
  96. return getRtAudioApiName(index);
  97. }
  98. # endif
  99. #endif
  100. carla_stderr("CarlaEngine::getDriverName(%i) - invalid index", index2);
  101. return nullptr;
  102. }
  103. const char* const* CarlaEngine::getDriverDeviceNames(const uint index2)
  104. {
  105. carla_debug("CarlaEngine::getDriverDeviceNames(%i)", index2);
  106. uint index = index2;
  107. if (jackbridge_is_ok() && index-- == 0)
  108. {
  109. static const char* ret[3] = { "Auto-Connect ON", "Auto-Connect OFF", nullptr };
  110. return ret;
  111. }
  112. #ifndef BUILD_BRIDGE
  113. # ifdef USING_JUCE
  114. if (const uint count = getJuceApiCount())
  115. {
  116. if (index < count)
  117. return getJuceApiDeviceNames(index);
  118. index -= count;
  119. }
  120. # else
  121. if (const uint count = getRtAudioApiCount())
  122. {
  123. if (index < count)
  124. return getRtAudioApiDeviceNames(index);
  125. }
  126. # endif
  127. #endif
  128. carla_stderr("CarlaEngine::getDriverDeviceNames(%i) - invalid index", index2);
  129. return nullptr;
  130. }
  131. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index2, const char* const deviceName)
  132. {
  133. carla_debug("CarlaEngine::getDriverDeviceInfo(%i, \"%s\")", index2, deviceName);
  134. uint index = index2;
  135. if (jackbridge_is_ok() && index-- == 0)
  136. {
  137. static EngineDriverDeviceInfo devInfo;
  138. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  139. devInfo.bufferSizes = nullptr;
  140. devInfo.sampleRates = nullptr;
  141. return &devInfo;
  142. }
  143. #ifndef BUILD_BRIDGE
  144. # ifdef USING_JUCE
  145. if (const uint count = getJuceApiCount())
  146. {
  147. if (index < count)
  148. return getJuceDeviceInfo(index, deviceName);
  149. index -= count;
  150. }
  151. # else
  152. if (const uint count = getRtAudioApiCount())
  153. {
  154. if (index < count)
  155. return getRtAudioDeviceInfo(index, deviceName);
  156. }
  157. # endif
  158. #endif
  159. carla_stderr("CarlaEngine::getDriverDeviceNames(%i, \"%s\") - invalid index", index2, deviceName);
  160. return nullptr;
  161. }
  162. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  163. {
  164. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  165. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  166. if (std::strcmp(driverName, "JACK") == 0)
  167. return newJack();
  168. #ifndef BUILD_BRIDGE
  169. # ifdef USING_JUCE
  170. // -------------------------------------------------------------------
  171. // linux
  172. if (std::strcmp(driverName, "ALSA") == 0)
  173. return newJuce(AUDIO_API_ALSA);
  174. // -------------------------------------------------------------------
  175. // macos
  176. if (std::strcmp(driverName, "CoreAudio") == 0)
  177. return newJuce(AUDIO_API_COREAUDIO);
  178. // -------------------------------------------------------------------
  179. // windows
  180. if (std::strcmp(driverName, "ASIO") == 0)
  181. return newJuce(AUDIO_API_ASIO);
  182. if (std::strcmp(driverName, "DirectSound") == 0)
  183. return newJuce(AUDIO_API_DIRECTSOUND);
  184. # else
  185. // -------------------------------------------------------------------
  186. // common
  187. if (std::strcmp(driverName, "Dummy") == 0)
  188. return newRtAudio(AUDIO_API_NULL);
  189. if (std::strncmp(driverName, "JACK ", 5) == 0)
  190. return newRtAudio(AUDIO_API_JACK);
  191. if (std::strcmp(driverName, "OSS") == 0)
  192. return newRtAudio(AUDIO_API_OSS);
  193. // -------------------------------------------------------------------
  194. // linux
  195. if (std::strcmp(driverName, "ALSA") == 0)
  196. return newRtAudio(AUDIO_API_ALSA);
  197. if (std::strcmp(driverName, "PulseAudio") == 0)
  198. return newRtAudio(AUDIO_API_PULSEAUDIO);
  199. // -------------------------------------------------------------------
  200. // macos
  201. if (std::strcmp(driverName, "CoreAudio") == 0)
  202. return newRtAudio(AUDIO_API_COREAUDIO);
  203. // -------------------------------------------------------------------
  204. // windows
  205. if (std::strcmp(driverName, "ASIO") == 0)
  206. return newRtAudio(AUDIO_API_ASIO);
  207. if (std::strcmp(driverName, "DirectSound") == 0)
  208. return newRtAudio(AUDIO_API_DIRECTSOUND);
  209. if (std::strcmp(driverName, "WASAPI") == 0)
  210. return newRtAudio(AUDIO_API_WASAPI);
  211. # endif
  212. #endif
  213. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  214. return nullptr;
  215. }
  216. // -----------------------------------------------------------------------
  217. // Constant values
  218. uint CarlaEngine::getMaxClientNameSize() const noexcept
  219. {
  220. return STR_MAX/2;
  221. }
  222. uint CarlaEngine::getMaxPortNameSize() const noexcept
  223. {
  224. return STR_MAX;
  225. }
  226. uint CarlaEngine::getCurrentPluginCount() const noexcept
  227. {
  228. return pData->curPluginCount;
  229. }
  230. uint CarlaEngine::getMaxPluginNumber() const noexcept
  231. {
  232. return pData->maxPluginNumber;
  233. }
  234. // -----------------------------------------------------------------------
  235. // Virtual, per-engine type calls
  236. bool CarlaEngine::close()
  237. {
  238. carla_debug("CarlaEngine::close()");
  239. if (pData->curPluginCount != 0)
  240. {
  241. pData->aboutToClose = true;
  242. removeAllPlugins();
  243. }
  244. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  245. if (pData->osc.isControlRegistered())
  246. oscSend_control_exit();
  247. #endif
  248. pData->close();
  249. callback(ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0, 0.0f, nullptr);
  250. return true;
  251. }
  252. bool CarlaEngine::usesConstantBufferSize() const noexcept
  253. {
  254. return true;
  255. }
  256. void CarlaEngine::idle() noexcept
  257. {
  258. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  259. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  260. CARLA_SAFE_ASSERT_RETURN(getType() != kEngineTypePlugin,);
  261. for (uint i=0; i < pData->curPluginCount; ++i)
  262. {
  263. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  264. if (plugin != nullptr && plugin->isEnabled())
  265. {
  266. const uint hints(plugin->getHints());
  267. if ((hints & PLUGIN_HAS_CUSTOM_UI) != 0 && (hints & PLUGIN_NEEDS_UI_MAIN_THREAD) != 0)
  268. {
  269. try {
  270. plugin->uiIdle();
  271. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  272. }
  273. }
  274. }
  275. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  276. pData->osc.idle();
  277. #endif
  278. }
  279. CarlaEngineClient* CarlaEngine::addClient(CarlaPlugin* const)
  280. {
  281. return new CarlaEngineClient(*this);
  282. }
  283. float CarlaEngine::getDSPLoad() const noexcept
  284. {
  285. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  286. return pData->dspLoad;
  287. #else
  288. return 0.0f;
  289. #endif
  290. }
  291. uint32_t CarlaEngine::getTotalXruns() const noexcept
  292. {
  293. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  294. return pData->xruns;
  295. #else
  296. return 0;
  297. #endif
  298. }
  299. // -----------------------------------------------------------------------
  300. // Plugin management
  301. bool CarlaEngine::addPlugin(const BinaryType btype, const PluginType ptype,
  302. const char* const filename, const char* const name, const char* const label, const int64_t uniqueId,
  303. const void* const extra, const uint options)
  304. {
  305. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  306. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  307. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  308. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  309. #endif
  310. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  311. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  312. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  313. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  314. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p, %u)", btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra, options);
  315. #ifndef CARLA_OS_WIN
  316. if (ptype != PLUGIN_JACK && filename != nullptr && filename[0] != '\0') {
  317. CARLA_SAFE_ASSERT_RETURN_ERR(filename[0] == CARLA_OS_SEP || filename[0] == '.' || filename[0] == '~', "Invalid plugin filename");
  318. }
  319. #endif
  320. uint id;
  321. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  322. CarlaPlugin* oldPlugin = nullptr;
  323. if (pData->nextPluginId < pData->curPluginCount)
  324. {
  325. id = pData->nextPluginId;
  326. pData->nextPluginId = pData->maxPluginNumber;
  327. oldPlugin = pData->plugins[id].plugin;
  328. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin != nullptr, "Invalid replace plugin Id");
  329. }
  330. else
  331. #endif
  332. {
  333. id = pData->curPluginCount;
  334. if (id == pData->maxPluginNumber)
  335. {
  336. setLastError("Maximum number of plugins reached");
  337. return false;
  338. }
  339. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  340. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin == nullptr, "Invalid engine internal data");
  341. #endif
  342. }
  343. CarlaPlugin::Initializer initializer = {
  344. this,
  345. id,
  346. filename,
  347. name,
  348. label,
  349. uniqueId,
  350. options
  351. };
  352. CarlaPlugin* plugin = nullptr;
  353. CarlaString bridgeBinary(pData->options.binaryDir);
  354. if (bridgeBinary.isNotEmpty())
  355. {
  356. #ifndef CARLA_OS_WIN
  357. if (btype == BINARY_NATIVE)
  358. {
  359. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  360. }
  361. else
  362. #endif
  363. {
  364. switch (btype)
  365. {
  366. case BINARY_POSIX32:
  367. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  368. break;
  369. case BINARY_POSIX64:
  370. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  371. break;
  372. case BINARY_WIN32:
  373. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  374. break;
  375. case BINARY_WIN64:
  376. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  377. break;
  378. default:
  379. bridgeBinary.clear();
  380. break;
  381. }
  382. }
  383. if (! File(bridgeBinary.buffer()).existsAsFile())
  384. bridgeBinary.clear();
  385. }
  386. // Prefer bridges for some specific plugins
  387. const bool preferBridges = pData->options.preferPluginBridges;
  388. #if 0 // ndef BUILD_BRIDGE
  389. if (! preferBridges)
  390. {
  391. if (ptype == PLUGIN_LV2 && label != nullptr)
  392. {
  393. if (std::strncmp(label, "http://calf.sourceforge.net/plugins/", 36) == 0 ||
  394. std::strcmp(label, "http://factorial.hu/plugins/lv2/ir") == 0 ||
  395. std::strstr(label, "v1.sourceforge.net/lv2") != nullptr)
  396. {
  397. preferBridges = true;
  398. }
  399. }
  400. }
  401. #endif // ! BUILD_BRIDGE
  402. const bool canBeBridged = ptype != PLUGIN_INTERNAL
  403. && ptype != PLUGIN_SF2
  404. && ptype != PLUGIN_SFZ
  405. && ptype != PLUGIN_JACK;
  406. if (canBeBridged && (btype != BINARY_NATIVE || (preferBridges && bridgeBinary.isNotEmpty())))
  407. {
  408. if (bridgeBinary.isNotEmpty())
  409. {
  410. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, bridgeBinary);
  411. }
  412. else
  413. {
  414. setLastError("This Carla build cannot handle this binary");
  415. return false;
  416. }
  417. }
  418. else
  419. {
  420. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  421. bool use16Outs;
  422. #endif
  423. setLastError("Invalid or unsupported plugin type");
  424. // Some stupid plugins mess up with global signals, err!!
  425. const CarlaSignalRestorer csr;
  426. switch (ptype)
  427. {
  428. case PLUGIN_NONE:
  429. break;
  430. case PLUGIN_LADSPA:
  431. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  432. break;
  433. case PLUGIN_DSSI:
  434. plugin = CarlaPlugin::newDSSI(initializer);
  435. break;
  436. case PLUGIN_LV2:
  437. plugin = CarlaPlugin::newLV2(initializer);
  438. break;
  439. case PLUGIN_VST2:
  440. plugin = CarlaPlugin::newVST2(initializer);
  441. break;
  442. case PLUGIN_VST3:
  443. plugin = CarlaPlugin::newVST3(initializer);
  444. break;
  445. case PLUGIN_AU:
  446. plugin = CarlaPlugin::newAU(initializer);
  447. break;
  448. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  449. case PLUGIN_INTERNAL:
  450. plugin = CarlaPlugin::newNative(initializer);
  451. break;
  452. case PLUGIN_SF2:
  453. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  454. plugin = CarlaPlugin::newFluidSynth(initializer, use16Outs);
  455. break;
  456. case PLUGIN_SFZ:
  457. plugin = CarlaPlugin::newSFZero(initializer);
  458. break;
  459. case PLUGIN_JACK:
  460. plugin = CarlaPlugin::newJackApp(initializer);
  461. break;
  462. #else
  463. case PLUGIN_INTERNAL:
  464. case PLUGIN_SF2:
  465. case PLUGIN_SFZ:
  466. case PLUGIN_JACK:
  467. setLastError("Plugin bridges cannot handle this binary");
  468. break;
  469. #endif
  470. }
  471. }
  472. if (plugin == nullptr)
  473. return false;
  474. plugin->reload();
  475. bool canRun = true;
  476. /**/ if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  477. {
  478. if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  479. {
  480. setLastError("Carla's rack mode cannot work with plugins that have CV ports, sorry!");
  481. canRun = false;
  482. }
  483. }
  484. else if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  485. {
  486. /**/ if (plugin->getMidiInCount() > 1 || plugin->getMidiOutCount() > 1)
  487. {
  488. setLastError("Carla's patchbay mode cannot work with plugins that have multiple MIDI ports, sorry!");
  489. canRun = false;
  490. }
  491. else if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  492. {
  493. setLastError("CV ports in patchbay mode is still TODO");
  494. canRun = false;
  495. }
  496. }
  497. if (! canRun)
  498. {
  499. delete plugin;
  500. return false;
  501. }
  502. EnginePluginData& pluginData(pData->plugins[id]);
  503. pluginData.plugin = plugin;
  504. carla_zeroFloats(pluginData.peaks, 4);
  505. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  506. if (oldPlugin != nullptr)
  507. {
  508. CARLA_SAFE_ASSERT(! pData->loadingProject);
  509. const ScopedThreadStopper sts(this);
  510. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  511. pData->graph.replacePlugin(oldPlugin, plugin);
  512. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  513. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  514. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  515. delete oldPlugin;
  516. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  517. plugin->setDryWet(oldDryWet, true, true);
  518. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  519. plugin->setVolume(oldVolume, true, true);
  520. plugin->setActive(wasActive, true, true);
  521. plugin->setEnabled(true);
  522. callback(ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0, 0.0f, nullptr);
  523. }
  524. else if (! pData->loadingProject)
  525. #endif
  526. {
  527. plugin->setEnabled(true);
  528. ++pData->curPluginCount;
  529. callback(ENGINE_CALLBACK_PLUGIN_ADDED, id, 0, 0, 0, 0.0f, plugin->getName());
  530. if (getType() != kEngineTypeBridge)
  531. plugin->setActive(true, false, true);
  532. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  533. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  534. pData->graph.addPlugin(plugin);
  535. #endif
  536. }
  537. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  538. plugin->registerToOscClient();
  539. #endif
  540. return true;
  541. }
  542. bool CarlaEngine::addPlugin(const PluginType ptype, const char* const filename, const char* const name, const char* const label, const int64_t uniqueId, const void* const extra)
  543. {
  544. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra, 0x0);
  545. }
  546. bool CarlaEngine::removePlugin(const uint id)
  547. {
  548. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  549. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  550. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  551. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  552. #endif
  553. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  554. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  555. carla_debug("CarlaEngine::removePlugin(%i)", id);
  556. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  557. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to remove");
  558. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  559. const ScopedThreadStopper sts(this);
  560. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  561. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  562. pData->graph.removePlugin(plugin);
  563. const ScopedActionLock sal(this, kEnginePostActionRemovePlugin, id, 0);
  564. /*
  565. for (uint i=id; i < pData->curPluginCount; ++i)
  566. {
  567. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  568. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  569. plugin2->updateOscURL();
  570. }
  571. */
  572. # if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  573. if (isOscControlRegistered())
  574. oscSend_control_remove_plugin(id);
  575. # endif
  576. #else
  577. pData->curPluginCount = 0;
  578. carla_zeroStructs(pData->plugins, 1);
  579. #endif
  580. delete plugin;
  581. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0, 0.0f, nullptr);
  582. return true;
  583. }
  584. bool CarlaEngine::removeAllPlugins()
  585. {
  586. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  587. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  588. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  589. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  590. #endif
  591. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  592. carla_debug("CarlaEngine::removeAllPlugins()");
  593. if (pData->curPluginCount == 0)
  594. return true;
  595. const ScopedThreadStopper sts(this);
  596. const uint curPluginCount(pData->curPluginCount);
  597. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  598. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  599. pData->graph.removeAllPlugins();
  600. # if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  601. if (isOscControlRegistered())
  602. {
  603. for (uint i=0; i < curPluginCount; ++i)
  604. oscSend_control_remove_plugin(curPluginCount-i-1);
  605. }
  606. # endif
  607. #endif
  608. const ScopedActionLock sal(this, kEnginePostActionZeroCount, 0, 0);
  609. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  610. for (uint i=0; i < curPluginCount; ++i)
  611. {
  612. const uint id = curPluginCount - i - 1;
  613. EnginePluginData& pluginData(pData->plugins[id]);
  614. if (pluginData.plugin != nullptr)
  615. {
  616. delete pluginData.plugin;
  617. pluginData.plugin = nullptr;
  618. }
  619. carla_zeroFloats(pluginData.peaks, 4);
  620. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0, 0.0f, nullptr);
  621. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  622. }
  623. return true;
  624. }
  625. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  626. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  627. {
  628. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  629. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  630. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  631. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  632. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  633. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  634. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  635. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  636. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  637. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  638. const char* const uniqueName(getUniquePluginName(newName));
  639. CARLA_SAFE_ASSERT_RETURN_ERRN(uniqueName != nullptr, "Unable to get new unique plugin name");
  640. plugin->setName(uniqueName);
  641. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  642. pData->graph.renamePlugin(plugin, uniqueName);
  643. delete[] uniqueName;
  644. return plugin->getName();
  645. }
  646. bool CarlaEngine::clonePlugin(const uint id)
  647. {
  648. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  649. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  650. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  651. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  652. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  653. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  654. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  655. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  656. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  657. char label[STR_MAX+1];
  658. carla_zeroChars(label, STR_MAX+1);
  659. plugin->getLabel(label);
  660. const uint pluginCountBefore(pData->curPluginCount);
  661. if (! addPlugin(plugin->getBinaryType(), plugin->getType(),
  662. plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(),
  663. plugin->getExtraStuff(), plugin->getOptionsEnabled()))
  664. return false;
  665. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  666. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  667. newPlugin->loadStateSave(plugin->getStateSave());
  668. return true;
  669. }
  670. bool CarlaEngine::replacePlugin(const uint id) noexcept
  671. {
  672. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  673. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  674. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  675. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  676. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  677. // might use this to reset
  678. if (id == pData->maxPluginNumber)
  679. {
  680. pData->nextPluginId = pData->maxPluginNumber;
  681. return true;
  682. }
  683. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  684. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  685. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  686. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  687. pData->nextPluginId = id;
  688. return true;
  689. }
  690. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  691. {
  692. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  693. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  694. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  695. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  696. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  697. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  698. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  699. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  700. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  701. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  702. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  703. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  704. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  705. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  706. const ScopedThreadStopper sts(this);
  707. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  708. pData->graph.replacePlugin(pluginA, pluginB);
  709. const ScopedActionLock sal(this, kEnginePostActionSwitchPlugins, idA, idB);
  710. // TODO
  711. /*
  712. pluginA->updateOscURL();
  713. pluginB->updateOscURL();
  714. if (isOscControlRegistered())
  715. oscSend_control_switch_plugins(idA, idB);
  716. */
  717. return true;
  718. }
  719. #endif
  720. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const noexcept
  721. {
  722. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  723. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  724. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  725. #endif
  726. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  727. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  728. return pData->plugins[id].plugin;
  729. }
  730. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  731. {
  732. return pData->plugins[id].plugin;
  733. }
  734. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  735. {
  736. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  737. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  738. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  739. CarlaString sname;
  740. sname = name;
  741. if (sname.isEmpty())
  742. {
  743. sname = "(No name)";
  744. return sname.dup();
  745. }
  746. const std::size_t maxNameSize(carla_minConstrained<uint>(getMaxClientNameSize(), 0xff, 6U) - 6); // 6 = strlen(" (10)") + 1
  747. if (maxNameSize == 0 || ! isRunning())
  748. return sname.dup();
  749. sname.truncate(maxNameSize);
  750. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  751. for (uint i=0; i < pData->curPluginCount; ++i)
  752. {
  753. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  754. // Check if unique name doesn't exist
  755. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  756. {
  757. if (sname != pluginName)
  758. continue;
  759. }
  760. // Check if string has already been modified
  761. {
  762. const std::size_t len(sname.length());
  763. // 1 digit, ex: " (2)"
  764. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  765. {
  766. const int number = sname[len-2] - '0';
  767. if (number == 9)
  768. {
  769. // next number is 10, 2 digits
  770. sname.truncate(len-4);
  771. sname += " (10)";
  772. //sname.replace(" (9)", " (10)");
  773. }
  774. else
  775. sname[len-2] = char('0' + number + 1);
  776. continue;
  777. }
  778. // 2 digits, ex: " (11)"
  779. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  780. {
  781. char n2 = sname[len-2];
  782. char n3 = sname[len-3];
  783. if (n2 == '9')
  784. {
  785. n2 = '0';
  786. n3 = static_cast<char>(n3 + 1);
  787. }
  788. else
  789. n2 = static_cast<char>(n2 + 1);
  790. sname[len-2] = n2;
  791. sname[len-3] = n3;
  792. continue;
  793. }
  794. }
  795. // Modify string if not
  796. sname += " (2)";
  797. }
  798. return sname.dup();
  799. }
  800. // -----------------------------------------------------------------------
  801. // Project management
  802. bool CarlaEngine::loadFile(const char* const filename)
  803. {
  804. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  805. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  806. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  807. const String jfilename = String(CharPointer_UTF8(filename));
  808. File file(jfilename);
  809. CARLA_SAFE_ASSERT_RETURN_ERR(file.exists(), "Requested file does not exist or is not a readable");
  810. CarlaString baseName(file.getFileNameWithoutExtension().toRawUTF8());
  811. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  812. const uint curPluginId(pData->nextPluginId < pData->curPluginCount ? pData->nextPluginId : pData->curPluginCount);
  813. // -------------------------------------------------------------------
  814. // NOTE: please keep in sync with carla_get_supported_file_extensions!!
  815. if (extension == "carxp" || extension == "carxs")
  816. return loadProject(filename, false);
  817. // -------------------------------------------------------------------
  818. if (extension == "sf2" || extension == "sf3")
  819. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  820. if (extension == "sfz")
  821. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  822. // -------------------------------------------------------------------
  823. if (
  824. #ifdef HAVE_SNDFILE
  825. extension == "aif" ||
  826. extension == "aifc" ||
  827. extension == "aiff" ||
  828. extension == "au" ||
  829. extension == "bwf" ||
  830. extension == "flac" ||
  831. extension == "htk" ||
  832. extension == "iff" ||
  833. extension == "mat4" ||
  834. extension == "mat5" ||
  835. extension == "oga" ||
  836. extension == "ogg" ||
  837. extension == "paf" ||
  838. extension == "pvf" ||
  839. extension == "pvf5" ||
  840. extension == "sd2" ||
  841. extension == "sf" ||
  842. extension == "snd" ||
  843. extension == "svx" ||
  844. extension == "vcc" ||
  845. extension == "w64" ||
  846. extension == "wav" ||
  847. extension == "xi" ||
  848. #endif
  849. #ifdef HAVE_FFMPEG
  850. extension == "3g2" ||
  851. extension == "3gp" ||
  852. extension == "aac" ||
  853. extension == "ac3" ||
  854. extension == "amr" ||
  855. extension == "ape" ||
  856. extension == "mp2" ||
  857. extension == "mp3" ||
  858. extension == "mpc" ||
  859. extension == "wma" ||
  860. # ifndef HAVE_SNDFILE
  861. // FFmpeg without sndfile
  862. extension == "flac" ||
  863. extension == "oga" ||
  864. extension == "ogg" ||
  865. extension == "w64" ||
  866. extension == "wav" ||
  867. # endif
  868. #endif
  869. false
  870. )
  871. {
  872. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  873. {
  874. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  875. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  876. return true;
  877. }
  878. return false;
  879. }
  880. // -------------------------------------------------------------------
  881. if (extension == "mid" || extension == "midi")
  882. {
  883. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  884. {
  885. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  886. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  887. return true;
  888. }
  889. return false;
  890. }
  891. // -------------------------------------------------------------------
  892. // ZynAddSubFX
  893. if (extension == "xmz" || extension == "xiz")
  894. {
  895. #ifdef HAVE_ZYN_DEPS
  896. CarlaString nicerName("Zyn - ");
  897. const std::size_t sep(baseName.find('-')+1);
  898. if (sep < baseName.length())
  899. nicerName += baseName.buffer()+sep;
  900. else
  901. nicerName += baseName;
  902. //nicerName
  903. if (addPlugin(PLUGIN_INTERNAL, nullptr, nicerName, "zynaddsubfx", 0, nullptr))
  904. {
  905. callback(ENGINE_CALLBACK_UI_STATE_CHANGED, curPluginId, 0, 0, 0, 0.0f, nullptr);
  906. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  907. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  908. return true;
  909. }
  910. return false;
  911. #else
  912. setLastError("This Carla build does not have ZynAddSubFX support");
  913. return false;
  914. #endif
  915. }
  916. // -------------------------------------------------------------------
  917. // Direct plugin binaries
  918. #ifdef CARLA_OS_MAC
  919. if (extension == "vst")
  920. return addPlugin(PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  921. #else
  922. if (extension == "dll" || extension == "so")
  923. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr, 0x0);
  924. #endif
  925. #if defined(USING_JUCE) && (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  926. if (extension == "vst3")
  927. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST3, filename, nullptr, nullptr, 0, nullptr, 0x0);
  928. #endif
  929. // -------------------------------------------------------------------
  930. setLastError("Unknown file extension");
  931. return false;
  932. }
  933. bool CarlaEngine::loadProject(const char* const filename, const bool setAsCurrentProject)
  934. {
  935. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  936. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  937. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  938. const String jfilename = String(CharPointer_UTF8(filename));
  939. File file(jfilename);
  940. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  941. if (setAsCurrentProject)
  942. {
  943. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  944. pData->currentProjectFilename = filename;
  945. #endif
  946. }
  947. XmlDocument xml(file);
  948. return loadProjectInternal(xml);
  949. }
  950. bool CarlaEngine::saveProject(const char* const filename, const bool setAsCurrentProject)
  951. {
  952. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  953. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  954. MemoryOutputStream out;
  955. saveProjectInternal(out);
  956. const String jfilename = String(CharPointer_UTF8(filename));
  957. File file(jfilename);
  958. if (setAsCurrentProject)
  959. {
  960. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  961. pData->currentProjectFilename = filename;
  962. #endif
  963. }
  964. if (file.replaceWithData(out.getData(), out.getDataSize()))
  965. return true;
  966. setLastError("Failed to write file");
  967. return false;
  968. }
  969. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  970. const char* CarlaEngine::getCurrentProjectFilename() const noexcept
  971. {
  972. return pData->currentProjectFilename;
  973. }
  974. void CarlaEngine::clearCurrentProjectFilename() noexcept
  975. {
  976. pData->currentProjectFilename.clear();
  977. }
  978. #endif
  979. // -----------------------------------------------------------------------
  980. // Information (base)
  981. uint CarlaEngine::getHints() const noexcept
  982. {
  983. return pData->hints;
  984. }
  985. uint32_t CarlaEngine::getBufferSize() const noexcept
  986. {
  987. return pData->bufferSize;
  988. }
  989. double CarlaEngine::getSampleRate() const noexcept
  990. {
  991. return pData->sampleRate;
  992. }
  993. const char* CarlaEngine::getName() const noexcept
  994. {
  995. return pData->name;
  996. }
  997. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  998. {
  999. return pData->options.processMode;
  1000. }
  1001. const EngineOptions& CarlaEngine::getOptions() const noexcept
  1002. {
  1003. return pData->options;
  1004. }
  1005. EngineTimeInfo CarlaEngine::getTimeInfo() const noexcept
  1006. {
  1007. return pData->timeInfo;
  1008. }
  1009. // -----------------------------------------------------------------------
  1010. // Information (peaks)
  1011. float* CarlaEngine::getPeaks(const uint pluginId) const noexcept
  1012. {
  1013. carla_zeroFloats(pData->peaks, 4);
  1014. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1015. {
  1016. // get peak from first plugin, if available
  1017. if (const uint count = pData->curPluginCount)
  1018. {
  1019. pData->peaks[0] = pData->plugins[0].peaks[0];
  1020. pData->peaks[1] = pData->plugins[0].peaks[1];
  1021. pData->peaks[2] = pData->plugins[count-1].peaks[2];
  1022. pData->peaks[3] = pData->plugins[count-1].peaks[3];
  1023. }
  1024. return pData->peaks;
  1025. }
  1026. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, pData->peaks);
  1027. return pData->plugins[pluginId].peaks;
  1028. }
  1029. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  1030. {
  1031. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1032. {
  1033. // get peak from first plugin, if available
  1034. if (pData->curPluginCount > 0)
  1035. return pData->plugins[0].peaks[isLeft ? 0 : 1];
  1036. return 0.0f;
  1037. }
  1038. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1039. return pData->plugins[pluginId].peaks[isLeft ? 0 : 1];
  1040. }
  1041. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  1042. {
  1043. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1044. {
  1045. // get peak from last plugin, if available
  1046. if (pData->curPluginCount > 0)
  1047. return pData->plugins[pData->curPluginCount-1].peaks[isLeft ? 2 : 3];
  1048. return 0.0f;
  1049. }
  1050. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1051. return pData->plugins[pluginId].peaks[isLeft ? 2 : 3];
  1052. }
  1053. // -----------------------------------------------------------------------
  1054. // Callback
  1055. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId,
  1056. const int value1, const int value2, const int value3,
  1057. const float valueF, const char* const valueStr) noexcept
  1058. {
  1059. #ifdef DEBUG
  1060. if (pData->isIdling)
  1061. carla_stdout("CarlaEngine::callback [while idling] (%i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1062. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueF, valueStr);
  1063. else if (action != ENGINE_CALLBACK_IDLE && action != ENGINE_CALLBACK_NOTE_ON && action != ENGINE_CALLBACK_NOTE_OFF)
  1064. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1065. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueF, valueStr);
  1066. #endif
  1067. if (pData->callback != nullptr)
  1068. {
  1069. if (action == ENGINE_CALLBACK_IDLE)
  1070. ++pData->isIdling;
  1071. try {
  1072. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueF, valueStr);
  1073. #if defined(CARLA_OS_LINUX) && defined(__arm__)
  1074. } catch (__cxxabiv1::__forced_unwind&) {
  1075. carla_stderr2("Caught forced unwind exception in callback");
  1076. throw;
  1077. #endif
  1078. } catch (...) {
  1079. carla_safe_exception("callback", __FILE__, __LINE__);
  1080. }
  1081. if (action == ENGINE_CALLBACK_IDLE)
  1082. --pData->isIdling;
  1083. }
  1084. }
  1085. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1086. {
  1087. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1088. pData->callback = func;
  1089. pData->callbackPtr = ptr;
  1090. }
  1091. // -----------------------------------------------------------------------
  1092. // File Callback
  1093. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1094. {
  1095. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1096. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1097. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1098. const char* ret = nullptr;
  1099. if (pData->fileCallback != nullptr)
  1100. {
  1101. try {
  1102. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1103. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1104. }
  1105. return ret;
  1106. }
  1107. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1108. {
  1109. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1110. pData->fileCallback = func;
  1111. pData->fileCallbackPtr = ptr;
  1112. }
  1113. // -----------------------------------------------------------------------
  1114. // Transport
  1115. void CarlaEngine::transportPlay() noexcept
  1116. {
  1117. pData->timeInfo.playing = true;
  1118. pData->time.setNeedsReset();
  1119. }
  1120. void CarlaEngine::transportPause() noexcept
  1121. {
  1122. if (pData->timeInfo.playing)
  1123. pData->time.pause();
  1124. else
  1125. pData->time.setNeedsReset();
  1126. }
  1127. void CarlaEngine::transportBPM(const double bpm) noexcept
  1128. {
  1129. try {
  1130. pData->time.setBPM(bpm);
  1131. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1132. }
  1133. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1134. {
  1135. pData->time.relocate(frame);
  1136. }
  1137. // -----------------------------------------------------------------------
  1138. // Error handling
  1139. const char* CarlaEngine::getLastError() const noexcept
  1140. {
  1141. return pData->lastError;
  1142. }
  1143. void CarlaEngine::setLastError(const char* const error) const noexcept
  1144. {
  1145. pData->lastError = error;
  1146. }
  1147. // -----------------------------------------------------------------------
  1148. // Misc
  1149. bool CarlaEngine::isAboutToClose() const noexcept
  1150. {
  1151. return pData->aboutToClose;
  1152. }
  1153. bool CarlaEngine::setAboutToClose() noexcept
  1154. {
  1155. carla_debug("CarlaEngine::setAboutToClose()");
  1156. pData->aboutToClose = true;
  1157. return (pData->isIdling == 0);
  1158. }
  1159. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1160. bool CarlaEngine::isLoadingProject() const noexcept
  1161. {
  1162. return pData->loadingProject;
  1163. }
  1164. #endif
  1165. void CarlaEngine::setActionCanceled(const bool canceled) noexcept
  1166. {
  1167. pData->actionCanceled = canceled;
  1168. }
  1169. bool CarlaEngine::wasActionCanceled() const noexcept
  1170. {
  1171. return pData->actionCanceled;
  1172. }
  1173. // -----------------------------------------------------------------------
  1174. // Global options
  1175. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1176. {
  1177. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1178. if (isRunning())
  1179. {
  1180. switch (option)
  1181. {
  1182. case ENGINE_OPTION_PROCESS_MODE:
  1183. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1184. case ENGINE_OPTION_AUDIO_DEVICE:
  1185. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!",
  1186. option, EngineOption2Str(option), value, valueStr);
  1187. default:
  1188. break;
  1189. }
  1190. }
  1191. // do not un-force stereo for rack mode
  1192. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1193. return;
  1194. switch (option)
  1195. {
  1196. case ENGINE_OPTION_DEBUG:
  1197. break;
  1198. case ENGINE_OPTION_PROCESS_MODE:
  1199. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1200. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1201. break;
  1202. case ENGINE_OPTION_TRANSPORT_MODE:
  1203. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1204. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1205. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1206. delete[] pData->options.transportExtra;
  1207. if (value >= ENGINE_TRANSPORT_MODE_DISABLED && valueStr != nullptr)
  1208. pData->options.transportExtra = carla_strdup_safe(valueStr);
  1209. else
  1210. pData->options.transportExtra = nullptr;
  1211. pData->time.setNeedsReset();
  1212. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1213. // enable link now if needed
  1214. {
  1215. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1216. pData->time.enableLink(linkEnabled);
  1217. }
  1218. #endif
  1219. break;
  1220. case ENGINE_OPTION_FORCE_STEREO:
  1221. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1222. pData->options.forceStereo = (value != 0);
  1223. break;
  1224. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1225. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1226. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1227. #else
  1228. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1229. #endif
  1230. pData->options.preferPluginBridges = (value != 0);
  1231. break;
  1232. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1233. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1234. pData->options.preferUiBridges = (value != 0);
  1235. break;
  1236. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1237. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1238. pData->options.uisAlwaysOnTop = (value != 0);
  1239. break;
  1240. case ENGINE_OPTION_MAX_PARAMETERS:
  1241. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1242. pData->options.maxParameters = static_cast<uint>(value);
  1243. break;
  1244. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1245. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1246. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1247. break;
  1248. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1249. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1250. pData->options.audioBufferSize = static_cast<uint>(value);
  1251. break;
  1252. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1253. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1254. pData->options.audioSampleRate = static_cast<uint>(value);
  1255. break;
  1256. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1257. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1258. pData->options.audioTripleBuffer = (value != 0);
  1259. break;
  1260. case ENGINE_OPTION_AUDIO_DEVICE:
  1261. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1262. if (pData->options.audioDevice != nullptr)
  1263. delete[] pData->options.audioDevice;
  1264. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1265. break;
  1266. case ENGINE_OPTION_PLUGIN_PATH:
  1267. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1268. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_SFZ,);
  1269. switch (value)
  1270. {
  1271. case PLUGIN_LADSPA:
  1272. if (pData->options.pathLADSPA != nullptr)
  1273. delete[] pData->options.pathLADSPA;
  1274. if (valueStr != nullptr)
  1275. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1276. else
  1277. pData->options.pathLADSPA = nullptr;
  1278. break;
  1279. case PLUGIN_DSSI:
  1280. if (pData->options.pathDSSI != nullptr)
  1281. delete[] pData->options.pathDSSI;
  1282. if (valueStr != nullptr)
  1283. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1284. else
  1285. pData->options.pathDSSI = nullptr;
  1286. break;
  1287. case PLUGIN_LV2:
  1288. if (pData->options.pathLV2 != nullptr)
  1289. delete[] pData->options.pathLV2;
  1290. if (valueStr != nullptr)
  1291. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1292. else
  1293. pData->options.pathLV2 = nullptr;
  1294. break;
  1295. case PLUGIN_VST2:
  1296. if (pData->options.pathVST2 != nullptr)
  1297. delete[] pData->options.pathVST2;
  1298. if (valueStr != nullptr)
  1299. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1300. else
  1301. pData->options.pathVST2 = nullptr;
  1302. break;
  1303. case PLUGIN_VST3:
  1304. if (pData->options.pathVST3 != nullptr)
  1305. delete[] pData->options.pathVST3;
  1306. if (valueStr != nullptr)
  1307. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1308. else
  1309. pData->options.pathVST3 = nullptr;
  1310. break;
  1311. case PLUGIN_SF2:
  1312. if (pData->options.pathSF2 != nullptr)
  1313. delete[] pData->options.pathSF2;
  1314. if (valueStr != nullptr)
  1315. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1316. else
  1317. pData->options.pathSF2 = nullptr;
  1318. break;
  1319. case PLUGIN_SFZ:
  1320. if (pData->options.pathSFZ != nullptr)
  1321. delete[] pData->options.pathSFZ;
  1322. if (valueStr != nullptr)
  1323. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1324. else
  1325. pData->options.pathSFZ = nullptr;
  1326. break;
  1327. default:
  1328. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type", option, EngineOption2Str(option), value, valueStr);
  1329. break;
  1330. }
  1331. break;
  1332. case ENGINE_OPTION_PATH_BINARIES:
  1333. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1334. if (pData->options.binaryDir != nullptr)
  1335. delete[] pData->options.binaryDir;
  1336. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1337. break;
  1338. case ENGINE_OPTION_PATH_RESOURCES:
  1339. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1340. if (pData->options.resourceDir != nullptr)
  1341. delete[] pData->options.resourceDir;
  1342. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1343. break;
  1344. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1345. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1346. #ifdef CARLA_OS_LINUX
  1347. const ScopedEngineEnvironmentLocker _seel(this);
  1348. if (value != 0)
  1349. {
  1350. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1351. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1352. }
  1353. else
  1354. {
  1355. ::unsetenv("LD_PRELOAD");
  1356. }
  1357. #endif
  1358. } break;
  1359. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1360. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1361. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1362. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1363. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1364. } break;
  1365. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1366. case ENGINE_OPTION_WINE_EXECUTABLE:
  1367. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1368. if (pData->options.wine.executable != nullptr)
  1369. delete[] pData->options.wine.executable;
  1370. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1371. break;
  1372. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1373. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1374. pData->options.wine.autoPrefix = (value != 0);
  1375. break;
  1376. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1377. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1378. if (pData->options.wine.fallbackPrefix != nullptr)
  1379. delete[] pData->options.wine.fallbackPrefix;
  1380. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1381. break;
  1382. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1383. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1384. pData->options.wine.rtPrio = (value != 0);
  1385. break;
  1386. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1387. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1388. pData->options.wine.baseRtPrio = value;
  1389. break;
  1390. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1391. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1392. pData->options.wine.serverRtPrio = value;
  1393. break;
  1394. #endif
  1395. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1396. break;
  1397. }
  1398. }
  1399. #ifndef BUILD_BRIDGE
  1400. // -----------------------------------------------------------------------
  1401. // OSC Stuff
  1402. bool CarlaEngine::isOscControlRegistered() const noexcept
  1403. {
  1404. # ifdef HAVE_LIBLO
  1405. return pData->osc.isControlRegistered();
  1406. # else
  1407. return false;
  1408. # endif
  1409. }
  1410. void CarlaEngine::idleOsc() const noexcept
  1411. {
  1412. # ifdef HAVE_LIBLO
  1413. pData->osc.idle();
  1414. # endif
  1415. }
  1416. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1417. {
  1418. # ifdef HAVE_LIBLO
  1419. return pData->osc.getServerPathTCP();
  1420. # else
  1421. return nullptr;
  1422. # endif
  1423. }
  1424. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1425. {
  1426. # ifdef HAVE_LIBLO
  1427. return pData->osc.getServerPathUDP();
  1428. # else
  1429. return nullptr;
  1430. # endif
  1431. }
  1432. #endif
  1433. // -----------------------------------------------------------------------
  1434. // Helper functions
  1435. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1436. {
  1437. return isInput ? pData->events.in : pData->events.out;
  1438. }
  1439. // -----------------------------------------------------------------------
  1440. // Internal stuff
  1441. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1442. {
  1443. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1444. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1445. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1446. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1447. {
  1448. pData->graph.setBufferSize(newBufferSize);
  1449. }
  1450. #endif
  1451. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1452. for (uint i=0; i < pData->curPluginCount; ++i)
  1453. {
  1454. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1455. if (plugin != nullptr && plugin->isEnabled())
  1456. {
  1457. plugin->tryLock(true);
  1458. plugin->bufferSizeChanged(newBufferSize);
  1459. plugin->unlock();
  1460. }
  1461. }
  1462. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0, 0.0f, nullptr);
  1463. }
  1464. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1465. {
  1466. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1467. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1468. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1469. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1470. {
  1471. pData->graph.setSampleRate(newSampleRate);
  1472. }
  1473. #endif
  1474. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1475. for (uint i=0; i < pData->curPluginCount; ++i)
  1476. {
  1477. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1478. if (plugin != nullptr && plugin->isEnabled())
  1479. {
  1480. plugin->tryLock(true);
  1481. plugin->sampleRateChanged(newSampleRate);
  1482. plugin->unlock();
  1483. }
  1484. }
  1485. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1486. }
  1487. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1488. {
  1489. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1490. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1491. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1492. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1493. {
  1494. pData->graph.setOffline(isOfflineNow);
  1495. }
  1496. #endif
  1497. for (uint i=0; i < pData->curPluginCount; ++i)
  1498. {
  1499. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1500. if (plugin != nullptr && plugin->isEnabled())
  1501. plugin->offlineModeChanged(isOfflineNow);
  1502. }
  1503. }
  1504. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1505. {
  1506. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1507. pluginData.peaks[0] = inPeaks[0];
  1508. pluginData.peaks[1] = inPeaks[1];
  1509. pluginData.peaks[2] = outPeaks[0];
  1510. pluginData.peaks[3] = outPeaks[1];
  1511. }
  1512. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1513. {
  1514. // send initial prepareForSave first, giving time for bridges to act
  1515. for (uint i=0; i < pData->curPluginCount; ++i)
  1516. {
  1517. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1518. if (plugin != nullptr && plugin->isEnabled())
  1519. {
  1520. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1521. // deactivate bridge client-side ping check, since some plugins block during save
  1522. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1523. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1524. #endif
  1525. plugin->prepareForSave();
  1526. }
  1527. }
  1528. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1529. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1530. outStream << "<CARLA-PROJECT VERSION='2.0'>\n";
  1531. const bool isPlugin(getType() == kEngineTypePlugin);
  1532. const EngineOptions& options(pData->options);
  1533. {
  1534. MemoryOutputStream outSettings(1024);
  1535. outSettings << " <EngineSettings>\n";
  1536. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1537. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1538. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1539. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1540. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1541. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1542. if (isPlugin)
  1543. {
  1544. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1545. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1546. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1547. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1548. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1549. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1550. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1551. }
  1552. outSettings << " </EngineSettings>\n";
  1553. outStream << outSettings;
  1554. }
  1555. if (pData->timeInfo.bbt.valid && ! isPlugin)
  1556. {
  1557. MemoryOutputStream outTransport(128);
  1558. outTransport << "\n <Transport>\n";
  1559. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  1560. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  1561. outTransport << " </Transport>\n";
  1562. outStream << outTransport;
  1563. }
  1564. char strBuf[STR_MAX+1];
  1565. for (uint i=0; i < pData->curPluginCount; ++i)
  1566. {
  1567. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1568. if (plugin != nullptr && plugin->isEnabled())
  1569. {
  1570. MemoryOutputStream outPlugin(4096), streamPlugin;
  1571. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1572. outPlugin << "\n";
  1573. strBuf[0] = '\0';
  1574. plugin->getRealName(strBuf);
  1575. if (strBuf[0] != '\0')
  1576. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1577. outPlugin << " <Plugin>\n";
  1578. outPlugin << streamPlugin;
  1579. outPlugin << " </Plugin>\n";
  1580. outStream << outPlugin;
  1581. }
  1582. }
  1583. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1584. // tell bridges we're done saving
  1585. for (uint i=0; i < pData->curPluginCount; ++i)
  1586. {
  1587. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1588. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1589. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1590. }
  1591. // save internal connections
  1592. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1593. {
  1594. if (const char* const* const patchbayConns = getPatchbayConnections(false))
  1595. {
  1596. MemoryOutputStream outPatchbay(2048);
  1597. outPatchbay << "\n <Patchbay>\n";
  1598. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1599. {
  1600. const char* const connSource(patchbayConns[i]);
  1601. const char* const connTarget(patchbayConns[i+1]);
  1602. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1603. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1604. outPatchbay << " <Connection>\n";
  1605. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1606. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1607. outPatchbay << " </Connection>\n";
  1608. }
  1609. outPatchbay << " </Patchbay>\n";
  1610. outStream << outPatchbay;
  1611. }
  1612. }
  1613. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1614. bool saveExternalConnections;
  1615. /**/ if (isPlugin)
  1616. saveExternalConnections = false;
  1617. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1618. saveExternalConnections = true;
  1619. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1620. saveExternalConnections = false;
  1621. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  1622. saveExternalConnections = false;
  1623. else if (std::getenv("NSM_URL") != nullptr)
  1624. saveExternalConnections = false;
  1625. else
  1626. saveExternalConnections = true;
  1627. if (saveExternalConnections)
  1628. {
  1629. if (const char* const* const patchbayConns = getPatchbayConnections(true))
  1630. {
  1631. MemoryOutputStream outPatchbay(2048);
  1632. outPatchbay << "\n <ExternalPatchbay>\n";
  1633. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1634. {
  1635. const char* const connSource(patchbayConns[i]);
  1636. const char* const connTarget(patchbayConns[i+1]);
  1637. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1638. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1639. outPatchbay << " <Connection>\n";
  1640. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1641. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1642. outPatchbay << " </Connection>\n";
  1643. }
  1644. outPatchbay << " </ExternalPatchbay>\n";
  1645. outStream << outPatchbay;
  1646. }
  1647. }
  1648. #endif
  1649. outStream << "</CARLA-PROJECT>\n";
  1650. }
  1651. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  1652. {
  1653. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  1654. // try direct filename first
  1655. String jbinary(binary);
  1656. // adjust for current platform
  1657. #ifdef CARLA_OS_WIN
  1658. if (jbinary[0] == '/')
  1659. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  1660. #else
  1661. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  1662. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  1663. #endif
  1664. String filename = File(jbinary).getFileName();
  1665. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  1666. #ifdef CARLA_OS_MAC
  1667. if (filename.endsWithIgnoreCase(".vst") || filename.endsWithIgnoreCase(".vst3"))
  1668. searchFlags |= File::findDirectories;
  1669. #endif
  1670. Array<File> results;
  1671. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1672. {
  1673. const File path(*it);
  1674. results.clear();
  1675. path.findChildFiles(results, searchFlags, true, filename);
  1676. if (results.size() > 0)
  1677. return results.getFirst().getFullPathName();
  1678. }
  1679. // try changing extension
  1680. #if defined(CARLA_OS_MAC)
  1681. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  1682. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  1683. #elif defined(CARLA_OS_WIN)
  1684. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  1685. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  1686. #else
  1687. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  1688. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  1689. #endif
  1690. else
  1691. return String();
  1692. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1693. {
  1694. const File path(*it);
  1695. results.clear();
  1696. path.findChildFiles(results, searchFlags, true, filename);
  1697. if (results.size() > 0)
  1698. return results.getFirst().getFullPathName();
  1699. }
  1700. return String();
  1701. }
  1702. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc)
  1703. {
  1704. ScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  1705. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  1706. const String& xmlType(xmlElement->getTagName());
  1707. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  1708. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  1709. {
  1710. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  1711. setLastError("Not a valid Carla project or preset file");
  1712. return false;
  1713. }
  1714. pData->actionCanceled = false;
  1715. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 1, 0, 0, 0.0f, "Loading project");
  1716. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1717. const ScopedValueSetter<bool> _svs2(pData->loadingProject, true, false);
  1718. #endif
  1719. // completely load file
  1720. xmlElement = xmlDoc.getDocumentElement(false);
  1721. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  1722. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1723. if (pData->aboutToClose)
  1724. return true;
  1725. if (pData->actionCanceled)
  1726. {
  1727. setLastError("Project load canceled");
  1728. return false;
  1729. }
  1730. const bool isPlugin(getType() == kEngineTypePlugin);
  1731. // load engine settings first of all
  1732. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  1733. {
  1734. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  1735. {
  1736. const String& tag(settElem->getTagName());
  1737. const String text(settElem->getAllSubText().trim());
  1738. /** some settings might be incorrect or require extra work,
  1739. so we call setOption rather than modifying them direly */
  1740. int option = -1;
  1741. int value = 0;
  1742. const char* valueStr = nullptr;
  1743. /**/ if (tag == "ForceStereo")
  1744. {
  1745. option = ENGINE_OPTION_FORCE_STEREO;
  1746. value = text == "true" ? 1 : 0;
  1747. }
  1748. else if (tag == "PreferPluginBridges")
  1749. {
  1750. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  1751. value = text == "true" ? 1 : 0;
  1752. }
  1753. else if (tag == "PreferUiBridges")
  1754. {
  1755. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  1756. value = text == "true" ? 1 : 0;
  1757. }
  1758. else if (tag == "UIsAlwaysOnTop")
  1759. {
  1760. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  1761. value = text == "true" ? 1 : 0;
  1762. }
  1763. else if (tag == "MaxParameters")
  1764. {
  1765. option = ENGINE_OPTION_MAX_PARAMETERS;
  1766. value = text.getIntValue();
  1767. }
  1768. else if (tag == "UIBridgesTimeout")
  1769. {
  1770. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  1771. value = text.getIntValue();
  1772. }
  1773. else if (isPlugin)
  1774. {
  1775. /**/ if (tag == "LADSPA_PATH")
  1776. {
  1777. option = ENGINE_OPTION_PLUGIN_PATH;
  1778. value = PLUGIN_LADSPA;
  1779. valueStr = text.toRawUTF8();
  1780. }
  1781. else if (tag == "DSSI_PATH")
  1782. {
  1783. option = ENGINE_OPTION_PLUGIN_PATH;
  1784. value = PLUGIN_DSSI;
  1785. valueStr = text.toRawUTF8();
  1786. }
  1787. else if (tag == "LV2_PATH")
  1788. {
  1789. option = ENGINE_OPTION_PLUGIN_PATH;
  1790. value = PLUGIN_LV2;
  1791. valueStr = text.toRawUTF8();
  1792. }
  1793. else if (tag == "VST2_PATH")
  1794. {
  1795. option = ENGINE_OPTION_PLUGIN_PATH;
  1796. value = PLUGIN_VST2;
  1797. valueStr = text.toRawUTF8();
  1798. }
  1799. else if (tag.equalsIgnoreCase("VST3_PATH"))
  1800. {
  1801. option = ENGINE_OPTION_PLUGIN_PATH;
  1802. value = PLUGIN_VST3;
  1803. valueStr = text.toRawUTF8();
  1804. }
  1805. else if (tag == "SF2_PATH")
  1806. {
  1807. option = ENGINE_OPTION_PLUGIN_PATH;
  1808. value = PLUGIN_SF2;
  1809. valueStr = text.toRawUTF8();
  1810. }
  1811. else if (tag == "SFZ_PATH")
  1812. {
  1813. option = ENGINE_OPTION_PLUGIN_PATH;
  1814. value = PLUGIN_SFZ;
  1815. valueStr = text.toRawUTF8();
  1816. }
  1817. }
  1818. if (option == -1)
  1819. {
  1820. // check old stuff, unhandled now
  1821. if (tag == "GIG_PATH")
  1822. continue;
  1823. // ignored tags
  1824. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  1825. continue;
  1826. if (tag == "VST3_PATH" || tag == "AU_PATH")
  1827. continue;
  1828. if (tag == "SF2_PATH" || tag == "SFZ_PATH")
  1829. continue;
  1830. // hmm something is wrong..
  1831. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  1832. continue;
  1833. }
  1834. setOption(static_cast<EngineOption>(option), value, valueStr);
  1835. }
  1836. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1837. if (pData->aboutToClose)
  1838. return true;
  1839. if (pData->actionCanceled)
  1840. {
  1841. setLastError("Project load canceled");
  1842. return false;
  1843. }
  1844. }
  1845. // now setup transport
  1846. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  1847. {
  1848. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  1849. {
  1850. const String bpmText(bpmElem->getAllSubText().trim());
  1851. const double bpm = bpmText.getDoubleValue();
  1852. // some sane limits
  1853. if (bpm >= 20.0 && bpm < 400.0)
  1854. pData->time.setBPM(bpm);
  1855. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1856. if (pData->aboutToClose)
  1857. return true;
  1858. if (pData->actionCanceled)
  1859. {
  1860. setLastError("Project load canceled");
  1861. return false;
  1862. }
  1863. }
  1864. }
  1865. // and we handle plugins
  1866. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  1867. {
  1868. const String& tagName(elem->getTagName());
  1869. if (isPreset || tagName == "Plugin")
  1870. {
  1871. CarlaStateSave stateSave;
  1872. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  1873. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1874. if (pData->aboutToClose)
  1875. return true;
  1876. if (pData->actionCanceled)
  1877. {
  1878. setLastError("Project load canceled");
  1879. return false;
  1880. }
  1881. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  1882. #ifndef BUILD_BRIDGE
  1883. // compatibility code to load projects with GIG files
  1884. // FIXME Remove on 2.1 release
  1885. if (std::strcmp(stateSave.type, "GIG") == 0)
  1886. {
  1887. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  1888. {
  1889. const uint pluginId = pData->curPluginCount;
  1890. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1891. {
  1892. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  1893. if (pData->aboutToClose)
  1894. return true;
  1895. if (pData->actionCanceled)
  1896. {
  1897. setLastError("Project load canceled");
  1898. return false;
  1899. }
  1900. String lsState;
  1901. lsState << "0.35\n";
  1902. lsState << "18 0 Chromatic\n";
  1903. lsState << "18 1 Drum Kits\n";
  1904. lsState << "20 0\n";
  1905. lsState << "0 1 " << stateSave.binary << "\n";
  1906. lsState << "0 0 0 0 1 0 GIG\n";
  1907. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  1908. plugin->restoreLV2State();
  1909. plugin->setDryWet(stateSave.dryWet, true, true);
  1910. plugin->setVolume(stateSave.volume, true, true);
  1911. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  1912. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  1913. plugin->setPanning(stateSave.panning, true, true);
  1914. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  1915. plugin->setActive(stateSave.active, true, true);
  1916. ++pData->curPluginCount;
  1917. plugin->setEnabled(true);
  1918. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  1919. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1920. pData->graph.addPlugin(plugin);
  1921. }
  1922. else
  1923. {
  1924. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  1925. }
  1926. }
  1927. else
  1928. {
  1929. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  1930. }
  1931. continue;
  1932. }
  1933. #endif
  1934. const void* extraStuff = nullptr;
  1935. static const char kTrue[] = "true";
  1936. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  1937. switch (ptype)
  1938. {
  1939. case PLUGIN_SF2:
  1940. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  1941. extraStuff = kTrue;
  1942. // fall through
  1943. case PLUGIN_LADSPA:
  1944. case PLUGIN_DSSI:
  1945. case PLUGIN_VST2:
  1946. case PLUGIN_VST3:
  1947. case PLUGIN_SFZ:
  1948. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  1949. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  1950. {
  1951. const char* searchPath;
  1952. switch (ptype)
  1953. {
  1954. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  1955. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  1956. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  1957. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  1958. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  1959. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  1960. default: searchPath = nullptr; break;
  1961. }
  1962. if (searchPath != nullptr && searchPath[0] != '\0')
  1963. {
  1964. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  1965. stateSave.binary);
  1966. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1967. if (result.isEmpty())
  1968. {
  1969. switch (ptype)
  1970. {
  1971. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  1972. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  1973. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  1974. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  1975. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  1976. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  1977. default: searchPath = nullptr; break;
  1978. }
  1979. if (searchPath != nullptr && searchPath[0] != '\0')
  1980. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1981. }
  1982. if (result.isNotEmpty())
  1983. {
  1984. delete[] stateSave.binary;
  1985. stateSave.binary = carla_strdup(result.toRawUTF8());
  1986. carla_stderr("Found it! :)");
  1987. }
  1988. else
  1989. {
  1990. carla_stderr("Damn, we failed... :(");
  1991. }
  1992. }
  1993. }
  1994. break;
  1995. default:
  1996. break;
  1997. }
  1998. BinaryType btype;
  1999. switch (ptype)
  2000. {
  2001. case PLUGIN_LADSPA:
  2002. case PLUGIN_DSSI:
  2003. case PLUGIN_LV2:
  2004. case PLUGIN_VST2:
  2005. btype = getBinaryTypeFromFile(stateSave.binary);
  2006. break;
  2007. default:
  2008. btype = BINARY_NATIVE;
  2009. break;
  2010. }
  2011. if (addPlugin(btype, ptype, stateSave.binary,
  2012. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  2013. {
  2014. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2015. const uint pluginId = pData->curPluginCount;
  2016. #else
  2017. const uint pluginId = 0;
  2018. #endif
  2019. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  2020. {
  2021. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2022. if (pData->aboutToClose)
  2023. return true;
  2024. if (pData->actionCanceled)
  2025. {
  2026. setLastError("Project load canceled");
  2027. return false;
  2028. }
  2029. // deactivate bridge client-side ping check, since some plugins block during load
  2030. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  2031. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  2032. plugin->loadStateSave(stateSave);
  2033. /* NOTE: The following code is the same as the end of addPlugin().
  2034. * When project is loading we do not enable the plugin right away,
  2035. * as we want to load state first.
  2036. */
  2037. plugin->setEnabled(true);
  2038. ++pData->curPluginCount;
  2039. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  2040. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2041. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2042. pData->graph.addPlugin(plugin);
  2043. #endif
  2044. }
  2045. else
  2046. {
  2047. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2048. }
  2049. }
  2050. else
  2051. {
  2052. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  2053. }
  2054. }
  2055. if (isPreset)
  2056. {
  2057. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2058. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2059. return true;
  2060. }
  2061. }
  2062. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2063. // tell bridges we're done loading
  2064. for (uint i=0; i < pData->curPluginCount; ++i)
  2065. {
  2066. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  2067. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2068. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2069. }
  2070. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2071. if (pData->aboutToClose)
  2072. return true;
  2073. if (pData->actionCanceled)
  2074. {
  2075. setLastError("Project load canceled");
  2076. return false;
  2077. }
  2078. bool hasInternalConnections = false;
  2079. // and now we handle connections (internal)
  2080. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  2081. {
  2082. hasInternalConnections = true;
  2083. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2084. {
  2085. CarlaString sourcePort, targetPort;
  2086. const bool isUsingExternal(pData->graph.isUsingExternal());
  2087. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2088. {
  2089. const String& patchTag(patchElem->getTagName());
  2090. if (patchTag != "Connection")
  2091. continue;
  2092. sourcePort.clear();
  2093. targetPort.clear();
  2094. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2095. {
  2096. const String& tag(connElem->getTagName());
  2097. const String text(connElem->getAllSubText().trim());
  2098. /**/ if (tag == "Source")
  2099. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2100. else if (tag == "Target")
  2101. targetPort = xmlSafeString(text, false).toRawUTF8();
  2102. }
  2103. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2104. restorePatchbayConnection(false, sourcePort, targetPort, !isUsingExternal);
  2105. }
  2106. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2107. if (pData->aboutToClose)
  2108. return true;
  2109. if (pData->actionCanceled)
  2110. {
  2111. setLastError("Project load canceled");
  2112. return false;
  2113. }
  2114. }
  2115. }
  2116. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2117. bool loadExternalConnections;
  2118. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2119. loadExternalConnections = true;
  2120. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2121. loadExternalConnections = false;
  2122. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2123. loadExternalConnections = false;
  2124. else if (std::getenv("NSM_URL") != nullptr)
  2125. loadExternalConnections = false;
  2126. else
  2127. loadExternalConnections = true;
  2128. // plus external connections too
  2129. if (loadExternalConnections)
  2130. {
  2131. const bool isUsingExternal = pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY ||
  2132. pData->graph.isUsingExternal();
  2133. const bool loadingAsExternal = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY &&
  2134. hasInternalConnections;
  2135. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2136. {
  2137. const String& tagName(elem->getTagName());
  2138. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2139. if (tagName == "Patchbay")
  2140. {
  2141. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2142. continue;
  2143. }
  2144. // or load external patchbay connections
  2145. else if (tagName != "ExternalPatchbay")
  2146. {
  2147. continue;
  2148. }
  2149. CarlaString sourcePort, targetPort;
  2150. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2151. {
  2152. const String& patchTag(patchElem->getTagName());
  2153. if (patchTag != "Connection")
  2154. continue;
  2155. sourcePort.clear();
  2156. targetPort.clear();
  2157. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2158. {
  2159. const String& tag(connElem->getTagName());
  2160. const String text(connElem->getAllSubText().trim());
  2161. /**/ if (tag == "Source")
  2162. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2163. else if (tag == "Target")
  2164. targetPort = xmlSafeString(text, false).toRawUTF8();
  2165. }
  2166. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2167. restorePatchbayConnection(loadingAsExternal, sourcePort, targetPort, isUsingExternal);
  2168. }
  2169. break;
  2170. }
  2171. }
  2172. #endif
  2173. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2174. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2175. return true;
  2176. }
  2177. // -----------------------------------------------------------------------
  2178. CARLA_BACKEND_END_NAMESPACE