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.

1558 lines
52KB

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