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.

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