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.

1520 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. #ifdef BUILD_BRIDGE
  18. # error This file should not be used under bridge mode
  19. #endif
  20. #include "CarlaPluginInternal.hpp"
  21. #include "CarlaEngine.hpp"
  22. #ifdef CARLA_OS_LINUX
  23. #include "CarlaBackendUtils.hpp"
  24. #include "CarlaBridgeUtils.hpp"
  25. #include "CarlaEngineUtils.hpp"
  26. #include "CarlaMathUtils.hpp"
  27. #include "CarlaPipeUtils.hpp"
  28. #include "CarlaShmUtils.hpp"
  29. #include "CarlaThread.hpp"
  30. #include "jackbridge/JackBridge.hpp"
  31. #include <ctime>
  32. // -------------------------------------------------------------------------------------------------------------------
  33. using juce::ChildProcess;
  34. using juce::File;
  35. using juce::ScopedPointer;
  36. using juce::String;
  37. using juce::StringArray;
  38. using juce::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 (uint32_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 (uint32_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. FloatVectorOperations::clear(audioOut[i], static_cast<int>(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. bool allNotesOffSent = false;
  518. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  519. {
  520. const EngineEvent& event(pData->event.portIn->getEvent(i));
  521. // Control change
  522. switch (event.type)
  523. {
  524. case kEngineEventTypeNull:
  525. break;
  526. case kEngineEventTypeControl: {
  527. const EngineControlEvent& ctrlEvent = event.ctrl;
  528. switch (ctrlEvent.type)
  529. {
  530. case kEngineControlEventTypeNull:
  531. break;
  532. case kEngineControlEventTypeParameter:
  533. // Control backend stuff
  534. if (event.channel == pData->ctrlChannel)
  535. {
  536. float value;
  537. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  538. {
  539. value = ctrlEvent.value;
  540. setDryWet(value, false, false);
  541. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  542. }
  543. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  544. {
  545. value = ctrlEvent.value*127.0f/100.0f;
  546. setVolume(value, false, false);
  547. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  548. }
  549. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  550. {
  551. float left, right;
  552. value = ctrlEvent.value/0.5f - 1.0f;
  553. if (value < 0.0f)
  554. {
  555. left = -1.0f;
  556. right = (value*2.0f)+1.0f;
  557. }
  558. else if (value > 0.0f)
  559. {
  560. left = (value*2.0f)-1.0f;
  561. right = 1.0f;
  562. }
  563. else
  564. {
  565. left = -1.0f;
  566. right = 1.0f;
  567. }
  568. setBalanceLeft(left, false, false);
  569. setBalanceRight(right, false, false);
  570. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  571. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  572. }
  573. }
  574. 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. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  608. {
  609. allNotesOffSent = true;
  610. sendMidiAllNotesOffToCallback();
  611. }
  612. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  613. fShmRtClientControl.writeUInt(event.time);
  614. fShmRtClientControl.writeByte(event.channel);
  615. fShmRtClientControl.commitWrite();
  616. }
  617. break;
  618. } // switch (ctrlEvent.type)
  619. break;
  620. } // case kEngineEventTypeControl
  621. case kEngineEventTypeMidi: {
  622. const EngineMidiEvent& midiEvent(event.midi);
  623. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  624. continue;
  625. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  626. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  627. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  628. continue;
  629. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  630. continue;
  631. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  632. continue;
  633. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  634. continue;
  635. // Fix bad note-off
  636. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  637. status = MIDI_STATUS_NOTE_OFF;
  638. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  639. fShmRtClientControl.writeUInt(event.time);
  640. fShmRtClientControl.writeByte(midiEvent.port);
  641. fShmRtClientControl.writeByte(midiEvent.size);
  642. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  643. for (uint8_t j=1; j < midiEvent.size; ++j)
  644. fShmRtClientControl.writeByte(midiData[j]);
  645. fShmRtClientControl.commitWrite();
  646. if (status == MIDI_STATUS_NOTE_ON)
  647. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  648. else if (status == MIDI_STATUS_NOTE_OFF)
  649. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  650. } break;
  651. }
  652. }
  653. pData->postRtEvents.trySplice();
  654. } // End of Event Input
  655. if (! processSingle(audioIn, audioOut, frames))
  656. return;
  657. // --------------------------------------------------------------------------------------------------------
  658. // MIDI Output
  659. if (pData->event.portOut != nullptr)
  660. {
  661. uint32_t time;
  662. uint8_t port, size;
  663. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  664. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize;)
  665. {
  666. // get time
  667. time = *(const uint32_t*)midiData;
  668. midiData += 4;
  669. // get port and size
  670. port = *midiData++;
  671. size = *midiData++;
  672. if (size == 0)
  673. break;
  674. // store midi data advancing as needed
  675. uint8_t data[size];
  676. for (uint8_t j=0; j<size; ++j)
  677. data[j] = *midiData++;
  678. pData->event.portOut->writeMidiEvent(time, size, data);
  679. read += 6U /* time, port and size */ + size;
  680. }
  681. } // End of Control and MIDI Output
  682. }
  683. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  684. {
  685. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  686. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  687. if (pData->audioIn.count > 0)
  688. {
  689. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  690. }
  691. if (pData->audioOut.count > 0)
  692. {
  693. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  694. }
  695. const int iframes(static_cast<int>(frames));
  696. // --------------------------------------------------------------------------------------------------------
  697. // Try lock, silence otherwise
  698. if (pData->engine->isOffline())
  699. {
  700. pData->singleMutex.lock();
  701. }
  702. else if (! pData->singleMutex.tryLock())
  703. {
  704. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  705. FloatVectorOperations::clear(audioOut[i], iframes);
  706. return false;
  707. }
  708. // --------------------------------------------------------------------------------------------------------
  709. // Reset audio buffers
  710. for (uint32_t i=0; i < fInfo.aIns; ++i)
  711. FloatVectorOperations::copy(fShmAudioPool.data + (i * frames), audioIn[i], iframes);
  712. // --------------------------------------------------------------------------------------------------------
  713. // TimeInfo
  714. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  715. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  716. bridgeTimeInfo.playing = timeInfo.playing;
  717. bridgeTimeInfo.frame = timeInfo.frame;
  718. bridgeTimeInfo.usecs = timeInfo.usecs;
  719. bridgeTimeInfo.valid = timeInfo.valid;
  720. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  721. {
  722. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  723. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  724. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  725. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  726. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  727. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  728. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  729. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  730. }
  731. // --------------------------------------------------------------------------------------------------------
  732. // Run plugin
  733. {
  734. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  735. fShmRtClientControl.commitWrite();
  736. }
  737. waitForClient("process", fProcWaitTime);
  738. if (fTimedOut)
  739. {
  740. pData->singleMutex.unlock();
  741. return false;
  742. }
  743. if (fShmRtClientControl.data->procFlags)
  744. {
  745. fInitiated = false;
  746. fProcCanceled = true;
  747. }
  748. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  749. FloatVectorOperations::copy(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), iframes);
  750. // --------------------------------------------------------------------------------------------------------
  751. // Post-processing (dry/wet, volume and balance)
  752. {
  753. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  754. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  755. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  756. const bool isMono = (pData->audioIn.count == 1);
  757. bool isPair;
  758. float bufValue, oldBufLeft[doBalance ? frames : 1];
  759. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  760. {
  761. // Dry/Wet
  762. if (doDryWet)
  763. {
  764. const uint32_t c = isMono ? 0 : i;
  765. for (uint32_t k=0; k < frames; ++k)
  766. {
  767. bufValue = audioIn[c][k];
  768. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  769. }
  770. }
  771. // Balance
  772. if (doBalance)
  773. {
  774. isPair = (i % 2 == 0);
  775. if (isPair)
  776. {
  777. CARLA_ASSERT(i+1 < pData->audioOut.count);
  778. FloatVectorOperations::copy(oldBufLeft, audioOut[i], iframes);
  779. }
  780. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  781. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  782. for (uint32_t k=0; k < frames; ++k)
  783. {
  784. if (isPair)
  785. {
  786. // left
  787. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  788. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  789. }
  790. else
  791. {
  792. // right
  793. audioOut[i][k] = audioOut[i][k] * balRangeR;
  794. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  795. }
  796. }
  797. }
  798. // Volume (and buffer copy)
  799. if (doVolume)
  800. {
  801. for (uint32_t k=0; k < frames; ++k)
  802. audioOut[i][k] *= pData->postProc.volume;
  803. }
  804. }
  805. } // End of Post-processing
  806. // --------------------------------------------------------------------------------------------------------
  807. pData->singleMutex.unlock();
  808. return true;
  809. }
  810. void bufferSizeChanged(const uint32_t newBufferSize) override
  811. {
  812. resizeAudioPool(newBufferSize);
  813. {
  814. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  815. fShmRtClientControl.writeUInt(newBufferSize);
  816. fShmRtClientControl.commitWrite();
  817. }
  818. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  819. fProcWaitTime = 1000;
  820. waitForClient("buffersize", 1000);
  821. }
  822. void sampleRateChanged(const double newSampleRate) override
  823. {
  824. {
  825. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  826. fShmRtClientControl.writeDouble(newSampleRate);
  827. fShmRtClientControl.commitWrite();
  828. }
  829. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  830. fProcWaitTime = 1000;
  831. waitForClient("samplerate", 1000);
  832. }
  833. void offlineModeChanged(const bool isOffline) override
  834. {
  835. {
  836. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  837. fShmRtClientControl.writeBool(isOffline);
  838. fShmRtClientControl.commitWrite();
  839. }
  840. waitForClient("offline", 1000);
  841. }
  842. // -------------------------------------------------------------------
  843. // Post-poned UI Stuff
  844. // -------------------------------------------------------------------
  845. void handleNonRtData()
  846. {
  847. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  848. {
  849. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  850. //#ifdef DEBUG
  851. if (opcode != kPluginBridgeNonRtServerPong)
  852. {
  853. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  854. }
  855. //#endif
  856. if (opcode != kPluginBridgeNonRtServerNull && fLastPingTime > 0)
  857. fLastPingTime = Time::currentTimeMillis();
  858. switch (opcode)
  859. {
  860. case kPluginBridgeNonRtServerNull:
  861. case kPluginBridgeNonRtServerPong:
  862. case kPluginBridgeNonRtServerPluginInfo1:
  863. case kPluginBridgeNonRtServerPluginInfo2:
  864. case kPluginBridgeNonRtServerAudioCount:
  865. case kPluginBridgeNonRtServerMidiCount:
  866. case kPluginBridgeNonRtServerCvCount:
  867. case kPluginBridgeNonRtServerParameterCount:
  868. case kPluginBridgeNonRtServerProgramCount:
  869. case kPluginBridgeNonRtServerMidiProgramCount:
  870. case kPluginBridgeNonRtServerPortName:
  871. case kPluginBridgeNonRtServerParameterData1:
  872. case kPluginBridgeNonRtServerParameterData2:
  873. case kPluginBridgeNonRtServerParameterRanges:
  874. case kPluginBridgeNonRtServerParameterValue:
  875. case kPluginBridgeNonRtServerParameterValue2:
  876. case kPluginBridgeNonRtServerDefaultValue:
  877. case kPluginBridgeNonRtServerCurrentProgram:
  878. case kPluginBridgeNonRtServerCurrentMidiProgram:
  879. case kPluginBridgeNonRtServerProgramName:
  880. case kPluginBridgeNonRtServerMidiProgramData:
  881. case kPluginBridgeNonRtServerSetCustomData:
  882. break;
  883. case kPluginBridgeNonRtServerSetChunkDataFile: {
  884. // uint/size, str[] (filename)
  885. const uint32_t chunkFilePathSize(fShmNonRtServerControl.readUInt());
  886. char chunkFilePath[chunkFilePathSize];
  887. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  888. } break;
  889. case kPluginBridgeNonRtServerSetLatency:
  890. break;
  891. case kPluginBridgeNonRtServerReady:
  892. fInitiated = true;
  893. break;
  894. case kPluginBridgeNonRtServerSaved:
  895. break;
  896. case kPluginBridgeNonRtServerUiClosed:
  897. carla_stdout("got kPluginBridgeNonRtServerUiClosed, bridge closed cleanly?");
  898. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  899. //fBridgeThread.signalThreadShouldExit();
  900. //handleProcessStopped();
  901. //fBridgeThread.stopThread(5000);
  902. break;
  903. case kPluginBridgeNonRtServerError: {
  904. // error
  905. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  906. char error[errorSize+1];
  907. carla_zeroChars(error, errorSize+1);
  908. fShmNonRtServerControl.readCustomData(error, errorSize);
  909. if (fInitiated)
  910. {
  911. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  912. // just in case
  913. pData->engine->setLastError(error);
  914. fInitError = true;
  915. }
  916. else
  917. {
  918. pData->engine->setLastError(error);
  919. fInitError = true;
  920. fInitiated = true;
  921. }
  922. } break;
  923. }
  924. }
  925. }
  926. // -------------------------------------------------------------------
  927. uintptr_t getUiBridgeProcessId() const noexcept override
  928. {
  929. return fBridgeThread.getProcessID();
  930. }
  931. // -------------------------------------------------------------------
  932. bool init(const char* const filename, const char* const name, const char* const label)
  933. {
  934. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  935. // ---------------------------------------------------------------
  936. // first checks
  937. if (pData->client != nullptr)
  938. {
  939. pData->engine->setLastError("Plugin client is already registered");
  940. return false;
  941. }
  942. if (filename == nullptr || filename[0] == '\0')
  943. {
  944. pData->engine->setLastError("null filename");
  945. return false;
  946. }
  947. if (label == nullptr || label[0] == '\0')
  948. {
  949. pData->engine->setLastError("null label");
  950. return false;
  951. }
  952. // ---------------------------------------------------------------
  953. // check setup
  954. if (std::strlen(label) != 5)
  955. {
  956. pData->engine->setLastError("invalid application setup received");
  957. return false;
  958. }
  959. for (int i=4; --i >= 0;) {
  960. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  961. }
  962. CARLA_SAFE_ASSERT_RETURN(label[4] >= '0' && label[4] < '0'+0x4f, false);
  963. fInfo.aIns = label[0] - '0';
  964. fInfo.aOuts = label[1] - '0';
  965. fInfo.mIns = carla_minPositive(label[2] - '0', 1);
  966. fInfo.mOuts = carla_minPositive(label[3] - '0', 1);
  967. fInfo.setupLabel = label;
  968. const int setupHints = label[4] - '0';
  969. // ---------------------------------------------------------------
  970. // set info
  971. pData->filename = carla_strdup(filename);
  972. if (name != nullptr && name[0] != '\0')
  973. pData->name = pData->engine->getUniquePluginName(name);
  974. else
  975. pData->name = pData->engine->getUniquePluginName("Jack Application");
  976. std::srand(static_cast<uint>(std::time(nullptr)));
  977. // ---------------------------------------------------------------
  978. // init sem/shm
  979. if (! fShmAudioPool.initializeServer())
  980. {
  981. carla_stderr("Failed to initialize shared memory audio pool");
  982. return false;
  983. }
  984. if (! fShmRtClientControl.initializeServer())
  985. {
  986. carla_stderr("Failed to initialize RT client control");
  987. fShmAudioPool.clear();
  988. return false;
  989. }
  990. if (! fShmNonRtClientControl.initializeServer())
  991. {
  992. carla_stderr("Failed to initialize Non-RT client control");
  993. fShmRtClientControl.clear();
  994. fShmAudioPool.clear();
  995. return false;
  996. }
  997. if (! fShmNonRtServerControl.initializeServer())
  998. {
  999. carla_stderr("Failed to initialize Non-RT server control");
  1000. fShmNonRtClientControl.clear();
  1001. fShmRtClientControl.clear();
  1002. fShmAudioPool.clear();
  1003. return false;
  1004. }
  1005. // ---------------------------------------------------------------
  1006. // setup hints and options
  1007. // FIXME dryWet broken
  1008. pData->hints = PLUGIN_IS_BRIDGE | /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE | PLUGIN_NEEDS_FIXED_BUFFERS;
  1009. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  1010. //fInfo.optionsAvailable = optionAv;
  1011. if (setupHints & 0x10)
  1012. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1013. // ---------------------------------------------------------------
  1014. // init bridge thread
  1015. {
  1016. char shmIdsStr[6*4+1];
  1017. carla_zeroChars(shmIdsStr, 6*4+1);
  1018. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1019. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1020. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1021. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1022. fBridgeThread.setData(shmIdsStr, label);
  1023. }
  1024. if (! restartBridgeThread())
  1025. return false;
  1026. // ---------------------------------------------------------------
  1027. // register client
  1028. if (pData->name == nullptr)
  1029. pData->name = pData->engine->getUniquePluginName("unknown");
  1030. pData->client = pData->engine->addClient(this);
  1031. if (pData->client == nullptr || ! pData->client->isOk())
  1032. {
  1033. pData->engine->setLastError("Failed to register plugin client");
  1034. return false;
  1035. }
  1036. return true;
  1037. }
  1038. private:
  1039. bool fInitiated;
  1040. bool fInitError;
  1041. bool fTimedOut;
  1042. bool fTimedError;
  1043. bool fProcCanceled;
  1044. uint fProcWaitTime;
  1045. int64_t fLastPingTime;
  1046. CarlaPluginJackThread fBridgeThread;
  1047. BridgeAudioPool fShmAudioPool;
  1048. BridgeRtClientControl fShmRtClientControl;
  1049. BridgeNonRtClientControl fShmNonRtClientControl;
  1050. BridgeNonRtServerControl fShmNonRtServerControl;
  1051. struct Info {
  1052. uint32_t aIns, aOuts;
  1053. uint32_t mIns, mOuts;
  1054. uint optionsAvailable;
  1055. CarlaString setupLabel;
  1056. std::vector<uint8_t> chunk;
  1057. Info()
  1058. : aIns(0),
  1059. aOuts(0),
  1060. mIns(0),
  1061. mOuts(0),
  1062. optionsAvailable(0),
  1063. setupLabel(),
  1064. chunk() {}
  1065. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1066. } fInfo;
  1067. void handleProcessStopped() noexcept
  1068. {
  1069. const bool wasActive = pData->active;
  1070. pData->active = false;
  1071. if (wasActive)
  1072. {
  1073. #ifdef HAVE_LIBLO
  1074. if (pData->engine->isOscControlRegistered())
  1075. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  1076. #endif
  1077. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  1078. }
  1079. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1080. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1081. }
  1082. void resizeAudioPool(const uint32_t bufferSize)
  1083. {
  1084. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, 0);
  1085. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1086. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1087. fShmRtClientControl.commitWrite();
  1088. waitForClient("resize-pool", 5000);
  1089. }
  1090. void waitForClient(const char* const action, const uint msecs)
  1091. {
  1092. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1093. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1094. if (fShmRtClientControl.waitForClient(msecs))
  1095. return;
  1096. fTimedOut = true;
  1097. carla_stderr("waitForClient(%s) timed out", action);
  1098. }
  1099. bool restartBridgeThread()
  1100. {
  1101. fInitiated = false;
  1102. fInitError = false;
  1103. fTimedError = false;
  1104. // reset memory
  1105. fProcCanceled = false;
  1106. fShmRtClientControl.data->procFlags = 0;
  1107. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1108. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1109. fShmRtClientControl.clearData();
  1110. fShmNonRtClientControl.clearData();
  1111. fShmNonRtServerControl.clearData();
  1112. // initial values
  1113. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientNull);
  1114. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1115. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1116. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1117. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1118. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1119. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1120. fShmNonRtClientControl.commitWrite();
  1121. if (fShmAudioPool.dataSize != 0)
  1122. {
  1123. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1124. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1125. fShmRtClientControl.commitWrite();
  1126. }
  1127. else
  1128. {
  1129. // testing dummy message
  1130. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1131. fShmRtClientControl.commitWrite();
  1132. }
  1133. fBridgeThread.startThread();
  1134. fLastPingTime = Time::currentTimeMillis();
  1135. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1136. static bool sFirstInit = true;
  1137. int64_t timeoutEnd = 5000;
  1138. if (sFirstInit)
  1139. timeoutEnd *= 2;
  1140. sFirstInit = false;
  1141. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1142. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1143. {
  1144. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1145. if (needsEngineIdle)
  1146. pData->engine->idle();
  1147. idle();
  1148. if (fInitiated)
  1149. break;
  1150. if (pData->engine->isAboutToClose())
  1151. break;
  1152. carla_msleep(20);
  1153. }
  1154. fLastPingTime = -1;
  1155. if (fInitError || ! fInitiated)
  1156. {
  1157. fBridgeThread.stopThread(6000);
  1158. if (! fInitError)
  1159. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1160. "(or the plugin crashed on initialization?)");
  1161. return false;
  1162. }
  1163. return true;
  1164. }
  1165. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1166. };
  1167. CARLA_BACKEND_END_NAMESPACE
  1168. #endif // CARLA_OS_LINUX
  1169. // -------------------------------------------------------------------------------------------------------------------
  1170. CARLA_BACKEND_START_NAMESPACE
  1171. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1172. {
  1173. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label);
  1174. #ifdef CARLA_OS_LINUX
  1175. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1176. if (! plugin->init(init.filename, init.name, init.label))
  1177. {
  1178. delete plugin;
  1179. return nullptr;
  1180. }
  1181. return plugin;
  1182. #else
  1183. init.engine->setLastError("JACK Application support not available");
  1184. return nullptr;
  1185. #endif
  1186. }
  1187. CARLA_BACKEND_END_NAMESPACE
  1188. // -------------------------------------------------------------------------------------------------------------------