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.

1563 lines
52KB

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