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.

1533 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 "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. // -------------------------------------------------------------------
  279. // Set ui stuff
  280. void showCustomUI(const bool yesNo) override
  281. {
  282. if (yesNo && ! fBridgeThread.isThreadRunning()) {
  283. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  284. }
  285. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  286. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  287. fShmNonRtClientControl.commitWrite();
  288. }
  289. void idle() override
  290. {
  291. if (fBridgeThread.isThreadRunning())
  292. {
  293. if (fInitiated && fTimedOut && pData->active)
  294. setActive(false, true, true);
  295. {
  296. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  297. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  298. fShmNonRtClientControl.commitWrite();
  299. }
  300. try {
  301. handleNonRtData();
  302. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  303. if (fLastPingTime > 0 && Time::currentTimeMillis() > fLastPingTime + 30000)
  304. {
  305. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  306. // TODO
  307. //threadShouldExit();
  308. //callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  309. }
  310. }
  311. else if (fInitiated)
  312. {
  313. fTimedOut = true;
  314. fTimedError = true;
  315. fInitiated = false;
  316. handleProcessStopped();
  317. }
  318. else if (fProcCanceled)
  319. {
  320. handleProcessStopped();
  321. fProcCanceled = false;
  322. }
  323. CarlaPlugin::idle();
  324. }
  325. // -------------------------------------------------------------------
  326. // Plugin state
  327. void reload() override
  328. {
  329. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  330. carla_debug("CarlaPluginJack::reload() - start");
  331. const EngineProcessMode processMode(pData->engine->getProccessMode());
  332. // Safely disable plugin for reload
  333. const ScopedDisabler sd(this);
  334. // cleanup of previous data
  335. pData->audioIn.clear();
  336. pData->audioOut.clear();
  337. pData->event.clear();
  338. bool needsCtrlIn, needsCtrlOut;
  339. needsCtrlIn = needsCtrlOut = false;
  340. if (fInfo.aIns > 0)
  341. {
  342. pData->audioIn.createNew(fInfo.aIns);
  343. }
  344. if (fInfo.aOuts > 0)
  345. {
  346. pData->audioOut.createNew(fInfo.aOuts);
  347. needsCtrlIn = true;
  348. }
  349. if (fInfo.mIns > 0)
  350. needsCtrlIn = true;
  351. if (fInfo.mOuts > 0)
  352. needsCtrlOut = true;
  353. const uint portNameSize(pData->engine->getMaxPortNameSize());
  354. CarlaString portName;
  355. // Audio Ins
  356. for (uint8_t j=0; j < fInfo.aIns; ++j)
  357. {
  358. portName.clear();
  359. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  360. {
  361. portName = pData->name;
  362. portName += ":";
  363. }
  364. if (fInfo.aIns > 1)
  365. {
  366. portName += "audio_in_";
  367. portName += CarlaString(j+1);
  368. }
  369. else
  370. {
  371. portName += "audio_in";
  372. }
  373. portName.truncate(portNameSize);
  374. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  375. pData->audioIn.ports[j].rindex = j;
  376. }
  377. // Audio Outs
  378. for (uint8_t j=0; j < fInfo.aOuts; ++j)
  379. {
  380. portName.clear();
  381. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  382. {
  383. portName = pData->name;
  384. portName += ":";
  385. }
  386. if (fInfo.aOuts > 1)
  387. {
  388. portName += "audio_out_";
  389. portName += CarlaString(j+1);
  390. }
  391. else
  392. {
  393. portName += "audio_out";
  394. }
  395. portName.truncate(portNameSize);
  396. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  397. pData->audioOut.ports[j].rindex = j;
  398. }
  399. if (needsCtrlIn)
  400. {
  401. portName.clear();
  402. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  403. {
  404. portName = pData->name;
  405. portName += ":";
  406. }
  407. portName += "event-in";
  408. portName.truncate(portNameSize);
  409. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  410. }
  411. if (needsCtrlOut)
  412. {
  413. portName.clear();
  414. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  415. {
  416. portName = pData->name;
  417. portName += ":";
  418. }
  419. portName += "event-out";
  420. portName.truncate(portNameSize);
  421. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  422. }
  423. // extra plugin hints
  424. pData->extraHints = 0x0;
  425. if (fInfo.mIns > 0)
  426. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  427. if (fInfo.mOuts > 0)
  428. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  429. if (fInfo.aIns <= 2 && fInfo.aOuts <= 2 && (fInfo.aIns == fInfo.aOuts || fInfo.aIns == 0 || fInfo.aOuts == 0))
  430. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  431. bufferSizeChanged(pData->engine->getBufferSize());
  432. reloadPrograms(true);
  433. carla_debug("CarlaPluginJack::reload() - end");
  434. }
  435. // -------------------------------------------------------------------
  436. // Plugin processing
  437. void activate() noexcept override
  438. {
  439. if (! fBridgeThread.isThreadRunning())
  440. {
  441. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  442. }
  443. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  444. {
  445. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  446. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  447. fShmNonRtClientControl.commitWrite();
  448. }
  449. fTimedOut = false;
  450. try {
  451. waitForClient("activate", 2000);
  452. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  453. }
  454. void deactivate() noexcept override
  455. {
  456. if (! fBridgeThread.isThreadRunning())
  457. return;
  458. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  459. {
  460. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  461. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  462. fShmNonRtClientControl.commitWrite();
  463. }
  464. fTimedOut = false;
  465. try {
  466. waitForClient("deactivate", 2000);
  467. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  468. }
  469. void process(const float** const audioIn, float** const audioOut, const float**, float**, const uint32_t frames) override
  470. {
  471. // --------------------------------------------------------------------------------------------------------
  472. // Check if active
  473. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  474. {
  475. // disable any output sound
  476. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  477. carla_zeroFloats(audioOut[i], frames);
  478. return;
  479. }
  480. // --------------------------------------------------------------------------------------------------------
  481. // Check if needs reset
  482. if (pData->needsReset)
  483. {
  484. // TODO
  485. pData->needsReset = false;
  486. }
  487. // --------------------------------------------------------------------------------------------------------
  488. // Event Input
  489. if (pData->event.portIn != nullptr)
  490. {
  491. // ----------------------------------------------------------------------------------------------------
  492. // MIDI Input (External)
  493. if (pData->extNotes.mutex.tryLock())
  494. {
  495. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  496. {
  497. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  498. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  499. uint8_t data1, data2, data3;
  500. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  501. data2 = note.note;
  502. data3 = note.velo;
  503. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  504. fShmRtClientControl.writeUInt(0); // time
  505. fShmRtClientControl.writeByte(0); // port
  506. fShmRtClientControl.writeByte(3); // size
  507. fShmRtClientControl.writeByte(data1);
  508. fShmRtClientControl.writeByte(data2);
  509. fShmRtClientControl.writeByte(data3);
  510. fShmRtClientControl.commitWrite();
  511. }
  512. pData->extNotes.data.clear();
  513. pData->extNotes.mutex.unlock();
  514. } // End of MIDI Input (External)
  515. // ----------------------------------------------------------------------------------------------------
  516. // Event Input (System)
  517. #ifndef BUILD_BRIDGE
  518. bool allNotesOffSent = false;
  519. #endif
  520. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  521. {
  522. const EngineEvent& event(pData->event.portIn->getEvent(i));
  523. // Control change
  524. switch (event.type)
  525. {
  526. case kEngineEventTypeNull:
  527. break;
  528. case kEngineEventTypeControl: {
  529. const EngineControlEvent& ctrlEvent = event.ctrl;
  530. switch (ctrlEvent.type)
  531. {
  532. case kEngineControlEventTypeNull:
  533. break;
  534. case kEngineControlEventTypeParameter:
  535. #ifndef BUILD_BRIDGE
  536. // Control backend stuff
  537. if (event.channel == pData->ctrlChannel)
  538. {
  539. float value;
  540. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  541. {
  542. value = ctrlEvent.value;
  543. setDryWet(value, false, false);
  544. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  545. }
  546. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  547. {
  548. value = ctrlEvent.value*127.0f/100.0f;
  549. setVolume(value, false, false);
  550. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  551. }
  552. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  553. {
  554. float left, right;
  555. value = ctrlEvent.value/0.5f - 1.0f;
  556. if (value < 0.0f)
  557. {
  558. left = -1.0f;
  559. right = (value*2.0f)+1.0f;
  560. }
  561. else if (value > 0.0f)
  562. {
  563. left = (value*2.0f)-1.0f;
  564. right = 1.0f;
  565. }
  566. else
  567. {
  568. left = -1.0f;
  569. right = 1.0f;
  570. }
  571. setBalanceLeft(left, false, false);
  572. setBalanceRight(right, false, false);
  573. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  574. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  575. }
  576. }
  577. #endif
  578. break;
  579. case kEngineControlEventTypeMidiBank:
  580. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  581. {
  582. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  583. fShmRtClientControl.writeUInt(event.time);
  584. fShmRtClientControl.writeByte(event.channel);
  585. fShmRtClientControl.writeUShort(event.ctrl.param);
  586. fShmRtClientControl.commitWrite();
  587. }
  588. break;
  589. case kEngineControlEventTypeMidiProgram:
  590. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  591. {
  592. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  593. fShmRtClientControl.writeUInt(event.time);
  594. fShmRtClientControl.writeByte(event.channel);
  595. fShmRtClientControl.writeUShort(event.ctrl.param);
  596. fShmRtClientControl.commitWrite();
  597. }
  598. break;
  599. case kEngineControlEventTypeAllSoundOff:
  600. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  601. {
  602. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  603. fShmRtClientControl.writeUInt(event.time);
  604. fShmRtClientControl.writeByte(event.channel);
  605. fShmRtClientControl.commitWrite();
  606. }
  607. break;
  608. case kEngineControlEventTypeAllNotesOff:
  609. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  610. {
  611. #ifndef BUILD_BRIDGE
  612. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  613. {
  614. allNotesOffSent = true;
  615. sendMidiAllNotesOffToCallback();
  616. }
  617. #endif
  618. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  619. fShmRtClientControl.writeUInt(event.time);
  620. fShmRtClientControl.writeByte(event.channel);
  621. fShmRtClientControl.commitWrite();
  622. }
  623. break;
  624. } // switch (ctrlEvent.type)
  625. break;
  626. } // case kEngineEventTypeControl
  627. case kEngineEventTypeMidi: {
  628. const EngineMidiEvent& midiEvent(event.midi);
  629. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  630. continue;
  631. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  632. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  633. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  634. continue;
  635. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  636. continue;
  637. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  638. continue;
  639. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  640. continue;
  641. // Fix bad note-off
  642. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  643. status = MIDI_STATUS_NOTE_OFF;
  644. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  645. fShmRtClientControl.writeUInt(event.time);
  646. fShmRtClientControl.writeByte(midiEvent.port);
  647. fShmRtClientControl.writeByte(midiEvent.size);
  648. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  649. for (uint8_t j=1; j < midiEvent.size; ++j)
  650. fShmRtClientControl.writeByte(midiData[j]);
  651. fShmRtClientControl.commitWrite();
  652. if (status == MIDI_STATUS_NOTE_ON)
  653. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  654. else if (status == MIDI_STATUS_NOTE_OFF)
  655. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  656. } break;
  657. }
  658. }
  659. pData->postRtEvents.trySplice();
  660. } // End of Event Input
  661. if (! processSingle(audioIn, audioOut, frames))
  662. return;
  663. // --------------------------------------------------------------------------------------------------------
  664. // MIDI Output
  665. if (pData->event.portOut != nullptr)
  666. {
  667. uint32_t time;
  668. uint8_t port, size;
  669. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  670. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  671. {
  672. // get time
  673. time = *(const uint32_t*)midiData;
  674. midiData += 4;
  675. // get port and size
  676. port = *midiData++;
  677. size = *midiData++;
  678. if (size == 0)
  679. break;
  680. // store midi data advancing as needed
  681. uint8_t data[size];
  682. for (uint8_t j=0; j<size; ++j)
  683. data[j] = *midiData++;
  684. pData->event.portOut->writeMidiEvent(time, size, data);
  685. read += kBridgeBaseMidiOutHeaderSize + size;
  686. }
  687. // TODO
  688. (void)port;
  689. } // End of Control and MIDI Output
  690. }
  691. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  692. {
  693. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  694. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  695. if (pData->audioIn.count > 0)
  696. {
  697. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  698. }
  699. if (pData->audioOut.count > 0)
  700. {
  701. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  702. }
  703. // --------------------------------------------------------------------------------------------------------
  704. // Try lock, silence otherwise
  705. if (pData->engine->isOffline())
  706. {
  707. pData->singleMutex.lock();
  708. }
  709. else if (! pData->singleMutex.tryLock())
  710. {
  711. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  712. carla_zeroFloats(audioOut[i], frames);
  713. return false;
  714. }
  715. // --------------------------------------------------------------------------------------------------------
  716. // Reset audio buffers
  717. for (uint32_t i=0; i < fInfo.aIns; ++i)
  718. carla_copyFloats(fShmAudioPool.data + (i * frames), audioIn[i], frames);
  719. // --------------------------------------------------------------------------------------------------------
  720. // TimeInfo
  721. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  722. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  723. bridgeTimeInfo.playing = timeInfo.playing;
  724. bridgeTimeInfo.frame = timeInfo.frame;
  725. bridgeTimeInfo.usecs = timeInfo.usecs;
  726. bridgeTimeInfo.valid = timeInfo.valid;
  727. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  728. {
  729. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  730. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  731. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  732. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  733. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  734. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  735. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  736. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  737. }
  738. // --------------------------------------------------------------------------------------------------------
  739. // Run plugin
  740. {
  741. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  742. fShmRtClientControl.commitWrite();
  743. }
  744. waitForClient("process", fProcWaitTime);
  745. if (fTimedOut)
  746. {
  747. pData->singleMutex.unlock();
  748. return false;
  749. }
  750. if (fShmRtClientControl.data->procFlags)
  751. {
  752. fInitiated = false;
  753. fProcCanceled = true;
  754. }
  755. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  756. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), frames);
  757. #ifndef BUILD_BRIDGE
  758. // --------------------------------------------------------------------------------------------------------
  759. // Post-processing (dry/wet, volume and balance)
  760. {
  761. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  762. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  763. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  764. const bool isMono = (pData->audioIn.count == 1);
  765. bool isPair;
  766. float bufValue, oldBufLeft[doBalance ? frames : 1];
  767. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  768. {
  769. // Dry/Wet
  770. if (doDryWet)
  771. {
  772. const uint32_t c = isMono ? 0 : i;
  773. for (uint32_t k=0; k < frames; ++k)
  774. {
  775. bufValue = audioIn[c][k];
  776. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  777. }
  778. }
  779. // Balance
  780. if (doBalance)
  781. {
  782. isPair = (i % 2 == 0);
  783. if (isPair)
  784. {
  785. CARLA_ASSERT(i+1 < pData->audioOut.count);
  786. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  787. }
  788. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  789. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  790. for (uint32_t k=0; k < frames; ++k)
  791. {
  792. if (isPair)
  793. {
  794. // left
  795. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  796. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  797. }
  798. else
  799. {
  800. // right
  801. audioOut[i][k] = audioOut[i][k] * balRangeR;
  802. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  803. }
  804. }
  805. }
  806. // Volume (and buffer copy)
  807. if (doVolume)
  808. {
  809. for (uint32_t k=0; k < frames; ++k)
  810. audioOut[i][k] *= pData->postProc.volume;
  811. }
  812. }
  813. } // End of Post-processing
  814. #endif
  815. // --------------------------------------------------------------------------------------------------------
  816. pData->singleMutex.unlock();
  817. return true;
  818. }
  819. void bufferSizeChanged(const uint32_t newBufferSize) override
  820. {
  821. resizeAudioPool(newBufferSize);
  822. {
  823. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  824. fShmRtClientControl.writeUInt(newBufferSize);
  825. fShmRtClientControl.commitWrite();
  826. }
  827. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  828. fProcWaitTime = 1000;
  829. waitForClient("buffersize", 1000);
  830. }
  831. void sampleRateChanged(const double newSampleRate) override
  832. {
  833. {
  834. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  835. fShmRtClientControl.writeDouble(newSampleRate);
  836. fShmRtClientControl.commitWrite();
  837. }
  838. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  839. fProcWaitTime = 1000;
  840. waitForClient("samplerate", 1000);
  841. }
  842. void offlineModeChanged(const bool isOffline) override
  843. {
  844. {
  845. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  846. fShmRtClientControl.writeBool(isOffline);
  847. fShmRtClientControl.commitWrite();
  848. }
  849. waitForClient("offline", 1000);
  850. }
  851. // -------------------------------------------------------------------
  852. // Post-poned UI Stuff
  853. // -------------------------------------------------------------------
  854. void handleNonRtData()
  855. {
  856. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  857. {
  858. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  859. //#ifdef DEBUG
  860. if (opcode != kPluginBridgeNonRtServerPong)
  861. {
  862. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  863. }
  864. //#endif
  865. if (opcode != kPluginBridgeNonRtServerNull && fLastPingTime > 0)
  866. fLastPingTime = Time::currentTimeMillis();
  867. switch (opcode)
  868. {
  869. case kPluginBridgeNonRtServerNull:
  870. case kPluginBridgeNonRtServerPong:
  871. case kPluginBridgeNonRtServerPluginInfo1:
  872. case kPluginBridgeNonRtServerPluginInfo2:
  873. case kPluginBridgeNonRtServerAudioCount:
  874. case kPluginBridgeNonRtServerMidiCount:
  875. case kPluginBridgeNonRtServerCvCount:
  876. case kPluginBridgeNonRtServerParameterCount:
  877. case kPluginBridgeNonRtServerProgramCount:
  878. case kPluginBridgeNonRtServerMidiProgramCount:
  879. case kPluginBridgeNonRtServerPortName:
  880. case kPluginBridgeNonRtServerParameterData1:
  881. case kPluginBridgeNonRtServerParameterData2:
  882. case kPluginBridgeNonRtServerParameterRanges:
  883. case kPluginBridgeNonRtServerParameterValue:
  884. case kPluginBridgeNonRtServerParameterValue2:
  885. case kPluginBridgeNonRtServerDefaultValue:
  886. case kPluginBridgeNonRtServerCurrentProgram:
  887. case kPluginBridgeNonRtServerCurrentMidiProgram:
  888. case kPluginBridgeNonRtServerProgramName:
  889. case kPluginBridgeNonRtServerMidiProgramData:
  890. case kPluginBridgeNonRtServerSetCustomData:
  891. break;
  892. case kPluginBridgeNonRtServerSetChunkDataFile: {
  893. // uint/size, str[] (filename)
  894. const uint32_t chunkFilePathSize(fShmNonRtServerControl.readUInt());
  895. char chunkFilePath[chunkFilePathSize];
  896. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  897. } break;
  898. case kPluginBridgeNonRtServerSetLatency:
  899. break;
  900. case kPluginBridgeNonRtServerReady:
  901. fInitiated = true;
  902. break;
  903. case kPluginBridgeNonRtServerSaved:
  904. break;
  905. case kPluginBridgeNonRtServerUiClosed:
  906. carla_stdout("got kPluginBridgeNonRtServerUiClosed, bridge closed cleanly?");
  907. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  908. //fBridgeThread.signalThreadShouldExit();
  909. //handleProcessStopped();
  910. //fBridgeThread.stopThread(5000);
  911. break;
  912. case kPluginBridgeNonRtServerError: {
  913. // error
  914. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  915. char error[errorSize+1];
  916. carla_zeroChars(error, errorSize+1);
  917. fShmNonRtServerControl.readCustomData(error, errorSize);
  918. if (fInitiated)
  919. {
  920. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  921. // just in case
  922. pData->engine->setLastError(error);
  923. fInitError = true;
  924. }
  925. else
  926. {
  927. pData->engine->setLastError(error);
  928. fInitError = true;
  929. fInitiated = true;
  930. }
  931. } break;
  932. }
  933. }
  934. }
  935. // -------------------------------------------------------------------
  936. uintptr_t getUiBridgeProcessId() const noexcept override
  937. {
  938. return fBridgeThread.getProcessID();
  939. }
  940. // -------------------------------------------------------------------
  941. bool init(const char* const filename, const char* const name, const char* const label)
  942. {
  943. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  944. // ---------------------------------------------------------------
  945. // first checks
  946. if (pData->client != nullptr)
  947. {
  948. pData->engine->setLastError("Plugin client is already registered");
  949. return false;
  950. }
  951. if (filename == nullptr || filename[0] == '\0')
  952. {
  953. pData->engine->setLastError("null filename");
  954. return false;
  955. }
  956. if (label == nullptr || label[0] == '\0')
  957. {
  958. pData->engine->setLastError("null label");
  959. return false;
  960. }
  961. // ---------------------------------------------------------------
  962. // check setup
  963. if (std::strlen(label) != 6)
  964. {
  965. pData->engine->setLastError("invalid application setup received");
  966. return false;
  967. }
  968. for (int i=4; --i >= 0;) {
  969. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  970. }
  971. for (int i=6; --i >= 4;) {
  972. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+0x4f, false);
  973. }
  974. fInfo.aIns = static_cast<uint8_t>(label[0] - '0');
  975. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  976. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  977. fInfo.mOuts = static_cast<uint8_t>(carla_minPositive(label[3] - '0', 1));
  978. fInfo.setupLabel = label;
  979. const int setupHints = label[5] - '0';
  980. // ---------------------------------------------------------------
  981. // set info
  982. pData->filename = carla_strdup(filename);
  983. if (name != nullptr && name[0] != '\0')
  984. pData->name = pData->engine->getUniquePluginName(name);
  985. else
  986. pData->name = pData->engine->getUniquePluginName("Jack Application");
  987. std::srand(static_cast<uint>(std::time(nullptr)));
  988. // ---------------------------------------------------------------
  989. // init sem/shm
  990. if (! fShmAudioPool.initializeServer())
  991. {
  992. carla_stderr("Failed to initialize shared memory audio pool");
  993. return false;
  994. }
  995. if (! fShmRtClientControl.initializeServer())
  996. {
  997. carla_stderr("Failed to initialize RT client control");
  998. fShmAudioPool.clear();
  999. return false;
  1000. }
  1001. if (! fShmNonRtClientControl.initializeServer())
  1002. {
  1003. carla_stderr("Failed to initialize Non-RT client control");
  1004. fShmRtClientControl.clear();
  1005. fShmAudioPool.clear();
  1006. return false;
  1007. }
  1008. if (! fShmNonRtServerControl.initializeServer())
  1009. {
  1010. carla_stderr("Failed to initialize Non-RT server control");
  1011. fShmNonRtClientControl.clear();
  1012. fShmRtClientControl.clear();
  1013. fShmAudioPool.clear();
  1014. return false;
  1015. }
  1016. // ---------------------------------------------------------------
  1017. // setup hints and options
  1018. // FIXME dryWet broken
  1019. pData->hints = PLUGIN_IS_BRIDGE | PLUGIN_OPTION_FIXED_BUFFERS;
  1020. #ifndef BUILD_BRIDGE
  1021. pData->hints |= /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE;
  1022. #endif
  1023. //fInfo.optionsAvailable = optionAv;
  1024. if (setupHints & 0x1)
  1025. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1026. // ---------------------------------------------------------------
  1027. // init bridge thread
  1028. {
  1029. char shmIdsStr[6*4+1];
  1030. carla_zeroChars(shmIdsStr, 6*4+1);
  1031. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1032. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1033. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1034. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1035. fBridgeThread.setData(shmIdsStr, label);
  1036. }
  1037. if (! restartBridgeThread())
  1038. return false;
  1039. // ---------------------------------------------------------------
  1040. // register client
  1041. if (pData->name == nullptr)
  1042. pData->name = pData->engine->getUniquePluginName("unknown");
  1043. pData->client = pData->engine->addClient(this);
  1044. if (pData->client == nullptr || ! pData->client->isOk())
  1045. {
  1046. pData->engine->setLastError("Failed to register plugin client");
  1047. return false;
  1048. }
  1049. return true;
  1050. }
  1051. private:
  1052. bool fInitiated;
  1053. bool fInitError;
  1054. bool fTimedOut;
  1055. bool fTimedError;
  1056. bool fProcCanceled;
  1057. uint fProcWaitTime;
  1058. int64_t fLastPingTime;
  1059. CarlaPluginJackThread fBridgeThread;
  1060. BridgeAudioPool fShmAudioPool;
  1061. BridgeRtClientControl fShmRtClientControl;
  1062. BridgeNonRtClientControl fShmNonRtClientControl;
  1063. BridgeNonRtServerControl fShmNonRtServerControl;
  1064. struct Info {
  1065. uint8_t aIns, aOuts;
  1066. uint8_t mIns, mOuts;
  1067. uint optionsAvailable;
  1068. CarlaString setupLabel;
  1069. std::vector<uint8_t> chunk;
  1070. Info()
  1071. : aIns(0),
  1072. aOuts(0),
  1073. mIns(0),
  1074. mOuts(0),
  1075. optionsAvailable(0),
  1076. setupLabel(),
  1077. chunk() {}
  1078. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1079. } fInfo;
  1080. void handleProcessStopped() noexcept
  1081. {
  1082. const bool wasActive = pData->active;
  1083. pData->active = false;
  1084. if (wasActive)
  1085. {
  1086. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1087. if (pData->engine->isOscControlRegistered())
  1088. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  1089. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  1090. #endif
  1091. }
  1092. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1093. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1094. }
  1095. void resizeAudioPool(const uint32_t bufferSize)
  1096. {
  1097. fShmAudioPool.resize(bufferSize, static_cast<uint32_t>(fInfo.aIns+fInfo.aOuts), 0);
  1098. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1099. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1100. fShmRtClientControl.commitWrite();
  1101. waitForClient("resize-pool", 5000);
  1102. }
  1103. void waitForClient(const char* const action, const uint msecs)
  1104. {
  1105. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1106. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1107. if (fShmRtClientControl.waitForClient(msecs))
  1108. return;
  1109. fTimedOut = true;
  1110. carla_stderr("waitForClient(%s) timed out", action);
  1111. }
  1112. bool restartBridgeThread()
  1113. {
  1114. fInitiated = false;
  1115. fInitError = false;
  1116. fTimedError = false;
  1117. // reset memory
  1118. fProcCanceled = false;
  1119. fShmRtClientControl.data->procFlags = 0;
  1120. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1121. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1122. fShmRtClientControl.clearData();
  1123. fShmNonRtClientControl.clearData();
  1124. fShmNonRtServerControl.clearData();
  1125. // initial values
  1126. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientVersion);
  1127. fShmNonRtClientControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION);
  1128. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1129. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1130. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1131. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1132. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1133. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1134. fShmNonRtClientControl.commitWrite();
  1135. if (fShmAudioPool.dataSize != 0)
  1136. {
  1137. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1138. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1139. fShmRtClientControl.commitWrite();
  1140. }
  1141. else
  1142. {
  1143. // testing dummy message
  1144. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1145. fShmRtClientControl.commitWrite();
  1146. }
  1147. fBridgeThread.startThread();
  1148. fLastPingTime = Time::currentTimeMillis();
  1149. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1150. static bool sFirstInit = true;
  1151. int64_t timeoutEnd = 5000;
  1152. if (sFirstInit)
  1153. timeoutEnd *= 2;
  1154. sFirstInit = false;
  1155. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1156. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1157. {
  1158. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1159. if (needsEngineIdle)
  1160. pData->engine->idle();
  1161. idle();
  1162. if (fInitiated)
  1163. break;
  1164. if (pData->engine->isAboutToClose())
  1165. break;
  1166. carla_msleep(20);
  1167. }
  1168. fLastPingTime = -1;
  1169. if (fInitError || ! fInitiated)
  1170. {
  1171. fBridgeThread.stopThread(6000);
  1172. if (! fInitError)
  1173. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1174. "(or the plugin crashed on initialization?)");
  1175. return false;
  1176. }
  1177. return true;
  1178. }
  1179. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1180. };
  1181. CARLA_BACKEND_END_NAMESPACE
  1182. #endif // CARLA_OS_LINUX
  1183. // -------------------------------------------------------------------------------------------------------------------
  1184. CARLA_BACKEND_START_NAMESPACE
  1185. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1186. {
  1187. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label);
  1188. #ifdef CARLA_OS_LINUX
  1189. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1190. if (! plugin->init(init.filename, init.name, init.label))
  1191. {
  1192. delete plugin;
  1193. return nullptr;
  1194. }
  1195. return plugin;
  1196. #else
  1197. init.engine->setLastError("JACK Application support not available");
  1198. return nullptr;
  1199. #endif
  1200. }
  1201. CARLA_BACKEND_END_NAMESPACE
  1202. // -------------------------------------------------------------------------------------------------------------------