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.

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