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.

2231 lines
76KB

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