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.

1579 lines
50KB

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