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.

2112 lines
72KB

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