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.

2576 lines
88KB

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