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.

1526 lines
51KB

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