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.

2828 lines
93KB

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