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.

1554 lines
49KB

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