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.

1552 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. 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. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  177. // close UI
  178. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  179. pData->transientTryCounter = 0;
  180. #endif
  181. pData->singleMutex.lock();
  182. pData->masterMutex.lock();
  183. if (pData->client != nullptr && pData->client->isActive())
  184. pData->client->deactivate();
  185. if (pData->active)
  186. {
  187. deactivate();
  188. pData->active = false;
  189. }
  190. if (fBridgeThread.isThreadRunning())
  191. {
  192. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  193. fShmRtClientControl.commitWrite();
  194. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  195. fShmNonRtClientControl.commitWrite();
  196. if (! fTimedOut)
  197. waitForClient("stopping", 3000);
  198. }
  199. fBridgeThread.stopThread(3000);
  200. fShmNonRtServerControl.clear();
  201. fShmNonRtClientControl.clear();
  202. fShmRtClientControl.clear();
  203. fShmAudioPool.clear();
  204. clearBuffers();
  205. fInfo.chunk.clear();
  206. }
  207. // -------------------------------------------------------------------
  208. // Information (base)
  209. PluginType getType() const noexcept override
  210. {
  211. return PLUGIN_JACK;
  212. }
  213. PluginCategory getCategory() const noexcept override
  214. {
  215. return PLUGIN_CATEGORY_NONE;
  216. }
  217. // -------------------------------------------------------------------
  218. // Information (count)
  219. uint32_t getMidiInCount() const noexcept override
  220. {
  221. return fInfo.mIns;
  222. }
  223. uint32_t getMidiOutCount() const noexcept override
  224. {
  225. return fInfo.mOuts;
  226. }
  227. // -------------------------------------------------------------------
  228. // Information (current data)
  229. // -------------------------------------------------------------------
  230. // Information (per-plugin data)
  231. uint getOptionsAvailable() const noexcept override
  232. {
  233. return fInfo.optionsAvailable;
  234. }
  235. void getLabel(char* const strBuf) const noexcept override
  236. {
  237. std::strncpy(strBuf, fInfo.setupLabel, STR_MAX);
  238. }
  239. void getMaker(char* const strBuf) const noexcept override
  240. {
  241. nullStrBuf(strBuf);
  242. }
  243. void getCopyright(char* const strBuf) const noexcept override
  244. {
  245. nullStrBuf(strBuf);
  246. }
  247. void getRealName(char* const strBuf) const noexcept override
  248. {
  249. // FIXME
  250. std::strncpy(strBuf, "Carla's libjack", STR_MAX);
  251. }
  252. // -------------------------------------------------------------------
  253. // Set data (state)
  254. void prepareForSave() noexcept override
  255. {
  256. {
  257. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  258. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPrepareForSave);
  259. fShmNonRtClientControl.commitWrite();
  260. }
  261. }
  262. // -------------------------------------------------------------------
  263. // Set data (internal stuff)
  264. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  265. {
  266. {
  267. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  268. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  269. fShmNonRtClientControl.writeUInt(option);
  270. fShmNonRtClientControl.writeBool(yesNo);
  271. fShmNonRtClientControl.commitWrite();
  272. }
  273. CarlaPlugin::setOption(option, yesNo, sendCallback);
  274. }
  275. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  276. {
  277. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  278. {
  279. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  280. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  281. fShmNonRtClientControl.writeShort(channel);
  282. fShmNonRtClientControl.commitWrite();
  283. }
  284. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  285. }
  286. // -------------------------------------------------------------------
  287. // Set data (plugin-specific stuff)
  288. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  289. {
  290. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  291. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  292. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  293. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  294. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  295. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "__CarlaPingOnOff__") == 0)
  296. {
  297. #if 0
  298. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  299. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPingOnOff);
  300. fShmNonRtClientControl.writeBool(std::strcmp(value, "true") == 0);
  301. fShmNonRtClientControl.commitWrite();
  302. #endif
  303. return;
  304. }
  305. CarlaPlugin::setCustomData(type, key, value, sendGui);
  306. }
  307. // -------------------------------------------------------------------
  308. // Set ui stuff
  309. void showCustomUI(const bool yesNo) override
  310. {
  311. if (yesNo && ! fBridgeThread.isThreadRunning()) {
  312. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  313. }
  314. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  315. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  316. fShmNonRtClientControl.commitWrite();
  317. }
  318. void idle() override
  319. {
  320. if (fBridgeThread.isThreadRunning())
  321. {
  322. if (fInitiated && fTimedOut && pData->active)
  323. setActive(false, true, true);
  324. {
  325. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  326. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  327. fShmNonRtClientControl.commitWrite();
  328. }
  329. try {
  330. handleNonRtData();
  331. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  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. switch (opcode)
  888. {
  889. case kPluginBridgeNonRtServerNull:
  890. case kPluginBridgeNonRtServerPong:
  891. case kPluginBridgeNonRtServerPluginInfo1:
  892. case kPluginBridgeNonRtServerPluginInfo2:
  893. case kPluginBridgeNonRtServerAudioCount:
  894. case kPluginBridgeNonRtServerMidiCount:
  895. case kPluginBridgeNonRtServerCvCount:
  896. case kPluginBridgeNonRtServerParameterCount:
  897. case kPluginBridgeNonRtServerProgramCount:
  898. case kPluginBridgeNonRtServerMidiProgramCount:
  899. case kPluginBridgeNonRtServerPortName:
  900. case kPluginBridgeNonRtServerParameterData1:
  901. case kPluginBridgeNonRtServerParameterData2:
  902. case kPluginBridgeNonRtServerParameterRanges:
  903. case kPluginBridgeNonRtServerParameterValue:
  904. case kPluginBridgeNonRtServerParameterValue2:
  905. case kPluginBridgeNonRtServerDefaultValue:
  906. case kPluginBridgeNonRtServerCurrentProgram:
  907. case kPluginBridgeNonRtServerCurrentMidiProgram:
  908. case kPluginBridgeNonRtServerProgramName:
  909. case kPluginBridgeNonRtServerMidiProgramData:
  910. case kPluginBridgeNonRtServerSetCustomData:
  911. break;
  912. case kPluginBridgeNonRtServerSetChunkDataFile:
  913. // uint/size, str[] (filename)
  914. if (const uint32_t chunkFilePathSize = fShmNonRtServerControl.readUInt())
  915. {
  916. char chunkFilePath[chunkFilePathSize];
  917. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  918. }
  919. break;
  920. case kPluginBridgeNonRtServerSetLatency:
  921. case kPluginBridgeNonRtServerSetParameterText:
  922. break;
  923. case kPluginBridgeNonRtServerReady:
  924. fInitiated = true;
  925. break;
  926. case kPluginBridgeNonRtServerSaved:
  927. break;
  928. case kPluginBridgeNonRtServerUiClosed:
  929. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  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_ALTERNATIVE_ARCH
  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 fBufferSize;
  1077. uint fProcWaitTime;
  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_stderr2("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. const bool needsCancelableAction = ! pData->engine->isLoadingProject();
  1168. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1169. if (needsCancelableAction)
  1170. {
  1171. pData->engine->setActionCanceled(false);
  1172. pData->engine->callback(ENGINE_CALLBACK_CANCELABLE_ACTION, pData->id, 1, 0, 0.0f, "Loading JACK application");
  1173. }
  1174. for (;fBridgeThread.isThreadRunning();)
  1175. {
  1176. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1177. if (needsEngineIdle)
  1178. pData->engine->idle();
  1179. idle();
  1180. if (fInitiated)
  1181. break;
  1182. if (pData->engine->isAboutToClose() || pData->engine->wasActionCanceled())
  1183. break;
  1184. carla_msleep(5);
  1185. }
  1186. if (needsCancelableAction)
  1187. pData->engine->callback(ENGINE_CALLBACK_CANCELABLE_ACTION, pData->id, 0, 0, 0.0f, "Loading JACK application");
  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\"})", 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. // -------------------------------------------------------------------------------------------------------------------