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.

2587 lines
87KB

  1. /*
  2. * Carla Plugin Bridge
  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. #ifdef BUILD_BRIDGE
  18. # error This file should be used under bridge mode
  19. #endif
  20. #include "CarlaPluginInternal.hpp"
  21. #include "CarlaBackendUtils.hpp"
  22. #include "CarlaBase64Utils.hpp"
  23. #include "CarlaBridgeUtils.hpp"
  24. #include "CarlaEngineUtils.hpp"
  25. #include "CarlaMathUtils.hpp"
  26. #include "CarlaShmUtils.hpp"
  27. #include "CarlaThread.hpp"
  28. #include "jackbridge/JackBridge.hpp"
  29. #include <ctime>
  30. // -------------------------------------------------------------------------------------------------------------------
  31. using juce::ChildProcess;
  32. using juce::File;
  33. using juce::ScopedPointer;
  34. using juce::String;
  35. using juce::StringArray;
  36. CARLA_BACKEND_START_NAMESPACE
  37. // -------------------------------------------------------------------------------------------------------------------
  38. struct BridgeAudioPool {
  39. CarlaString filename;
  40. std::size_t size;
  41. float* data;
  42. shm_t shm;
  43. BridgeAudioPool() noexcept
  44. : filename(),
  45. size(0),
  46. data(nullptr)
  47. #ifdef CARLA_PROPER_CPP11_SUPPORT
  48. , shm(shm_t_INIT) {}
  49. #else
  50. {
  51. shm = shm_t_INIT;
  52. }
  53. #endif
  54. ~BridgeAudioPool() noexcept
  55. {
  56. // should be cleared by now
  57. CARLA_SAFE_ASSERT(data == nullptr);
  58. clear();
  59. }
  60. bool initialize() noexcept
  61. {
  62. char tmpFileBase[64];
  63. std::sprintf(tmpFileBase, PLUGIN_BRIDGE_NAMEPREFIX_AUDIO_POOL "XXXXXX");
  64. shm = carla_shm_create_temp(tmpFileBase);
  65. if (! carla_is_shm_valid(shm))
  66. return false;
  67. filename = tmpFileBase;
  68. return true;
  69. }
  70. void clear() noexcept
  71. {
  72. filename.clear();
  73. if (! carla_is_shm_valid(shm))
  74. {
  75. CARLA_SAFE_ASSERT(data == nullptr);
  76. return;
  77. }
  78. if (data != nullptr)
  79. {
  80. carla_shm_unmap(shm, data);
  81. data = nullptr;
  82. }
  83. size = 0;
  84. carla_shm_close(shm);
  85. carla_shm_init(shm);
  86. }
  87. void resize(const uint32_t bufferSize, const uint32_t audioPortCount, const uint32_t cvPortCount) noexcept
  88. {
  89. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm),);
  90. if (data != nullptr)
  91. carla_shm_unmap(shm, data);
  92. size = (audioPortCount+cvPortCount)*bufferSize*sizeof(float);
  93. if (size == 0)
  94. size = sizeof(float);
  95. data = (float*)carla_shm_map(shm, size);
  96. }
  97. CARLA_DECLARE_NON_COPY_STRUCT(BridgeAudioPool)
  98. };
  99. // -------------------------------------------------------------------------------------------------------------------
  100. struct BridgeRtClientControl : public CarlaRingBufferControl<SmallStackBuffer> {
  101. BridgeRtClientData* data;
  102. CarlaString filename;
  103. bool needsSemDestroy;
  104. shm_t shm;
  105. BridgeRtClientControl()
  106. : data(nullptr),
  107. filename(),
  108. needsSemDestroy(false),
  109. #ifdef CARLA_PROPER_CPP11_SUPPORT
  110. shm(shm_t_INIT) {}
  111. #else
  112. {
  113. shm = shm_t_INIT;
  114. }
  115. #endif
  116. ~BridgeRtClientControl() noexcept override
  117. {
  118. // should be cleared by now
  119. CARLA_SAFE_ASSERT(data == nullptr);
  120. clear();
  121. }
  122. bool initialize() noexcept
  123. {
  124. char tmpFileBase[64];
  125. std::sprintf(tmpFileBase, PLUGIN_BRIDGE_NAMEPREFIX_RT_CLIENT "XXXXXX");
  126. shm = carla_shm_create_temp(tmpFileBase);
  127. if (! carla_is_shm_valid(shm))
  128. return false;
  129. if (! mapData())
  130. {
  131. carla_shm_close(shm);
  132. carla_shm_init(shm);
  133. return false;
  134. }
  135. CARLA_SAFE_ASSERT(data != nullptr);
  136. if (! jackbridge_sem_init(&data->sem.server))
  137. {
  138. unmapData();
  139. carla_shm_close(shm);
  140. carla_shm_init(shm);
  141. return false;
  142. }
  143. if (! jackbridge_sem_init(&data->sem.client))
  144. {
  145. jackbridge_sem_destroy(&data->sem.server);
  146. unmapData();
  147. carla_shm_close(shm);
  148. carla_shm_init(shm);
  149. return false;
  150. }
  151. filename = tmpFileBase;
  152. needsSemDestroy = true;
  153. return true;
  154. }
  155. void clear() noexcept
  156. {
  157. filename.clear();
  158. if (needsSemDestroy)
  159. {
  160. jackbridge_sem_destroy(&data->sem.client);
  161. jackbridge_sem_destroy(&data->sem.server);
  162. needsSemDestroy = false;
  163. }
  164. if (data != nullptr)
  165. unmapData();
  166. if (! carla_is_shm_valid(shm))
  167. return;
  168. carla_shm_close(shm);
  169. carla_shm_init(shm);
  170. }
  171. bool mapData() noexcept
  172. {
  173. CARLA_SAFE_ASSERT(data == nullptr);
  174. if (carla_shm_map<BridgeRtClientData>(shm, data))
  175. {
  176. carla_zeroStruct(data->sem);
  177. carla_zeroStruct(data->timeInfo);
  178. carla_zeroBytes(data->midiOut, kBridgeRtClientDataMidiOutSize);
  179. setRingBuffer(&data->ringBuffer, true);
  180. return true;
  181. }
  182. return false;
  183. }
  184. void unmapData() noexcept
  185. {
  186. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  187. carla_shm_unmap(shm, data);
  188. data = nullptr;
  189. setRingBuffer(nullptr, false);
  190. }
  191. bool waitForClient(const uint secs) noexcept
  192. {
  193. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  194. jackbridge_sem_post(&data->sem.server);
  195. return jackbridge_sem_timedwait(&data->sem.client, secs);
  196. }
  197. void writeOpcode(const PluginBridgeRtClientOpcode opcode) noexcept
  198. {
  199. writeUInt(static_cast<uint32_t>(opcode));
  200. }
  201. CARLA_DECLARE_NON_COPY_STRUCT(BridgeRtClientControl)
  202. };
  203. // -------------------------------------------------------------------------------------------------------------------
  204. struct BridgeNonRtClientControl : public CarlaRingBufferControl<BigStackBuffer> {
  205. BridgeNonRtClientData* data;
  206. CarlaString filename;
  207. CarlaMutex mutex;
  208. shm_t shm;
  209. BridgeNonRtClientControl() noexcept
  210. : data(nullptr),
  211. filename(),
  212. mutex()
  213. #ifdef CARLA_PROPER_CPP11_SUPPORT
  214. , shm(shm_t_INIT) {}
  215. #else
  216. {
  217. shm = shm_t_INIT;
  218. }
  219. #endif
  220. ~BridgeNonRtClientControl() noexcept override
  221. {
  222. // should be cleared by now
  223. CARLA_SAFE_ASSERT(data == nullptr);
  224. clear();
  225. }
  226. bool initialize() noexcept
  227. {
  228. char tmpFileBase[64];
  229. std::sprintf(tmpFileBase, PLUGIN_BRIDGE_NAMEPREFIX_NON_RT_CLIENT "XXXXXX");
  230. shm = carla_shm_create_temp(tmpFileBase);
  231. if (! carla_is_shm_valid(shm))
  232. return false;
  233. if (! mapData())
  234. {
  235. carla_shm_close(shm);
  236. carla_shm_init(shm);
  237. return false;
  238. }
  239. CARLA_SAFE_ASSERT(data != nullptr);
  240. filename = tmpFileBase;
  241. return true;
  242. }
  243. void clear() noexcept
  244. {
  245. filename.clear();
  246. if (data != nullptr)
  247. unmapData();
  248. if (! carla_is_shm_valid(shm))
  249. return;
  250. carla_shm_close(shm);
  251. carla_shm_init(shm);
  252. }
  253. bool mapData() noexcept
  254. {
  255. CARLA_SAFE_ASSERT(data == nullptr);
  256. if (carla_shm_map<BridgeNonRtClientData>(shm, data))
  257. {
  258. setRingBuffer(&data->ringBuffer, true);
  259. return true;
  260. }
  261. return false;
  262. }
  263. void unmapData() noexcept
  264. {
  265. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  266. carla_shm_unmap(shm, data);
  267. data = nullptr;
  268. setRingBuffer(nullptr, false);
  269. }
  270. void writeOpcode(const PluginBridgeNonRtClientOpcode opcode) noexcept
  271. {
  272. writeUInt(static_cast<uint32_t>(opcode));
  273. }
  274. void waitIfDataIsReachingLimit() noexcept
  275. {
  276. if (getAvailableDataSize() < BigStackBuffer::size/4)
  277. return;
  278. for (int i=50; --i >= 0;)
  279. {
  280. if (getAvailableDataSize() >= BigStackBuffer::size*3/4)
  281. {
  282. //carla_stdout("Server waitIfDataIsReachingLimit() reached and waited successfully");
  283. writeOpcode(kPluginBridgeNonRtClientPing);
  284. commitWrite();
  285. return;
  286. }
  287. carla_msleep(20);
  288. }
  289. carla_stderr("Server waitIfDataIsReachingLimit() reached and failed");
  290. }
  291. CARLA_DECLARE_NON_COPY_STRUCT(BridgeNonRtClientControl)
  292. };
  293. // -------------------------------------------------------------------------------------------------------------------
  294. struct BridgeNonRtServerControl : public CarlaRingBufferControl<HugeStackBuffer> {
  295. BridgeNonRtServerData* data;
  296. CarlaString filename;
  297. shm_t shm;
  298. BridgeNonRtServerControl() noexcept
  299. : data(nullptr),
  300. filename()
  301. #ifdef CARLA_PROPER_CPP11_SUPPORT
  302. , shm(shm_t_INIT) {}
  303. #else
  304. {
  305. shm = shm_t_INIT;
  306. }
  307. #endif
  308. ~BridgeNonRtServerControl() noexcept override
  309. {
  310. // should be cleared by now
  311. CARLA_SAFE_ASSERT(data == nullptr);
  312. clear();
  313. }
  314. bool initialize() noexcept
  315. {
  316. char tmpFileBase[64];
  317. std::sprintf(tmpFileBase, PLUGIN_BRIDGE_NAMEPREFIX_NON_RT_SERVER "XXXXXX");
  318. shm = carla_shm_create_temp(tmpFileBase);
  319. if (! carla_is_shm_valid(shm))
  320. return false;
  321. if (! mapData())
  322. {
  323. carla_shm_close(shm);
  324. carla_shm_init(shm);
  325. return false;
  326. }
  327. CARLA_SAFE_ASSERT(data != nullptr);
  328. filename = tmpFileBase;
  329. return true;
  330. }
  331. void clear() noexcept
  332. {
  333. filename.clear();
  334. if (data != nullptr)
  335. unmapData();
  336. if (! carla_is_shm_valid(shm))
  337. return;
  338. carla_shm_close(shm);
  339. carla_shm_init(shm);
  340. }
  341. bool mapData() noexcept
  342. {
  343. CARLA_SAFE_ASSERT(data == nullptr);
  344. if (carla_shm_map<BridgeNonRtServerData>(shm, data))
  345. {
  346. setRingBuffer(&data->ringBuffer, true);
  347. return true;
  348. }
  349. return false;
  350. }
  351. void unmapData() noexcept
  352. {
  353. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  354. carla_shm_unmap(shm, data);
  355. data = nullptr;
  356. setRingBuffer(nullptr, false);
  357. }
  358. PluginBridgeNonRtServerOpcode readOpcode() noexcept
  359. {
  360. return static_cast<PluginBridgeNonRtServerOpcode>(readUInt());
  361. }
  362. CARLA_DECLARE_NON_COPY_STRUCT(BridgeNonRtServerControl)
  363. };
  364. // -------------------------------------------------------------------------------------------------------------------
  365. struct BridgeParamInfo {
  366. float value;
  367. CarlaString name;
  368. CarlaString symbol;
  369. CarlaString unit;
  370. BridgeParamInfo() noexcept
  371. : value(0.0f),
  372. name(),
  373. symbol(),
  374. unit() {}
  375. CARLA_DECLARE_NON_COPY_STRUCT(BridgeParamInfo)
  376. };
  377. // -------------------------------------------------------------------------------------------------------------------
  378. class CarlaPluginBridgeThread : public CarlaThread
  379. {
  380. public:
  381. CarlaPluginBridgeThread(CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  382. : CarlaThread("CarlaPluginBridgeThread"),
  383. kEngine(engine),
  384. kPlugin(plugin),
  385. fBinary(),
  386. fLabel(),
  387. fShmIds(),
  388. fProcess(),
  389. leakDetector_CarlaPluginBridgeThread() {}
  390. void setData(const char* const binary, const char* const label, const char* const shmIds) noexcept
  391. {
  392. CARLA_SAFE_ASSERT_RETURN(binary != nullptr && binary[0] != '\0',);
  393. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  394. CARLA_SAFE_ASSERT(! isThreadRunning());
  395. fBinary = binary;
  396. fShmIds = shmIds;
  397. if (label != nullptr)
  398. fLabel = label;
  399. if (fLabel.isEmpty())
  400. fLabel = "\"\"";
  401. }
  402. uintptr_t getProcessPID() const noexcept
  403. {
  404. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  405. return (uintptr_t)fProcess->getPID();
  406. }
  407. protected:
  408. void run()
  409. {
  410. if (fProcess == nullptr)
  411. {
  412. fProcess = new ChildProcess();
  413. }
  414. else if (fProcess->isRunning())
  415. {
  416. carla_stderr("CarlaPluginBridgeThread::run() - already running, giving up...");
  417. }
  418. String name(kPlugin->getName());
  419. String filename(kPlugin->getFilename());
  420. if (name.isEmpty())
  421. name = "(none)";
  422. if (filename.isEmpty())
  423. filename = "\"\"";
  424. StringArray arguments;
  425. #ifndef CARLA_OS_WIN
  426. // start with "wine" if needed
  427. if (fBinary.endsWithIgnoreCase(".exe"))
  428. arguments.add("wine");
  429. #endif
  430. // binary
  431. arguments.add(fBinary);
  432. // plugin type
  433. arguments.add(getPluginTypeAsString(kPlugin->getType()));
  434. // filename
  435. arguments.add(filename);
  436. // label
  437. arguments.add(fLabel);
  438. // uniqueId
  439. arguments.add(String(static_cast<juce::int64>(kPlugin->getUniqueId())));
  440. bool started;
  441. {
  442. char strBuf[STR_MAX+1];
  443. strBuf[STR_MAX] = '\0';
  444. const EngineOptions& options(kEngine->getOptions());
  445. const ScopedEngineEnvironmentLocker _seel(kEngine);
  446. #ifdef CARLA_OS_LINUX
  447. const char* const oldPreload(std::getenv("LD_PRELOAD"));
  448. if (oldPreload != nullptr)
  449. ::unsetenv("LD_PRELOAD");
  450. #endif
  451. carla_setenv("ENGINE_OPTION_FORCE_STEREO", bool2str(options.forceStereo));
  452. carla_setenv("ENGINE_OPTION_PREFER_PLUGIN_BRIDGES", bool2str(options.preferPluginBridges));
  453. carla_setenv("ENGINE_OPTION_PREFER_UI_BRIDGES", bool2str(options.preferUiBridges));
  454. carla_setenv("ENGINE_OPTION_UIS_ALWAYS_ON_TOP", bool2str(options.uisAlwaysOnTop));
  455. std::snprintf(strBuf, STR_MAX, "%u", options.maxParameters);
  456. carla_setenv("ENGINE_OPTION_MAX_PARAMETERS", strBuf);
  457. std::snprintf(strBuf, STR_MAX, "%u", options.uiBridgesTimeout);
  458. carla_setenv("ENGINE_OPTION_UI_BRIDGES_TIMEOUT",strBuf);
  459. if (options.pathLADSPA != nullptr)
  460. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LADSPA", options.pathLADSPA);
  461. else
  462. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LADSPA", "");
  463. if (options.pathDSSI != nullptr)
  464. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_DSSI", options.pathDSSI);
  465. else
  466. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_DSSI", "");
  467. if (options.pathLV2 != nullptr)
  468. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LV2", options.pathLV2);
  469. else
  470. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_LV2", "");
  471. if (options.pathVST2 != nullptr)
  472. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST2", options.pathVST2);
  473. else
  474. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST2", "");
  475. if (options.pathVST3 != nullptr)
  476. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST3", options.pathVST3);
  477. else
  478. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_VST3", "");
  479. if (options.pathAU != nullptr)
  480. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_AU", options.pathAU);
  481. else
  482. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_AU", "");
  483. if (options.pathGIG != nullptr)
  484. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_GIG", options.pathGIG);
  485. else
  486. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_GIG", "");
  487. if (options.pathSF2 != nullptr)
  488. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SF2", options.pathSF2);
  489. else
  490. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SF2", "");
  491. if (options.pathSFZ != nullptr)
  492. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SFZ", options.pathSFZ);
  493. else
  494. carla_setenv("ENGINE_OPTION_PLUGIN_PATH_SFZ", "");
  495. if (options.binaryDir != nullptr)
  496. carla_setenv("ENGINE_OPTION_PATH_BINARIES", options.binaryDir);
  497. else
  498. carla_setenv("ENGINE_OPTION_PATH_BINARIES", "");
  499. if (options.resourceDir != nullptr)
  500. carla_setenv("ENGINE_OPTION_PATH_RESOURCES", options.resourceDir);
  501. else
  502. carla_setenv("ENGINE_OPTION_PATH_RESOURCES", "");
  503. carla_setenv("ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR", bool2str(options.preventBadBehaviour));
  504. std::snprintf(strBuf, STR_MAX, P_UINTPTR, options.frontendWinId);
  505. carla_setenv("ENGINE_OPTION_FRONTEND_WIN_ID", strBuf);
  506. carla_setenv("ENGINE_BRIDGE_SHM_IDS", fShmIds.toRawUTF8());
  507. carla_setenv("WINEDEBUG", "-all");
  508. carla_stdout("starting plugin bridge, command is:\n%s \"%s\" \"%s\" \"%s\" " P_INT64,
  509. fBinary.toRawUTF8(), getPluginTypeAsString(kPlugin->getType()), filename.toRawUTF8(), fLabel.toRawUTF8(), kPlugin->getUniqueId());
  510. started = fProcess->start(arguments);
  511. #ifdef CARLA_OS_LINUX
  512. if (oldPreload != nullptr)
  513. ::setenv("LD_PRELOAD", oldPreload, 1);
  514. #endif
  515. }
  516. if (! started)
  517. {
  518. carla_stdout("failed!");
  519. fProcess = nullptr;
  520. return;
  521. }
  522. for (; fProcess->isRunning() && ! shouldThreadExit();)
  523. carla_sleep(1);
  524. // we only get here if bridge crashed or thread asked to exit
  525. if (fProcess->isRunning() && shouldThreadExit())
  526. {
  527. fProcess->waitForProcessToFinish(2000);
  528. if (fProcess->isRunning())
  529. {
  530. carla_stdout("CarlaPluginBridgeThread::run() - bridge refused to close, force kill now");
  531. fProcess->kill();
  532. }
  533. else
  534. {
  535. carla_stdout("CarlaPluginBridgeThread::run() - bridge auto-closed successfully");
  536. }
  537. }
  538. else
  539. {
  540. // forced quit, may have crashed
  541. if (fProcess->getExitCode() != 0 /*|| fProcess->exitStatus() == QProcess::CrashExit*/)
  542. {
  543. carla_stderr("CarlaPluginBridgeThread::run() - bridge crashed");
  544. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  545. "Saving now will lose its current settings.\n"
  546. "Please remove this plugin, and not rely on it from this point.");
  547. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_ERROR, kPlugin->getId(), 0, 0, 0.0f, errorString);
  548. }
  549. else
  550. carla_stderr("CarlaPluginBridgeThread::run() - bridge closed cleanly");
  551. }
  552. carla_stdout("plugin bridge finished");
  553. fProcess = nullptr;
  554. }
  555. private:
  556. CarlaEngine* const kEngine;
  557. CarlaPlugin* const kPlugin;
  558. String fBinary;
  559. String fLabel;
  560. String fShmIds;
  561. ScopedPointer<ChildProcess> fProcess;
  562. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginBridgeThread)
  563. };
  564. // -------------------------------------------------------------------------------------------------------------------
  565. class CarlaPluginBridge : public CarlaPlugin
  566. {
  567. public:
  568. CarlaPluginBridge(CarlaEngine* const engine, const uint id, const BinaryType btype, const PluginType ptype)
  569. : CarlaPlugin(engine, id),
  570. fBinaryType(btype),
  571. fPluginType(ptype),
  572. fInitiated(false),
  573. fInitError(false),
  574. fSaved(false),
  575. fTimedOut(false),
  576. fLastPongCounter(-1),
  577. fBridgeBinary(),
  578. fBridgeThread(engine, this),
  579. fShmAudioPool(),
  580. fShmRtClientControl(),
  581. fShmNonRtClientControl(),
  582. fShmNonRtServerControl(),
  583. fInfo(),
  584. fParams(nullptr),
  585. leakDetector_CarlaPluginBridge()
  586. {
  587. carla_debug("CarlaPluginBridge::CarlaPluginBridge(%p, %i, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  588. pData->hints |= PLUGIN_IS_BRIDGE;
  589. }
  590. ~CarlaPluginBridge() override
  591. {
  592. carla_debug("CarlaPluginBridge::~CarlaPluginBridge()");
  593. // close UI
  594. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  595. pData->transientTryCounter = 0;
  596. pData->singleMutex.lock();
  597. pData->masterMutex.lock();
  598. if (pData->client != nullptr && pData->client->isActive())
  599. pData->client->deactivate();
  600. if (pData->active)
  601. {
  602. deactivate();
  603. pData->active = false;
  604. }
  605. if (fBridgeThread.isThreadRunning())
  606. {
  607. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  608. fShmNonRtClientControl.commitWrite();
  609. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  610. fShmRtClientControl.commitWrite();
  611. if (! fTimedOut)
  612. fShmRtClientControl.waitForClient(3);
  613. }
  614. fBridgeThread.stopThread(3000);
  615. fShmNonRtServerControl.clear();
  616. fShmNonRtClientControl.clear();
  617. fShmRtClientControl.clear();
  618. fShmAudioPool.clear();
  619. clearBuffers();
  620. fInfo.chunk.clear();
  621. }
  622. // -------------------------------------------------------------------
  623. // Information (base)
  624. BinaryType getBinaryType() const noexcept
  625. {
  626. return fBinaryType;
  627. }
  628. PluginType getType() const noexcept override
  629. {
  630. return fPluginType;
  631. }
  632. PluginCategory getCategory() const noexcept override
  633. {
  634. return fInfo.category;
  635. }
  636. int64_t getUniqueId() const noexcept override
  637. {
  638. return fInfo.uniqueId;
  639. }
  640. // -------------------------------------------------------------------
  641. // Information (count)
  642. uint32_t getMidiInCount() const noexcept override
  643. {
  644. return fInfo.mIns;
  645. }
  646. uint32_t getMidiOutCount() const noexcept override
  647. {
  648. return fInfo.mOuts;
  649. }
  650. // -------------------------------------------------------------------
  651. // Information (current data)
  652. std::size_t getChunkData(void** const dataPtr) noexcept override
  653. {
  654. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  655. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  656. CARLA_SAFE_ASSERT_RETURN(fInfo.chunk.size() > 0, 0);
  657. *dataPtr = fInfo.chunk.data();
  658. return fInfo.chunk.size();
  659. }
  660. // -------------------------------------------------------------------
  661. // Information (per-plugin data)
  662. uint getOptionsAvailable() const noexcept override
  663. {
  664. return fInfo.optionsAvailable;
  665. }
  666. float getParameterValue(const uint32_t parameterId) const noexcept override
  667. {
  668. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  669. return fParams[parameterId].value;
  670. }
  671. void getLabel(char* const strBuf) const noexcept override
  672. {
  673. std::strncpy(strBuf, fInfo.label, STR_MAX);
  674. }
  675. void getMaker(char* const strBuf) const noexcept override
  676. {
  677. std::strncpy(strBuf, fInfo.maker, STR_MAX);
  678. }
  679. void getCopyright(char* const strBuf) const noexcept override
  680. {
  681. std::strncpy(strBuf, fInfo.copyright, STR_MAX);
  682. }
  683. void getRealName(char* const strBuf) const noexcept override
  684. {
  685. std::strncpy(strBuf, fInfo.name, STR_MAX);
  686. }
  687. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  688. {
  689. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  690. std::strncpy(strBuf, fParams[parameterId].name.buffer(), STR_MAX);
  691. }
  692. void getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  693. {
  694. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  695. std::strncpy(strBuf, fParams[parameterId].symbol.buffer(), STR_MAX);
  696. }
  697. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  698. {
  699. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, nullStrBuf(strBuf));
  700. std::strncpy(strBuf, fParams[parameterId].unit.buffer(), STR_MAX);
  701. }
  702. // -------------------------------------------------------------------
  703. // Set data (state)
  704. void prepareForSave() override
  705. {
  706. fSaved = false;
  707. {
  708. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  709. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPrepareForSave);
  710. fShmNonRtClientControl.commitWrite();
  711. }
  712. carla_stdout("CarlaPluginBridge::prepareForSave() - sent, now waiting...");
  713. for (int i=0; i < 200; ++i)
  714. {
  715. if (fSaved)
  716. break;
  717. carla_msleep(30);
  718. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  719. pData->engine->idle();
  720. }
  721. if (! fSaved)
  722. carla_stderr("CarlaPluginBridge::prepareForSave() - Timeout while requesting save state");
  723. else
  724. carla_stdout("CarlaPluginBridge::prepareForSave() - success!");
  725. }
  726. // -------------------------------------------------------------------
  727. // Set data (internal stuff)
  728. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  729. {
  730. {
  731. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  732. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  733. fShmNonRtClientControl.writeUInt(option);
  734. fShmNonRtClientControl.writeBool(yesNo);
  735. fShmNonRtClientControl.commitWrite();
  736. }
  737. CarlaPlugin::setOption(option, yesNo, sendCallback);
  738. }
  739. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  740. {
  741. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  742. {
  743. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  744. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  745. fShmNonRtClientControl.writeShort(channel);
  746. fShmNonRtClientControl.commitWrite();
  747. }
  748. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  749. }
  750. // -------------------------------------------------------------------
  751. // Set data (plugin-specific stuff)
  752. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  753. {
  754. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,); // never call this from RT
  755. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  756. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  757. fParams[parameterId].value = fixedValue;
  758. {
  759. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  760. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterValue);
  761. fShmNonRtClientControl.writeUInt(parameterId);
  762. fShmNonRtClientControl.writeFloat(value);
  763. fShmNonRtClientControl.commitWrite();
  764. fShmNonRtClientControl.waitIfDataIsReachingLimit();
  765. }
  766. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  767. }
  768. void setParameterMidiChannel(const uint32_t parameterId, const uint8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  769. {
  770. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  771. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  772. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  773. {
  774. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  775. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMidiChannel);
  776. fShmNonRtClientControl.writeUInt(parameterId);
  777. fShmNonRtClientControl.writeByte(channel);
  778. fShmNonRtClientControl.commitWrite();
  779. }
  780. CarlaPlugin::setParameterMidiChannel(parameterId, channel, sendOsc, sendCallback);
  781. }
  782. void setParameterMidiCC(const uint32_t parameterId, const int16_t cc, const bool sendOsc, const bool sendCallback) noexcept override
  783. {
  784. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  785. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  786. CARLA_SAFE_ASSERT_RETURN(cc >= -1 && cc < MAX_MIDI_CONTROL,);
  787. {
  788. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  789. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetParameterMidiCC);
  790. fShmNonRtClientControl.writeUInt(parameterId);
  791. fShmNonRtClientControl.writeShort(cc);
  792. fShmNonRtClientControl.commitWrite();
  793. }
  794. CarlaPlugin::setParameterMidiCC(parameterId, cc, sendOsc, sendCallback);
  795. }
  796. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  797. {
  798. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,); // never call this from RT
  799. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  800. {
  801. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  802. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetProgram);
  803. fShmNonRtClientControl.writeInt(index);
  804. fShmNonRtClientControl.commitWrite();
  805. }
  806. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  807. }
  808. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  809. {
  810. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,); // never call this from RT
  811. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  812. {
  813. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  814. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetMidiProgram);
  815. fShmNonRtClientControl.writeInt(index);
  816. fShmNonRtClientControl.commitWrite();
  817. }
  818. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  819. }
  820. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  821. {
  822. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  823. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  824. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  825. const uint32_t typeLen(static_cast<uint32_t>(std::strlen(type)));
  826. const uint32_t keyLen(static_cast<uint32_t>(std::strlen(key)));
  827. const uint32_t valueLen(static_cast<uint32_t>(std::strlen(value)));
  828. {
  829. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  830. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCustomData);
  831. fShmNonRtClientControl.writeUInt(typeLen);
  832. fShmNonRtClientControl.writeCustomData(type, typeLen);
  833. fShmNonRtClientControl.writeUInt(keyLen);
  834. fShmNonRtClientControl.writeCustomData(key, keyLen);
  835. fShmNonRtClientControl.writeUInt(valueLen);
  836. fShmNonRtClientControl.writeCustomData(value, valueLen);
  837. fShmNonRtClientControl.commitWrite();
  838. }
  839. CarlaPlugin::setCustomData(type, key, value, sendGui);
  840. }
  841. void setChunkData(const void* const data, const std::size_t dataSize) override
  842. {
  843. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  844. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  845. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  846. CarlaString dataBase64(CarlaString::asBase64(data, dataSize));
  847. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0,);
  848. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  849. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  850. filePath += fShmAudioPool.filename.buffer() + 18;
  851. if (File(filePath).replaceWithText(dataBase64.buffer()))
  852. {
  853. const uint32_t ulength(static_cast<uint32_t>(filePath.length()));
  854. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  855. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetChunkDataFile);
  856. fShmNonRtClientControl.writeUInt(ulength);
  857. fShmNonRtClientControl.writeCustomData(filePath.toRawUTF8(), ulength);
  858. fShmNonRtClientControl.commitWrite();
  859. }
  860. }
  861. // -------------------------------------------------------------------
  862. // Set ui stuff
  863. void showCustomUI(const bool yesNo) override
  864. {
  865. {
  866. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  867. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  868. fShmNonRtClientControl.commitWrite();
  869. }
  870. if (yesNo)
  871. {
  872. pData->tryTransient();
  873. }
  874. else
  875. {
  876. pData->transientTryCounter = 0;
  877. }
  878. }
  879. void idle() override
  880. {
  881. if (fBridgeThread.isThreadRunning())
  882. {
  883. if (fInitiated && fTimedOut && pData->active)
  884. setActive(false, true, true);
  885. {
  886. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  887. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  888. fShmNonRtClientControl.commitWrite();
  889. }
  890. try {
  891. handleNonRtData();
  892. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  893. }
  894. else
  895. carla_stderr2("TESTING: Bridge has closed!");
  896. CarlaPlugin::idle();
  897. }
  898. // -------------------------------------------------------------------
  899. // Plugin state
  900. void reload() override
  901. {
  902. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  903. carla_debug("CarlaPluginBridge::reload() - start");
  904. const EngineProcessMode processMode(pData->engine->getProccessMode());
  905. // Safely disable plugin for reload
  906. const ScopedDisabler sd(this);
  907. bool needsCtrlIn, needsCtrlOut;
  908. needsCtrlIn = needsCtrlOut = false;
  909. if (fInfo.aIns > 0)
  910. {
  911. pData->audioIn.createNew(fInfo.aIns);
  912. }
  913. if (fInfo.aOuts > 0)
  914. {
  915. pData->audioOut.createNew(fInfo.aOuts);
  916. needsCtrlIn = true;
  917. }
  918. if (fInfo.cvIns > 0)
  919. {
  920. pData->cvIn.createNew(fInfo.cvIns);
  921. }
  922. if (fInfo.cvOuts > 0)
  923. {
  924. pData->cvOut.createNew(fInfo.cvOuts);
  925. }
  926. if (fInfo.mIns > 0)
  927. needsCtrlIn = true;
  928. if (fInfo.mOuts > 0)
  929. needsCtrlOut = true;
  930. const uint portNameSize(pData->engine->getMaxPortNameSize());
  931. CarlaString portName;
  932. // Audio Ins
  933. for (uint32_t j=0; j < fInfo.aIns; ++j)
  934. {
  935. portName.clear();
  936. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  937. {
  938. portName = pData->name;
  939. portName += ":";
  940. }
  941. if (fInfo.aIns > 1)
  942. {
  943. portName += "input_";
  944. portName += CarlaString(j+1);
  945. }
  946. else
  947. portName += "input";
  948. portName.truncate(portNameSize);
  949. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  950. pData->audioIn.ports[j].rindex = j;
  951. }
  952. // Audio Outs
  953. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  954. {
  955. portName.clear();
  956. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  957. {
  958. portName = pData->name;
  959. portName += ":";
  960. }
  961. if (fInfo.aOuts > 1)
  962. {
  963. portName += "output_";
  964. portName += CarlaString(j+1);
  965. }
  966. else
  967. portName += "output";
  968. portName.truncate(portNameSize);
  969. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  970. pData->audioOut.ports[j].rindex = j;
  971. }
  972. // TODO - CV
  973. if (needsCtrlIn)
  974. {
  975. portName.clear();
  976. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  977. {
  978. portName = pData->name;
  979. portName += ":";
  980. }
  981. portName += "event-in";
  982. portName.truncate(portNameSize);
  983. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  984. }
  985. if (needsCtrlOut)
  986. {
  987. portName.clear();
  988. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  989. {
  990. portName = pData->name;
  991. portName += ":";
  992. }
  993. portName += "event-out";
  994. portName.truncate(portNameSize);
  995. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  996. }
  997. // extra plugin hints
  998. pData->extraHints = 0x0;
  999. if (fInfo.mIns > 0)
  1000. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  1001. if (fInfo.mOuts > 0)
  1002. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  1003. if (fInfo.aIns <= 2 && fInfo.aOuts <= 2 && (fInfo.aIns == fInfo.aOuts || fInfo.aIns == 0 || fInfo.aOuts == 0))
  1004. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  1005. bufferSizeChanged(pData->engine->getBufferSize());
  1006. reloadPrograms(true);
  1007. carla_debug("CarlaPluginBridge::reload() - end");
  1008. }
  1009. // -------------------------------------------------------------------
  1010. // Plugin processing
  1011. void activate() noexcept override
  1012. {
  1013. {
  1014. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1015. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  1016. fShmNonRtClientControl.commitWrite();
  1017. }
  1018. bool timedOut = true;
  1019. try {
  1020. timedOut = waitForClient(1);
  1021. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  1022. if (! timedOut)
  1023. fTimedOut = false;
  1024. }
  1025. void deactivate() noexcept override
  1026. {
  1027. {
  1028. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1029. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  1030. fShmNonRtClientControl.commitWrite();
  1031. }
  1032. bool timedOut = true;
  1033. try {
  1034. timedOut = waitForClient(1);
  1035. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  1036. if (! timedOut)
  1037. fTimedOut = false;
  1038. }
  1039. void process(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames) override
  1040. {
  1041. // --------------------------------------------------------------------------------------------------------
  1042. // Check if active
  1043. if (fTimedOut || ! pData->active)
  1044. {
  1045. // disable any output sound
  1046. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1047. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  1048. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1049. FloatVectorOperations::clear(cvOut[i], static_cast<int>(frames));
  1050. return;
  1051. }
  1052. // --------------------------------------------------------------------------------------------------------
  1053. // Check if needs reset
  1054. if (pData->needsReset)
  1055. {
  1056. // TODO
  1057. pData->needsReset = false;
  1058. }
  1059. // --------------------------------------------------------------------------------------------------------
  1060. // Event Input
  1061. if (pData->event.portIn != nullptr)
  1062. {
  1063. // ----------------------------------------------------------------------------------------------------
  1064. // MIDI Input (External)
  1065. if (pData->extNotes.mutex.tryLock())
  1066. {
  1067. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin(); it.valid(); it.next())
  1068. {
  1069. const ExternalMidiNote& note(it.getValue());
  1070. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1071. uint8_t data1, data2, data3;
  1072. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  1073. data2 = note.note;
  1074. data3 = note.velo;
  1075. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1076. fShmRtClientControl.writeUInt(0); // time
  1077. fShmRtClientControl.writeByte(0); // port
  1078. fShmRtClientControl.writeByte(3); // size
  1079. fShmRtClientControl.writeByte(data1);
  1080. fShmRtClientControl.writeByte(data2);
  1081. fShmRtClientControl.writeByte(data3);
  1082. fShmRtClientControl.commitWrite();
  1083. }
  1084. pData->extNotes.data.clear();
  1085. pData->extNotes.mutex.unlock();
  1086. } // End of MIDI Input (External)
  1087. // ----------------------------------------------------------------------------------------------------
  1088. // Event Input (System)
  1089. bool allNotesOffSent = false;
  1090. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1091. {
  1092. const EngineEvent& event(pData->event.portIn->getEvent(i));
  1093. // Control change
  1094. switch (event.type)
  1095. {
  1096. case kEngineEventTypeNull:
  1097. break;
  1098. case kEngineEventTypeControl: {
  1099. const EngineControlEvent& ctrlEvent = event.ctrl;
  1100. switch (ctrlEvent.type)
  1101. {
  1102. case kEngineControlEventTypeNull:
  1103. break;
  1104. case kEngineControlEventTypeParameter:
  1105. // Control backend stuff
  1106. if (event.channel == pData->ctrlChannel)
  1107. {
  1108. float value;
  1109. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1110. {
  1111. value = ctrlEvent.value;
  1112. setDryWet(value, false, false);
  1113. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  1114. break;
  1115. }
  1116. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1117. {
  1118. value = ctrlEvent.value*127.0f/100.0f;
  1119. setVolume(value, false, false);
  1120. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  1121. break;
  1122. }
  1123. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1124. {
  1125. float left, right;
  1126. value = ctrlEvent.value/0.5f - 1.0f;
  1127. if (value < 0.0f)
  1128. {
  1129. left = -1.0f;
  1130. right = (value*2.0f)+1.0f;
  1131. }
  1132. else if (value > 0.0f)
  1133. {
  1134. left = (value*2.0f)-1.0f;
  1135. right = 1.0f;
  1136. }
  1137. else
  1138. {
  1139. left = -1.0f;
  1140. right = 1.0f;
  1141. }
  1142. setBalanceLeft(left, false, false);
  1143. setBalanceRight(right, false, false);
  1144. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  1145. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  1146. break;
  1147. }
  1148. }
  1149. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventParameter);
  1150. fShmRtClientControl.writeUInt(event.time);
  1151. fShmRtClientControl.writeByte(event.channel);
  1152. fShmRtClientControl.writeUShort(event.ctrl.param);
  1153. fShmRtClientControl.writeFloat(event.ctrl.value);
  1154. fShmRtClientControl.commitWrite();
  1155. break;
  1156. case kEngineControlEventTypeMidiBank:
  1157. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1158. {
  1159. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  1160. fShmRtClientControl.writeUInt(event.time);
  1161. fShmRtClientControl.writeByte(event.channel);
  1162. fShmRtClientControl.writeUShort(event.ctrl.param);
  1163. fShmRtClientControl.commitWrite();
  1164. }
  1165. break;
  1166. case kEngineControlEventTypeMidiProgram:
  1167. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1168. {
  1169. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  1170. fShmRtClientControl.writeUInt(event.time);
  1171. fShmRtClientControl.writeByte(event.channel);
  1172. fShmRtClientControl.writeUShort(event.ctrl.param);
  1173. fShmRtClientControl.commitWrite();
  1174. }
  1175. break;
  1176. case kEngineControlEventTypeAllSoundOff:
  1177. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1178. {
  1179. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  1180. fShmRtClientControl.writeUInt(event.time);
  1181. fShmRtClientControl.writeByte(event.channel);
  1182. fShmRtClientControl.commitWrite();
  1183. }
  1184. break;
  1185. case kEngineControlEventTypeAllNotesOff:
  1186. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1187. {
  1188. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1189. {
  1190. allNotesOffSent = true;
  1191. sendMidiAllNotesOffToCallback();
  1192. }
  1193. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  1194. fShmRtClientControl.writeUInt(event.time);
  1195. fShmRtClientControl.writeByte(event.channel);
  1196. fShmRtClientControl.commitWrite();
  1197. }
  1198. break;
  1199. } // switch (ctrlEvent.type)
  1200. break;
  1201. } // case kEngineEventTypeControl
  1202. case kEngineEventTypeMidi: {
  1203. const EngineMidiEvent& midiEvent(event.midi);
  1204. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  1205. continue;
  1206. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  1207. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  1208. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1209. continue;
  1210. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1211. continue;
  1212. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1213. continue;
  1214. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1215. continue;
  1216. // Fix bad note-off
  1217. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  1218. status = MIDI_STATUS_NOTE_OFF;
  1219. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  1220. fShmRtClientControl.writeUInt(event.time);
  1221. fShmRtClientControl.writeByte(midiEvent.port);
  1222. fShmRtClientControl.writeByte(midiEvent.size);
  1223. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  1224. for (uint8_t j=1; j < midiEvent.size; ++j)
  1225. fShmRtClientControl.writeByte(midiData[j]);
  1226. fShmRtClientControl.commitWrite();
  1227. if (status == MIDI_STATUS_NOTE_ON)
  1228. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  1229. else if (status == MIDI_STATUS_NOTE_OFF)
  1230. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  1231. } break;
  1232. }
  1233. }
  1234. pData->postRtEvents.trySplice();
  1235. } // End of Event Input
  1236. processSingle(audioIn, audioOut, cvIn, cvOut, frames);
  1237. }
  1238. bool processSingle(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames)
  1239. {
  1240. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1241. if (pData->audioIn.count > 0)
  1242. {
  1243. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  1244. }
  1245. if (pData->audioOut.count > 0)
  1246. {
  1247. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  1248. }
  1249. if (pData->cvIn.count > 0)
  1250. {
  1251. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  1252. }
  1253. if (pData->cvOut.count > 0)
  1254. {
  1255. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  1256. }
  1257. // --------------------------------------------------------------------------------------------------------
  1258. // Try lock, silence otherwise
  1259. if (pData->engine->isOffline())
  1260. {
  1261. pData->singleMutex.lock();
  1262. }
  1263. else if (! pData->singleMutex.tryLock())
  1264. {
  1265. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1266. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  1267. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1268. FloatVectorOperations::clear(cvOut[i], static_cast<int>(frames));
  1269. return false;
  1270. }
  1271. // --------------------------------------------------------------------------------------------------------
  1272. // Reset audio buffers
  1273. for (uint32_t i=0; i < fInfo.aIns; ++i)
  1274. FloatVectorOperations::copy(fShmAudioPool.data + (i * frames), audioIn[i], static_cast<int>(frames));
  1275. // --------------------------------------------------------------------------------------------------------
  1276. // TimeInfo
  1277. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  1278. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1279. bridgeTimeInfo.playing = timeInfo.playing;
  1280. bridgeTimeInfo.frame = timeInfo.frame;
  1281. bridgeTimeInfo.usecs = timeInfo.usecs;
  1282. bridgeTimeInfo.valid = timeInfo.valid;
  1283. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  1284. {
  1285. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  1286. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  1287. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  1288. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  1289. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  1290. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  1291. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  1292. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  1293. }
  1294. // --------------------------------------------------------------------------------------------------------
  1295. // Run plugin
  1296. {
  1297. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  1298. fShmRtClientControl.commitWrite();
  1299. }
  1300. if (! waitForClient(2))
  1301. {
  1302. pData->singleMutex.unlock();
  1303. return true;
  1304. }
  1305. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  1306. FloatVectorOperations::copy(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), static_cast<int>(frames));
  1307. // --------------------------------------------------------------------------------------------------------
  1308. // Post-processing (dry/wet, volume and balance)
  1309. {
  1310. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && ! carla_compareFloats(pData->postProc.volume, 1.0f);
  1311. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && ! carla_compareFloats(pData->postProc.dryWet, 1.0f);
  1312. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_compareFloats(pData->postProc.balanceLeft, -1.0f) && carla_compareFloats(pData->postProc.balanceRight, 1.0f));
  1313. bool isPair;
  1314. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1315. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1316. {
  1317. // Dry/Wet
  1318. if (doDryWet)
  1319. {
  1320. for (uint32_t k=0; k < frames; ++k)
  1321. {
  1322. bufValue = audioIn[(pData->audioIn.count == 1) ? 0 : i][k];
  1323. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1324. }
  1325. }
  1326. // Balance
  1327. if (doBalance)
  1328. {
  1329. isPair = (i % 2 == 0);
  1330. if (isPair)
  1331. {
  1332. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1333. FloatVectorOperations::copy(oldBufLeft, audioOut[i], static_cast<int>(frames));
  1334. }
  1335. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1336. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1337. for (uint32_t k=0; k < frames; ++k)
  1338. {
  1339. if (isPair)
  1340. {
  1341. // left
  1342. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1343. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  1344. }
  1345. else
  1346. {
  1347. // right
  1348. audioOut[i][k] = audioOut[i][k] * balRangeR;
  1349. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  1350. }
  1351. }
  1352. }
  1353. // Volume (and buffer copy)
  1354. if (doVolume)
  1355. {
  1356. for (uint32_t k=0; k < frames; ++k)
  1357. audioOut[i][k] *= pData->postProc.volume;
  1358. }
  1359. }
  1360. } // End of Post-processing
  1361. // --------------------------------------------------------------------------------------------------------
  1362. pData->singleMutex.unlock();
  1363. return true;
  1364. }
  1365. void bufferSizeChanged(const uint32_t newBufferSize) override
  1366. {
  1367. resizeAudioPool(newBufferSize);
  1368. {
  1369. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1370. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetBufferSize);
  1371. fShmNonRtClientControl.writeUInt(newBufferSize);
  1372. fShmNonRtClientControl.commitWrite();
  1373. }
  1374. fShmRtClientControl.waitForClient(1);
  1375. }
  1376. void sampleRateChanged(const double newSampleRate) override
  1377. {
  1378. {
  1379. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1380. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetSampleRate);
  1381. fShmNonRtClientControl.writeDouble(newSampleRate);
  1382. fShmNonRtClientControl.commitWrite();
  1383. }
  1384. fShmRtClientControl.waitForClient(1);
  1385. }
  1386. void offlineModeChanged(const bool isOffline) override
  1387. {
  1388. {
  1389. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1390. fShmNonRtClientControl.writeOpcode(isOffline ? kPluginBridgeNonRtClientSetOffline : kPluginBridgeNonRtClientSetOnline);
  1391. fShmNonRtClientControl.commitWrite();
  1392. }
  1393. fShmRtClientControl.waitForClient(1);
  1394. }
  1395. // -------------------------------------------------------------------
  1396. // Plugin buffers
  1397. void clearBuffers() noexcept override
  1398. {
  1399. if (fParams != nullptr)
  1400. {
  1401. delete[] fParams;
  1402. fParams = nullptr;
  1403. }
  1404. CarlaPlugin::clearBuffers();
  1405. }
  1406. // -------------------------------------------------------------------
  1407. // Post-poned UI Stuff
  1408. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1409. {
  1410. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1411. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1412. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiParameterChange);
  1413. fShmNonRtClientControl.writeUInt(index);
  1414. fShmNonRtClientControl.writeFloat(value);
  1415. fShmNonRtClientControl.commitWrite();
  1416. }
  1417. void uiProgramChange(const uint32_t index) noexcept override
  1418. {
  1419. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1420. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1421. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiProgramChange);
  1422. fShmNonRtClientControl.writeUInt(index);
  1423. fShmNonRtClientControl.commitWrite();
  1424. }
  1425. void uiMidiProgramChange(const uint32_t index) noexcept override
  1426. {
  1427. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1428. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1429. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiMidiProgramChange);
  1430. fShmNonRtClientControl.writeUInt(index);
  1431. fShmNonRtClientControl.commitWrite();
  1432. }
  1433. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1434. {
  1435. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1436. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1437. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1438. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1439. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOn);
  1440. fShmNonRtClientControl.writeByte(channel);
  1441. fShmNonRtClientControl.writeByte(note);
  1442. fShmNonRtClientControl.writeByte(velo);
  1443. fShmNonRtClientControl.commitWrite();
  1444. }
  1445. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1446. {
  1447. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1448. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1449. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  1450. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientUiNoteOff);
  1451. fShmNonRtClientControl.writeByte(channel);
  1452. fShmNonRtClientControl.writeByte(note);
  1453. fShmNonRtClientControl.commitWrite();
  1454. }
  1455. // -------------------------------------------------------------------
  1456. void handleNonRtData()
  1457. {
  1458. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  1459. {
  1460. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  1461. #ifdef DEBUG
  1462. if (opcode != kPluginBridgeNonRtServerPong) {
  1463. carla_debug("CarlaPluginBridge::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  1464. }
  1465. #endif
  1466. if (opcode != kPluginBridgeNonRtServerNull && fLastPongCounter > 0)
  1467. fLastPongCounter = 0;
  1468. switch (opcode)
  1469. {
  1470. case kPluginBridgeNonRtServerNull:
  1471. case kPluginBridgeNonRtServerPong:
  1472. break;
  1473. case kPluginBridgeNonRtServerPluginInfo1: {
  1474. // uint/category, uint/hints, uint/optionsAvailable, uint/optionsEnabled, long/uniqueId
  1475. const uint32_t category = fShmNonRtServerControl.readUInt();
  1476. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1477. const uint32_t optionAv = fShmNonRtServerControl.readUInt();
  1478. const uint32_t optionEn = fShmNonRtServerControl.readUInt();
  1479. const int64_t uniqueId = fShmNonRtServerControl.readLong();
  1480. pData->hints = hints | PLUGIN_IS_BRIDGE;
  1481. pData->options = optionEn;
  1482. fInfo.category = static_cast<PluginCategory>(category);
  1483. fInfo.uniqueId = uniqueId;
  1484. fInfo.optionsAvailable = optionAv;
  1485. } break;
  1486. case kPluginBridgeNonRtServerPluginInfo2: {
  1487. // uint/size, str[] (realName), uint/size, str[] (label), uint/size, str[] (maker), uint/size, str[] (copyright)
  1488. // realName
  1489. const uint32_t realNameSize(fShmNonRtServerControl.readUInt());
  1490. char realName[realNameSize+1];
  1491. carla_zeroChar(realName, realNameSize+1);
  1492. fShmNonRtServerControl.readCustomData(realName, realNameSize);
  1493. // label
  1494. const uint32_t labelSize(fShmNonRtServerControl.readUInt());
  1495. char label[labelSize+1];
  1496. carla_zeroChar(label, labelSize+1);
  1497. fShmNonRtServerControl.readCustomData(label, labelSize);
  1498. // maker
  1499. const uint32_t makerSize(fShmNonRtServerControl.readUInt());
  1500. char maker[makerSize+1];
  1501. carla_zeroChar(maker, makerSize+1);
  1502. fShmNonRtServerControl.readCustomData(maker, makerSize);
  1503. // copyright
  1504. const uint32_t copyrightSize(fShmNonRtServerControl.readUInt());
  1505. char copyright[copyrightSize+1];
  1506. carla_zeroChar(copyright, copyrightSize+1);
  1507. fShmNonRtServerControl.readCustomData(copyright, copyrightSize);
  1508. fInfo.name = realName;
  1509. fInfo.label = label;
  1510. fInfo.maker = maker;
  1511. fInfo.copyright = copyright;
  1512. if (pData->name == nullptr)
  1513. pData->name = pData->engine->getUniquePluginName(realName);
  1514. } break;
  1515. case kPluginBridgeNonRtServerAudioCount: {
  1516. // uint/ins, uint/outs
  1517. fInfo.aIns = fShmNonRtServerControl.readUInt();
  1518. fInfo.aOuts = fShmNonRtServerControl.readUInt();
  1519. } break;
  1520. case kPluginBridgeNonRtServerMidiCount: {
  1521. // uint/ins, uint/outs
  1522. fInfo.mIns = fShmNonRtServerControl.readUInt();
  1523. fInfo.mOuts = fShmNonRtServerControl.readUInt();
  1524. } break;
  1525. case kPluginBridgeNonRtServerParameterCount: {
  1526. // uint/count
  1527. const uint32_t count = fShmNonRtServerControl.readUInt();
  1528. // delete old data
  1529. pData->param.clear();
  1530. if (fParams != nullptr)
  1531. {
  1532. delete[] fParams;
  1533. fParams = nullptr;
  1534. }
  1535. if (count > 0)
  1536. {
  1537. pData->param.createNew(count, false);
  1538. fParams = new BridgeParamInfo[count];
  1539. // we might not receive all parameter data, so ensure range max is not 0
  1540. for (uint32_t i=0; i<count; ++i)
  1541. {
  1542. pData->param.ranges[i].def = 0.0f;
  1543. pData->param.ranges[i].min = 0.0f;
  1544. pData->param.ranges[i].max = 1.0f;
  1545. pData->param.ranges[i].step = 0.001f;
  1546. pData->param.ranges[i].stepSmall = 0.0001f;
  1547. pData->param.ranges[i].stepLarge = 0.1f;
  1548. }
  1549. }
  1550. } break;
  1551. case kPluginBridgeNonRtServerProgramCount: {
  1552. // uint/count
  1553. pData->prog.clear();
  1554. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1555. pData->prog.createNew(static_cast<uint32_t>(count));
  1556. } break;
  1557. case kPluginBridgeNonRtServerMidiProgramCount: {
  1558. // uint/count
  1559. pData->midiprog.clear();
  1560. if (const uint32_t count = fShmNonRtServerControl.readUInt())
  1561. pData->midiprog.createNew(static_cast<uint32_t>(count));
  1562. } break;
  1563. case kPluginBridgeNonRtServerParameterData1: {
  1564. // uint/index, int/rindex, uint/type, uint/hints, int/cc
  1565. const uint32_t index = fShmNonRtServerControl.readUInt();
  1566. const int32_t rindex = fShmNonRtServerControl.readInt();
  1567. const uint32_t type = fShmNonRtServerControl.readUInt();
  1568. const uint32_t hints = fShmNonRtServerControl.readUInt();
  1569. const int16_t midiCC = fShmNonRtServerControl.readShort();
  1570. CARLA_SAFE_ASSERT_BREAK(midiCC >= -1 && midiCC < MAX_MIDI_CONTROL);
  1571. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1572. if (index < pData->param.count)
  1573. {
  1574. pData->param.data[index].type = static_cast<ParameterType>(type);
  1575. pData->param.data[index].index = static_cast<int32_t>(index);
  1576. pData->param.data[index].rindex = rindex;
  1577. pData->param.data[index].hints = hints;
  1578. pData->param.data[index].midiCC = midiCC;
  1579. }
  1580. } break;
  1581. case kPluginBridgeNonRtServerParameterData2: {
  1582. // uint/index, uint/size, str[] (name), uint/size, str[] (unit)
  1583. const uint32_t index = fShmNonRtServerControl.readUInt();
  1584. // name
  1585. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1586. char name[nameSize+1];
  1587. carla_zeroChar(name, nameSize+1);
  1588. fShmNonRtServerControl.readCustomData(name, nameSize);
  1589. // symbol
  1590. const uint32_t symbolSize(fShmNonRtServerControl.readUInt());
  1591. char symbol[symbolSize+1];
  1592. carla_zeroChar(symbol, symbolSize+1);
  1593. fShmNonRtServerControl.readCustomData(symbol, symbolSize);
  1594. // unit
  1595. const uint32_t unitSize(fShmNonRtServerControl.readUInt());
  1596. char unit[unitSize+1];
  1597. carla_zeroChar(unit, unitSize+1);
  1598. fShmNonRtServerControl.readCustomData(unit, unitSize);
  1599. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1600. if (index < pData->param.count)
  1601. {
  1602. fParams[index].name = name;
  1603. fParams[index].symbol = symbol;
  1604. fParams[index].unit = unit;
  1605. }
  1606. } break;
  1607. case kPluginBridgeNonRtServerParameterRanges: {
  1608. // uint/index, float/def, float/min, float/max, float/step, float/stepSmall, float/stepLarge
  1609. const uint32_t index = fShmNonRtServerControl.readUInt();
  1610. const float def = fShmNonRtServerControl.readFloat();
  1611. const float min = fShmNonRtServerControl.readFloat();
  1612. const float max = fShmNonRtServerControl.readFloat();
  1613. const float step = fShmNonRtServerControl.readFloat();
  1614. const float stepSmall = fShmNonRtServerControl.readFloat();
  1615. const float stepLarge = fShmNonRtServerControl.readFloat();
  1616. CARLA_SAFE_ASSERT_BREAK(min < max);
  1617. CARLA_SAFE_ASSERT_BREAK(def >= min);
  1618. CARLA_SAFE_ASSERT_BREAK(def <= max);
  1619. CARLA_SAFE_ASSERT_INT2(index < pData->param.count, index, pData->param.count);
  1620. if (index < pData->param.count)
  1621. {
  1622. pData->param.ranges[index].def = def;
  1623. pData->param.ranges[index].min = min;
  1624. pData->param.ranges[index].max = max;
  1625. pData->param.ranges[index].step = step;
  1626. pData->param.ranges[index].stepSmall = stepSmall;
  1627. pData->param.ranges[index].stepLarge = stepLarge;
  1628. }
  1629. } break;
  1630. case kPluginBridgeNonRtServerParameterValue: {
  1631. // uint/index, float/value
  1632. const uint32_t index = fShmNonRtServerControl.readUInt();
  1633. const float value = fShmNonRtServerControl.readFloat();
  1634. if (index < pData->param.count)
  1635. {
  1636. const float fixedValue(pData->param.getFixedValue(index, value));
  1637. fParams[index].value = fixedValue;
  1638. CarlaPlugin::setParameterValue(index, fixedValue, false, true, true);
  1639. }
  1640. } break;
  1641. case kPluginBridgeNonRtServerParameterValue2: {
  1642. // uint/index, float/value
  1643. const uint32_t index = fShmNonRtServerControl.readUInt();
  1644. const float value = fShmNonRtServerControl.readFloat();
  1645. if (index < pData->param.count)
  1646. {
  1647. const float fixedValue(pData->param.getFixedValue(index, value));
  1648. fParams[index].value = fixedValue;
  1649. }
  1650. } break;
  1651. case kPluginBridgeNonRtServerDefaultValue: {
  1652. // uint/index, float/value
  1653. const uint32_t index = fShmNonRtServerControl.readUInt();
  1654. const float value = fShmNonRtServerControl.readFloat();
  1655. if (index < pData->param.count)
  1656. pData->param.ranges[index].def = value;
  1657. } break;
  1658. case kPluginBridgeNonRtServerCurrentProgram: {
  1659. // int/index
  1660. const int32_t index = fShmNonRtServerControl.readInt();
  1661. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1662. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1663. CarlaPlugin::setProgram(index, false, true, true);
  1664. } break;
  1665. case kPluginBridgeNonRtServerCurrentMidiProgram: {
  1666. // int/index
  1667. const int32_t index = fShmNonRtServerControl.readInt();
  1668. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1669. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1670. CarlaPlugin::setMidiProgram(index, false, true, true);
  1671. } break;
  1672. case kPluginBridgeNonRtServerProgramName: {
  1673. // uint/index, uint/size, str[] (name)
  1674. const uint32_t index = fShmNonRtServerControl.readUInt();
  1675. // name
  1676. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1677. char name[nameSize+1];
  1678. carla_zeroChar(name, nameSize+1);
  1679. fShmNonRtServerControl.readCustomData(name, nameSize);
  1680. CARLA_SAFE_ASSERT_INT2(index < pData->prog.count, index, pData->prog.count);
  1681. if (index < pData->prog.count)
  1682. {
  1683. if (pData->prog.names[index] != nullptr)
  1684. delete[] pData->prog.names[index];
  1685. pData->prog.names[index] = carla_strdup(name);
  1686. }
  1687. } break;
  1688. case kPluginBridgeNonRtServerMidiProgramData: {
  1689. // uint/index, uint/bank, uint/program, uint/size, str[] (name)
  1690. const uint32_t index = fShmNonRtServerControl.readUInt();
  1691. const uint32_t bank = fShmNonRtServerControl.readUInt();
  1692. const uint32_t program = fShmNonRtServerControl.readUInt();
  1693. // name
  1694. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1695. char name[nameSize+1];
  1696. carla_zeroChar(name, nameSize+1);
  1697. fShmNonRtServerControl.readCustomData(name, nameSize);
  1698. CARLA_SAFE_ASSERT_INT2(index < pData->midiprog.count, index, pData->midiprog.count);
  1699. if (index < pData->midiprog.count)
  1700. {
  1701. if (pData->midiprog.data[index].name != nullptr)
  1702. delete[] pData->midiprog.data[index].name;
  1703. pData->midiprog.data[index].bank = bank;
  1704. pData->midiprog.data[index].program = program;
  1705. pData->midiprog.data[index].name = carla_strdup(name);
  1706. }
  1707. } break;
  1708. case kPluginBridgeNonRtServerSetCustomData: {
  1709. // uint/size, str[], uint/size, str[], uint/size, str[]
  1710. // type
  1711. const uint32_t typeSize(fShmNonRtServerControl.readUInt());
  1712. char type[typeSize+1];
  1713. carla_zeroChar(type, typeSize+1);
  1714. fShmNonRtServerControl.readCustomData(type, typeSize);
  1715. // key
  1716. const uint32_t keySize(fShmNonRtServerControl.readUInt());
  1717. char key[keySize+1];
  1718. carla_zeroChar(key, keySize+1);
  1719. fShmNonRtServerControl.readCustomData(key, keySize);
  1720. // value
  1721. const uint32_t valueSize(fShmNonRtServerControl.readUInt());
  1722. char value[valueSize+1];
  1723. carla_zeroChar(value, valueSize+1);
  1724. fShmNonRtServerControl.readCustomData(value, valueSize);
  1725. CarlaPlugin::setCustomData(type, key, value, false);
  1726. } break;
  1727. case kPluginBridgeNonRtServerSetChunkDataFile: {
  1728. // uint/size, str[] (filename)
  1729. // chunkFilePath
  1730. const uint32_t chunkFilePathSize(fShmNonRtServerControl.readUInt());
  1731. char chunkFilePath[chunkFilePathSize+1];
  1732. carla_zeroChar(chunkFilePath, chunkFilePathSize+1);
  1733. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  1734. String realChunkFilePath(chunkFilePath);
  1735. carla_stdout("chunk save path BEFORE => %s", realChunkFilePath.toRawUTF8());
  1736. #ifndef CARLA_OS_WIN
  1737. // Using Wine, fix temp dir
  1738. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  1739. {
  1740. // Get WINEPREFIX
  1741. String wineDir;
  1742. if (const char* const WINEPREFIX = getenv("WINEPREFIX"))
  1743. wineDir = String(WINEPREFIX);
  1744. else
  1745. wineDir = File::getSpecialLocation(File::userHomeDirectory).getFullPathName() + "/.wine";
  1746. const StringArray driveLetterSplit(StringArray::fromTokens(realChunkFilePath, ":/", ""));
  1747. realChunkFilePath = wineDir;
  1748. realChunkFilePath += "/drive_";
  1749. realChunkFilePath += driveLetterSplit[0].toLowerCase();
  1750. realChunkFilePath += "/";
  1751. realChunkFilePath += driveLetterSplit[1];
  1752. realChunkFilePath = realChunkFilePath.replace("\\", "/");
  1753. carla_stdout("chunk save path AFTER => %s", realChunkFilePath.toRawUTF8());
  1754. }
  1755. #endif
  1756. File chunkFile(realChunkFilePath);
  1757. if (chunkFile.existsAsFile())
  1758. {
  1759. fInfo.chunk = carla_getChunkFromBase64String(chunkFile.loadFileAsString().toRawUTF8());
  1760. chunkFile.deleteFile();
  1761. carla_stderr("chunk data final");
  1762. }
  1763. } break;
  1764. case kPluginBridgeNonRtServerSetLatency: {
  1765. // uint
  1766. } break;
  1767. case kPluginBridgeNonRtServerReady:
  1768. fInitiated = true;
  1769. break;
  1770. case kPluginBridgeNonRtServerSaved:
  1771. fSaved = true;
  1772. break;
  1773. case kPluginBridgeNonRtServerUiClosed:
  1774. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1775. break;
  1776. case kPluginBridgeNonRtServerError: {
  1777. // error
  1778. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  1779. char error[errorSize+1];
  1780. carla_zeroChar(error, errorSize+1);
  1781. fShmNonRtServerControl.readCustomData(error, errorSize);
  1782. pData->engine->setLastError(error);
  1783. fInitError = true;
  1784. fInitiated = true;
  1785. } break;
  1786. }
  1787. }
  1788. }
  1789. // -------------------------------------------------------------------
  1790. uintptr_t getUiBridgeProcessId() const noexcept override
  1791. {
  1792. return fBridgeThread.getProcessPID();
  1793. }
  1794. const void* getExtraStuff() const noexcept override
  1795. {
  1796. return fBridgeBinary.isNotEmpty() ? fBridgeBinary.buffer() : nullptr;
  1797. }
  1798. // -------------------------------------------------------------------
  1799. bool init(const char* const filename, const char* const name, const char* const label, const char* const bridgeBinary)
  1800. {
  1801. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1802. // ---------------------------------------------------------------
  1803. // first checks
  1804. if (pData->client != nullptr)
  1805. {
  1806. pData->engine->setLastError("Plugin client is already registered");
  1807. return false;
  1808. }
  1809. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  1810. {
  1811. pData->engine->setLastError("null bridge binary");
  1812. return false;
  1813. }
  1814. // ---------------------------------------------------------------
  1815. // set info
  1816. if (name != nullptr && name[0] != '\0')
  1817. pData->name = pData->engine->getUniquePluginName(name);
  1818. if (filename != nullptr && filename[0] != '\0')
  1819. pData->filename = carla_strdup(filename);
  1820. else
  1821. pData->filename = carla_strdup("");
  1822. fBridgeBinary = bridgeBinary;
  1823. std::srand(static_cast<uint>(std::time(nullptr)));
  1824. // ---------------------------------------------------------------
  1825. // init sem/shm
  1826. if (! fShmAudioPool.initialize())
  1827. {
  1828. carla_stdout("Failed to initialize shared memory audio pool");
  1829. return false;
  1830. }
  1831. if (! fShmRtClientControl.initialize())
  1832. {
  1833. carla_stdout("Failed to initialize RT client control");
  1834. fShmAudioPool.clear();
  1835. return false;
  1836. }
  1837. if (! fShmNonRtClientControl.initialize())
  1838. {
  1839. carla_stdout("Failed to initialize Non-RT client control");
  1840. fShmRtClientControl.clear();
  1841. fShmAudioPool.clear();
  1842. return false;
  1843. }
  1844. if (! fShmNonRtServerControl.initialize())
  1845. {
  1846. carla_stdout("Failed to initialize Non-RT server control");
  1847. fShmNonRtClientControl.clear();
  1848. fShmRtClientControl.clear();
  1849. fShmAudioPool.clear();
  1850. return false;
  1851. }
  1852. // ---------------------------------------------------------------
  1853. carla_stdout("Carla Server Info:");
  1854. carla_stdout(" sizeof(BridgeRtClientData): " P_SIZE, sizeof(BridgeRtClientData));
  1855. carla_stdout(" sizeof(BridgeNonRtClientData): " P_SIZE, sizeof(BridgeNonRtClientData));
  1856. carla_stdout(" sizeof(BridgeNonRtServerData): " P_SIZE, sizeof(BridgeNonRtServerData));
  1857. // initial values
  1858. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientNull);
  1859. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1860. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1861. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1862. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetBufferSize);
  1863. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1864. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetSampleRate);
  1865. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1866. fShmNonRtClientControl.commitWrite();
  1867. // init bridge thread
  1868. {
  1869. char shmIdsStr[6*4+1];
  1870. carla_zeroChar(shmIdsStr, 6*4+1);
  1871. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1872. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1873. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1874. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1875. fBridgeThread.setData(bridgeBinary, label, shmIdsStr);
  1876. fBridgeThread.startThread();
  1877. }
  1878. fInitiated = false;
  1879. fLastPongCounter = 0;
  1880. for (; fLastPongCounter++ < 500;)
  1881. {
  1882. if (fInitiated || ! fBridgeThread.isThreadRunning())
  1883. break;
  1884. carla_msleep(20);
  1885. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1886. pData->engine->idle();
  1887. idle();
  1888. }
  1889. fLastPongCounter = -1;
  1890. if (fInitError || ! fInitiated)
  1891. {
  1892. fBridgeThread.stopThread(6000);
  1893. if (! fInitError)
  1894. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n(or the plugin crashed on initialization?)");
  1895. return false;
  1896. }
  1897. // ---------------------------------------------------------------
  1898. // register client
  1899. if (pData->name == nullptr)
  1900. {
  1901. if (label != nullptr && label[0] != '\0')
  1902. pData->name = pData->engine->getUniquePluginName(label);
  1903. else
  1904. pData->name = pData->engine->getUniquePluginName("unknown");
  1905. }
  1906. pData->client = pData->engine->addClient(this);
  1907. if (pData->client == nullptr || ! pData->client->isOk())
  1908. {
  1909. pData->engine->setLastError("Failed to register plugin client");
  1910. return false;
  1911. }
  1912. return true;
  1913. }
  1914. private:
  1915. const BinaryType fBinaryType;
  1916. const PluginType fPluginType;
  1917. bool fInitiated;
  1918. bool fInitError;
  1919. bool fSaved;
  1920. bool fTimedOut;
  1921. int32_t fLastPongCounter;
  1922. CarlaString fBridgeBinary;
  1923. CarlaPluginBridgeThread fBridgeThread;
  1924. BridgeAudioPool fShmAudioPool;
  1925. BridgeRtClientControl fShmRtClientControl;
  1926. BridgeNonRtClientControl fShmNonRtClientControl;
  1927. BridgeNonRtServerControl fShmNonRtServerControl;
  1928. struct Info {
  1929. uint32_t aIns, aOuts;
  1930. uint32_t cvIns, cvOuts;
  1931. uint32_t mIns, mOuts;
  1932. PluginCategory category;
  1933. uint optionsAvailable;
  1934. int64_t uniqueId;
  1935. CarlaString name;
  1936. CarlaString label;
  1937. CarlaString maker;
  1938. CarlaString copyright;
  1939. std::vector<uint8_t> chunk;
  1940. Info()
  1941. : aIns(0),
  1942. aOuts(0),
  1943. cvIns(0),
  1944. cvOuts(0),
  1945. mIns(0),
  1946. mOuts(0),
  1947. category(PLUGIN_CATEGORY_NONE),
  1948. optionsAvailable(0),
  1949. uniqueId(0),
  1950. name(),
  1951. label(),
  1952. maker(),
  1953. copyright(),
  1954. chunk() {}
  1955. } fInfo;
  1956. BridgeParamInfo* fParams;
  1957. void resizeAudioPool(const uint32_t bufferSize)
  1958. {
  1959. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, fInfo.cvIns+fInfo.cvOuts);
  1960. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1961. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.size));
  1962. fShmRtClientControl.commitWrite();
  1963. waitForClient();
  1964. }
  1965. bool waitForClient(const uint secs = 5)
  1966. {
  1967. CARLA_SAFE_ASSERT_RETURN(! fTimedOut, false);
  1968. if (! fShmRtClientControl.waitForClient(secs))
  1969. {
  1970. carla_stderr("waitForClient() timeout here");
  1971. fTimedOut = true;
  1972. return false;
  1973. }
  1974. return true;
  1975. }
  1976. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginBridge)
  1977. };
  1978. CARLA_BACKEND_END_NAMESPACE
  1979. // -------------------------------------------------------------------------------------------------------------------
  1980. CARLA_BACKEND_START_NAMESPACE
  1981. CarlaPlugin* CarlaPlugin::newBridge(const Initializer& init, BinaryType btype, PluginType ptype, const char* const bridgeBinary)
  1982. {
  1983. carla_debug("CarlaPlugin::newBridge({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label, BinaryType2Str(btype), PluginType2Str(ptype), bridgeBinary);
  1984. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  1985. {
  1986. init.engine->setLastError("Bridge not possible, bridge-binary not found");
  1987. return nullptr;
  1988. }
  1989. CarlaPluginBridge* const plugin(new CarlaPluginBridge(init.engine, init.id, btype, ptype));
  1990. if (! plugin->init(init.filename, init.name, init.label, bridgeBinary))
  1991. {
  1992. delete plugin;
  1993. return nullptr;
  1994. }
  1995. plugin->reload();
  1996. bool canRun = true;
  1997. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1998. {
  1999. if (! plugin->canRunInRack())
  2000. {
  2001. init.engine->setLastError("Carla's rack mode can only work with Stereo Bridged plugins, sorry!");
  2002. canRun = false;
  2003. }
  2004. else if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  2005. {
  2006. init.engine->setLastError("Carla's rack mode cannot work with plugins that have CV ports, sorry!");
  2007. canRun = false;
  2008. }
  2009. }
  2010. else if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_PATCHBAY && (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0))
  2011. {
  2012. init.engine->setLastError("CV ports in patchbay mode is still TODO");
  2013. canRun = false;
  2014. }
  2015. if (! canRun)
  2016. {
  2017. delete plugin;
  2018. return nullptr;
  2019. }
  2020. return plugin;
  2021. }
  2022. CARLA_BACKEND_END_NAMESPACE
  2023. // -------------------------------------------------------------------------------------------------------------------