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.

2900 lines
95KB

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