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.

1569 lines
52KB

  1. /*
  2. * Carla Plugin JACK
  3. * Copyright (C) 2016-2018 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. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #ifdef CARLA_OS_LINUX
  20. #include "CarlaBackendUtils.hpp"
  21. #include "CarlaBridgeUtils.hpp"
  22. #include "CarlaEngineUtils.hpp"
  23. #include "CarlaMathUtils.hpp"
  24. #include "CarlaPipeUtils.hpp"
  25. #include "CarlaShmUtils.hpp"
  26. #include "CarlaThread.hpp"
  27. #include "water/misc/Time.h"
  28. #include "water/text/StringArray.h"
  29. #include "water/threads/ChildProcess.h"
  30. #include "jackbridge/JackBridge.hpp"
  31. #include <ctime>
  32. #include <vector>
  33. // -------------------------------------------------------------------------------------------------------------------
  34. using water::ChildProcess;
  35. using water::File;
  36. using water::String;
  37. using water::StringArray;
  38. using water::Time;
  39. CARLA_BACKEND_START_NAMESPACE
  40. // -------------------------------------------------------------------------------------------------------------------
  41. // Fallback data
  42. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  43. // -------------------------------------------------------------------------------------------------------------------
  44. class CarlaPluginJackThread : public CarlaThread
  45. {
  46. public:
  47. CarlaPluginJackThread(CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  48. : CarlaThread("CarlaPluginJackThread"),
  49. kEngine(engine),
  50. kPlugin(plugin),
  51. fShmIds(),
  52. fNumPorts(),
  53. fProcess() {}
  54. void setData(const char* const shmIds, const char* const numPorts) noexcept
  55. {
  56. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  57. CARLA_SAFE_ASSERT_RETURN(numPorts != nullptr && numPorts[0] != '\0',);
  58. CARLA_SAFE_ASSERT(! isThreadRunning());
  59. fShmIds = shmIds;
  60. fNumPorts = numPorts;
  61. }
  62. uintptr_t getProcessID() const noexcept
  63. {
  64. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  65. return (uintptr_t)fProcess->getPID();
  66. }
  67. protected:
  68. void run()
  69. {
  70. if (fProcess == nullptr)
  71. {
  72. fProcess = new ChildProcess();
  73. }
  74. else if (fProcess->isRunning())
  75. {
  76. carla_stderr("CarlaPluginJackThread::run() - already running");
  77. }
  78. String name(kPlugin->getName());
  79. String filename(kPlugin->getFilename());
  80. if (name.isEmpty())
  81. name = "(none)";
  82. CARLA_SAFE_ASSERT_RETURN(filename.isNotEmpty(),);
  83. StringArray arguments;
  84. // binary
  85. arguments.addTokens(filename, true);
  86. bool started;
  87. {
  88. const EngineOptions& options(kEngine->getOptions());
  89. char winIdStr[STR_MAX+1];
  90. std::snprintf(winIdStr, STR_MAX, P_UINTPTR, options.frontendWinId);
  91. winIdStr[STR_MAX] = '\0';
  92. CarlaString libjackdir(options.binaryDir);
  93. libjackdir += "/jack";
  94. CarlaString ldpreload;
  95. #ifdef HAVE_X11
  96. ldpreload = (CarlaString(options.binaryDir)
  97. + "/libcarla_interposer-jack-x11.so");
  98. #endif
  99. const ScopedEngineEnvironmentLocker _seel(kEngine);
  100. const ScopedEnvVar sev2("LD_LIBRARY_PATH", libjackdir.buffer());
  101. const ScopedEnvVar sev1("LD_PRELOAD", ldpreload.isNotEmpty() ? ldpreload.buffer() : nullptr);
  102. if (kPlugin->getHints() & PLUGIN_HAS_CUSTOM_UI)
  103. carla_setenv("CARLA_FRONTEND_WIN_ID", winIdStr);
  104. else
  105. carla_unsetenv("CARLA_FRONTEND_WIN_ID");
  106. carla_setenv("CARLA_LIBJACK_SETUP", fNumPorts.buffer());
  107. carla_setenv("CARLA_SHM_IDS", fShmIds.buffer());
  108. started = fProcess->start(arguments);
  109. }
  110. if (! started)
  111. {
  112. carla_stdout("failed!");
  113. fProcess = nullptr;
  114. return;
  115. }
  116. for (; fProcess->isRunning() && ! shouldThreadExit();)
  117. carla_msleep(50);
  118. // we only get here if bridge crashed or thread asked to exit
  119. if (fProcess->isRunning() && shouldThreadExit())
  120. {
  121. fProcess->waitForProcessToFinish(2000);
  122. if (fProcess->isRunning())
  123. {
  124. carla_stdout("CarlaPluginJackThread::run() - application refused to close, force kill now");
  125. fProcess->kill();
  126. }
  127. }
  128. else
  129. {
  130. // forced quit, may have crashed
  131. if (fProcess->getExitCode() != 0 /*|| fProcess->exitStatus() == QProcess::CrashExit*/)
  132. {
  133. carla_stderr("CarlaPluginJackThread::run() - application crashed");
  134. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  135. "Saving now will lose its current settings.\n"
  136. "Please remove this plugin, and not rely on it from this point.");
  137. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_ERROR, kPlugin->getId(), 0, 0, 0.0f, errorString);
  138. }
  139. }
  140. fProcess = nullptr;
  141. }
  142. private:
  143. CarlaEngine* const kEngine;
  144. CarlaPlugin* const kPlugin;
  145. CarlaString fShmIds;
  146. CarlaString fNumPorts;
  147. ScopedPointer<ChildProcess> fProcess;
  148. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJackThread)
  149. };
  150. // -------------------------------------------------------------------------------------------------------------------
  151. class CarlaPluginJack : public CarlaPlugin
  152. {
  153. public:
  154. CarlaPluginJack(CarlaEngine* const engine, const uint id)
  155. : CarlaPlugin(engine, id),
  156. fInitiated(false),
  157. fInitError(false),
  158. fTimedOut(false),
  159. fTimedError(false),
  160. fProcCanceled(false),
  161. fBufferSize(engine->getBufferSize()),
  162. fProcWaitTime(0),
  163. fLastPingTime(-1),
  164. fBridgeThread(engine, this),
  165. fShmAudioPool(),
  166. fShmRtClientControl(),
  167. fShmNonRtClientControl(),
  168. fShmNonRtServerControl(),
  169. fInfo()
  170. {
  171. carla_debug("CarlaPluginJack::CarlaPluginJack(%p, %i)", engine, id);
  172. pData->hints |= PLUGIN_IS_BRIDGE;
  173. }
  174. ~CarlaPluginJack() override
  175. {
  176. carla_debug("CarlaPluginJack::~CarlaPluginJack()");
  177. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  178. // close UI
  179. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  180. pData->transientTryCounter = 0;
  181. #endif
  182. pData->singleMutex.lock();
  183. pData->masterMutex.lock();
  184. if (pData->client != nullptr && pData->client->isActive())
  185. pData->client->deactivate();
  186. if (pData->active)
  187. {
  188. deactivate();
  189. pData->active = false;
  190. }
  191. if (fBridgeThread.isThreadRunning())
  192. {
  193. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  194. fShmRtClientControl.commitWrite();
  195. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  196. fShmNonRtClientControl.commitWrite();
  197. if (! fTimedOut)
  198. waitForClient("stopping", 3000);
  199. }
  200. fBridgeThread.stopThread(3000);
  201. fShmNonRtServerControl.clear();
  202. fShmNonRtClientControl.clear();
  203. fShmRtClientControl.clear();
  204. fShmAudioPool.clear();
  205. clearBuffers();
  206. fInfo.chunk.clear();
  207. }
  208. // -------------------------------------------------------------------
  209. // Information (base)
  210. PluginType getType() const noexcept override
  211. {
  212. return PLUGIN_JACK;
  213. }
  214. PluginCategory getCategory() const noexcept override
  215. {
  216. return PLUGIN_CATEGORY_NONE;
  217. }
  218. // -------------------------------------------------------------------
  219. // Information (count)
  220. uint32_t getMidiInCount() const noexcept override
  221. {
  222. return fInfo.mIns;
  223. }
  224. uint32_t getMidiOutCount() const noexcept override
  225. {
  226. return fInfo.mOuts;
  227. }
  228. // -------------------------------------------------------------------
  229. // Information (current data)
  230. // -------------------------------------------------------------------
  231. // Information (per-plugin data)
  232. uint getOptionsAvailable() const noexcept override
  233. {
  234. return fInfo.optionsAvailable;
  235. }
  236. void getLabel(char* const strBuf) const noexcept override
  237. {
  238. std::strncpy(strBuf, fInfo.setupLabel, STR_MAX);
  239. }
  240. void getMaker(char* const strBuf) const noexcept override
  241. {
  242. nullStrBuf(strBuf);
  243. }
  244. void getCopyright(char* const strBuf) const noexcept override
  245. {
  246. nullStrBuf(strBuf);
  247. }
  248. void getRealName(char* const strBuf) const noexcept override
  249. {
  250. // FIXME
  251. std::strncpy(strBuf, "Carla's libjack", STR_MAX);
  252. }
  253. // -------------------------------------------------------------------
  254. // Set data (state)
  255. void prepareForSave() noexcept override
  256. {
  257. {
  258. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  259. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPrepareForSave);
  260. fShmNonRtClientControl.commitWrite();
  261. }
  262. }
  263. // -------------------------------------------------------------------
  264. // Set data (internal stuff)
  265. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  266. {
  267. {
  268. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  269. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  270. fShmNonRtClientControl.writeUInt(option);
  271. fShmNonRtClientControl.writeBool(yesNo);
  272. fShmNonRtClientControl.commitWrite();
  273. }
  274. CarlaPlugin::setOption(option, yesNo, sendCallback);
  275. }
  276. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  277. {
  278. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  279. {
  280. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  281. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  282. fShmNonRtClientControl.writeShort(channel);
  283. fShmNonRtClientControl.commitWrite();
  284. }
  285. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  286. }
  287. // -------------------------------------------------------------------
  288. // Set data (plugin-specific stuff)
  289. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  290. {
  291. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  292. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  293. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  294. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  295. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  296. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "__CarlaPingOnOff__") == 0)
  297. {
  298. #if 0
  299. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  300. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPingOnOff);
  301. fShmNonRtClientControl.writeBool(std::strcmp(value, "true") == 0);
  302. fShmNonRtClientControl.commitWrite();
  303. #endif
  304. return;
  305. }
  306. CarlaPlugin::setCustomData(type, key, value, sendGui);
  307. }
  308. // -------------------------------------------------------------------
  309. // Set ui stuff
  310. void showCustomUI(const bool yesNo) override
  311. {
  312. if (yesNo && ! fBridgeThread.isThreadRunning()) {
  313. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  314. }
  315. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  316. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  317. fShmNonRtClientControl.commitWrite();
  318. }
  319. void idle() override
  320. {
  321. if (fBridgeThread.isThreadRunning())
  322. {
  323. if (fInitiated && fTimedOut && pData->active)
  324. setActive(false, true, true);
  325. {
  326. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  327. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  328. fShmNonRtClientControl.commitWrite();
  329. }
  330. try {
  331. handleNonRtData();
  332. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  333. if (fLastPingTime > 0 && Time::currentTimeMillis() > fLastPingTime + 30000)
  334. {
  335. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  336. // TODO
  337. //threadShouldExit();
  338. //callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  339. }
  340. }
  341. else if (fInitiated)
  342. {
  343. fTimedOut = true;
  344. fTimedError = true;
  345. fInitiated = false;
  346. handleProcessStopped();
  347. }
  348. else if (fProcCanceled)
  349. {
  350. handleProcessStopped();
  351. fProcCanceled = false;
  352. }
  353. CarlaPlugin::idle();
  354. }
  355. // -------------------------------------------------------------------
  356. // Plugin state
  357. void reload() override
  358. {
  359. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  360. carla_debug("CarlaPluginJack::reload() - start");
  361. const EngineProcessMode processMode(pData->engine->getProccessMode());
  362. // Safely disable plugin for reload
  363. const ScopedDisabler sd(this);
  364. // cleanup of previous data
  365. pData->audioIn.clear();
  366. pData->audioOut.clear();
  367. pData->event.clear();
  368. bool needsCtrlIn, needsCtrlOut;
  369. needsCtrlIn = needsCtrlOut = false;
  370. if (fInfo.aIns > 0)
  371. {
  372. pData->audioIn.createNew(fInfo.aIns);
  373. }
  374. if (fInfo.aOuts > 0)
  375. {
  376. pData->audioOut.createNew(fInfo.aOuts);
  377. needsCtrlIn = true;
  378. }
  379. if (fInfo.mIns > 0)
  380. needsCtrlIn = true;
  381. if (fInfo.mOuts > 0)
  382. needsCtrlOut = true;
  383. const uint portNameSize(pData->engine->getMaxPortNameSize());
  384. CarlaString portName;
  385. // Audio Ins
  386. for (uint8_t j=0; j < fInfo.aIns; ++j)
  387. {
  388. portName.clear();
  389. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  390. {
  391. portName = pData->name;
  392. portName += ":";
  393. }
  394. if (fInfo.aIns > 1)
  395. {
  396. portName += "audio_in_";
  397. portName += CarlaString(j+1);
  398. }
  399. else
  400. {
  401. portName += "audio_in";
  402. }
  403. portName.truncate(portNameSize);
  404. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  405. pData->audioIn.ports[j].rindex = j;
  406. }
  407. // Audio Outs
  408. for (uint8_t j=0; j < fInfo.aOuts; ++j)
  409. {
  410. portName.clear();
  411. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  412. {
  413. portName = pData->name;
  414. portName += ":";
  415. }
  416. if (fInfo.aOuts > 1)
  417. {
  418. portName += "audio_out_";
  419. portName += CarlaString(j+1);
  420. }
  421. else
  422. {
  423. portName += "audio_out";
  424. }
  425. portName.truncate(portNameSize);
  426. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  427. pData->audioOut.ports[j].rindex = j;
  428. }
  429. if (needsCtrlIn)
  430. {
  431. portName.clear();
  432. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  433. {
  434. portName = pData->name;
  435. portName += ":";
  436. }
  437. portName += "event-in";
  438. portName.truncate(portNameSize);
  439. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  440. }
  441. if (needsCtrlOut)
  442. {
  443. portName.clear();
  444. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  445. {
  446. portName = pData->name;
  447. portName += ":";
  448. }
  449. portName += "event-out";
  450. portName.truncate(portNameSize);
  451. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  452. }
  453. // extra plugin hints
  454. pData->extraHints = 0x0;
  455. if (fInfo.mIns > 0)
  456. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  457. if (fInfo.mOuts > 0)
  458. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  459. bufferSizeChanged(pData->engine->getBufferSize());
  460. reloadPrograms(true);
  461. carla_debug("CarlaPluginJack::reload() - end");
  462. }
  463. // -------------------------------------------------------------------
  464. // Plugin processing
  465. void activate() noexcept override
  466. {
  467. if (! fBridgeThread.isThreadRunning())
  468. {
  469. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  470. }
  471. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  472. {
  473. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  474. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  475. fShmNonRtClientControl.commitWrite();
  476. }
  477. fTimedOut = false;
  478. try {
  479. waitForClient("activate", 2000);
  480. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  481. }
  482. void deactivate() noexcept override
  483. {
  484. if (! fBridgeThread.isThreadRunning())
  485. return;
  486. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  487. {
  488. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  489. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  490. fShmNonRtClientControl.commitWrite();
  491. }
  492. fTimedOut = false;
  493. try {
  494. waitForClient("deactivate", 2000);
  495. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  496. }
  497. void process(const float** const audioIn, float** const audioOut, const float**, float**, const uint32_t frames) override
  498. {
  499. // --------------------------------------------------------------------------------------------------------
  500. // Check if active
  501. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  502. {
  503. // disable any output sound
  504. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  505. carla_zeroFloats(audioOut[i], frames);
  506. return;
  507. }
  508. // --------------------------------------------------------------------------------------------------------
  509. // Check if needs reset
  510. if (pData->needsReset)
  511. {
  512. // TODO
  513. pData->needsReset = false;
  514. }
  515. // --------------------------------------------------------------------------------------------------------
  516. // Event Input
  517. if (pData->event.portIn != nullptr)
  518. {
  519. // ----------------------------------------------------------------------------------------------------
  520. // MIDI Input (External)
  521. if (pData->extNotes.mutex.tryLock())
  522. {
  523. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  524. {
  525. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  526. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  527. uint8_t data1, data2, data3;
  528. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  529. data2 = note.note;
  530. data3 = note.velo;
  531. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  532. fShmRtClientControl.writeUInt(0); // time
  533. fShmRtClientControl.writeByte(0); // port
  534. fShmRtClientControl.writeByte(3); // size
  535. fShmRtClientControl.writeByte(data1);
  536. fShmRtClientControl.writeByte(data2);
  537. fShmRtClientControl.writeByte(data3);
  538. fShmRtClientControl.commitWrite();
  539. }
  540. pData->extNotes.data.clear();
  541. pData->extNotes.mutex.unlock();
  542. } // End of MIDI Input (External)
  543. // ----------------------------------------------------------------------------------------------------
  544. // Event Input (System)
  545. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  546. bool allNotesOffSent = false;
  547. #endif
  548. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  549. {
  550. const EngineEvent& event(pData->event.portIn->getEvent(i));
  551. // Control change
  552. switch (event.type)
  553. {
  554. case kEngineEventTypeNull:
  555. break;
  556. case kEngineEventTypeControl: {
  557. const EngineControlEvent& ctrlEvent = event.ctrl;
  558. switch (ctrlEvent.type)
  559. {
  560. case kEngineControlEventTypeNull:
  561. break;
  562. case kEngineControlEventTypeParameter:
  563. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  564. // Control backend stuff
  565. if (event.channel == pData->ctrlChannel)
  566. {
  567. float value;
  568. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  569. {
  570. value = ctrlEvent.value;
  571. setDryWetRT(value);
  572. }
  573. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  574. {
  575. value = ctrlEvent.value*127.0f/100.0f;
  576. setVolumeRT(value);
  577. }
  578. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  579. {
  580. float left, right;
  581. value = ctrlEvent.value/0.5f - 1.0f;
  582. if (value < 0.0f)
  583. {
  584. left = -1.0f;
  585. right = (value*2.0f)+1.0f;
  586. }
  587. else if (value > 0.0f)
  588. {
  589. left = (value*2.0f)-1.0f;
  590. right = 1.0f;
  591. }
  592. else
  593. {
  594. left = -1.0f;
  595. right = 1.0f;
  596. }
  597. setBalanceLeftRT(left);
  598. setBalanceRightRT(right);
  599. }
  600. }
  601. #endif
  602. break;
  603. case kEngineControlEventTypeMidiBank:
  604. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  605. {
  606. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  607. fShmRtClientControl.writeUInt(event.time);
  608. fShmRtClientControl.writeByte(event.channel);
  609. fShmRtClientControl.writeUShort(event.ctrl.param);
  610. fShmRtClientControl.commitWrite();
  611. }
  612. break;
  613. case kEngineControlEventTypeMidiProgram:
  614. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  615. {
  616. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  617. fShmRtClientControl.writeUInt(event.time);
  618. fShmRtClientControl.writeByte(event.channel);
  619. fShmRtClientControl.writeUShort(event.ctrl.param);
  620. fShmRtClientControl.commitWrite();
  621. }
  622. break;
  623. case kEngineControlEventTypeAllSoundOff:
  624. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  625. {
  626. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  627. fShmRtClientControl.writeUInt(event.time);
  628. fShmRtClientControl.writeByte(event.channel);
  629. fShmRtClientControl.commitWrite();
  630. }
  631. break;
  632. case kEngineControlEventTypeAllNotesOff:
  633. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  634. {
  635. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  636. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  637. {
  638. allNotesOffSent = true;
  639. sendMidiAllNotesOffToCallback();
  640. }
  641. #endif
  642. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  643. fShmRtClientControl.writeUInt(event.time);
  644. fShmRtClientControl.writeByte(event.channel);
  645. fShmRtClientControl.commitWrite();
  646. }
  647. break;
  648. } // switch (ctrlEvent.type)
  649. break;
  650. } // case kEngineEventTypeControl
  651. case kEngineEventTypeMidi: {
  652. const EngineMidiEvent& midiEvent(event.midi);
  653. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  654. continue;
  655. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  656. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  657. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  658. continue;
  659. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  660. continue;
  661. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  662. continue;
  663. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  664. continue;
  665. // Fix bad note-off
  666. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  667. status = MIDI_STATUS_NOTE_OFF;
  668. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  669. fShmRtClientControl.writeUInt(event.time);
  670. fShmRtClientControl.writeByte(midiEvent.port);
  671. fShmRtClientControl.writeByte(midiEvent.size);
  672. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  673. for (uint8_t j=1; j < midiEvent.size; ++j)
  674. fShmRtClientControl.writeByte(midiData[j]);
  675. fShmRtClientControl.commitWrite();
  676. if (status == MIDI_STATUS_NOTE_ON)
  677. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  678. else if (status == MIDI_STATUS_NOTE_OFF)
  679. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  680. } break;
  681. }
  682. }
  683. pData->postRtEvents.trySplice();
  684. } // End of Event Input
  685. if (! processSingle(audioIn, audioOut, frames))
  686. return;
  687. // --------------------------------------------------------------------------------------------------------
  688. // MIDI Output
  689. if (pData->event.portOut != nullptr)
  690. {
  691. uint32_t time;
  692. uint8_t port, size;
  693. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  694. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  695. {
  696. // get time
  697. time = *(const uint32_t*)midiData;
  698. midiData += 4;
  699. // get port and size
  700. port = *midiData++;
  701. size = *midiData++;
  702. if (size == 0)
  703. break;
  704. // store midi data advancing as needed
  705. uint8_t data[size];
  706. for (uint8_t j=0; j<size; ++j)
  707. data[j] = *midiData++;
  708. pData->event.portOut->writeMidiEvent(time, size, data);
  709. read += kBridgeBaseMidiOutHeaderSize + size;
  710. }
  711. // TODO
  712. (void)port;
  713. } // End of Control and MIDI Output
  714. }
  715. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  716. {
  717. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  718. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  719. CARLA_SAFE_ASSERT_RETURN(frames <= fBufferSize, false);
  720. if (pData->audioIn.count > 0)
  721. {
  722. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  723. }
  724. if (pData->audioOut.count > 0)
  725. {
  726. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  727. }
  728. // --------------------------------------------------------------------------------------------------------
  729. // Try lock, silence otherwise
  730. #ifndef STOAT_TEST_BUILD
  731. if (pData->engine->isOffline())
  732. {
  733. pData->singleMutex.lock();
  734. }
  735. else
  736. #endif
  737. if (! pData->singleMutex.tryLock())
  738. {
  739. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  740. carla_zeroFloats(audioOut[i], frames);
  741. return false;
  742. }
  743. // --------------------------------------------------------------------------------------------------------
  744. // Reset audio buffers
  745. for (uint32_t i=0; i < fInfo.aIns; ++i)
  746. carla_copyFloats(fShmAudioPool.data + (i * fBufferSize), audioIn[i], frames);
  747. // --------------------------------------------------------------------------------------------------------
  748. // TimeInfo
  749. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  750. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  751. bridgeTimeInfo.playing = timeInfo.playing;
  752. bridgeTimeInfo.frame = timeInfo.frame;
  753. bridgeTimeInfo.usecs = timeInfo.usecs;
  754. bridgeTimeInfo.validFlags = timeInfo.bbt.valid ? kPluginBridgeTimeInfoValidBBT : 0x0;
  755. if (timeInfo.bbt.valid)
  756. {
  757. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  758. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  759. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  760. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  761. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  762. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  763. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  764. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  765. }
  766. // --------------------------------------------------------------------------------------------------------
  767. // Run plugin
  768. {
  769. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  770. fShmRtClientControl.writeUInt(frames);
  771. fShmRtClientControl.commitWrite();
  772. }
  773. waitForClient("process", fProcWaitTime);
  774. if (fTimedOut)
  775. {
  776. pData->singleMutex.unlock();
  777. return false;
  778. }
  779. if (fShmRtClientControl.data->procFlags)
  780. {
  781. fInitiated = false;
  782. fProcCanceled = true;
  783. }
  784. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  785. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * fBufferSize), frames);
  786. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  787. // --------------------------------------------------------------------------------------------------------
  788. // Post-processing (dry/wet, volume and balance)
  789. {
  790. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  791. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  792. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  793. const bool isMono = (pData->audioIn.count == 1);
  794. bool isPair;
  795. float bufValue, oldBufLeft[doBalance ? frames : 1];
  796. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  797. {
  798. // Dry/Wet
  799. if (doDryWet)
  800. {
  801. const uint32_t c = isMono ? 0 : i;
  802. for (uint32_t k=0; k < frames; ++k)
  803. {
  804. bufValue = audioIn[c][k];
  805. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  806. }
  807. }
  808. // Balance
  809. if (doBalance)
  810. {
  811. isPair = (i % 2 == 0);
  812. if (isPair)
  813. {
  814. CARLA_ASSERT(i+1 < pData->audioOut.count);
  815. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  816. }
  817. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  818. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  819. for (uint32_t k=0; k < frames; ++k)
  820. {
  821. if (isPair)
  822. {
  823. // left
  824. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  825. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  826. }
  827. else
  828. {
  829. // right
  830. audioOut[i][k] = audioOut[i][k] * balRangeR;
  831. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  832. }
  833. }
  834. }
  835. // Volume (and buffer copy)
  836. if (doVolume)
  837. {
  838. for (uint32_t k=0; k < frames; ++k)
  839. audioOut[i][k] *= pData->postProc.volume;
  840. }
  841. }
  842. } // End of Post-processing
  843. #endif
  844. // --------------------------------------------------------------------------------------------------------
  845. pData->singleMutex.unlock();
  846. return true;
  847. }
  848. void bufferSizeChanged(const uint32_t newBufferSize) override
  849. {
  850. fBufferSize = newBufferSize;
  851. resizeAudioPool(newBufferSize);
  852. {
  853. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  854. fShmRtClientControl.writeUInt(newBufferSize);
  855. fShmRtClientControl.commitWrite();
  856. }
  857. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  858. fProcWaitTime = 1000;
  859. waitForClient("buffersize", 1000);
  860. }
  861. void sampleRateChanged(const double newSampleRate) override
  862. {
  863. {
  864. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  865. fShmRtClientControl.writeDouble(newSampleRate);
  866. fShmRtClientControl.commitWrite();
  867. }
  868. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  869. fProcWaitTime = 1000;
  870. waitForClient("samplerate", 1000);
  871. }
  872. void offlineModeChanged(const bool isOffline) override
  873. {
  874. {
  875. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  876. fShmRtClientControl.writeBool(isOffline);
  877. fShmRtClientControl.commitWrite();
  878. }
  879. waitForClient("offline", 1000);
  880. }
  881. // -------------------------------------------------------------------
  882. // Post-poned UI Stuff
  883. // -------------------------------------------------------------------
  884. void handleNonRtData()
  885. {
  886. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  887. {
  888. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  889. //#ifdef DEBUG
  890. if (opcode != kPluginBridgeNonRtServerPong)
  891. {
  892. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  893. }
  894. //#endif
  895. if (opcode != kPluginBridgeNonRtServerNull && fLastPingTime > 0)
  896. fLastPingTime = Time::currentTimeMillis();
  897. switch (opcode)
  898. {
  899. case kPluginBridgeNonRtServerNull:
  900. case kPluginBridgeNonRtServerPong:
  901. case kPluginBridgeNonRtServerPluginInfo1:
  902. case kPluginBridgeNonRtServerPluginInfo2:
  903. case kPluginBridgeNonRtServerAudioCount:
  904. case kPluginBridgeNonRtServerMidiCount:
  905. case kPluginBridgeNonRtServerCvCount:
  906. case kPluginBridgeNonRtServerParameterCount:
  907. case kPluginBridgeNonRtServerProgramCount:
  908. case kPluginBridgeNonRtServerMidiProgramCount:
  909. case kPluginBridgeNonRtServerPortName:
  910. case kPluginBridgeNonRtServerParameterData1:
  911. case kPluginBridgeNonRtServerParameterData2:
  912. case kPluginBridgeNonRtServerParameterRanges:
  913. case kPluginBridgeNonRtServerParameterValue:
  914. case kPluginBridgeNonRtServerParameterValue2:
  915. case kPluginBridgeNonRtServerDefaultValue:
  916. case kPluginBridgeNonRtServerCurrentProgram:
  917. case kPluginBridgeNonRtServerCurrentMidiProgram:
  918. case kPluginBridgeNonRtServerProgramName:
  919. case kPluginBridgeNonRtServerMidiProgramData:
  920. case kPluginBridgeNonRtServerSetCustomData:
  921. break;
  922. case kPluginBridgeNonRtServerSetChunkDataFile:
  923. // uint/size, str[] (filename)
  924. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  925. {
  926. char chunkFilePath[chunkFilePathSize];
  927. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  928. }
  929. break;
  930. case kPluginBridgeNonRtServerSetLatency:
  931. case kPluginBridgeNonRtServerSetParameterText:
  932. break;
  933. case kPluginBridgeNonRtServerReady:
  934. fInitiated = true;
  935. break;
  936. case kPluginBridgeNonRtServerSaved:
  937. break;
  938. case kPluginBridgeNonRtServerUiClosed:
  939. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  940. break;
  941. case kPluginBridgeNonRtServerError: {
  942. // error
  943. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  944. char error[errorSize+1];
  945. carla_zeroChars(error, errorSize+1);
  946. fShmNonRtServerControl.readCustomData(error, errorSize);
  947. if (fInitiated)
  948. {
  949. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  950. // just in case
  951. pData->engine->setLastError(error);
  952. fInitError = true;
  953. }
  954. else
  955. {
  956. pData->engine->setLastError(error);
  957. fInitError = true;
  958. fInitiated = true;
  959. }
  960. } break;
  961. }
  962. }
  963. }
  964. // -------------------------------------------------------------------
  965. uintptr_t getUiBridgeProcessId() const noexcept override
  966. {
  967. return fBridgeThread.getProcessID();
  968. }
  969. // -------------------------------------------------------------------
  970. bool init(const char* const filename, const char* const name, const char* const label)
  971. {
  972. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  973. // ---------------------------------------------------------------
  974. // first checks
  975. if (pData->client != nullptr)
  976. {
  977. pData->engine->setLastError("Plugin client is already registered");
  978. return false;
  979. }
  980. if (filename == nullptr || filename[0] == '\0')
  981. {
  982. pData->engine->setLastError("null filename");
  983. return false;
  984. }
  985. if (label == nullptr || label[0] == '\0')
  986. {
  987. pData->engine->setLastError("null label");
  988. return false;
  989. }
  990. // ---------------------------------------------------------------
  991. // check setup
  992. if (std::strlen(label) != 6)
  993. {
  994. pData->engine->setLastError("invalid application setup received");
  995. return false;
  996. }
  997. for (int i=4; --i >= 0;) {
  998. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  999. }
  1000. for (int i=6; --i >= 4;) {
  1001. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+0x4f, false);
  1002. }
  1003. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  1004. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  1005. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  1006. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  1007. fInfo.setupLabel = label;
  1008. const int setupHints = label[5] - '0';
  1009. // ---------------------------------------------------------------
  1010. // set info
  1011. pData->filename = carla_strdup(filename);
  1012. if (name != nullptr && name[0] != '\0')
  1013. pData->name = pData->engine->getUniquePluginName(name);
  1014. else
  1015. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1016. std::srand(static_cast<uint>(std::time(nullptr)));
  1017. // ---------------------------------------------------------------
  1018. // init sem/shm
  1019. if (! fShmAudioPool.initializeServer())
  1020. {
  1021. carla_stderr("Failed to initialize shared memory audio pool");
  1022. return false;
  1023. }
  1024. if (! fShmRtClientControl.initializeServer())
  1025. {
  1026. carla_stderr("Failed to initialize RT client control");
  1027. fShmAudioPool.clear();
  1028. return false;
  1029. }
  1030. if (! fShmNonRtClientControl.initializeServer())
  1031. {
  1032. carla_stderr("Failed to initialize Non-RT client control");
  1033. fShmRtClientControl.clear();
  1034. fShmAudioPool.clear();
  1035. return false;
  1036. }
  1037. if (! fShmNonRtServerControl.initializeServer())
  1038. {
  1039. carla_stderr("Failed to initialize Non-RT server control");
  1040. fShmNonRtClientControl.clear();
  1041. fShmRtClientControl.clear();
  1042. fShmAudioPool.clear();
  1043. return false;
  1044. }
  1045. // ---------------------------------------------------------------
  1046. // setup hints and options
  1047. // FIXME dryWet broken
  1048. pData->hints = PLUGIN_IS_BRIDGE | PLUGIN_OPTION_FIXED_BUFFERS;
  1049. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1050. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1051. #endif
  1052. //fInfo.optionsAvailable = optionAv;
  1053. if (setupHints & 0x1)
  1054. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1055. // ---------------------------------------------------------------
  1056. // init bridge thread
  1057. {
  1058. char shmIdsStr[6*4+1];
  1059. carla_zeroChars(shmIdsStr, 6*4+1);
  1060. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1061. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1062. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1063. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1064. fBridgeThread.setData(shmIdsStr, label);
  1065. }
  1066. if (! restartBridgeThread())
  1067. return false;
  1068. // ---------------------------------------------------------------
  1069. // register client
  1070. if (pData->name == nullptr)
  1071. pData->name = pData->engine->getUniquePluginName("unknown");
  1072. pData->client = pData->engine->addClient(this);
  1073. if (pData->client == nullptr || ! pData->client->isOk())
  1074. {
  1075. pData->engine->setLastError("Failed to register plugin client");
  1076. return false;
  1077. }
  1078. return true;
  1079. }
  1080. private:
  1081. bool fInitiated;
  1082. bool fInitError;
  1083. bool fTimedOut;
  1084. bool fTimedError;
  1085. bool fProcCanceled;
  1086. uint fBufferSize;
  1087. uint fProcWaitTime;
  1088. int64_t fLastPingTime;
  1089. CarlaPluginJackThread fBridgeThread;
  1090. BridgeAudioPool fShmAudioPool;
  1091. BridgeRtClientControl fShmRtClientControl;
  1092. BridgeNonRtClientControl fShmNonRtClientControl;
  1093. BridgeNonRtServerControl fShmNonRtServerControl;
  1094. struct Info {
  1095. uint8_t aIns, aOuts;
  1096. uint8_t mIns, mOuts;
  1097. uint optionsAvailable;
  1098. CarlaString setupLabel;
  1099. std::vector<uint8_t> chunk;
  1100. Info()
  1101. : aIns(0),
  1102. aOuts(0),
  1103. mIns(0),
  1104. mOuts(0),
  1105. optionsAvailable(0),
  1106. setupLabel(),
  1107. chunk() {}
  1108. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1109. } fInfo;
  1110. void handleProcessStopped() noexcept
  1111. {
  1112. const bool wasActive = pData->active;
  1113. pData->active = false;
  1114. if (wasActive)
  1115. {
  1116. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1117. if (pData->engine->isOscControlRegistered())
  1118. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  1119. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  1120. #endif
  1121. }
  1122. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1123. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1124. }
  1125. void resizeAudioPool(const uint32_t bufferSize)
  1126. {
  1127. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1128. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1129. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1130. fShmRtClientControl.commitWrite();
  1131. waitForClient("resize-pool", 5000);
  1132. }
  1133. void waitForClient(const char* const action, const uint msecs)
  1134. {
  1135. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1136. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1137. if (fShmRtClientControl.waitForClient(msecs))
  1138. return;
  1139. fTimedOut = true;
  1140. carla_stderr2("waitForClient(%s) timed out", action);
  1141. }
  1142. bool restartBridgeThread()
  1143. {
  1144. fInitiated = false;
  1145. fInitError = false;
  1146. fTimedError = false;
  1147. // reset memory
  1148. fProcCanceled = false;
  1149. fShmRtClientControl.data->procFlags = 0;
  1150. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1151. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1152. fShmRtClientControl.clearData();
  1153. fShmNonRtClientControl.clearData();
  1154. fShmNonRtServerControl.clearData();
  1155. // initial values
  1156. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1157. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION);
  1158. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1159. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1160. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1161. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1162. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1163. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1164. fShmNonRtClientControl.commitWrite();
  1165. if (fShmAudioPool.dataSize != 0)
  1166. {
  1167. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1168. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1169. fShmRtClientControl.commitWrite();
  1170. }
  1171. else
  1172. {
  1173. // testing dummy message
  1174. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1175. fShmRtClientControl.commitWrite();
  1176. }
  1177. fBridgeThread.startThread();
  1178. fLastPingTime = Time::currentTimeMillis();
  1179. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1180. static bool sFirstInit = true;
  1181. int64_t timeoutEnd = 5000;
  1182. if (sFirstInit)
  1183. timeoutEnd *= 2;
  1184. sFirstInit = false;
  1185. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1186. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1187. {
  1188. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1189. if (needsEngineIdle)
  1190. pData->engine->idle();
  1191. idle();
  1192. if (fInitiated)
  1193. break;
  1194. if (pData->engine->isAboutToClose())
  1195. break;
  1196. carla_msleep(20);
  1197. }
  1198. fLastPingTime = -1;
  1199. if (fInitError || ! fInitiated)
  1200. {
  1201. fBridgeThread.stopThread(6000);
  1202. if (! fInitError)
  1203. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1204. "(or the plugin crashed on initialization?)");
  1205. return false;
  1206. }
  1207. return true;
  1208. }
  1209. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1210. };
  1211. CARLA_BACKEND_END_NAMESPACE
  1212. #endif // CARLA_OS_LINUX
  1213. // -------------------------------------------------------------------------------------------------------------------
  1214. CARLA_BACKEND_START_NAMESPACE
  1215. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1216. {
  1217. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"})", init.engine, init.filename, init.name, init.label);
  1218. #ifdef CARLA_OS_LINUX
  1219. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1220. if (! plugin->init(init.filename, init.name, init.label))
  1221. {
  1222. delete plugin;
  1223. return nullptr;
  1224. }
  1225. return plugin;
  1226. #else
  1227. init.engine->setLastError("JACK Application support not available");
  1228. return nullptr;
  1229. #endif
  1230. }
  1231. CARLA_BACKEND_END_NAMESPACE
  1232. // -------------------------------------------------------------------------------------------------------------------