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.

2788 lines
92KB

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