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.

2298 lines
79KB

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