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.

2233 lines
77KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2017 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 "CarlaStateUtils.hpp"
  31. #include "CarlaMIDI.h"
  32. #include "jackbridge/JackBridge.hpp"
  33. #include "AppConfig.h"
  34. #include "juce_core/juce_core.h"
  35. using juce::Array;
  36. using juce::CharPointer_UTF8;
  37. using juce::File;
  38. using juce::MemoryOutputStream;
  39. using juce::ScopedPointer;
  40. using juce::String;
  41. using juce::StringArray;
  42. using juce::XmlDocument;
  43. using juce::XmlElement;
  44. CARLA_BACKEND_START_NAMESPACE
  45. // -----------------------------------------------------------------------
  46. // Carla Engine
  47. CarlaEngine::CarlaEngine()
  48. : pData(new ProtectedData(this))
  49. {
  50. carla_debug("CarlaEngine::CarlaEngine()");
  51. }
  52. CarlaEngine::~CarlaEngine()
  53. {
  54. carla_debug("CarlaEngine::~CarlaEngine()");
  55. delete pData;
  56. }
  57. // -----------------------------------------------------------------------
  58. // Static calls
  59. uint CarlaEngine::getDriverCount()
  60. {
  61. carla_debug("CarlaEngine::getDriverCount()");
  62. uint count = 0;
  63. if (jackbridge_is_ok())
  64. count += 1;
  65. #ifndef BUILD_BRIDGE
  66. count += getRtAudioApiCount();
  67. #endif
  68. return count;
  69. }
  70. const char* CarlaEngine::getDriverName(const uint index2)
  71. {
  72. carla_debug("CarlaEngine::getDriverName(%i)", index2);
  73. uint index(index2);
  74. if (jackbridge_is_ok() && index-- == 0)
  75. return "JACK";
  76. #ifndef BUILD_BRIDGE
  77. if (const uint count = getRtAudioApiCount())
  78. {
  79. if (index < count)
  80. return getRtAudioApiName(index);
  81. index -= count;
  82. }
  83. #endif
  84. carla_stderr("CarlaEngine::getDriverName(%i) - invalid index", index2);
  85. return nullptr;
  86. }
  87. const char* const* CarlaEngine::getDriverDeviceNames(const uint index2)
  88. {
  89. carla_debug("CarlaEngine::getDriverDeviceNames(%i)", index2);
  90. uint index(index2);
  91. if (jackbridge_is_ok() && index-- == 0)
  92. {
  93. static const char* ret[3] = { "Auto-Connect OFF", "Auto-Connect ON", nullptr };
  94. return ret;
  95. }
  96. #ifndef BUILD_BRIDGE
  97. if (const uint count = getRtAudioApiCount())
  98. {
  99. if (index < count)
  100. return getRtAudioApiDeviceNames(index);
  101. index -= count;
  102. }
  103. #endif
  104. carla_stderr("CarlaEngine::getDriverDeviceNames(%i) - invalid index", index2);
  105. return nullptr;
  106. }
  107. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index2, const char* const deviceName)
  108. {
  109. carla_debug("CarlaEngine::getDriverDeviceInfo(%i, \"%s\")", index2, deviceName);
  110. uint index(index2);
  111. if (jackbridge_is_ok() && index-- == 0)
  112. {
  113. static uint32_t bufSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  114. static EngineDriverDeviceInfo devInfo;
  115. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  116. devInfo.bufferSizes = bufSizes;
  117. devInfo.sampleRates = nullptr;
  118. return &devInfo;
  119. }
  120. #ifndef BUILD_BRIDGE
  121. if (const uint count = getRtAudioApiCount())
  122. {
  123. if (index < count)
  124. return getRtAudioDeviceInfo(index, deviceName);
  125. index -= count;
  126. }
  127. #endif
  128. carla_stderr("CarlaEngine::getDriverDeviceNames(%i, \"%s\") - invalid index", index2, deviceName);
  129. return nullptr;
  130. }
  131. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  132. {
  133. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  134. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  135. if (std::strcmp(driverName, "JACK") == 0)
  136. return newJack();
  137. #ifndef BUILD_BRIDGE
  138. // -------------------------------------------------------------------
  139. // common
  140. if (std::strncmp(driverName, "JACK ", 5) == 0)
  141. return newRtAudio(AUDIO_API_JACK);
  142. if (std::strcmp(driverName, "OSS") == 0)
  143. return newRtAudio(AUDIO_API_OSS);
  144. // -------------------------------------------------------------------
  145. // linux
  146. if (std::strcmp(driverName, "ALSA") == 0)
  147. return newRtAudio(AUDIO_API_ALSA);
  148. if (std::strcmp(driverName, "PulseAudio") == 0)
  149. return newRtAudio(AUDIO_API_PULSEAUDIO);
  150. // -------------------------------------------------------------------
  151. // macos
  152. if (std::strcmp(driverName, "CoreAudio") == 0)
  153. return newRtAudio(AUDIO_API_COREAUDIO);
  154. // -------------------------------------------------------------------
  155. // windows
  156. if (std::strcmp(driverName, "ASIO") == 0)
  157. return newRtAudio(AUDIO_API_ASIO);
  158. if (std::strcmp(driverName, "DirectSound") == 0)
  159. return newRtAudio(AUDIO_API_DIRECTSOUND);
  160. if (std::strcmp(driverName, "WASAPI") == 0)
  161. return newRtAudio(AUDIO_API_WASAPI);
  162. #endif
  163. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  164. return nullptr;
  165. }
  166. // -----------------------------------------------------------------------
  167. // Constant values
  168. uint CarlaEngine::getMaxClientNameSize() const noexcept
  169. {
  170. return STR_MAX/2;
  171. }
  172. uint CarlaEngine::getMaxPortNameSize() const noexcept
  173. {
  174. return STR_MAX;
  175. }
  176. uint CarlaEngine::getCurrentPluginCount() const noexcept
  177. {
  178. return pData->curPluginCount;
  179. }
  180. uint CarlaEngine::getMaxPluginNumber() const noexcept
  181. {
  182. return pData->maxPluginNumber;
  183. }
  184. // -----------------------------------------------------------------------
  185. // Virtual, per-engine type calls
  186. bool CarlaEngine::close()
  187. {
  188. carla_debug("CarlaEngine::close()");
  189. if (pData->curPluginCount != 0)
  190. {
  191. pData->aboutToClose = true;
  192. removeAllPlugins();
  193. }
  194. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  195. if (pData->osc.isControlRegistered())
  196. oscSend_control_exit();
  197. #endif
  198. pData->close();
  199. callback(ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  200. return true;
  201. }
  202. bool CarlaEngine::usesConstantBufferSize() const noexcept
  203. {
  204. return true;
  205. }
  206. void CarlaEngine::idle() noexcept
  207. {
  208. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,); // FIXME REMOVE
  209. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  210. CARLA_SAFE_ASSERT_RETURN(getType() != kEngineTypePlugin,);
  211. for (uint i=0; i < pData->curPluginCount; ++i)
  212. {
  213. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  214. if (plugin != nullptr && plugin->isEnabled())
  215. {
  216. const uint hints(plugin->getHints());
  217. if ((hints & PLUGIN_HAS_CUSTOM_UI) != 0 && (hints & PLUGIN_NEEDS_UI_MAIN_THREAD) != 0)
  218. {
  219. try {
  220. plugin->uiIdle();
  221. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  222. }
  223. }
  224. }
  225. #ifdef HAVE_LIBLO
  226. pData->osc.idle();
  227. #endif
  228. }
  229. CarlaEngineClient* CarlaEngine::addClient(CarlaPlugin* const)
  230. {
  231. return new CarlaEngineClient(*this);
  232. }
  233. // -----------------------------------------------------------------------
  234. // Plugin management
  235. bool CarlaEngine::addPlugin(const BinaryType btype, const PluginType ptype,
  236. const char* const filename, const char* const name, const char* const label, const int64_t uniqueId,
  237. const void* const extra, const uint options)
  238. {
  239. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  240. #ifndef BUILD_BRIDGE
  241. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  242. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  243. #endif
  244. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  245. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  246. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  247. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  248. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p, %u)", btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra, options);
  249. uint id;
  250. #ifndef BUILD_BRIDGE
  251. CarlaPlugin* oldPlugin = nullptr;
  252. if (pData->nextPluginId < pData->curPluginCount)
  253. {
  254. id = pData->nextPluginId;
  255. pData->nextPluginId = pData->maxPluginNumber;
  256. oldPlugin = pData->plugins[id].plugin;
  257. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin != nullptr, "Invalid replace plugin Id");
  258. }
  259. else
  260. #endif
  261. {
  262. id = pData->curPluginCount;
  263. if (id == pData->maxPluginNumber)
  264. {
  265. setLastError("Maximum number of plugins reached");
  266. return false;
  267. }
  268. #ifndef BUILD_BRIDGE
  269. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin == nullptr, "Invalid engine internal data");
  270. #endif
  271. }
  272. CarlaPlugin::Initializer initializer = {
  273. this,
  274. id,
  275. filename,
  276. name,
  277. label,
  278. uniqueId,
  279. options
  280. };
  281. CarlaPlugin* plugin = nullptr;
  282. CarlaString bridgeBinary(pData->options.binaryDir);
  283. if (bridgeBinary.isNotEmpty())
  284. {
  285. if (btype == BINARY_NATIVE)
  286. {
  287. #ifdef CARLA_OS_WIN
  288. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native.exe";
  289. #else
  290. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  291. #endif
  292. }
  293. else
  294. {
  295. switch (btype)
  296. {
  297. case BINARY_POSIX32:
  298. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  299. break;
  300. case BINARY_POSIX64:
  301. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  302. break;
  303. case BINARY_WIN32:
  304. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  305. break;
  306. case BINARY_WIN64:
  307. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  308. break;
  309. default:
  310. bridgeBinary.clear();
  311. break;
  312. }
  313. }
  314. if (! File(bridgeBinary.buffer()).existsAsFile())
  315. bridgeBinary.clear();
  316. }
  317. // Prefer bridges for some specific plugins
  318. bool preferBridges = pData->options.preferPluginBridges;
  319. #ifndef BUILD_BRIDGE
  320. if (! preferBridges)
  321. {
  322. if (ptype == PLUGIN_LV2 && label != nullptr)
  323. {
  324. if (std::strncmp(label, "http://calf.sourceforge.net/plugins/", 36) == 0 ||
  325. std::strcmp(label, "http://factorial.hu/plugins/lv2/ir") == 0 ||
  326. std::strstr(label, "v1.sourceforge.net/lv2") != nullptr)
  327. {
  328. preferBridges = true;
  329. }
  330. }
  331. # if 0
  332. else if (ptype == PLUGIN_VST2)
  333. {
  334. /*
  335. char uniqueIdChars[5] = {
  336. static_cast<char>((uniqueId & 0xFF000000) >> 24),
  337. static_cast<char>((uniqueId & 0x00FF0000) >> 16),
  338. static_cast<char>((uniqueId & 0x0000FF00) >> 8),
  339. static_cast<char>((uniqueId & 0x000000FF) >> 1),
  340. 0
  341. };
  342. */
  343. /**/ if (uniqueId == 1633895765 && std::strstr(filename, "/ACE.") != nullptr)
  344. preferBridges = true;
  345. else if (uniqueId == 1433421876 && std::strstr(filename, "/Bazille.") != nullptr)
  346. preferBridges = true;
  347. else if (uniqueId == 1147754081 && std::strstr(filename, "/Diva.") != nullptr)
  348. preferBridges = true;
  349. else if (uniqueId == 1095583057 && std::strstr(filename, "/Filterscape.") != nullptr)
  350. preferBridges = true;
  351. else if (uniqueId == 1179866689 && std::strstr(filename, "/Filterscape.") != nullptr)
  352. preferBridges = true;
  353. else if (uniqueId == 1179865398 && std::strstr(filename, "/Filterscape.") != nullptr)
  354. preferBridges = true;
  355. else if (uniqueId == 1749636677 && std::strstr(filename, "/Hive.") != nullptr)
  356. preferBridges = true;
  357. else if (uniqueId == 1296452914 && std::strstr(filename, "/MFM2.") != nullptr)
  358. preferBridges = true;
  359. else if (uniqueId == 1349477487 && std::strstr(filename, "/Podolski.") != nullptr)
  360. preferBridges = true;
  361. else if (uniqueId == 1886548821 && std::strstr(filename, "/Presswerk.") != nullptr)
  362. preferBridges = true;
  363. else if (uniqueId == 1969770582 && std::strstr(filename, "/Protoverb.") != nullptr)
  364. preferBridges = true;
  365. else if (uniqueId == 1969771348 && std::strstr(filename, "/Satin.") != nullptr)
  366. preferBridges = true;
  367. else if (uniqueId == 1667388281 && std::strstr(filename, "/TripleCheese.") != nullptr)
  368. preferBridges = true;
  369. else if (uniqueId == 1952017974 && std::strstr(filename, "/TyrellN6.") != nullptr)
  370. preferBridges = true;
  371. else if (uniqueId == 1432568113 && std::strstr(filename, "/Uhbik.") != nullptr)
  372. preferBridges = true;
  373. else if (uniqueId == 1432568881 && std::strstr(filename, "/Uhbik.") != nullptr)
  374. preferBridges = true;
  375. else if (uniqueId == 1432572209 && std::strstr(filename, "/Uhbik.") != nullptr)
  376. preferBridges = true;
  377. else if (uniqueId == 1432569393 && std::strstr(filename, "/Uhbik.") != nullptr)
  378. preferBridges = true;
  379. else if (uniqueId == 1432569649 && std::strstr(filename, "/Uhbik.") != nullptr)
  380. preferBridges = true;
  381. else if (uniqueId == 1432571953 && std::strstr(filename, "/Uhbik.") != nullptr)
  382. preferBridges = true;
  383. else if (uniqueId == 1382232375 && std::strstr(filename, "/Uhbik.") != nullptr)
  384. preferBridges = true;
  385. else if (uniqueId == 1432572721 && std::strstr(filename, "/Uhbik.") != nullptr)
  386. preferBridges = true;
  387. else if (uniqueId == 1432572977 && std::strstr(filename, "/Uhbik.") != nullptr)
  388. preferBridges = true;
  389. else if (uniqueId == 1397572658 && std::strstr(filename, "/Zebra2.") != nullptr)
  390. preferBridges = true;
  391. else if (uniqueId == 1397572659 && std::strstr(filename, "/Zebra2.") != nullptr)
  392. preferBridges = true;
  393. else if (uniqueId == 1919243824 && std::strstr(filename, "/Zebra2.") != nullptr)
  394. preferBridges = true;
  395. else if (uniqueId == 1397578034 && std::strstr(filename, "/Zebra2.") != nullptr)
  396. preferBridges = true;
  397. else if (uniqueId == 1397573722 && std::strstr(filename, "/ZebraHZ.") != nullptr)
  398. preferBridges = true;
  399. }
  400. # endif
  401. // FIXME: linuxsampler inside carla-rack/patchbay plugin has some issues (only last kit makes noise)
  402. else if (getType() == kEngineTypePlugin && (ptype == PLUGIN_GIG || ptype == PLUGIN_SFZ))
  403. {
  404. // if we're not loading a project consider all is ok
  405. if (! pData->loadingProject)
  406. pData->firstLinuxSamplerInstance = true;
  407. // loading a project, revert first status if set
  408. else if (pData->firstLinuxSamplerInstance)
  409. pData->firstLinuxSamplerInstance = false;
  410. // now check if bridge is needed
  411. if (! pData->firstLinuxSamplerInstance)
  412. preferBridges = true;
  413. }
  414. }
  415. #endif // ! BUILD_BRIDGE
  416. if (ptype != PLUGIN_INTERNAL && (btype != BINARY_NATIVE || (preferBridges && bridgeBinary.isNotEmpty())))
  417. {
  418. if (bridgeBinary.isNotEmpty())
  419. {
  420. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, bridgeBinary);
  421. }
  422. else
  423. {
  424. setLastError("This Carla build cannot handle this binary");
  425. return false;
  426. }
  427. }
  428. else
  429. {
  430. bool use16Outs;
  431. setLastError("Invalid or unsupported plugin type");
  432. switch (ptype)
  433. {
  434. case PLUGIN_NONE:
  435. break;
  436. case PLUGIN_INTERNAL:
  437. /*if (std::strcmp(label, "FluidSynth") == 0)
  438. {
  439. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  440. plugin = CarlaPlugin::newFluidSynth(initializer, use16Outs);
  441. }
  442. else if (std::strcmp(label, "LinuxSampler (GIG)") == 0)
  443. {
  444. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  445. plugin = CarlaPlugin::newLinuxSampler(initializer, "GIG", use16Outs);
  446. }
  447. else if (std::strcmp(label, "LinuxSampler (SF2)") == 0)
  448. {
  449. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  450. plugin = CarlaPlugin::newLinuxSampler(initializer, "SF2", use16Outs);
  451. }
  452. else if (std::strcmp(label, "LinuxSampler (SFZ)") == 0)
  453. {
  454. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  455. plugin = CarlaPlugin::newLinuxSampler(initializer, "SFZ", use16Outs);
  456. }*/
  457. plugin = CarlaPlugin::newNative(initializer);
  458. break;
  459. case PLUGIN_LADSPA:
  460. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  461. break;
  462. case PLUGIN_DSSI:
  463. // TODO remove this
  464. if (CarlaString(filename).contains("dssi-vst", true))
  465. {
  466. const ScopedEngineEnvironmentLocker _seel(this);
  467. const ScopedEnvVar _sev("VST_PATH", pData->options.pathVST2);
  468. plugin = CarlaPlugin::newDSSI(initializer);
  469. }
  470. else
  471. {
  472. plugin = CarlaPlugin::newDSSI(initializer);
  473. }
  474. break;
  475. case PLUGIN_LV2:
  476. plugin = CarlaPlugin::newLV2(initializer);
  477. break;
  478. case PLUGIN_VST2:
  479. plugin = CarlaPlugin::newVST2(initializer);
  480. break;
  481. case PLUGIN_GIG:
  482. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  483. plugin = CarlaPlugin::newFileGIG(initializer, use16Outs);
  484. break;
  485. case PLUGIN_SF2:
  486. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  487. plugin = CarlaPlugin::newFileSF2(initializer, use16Outs);
  488. break;
  489. case PLUGIN_SFZ:
  490. plugin = CarlaPlugin::newFileSFZ(initializer);
  491. break;
  492. case PLUGIN_JACK:
  493. plugin = CarlaPlugin::newJackApp(initializer);
  494. break;
  495. }
  496. }
  497. if (plugin == nullptr)
  498. return false;
  499. plugin->reload();
  500. #ifndef BUILD_BRIDGE
  501. bool canRun = true;
  502. /**/ if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  503. {
  504. /**/ if (! plugin->canRunInRack())
  505. {
  506. setLastError("Carla's rack mode can only work with Mono or Stereo plugins, sorry!");
  507. canRun = false;
  508. }
  509. else if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  510. {
  511. setLastError("Carla's rack mode cannot work with plugins that have CV ports, sorry!");
  512. canRun = false;
  513. }
  514. }
  515. if (! canRun)
  516. {
  517. delete plugin;
  518. return false;
  519. }
  520. # ifdef HAVE_LIBLO
  521. plugin->registerToOscClient();
  522. # endif
  523. #endif
  524. EnginePluginData& pluginData(pData->plugins[id]);
  525. pluginData.plugin = plugin;
  526. pluginData.insPeak[0] = 0.0f;
  527. pluginData.insPeak[1] = 0.0f;
  528. pluginData.outsPeak[0] = 0.0f;
  529. pluginData.outsPeak[1] = 0.0f;
  530. #ifndef BUILD_BRIDGE
  531. if (oldPlugin != nullptr)
  532. {
  533. CARLA_SAFE_ASSERT(! pData->loadingProject);
  534. const ScopedThreadStopper sts(this);
  535. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  536. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  537. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  538. delete oldPlugin;
  539. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  540. plugin->setDryWet(oldDryWet, true, true);
  541. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  542. plugin->setVolume(oldVolume, true, true);
  543. plugin->setActive(wasActive, true, true);
  544. plugin->setEnabled(true);
  545. callback(ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0.0f, nullptr);
  546. }
  547. else if (! pData->loadingProject)
  548. #endif
  549. {
  550. plugin->setActive(true, true, false);
  551. plugin->setEnabled(true);
  552. ++pData->curPluginCount;
  553. callback(ENGINE_CALLBACK_PLUGIN_ADDED, id, 0, 0, 0.0f, plugin->getName());
  554. }
  555. return true;
  556. }
  557. 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)
  558. {
  559. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra, 0x0);
  560. }
  561. bool CarlaEngine::removePlugin(const uint id)
  562. {
  563. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  564. #ifndef BUILD_BRIDGE
  565. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  566. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  567. #endif
  568. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  569. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  570. carla_debug("CarlaEngine::removePlugin(%i)", id);
  571. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  572. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to remove");
  573. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  574. const ScopedThreadStopper sts(this);
  575. #ifndef BUILD_BRIDGE
  576. const bool lockWait(isRunning() /*&& pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS*/);
  577. const ScopedActionLock sal(this, kEnginePostActionRemovePlugin, id, 0, lockWait);
  578. /*
  579. for (uint i=id; i < pData->curPluginCount; ++i)
  580. {
  581. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  582. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  583. plugin2->updateOscURL();
  584. }
  585. */
  586. # ifdef HAVE_LIBLO
  587. if (isOscControlRegistered())
  588. oscSend_control_remove_plugin(id);
  589. # endif
  590. #else
  591. pData->curPluginCount = 0;
  592. carla_zeroStructs(pData->plugins, 1);
  593. #endif
  594. delete plugin;
  595. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0.0f, nullptr);
  596. return true;
  597. }
  598. bool CarlaEngine::removeAllPlugins()
  599. {
  600. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  601. #ifndef BUILD_BRIDGE
  602. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  603. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  604. #endif
  605. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  606. carla_debug("CarlaEngine::removeAllPlugins()");
  607. if (pData->curPluginCount == 0)
  608. return true;
  609. const ScopedThreadStopper sts(this);
  610. const uint curPluginCount(pData->curPluginCount);
  611. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  612. if (isOscControlRegistered())
  613. {
  614. for (uint i=0; i < curPluginCount; ++i)
  615. oscSend_control_remove_plugin(curPluginCount-i-1);
  616. }
  617. #endif
  618. const bool lockWait(isRunning());
  619. const ScopedActionLock sal(this, kEnginePostActionZeroCount, 0, 0, lockWait);
  620. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  621. for (uint i=0; i < curPluginCount; ++i)
  622. {
  623. EnginePluginData& pluginData(pData->plugins[i]);
  624. if (pluginData.plugin != nullptr)
  625. {
  626. delete pluginData.plugin;
  627. pluginData.plugin = nullptr;
  628. }
  629. pluginData.insPeak[0] = 0.0f;
  630. pluginData.insPeak[1] = 0.0f;
  631. pluginData.outsPeak[0] = 0.0f;
  632. pluginData.outsPeak[1] = 0.0f;
  633. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  634. }
  635. return true;
  636. }
  637. #ifndef BUILD_BRIDGE
  638. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  639. {
  640. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  641. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  642. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  643. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  644. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  645. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  646. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  647. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  648. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  649. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  650. const char* const uniqueName(getUniquePluginName(newName));
  651. CARLA_SAFE_ASSERT_RETURN_ERRN(uniqueName != nullptr, "Unable to get new unique plugin name");
  652. plugin->setName(uniqueName);
  653. delete[] uniqueName;
  654. return plugin->getName();
  655. }
  656. bool CarlaEngine::clonePlugin(const uint id)
  657. {
  658. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  659. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  660. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  661. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  662. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  663. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  664. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  665. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  666. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  667. char label[STR_MAX+1];
  668. carla_zeroChars(label, STR_MAX+1);
  669. plugin->getLabel(label);
  670. const uint pluginCountBefore(pData->curPluginCount);
  671. if (! addPlugin(plugin->getBinaryType(), plugin->getType(),
  672. plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(),
  673. plugin->getExtraStuff(), plugin->getOptionsEnabled()))
  674. return false;
  675. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  676. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  677. newPlugin->loadStateSave(plugin->getStateSave());
  678. return true;
  679. }
  680. bool CarlaEngine::replacePlugin(const uint id) noexcept
  681. {
  682. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  683. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  684. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  685. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  686. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  687. // might use this to reset
  688. if (id == pData->maxPluginNumber)
  689. {
  690. pData->nextPluginId = pData->maxPluginNumber;
  691. return true;
  692. }
  693. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  694. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  695. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  696. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  697. pData->nextPluginId = id;
  698. return true;
  699. }
  700. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  701. {
  702. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  703. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  704. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  705. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  706. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  707. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  708. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  709. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  710. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  711. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  712. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  713. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  714. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  715. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  716. const ScopedThreadStopper sts(this);
  717. const bool lockWait(isRunning() /*&& pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS*/);
  718. const ScopedActionLock sal(this, kEnginePostActionSwitchPlugins, idA, idB, lockWait);
  719. // TODO
  720. /*
  721. pluginA->updateOscURL();
  722. pluginB->updateOscURL();
  723. if (isOscControlRegistered())
  724. oscSend_control_switch_plugins(idA, idB);
  725. */
  726. return true;
  727. }
  728. #endif
  729. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const noexcept
  730. {
  731. #ifndef BUILD_BRIDGE
  732. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  733. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  734. #endif
  735. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  736. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  737. return pData->plugins[id].plugin;
  738. }
  739. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  740. {
  741. return pData->plugins[id].plugin;
  742. }
  743. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  744. {
  745. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  746. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  747. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  748. CarlaString sname;
  749. sname = name;
  750. if (sname.isEmpty())
  751. {
  752. sname = "(No name)";
  753. return sname.dup();
  754. }
  755. const std::size_t maxNameSize(carla_minConstrained<uint>(getMaxClientNameSize(), 0xff, 6U) - 6); // 6 = strlen(" (10)") + 1
  756. if (maxNameSize == 0 || ! isRunning())
  757. return sname.dup();
  758. sname.truncate(maxNameSize);
  759. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  760. for (uint i=0; i < pData->curPluginCount; ++i)
  761. {
  762. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  763. // Check if unique name doesn't exist
  764. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  765. {
  766. if (sname != pluginName)
  767. continue;
  768. }
  769. // Check if string has already been modified
  770. {
  771. const std::size_t len(sname.length());
  772. // 1 digit, ex: " (2)"
  773. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  774. {
  775. const int number = sname[len-2] - '0';
  776. if (number == 9)
  777. {
  778. // next number is 10, 2 digits
  779. sname.truncate(len-4);
  780. sname += " (10)";
  781. //sname.replace(" (9)", " (10)");
  782. }
  783. else
  784. sname[len-2] = char('0' + number + 1);
  785. continue;
  786. }
  787. // 2 digits, ex: " (11)"
  788. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  789. {
  790. char n2 = sname[len-2];
  791. char n3 = sname[len-3];
  792. if (n2 == '9')
  793. {
  794. n2 = '0';
  795. n3 = static_cast<char>(n3 + 1);
  796. }
  797. else
  798. n2 = static_cast<char>(n2 + 1);
  799. sname[len-2] = n2;
  800. sname[len-3] = n3;
  801. continue;
  802. }
  803. }
  804. // Modify string if not
  805. sname += " (2)";
  806. }
  807. return sname.dup();
  808. }
  809. // -----------------------------------------------------------------------
  810. // Project management
  811. bool CarlaEngine::loadFile(const char* const filename)
  812. {
  813. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  814. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  815. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  816. const String jfilename = String(CharPointer_UTF8(filename));
  817. File file(jfilename);
  818. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  819. CarlaString baseName(file.getFileNameWithoutExtension().toRawUTF8());
  820. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  821. const uint curPluginId(pData->nextPluginId < pData->curPluginCount ? pData->nextPluginId : pData->curPluginCount);
  822. // -------------------------------------------------------------------
  823. if (extension == "carxp" || extension == "carxs")
  824. return loadProject(filename);
  825. // -------------------------------------------------------------------
  826. if (extension == "gig")
  827. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  828. if (extension == "sf2")
  829. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  830. if (extension == "sfz")
  831. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  832. // -------------------------------------------------------------------
  833. if (extension == "aif" || extension == "aiff" || extension == "bwf" || extension == "flac" || extension == "ogg" || extension == "wav")
  834. {
  835. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  836. {
  837. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  838. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  839. return true;
  840. }
  841. return false;
  842. }
  843. // -------------------------------------------------------------------
  844. if (extension == "mid" || extension == "midi")
  845. {
  846. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  847. {
  848. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  849. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  850. return true;
  851. }
  852. return false;
  853. }
  854. // -------------------------------------------------------------------
  855. // ZynAddSubFX
  856. if (extension == "xmz" || extension == "xiz")
  857. {
  858. #ifdef HAVE_ZYN_DEPS
  859. CarlaString nicerName("Zyn - ");
  860. const std::size_t sep(baseName.find('-')+1);
  861. if (sep < baseName.length())
  862. nicerName += baseName.buffer()+sep;
  863. else
  864. nicerName += baseName;
  865. //nicerName
  866. if (addPlugin(PLUGIN_INTERNAL, nullptr, nicerName, "zynaddsubfx", 0, nullptr))
  867. {
  868. callback(ENGINE_CALLBACK_UI_STATE_CHANGED, curPluginId, 0, 0, 0.0f, nullptr);
  869. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  870. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  871. return true;
  872. }
  873. return false;
  874. #else
  875. setLastError("This Carla build does not have ZynAddSubFX support");
  876. return false;
  877. #endif
  878. }
  879. // -------------------------------------------------------------------
  880. // Direct plugin binaries
  881. #ifdef CARLA_OS_MAC
  882. if (extension == "vst")
  883. return addPlugin(PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  884. #else
  885. if (extension == "dll" || extension == "so")
  886. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr, 0x0);
  887. #endif
  888. // -------------------------------------------------------------------
  889. setLastError("Unknown file extension");
  890. return false;
  891. }
  892. bool CarlaEngine::loadProject(const char* const filename)
  893. {
  894. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  895. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  896. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  897. const String jfilename = String(CharPointer_UTF8(filename));
  898. File file(jfilename);
  899. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  900. XmlDocument xml(file);
  901. return loadProjectInternal(xml);
  902. }
  903. bool CarlaEngine::saveProject(const char* const filename)
  904. {
  905. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  906. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  907. MemoryOutputStream out;
  908. saveProjectInternal(out);
  909. const String jfilename = String(CharPointer_UTF8(filename));
  910. File file(jfilename);
  911. if (file.replaceWithData(out.getData(), out.getDataSize()))
  912. return true;
  913. setLastError("Failed to write file");
  914. return false;
  915. }
  916. // -----------------------------------------------------------------------
  917. // Information (base)
  918. uint CarlaEngine::getHints() const noexcept
  919. {
  920. return pData->hints;
  921. }
  922. uint32_t CarlaEngine::getBufferSize() const noexcept
  923. {
  924. return pData->bufferSize;
  925. }
  926. double CarlaEngine::getSampleRate() const noexcept
  927. {
  928. return pData->sampleRate;
  929. }
  930. const char* CarlaEngine::getName() const noexcept
  931. {
  932. return pData->name;
  933. }
  934. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  935. {
  936. return pData->options.processMode;
  937. }
  938. const EngineOptions& CarlaEngine::getOptions() const noexcept
  939. {
  940. return pData->options;
  941. }
  942. const EngineTimeInfo& CarlaEngine::getTimeInfo() const noexcept
  943. {
  944. return pData->timeInfo;
  945. }
  946. // -----------------------------------------------------------------------
  947. // Information (peaks)
  948. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  949. {
  950. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  951. return pData->plugins[pluginId].insPeak[isLeft ? 0 : 1];
  952. }
  953. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  954. {
  955. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  956. return pData->plugins[pluginId].outsPeak[isLeft ? 0 : 1];
  957. }
  958. // -----------------------------------------------------------------------
  959. // Callback
  960. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  961. {
  962. #ifdef DEBUG
  963. if (action != ENGINE_CALLBACK_IDLE)
  964. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  965. #endif
  966. #ifdef BUILD_BRIDGE
  967. if (pData->isIdling)
  968. #else
  969. if (pData->isIdling && action != ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED)
  970. #endif
  971. {
  972. carla_stdout("callback while idling (%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  973. }
  974. if (pData->callback != nullptr)
  975. {
  976. if (action == ENGINE_CALLBACK_IDLE)
  977. ++pData->isIdling;
  978. try {
  979. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  980. #if defined(CARLA_OS_LINUX) && defined(__arm__)
  981. } catch (__cxxabiv1::__forced_unwind&) {
  982. carla_stderr2("Caught forced unwind exception in callback");
  983. throw;
  984. #endif
  985. } catch (...) {
  986. carla_safe_exception("callback", __FILE__, __LINE__);
  987. }
  988. if (action == ENGINE_CALLBACK_IDLE)
  989. --pData->isIdling;
  990. }
  991. }
  992. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  993. {
  994. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  995. pData->callback = func;
  996. pData->callbackPtr = ptr;
  997. }
  998. // -----------------------------------------------------------------------
  999. // File Callback
  1000. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1001. {
  1002. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1003. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1004. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1005. const char* ret = nullptr;
  1006. if (pData->fileCallback != nullptr)
  1007. {
  1008. try {
  1009. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1010. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1011. }
  1012. return ret;
  1013. }
  1014. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1015. {
  1016. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1017. pData->fileCallback = func;
  1018. pData->fileCallbackPtr = ptr;
  1019. }
  1020. // -----------------------------------------------------------------------
  1021. // Transport
  1022. void CarlaEngine::transportPlay() noexcept
  1023. {
  1024. pData->timeInfo.playing = true;
  1025. pData->time.setNeedsReset();
  1026. }
  1027. void CarlaEngine::transportPause() noexcept
  1028. {
  1029. pData->timeInfo.playing = false;
  1030. pData->time.setNeedsReset();
  1031. }
  1032. void CarlaEngine::transportBPM(const double bpm) noexcept
  1033. {
  1034. try {
  1035. pData->time.setBPM(bpm);
  1036. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1037. }
  1038. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1039. {
  1040. pData->time.relocate(frame);
  1041. }
  1042. // -----------------------------------------------------------------------
  1043. // Error handling
  1044. const char* CarlaEngine::getLastError() const noexcept
  1045. {
  1046. return pData->lastError;
  1047. }
  1048. void CarlaEngine::setLastError(const char* const error) const noexcept
  1049. {
  1050. pData->lastError = error;
  1051. }
  1052. // -----------------------------------------------------------------------
  1053. // Misc
  1054. bool CarlaEngine::isAboutToClose() const noexcept
  1055. {
  1056. return pData->aboutToClose;
  1057. }
  1058. bool CarlaEngine::setAboutToClose() noexcept
  1059. {
  1060. carla_debug("CarlaEngine::setAboutToClose()");
  1061. pData->aboutToClose = true;
  1062. return (pData->isIdling == 0);
  1063. }
  1064. // -----------------------------------------------------------------------
  1065. // Global options
  1066. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1067. {
  1068. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1069. if (isRunning() && (option == ENGINE_OPTION_PROCESS_MODE || option == ENGINE_OPTION_AUDIO_NUM_PERIODS || option == ENGINE_OPTION_AUDIO_DEVICE))
  1070. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!", option, EngineOption2Str(option), value, valueStr);
  1071. // do not un-force stereo for rack mode
  1072. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1073. return;
  1074. switch (option)
  1075. {
  1076. case ENGINE_OPTION_DEBUG:
  1077. break;
  1078. case ENGINE_OPTION_PROCESS_MODE:
  1079. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1080. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1081. break;
  1082. case ENGINE_OPTION_TRANSPORT_MODE:
  1083. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_INTERNAL && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1084. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1085. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1086. delete[] pData->options.transportExtra;
  1087. pData->options.transportExtra = (valueStr != nullptr) ? carla_strdup_safe(valueStr) : nullptr;
  1088. pData->time.setNeedsReset();
  1089. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1090. // enable link now if needed
  1091. {
  1092. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1093. pData->time.enableLink(linkEnabled);
  1094. }
  1095. #endif
  1096. break;
  1097. case ENGINE_OPTION_FORCE_STEREO:
  1098. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1099. pData->options.forceStereo = (value != 0);
  1100. break;
  1101. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1102. #ifdef BUILD_BRIDGE
  1103. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1104. #else
  1105. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1106. #endif
  1107. pData->options.preferPluginBridges = (value != 0);
  1108. break;
  1109. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1110. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1111. pData->options.preferUiBridges = (value != 0);
  1112. break;
  1113. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1114. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1115. pData->options.uisAlwaysOnTop = (value != 0);
  1116. break;
  1117. case ENGINE_OPTION_MAX_PARAMETERS:
  1118. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1119. pData->options.maxParameters = static_cast<uint>(value);
  1120. break;
  1121. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1122. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1123. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1124. break;
  1125. case ENGINE_OPTION_AUDIO_NUM_PERIODS:
  1126. CARLA_SAFE_ASSERT_RETURN(value >= 2 && value <= 3,);
  1127. pData->options.audioNumPeriods = static_cast<uint>(value);
  1128. break;
  1129. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1130. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1131. pData->options.audioBufferSize = static_cast<uint>(value);
  1132. break;
  1133. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1134. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1135. pData->options.audioSampleRate = static_cast<uint>(value);
  1136. break;
  1137. case ENGINE_OPTION_AUDIO_DEVICE:
  1138. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1139. if (pData->options.audioDevice != nullptr)
  1140. delete[] pData->options.audioDevice;
  1141. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1142. break;
  1143. case ENGINE_OPTION_PLUGIN_PATH:
  1144. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1145. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_SFZ,);
  1146. switch (value)
  1147. {
  1148. case PLUGIN_LADSPA:
  1149. if (pData->options.pathLADSPA != nullptr)
  1150. delete[] pData->options.pathLADSPA;
  1151. if (valueStr != nullptr)
  1152. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1153. else
  1154. pData->options.pathLADSPA = nullptr;
  1155. break;
  1156. case PLUGIN_DSSI:
  1157. if (pData->options.pathDSSI != nullptr)
  1158. delete[] pData->options.pathDSSI;
  1159. if (valueStr != nullptr)
  1160. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1161. else
  1162. pData->options.pathDSSI = nullptr;
  1163. break;
  1164. case PLUGIN_LV2:
  1165. if (pData->options.pathLV2 != nullptr)
  1166. delete[] pData->options.pathLV2;
  1167. if (valueStr != nullptr)
  1168. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1169. else
  1170. pData->options.pathLV2 = nullptr;
  1171. break;
  1172. case PLUGIN_VST2:
  1173. if (pData->options.pathVST2 != nullptr)
  1174. delete[] pData->options.pathVST2;
  1175. if (valueStr != nullptr)
  1176. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1177. else
  1178. pData->options.pathVST2 = nullptr;
  1179. break;
  1180. case PLUGIN_GIG:
  1181. if (pData->options.pathGIG != nullptr)
  1182. delete[] pData->options.pathGIG;
  1183. if (valueStr != nullptr)
  1184. pData->options.pathGIG = carla_strdup_safe(valueStr);
  1185. else
  1186. pData->options.pathGIG = nullptr;
  1187. break;
  1188. case PLUGIN_SF2:
  1189. if (pData->options.pathSF2 != nullptr)
  1190. delete[] pData->options.pathSF2;
  1191. if (valueStr != nullptr)
  1192. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1193. else
  1194. pData->options.pathSF2 = nullptr;
  1195. break;
  1196. case PLUGIN_SFZ:
  1197. if (pData->options.pathSFZ != nullptr)
  1198. delete[] pData->options.pathSFZ;
  1199. if (valueStr != nullptr)
  1200. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1201. else
  1202. pData->options.pathSFZ = nullptr;
  1203. break;
  1204. default:
  1205. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type", option, EngineOption2Str(option), value, valueStr);
  1206. break;
  1207. }
  1208. break;
  1209. case ENGINE_OPTION_PATH_BINARIES:
  1210. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1211. if (pData->options.binaryDir != nullptr)
  1212. delete[] pData->options.binaryDir;
  1213. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1214. break;
  1215. case ENGINE_OPTION_PATH_RESOURCES:
  1216. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1217. if (pData->options.resourceDir != nullptr)
  1218. delete[] pData->options.resourceDir;
  1219. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1220. break;
  1221. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1222. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1223. #ifdef CARLA_OS_LINUX
  1224. const ScopedEngineEnvironmentLocker _seel(this);
  1225. if (value != 0)
  1226. {
  1227. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1228. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1229. }
  1230. else
  1231. {
  1232. ::unsetenv("LD_PRELOAD");
  1233. }
  1234. #endif
  1235. } break;
  1236. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1237. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1238. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1239. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1240. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1241. } break;
  1242. case ENGINE_OPTION_WINE_EXECUTABLE:
  1243. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1244. if (pData->options.wine.executable != nullptr)
  1245. delete[] pData->options.wine.executable;
  1246. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1247. break;
  1248. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1249. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1250. pData->options.wine.autoPrefix = (value != 0);
  1251. break;
  1252. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1253. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1254. if (pData->options.wine.fallbackPrefix != nullptr)
  1255. delete[] pData->options.wine.fallbackPrefix;
  1256. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1257. break;
  1258. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1259. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1260. pData->options.wine.rtPrio = (value != 0);
  1261. break;
  1262. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1263. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1264. pData->options.wine.baseRtPrio = value;
  1265. break;
  1266. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1267. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1268. pData->options.wine.serverRtPrio = value;
  1269. break;
  1270. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1271. break;
  1272. }
  1273. }
  1274. #ifdef HAVE_LIBLO
  1275. // -----------------------------------------------------------------------
  1276. // OSC Stuff
  1277. # ifndef BUILD_BRIDGE
  1278. bool CarlaEngine::isOscControlRegistered() const noexcept
  1279. {
  1280. return pData->osc.isControlRegistered();
  1281. }
  1282. # endif
  1283. void CarlaEngine::idleOsc() const noexcept
  1284. {
  1285. pData->osc.idle();
  1286. }
  1287. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1288. {
  1289. return pData->osc.getServerPathTCP();
  1290. }
  1291. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1292. {
  1293. return pData->osc.getServerPathUDP();
  1294. }
  1295. #endif
  1296. // -----------------------------------------------------------------------
  1297. // Helper functions
  1298. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1299. {
  1300. return isInput ? pData->events.in : pData->events.out;
  1301. }
  1302. // -----------------------------------------------------------------------
  1303. // Internal stuff
  1304. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1305. {
  1306. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1307. #ifndef BUILD_BRIDGE
  1308. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1309. pData->graph.setBufferSize(newBufferSize);
  1310. #endif
  1311. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1312. for (uint i=0; i < pData->curPluginCount; ++i)
  1313. {
  1314. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1315. if (plugin != nullptr && plugin->isEnabled())
  1316. plugin->bufferSizeChanged(newBufferSize);
  1317. }
  1318. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1319. }
  1320. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1321. {
  1322. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1323. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1324. for (uint i=0; i < pData->curPluginCount; ++i)
  1325. {
  1326. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1327. if (plugin != nullptr && plugin->isEnabled())
  1328. plugin->sampleRateChanged(newSampleRate);
  1329. }
  1330. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1331. }
  1332. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1333. {
  1334. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1335. #ifndef BUILD_BRIDGE
  1336. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1337. pData->graph.setOffline(isOfflineNow);
  1338. #endif
  1339. for (uint i=0; i < pData->curPluginCount; ++i)
  1340. {
  1341. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1342. if (plugin != nullptr && plugin->isEnabled())
  1343. plugin->offlineModeChanged(isOfflineNow);
  1344. }
  1345. }
  1346. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1347. {
  1348. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1349. pluginData.insPeak[0] = inPeaks[0];
  1350. pluginData.insPeak[1] = inPeaks[1];
  1351. pluginData.outsPeak[0] = outPeaks[0];
  1352. pluginData.outsPeak[1] = outPeaks[1];
  1353. }
  1354. void CarlaEngine::saveProjectInternal(juce::MemoryOutputStream& outStream) const
  1355. {
  1356. // send initial prepareForSave first, giving time for bridges to act
  1357. for (uint i=0; i < pData->curPluginCount; ++i)
  1358. {
  1359. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1360. if (plugin != nullptr && plugin->isEnabled())
  1361. {
  1362. #ifndef BUILD_BRIDGE
  1363. // deactivate bridge client-side ping check, since some plugins block during save
  1364. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1365. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1366. #endif
  1367. plugin->prepareForSave();
  1368. }
  1369. }
  1370. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1371. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1372. outStream << "<CARLA-PROJECT VERSION='2.0'>\n";
  1373. const bool isPlugin(getType() == kEngineTypePlugin);
  1374. const EngineOptions& options(pData->options);
  1375. MemoryOutputStream outSettings(1024);
  1376. // save appropriate engine settings
  1377. outSettings << " <EngineSettings>\n";
  1378. //processMode
  1379. //transportMode
  1380. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1381. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1382. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1383. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1384. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1385. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1386. if (isPlugin)
  1387. {
  1388. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1389. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1390. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1391. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1392. outSettings << " <GIG_PATH>" << xmlSafeString(options.pathGIG, true) << "</GIG_PATH>\n";
  1393. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1394. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1395. }
  1396. outSettings << " </EngineSettings>\n";
  1397. outStream << outSettings;
  1398. char strBuf[STR_MAX+1];
  1399. for (uint i=0; i < pData->curPluginCount; ++i)
  1400. {
  1401. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1402. if (plugin != nullptr && plugin->isEnabled())
  1403. {
  1404. MemoryOutputStream outPlugin(4096), streamPlugin;
  1405. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1406. outPlugin << "\n";
  1407. strBuf[0] = '\0';
  1408. plugin->getRealName(strBuf);
  1409. if (strBuf[0] != '\0')
  1410. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1411. outPlugin << " <Plugin>\n";
  1412. outPlugin << streamPlugin;
  1413. outPlugin << " </Plugin>\n";
  1414. outStream << outPlugin;
  1415. }
  1416. }
  1417. #ifndef BUILD_BRIDGE
  1418. // tell bridges we're done saving
  1419. for (uint i=0; i < pData->curPluginCount; ++i)
  1420. {
  1421. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1422. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1423. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1424. }
  1425. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1426. bool saveConnections;
  1427. /**/ if (isPlugin)
  1428. saveConnections = false;
  1429. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1430. saveConnections = true;
  1431. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1432. saveConnections = false;
  1433. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  1434. saveConnections = false;
  1435. else if (std::getenv("NSM_URL") != nullptr)
  1436. saveConnections = false;
  1437. else
  1438. saveConnections = true;
  1439. if (saveConnections)
  1440. {
  1441. if (const char* const* const patchbayConns = getPatchbayConnections())
  1442. {
  1443. MemoryOutputStream outPatchbay(2048);
  1444. outPatchbay << "\n <Patchbay>\n";
  1445. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1446. {
  1447. const char* const connSource(patchbayConns[i]);
  1448. const char* const connTarget(patchbayConns[i+1]);
  1449. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1450. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1451. outPatchbay << " <Connection>\n";
  1452. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1453. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1454. outPatchbay << " </Connection>\n";
  1455. }
  1456. outPatchbay << " </Patchbay>\n";
  1457. outStream << outPatchbay;
  1458. }
  1459. }
  1460. #endif
  1461. outStream << "</CARLA-PROJECT>\n";
  1462. }
  1463. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  1464. {
  1465. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  1466. // try direct filename first
  1467. String jbinary(binary);
  1468. // adjust for current platform
  1469. #ifdef CARLA_OS_WIN
  1470. if (jbinary[0] == '/')
  1471. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  1472. #else
  1473. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  1474. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  1475. #endif
  1476. String filename = File(jbinary).getFileName();
  1477. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  1478. #ifdef CARLA_OS_MAC
  1479. if (filename.endsWithIgnoreCase(".vst"))
  1480. searchFlags |= File::findDirectories;
  1481. #endif
  1482. Array<File> results;
  1483. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1484. {
  1485. const File path(*it);
  1486. results.clear();
  1487. path.findChildFiles(results, searchFlags, true, filename);
  1488. if (results.size() > 0)
  1489. return results.getFirst().getFullPathName();
  1490. }
  1491. // try changing extension
  1492. #if defined(CARLA_OS_MAC)
  1493. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  1494. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  1495. #elif defined(CARLA_OS_WIN)
  1496. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  1497. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  1498. #else
  1499. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  1500. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  1501. #endif
  1502. else
  1503. return String();
  1504. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1505. {
  1506. const File path(*it);
  1507. results.clear();
  1508. path.findChildFiles(results, searchFlags, true, filename);
  1509. if (results.size() > 0)
  1510. return results.getFirst().getFullPathName();
  1511. }
  1512. return String();
  1513. }
  1514. bool CarlaEngine::loadProjectInternal(juce::XmlDocument& xmlDoc)
  1515. {
  1516. ScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  1517. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  1518. const String& xmlType(xmlElement->getTagName());
  1519. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  1520. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  1521. {
  1522. setLastError("Not a valid Carla project or preset file");
  1523. return false;
  1524. }
  1525. #ifndef BUILD_BRIDGE
  1526. const ScopedValueSetter<bool> _svs(pData->loadingProject, true, false);
  1527. #endif
  1528. // completely load file
  1529. xmlElement = xmlDoc.getDocumentElement(false);
  1530. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  1531. if (pData->aboutToClose)
  1532. return true;
  1533. const bool isPlugin(getType() == kEngineTypePlugin);
  1534. // engine settings
  1535. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  1536. {
  1537. const String& tagName(elem->getTagName());
  1538. if (! tagName.equalsIgnoreCase("enginesettings"))
  1539. continue;
  1540. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  1541. {
  1542. const String& tag(settElem->getTagName());
  1543. const String text(settElem->getAllSubText().trim());
  1544. /** some settings might be incorrect or require extra work,
  1545. so we call setOption rather than modifying them direly */
  1546. int option = -1;
  1547. int value = 0;
  1548. const char* valueStr = nullptr;
  1549. /**/ if (tag.equalsIgnoreCase("forcestereo"))
  1550. {
  1551. option = ENGINE_OPTION_FORCE_STEREO;
  1552. value = text.equalsIgnoreCase("true") ? 1 : 0;
  1553. }
  1554. else if (tag.equalsIgnoreCase("preferpluginbridges"))
  1555. {
  1556. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  1557. value = text.equalsIgnoreCase("true") ? 1 : 0;
  1558. }
  1559. else if (tag.equalsIgnoreCase("preferuibridges"))
  1560. {
  1561. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  1562. value = text.equalsIgnoreCase("true") ? 1 : 0;
  1563. }
  1564. else if (tag.equalsIgnoreCase("uisalwaysontop"))
  1565. {
  1566. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  1567. value = text.equalsIgnoreCase("true") ? 1 : 0;
  1568. }
  1569. else if (tag.equalsIgnoreCase("maxparameters"))
  1570. {
  1571. option = ENGINE_OPTION_MAX_PARAMETERS;
  1572. value = text.getIntValue();
  1573. }
  1574. else if (tag.equalsIgnoreCase("uibridgestimeout"))
  1575. {
  1576. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  1577. value = text.getIntValue();
  1578. }
  1579. else if (isPlugin)
  1580. {
  1581. /**/ if (tag.equalsIgnoreCase("LADSPA_PATH"))
  1582. {
  1583. option = ENGINE_OPTION_PLUGIN_PATH;
  1584. value = PLUGIN_LADSPA;
  1585. valueStr = text.toRawUTF8();
  1586. }
  1587. else if (tag.equalsIgnoreCase("DSSI_PATH"))
  1588. {
  1589. option = ENGINE_OPTION_PLUGIN_PATH;
  1590. value = PLUGIN_DSSI;
  1591. valueStr = text.toRawUTF8();
  1592. }
  1593. else if (tag.equalsIgnoreCase("LV2_PATH"))
  1594. {
  1595. option = ENGINE_OPTION_PLUGIN_PATH;
  1596. value = PLUGIN_LV2;
  1597. valueStr = text.toRawUTF8();
  1598. }
  1599. else if (tag.equalsIgnoreCase("VST2_PATH"))
  1600. {
  1601. option = ENGINE_OPTION_PLUGIN_PATH;
  1602. value = PLUGIN_VST2;
  1603. valueStr = text.toRawUTF8();
  1604. }
  1605. else if (tag.equalsIgnoreCase("GIG_PATH"))
  1606. {
  1607. option = ENGINE_OPTION_PLUGIN_PATH;
  1608. value = PLUGIN_GIG;
  1609. valueStr = text.toRawUTF8();
  1610. }
  1611. else if (tag.equalsIgnoreCase("SF2_PATH"))
  1612. {
  1613. option = ENGINE_OPTION_PLUGIN_PATH;
  1614. value = PLUGIN_SF2;
  1615. valueStr = text.toRawUTF8();
  1616. }
  1617. else if (tag.equalsIgnoreCase("SFZ_PATH"))
  1618. {
  1619. option = ENGINE_OPTION_PLUGIN_PATH;
  1620. value = PLUGIN_SFZ;
  1621. valueStr = text.toRawUTF8();
  1622. }
  1623. }
  1624. CARLA_SAFE_ASSERT_CONTINUE(option != -1);
  1625. setOption(static_cast<EngineOption>(option), value, valueStr);
  1626. }
  1627. break;
  1628. }
  1629. if (pData->aboutToClose)
  1630. return true;
  1631. // handle plugins first
  1632. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  1633. {
  1634. const String& tagName(elem->getTagName());
  1635. if (isPreset || tagName.equalsIgnoreCase("plugin"))
  1636. {
  1637. CarlaStateSave stateSave;
  1638. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  1639. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1640. if (pData->aboutToClose)
  1641. return true;
  1642. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  1643. const void* extraStuff = nullptr;
  1644. static const char kTrue[] = "true";
  1645. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  1646. switch (ptype)
  1647. {
  1648. case PLUGIN_GIG:
  1649. case PLUGIN_SF2:
  1650. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  1651. extraStuff = kTrue;
  1652. // fall through
  1653. case PLUGIN_LADSPA:
  1654. case PLUGIN_DSSI:
  1655. case PLUGIN_VST2:
  1656. case PLUGIN_SFZ:
  1657. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  1658. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  1659. {
  1660. const char* searchPath;
  1661. switch (ptype)
  1662. {
  1663. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  1664. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  1665. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  1666. case PLUGIN_GIG: searchPath = pData->options.pathGIG; break;
  1667. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  1668. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  1669. default: searchPath = nullptr; break;
  1670. }
  1671. if (searchPath != nullptr && searchPath[0] != '\0')
  1672. {
  1673. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  1674. stateSave.binary);
  1675. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1676. if (result.isEmpty())
  1677. {
  1678. switch (ptype)
  1679. {
  1680. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  1681. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  1682. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  1683. case PLUGIN_GIG: searchPath = std::getenv("GIG_PATH"); break;
  1684. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  1685. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  1686. default: searchPath = nullptr; break;
  1687. }
  1688. if (searchPath != nullptr && searchPath[0] != '\0')
  1689. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1690. }
  1691. if (result.isNotEmpty())
  1692. {
  1693. delete[] stateSave.binary;
  1694. stateSave.binary = carla_strdup(result.toRawUTF8());
  1695. carla_stderr("Found it! :)");
  1696. }
  1697. else
  1698. {
  1699. carla_stderr("Damn, we failed... :(");
  1700. }
  1701. }
  1702. }
  1703. break;
  1704. default:
  1705. break;
  1706. }
  1707. if (addPlugin(getBinaryTypeFromFile(stateSave.binary), ptype, stateSave.binary,
  1708. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  1709. {
  1710. #ifndef BUILD_BRIDGE
  1711. const uint pluginId = pData->curPluginCount;
  1712. #else
  1713. const uint pluginId = 0;
  1714. #endif
  1715. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1716. {
  1717. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1718. if (pData->aboutToClose)
  1719. return true;
  1720. // deactivate bridge client-side ping check, since some plugins block during load
  1721. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  1722. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1723. plugin->loadStateSave(stateSave);
  1724. /* NOTE: The following code is the same as the end of addPlugin().
  1725. * When project is loading we do not enable the plugin right away,
  1726. * as we want to load state first.
  1727. */
  1728. #ifdef BUILD_BRIDGE
  1729. plugin->setActive(true, true, false);
  1730. #else
  1731. ++pData->curPluginCount;
  1732. #endif
  1733. plugin->setEnabled(true);
  1734. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0.0f, plugin->getName());
  1735. }
  1736. else
  1737. {
  1738. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  1739. }
  1740. }
  1741. else
  1742. {
  1743. carla_stderr2("Failed to load a plugin, error was:\n%s", getLastError());
  1744. }
  1745. }
  1746. if (isPreset)
  1747. return true;
  1748. }
  1749. #ifndef BUILD_BRIDGE
  1750. // tell bridges we're done loading
  1751. for (uint i=0; i < pData->curPluginCount; ++i)
  1752. {
  1753. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1754. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1755. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1756. }
  1757. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1758. if (pData->aboutToClose)
  1759. return true;
  1760. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1761. bool loadConnections;
  1762. /**/ if (isPlugin)
  1763. loadConnections = false;
  1764. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1765. loadConnections = true;
  1766. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1767. loadConnections = false;
  1768. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  1769. loadConnections = false;
  1770. else if (std::getenv("NSM_URL") != nullptr)
  1771. loadConnections = false;
  1772. else
  1773. loadConnections = true;
  1774. // handle connections
  1775. if (loadConnections)
  1776. {
  1777. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  1778. {
  1779. const String& tagName(elem->getTagName());
  1780. if (! tagName.equalsIgnoreCase("patchbay") && ! tagName.equalsIgnoreCase("externalpatchbay"))
  1781. continue;
  1782. CarlaString sourcePort, targetPort;
  1783. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  1784. {
  1785. const String& patchTag(patchElem->getTagName());
  1786. sourcePort.clear();
  1787. targetPort.clear();
  1788. if (! patchTag.equalsIgnoreCase("connection"))
  1789. continue;
  1790. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  1791. {
  1792. const String& tag(connElem->getTagName());
  1793. const String text(connElem->getAllSubText().trim());
  1794. /**/ if (tag.equalsIgnoreCase("source"))
  1795. sourcePort = xmlSafeString(text, false).toRawUTF8();
  1796. else if (tag.equalsIgnoreCase("target"))
  1797. targetPort = xmlSafeString(text, false).toRawUTF8();
  1798. }
  1799. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  1800. restorePatchbayConnection(sourcePort, targetPort);
  1801. }
  1802. break;
  1803. }
  1804. }
  1805. #endif
  1806. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  1807. return true;
  1808. }
  1809. // -----------------------------------------------------------------------
  1810. CARLA_BACKEND_END_NAMESPACE