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.

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