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.

1549 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. #ifndef BUILD_BRIDGE
  377. /*if (std::strcmp(label, "FluidSynth") == 0)
  378. {
  379. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  380. plugin = CarlaPlugin::newFluidSynth(initializer, use16Outs);
  381. }
  382. else if (std::strcmp(label, "LinuxSampler (GIG)") == 0)
  383. {
  384. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  385. plugin = CarlaPlugin::newLinuxSampler(initializer, "GIG", use16Outs);
  386. }
  387. else if (std::strcmp(label, "LinuxSampler (SF2)") == 0)
  388. {
  389. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  390. plugin = CarlaPlugin::newLinuxSampler(initializer, "SF2", use16Outs);
  391. }
  392. else if (std::strcmp(label, "LinuxSampler (SFZ)") == 0)
  393. {
  394. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  395. plugin = CarlaPlugin::newLinuxSampler(initializer, "SFZ", use16Outs);
  396. }*/
  397. plugin = CarlaPlugin::newNative(initializer);
  398. #endif
  399. break;
  400. case PLUGIN_LADSPA:
  401. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  402. break;
  403. case PLUGIN_DSSI:
  404. plugin = CarlaPlugin::newDSSI(initializer);
  405. break;
  406. case PLUGIN_LV2:
  407. plugin = CarlaPlugin::newLV2(initializer);
  408. break;
  409. case PLUGIN_VST:
  410. plugin = CarlaPlugin::newVST(initializer);
  411. break;
  412. case PLUGIN_VST3:
  413. plugin = CarlaPlugin::newVST3(initializer);
  414. break;
  415. case PLUGIN_AU:
  416. plugin = CarlaPlugin::newAU(initializer);
  417. break;
  418. case PLUGIN_GIG:
  419. #ifndef BUILD_BRIDGE
  420. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  421. plugin = CarlaPlugin::newFileGIG(initializer, use16Outs);
  422. #endif
  423. break;
  424. case PLUGIN_SF2:
  425. #ifndef BUILD_BRIDGE
  426. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  427. plugin = CarlaPlugin::newFileSF2(initializer, use16Outs);
  428. #endif
  429. break;
  430. case PLUGIN_SFZ:
  431. #ifndef BUILD_BRIDGE
  432. plugin = CarlaPlugin::newFileSFZ(initializer);
  433. #endif
  434. break;
  435. }
  436. }
  437. if (plugin == nullptr)
  438. return false;
  439. plugin->registerToOscClient();
  440. EnginePluginData& pluginData(pData->plugins[id]);
  441. pluginData.plugin = plugin;
  442. pluginData.insPeak[0] = 0.0f;
  443. pluginData.insPeak[1] = 0.0f;
  444. pluginData.outsPeak[0] = 0.0f;
  445. pluginData.outsPeak[1] = 0.0f;
  446. #ifndef BUILD_BRIDGE
  447. if (oldPlugin != nullptr)
  448. {
  449. // the engine thread might be reading from the old plugin
  450. pData->thread.stopThread(500);
  451. pData->thread.startThread();
  452. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  453. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  454. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  455. delete oldPlugin;
  456. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  457. plugin->setDryWet(oldDryWet, true, true);
  458. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  459. plugin->setVolume(oldVolume, true, true);
  460. if (wasActive)
  461. plugin->setActive(true, true, true);
  462. callback(ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0.0f, nullptr);
  463. }
  464. else
  465. #endif
  466. {
  467. ++pData->curPluginCount;
  468. callback(ENGINE_CALLBACK_PLUGIN_ADDED, id, 0, 0, 0.0f, plugin->getName());
  469. }
  470. return true;
  471. }
  472. 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)
  473. {
  474. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra);
  475. }
  476. bool CarlaEngine::removePlugin(const uint id)
  477. {
  478. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  479. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  480. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "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 ScopedActionLock sal(pData, kEnginePostActionRemovePlugin, id, 0, isRunning());
  489. if (isOscControlRegistered())
  490. oscSend_control_remove_plugin(id);
  491. #else
  492. pData->curPluginCount = 0;
  493. carla_zeroStruct(pData->plugins, 1);
  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_debug("CarlaEngine::removeAllPlugins()");
  507. if (pData->curPluginCount == 0)
  508. return true;
  509. pData->thread.stopThread(500);
  510. const ScopedActionLock sal(pData, kEnginePostActionZeroCount, 0, 0, isRunning());
  511. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  512. for (uint i=0; i < pData->maxPluginNumber; ++i)
  513. {
  514. EnginePluginData& pluginData(pData->plugins[i]);
  515. if (pluginData.plugin != nullptr)
  516. {
  517. delete pluginData.plugin;
  518. pluginData.plugin = nullptr;
  519. }
  520. pluginData.insPeak[0] = 0.0f;
  521. pluginData.insPeak[1] = 0.0f;
  522. pluginData.outsPeak[0] = 0.0f;
  523. pluginData.outsPeak[1] = 0.0f;
  524. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  525. }
  526. if (isRunning() && ! pData->aboutToClose)
  527. pData->thread.startThread();
  528. return true;
  529. }
  530. #ifndef BUILD_BRIDGE
  531. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  532. {
  533. CARLA_SAFE_ASSERT_RETURN_ERRN(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  534. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  535. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  536. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  537. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  538. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  539. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  540. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  541. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  542. if (const char* const name = getUniquePluginName(newName))
  543. {
  544. plugin->setName(name);
  545. return name;
  546. }
  547. setLastError("Unable to get new unique plugin name");
  548. return nullptr;
  549. }
  550. bool CarlaEngine::clonePlugin(const uint id)
  551. {
  552. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  553. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  554. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  555. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  556. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  557. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  558. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  559. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  560. char label[STR_MAX+1];
  561. carla_zeroChar(label, STR_MAX+1);
  562. plugin->getLabel(label);
  563. const uint pluginCountBefore(pData->curPluginCount);
  564. if (! addPlugin(plugin->getBinaryType(), plugin->getType(), plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(), plugin->getExtraStuff()))
  565. return false;
  566. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  567. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  568. newPlugin->loadStateSave(plugin->getStateSave());
  569. return true;
  570. }
  571. bool CarlaEngine::replacePlugin(const uint id) noexcept
  572. {
  573. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  574. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  575. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  576. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  577. // might use this to reset
  578. if (id == pData->curPluginCount || id == pData->maxPluginNumber)
  579. {
  580. pData->nextPluginId = pData->maxPluginNumber;
  581. return true;
  582. }
  583. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  584. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  585. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  586. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  587. pData->nextPluginId = id;
  588. return true;
  589. }
  590. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  591. {
  592. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  593. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  594. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  595. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  596. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  597. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  598. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  599. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  600. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  601. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  602. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  603. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  604. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  605. pData->thread.stopThread(500);
  606. const ScopedActionLock sal(pData, kEnginePostActionSwitchPlugins, idA, idB, isRunning());
  607. // TODO
  608. //if (isOscControlRegistered())
  609. // oscSend_control_switch_plugins(idA, idB);
  610. if (isRunning() && ! pData->aboutToClose)
  611. pData->thread.startThread();
  612. return true;
  613. }
  614. #endif
  615. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const noexcept
  616. {
  617. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  618. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  619. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  620. return pData->plugins[id].plugin;
  621. }
  622. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  623. {
  624. return pData->plugins[id].plugin;
  625. }
  626. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  627. {
  628. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  629. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  630. CarlaString sname;
  631. sname = name;
  632. if (sname.isEmpty())
  633. {
  634. sname = "(No name)";
  635. return sname.dup();
  636. }
  637. const size_t maxNameSize(carla_min<uint>(getMaxClientNameSize(), 0xff, 6) - 6); // 6 = strlen(" (10)") + 1
  638. if (maxNameSize == 0 || ! isRunning())
  639. return sname.dup();
  640. sname.truncate(maxNameSize);
  641. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  642. for (uint i=0; i < pData->curPluginCount; ++i)
  643. {
  644. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  645. // Check if unique name doesn't exist
  646. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  647. {
  648. if (sname != pluginName)
  649. continue;
  650. }
  651. // Check if string has already been modified
  652. {
  653. const size_t len(sname.length());
  654. // 1 digit, ex: " (2)"
  655. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  656. {
  657. int number = sname[len-2] - '0';
  658. if (number == 9)
  659. {
  660. // next number is 10, 2 digits
  661. sname.truncate(len-4);
  662. sname += " (10)";
  663. //sname.replace(" (9)", " (10)");
  664. }
  665. else
  666. sname[len-2] = char('0' + number + 1);
  667. continue;
  668. }
  669. // 2 digits, ex: " (11)"
  670. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  671. {
  672. char n2 = sname[len-2];
  673. char n3 = sname[len-3];
  674. if (n2 == '9')
  675. {
  676. n2 = '0';
  677. n3 = static_cast<char>(n3 + 1);
  678. }
  679. else
  680. n2 = static_cast<char>(n2 + 1);
  681. sname[len-2] = n2;
  682. sname[len-3] = n3;
  683. continue;
  684. }
  685. }
  686. // Modify string if not
  687. sname += " (2)";
  688. }
  689. return sname.dup();
  690. }
  691. // -----------------------------------------------------------------------
  692. // Project management
  693. bool CarlaEngine::loadFile(const char* const filename)
  694. {
  695. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  696. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  697. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  698. File file(filename);
  699. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  700. CarlaString baseName(file.getFileName().toRawUTF8());
  701. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  702. // -------------------------------------------------------------------
  703. if (extension == "carxp" || extension == "carxs")
  704. return loadProject(filename);
  705. // -------------------------------------------------------------------
  706. if (extension == "gig")
  707. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  708. if (extension == "sf2")
  709. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  710. if (extension == "sfz")
  711. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  712. // -------------------------------------------------------------------
  713. if (extension == "aif" || extension == "aiff" || extension == "bwf" || extension == "flac" || extension == "ogg" || extension == "wav")
  714. {
  715. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  716. {
  717. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  718. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  719. return true;
  720. }
  721. return false;
  722. }
  723. // -------------------------------------------------------------------
  724. if (extension == "mid" || extension == "midi")
  725. {
  726. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 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. // ZynAddSubFX
  736. if (extension == "xmz" || extension == "xiz")
  737. {
  738. #ifdef WANT_ZYNADDSUBFX
  739. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "zynaddsubfx", 0, nullptr))
  740. {
  741. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  742. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  743. return true;
  744. }
  745. return false;
  746. #else
  747. setLastError("This Carla build does not have ZynAddSubFX support");
  748. return false;
  749. #endif
  750. }
  751. // -------------------------------------------------------------------
  752. setLastError("Unknown file extension");
  753. return false;
  754. }
  755. bool CarlaEngine::loadProject(const char* const filename)
  756. {
  757. CARLA_SAFE_ASSERT_RETURN_ERR(! pData->isIdling, "An operation is still being processed, please wait for it to finish");
  758. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  759. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  760. File file(filename);
  761. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  762. XmlDocument xml(file);
  763. ScopedPointer<XmlElement> xmlElement(xml.getDocumentElement(true));
  764. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  765. const String& xmlType(xmlElement->getTagName());
  766. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  767. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  768. {
  769. setLastError("Not a valid Carla project or preset file");
  770. return false;
  771. }
  772. // completely load file
  773. xmlElement = xml.getDocumentElement(false);
  774. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  775. // handle plugins first
  776. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  777. {
  778. const String& tagName(elem->getTagName());
  779. if (isPreset || tagName.equalsIgnoreCase("plugin"))
  780. {
  781. StateSave stateSave;
  782. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  783. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  784. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  785. const void* extraStuff = nullptr;
  786. // check if using GIG, SF2 or SFZ 16outs
  787. static const char kUse16OutsSuffix[] = " (16 outs)";
  788. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  789. if (CarlaString(stateSave.label).endsWith(kUse16OutsSuffix))
  790. {
  791. if (ptype == PLUGIN_GIG || ptype == PLUGIN_SF2)
  792. extraStuff = "true";
  793. }
  794. // TODO - proper find&load plugins
  795. if (addPlugin(ptype, stateSave.binary, stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff))
  796. {
  797. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  798. plugin->loadStateSave(stateSave);
  799. }
  800. else
  801. carla_stderr2("Failed to load a plugin, error was:%s\n", getLastError());
  802. }
  803. if (isPreset)
  804. return true;
  805. }
  806. #ifndef BUILD_BRIDGE
  807. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  808. // if we're running inside some session-manager, let them handle the connections
  809. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  810. {
  811. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  812. return true;
  813. }
  814. // now handle connections
  815. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  816. {
  817. const String& tagName(elem->getTagName());
  818. if (tagName.equalsIgnoreCase("patchbay"))
  819. {
  820. CarlaString sourcePort, targetPort;
  821. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  822. {
  823. const String& patchTag(patchElem->getTagName());
  824. sourcePort.clear();
  825. targetPort.clear();
  826. if (! patchTag.equalsIgnoreCase("connection"))
  827. continue;
  828. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  829. {
  830. const String& tag(connElem->getTagName());
  831. const String text(connElem->getAllSubText().trim());
  832. if (tag.equalsIgnoreCase("source"))
  833. sourcePort = text.toRawUTF8();
  834. else if (tag.equalsIgnoreCase("target"))
  835. targetPort = text.toRawUTF8();
  836. }
  837. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  838. restorePatchbayConnection(sourcePort, targetPort);
  839. }
  840. break;
  841. }
  842. }
  843. #endif
  844. return true;
  845. }
  846. bool CarlaEngine::saveProject(const char* const filename)
  847. {
  848. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  849. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  850. MemoryOutputStream out;
  851. out << "<?xml version='1.0' encoding='UTF-8'?>\n";
  852. out << "<!DOCTYPE CARLA-PROJECT>\n";
  853. out << "<CARLA-PROJECT VERSION='2.0'>\n";
  854. bool firstPlugin = true;
  855. char strBuf[STR_MAX+1];
  856. for (uint i=0; i < pData->curPluginCount; ++i)
  857. {
  858. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  859. if (plugin != nullptr && plugin->isEnabled())
  860. {
  861. if (! firstPlugin)
  862. out << "\n";
  863. strBuf[0] = '\0';
  864. plugin->getRealName(strBuf);
  865. //if (strBuf[0] != '\0')
  866. // out << QString(" <!-- %1 -->\n").arg(xmlSafeString(strBuf, true));
  867. out << " <Plugin>\n";
  868. out << plugin->getStateSave().toString();
  869. out << " </Plugin>\n";
  870. firstPlugin = false;
  871. }
  872. }
  873. #ifndef BUILD_BRIDGE
  874. // if we're running inside some session-manager, let them handle the connections
  875. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  876. {
  877. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  878. return true;
  879. }
  880. if (const char* const* patchbayConns = getPatchbayConnections())
  881. {
  882. if (! firstPlugin)
  883. out << "\n";
  884. out << " <Patchbay>\n";
  885. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  886. {
  887. const char* const connSource(patchbayConns[i]);
  888. const char* const connTarget(patchbayConns[i+1]);
  889. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  890. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  891. out << " <Connection>\n";
  892. out << " <Source>" << connSource << "</Source>\n";
  893. out << " <Target>" << connTarget << "</Target>\n";
  894. out << " </Connection>\n";
  895. delete[] connSource;
  896. delete[] connTarget;
  897. }
  898. out << " </Patchbay>\n";
  899. }
  900. #endif
  901. out << "</CARLA-PROJECT>\n";
  902. File file(filename);
  903. if (file.replaceWithData(out.getData(), out.getDataSize()))
  904. return true;
  905. setLastError("Failed to write file");
  906. return false;
  907. }
  908. // -----------------------------------------------------------------------
  909. // Information (base)
  910. uint CarlaEngine::getHints() const noexcept
  911. {
  912. return pData->hints;
  913. }
  914. uint32_t CarlaEngine::getBufferSize() const noexcept
  915. {
  916. return pData->bufferSize;
  917. }
  918. double CarlaEngine::getSampleRate() const noexcept
  919. {
  920. return pData->sampleRate;
  921. }
  922. const char* CarlaEngine::getName() const noexcept
  923. {
  924. return pData->name;
  925. }
  926. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  927. {
  928. return pData->options.processMode;
  929. }
  930. const EngineOptions& CarlaEngine::getOptions() const noexcept
  931. {
  932. return pData->options;
  933. }
  934. const EngineTimeInfo& CarlaEngine::getTimeInfo() const noexcept
  935. {
  936. return pData->timeInfo;
  937. }
  938. // -----------------------------------------------------------------------
  939. // Information (peaks)
  940. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  941. {
  942. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  943. return pData->plugins[pluginId].insPeak[isLeft ? 0 : 1];
  944. }
  945. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  946. {
  947. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  948. return pData->plugins[pluginId].outsPeak[isLeft ? 0 : 1];
  949. }
  950. // -----------------------------------------------------------------------
  951. // Callback
  952. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  953. {
  954. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  955. if (pData->isIdling && action != ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED)
  956. carla_stdout("callback while idling (%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  957. if (action == ENGINE_CALLBACK_IDLE)
  958. pData->isIdling = true;
  959. if (pData->callback != nullptr)
  960. {
  961. try {
  962. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  963. } CARLA_SAFE_EXCEPTION("callback");
  964. }
  965. if (action == ENGINE_CALLBACK_IDLE)
  966. pData->isIdling = false;
  967. }
  968. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  969. {
  970. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  971. pData->callback = func;
  972. pData->callbackPtr = ptr;
  973. }
  974. // -----------------------------------------------------------------------
  975. // File Callback
  976. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  977. {
  978. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  979. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  980. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  981. const char* ret = nullptr;
  982. if (pData->fileCallback != nullptr)
  983. {
  984. try {
  985. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  986. } CARLA_SAFE_EXCEPTION("runFileCallback");
  987. }
  988. return ret;
  989. }
  990. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  991. {
  992. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  993. pData->fileCallback = func;
  994. pData->fileCallbackPtr = ptr;
  995. }
  996. // -----------------------------------------------------------------------
  997. // Transport
  998. void CarlaEngine::transportPlay() noexcept
  999. {
  1000. pData->time.playing = true;
  1001. }
  1002. void CarlaEngine::transportPause() noexcept
  1003. {
  1004. pData->time.playing = false;
  1005. }
  1006. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1007. {
  1008. pData->time.frame = frame;
  1009. }
  1010. // -----------------------------------------------------------------------
  1011. // Error handling
  1012. const char* CarlaEngine::getLastError() const noexcept
  1013. {
  1014. return pData->lastError;
  1015. }
  1016. void CarlaEngine::setLastError(const char* const error) const noexcept
  1017. {
  1018. pData->lastError = error;
  1019. }
  1020. void CarlaEngine::setAboutToClose() noexcept
  1021. {
  1022. carla_debug("CarlaEngine::setAboutToClose()");
  1023. pData->aboutToClose = true;
  1024. }
  1025. // -----------------------------------------------------------------------
  1026. // Global options
  1027. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1028. {
  1029. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1030. if (isRunning() && (option == ENGINE_OPTION_PROCESS_MODE || option == ENGINE_OPTION_AUDIO_NUM_PERIODS || option == ENGINE_OPTION_AUDIO_DEVICE))
  1031. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!", option, EngineOption2Str(option), value, valueStr);
  1032. switch (option)
  1033. {
  1034. case ENGINE_OPTION_DEBUG:
  1035. case ENGINE_OPTION_NSM_INIT:
  1036. break;
  1037. case ENGINE_OPTION_PROCESS_MODE:
  1038. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1039. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1040. break;
  1041. case ENGINE_OPTION_TRANSPORT_MODE:
  1042. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_INTERNAL && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1043. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1044. break;
  1045. case ENGINE_OPTION_FORCE_STEREO:
  1046. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1047. pData->options.forceStereo = (value != 0);
  1048. break;
  1049. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1050. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1051. pData->options.preferPluginBridges = (value != 0);
  1052. break;
  1053. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1054. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1055. pData->options.preferUiBridges = (value != 0);
  1056. break;
  1057. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1058. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1059. pData->options.uisAlwaysOnTop = (value != 0);
  1060. break;
  1061. case ENGINE_OPTION_MAX_PARAMETERS:
  1062. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1063. pData->options.maxParameters = static_cast<uint>(value);
  1064. break;
  1065. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1066. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1067. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1068. break;
  1069. case ENGINE_OPTION_AUDIO_NUM_PERIODS:
  1070. CARLA_SAFE_ASSERT_RETURN(value >= 2 && value <= 3,);
  1071. pData->options.audioNumPeriods = static_cast<uint>(value);
  1072. break;
  1073. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1074. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1075. pData->options.audioBufferSize = static_cast<uint>(value);
  1076. break;
  1077. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1078. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1079. pData->options.audioSampleRate = static_cast<uint>(value);
  1080. break;
  1081. case ENGINE_OPTION_AUDIO_DEVICE:
  1082. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1083. if (pData->options.audioDevice != nullptr)
  1084. delete[] pData->options.audioDevice;
  1085. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1086. break;
  1087. case ENGINE_OPTION_PATH_BINARIES:
  1088. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1089. if (pData->options.binaryDir != nullptr)
  1090. delete[] pData->options.binaryDir;
  1091. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1092. break;
  1093. case ENGINE_OPTION_PATH_RESOURCES:
  1094. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1095. if (pData->options.resourceDir != nullptr)
  1096. delete[] pData->options.resourceDir;
  1097. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1098. break;
  1099. case ENGINE_OPTION_FRONTEND_WIN_ID:
  1100. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1101. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1102. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1103. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1104. break;
  1105. }
  1106. }
  1107. // -----------------------------------------------------------------------
  1108. // OSC Stuff
  1109. #ifdef BUILD_BRIDGE
  1110. bool CarlaEngine::isOscBridgeRegistered() const noexcept
  1111. {
  1112. return (pData->oscData != nullptr);
  1113. }
  1114. #else
  1115. bool CarlaEngine::isOscControlRegistered() const noexcept
  1116. {
  1117. return pData->osc.isControlRegistered();
  1118. }
  1119. #endif
  1120. void CarlaEngine::idleOsc() const noexcept
  1121. {
  1122. pData->osc.idle();
  1123. }
  1124. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1125. {
  1126. return pData->osc.getServerPathTCP();
  1127. }
  1128. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1129. {
  1130. return pData->osc.getServerPathUDP();
  1131. }
  1132. #ifdef BUILD_BRIDGE
  1133. void CarlaEngine::setOscBridgeData(const CarlaOscData* const oscData) const noexcept
  1134. {
  1135. pData->oscData = oscData;
  1136. }
  1137. #endif
  1138. // -----------------------------------------------------------------------
  1139. // Helper functions
  1140. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1141. {
  1142. return isInput ? pData->events.in : pData->events.out;
  1143. }
  1144. void CarlaEngine::registerEnginePlugin(const uint id, CarlaPlugin* const plugin) noexcept
  1145. {
  1146. CARLA_SAFE_ASSERT_RETURN(id == pData->curPluginCount,);
  1147. carla_debug("CarlaEngine::registerEnginePlugin(%i, %p)", id, plugin);
  1148. pData->plugins[id].plugin = plugin;
  1149. }
  1150. // -----------------------------------------------------------------------
  1151. // Internal stuff
  1152. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1153. {
  1154. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1155. #ifndef BUILD_BRIDGE
  1156. pData->graph.setBufferSize(newBufferSize);
  1157. #endif
  1158. for (uint i=0; i < pData->curPluginCount; ++i)
  1159. {
  1160. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1161. if (plugin != nullptr && plugin->isEnabled())
  1162. plugin->bufferSizeChanged(newBufferSize);
  1163. }
  1164. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1165. }
  1166. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1167. {
  1168. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1169. #ifndef BUILD_BRIDGE
  1170. pData->graph.setSampleRate(newSampleRate);
  1171. #endif
  1172. for (uint i=0; i < pData->curPluginCount; ++i)
  1173. {
  1174. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1175. if (plugin != nullptr && plugin->isEnabled())
  1176. plugin->sampleRateChanged(newSampleRate);
  1177. }
  1178. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1179. }
  1180. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1181. {
  1182. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1183. #ifndef BUILD_BRIDGE
  1184. pData->graph.setOffline(isOfflineNow);
  1185. #endif
  1186. for (uint i=0; i < pData->curPluginCount; ++i)
  1187. {
  1188. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1189. if (plugin != nullptr && plugin->isEnabled())
  1190. plugin->offlineModeChanged(isOfflineNow);
  1191. }
  1192. }
  1193. void CarlaEngine::runPendingRtEvents() noexcept
  1194. {
  1195. pData->doNextPluginAction(true);
  1196. if (pData->time.playing)
  1197. pData->time.frame += pData->bufferSize;
  1198. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  1199. {
  1200. pData->timeInfo.playing = pData->time.playing;
  1201. pData->timeInfo.frame = pData->time.frame;
  1202. }
  1203. }
  1204. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1205. {
  1206. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1207. pluginData.insPeak[0] = inPeaks[0];
  1208. pluginData.insPeak[1] = inPeaks[1];
  1209. pluginData.outsPeak[0] = outPeaks[0];
  1210. pluginData.outsPeak[1] = outPeaks[1];
  1211. }
  1212. // -----------------------------------------------------------------------
  1213. CARLA_BACKEND_END_NAMESPACE