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.

1566 lines
49KB

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