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 water::ChildProcess;
  31. using water::File;
  32. using water::String;
  33. using water::StringArray;
  34. using water::Time;
  35. CARLA_BACKEND_START_NAMESPACE
  36. // -------------------------------------------------------------------------------------------------------------------
  37. // Fallback data
  38. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  39. // -------------------------------------------------------------------------------------------------------------------
  40. class CarlaPluginJackThread : public CarlaThread
  41. {
  42. public:
  43. CarlaPluginJackThread(CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  44. : CarlaThread("CarlaPluginJackThread"),
  45. kEngine(engine),
  46. kPlugin(plugin),
  47. fShmIds(),
  48. fNumPorts(),
  49. fProcess() {}
  50. void setData(const char* const shmIds, const char* const numPorts) noexcept
  51. {
  52. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  53. CARLA_SAFE_ASSERT_RETURN(numPorts != nullptr && numPorts[0] != '\0',);
  54. CARLA_SAFE_ASSERT(! isThreadRunning());
  55. fShmIds = shmIds;
  56. fNumPorts = numPorts;
  57. }
  58. uintptr_t getProcessID() const noexcept
  59. {
  60. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  61. return (uintptr_t)fProcess->getPID();
  62. }
  63. protected:
  64. void run()
  65. {
  66. if (fProcess == nullptr)
  67. {
  68. fProcess = new ChildProcess();
  69. }
  70. else if (fProcess->isRunning())
  71. {
  72. carla_stderr("CarlaPluginJackThread::run() - already running");
  73. }
  74. String name(kPlugin->getName());
  75. String filename(kPlugin->getFilename());
  76. if (name.isEmpty())
  77. name = "(none)";
  78. CARLA_SAFE_ASSERT_RETURN(filename.isNotEmpty(),);
  79. StringArray arguments;
  80. // binary
  81. arguments.addTokens(filename, true);
  82. bool started;
  83. {
  84. const EngineOptions& options(kEngine->getOptions());
  85. char winIdStr[STR_MAX+1];
  86. std::snprintf(winIdStr, STR_MAX, P_UINTPTR, options.frontendWinId);
  87. winIdStr[STR_MAX] = '\0';
  88. CarlaString libjackdir(options.binaryDir);
  89. libjackdir += "/jack";
  90. CarlaString ldpreload;
  91. #ifdef HAVE_X11
  92. ldpreload = (CarlaString(options.binaryDir)
  93. + "/libcarla_interposer-jack-x11.so");
  94. #endif
  95. const ScopedEngineEnvironmentLocker _seel(kEngine);
  96. const ScopedEnvVar sev2("LD_LIBRARY_PATH", libjackdir.buffer());
  97. const ScopedEnvVar sev1("LD_PRELOAD", ldpreload.isNotEmpty() ? ldpreload.buffer() : nullptr);
  98. if (kPlugin->getHints() & PLUGIN_HAS_CUSTOM_UI)
  99. carla_setenv("CARLA_FRONTEND_WIN_ID", winIdStr);
  100. else
  101. carla_unsetenv("CARLA_FRONTEND_WIN_ID");
  102. carla_setenv("CARLA_LIBJACK_SETUP", fNumPorts.buffer());
  103. carla_setenv("CARLA_SHM_IDS", fShmIds.buffer());
  104. started = fProcess->start(arguments);
  105. }
  106. if (! started)
  107. {
  108. carla_stdout("failed!");
  109. fProcess = nullptr;
  110. return;
  111. }
  112. for (; fProcess->isRunning() && ! shouldThreadExit();)
  113. carla_msleep(50);
  114. // we only get here if bridge crashed or thread asked to exit
  115. if (fProcess->isRunning() && shouldThreadExit())
  116. {
  117. fProcess->waitForProcessToFinish(2000);
  118. if (fProcess->isRunning())
  119. {
  120. carla_stdout("CarlaPluginJackThread::run() - application refused to close, force kill now");
  121. fProcess->kill();
  122. }
  123. }
  124. else
  125. {
  126. // forced quit, may have crashed
  127. if (fProcess->getExitCode() != 0 /*|| fProcess->exitStatus() == QProcess::CrashExit*/)
  128. {
  129. carla_stderr("CarlaPluginJackThread::run() - application crashed");
  130. CarlaString errorString("Plugin '" + CarlaString(kPlugin->getName()) + "' has crashed!\n"
  131. "Saving now will lose its current settings.\n"
  132. "Please remove this plugin, and not rely on it from this point.");
  133. kEngine->callback(CarlaBackend::ENGINE_CALLBACK_ERROR, kPlugin->getId(), 0, 0, 0.0f, errorString);
  134. }
  135. }
  136. fProcess = nullptr;
  137. }
  138. private:
  139. CarlaEngine* const kEngine;
  140. CarlaPlugin* const kPlugin;
  141. CarlaString fShmIds;
  142. CarlaString fNumPorts;
  143. ScopedPointer<ChildProcess> fProcess;
  144. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJackThread)
  145. };
  146. // -------------------------------------------------------------------------------------------------------------------
  147. class CarlaPluginJack : public CarlaPlugin
  148. {
  149. public:
  150. CarlaPluginJack(CarlaEngine* const engine, const uint id)
  151. : CarlaPlugin(engine, id),
  152. fInitiated(false),
  153. fInitError(false),
  154. fTimedOut(false),
  155. fTimedError(false),
  156. fProcCanceled(false),
  157. fProcWaitTime(0),
  158. fLastPingTime(-1),
  159. fBridgeThread(engine, this),
  160. fShmAudioPool(),
  161. fShmRtClientControl(),
  162. fShmNonRtClientControl(),
  163. fShmNonRtServerControl(),
  164. fInfo()
  165. {
  166. carla_debug("CarlaPluginJack::CarlaPluginJack(%p, %i)", engine, id);
  167. pData->hints |= PLUGIN_IS_BRIDGE;
  168. }
  169. ~CarlaPluginJack() override
  170. {
  171. carla_debug("CarlaPluginJack::~CarlaPluginJack()");
  172. // close UI
  173. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  174. pData->transientTryCounter = 0;
  175. pData->singleMutex.lock();
  176. pData->masterMutex.lock();
  177. if (pData->client != nullptr && pData->client->isActive())
  178. pData->client->deactivate();
  179. if (pData->active)
  180. {
  181. deactivate();
  182. pData->active = false;
  183. }
  184. if (fBridgeThread.isThreadRunning())
  185. {
  186. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  187. fShmRtClientControl.commitWrite();
  188. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  189. fShmNonRtClientControl.commitWrite();
  190. if (! fTimedOut)
  191. waitForClient("stopping", 3000);
  192. }
  193. fBridgeThread.stopThread(3000);
  194. fShmNonRtServerControl.clear();
  195. fShmNonRtClientControl.clear();
  196. fShmRtClientControl.clear();
  197. fShmAudioPool.clear();
  198. clearBuffers();
  199. fInfo.chunk.clear();
  200. }
  201. // -------------------------------------------------------------------
  202. // Information (base)
  203. PluginType getType() const noexcept override
  204. {
  205. return PLUGIN_JACK;
  206. }
  207. PluginCategory getCategory() const noexcept override
  208. {
  209. return PLUGIN_CATEGORY_NONE;
  210. }
  211. // -------------------------------------------------------------------
  212. // Information (count)
  213. uint32_t getMidiInCount() const noexcept override
  214. {
  215. return fInfo.mIns;
  216. }
  217. uint32_t getMidiOutCount() const noexcept override
  218. {
  219. return fInfo.mOuts;
  220. }
  221. // -------------------------------------------------------------------
  222. // Information (current data)
  223. // -------------------------------------------------------------------
  224. // Information (per-plugin data)
  225. uint getOptionsAvailable() const noexcept override
  226. {
  227. return fInfo.optionsAvailable;
  228. }
  229. void getLabel(char* const strBuf) const noexcept override
  230. {
  231. std::strncpy(strBuf, fInfo.setupLabel, STR_MAX);
  232. }
  233. void getMaker(char* const strBuf) const noexcept override
  234. {
  235. nullStrBuf(strBuf);
  236. }
  237. void getCopyright(char* const strBuf) const noexcept override
  238. {
  239. nullStrBuf(strBuf);
  240. }
  241. void getRealName(char* const strBuf) const noexcept override
  242. {
  243. // FIXME
  244. std::strncpy(strBuf, "Carla's libjack", STR_MAX);
  245. }
  246. // -------------------------------------------------------------------
  247. // Set data (state)
  248. // -------------------------------------------------------------------
  249. // Set data (internal stuff)
  250. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  251. {
  252. {
  253. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  254. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  255. fShmNonRtClientControl.writeUInt(option);
  256. fShmNonRtClientControl.writeBool(yesNo);
  257. fShmNonRtClientControl.commitWrite();
  258. }
  259. CarlaPlugin::setOption(option, yesNo, sendCallback);
  260. }
  261. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  262. {
  263. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  264. {
  265. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  266. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  267. fShmNonRtClientControl.writeShort(channel);
  268. fShmNonRtClientControl.commitWrite();
  269. }
  270. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  271. }
  272. // -------------------------------------------------------------------
  273. // Set data (plugin-specific stuff)
  274. // -------------------------------------------------------------------
  275. // Set ui stuff
  276. void showCustomUI(const bool yesNo) override
  277. {
  278. if (yesNo && ! fBridgeThread.isThreadRunning()) {
  279. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  280. }
  281. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  282. fShmNonRtClientControl.writeOpcode(yesNo ? kPluginBridgeNonRtClientShowUI : kPluginBridgeNonRtClientHideUI);
  283. fShmNonRtClientControl.commitWrite();
  284. }
  285. void idle() override
  286. {
  287. if (fBridgeThread.isThreadRunning())
  288. {
  289. if (fInitiated && fTimedOut && pData->active)
  290. setActive(false, true, true);
  291. {
  292. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  293. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  294. fShmNonRtClientControl.commitWrite();
  295. }
  296. try {
  297. handleNonRtData();
  298. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  299. if (fLastPingTime > 0 && Time::currentTimeMillis() > fLastPingTime + 30000)
  300. {
  301. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  302. // TODO
  303. //threadShouldExit();
  304. //callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  305. }
  306. }
  307. else if (fInitiated)
  308. {
  309. fTimedOut = true;
  310. fTimedError = true;
  311. fInitiated = false;
  312. handleProcessStopped();
  313. }
  314. else if (fProcCanceled)
  315. {
  316. handleProcessStopped();
  317. fProcCanceled = false;
  318. }
  319. CarlaPlugin::idle();
  320. }
  321. // -------------------------------------------------------------------
  322. // Plugin state
  323. void reload() override
  324. {
  325. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  326. carla_debug("CarlaPluginJack::reload() - start");
  327. const EngineProcessMode processMode(pData->engine->getProccessMode());
  328. // Safely disable plugin for reload
  329. const ScopedDisabler sd(this);
  330. // cleanup of previous data
  331. pData->audioIn.clear();
  332. pData->audioOut.clear();
  333. pData->event.clear();
  334. bool needsCtrlIn, needsCtrlOut;
  335. needsCtrlIn = needsCtrlOut = false;
  336. if (fInfo.aIns > 0)
  337. {
  338. pData->audioIn.createNew(fInfo.aIns);
  339. }
  340. if (fInfo.aOuts > 0)
  341. {
  342. pData->audioOut.createNew(fInfo.aOuts);
  343. needsCtrlIn = true;
  344. }
  345. if (fInfo.mIns > 0)
  346. needsCtrlIn = true;
  347. if (fInfo.mOuts > 0)
  348. needsCtrlOut = true;
  349. const uint portNameSize(pData->engine->getMaxPortNameSize());
  350. CarlaString portName;
  351. // Audio Ins
  352. for (uint8_t j=0; j < fInfo.aIns; ++j)
  353. {
  354. portName.clear();
  355. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  356. {
  357. portName = pData->name;
  358. portName += ":";
  359. }
  360. if (fInfo.aIns > 1)
  361. {
  362. portName += "audio_in_";
  363. portName += CarlaString(j+1);
  364. }
  365. else
  366. {
  367. portName += "audio_in";
  368. }
  369. portName.truncate(portNameSize);
  370. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  371. pData->audioIn.ports[j].rindex = j;
  372. }
  373. // Audio Outs
  374. for (uint8_t j=0; j < fInfo.aOuts; ++j)
  375. {
  376. portName.clear();
  377. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  378. {
  379. portName = pData->name;
  380. portName += ":";
  381. }
  382. if (fInfo.aOuts > 1)
  383. {
  384. portName += "audio_out_";
  385. portName += CarlaString(j+1);
  386. }
  387. else
  388. {
  389. portName += "audio_out";
  390. }
  391. portName.truncate(portNameSize);
  392. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  393. pData->audioOut.ports[j].rindex = j;
  394. }
  395. if (needsCtrlIn)
  396. {
  397. portName.clear();
  398. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  399. {
  400. portName = pData->name;
  401. portName += ":";
  402. }
  403. portName += "event-in";
  404. portName.truncate(portNameSize);
  405. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  406. }
  407. if (needsCtrlOut)
  408. {
  409. portName.clear();
  410. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  411. {
  412. portName = pData->name;
  413. portName += ":";
  414. }
  415. portName += "event-out";
  416. portName.truncate(portNameSize);
  417. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  418. }
  419. // extra plugin hints
  420. pData->extraHints = 0x0;
  421. if (fInfo.mIns > 0)
  422. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  423. if (fInfo.mOuts > 0)
  424. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  425. if (fInfo.aIns <= 2 && fInfo.aOuts <= 2 && (fInfo.aIns == fInfo.aOuts || fInfo.aIns == 0 || fInfo.aOuts == 0))
  426. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  427. bufferSizeChanged(pData->engine->getBufferSize());
  428. reloadPrograms(true);
  429. carla_debug("CarlaPluginJack::reload() - end");
  430. }
  431. // -------------------------------------------------------------------
  432. // Plugin processing
  433. void activate() noexcept override
  434. {
  435. if (! fBridgeThread.isThreadRunning())
  436. {
  437. CARLA_SAFE_ASSERT_RETURN(restartBridgeThread(),);
  438. }
  439. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  440. {
  441. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  442. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  443. fShmNonRtClientControl.commitWrite();
  444. }
  445. fTimedOut = false;
  446. try {
  447. waitForClient("activate", 2000);
  448. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  449. }
  450. void deactivate() noexcept override
  451. {
  452. if (! fBridgeThread.isThreadRunning())
  453. return;
  454. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  455. {
  456. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  457. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  458. fShmNonRtClientControl.commitWrite();
  459. }
  460. fTimedOut = false;
  461. try {
  462. waitForClient("deactivate", 2000);
  463. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  464. }
  465. void process(const float** const audioIn, float** const audioOut, const float**, float**, const uint32_t frames) override
  466. {
  467. // --------------------------------------------------------------------------------------------------------
  468. // Check if active
  469. if (fProcCanceled || fTimedOut || fTimedError || ! pData->active)
  470. {
  471. // disable any output sound
  472. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  473. carla_zeroFloats(audioOut[i], frames);
  474. return;
  475. }
  476. // --------------------------------------------------------------------------------------------------------
  477. // Check if needs reset
  478. if (pData->needsReset)
  479. {
  480. // TODO
  481. pData->needsReset = false;
  482. }
  483. // --------------------------------------------------------------------------------------------------------
  484. // Event Input
  485. if (pData->event.portIn != nullptr)
  486. {
  487. // ----------------------------------------------------------------------------------------------------
  488. // MIDI Input (External)
  489. if (pData->extNotes.mutex.tryLock())
  490. {
  491. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  492. {
  493. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  494. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  495. uint8_t data1, data2, data3;
  496. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  497. data2 = note.note;
  498. data3 = note.velo;
  499. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  500. fShmRtClientControl.writeUInt(0); // time
  501. fShmRtClientControl.writeByte(0); // port
  502. fShmRtClientControl.writeByte(3); // size
  503. fShmRtClientControl.writeByte(data1);
  504. fShmRtClientControl.writeByte(data2);
  505. fShmRtClientControl.writeByte(data3);
  506. fShmRtClientControl.commitWrite();
  507. }
  508. pData->extNotes.data.clear();
  509. pData->extNotes.mutex.unlock();
  510. } // End of MIDI Input (External)
  511. // ----------------------------------------------------------------------------------------------------
  512. // Event Input (System)
  513. #ifndef BUILD_BRIDGE
  514. bool allNotesOffSent = false;
  515. #endif
  516. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  517. {
  518. const EngineEvent& event(pData->event.portIn->getEvent(i));
  519. // Control change
  520. switch (event.type)
  521. {
  522. case kEngineEventTypeNull:
  523. break;
  524. case kEngineEventTypeControl: {
  525. const EngineControlEvent& ctrlEvent = event.ctrl;
  526. switch (ctrlEvent.type)
  527. {
  528. case kEngineControlEventTypeNull:
  529. break;
  530. case kEngineControlEventTypeParameter:
  531. #ifndef BUILD_BRIDGE
  532. // Control backend stuff
  533. if (event.channel == pData->ctrlChannel)
  534. {
  535. float value;
  536. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  537. {
  538. value = ctrlEvent.value;
  539. setDryWet(value, false, false);
  540. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  541. }
  542. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  543. {
  544. value = ctrlEvent.value*127.0f/100.0f;
  545. setVolume(value, false, false);
  546. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  547. }
  548. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  549. {
  550. float left, right;
  551. value = ctrlEvent.value/0.5f - 1.0f;
  552. if (value < 0.0f)
  553. {
  554. left = -1.0f;
  555. right = (value*2.0f)+1.0f;
  556. }
  557. else if (value > 0.0f)
  558. {
  559. left = (value*2.0f)-1.0f;
  560. right = 1.0f;
  561. }
  562. else
  563. {
  564. left = -1.0f;
  565. right = 1.0f;
  566. }
  567. setBalanceLeft(left, false, false);
  568. setBalanceRight(right, false, false);
  569. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  570. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  571. }
  572. }
  573. #endif
  574. break;
  575. case kEngineControlEventTypeMidiBank:
  576. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  577. {
  578. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  579. fShmRtClientControl.writeUInt(event.time);
  580. fShmRtClientControl.writeByte(event.channel);
  581. fShmRtClientControl.writeUShort(event.ctrl.param);
  582. fShmRtClientControl.commitWrite();
  583. }
  584. break;
  585. case kEngineControlEventTypeMidiProgram:
  586. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  587. {
  588. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  589. fShmRtClientControl.writeUInt(event.time);
  590. fShmRtClientControl.writeByte(event.channel);
  591. fShmRtClientControl.writeUShort(event.ctrl.param);
  592. fShmRtClientControl.commitWrite();
  593. }
  594. break;
  595. case kEngineControlEventTypeAllSoundOff:
  596. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  597. {
  598. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  599. fShmRtClientControl.writeUInt(event.time);
  600. fShmRtClientControl.writeByte(event.channel);
  601. fShmRtClientControl.commitWrite();
  602. }
  603. break;
  604. case kEngineControlEventTypeAllNotesOff:
  605. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  606. {
  607. #ifndef BUILD_BRIDGE
  608. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  609. {
  610. allNotesOffSent = true;
  611. sendMidiAllNotesOffToCallback();
  612. }
  613. #endif
  614. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  615. fShmRtClientControl.writeUInt(event.time);
  616. fShmRtClientControl.writeByte(event.channel);
  617. fShmRtClientControl.commitWrite();
  618. }
  619. break;
  620. } // switch (ctrlEvent.type)
  621. break;
  622. } // case kEngineEventTypeControl
  623. case kEngineEventTypeMidi: {
  624. const EngineMidiEvent& midiEvent(event.midi);
  625. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  626. continue;
  627. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  628. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  629. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  630. continue;
  631. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  632. continue;
  633. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  634. continue;
  635. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  636. continue;
  637. // Fix bad note-off
  638. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  639. status = MIDI_STATUS_NOTE_OFF;
  640. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  641. fShmRtClientControl.writeUInt(event.time);
  642. fShmRtClientControl.writeByte(midiEvent.port);
  643. fShmRtClientControl.writeByte(midiEvent.size);
  644. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  645. for (uint8_t j=1; j < midiEvent.size; ++j)
  646. fShmRtClientControl.writeByte(midiData[j]);
  647. fShmRtClientControl.commitWrite();
  648. if (status == MIDI_STATUS_NOTE_ON)
  649. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  650. else if (status == MIDI_STATUS_NOTE_OFF)
  651. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  652. } break;
  653. }
  654. }
  655. pData->postRtEvents.trySplice();
  656. } // End of Event Input
  657. if (! processSingle(audioIn, audioOut, frames))
  658. return;
  659. // --------------------------------------------------------------------------------------------------------
  660. // MIDI Output
  661. if (pData->event.portOut != nullptr)
  662. {
  663. uint32_t time;
  664. uint8_t port, size;
  665. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  666. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize-kBridgeBaseMidiOutHeaderSize;)
  667. {
  668. // get time
  669. time = *(const uint32_t*)midiData;
  670. midiData += 4;
  671. // get port and size
  672. port = *midiData++;
  673. size = *midiData++;
  674. if (size == 0)
  675. break;
  676. // store midi data advancing as needed
  677. uint8_t data[size];
  678. for (uint8_t j=0; j<size; ++j)
  679. data[j] = *midiData++;
  680. pData->event.portOut->writeMidiEvent(time, size, data);
  681. read += kBridgeBaseMidiOutHeaderSize + size;
  682. }
  683. // TODO
  684. (void)port;
  685. } // End of Control and MIDI Output
  686. }
  687. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  688. {
  689. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  690. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  691. if (pData->audioIn.count > 0)
  692. {
  693. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  694. }
  695. if (pData->audioOut.count > 0)
  696. {
  697. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  698. }
  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. carla_zeroFloats(audioOut[i], frames);
  709. return false;
  710. }
  711. // --------------------------------------------------------------------------------------------------------
  712. // Reset audio buffers
  713. for (uint32_t i=0; i < fInfo.aIns; ++i)
  714. carla_copyFloats(fShmAudioPool.data + (i * frames), audioIn[i], frames);
  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. carla_copyFloats(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), frames);
  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. carla_copyFloats(oldBufLeft, audioOut[i], frames);
  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 = static_cast<uint8_t>(label[0] - '0');
  971. fInfo.aOuts = static_cast<uint8_t>(label[1] - '0');
  972. fInfo.mIns = static_cast<uint8_t>(carla_minPositive(label[2] - '0', 1));
  973. fInfo.mOuts = static_cast<uint8_t>(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. uint8_t aIns, aOuts;
  1062. uint8_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, static_cast<uint32_t>(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. // -------------------------------------------------------------------------------------------------------------------