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.

2322 lines
80KB

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