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.

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