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
87KB

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