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.

2703 lines
89KB

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