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.

2696 lines
91KB

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