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.

1541 lines
48KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. /* TODO:
  18. * - complete processRack(): carefully add to input, sorted events
  19. * - implement processPatchbay()
  20. * - implement oscSend_control_switch_plugins()
  21. * - proper find&load plugins
  22. * - something about the peaks?
  23. */
  24. #include "CarlaEngineInternal.hpp"
  25. #include "CarlaPlugin.hpp"
  26. #include "CarlaBackendUtils.hpp"
  27. #include "CarlaEngineUtils.hpp"
  28. #include "CarlaMathUtils.hpp"
  29. #include "CarlaStateUtils.hpp"
  30. #include "CarlaMIDI.h"
  31. #include "jackbridge/JackBridge.hpp"
  32. #include "juce_core.h"
  33. using juce::File;
  34. using juce::MemoryOutputStream;
  35. using juce::ScopedPointer;
  36. using juce::String;
  37. using juce::XmlDocument;
  38. using juce::XmlElement;
  39. CARLA_BACKEND_START_NAMESPACE
  40. // -----------------------------------------------------------------------
  41. // Carla Engine
  42. CarlaEngine::CarlaEngine()
  43. : pData(new ProtectedData(this))
  44. {
  45. carla_debug("CarlaEngine::CarlaEngine()");
  46. }
  47. CarlaEngine::~CarlaEngine()
  48. {
  49. carla_debug("CarlaEngine::~CarlaEngine()");
  50. delete pData;
  51. }
  52. // -----------------------------------------------------------------------
  53. // Static calls
  54. uint CarlaEngine::getDriverCount()
  55. {
  56. carla_debug("CarlaEngine::getDriverCount()");
  57. uint count = 0;
  58. if (jackbridge_is_ok())
  59. count += 1;
  60. #ifndef BUILD_BRIDGE
  61. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  62. count += getJuceApiCount();
  63. # else
  64. count += getRtAudioApiCount();
  65. # endif
  66. #endif
  67. return count;
  68. }
  69. const char* CarlaEngine::getDriverName(const uint index2)
  70. {
  71. carla_debug("CarlaEngine::getDriverName(%i)", index2);
  72. uint index(index2);
  73. if (jackbridge_is_ok() && index-- == 0)
  74. return "JACK";
  75. #ifndef BUILD_BRIDGE
  76. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  77. if (const uint count = getJuceApiCount())
  78. {
  79. if (index < count)
  80. return getJuceApiName(index);
  81. index -= count;
  82. }
  83. # else
  84. if (const uint count = getRtAudioApiCount())
  85. {
  86. if (index < count)
  87. return getRtAudioApiName(index);
  88. index -= count;
  89. }
  90. # endif
  91. #endif
  92. carla_stderr("CarlaEngine::getDriverName(%i) - invalid index", index2);
  93. return nullptr;
  94. }
  95. const char* const* CarlaEngine::getDriverDeviceNames(const uint index2)
  96. {
  97. carla_debug("CarlaEngine::getDriverDeviceNames(%i)", index2);
  98. uint index(index2);
  99. if (jackbridge_is_ok() && index-- == 0)
  100. {
  101. static const char* ret[3] = { "Auto-Connect OFF", "Auto-Connect ON", nullptr };
  102. return ret;
  103. }
  104. #ifndef BUILD_BRIDGE
  105. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  106. if (const uint count = getJuceApiCount())
  107. {
  108. if (index < count)
  109. return getJuceApiDeviceNames(index);
  110. index -= count;
  111. }
  112. # else
  113. if (const uint count = getRtAudioApiCount())
  114. {
  115. if (index < count)
  116. return getRtAudioApiDeviceNames(index);
  117. index -= count;
  118. }
  119. # endif
  120. #endif
  121. carla_stderr("CarlaEngine::getDriverDeviceNames(%i) - invalid index", index2);
  122. return nullptr;
  123. }
  124. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index2, const char* const deviceName)
  125. {
  126. carla_debug("CarlaEngine::getDriverDeviceInfo(%i, \"%s\")", index2, deviceName);
  127. uint index(index2);
  128. if (jackbridge_is_ok() && index-- == 0)
  129. {
  130. static uint32_t bufSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  131. static EngineDriverDeviceInfo devInfo;
  132. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  133. devInfo.bufferSizes = bufSizes;
  134. devInfo.sampleRates = nullptr;
  135. return &devInfo;
  136. }
  137. #ifndef BUILD_BRIDGE
  138. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  139. if (const uint count = getJuceApiCount())
  140. {
  141. if (index < count)
  142. return getJuceDeviceInfo(index, deviceName);
  143. index -= count;
  144. }
  145. # else
  146. if (const uint count = getRtAudioApiCount())
  147. {
  148. if (index < count)
  149. return getRtAudioDeviceInfo(index, deviceName);
  150. index -= count;
  151. }
  152. # endif
  153. #endif
  154. carla_stderr("CarlaEngine::getDriverDeviceNames(%i, \"%s\") - invalid index", index2, deviceName);
  155. return nullptr;
  156. }
  157. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  158. {
  159. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  160. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  161. if (std::strcmp(driverName, "JACK") == 0)
  162. return newJack();
  163. #ifndef BUILD_BRIDGE
  164. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  165. // -------------------------------------------------------------------
  166. // macos
  167. if (std::strcmp(driverName, "CoreAudio") == 0)
  168. return newJuce(AUDIO_API_CORE);
  169. // -------------------------------------------------------------------
  170. // windows
  171. if (std::strcmp(driverName, "ASIO") == 0)
  172. return newJuce(AUDIO_API_ASIO);
  173. if (std::strcmp(driverName, "DirectSound") == 0)
  174. return newJuce(AUDIO_API_DS);
  175. #else
  176. // -------------------------------------------------------------------
  177. // common
  178. if (std::strncmp(driverName, "JACK ", 5) == 0)
  179. return newRtAudio(AUDIO_API_JACK);
  180. // -------------------------------------------------------------------
  181. // linux
  182. if (std::strcmp(driverName, "ALSA") == 0)
  183. return newRtAudio(AUDIO_API_ALSA);
  184. if (std::strcmp(driverName, "OSS") == 0)
  185. return newRtAudio(AUDIO_API_OSS);
  186. if (std::strcmp(driverName, "PulseAudio") == 0)
  187. return newRtAudio(AUDIO_API_PULSE);
  188. # endif
  189. #endif
  190. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  191. return nullptr;
  192. }
  193. // -----------------------------------------------------------------------
  194. // Constant values
  195. uint CarlaEngine::getMaxClientNameSize() const noexcept
  196. {
  197. return STR_MAX/2;
  198. }
  199. uint CarlaEngine::getMaxPortNameSize() const noexcept
  200. {
  201. return STR_MAX;
  202. }
  203. uint CarlaEngine::getCurrentPluginCount() const noexcept
  204. {
  205. return pData->curPluginCount;
  206. }
  207. uint CarlaEngine::getMaxPluginNumber() const noexcept
  208. {
  209. return pData->maxPluginNumber;
  210. }
  211. // -----------------------------------------------------------------------
  212. // Virtual, per-engine type calls
  213. bool CarlaEngine::init(const char* const clientName)
  214. {
  215. carla_debug("CarlaEngine::init(\"%s\")", clientName);
  216. if (! pData->init(clientName))
  217. return false;
  218. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0, pData->options.processMode, pData->options.transportMode, 0.0f, getCurrentDriverName());
  219. return true;
  220. }
  221. bool CarlaEngine::close()
  222. {
  223. carla_debug("CarlaEngine::close()");
  224. if (pData->curPluginCount != 0)
  225. {
  226. pData->aboutToClose = true;
  227. removeAllPlugins();
  228. }
  229. #ifndef BUILD_BRIDGE
  230. if (pData->osc.isControlRegistered())
  231. oscSend_control_exit();
  232. #endif
  233. pData->close();
  234. callback(ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  235. return true;
  236. }
  237. void CarlaEngine::idle() noexcept
  238. {
  239. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode.get() == kEnginePostActionNull,); // FIXME REMOVE
  240. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  241. for (uint i=0; i < pData->curPluginCount; ++i)
  242. {
  243. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  244. if (plugin != nullptr && plugin->isEnabled())
  245. {
  246. try {
  247. plugin->idle();
  248. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin idle");
  249. }
  250. }
  251. pData->osc.idle();
  252. }
  253. CarlaEngineClient* CarlaEngine::addClient(CarlaPlugin* const)
  254. {
  255. return new CarlaEngineClient(*this);
  256. }
  257. // -----------------------------------------------------------------------
  258. // Plugin management
  259. bool CarlaEngine::addPlugin(const BinaryType btype, const PluginType ptype, const char* const filename, const char* const name, const char* const label, const int64_t uniqueId, const void* const extra)
  260. {
  261. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  262. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  263. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  264. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  265. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  266. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  267. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p)", btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra);
  268. uint id;
  269. #ifndef BUILD_BRIDGE
  270. CarlaPlugin* oldPlugin = nullptr;
  271. if (pData->nextPluginId < pData->curPluginCount)
  272. {
  273. id = pData->nextPluginId;
  274. pData->nextPluginId = pData->maxPluginNumber;
  275. oldPlugin = pData->plugins[id].plugin;
  276. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin != nullptr, "Invalid replace plugin Id");
  277. }
  278. else
  279. #endif
  280. {
  281. id = pData->curPluginCount;
  282. if (id == pData->maxPluginNumber)
  283. {
  284. setLastError("Maximum number of plugins reached");
  285. return false;
  286. }
  287. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin == nullptr, "Invalid engine internal data");
  288. }
  289. CarlaPlugin::Initializer initializer = {
  290. this,
  291. id,
  292. filename,
  293. name,
  294. label,
  295. uniqueId
  296. };
  297. CarlaPlugin* plugin = nullptr;
  298. #ifndef BUILD_BRIDGE
  299. CarlaString bridgeBinary(pData->options.binaryDir);
  300. if (bridgeBinary.isNotEmpty())
  301. {
  302. # ifndef CARLA_OS_WIN
  303. if (btype == BINARY_NATIVE)
  304. {
  305. bridgeBinary += OS_SEP_STR "carla-bridge-native";
  306. }
  307. else
  308. # endif
  309. {
  310. switch (btype)
  311. {
  312. case BINARY_POSIX32:
  313. bridgeBinary += OS_SEP_STR "carla-bridge-posix32";
  314. break;
  315. case BINARY_POSIX64:
  316. bridgeBinary += OS_SEP_STR "carla-bridge-posix64";
  317. break;
  318. case BINARY_WIN32:
  319. bridgeBinary += OS_SEP_STR "carla-bridge-win32.exe";
  320. break;
  321. case BINARY_WIN64:
  322. bridgeBinary += OS_SEP_STR "carla-bridge-win64.exe";
  323. break;
  324. default:
  325. bridgeBinary.clear();
  326. break;
  327. }
  328. }
  329. if (! File(bridgeBinary.buffer()).existsAsFile())
  330. bridgeBinary.clear();
  331. }
  332. if (ptype != PLUGIN_INTERNAL && (btype != BINARY_NATIVE || (pData->options.preferPluginBridges && bridgeBinary.isNotEmpty())))
  333. {
  334. if (bridgeBinary.isNotEmpty())
  335. {
  336. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, bridgeBinary);
  337. }
  338. # ifdef CARLA_OS_LINUX
  339. else if (btype == BINARY_WIN32)
  340. {
  341. // fallback to dssi-vst
  342. File file(filename);
  343. CarlaString label2(file.getFullPathName().toRawUTF8());
  344. label2.replace(' ', '*');
  345. CarlaPlugin::Initializer init2 = {
  346. this,
  347. id,
  348. "/usr/lib/dssi/dssi-vst.so",
  349. name,
  350. label2,
  351. uniqueId
  352. };
  353. char* const oldVstPath(getenv("VST_PATH"));
  354. carla_setenv("VST_PATH", file.getParentDirectory().getFullPathName().toRawUTF8());
  355. plugin = CarlaPlugin::newDSSI(init2);
  356. if (oldVstPath != nullptr)
  357. carla_setenv("VST_PATH", oldVstPath);
  358. }
  359. # endif
  360. else
  361. {
  362. setLastError("This Carla build cannot handle this binary");
  363. return false;
  364. }
  365. }
  366. else
  367. #endif // ! BUILD_BRIDGE
  368. {
  369. bool use16Outs;
  370. setLastError("Invalid or unsupported plugin type");
  371. switch (ptype)
  372. {
  373. case PLUGIN_NONE:
  374. break;
  375. case PLUGIN_INTERNAL:
  376. /*if (std::strcmp(label, "FluidSynth") == 0)
  377. {
  378. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  379. plugin = CarlaPlugin::newFluidSynth(initializer, use16Outs);
  380. }
  381. else if (std::strcmp(label, "LinuxSampler (GIG)") == 0)
  382. {
  383. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  384. plugin = CarlaPlugin::newLinuxSampler(initializer, "GIG", use16Outs);
  385. }
  386. else if (std::strcmp(label, "LinuxSampler (SF2)") == 0)
  387. {
  388. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  389. plugin = CarlaPlugin::newLinuxSampler(initializer, "SF2", use16Outs);
  390. }
  391. else if (std::strcmp(label, "LinuxSampler (SFZ)") == 0)
  392. {
  393. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  394. plugin = CarlaPlugin::newLinuxSampler(initializer, "SFZ", use16Outs);
  395. }*/
  396. plugin = CarlaPlugin::newNative(initializer);
  397. break;
  398. case PLUGIN_LADSPA:
  399. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  400. break;
  401. case PLUGIN_DSSI:
  402. plugin = CarlaPlugin::newDSSI(initializer);
  403. break;
  404. case PLUGIN_LV2:
  405. plugin = CarlaPlugin::newLV2(initializer);
  406. break;
  407. case PLUGIN_VST:
  408. plugin = CarlaPlugin::newVST(initializer);
  409. break;
  410. case PLUGIN_VST3:
  411. plugin = CarlaPlugin::newVST3(initializer);
  412. break;
  413. case PLUGIN_AU:
  414. plugin = CarlaPlugin::newAU(initializer);
  415. break;
  416. case PLUGIN_GIG:
  417. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  418. plugin = CarlaPlugin::newFileGIG(initializer, use16Outs);
  419. break;
  420. case PLUGIN_SF2:
  421. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  422. plugin = CarlaPlugin::newFileSF2(initializer, use16Outs);
  423. break;
  424. case PLUGIN_SFZ:
  425. plugin = CarlaPlugin::newFileSFZ(initializer);
  426. break;
  427. }
  428. }
  429. if (plugin == nullptr)
  430. return false;
  431. plugin->registerToOscClient();
  432. EnginePluginData& pluginData(pData->plugins[id]);
  433. pluginData.plugin = plugin;
  434. pluginData.insPeak[0] = 0.0f;
  435. pluginData.insPeak[1] = 0.0f;
  436. pluginData.outsPeak[0] = 0.0f;
  437. pluginData.outsPeak[1] = 0.0f;
  438. #ifndef BUILD_BRIDGE
  439. if (oldPlugin != nullptr)
  440. {
  441. // the engine thread might be reading from the old plugin
  442. pData->thread.stopThread(500);
  443. pData->thread.startThread();
  444. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  445. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  446. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  447. delete oldPlugin;
  448. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  449. plugin->setDryWet(oldDryWet, true, true);
  450. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  451. plugin->setVolume(oldVolume, true, true);
  452. if (wasActive)
  453. plugin->setActive(true, true, true);
  454. callback(ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0.0f, nullptr);
  455. }
  456. else
  457. #endif
  458. {
  459. ++pData->curPluginCount;
  460. callback(ENGINE_CALLBACK_PLUGIN_ADDED, id, 0, 0, 0.0f, plugin->getName());
  461. }
  462. return true;
  463. }
  464. 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)
  465. {
  466. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra);
  467. }
  468. bool CarlaEngine::removePlugin(const uint id)
  469. {
  470. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  471. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  472. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  473. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  474. carla_debug("CarlaEngine::removePlugin(%i)", id);
  475. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  476. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to remove");
  477. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  478. pData->thread.stopThread(500);
  479. #ifndef BUILD_BRIDGE
  480. const ScopedActionLock sal(pData, kEnginePostActionRemovePlugin, id, 0, isRunning());
  481. if (isOscControlRegistered())
  482. oscSend_control_remove_plugin(id);
  483. #else
  484. pData->curPluginCount = 0;
  485. carla_zeroStruct(pData->plugins, 1);
  486. #endif
  487. delete plugin;
  488. if (isRunning() && ! pData->aboutToClose)
  489. pData->thread.startThread();
  490. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0.0f, nullptr);
  491. return true;
  492. }
  493. bool CarlaEngine::removeAllPlugins()
  494. {
  495. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  496. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  497. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  498. carla_debug("CarlaEngine::removeAllPlugins()");
  499. if (pData->curPluginCount == 0)
  500. return true;
  501. pData->thread.stopThread(500);
  502. const ScopedActionLock sal(pData, kEnginePostActionZeroCount, 0, 0, isRunning());
  503. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  504. for (uint i=0; i < pData->maxPluginNumber; ++i)
  505. {
  506. EnginePluginData& pluginData(pData->plugins[i]);
  507. if (pluginData.plugin != nullptr)
  508. {
  509. delete pluginData.plugin;
  510. pluginData.plugin = nullptr;
  511. }
  512. pluginData.insPeak[0] = 0.0f;
  513. pluginData.insPeak[1] = 0.0f;
  514. pluginData.outsPeak[0] = 0.0f;
  515. pluginData.outsPeak[1] = 0.0f;
  516. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  517. }
  518. if (isRunning() && ! pData->aboutToClose)
  519. pData->thread.startThread();
  520. return true;
  521. }
  522. #ifndef BUILD_BRIDGE
  523. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  524. {
  525. CARLA_SAFE_ASSERT_RETURN_ERRN(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  526. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  527. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  528. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  529. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  530. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  531. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  532. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  533. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  534. if (const char* const name = getUniquePluginName(newName))
  535. {
  536. plugin->setName(name);
  537. return name;
  538. }
  539. setLastError("Unable to get new unique plugin name");
  540. return nullptr;
  541. }
  542. bool CarlaEngine::clonePlugin(const uint id)
  543. {
  544. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  545. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  546. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  547. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  548. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  549. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  550. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  551. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  552. char label[STR_MAX+1];
  553. carla_zeroChar(label, STR_MAX+1);
  554. plugin->getLabel(label);
  555. const uint pluginCountBefore(pData->curPluginCount);
  556. if (! addPlugin(plugin->getBinaryType(), plugin->getType(), plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(), plugin->getExtraStuff()))
  557. return false;
  558. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  559. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  560. newPlugin->loadStateSave(plugin->getStateSave());
  561. return true;
  562. }
  563. bool CarlaEngine::replacePlugin(const uint id)
  564. {
  565. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  566. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  567. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  568. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  569. // might use this to reset
  570. if (id == pData->curPluginCount || id == pData->maxPluginNumber)
  571. {
  572. pData->nextPluginId = pData->maxPluginNumber;
  573. return true;
  574. }
  575. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  576. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  577. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  578. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  579. pData->nextPluginId = id;
  580. return true;
  581. }
  582. bool CarlaEngine::switchPlugins(const uint idA, const uint idB)
  583. {
  584. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  585. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  586. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  587. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  588. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  589. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  590. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  591. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  592. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  593. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  594. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  595. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  596. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  597. pData->thread.stopThread(500);
  598. const ScopedActionLock sal(pData, kEnginePostActionSwitchPlugins, idA, idB, isRunning());
  599. // TODO
  600. //if (isOscControlRegistered())
  601. // oscSend_control_switch_plugins(idA, idB);
  602. if (isRunning() && ! pData->aboutToClose)
  603. pData->thread.startThread();
  604. return true;
  605. }
  606. #endif
  607. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const
  608. {
  609. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  610. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  611. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  612. return pData->plugins[id].plugin;
  613. }
  614. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  615. {
  616. return pData->plugins[id].plugin;
  617. }
  618. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  619. {
  620. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  621. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  622. CarlaString sname;
  623. sname = name;
  624. if (sname.isEmpty())
  625. {
  626. sname = "(No name)";
  627. return sname.dup();
  628. }
  629. const size_t maxNameSize(carla_min<uint>(getMaxClientNameSize(), 0xff, 6) - 6); // 6 = strlen(" (10)") + 1
  630. if (maxNameSize == 0 || ! isRunning())
  631. return sname.dup();
  632. sname.truncate(maxNameSize);
  633. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  634. for (uint i=0; i < pData->curPluginCount; ++i)
  635. {
  636. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  637. // Check if unique name doesn't exist
  638. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  639. {
  640. if (sname != pluginName)
  641. continue;
  642. }
  643. // Check if string has already been modified
  644. {
  645. const size_t len(sname.length());
  646. // 1 digit, ex: " (2)"
  647. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  648. {
  649. int number = sname[len-2] - '0';
  650. if (number == 9)
  651. {
  652. // next number is 10, 2 digits
  653. sname.truncate(len-4);
  654. sname += " (10)";
  655. //sname.replace(" (9)", " (10)");
  656. }
  657. else
  658. sname[len-2] = char('0' + number + 1);
  659. continue;
  660. }
  661. // 2 digits, ex: " (11)"
  662. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  663. {
  664. char n2 = sname[len-2];
  665. char n3 = sname[len-3];
  666. if (n2 == '9')
  667. {
  668. n2 = '0';
  669. n3 = static_cast<char>(n3 + 1);
  670. }
  671. else
  672. n2 = static_cast<char>(n2 + 1);
  673. sname[len-2] = n2;
  674. sname[len-3] = n3;
  675. continue;
  676. }
  677. }
  678. // Modify string if not
  679. sname += " (2)";
  680. }
  681. return sname.dup();
  682. }
  683. // -----------------------------------------------------------------------
  684. // Project management
  685. bool CarlaEngine::loadFile(const char* const filename)
  686. {
  687. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  688. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  689. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  690. File file(filename);
  691. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  692. CarlaString baseName(file.getFileName().toRawUTF8());
  693. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  694. // -------------------------------------------------------------------
  695. if (extension == "carxp" || extension == "carxs")
  696. return loadProject(filename);
  697. // -------------------------------------------------------------------
  698. if (extension == "gig")
  699. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  700. if (extension == "sf2")
  701. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  702. if (extension == "sfz")
  703. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  704. // -------------------------------------------------------------------
  705. if (extension == "aif" || extension == "aiff" || extension == "bwf" || extension == "flac" || extension == "ogg" || extension == "wav")
  706. {
  707. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  708. {
  709. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  710. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  711. return true;
  712. }
  713. return false;
  714. }
  715. // -------------------------------------------------------------------
  716. if (extension == "mid" || extension == "midi")
  717. {
  718. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  719. {
  720. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  721. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  722. return true;
  723. }
  724. return false;
  725. }
  726. // -------------------------------------------------------------------
  727. // ZynAddSubFX
  728. if (extension == "xmz" || extension == "xiz")
  729. {
  730. #ifdef WANT_ZYNADDSUBFX
  731. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "zynaddsubfx", 0, nullptr))
  732. {
  733. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  734. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  735. return true;
  736. }
  737. return false;
  738. #else
  739. setLastError("This Carla build does not have ZynAddSubFX support");
  740. return false;
  741. #endif
  742. }
  743. // -------------------------------------------------------------------
  744. setLastError("Unknown file extension");
  745. return false;
  746. }
  747. bool CarlaEngine::loadProject(const char* const filename)
  748. {
  749. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  750. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  751. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  752. File file(filename);
  753. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  754. XmlDocument xml(file);
  755. ScopedPointer<XmlElement> xmlElement(xml.getDocumentElement(true));
  756. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  757. const String& xmlType(xmlElement->getTagName());
  758. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  759. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  760. {
  761. setLastError("Not a valid Carla project or preset file");
  762. return false;
  763. }
  764. // completely load file
  765. xmlElement = xml.getDocumentElement(false);
  766. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  767. // handle plugins first
  768. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  769. {
  770. const String& tagName(elem->getTagName());
  771. if (isPreset || tagName.equalsIgnoreCase("plugin"))
  772. {
  773. StateSave stateSave;
  774. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  775. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  776. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  777. const void* extraStuff = nullptr;
  778. // check if using GIG, SF2 or SFZ 16outs
  779. static const char kUse16OutsSuffix[] = " (16 outs)";
  780. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  781. if (CarlaString(stateSave.label).endsWith(kUse16OutsSuffix))
  782. {
  783. if (ptype == PLUGIN_GIG || ptype == PLUGIN_SF2)
  784. extraStuff = "true";
  785. }
  786. // TODO - proper find&load plugins
  787. if (addPlugin(ptype, stateSave.binary, stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff))
  788. {
  789. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  790. plugin->loadStateSave(stateSave);
  791. }
  792. else
  793. carla_stderr2("Failed to load a plugin, error was:%s\n", getLastError());
  794. }
  795. if (isPreset)
  796. return true;
  797. }
  798. #ifndef BUILD_BRIDGE
  799. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  800. // if we're running inside some session-manager, let them handle the connections
  801. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  802. {
  803. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  804. return true;
  805. }
  806. // now handle connections
  807. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  808. {
  809. const String& tagName(elem->getTagName());
  810. if (tagName.equalsIgnoreCase("patchbay"))
  811. {
  812. CarlaString sourcePort, targetPort;
  813. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  814. {
  815. const String& patchTag(patchElem->getTagName());
  816. sourcePort.clear();
  817. targetPort.clear();
  818. if (! patchTag.equalsIgnoreCase("connection"))
  819. continue;
  820. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  821. {
  822. const String& tag(connElem->getTagName());
  823. const String text(connElem->getAllSubText().trim());
  824. if (tag.equalsIgnoreCase("source"))
  825. sourcePort = text.toRawUTF8();
  826. else if (tag.equalsIgnoreCase("target"))
  827. targetPort = text.toRawUTF8();
  828. }
  829. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  830. restorePatchbayConnection(sourcePort, targetPort);
  831. }
  832. break;
  833. }
  834. }
  835. #endif
  836. return true;
  837. }
  838. bool CarlaEngine::saveProject(const char* const filename)
  839. {
  840. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  841. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  842. MemoryOutputStream out;
  843. out << "<?xml version='1.0' encoding='UTF-8'?>\n";
  844. out << "<!DOCTYPE CARLA-PROJECT>\n";
  845. out << "<CARLA-PROJECT VERSION='2.0'>\n";
  846. bool firstPlugin = true;
  847. char strBuf[STR_MAX+1];
  848. for (uint i=0; i < pData->curPluginCount; ++i)
  849. {
  850. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  851. if (plugin != nullptr && plugin->isEnabled())
  852. {
  853. if (! firstPlugin)
  854. out << "\n";
  855. strBuf[0] = '\0';
  856. plugin->getRealName(strBuf);
  857. //if (strBuf[0] != '\0')
  858. // out << QString(" <!-- %1 -->\n").arg(xmlSafeString(strBuf, true));
  859. out << " <Plugin>\n";
  860. out << plugin->getStateSave().toString();
  861. out << " </Plugin>\n";
  862. firstPlugin = false;
  863. }
  864. }
  865. #ifndef BUILD_BRIDGE
  866. // if we're running inside some session-manager, let them handle the connections
  867. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  868. {
  869. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  870. return true;
  871. }
  872. if (const char* const* patchbayConns = getPatchbayConnections())
  873. {
  874. if (! firstPlugin)
  875. out << "\n";
  876. out << " <Patchbay>\n";
  877. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  878. {
  879. const char* const connSource(patchbayConns[i]);
  880. const char* const connTarget(patchbayConns[i+1]);
  881. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  882. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  883. out << " <Connection>\n";
  884. out << " <Source>" << connSource << "</Source>\n";
  885. out << " <Target>" << connTarget << "</Target>\n";
  886. out << " </Connection>\n";
  887. delete[] connSource;
  888. delete[] connTarget;
  889. }
  890. out << " </Patchbay>\n";
  891. }
  892. #endif
  893. out << "</CARLA-PROJECT>\n";
  894. File file(filename);
  895. if (file.replaceWithData(out.getData(), out.getDataSize()))
  896. return true;
  897. setLastError("Failed to write file");
  898. return false;
  899. }
  900. // -----------------------------------------------------------------------
  901. // Information (base)
  902. uint CarlaEngine::getHints() const noexcept
  903. {
  904. return pData->hints;
  905. }
  906. uint32_t CarlaEngine::getBufferSize() const noexcept
  907. {
  908. return pData->bufferSize;
  909. }
  910. double CarlaEngine::getSampleRate() const noexcept
  911. {
  912. return pData->sampleRate;
  913. }
  914. const char* CarlaEngine::getName() const noexcept
  915. {
  916. return pData->name;
  917. }
  918. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  919. {
  920. return pData->options.processMode;
  921. }
  922. const EngineOptions& CarlaEngine::getOptions() const noexcept
  923. {
  924. return pData->options;
  925. }
  926. const EngineTimeInfo& CarlaEngine::getTimeInfo() const noexcept
  927. {
  928. return pData->timeInfo;
  929. }
  930. // -----------------------------------------------------------------------
  931. // Information (peaks)
  932. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  933. {
  934. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  935. return pData->plugins[pluginId].insPeak[isLeft ? 0 : 1];
  936. }
  937. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  938. {
  939. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  940. return pData->plugins[pluginId].outsPeak[isLeft ? 0 : 1];
  941. }
  942. // -----------------------------------------------------------------------
  943. // Callback
  944. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  945. {
  946. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  947. if (pData->isIdling && action != ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED)
  948. carla_stdout("callback while idling (%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  949. if (action == ENGINE_CALLBACK_IDLE)
  950. pData->isIdling = true;
  951. if (pData->callback != nullptr)
  952. {
  953. try {
  954. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  955. } catch(...) {}
  956. }
  957. if (action == ENGINE_CALLBACK_IDLE)
  958. pData->isIdling = false;
  959. }
  960. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  961. {
  962. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  963. pData->callback = func;
  964. pData->callbackPtr = ptr;
  965. }
  966. // -----------------------------------------------------------------------
  967. // File Callback
  968. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  969. {
  970. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  971. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  972. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  973. const char* ret = nullptr;
  974. if (pData->fileCallback != nullptr)
  975. {
  976. try {
  977. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  978. } catch(...) {}
  979. }
  980. return ret;
  981. }
  982. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  983. {
  984. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  985. pData->fileCallback = func;
  986. pData->fileCallbackPtr = ptr;
  987. }
  988. // -----------------------------------------------------------------------
  989. // Transport
  990. void CarlaEngine::transportPlay() noexcept
  991. {
  992. pData->time.playing = true;
  993. }
  994. void CarlaEngine::transportPause() noexcept
  995. {
  996. pData->time.playing = false;
  997. }
  998. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  999. {
  1000. pData->time.frame = frame;
  1001. }
  1002. // -----------------------------------------------------------------------
  1003. // Error handling
  1004. const char* CarlaEngine::getLastError() const noexcept
  1005. {
  1006. return pData->lastError;
  1007. }
  1008. void CarlaEngine::setLastError(const char* const error) const noexcept
  1009. {
  1010. pData->lastError = error;
  1011. }
  1012. void CarlaEngine::setAboutToClose() noexcept
  1013. {
  1014. carla_debug("CarlaEngine::setAboutToClose()");
  1015. pData->aboutToClose = true;
  1016. }
  1017. // -----------------------------------------------------------------------
  1018. // Global options
  1019. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr)
  1020. {
  1021. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1022. if (isRunning() && (option == ENGINE_OPTION_PROCESS_MODE || option == ENGINE_OPTION_AUDIO_NUM_PERIODS || option == ENGINE_OPTION_AUDIO_DEVICE))
  1023. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!", option, EngineOption2Str(option), value, valueStr);
  1024. switch (option)
  1025. {
  1026. case ENGINE_OPTION_DEBUG:
  1027. case ENGINE_OPTION_NSM_INIT:
  1028. break;
  1029. case ENGINE_OPTION_PROCESS_MODE:
  1030. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1031. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1032. break;
  1033. case ENGINE_OPTION_TRANSPORT_MODE:
  1034. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_INTERNAL && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1035. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1036. break;
  1037. case ENGINE_OPTION_FORCE_STEREO:
  1038. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1039. pData->options.forceStereo = (value != 0);
  1040. break;
  1041. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1042. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1043. pData->options.preferPluginBridges = (value != 0);
  1044. break;
  1045. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1046. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1047. pData->options.preferUiBridges = (value != 0);
  1048. break;
  1049. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1050. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1051. pData->options.uisAlwaysOnTop = (value != 0);
  1052. break;
  1053. case ENGINE_OPTION_MAX_PARAMETERS:
  1054. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1055. pData->options.maxParameters = static_cast<uint>(value);
  1056. break;
  1057. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1058. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1059. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1060. break;
  1061. case ENGINE_OPTION_AUDIO_NUM_PERIODS:
  1062. CARLA_SAFE_ASSERT_RETURN(value >= 2 && value <= 3,);
  1063. pData->options.audioNumPeriods = static_cast<uint>(value);
  1064. break;
  1065. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1066. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1067. pData->options.audioBufferSize = static_cast<uint>(value);
  1068. break;
  1069. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1070. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1071. pData->options.audioSampleRate = static_cast<uint>(value);
  1072. break;
  1073. case ENGINE_OPTION_AUDIO_DEVICE:
  1074. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1075. if (pData->options.audioDevice != nullptr)
  1076. delete[] pData->options.audioDevice;
  1077. pData->options.audioDevice = carla_strdup(valueStr);
  1078. break;
  1079. case ENGINE_OPTION_PATH_BINARIES:
  1080. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1081. if (pData->options.binaryDir != nullptr)
  1082. delete[] pData->options.binaryDir;
  1083. pData->options.binaryDir = carla_strdup(valueStr);
  1084. break;
  1085. case ENGINE_OPTION_PATH_RESOURCES:
  1086. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1087. if (pData->options.resourceDir != nullptr)
  1088. delete[] pData->options.resourceDir;
  1089. pData->options.resourceDir = carla_strdup(valueStr);
  1090. break;
  1091. case ENGINE_OPTION_FRONTEND_WIN_ID:
  1092. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1093. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1094. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1095. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1096. break;
  1097. }
  1098. }
  1099. // -----------------------------------------------------------------------
  1100. // OSC Stuff
  1101. #ifdef BUILD_BRIDGE
  1102. bool CarlaEngine::isOscBridgeRegistered() const noexcept
  1103. {
  1104. return (pData->oscData != nullptr);
  1105. }
  1106. #else
  1107. bool CarlaEngine::isOscControlRegistered() const noexcept
  1108. {
  1109. return pData->osc.isControlRegistered();
  1110. }
  1111. #endif
  1112. void CarlaEngine::idleOsc() const noexcept
  1113. {
  1114. pData->osc.idle();
  1115. }
  1116. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1117. {
  1118. return pData->osc.getServerPathTCP();
  1119. }
  1120. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1121. {
  1122. return pData->osc.getServerPathUDP();
  1123. }
  1124. #ifdef BUILD_BRIDGE
  1125. void CarlaEngine::setOscBridgeData(const CarlaOscData* const oscData) const noexcept
  1126. {
  1127. pData->oscData = oscData;
  1128. }
  1129. #endif
  1130. // -----------------------------------------------------------------------
  1131. // Helper functions
  1132. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1133. {
  1134. return isInput ? pData->events.in : pData->events.out;
  1135. }
  1136. void CarlaEngine::registerEnginePlugin(const uint id, CarlaPlugin* const plugin) noexcept
  1137. {
  1138. CARLA_SAFE_ASSERT_RETURN(id == pData->curPluginCount,);
  1139. carla_debug("CarlaEngine::registerEnginePlugin(%i, %p)", id, plugin);
  1140. pData->plugins[id].plugin = plugin;
  1141. }
  1142. // -----------------------------------------------------------------------
  1143. // Internal stuff
  1144. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1145. {
  1146. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1147. #ifndef BUILD_BRIDGE
  1148. pData->graph.setBufferSize(newBufferSize);
  1149. #endif
  1150. for (uint i=0; i < pData->curPluginCount; ++i)
  1151. {
  1152. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1153. if (plugin != nullptr && plugin->isEnabled())
  1154. plugin->bufferSizeChanged(newBufferSize);
  1155. }
  1156. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1157. }
  1158. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1159. {
  1160. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1161. #ifndef BUILD_BRIDGE
  1162. pData->graph.setSampleRate(newSampleRate);
  1163. #endif
  1164. for (uint i=0; i < pData->curPluginCount; ++i)
  1165. {
  1166. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1167. if (plugin != nullptr && plugin->isEnabled())
  1168. plugin->sampleRateChanged(newSampleRate);
  1169. }
  1170. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1171. }
  1172. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1173. {
  1174. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1175. #ifndef BUILD_BRIDGE
  1176. pData->graph.setOffline(isOfflineNow);
  1177. #endif
  1178. for (uint i=0; i < pData->curPluginCount; ++i)
  1179. {
  1180. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1181. if (plugin != nullptr && plugin->isEnabled())
  1182. plugin->offlineModeChanged(isOfflineNow);
  1183. }
  1184. }
  1185. void CarlaEngine::runPendingRtEvents() noexcept
  1186. {
  1187. pData->doNextPluginAction(true);
  1188. if (pData->time.playing)
  1189. pData->time.frame += pData->bufferSize;
  1190. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  1191. {
  1192. pData->timeInfo.playing = pData->time.playing;
  1193. pData->timeInfo.frame = pData->time.frame;
  1194. }
  1195. }
  1196. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1197. {
  1198. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1199. pluginData.insPeak[0] = inPeaks[0];
  1200. pluginData.insPeak[1] = inPeaks[1];
  1201. pluginData.outsPeak[0] = outPeaks[0];
  1202. pluginData.outsPeak[1] = outPeaks[1];
  1203. }
  1204. // -----------------------------------------------------------------------
  1205. CARLA_BACKEND_END_NAMESPACE