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.

1557 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. break;
  919. case kPluginBridgeNonRtServerReady:
  920. fInitiated = true;
  921. break;
  922. case kPluginBridgeNonRtServerSaved:
  923. break;
  924. case kPluginBridgeNonRtServerUiClosed:
  925. carla_stdout("got kPluginBridgeNonRtServerUiClosed, bridge closed cleanly?");
  926. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  927. //fBridgeThread.signalThreadShouldExit();
  928. //handleProcessStopped();
  929. //fBridgeThread.stopThread(5000);
  930. break;
  931. case kPluginBridgeNonRtServerError: {
  932. // error
  933. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  934. char error[errorSize+1];
  935. carla_zeroChars(error, errorSize+1);
  936. fShmNonRtServerControl.readCustomData(error, errorSize);
  937. if (fInitiated)
  938. {
  939. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  940. // just in case
  941. pData->engine->setLastError(error);
  942. fInitError = true;
  943. }
  944. else
  945. {
  946. pData->engine->setLastError(error);
  947. fInitError = true;
  948. fInitiated = true;
  949. }
  950. } break;
  951. }
  952. }
  953. }
  954. // -------------------------------------------------------------------
  955. uintptr_t getUiBridgeProcessId() const noexcept override
  956. {
  957. return fBridgeThread.getProcessID();
  958. }
  959. // -------------------------------------------------------------------
  960. bool init(const char* const filename, const char* const name, const char* const label)
  961. {
  962. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  963. // ---------------------------------------------------------------
  964. // first checks
  965. if (pData->client != nullptr)
  966. {
  967. pData->engine->setLastError("Plugin client is already registered");
  968. return false;
  969. }
  970. if (filename == nullptr || filename[0] == '\0')
  971. {
  972. pData->engine->setLastError("null filename");
  973. return false;
  974. }
  975. if (label == nullptr || label[0] == '\0')
  976. {
  977. pData->engine->setLastError("null label");
  978. return false;
  979. }
  980. // ---------------------------------------------------------------
  981. // check setup
  982. if (std::strlen(label) != 6)
  983. {
  984. pData->engine->setLastError("invalid application setup received");
  985. return false;
  986. }
  987. for (int i=4; --i >= 0;) {
  988. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  989. }
  990. for (int i=6; --i >= 4;) {
  991. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+0x4f, false);
  992. }
  993. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  994. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  995. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  996. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  997. fInfo.setupLabel = label;
  998. const int setupHints = label[5] - '0';
  999. // ---------------------------------------------------------------
  1000. // set info
  1001. pData->filename = carla_strdup(filename);
  1002. if (name != nullptr && name[0] != '\0')
  1003. pData->name = pData->engine->getUniquePluginName(name);
  1004. else
  1005. pData->name = pData->engine->getUniquePluginName("Jack Application");
  1006. std::srand(static_cast<uint>(std::time(nullptr)));
  1007. // ---------------------------------------------------------------
  1008. // init sem/shm
  1009. if (! fShmAudioPool.initializeServer())
  1010. {
  1011. carla_stderr("Failed to initialize shared memory audio pool");
  1012. return false;
  1013. }
  1014. if (! fShmRtClientControl.initializeServer())
  1015. {
  1016. carla_stderr("Failed to initialize RT client control");
  1017. fShmAudioPool.clear();
  1018. return false;
  1019. }
  1020. if (! fShmNonRtClientControl.initializeServer())
  1021. {
  1022. carla_stderr("Failed to initialize Non-RT client control");
  1023. fShmRtClientControl.clear();
  1024. fShmAudioPool.clear();
  1025. return false;
  1026. }
  1027. if (! fShmNonRtServerControl.initializeServer())
  1028. {
  1029. carla_stderr("Failed to initialize Non-RT server control");
  1030. fShmNonRtClientControl.clear();
  1031. fShmRtClientControl.clear();
  1032. fShmAudioPool.clear();
  1033. return false;
  1034. }
  1035. // ---------------------------------------------------------------
  1036. // setup hints and options
  1037. // FIXME dryWet broken
  1038. pData->hints = PLUGIN_IS_BRIDGE | PLUGIN_OPTION_FIXED_BUFFERS;
  1039. #ifndef BUILD_BRIDGE
  1040. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1041. #endif
  1042. //fInfo.optionsAvailable = optionAv;
  1043. if (setupHints & 0x1)
  1044. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1045. // ---------------------------------------------------------------
  1046. // init bridge thread
  1047. {
  1048. char shmIdsStr[6*4+1];
  1049. carla_zeroChars(shmIdsStr, 6*4+1);
  1050. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1051. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1052. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1053. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1054. fBridgeThread.setData(shmIdsStr, label);
  1055. }
  1056. if (! restartBridgeThread())
  1057. return false;
  1058. // ---------------------------------------------------------------
  1059. // register client
  1060. if (pData->name == nullptr)
  1061. pData->name = pData->engine->getUniquePluginName("unknown");
  1062. pData->client = pData->engine->addClient(this);
  1063. if (pData->client == nullptr || ! pData->client->isOk())
  1064. {
  1065. pData->engine->setLastError("Failed to register plugin client");
  1066. return false;
  1067. }
  1068. return true;
  1069. }
  1070. private:
  1071. bool fInitiated;
  1072. bool fInitError;
  1073. bool fTimedOut;
  1074. bool fTimedError;
  1075. bool fProcCanceled;
  1076. uint fProcWaitTime;
  1077. int64_t fLastPingTime;
  1078. CarlaPluginJackThread fBridgeThread;
  1079. BridgeAudioPool fShmAudioPool;
  1080. BridgeRtClientControl fShmRtClientControl;
  1081. BridgeNonRtClientControl fShmNonRtClientControl;
  1082. BridgeNonRtServerControl fShmNonRtServerControl;
  1083. struct Info {
  1084. uint8_t aIns, aOuts;
  1085. uint8_t mIns, mOuts;
  1086. uint optionsAvailable;
  1087. CarlaString setupLabel;
  1088. std::vector<uint8_t> chunk;
  1089. Info()
  1090. : aIns(0),
  1091. aOuts(0),
  1092. mIns(0),
  1093. mOuts(0),
  1094. optionsAvailable(0),
  1095. setupLabel(),
  1096. chunk() {}
  1097. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1098. } fInfo;
  1099. void handleProcessStopped() noexcept
  1100. {
  1101. const bool wasActive = pData->active;
  1102. pData->active = false;
  1103. if (wasActive)
  1104. {
  1105. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1106. if (pData->engine->isOscControlRegistered())
  1107. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  1108. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  1109. #endif
  1110. }
  1111. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1112. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1113. }
  1114. void resizeAudioPool(const uint32_t bufferSize)
  1115. {
  1116. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1117. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1118. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1119. fShmRtClientControl.commitWrite();
  1120. waitForClient("resize-pool", 5000);
  1121. }
  1122. void waitForClient(const char* const action, const uint msecs)
  1123. {
  1124. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1125. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1126. if (fShmRtClientControl.waitForClient(msecs))
  1127. return;
  1128. fTimedOut = true;
  1129. carla_stderr("waitForClient(%s) timed out", action);
  1130. }
  1131. bool restartBridgeThread()
  1132. {
  1133. fInitiated = false;
  1134. fInitError = false;
  1135. fTimedError = false;
  1136. // reset memory
  1137. fProcCanceled = false;
  1138. fShmRtClientControl.data->procFlags = 0;
  1139. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1140. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1141. fShmRtClientControl.clearData();
  1142. fShmNonRtClientControl.clearData();
  1143. fShmNonRtServerControl.clearData();
  1144. // initial values
  1145. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1146. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION);
  1147. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1148. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1149. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1150. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1151. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1152. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1153. fShmNonRtClientControl.commitWrite();
  1154. if (fShmAudioPool.dataSize != 0)
  1155. {
  1156. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1157. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1158. fShmRtClientControl.commitWrite();
  1159. }
  1160. else
  1161. {
  1162. // testing dummy message
  1163. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1164. fShmRtClientControl.commitWrite();
  1165. }
  1166. fBridgeThread.startThread();
  1167. fLastPingTime = Time::currentTimeMillis();
  1168. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1169. static bool sFirstInit = true;
  1170. int64_t timeoutEnd = 5000;
  1171. if (sFirstInit)
  1172. timeoutEnd *= 2;
  1173. sFirstInit = false;
  1174. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1175. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1176. {
  1177. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1178. if (needsEngineIdle)
  1179. pData->engine->idle();
  1180. idle();
  1181. if (fInitiated)
  1182. break;
  1183. if (pData->engine->isAboutToClose())
  1184. break;
  1185. carla_msleep(20);
  1186. }
  1187. fLastPingTime = -1;
  1188. if (fInitError || ! fInitiated)
  1189. {
  1190. fBridgeThread.stopThread(6000);
  1191. if (! fInitError)
  1192. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1193. "(or the plugin crashed on initialization?)");
  1194. return false;
  1195. }
  1196. return true;
  1197. }
  1198. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1199. };
  1200. CARLA_BACKEND_END_NAMESPACE
  1201. #endif // CARLA_OS_LINUX
  1202. // -------------------------------------------------------------------------------------------------------------------
  1203. CARLA_BACKEND_START_NAMESPACE
  1204. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1205. {
  1206. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label);
  1207. #ifdef CARLA_OS_LINUX
  1208. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1209. if (! plugin->init(init.filename, init.name, init.label))
  1210. {
  1211. delete plugin;
  1212. return nullptr;
  1213. }
  1214. return plugin;
  1215. #else
  1216. init.engine->setLastError("JACK Application support not available");
  1217. return nullptr;
  1218. #endif
  1219. }
  1220. CARLA_BACKEND_END_NAMESPACE
  1221. // -------------------------------------------------------------------------------------------------------------------