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.

2146 lines
73KB

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