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.

1554 lines
52KB

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