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.

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