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.

1524 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 strBuf[STR_MAX+1];
  90. std::snprintf(strBuf, STR_MAX, P_UINTPTR, options.frontendWinId);
  91. strBuf[STR_MAX] = '\0';
  92. CarlaString libjackdir(options.binaryDir);
  93. libjackdir += "/jack";
  94. const ScopedEngineEnvironmentLocker _seel(kEngine);
  95. const ScopedEnvVar sev1("LD_PRELOAD", nullptr);
  96. const ScopedEnvVar sev2("LD_LIBRARY_PATH", libjackdir.buffer());
  97. carla_setenv("CARLA_FRONTEND_WIN_ID", strBuf);
  98. carla_setenv("CARLA_SHM_IDS", fShmIds.buffer());
  99. carla_setenv("CARLA_NUM_PORTS", fNumPorts.buffer());
  100. started = fProcess->start(arguments);
  101. }
  102. if (! started)
  103. {
  104. carla_stdout("failed!");
  105. fProcess = nullptr;
  106. return;
  107. }
  108. for (; fProcess->isRunning() && ! shouldThreadExit();)
  109. carla_msleep(50);
  110. // we only get here if bridge crashed or thread asked to exit
  111. if (fProcess->isRunning() && shouldThreadExit())
  112. {
  113. fProcess->waitForProcessToFinish(2000);
  114. if (fProcess->isRunning())
  115. {
  116. carla_stdout("CarlaPluginJackThread::run() - bridge refused to close, force kill now");
  117. fProcess->kill();
  118. }
  119. else
  120. {
  121. carla_stdout("CarlaPluginJackThread::run() - bridge auto-closed successfully");
  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() - bridge 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. else
  136. {
  137. carla_stderr("CarlaPluginJackThread::run() - bridge closed itself");
  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, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  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 fInfo.category;
  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 idle() override
  281. {
  282. if (fBridgeThread.isThreadRunning())
  283. {
  284. if (fInitiated && fTimedOut && pData->active)
  285. setActive(false, true, true);
  286. {
  287. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  288. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  289. fShmNonRtClientControl.commitWrite();
  290. }
  291. try {
  292. handleNonRtData();
  293. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  294. if (fLastPingTime > 0 && Time::currentTimeMillis() > fLastPingTime + 30000)
  295. {
  296. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  297. // TODO
  298. //threadShouldExit();
  299. //callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  300. }
  301. }
  302. else if (fInitiated)
  303. {
  304. fTimedOut = true;
  305. fTimedError = true;
  306. fInitiated = false;
  307. carla_stderr2("Plugin bridge has been stopped or crashed");
  308. pData->engine->callback(ENGINE_CALLBACK_PLUGIN_UNAVAILABLE, pData->id, 0, 0, 0.0f,
  309. "Plugin bridge has been stopped or crashed");
  310. }
  311. CarlaPlugin::idle();
  312. }
  313. // -------------------------------------------------------------------
  314. // Plugin state
  315. void reload() override
  316. {
  317. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  318. carla_debug("CarlaPluginJack::reload() - start");
  319. const EngineProcessMode processMode(pData->engine->getProccessMode());
  320. // Safely disable plugin for reload
  321. const ScopedDisabler sd(this);
  322. // cleanup of previous data
  323. pData->audioIn.clear();
  324. pData->audioOut.clear();
  325. pData->cvIn.clear();
  326. pData->cvOut.clear();
  327. pData->event.clear();
  328. bool needsCtrlIn, needsCtrlOut;
  329. needsCtrlIn = needsCtrlOut = false;
  330. if (fInfo.aIns > 0)
  331. {
  332. pData->audioIn.createNew(fInfo.aIns);
  333. }
  334. if (fInfo.aOuts > 0)
  335. {
  336. pData->audioOut.createNew(fInfo.aOuts);
  337. needsCtrlIn = true;
  338. }
  339. if (fInfo.cvIns > 0)
  340. {
  341. pData->cvIn.createNew(fInfo.cvIns);
  342. }
  343. if (fInfo.cvOuts > 0)
  344. {
  345. pData->cvOut.createNew(fInfo.cvOuts);
  346. }
  347. if (fInfo.mIns > 0)
  348. needsCtrlIn = true;
  349. if (fInfo.mOuts > 0)
  350. needsCtrlOut = true;
  351. const uint portNameSize(pData->engine->getMaxPortNameSize());
  352. CarlaString portName;
  353. // Audio Ins
  354. for (uint32_t j=0; j < fInfo.aIns; ++j)
  355. {
  356. portName.clear();
  357. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  358. {
  359. portName = pData->name;
  360. portName += ":";
  361. }
  362. if (fInfo.aIns > 1)
  363. {
  364. portName += "audio_in_";
  365. portName += CarlaString(j+1);
  366. }
  367. else
  368. {
  369. portName += "audio_in";
  370. }
  371. portName.truncate(portNameSize);
  372. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  373. pData->audioIn.ports[j].rindex = j;
  374. }
  375. // Audio Outs
  376. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  377. {
  378. portName.clear();
  379. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  380. {
  381. portName = pData->name;
  382. portName += ":";
  383. }
  384. if (fInfo.aOuts > 1)
  385. {
  386. portName += "audio_out_";
  387. portName += CarlaString(j+1);
  388. }
  389. else
  390. {
  391. portName += "audio_out";
  392. }
  393. portName.truncate(portNameSize);
  394. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  395. pData->audioOut.ports[j].rindex = j;
  396. }
  397. // TODO - MIDI
  398. // TODO - CV
  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** const cvIn, float** const cvOut, 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. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  479. FloatVectorOperations::clear(cvOut[i], static_cast<int>(frames));
  480. return;
  481. }
  482. // --------------------------------------------------------------------------------------------------------
  483. // Check if needs reset
  484. if (pData->needsReset)
  485. {
  486. // TODO
  487. pData->needsReset = false;
  488. }
  489. // --------------------------------------------------------------------------------------------------------
  490. // Event Input
  491. if (pData->event.portIn != nullptr)
  492. {
  493. // ----------------------------------------------------------------------------------------------------
  494. // MIDI Input (External)
  495. if (pData->extNotes.mutex.tryLock())
  496. {
  497. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  498. {
  499. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  500. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  501. uint8_t data1, data2, data3;
  502. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  503. data2 = note.note;
  504. data3 = note.velo;
  505. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  506. fShmRtClientControl.writeUInt(0); // time
  507. fShmRtClientControl.writeByte(0); // port
  508. fShmRtClientControl.writeByte(3); // size
  509. fShmRtClientControl.writeByte(data1);
  510. fShmRtClientControl.writeByte(data2);
  511. fShmRtClientControl.writeByte(data3);
  512. fShmRtClientControl.commitWrite();
  513. }
  514. pData->extNotes.data.clear();
  515. pData->extNotes.mutex.unlock();
  516. } // End of MIDI Input (External)
  517. // ----------------------------------------------------------------------------------------------------
  518. // Event Input (System)
  519. bool allNotesOffSent = false;
  520. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  521. {
  522. const EngineEvent& event(pData->event.portIn->getEvent(i));
  523. // Control change
  524. switch (event.type)
  525. {
  526. case kEngineEventTypeNull:
  527. break;
  528. case kEngineEventTypeControl: {
  529. const EngineControlEvent& ctrlEvent = event.ctrl;
  530. switch (ctrlEvent.type)
  531. {
  532. case kEngineControlEventTypeNull:
  533. break;
  534. case kEngineControlEventTypeParameter:
  535. // Control backend stuff
  536. if (event.channel == pData->ctrlChannel)
  537. {
  538. float value;
  539. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  540. {
  541. value = ctrlEvent.value;
  542. setDryWet(value, false, false);
  543. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  544. }
  545. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  546. {
  547. value = ctrlEvent.value*127.0f/100.0f;
  548. setVolume(value, false, false);
  549. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  550. }
  551. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  552. {
  553. float left, right;
  554. value = ctrlEvent.value/0.5f - 1.0f;
  555. if (value < 0.0f)
  556. {
  557. left = -1.0f;
  558. right = (value*2.0f)+1.0f;
  559. }
  560. else if (value > 0.0f)
  561. {
  562. left = (value*2.0f)-1.0f;
  563. right = 1.0f;
  564. }
  565. else
  566. {
  567. left = -1.0f;
  568. right = 1.0f;
  569. }
  570. setBalanceLeft(left, false, false);
  571. setBalanceRight(right, false, false);
  572. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  573. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  574. }
  575. }
  576. break;
  577. case kEngineControlEventTypeMidiBank:
  578. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  579. {
  580. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  581. fShmRtClientControl.writeUInt(event.time);
  582. fShmRtClientControl.writeByte(event.channel);
  583. fShmRtClientControl.writeUShort(event.ctrl.param);
  584. fShmRtClientControl.commitWrite();
  585. }
  586. break;
  587. case kEngineControlEventTypeMidiProgram:
  588. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  589. {
  590. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  591. fShmRtClientControl.writeUInt(event.time);
  592. fShmRtClientControl.writeByte(event.channel);
  593. fShmRtClientControl.writeUShort(event.ctrl.param);
  594. fShmRtClientControl.commitWrite();
  595. }
  596. break;
  597. case kEngineControlEventTypeAllSoundOff:
  598. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  599. {
  600. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  601. fShmRtClientControl.writeUInt(event.time);
  602. fShmRtClientControl.writeByte(event.channel);
  603. fShmRtClientControl.commitWrite();
  604. }
  605. break;
  606. case kEngineControlEventTypeAllNotesOff:
  607. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  608. {
  609. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  610. {
  611. allNotesOffSent = true;
  612. sendMidiAllNotesOffToCallback();
  613. }
  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, cvIn, cvOut, frames))
  658. return;
  659. // --------------------------------------------------------------------------------------------------------
  660. // MIDI Output
  661. if (pData->event.portOut != nullptr)
  662. {
  663. uint8_t size;
  664. uint32_t time;
  665. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  666. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize;)
  667. {
  668. size = *midiData;
  669. if (size == 0)
  670. break;
  671. // advance 8 bits (1 byte)
  672. midiData = midiData + 1;
  673. // get time as 32bit
  674. time = *(const uint32_t*)midiData;
  675. // advance 32 bits (4 bytes)
  676. midiData = midiData + 4;
  677. // store midi data advancing as needed
  678. uint8_t data[size];
  679. for (uint8_t j=0; j<size; ++j)
  680. data[j] = *midiData++;
  681. pData->event.portOut->writeMidiEvent(time, size, data);
  682. read += 1U /* size*/ + 4U /* time */ + size;
  683. }
  684. } // End of Control and MIDI Output
  685. }
  686. bool processSingle(const float** const audioIn, float** const audioOut,
  687. const float** const cvIn, float** const cvOut, 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. if (pData->cvIn.count > 0)
  700. {
  701. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  702. }
  703. if (pData->cvOut.count > 0)
  704. {
  705. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  706. }
  707. const int iframes(static_cast<int>(frames));
  708. // --------------------------------------------------------------------------------------------------------
  709. // Try lock, silence otherwise
  710. if (pData->engine->isOffline())
  711. {
  712. pData->singleMutex.lock();
  713. }
  714. else if (! pData->singleMutex.tryLock())
  715. {
  716. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  717. FloatVectorOperations::clear(audioOut[i], iframes);
  718. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  719. FloatVectorOperations::clear(cvOut[i], iframes);
  720. return false;
  721. }
  722. // --------------------------------------------------------------------------------------------------------
  723. // Reset audio buffers
  724. for (uint32_t i=0; i < fInfo.aIns; ++i)
  725. FloatVectorOperations::copy(fShmAudioPool.data + (i * frames), audioIn[i], iframes);
  726. // --------------------------------------------------------------------------------------------------------
  727. // TimeInfo
  728. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  729. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  730. bridgeTimeInfo.playing = timeInfo.playing;
  731. bridgeTimeInfo.frame = timeInfo.frame;
  732. bridgeTimeInfo.usecs = timeInfo.usecs;
  733. bridgeTimeInfo.valid = timeInfo.valid;
  734. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  735. {
  736. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  737. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  738. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  739. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  740. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  741. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  742. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  743. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  744. }
  745. // --------------------------------------------------------------------------------------------------------
  746. // Run plugin
  747. {
  748. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  749. fShmRtClientControl.commitWrite();
  750. }
  751. waitForClient("process", fProcWaitTime);
  752. if (fTimedOut)
  753. {
  754. pData->singleMutex.unlock();
  755. return false;
  756. }
  757. if (fShmRtClientControl.data->procFlags)
  758. {
  759. carla_stdout("PROC Flags active, disabling plugin");
  760. fInitiated = false;
  761. fProcCanceled = true;
  762. }
  763. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  764. FloatVectorOperations::copy(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), iframes);
  765. // --------------------------------------------------------------------------------------------------------
  766. // Post-processing (dry/wet, volume and balance)
  767. {
  768. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  769. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  770. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  771. const bool isMono = (pData->audioIn.count == 1);
  772. bool isPair;
  773. float bufValue, oldBufLeft[doBalance ? frames : 1];
  774. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  775. {
  776. // Dry/Wet
  777. if (doDryWet)
  778. {
  779. const uint32_t c = isMono ? 0 : i;
  780. for (uint32_t k=0; k < frames; ++k)
  781. {
  782. bufValue = audioIn[c][k];
  783. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  784. }
  785. }
  786. // Balance
  787. if (doBalance)
  788. {
  789. isPair = (i % 2 == 0);
  790. if (isPair)
  791. {
  792. CARLA_ASSERT(i+1 < pData->audioOut.count);
  793. FloatVectorOperations::copy(oldBufLeft, audioOut[i], iframes);
  794. }
  795. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  796. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  797. for (uint32_t k=0; k < frames; ++k)
  798. {
  799. if (isPair)
  800. {
  801. // left
  802. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  803. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  804. }
  805. else
  806. {
  807. // right
  808. audioOut[i][k] = audioOut[i][k] * balRangeR;
  809. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  810. }
  811. }
  812. }
  813. // Volume (and buffer copy)
  814. if (doVolume)
  815. {
  816. for (uint32_t k=0; k < frames; ++k)
  817. audioOut[i][k] *= pData->postProc.volume;
  818. }
  819. }
  820. } // End of Post-processing
  821. // --------------------------------------------------------------------------------------------------------
  822. pData->singleMutex.unlock();
  823. return true;
  824. }
  825. void bufferSizeChanged(const uint32_t newBufferSize) override
  826. {
  827. resizeAudioPool(newBufferSize);
  828. {
  829. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  830. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetBufferSize);
  831. fShmNonRtClientControl.writeUInt(newBufferSize);
  832. fShmNonRtClientControl.commitWrite();
  833. }
  834. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  835. fProcWaitTime = 1000;
  836. waitForClient("buffersize", 1000);
  837. }
  838. void sampleRateChanged(const double newSampleRate) override
  839. {
  840. {
  841. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  842. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetSampleRate);
  843. fShmNonRtClientControl.writeDouble(newSampleRate);
  844. fShmNonRtClientControl.commitWrite();
  845. }
  846. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  847. fProcWaitTime = 1000;
  848. waitForClient("samplerate", 1000);
  849. }
  850. void offlineModeChanged(const bool isOffline) override
  851. {
  852. {
  853. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  854. fShmNonRtClientControl.writeOpcode(isOffline ? kPluginBridgeNonRtClientSetOffline : kPluginBridgeNonRtClientSetOnline);
  855. fShmNonRtClientControl.commitWrite();
  856. }
  857. waitForClient("offline", 1000);
  858. }
  859. // -------------------------------------------------------------------
  860. // Post-poned UI Stuff
  861. // -------------------------------------------------------------------
  862. void handleNonRtData()
  863. {
  864. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  865. {
  866. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  867. //#ifdef DEBUG
  868. if (opcode != kPluginBridgeNonRtServerPong)
  869. {
  870. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  871. }
  872. //#endif
  873. if (opcode != kPluginBridgeNonRtServerNull && fLastPingTime > 0)
  874. fLastPingTime = Time::currentTimeMillis();
  875. switch (opcode)
  876. {
  877. case kPluginBridgeNonRtServerNull:
  878. case kPluginBridgeNonRtServerPong:
  879. case kPluginBridgeNonRtServerPluginInfo1:
  880. case kPluginBridgeNonRtServerPluginInfo2:
  881. case kPluginBridgeNonRtServerAudioCount:
  882. case kPluginBridgeNonRtServerMidiCount:
  883. case kPluginBridgeNonRtServerCvCount:
  884. case kPluginBridgeNonRtServerParameterCount:
  885. case kPluginBridgeNonRtServerProgramCount:
  886. case kPluginBridgeNonRtServerMidiProgramCount:
  887. case kPluginBridgeNonRtServerPortName:
  888. case kPluginBridgeNonRtServerParameterData1:
  889. case kPluginBridgeNonRtServerParameterData2:
  890. case kPluginBridgeNonRtServerParameterRanges:
  891. case kPluginBridgeNonRtServerParameterValue:
  892. case kPluginBridgeNonRtServerParameterValue2:
  893. case kPluginBridgeNonRtServerDefaultValue:
  894. case kPluginBridgeNonRtServerCurrentProgram:
  895. case kPluginBridgeNonRtServerCurrentMidiProgram:
  896. case kPluginBridgeNonRtServerProgramName:
  897. case kPluginBridgeNonRtServerMidiProgramData:
  898. case kPluginBridgeNonRtServerSetCustomData:
  899. break;
  900. case kPluginBridgeNonRtServerSetChunkDataFile: {
  901. // uint/size, str[] (filename)
  902. const uint32_t chunkFilePathSize(fShmNonRtServerControl.readUInt());
  903. char chunkFilePath[chunkFilePathSize];
  904. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  905. } break;
  906. case kPluginBridgeNonRtServerSetLatency:
  907. break;
  908. case kPluginBridgeNonRtServerReady:
  909. fInitiated = true;
  910. break;
  911. case kPluginBridgeNonRtServerSaved:
  912. break;
  913. case kPluginBridgeNonRtServerUiClosed:
  914. carla_stdout("bridge closed cleanly?");
  915. pData->active = false;
  916. #ifdef HAVE_LIBLO
  917. if (pData->engine->isOscControlRegistered())
  918. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  919. #endif
  920. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  921. fBridgeThread.stopThread(1000);
  922. break;
  923. case kPluginBridgeNonRtServerError: {
  924. // error
  925. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  926. char error[errorSize+1];
  927. carla_zeroChars(error, errorSize+1);
  928. fShmNonRtServerControl.readCustomData(error, errorSize);
  929. if (fInitiated)
  930. {
  931. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  932. // just in case
  933. pData->engine->setLastError(error);
  934. fInitError = true;
  935. }
  936. else
  937. {
  938. pData->engine->setLastError(error);
  939. fInitError = true;
  940. fInitiated = true;
  941. }
  942. } break;
  943. }
  944. }
  945. }
  946. // -------------------------------------------------------------------
  947. uintptr_t getUiBridgeProcessId() const noexcept override
  948. {
  949. return fBridgeThread.getProcessID();
  950. }
  951. // -------------------------------------------------------------------
  952. bool init(const char* const filename, const char* const name, const char* const label)
  953. {
  954. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  955. // ---------------------------------------------------------------
  956. // first checks
  957. if (pData->client != nullptr)
  958. {
  959. pData->engine->setLastError("Plugin client is already registered");
  960. return false;
  961. }
  962. if (filename == nullptr || filename[0] == '\0')
  963. {
  964. pData->engine->setLastError("null filename");
  965. return false;
  966. }
  967. if (label == nullptr || label[0] == '\0')
  968. {
  969. pData->engine->setLastError("null label");
  970. return false;
  971. }
  972. // ---------------------------------------------------------------
  973. // check setup
  974. if (std::strlen(label) != 6)
  975. {
  976. pData->engine->setLastError("invalid application setup received");
  977. return false;
  978. }
  979. for (int i=6; --i >= 0;) {
  980. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] < '0'+64, false);
  981. }
  982. fInfo.aIns = label[0] - '0';
  983. fInfo.aOuts = label[1] - '0';
  984. fInfo.cvIns = label[2] - '0';
  985. fInfo.cvOuts = label[3] - '0';
  986. fInfo.mIns = label[4] - '0';
  987. fInfo.mOuts = label[5] - '0';
  988. fInfo.setupLabel = label;
  989. // TODO
  990. fInfo.cvIns = fInfo.cvOuts = fInfo.mIns = fInfo.mOuts = 0;
  991. // ---------------------------------------------------------------
  992. // set info
  993. pData->filename = carla_strdup(filename);
  994. if (name != nullptr && name[0] != '\0')
  995. pData->name = pData->engine->getUniquePluginName(name);
  996. else
  997. pData->name = pData->engine->getUniquePluginName("Jack Application");
  998. std::srand(static_cast<uint>(std::time(nullptr)));
  999. // ---------------------------------------------------------------
  1000. // init sem/shm
  1001. if (! fShmAudioPool.initializeServer())
  1002. {
  1003. carla_stderr("Failed to initialize shared memory audio pool");
  1004. return false;
  1005. }
  1006. if (! fShmRtClientControl.initializeServer())
  1007. {
  1008. carla_stderr("Failed to initialize RT client control");
  1009. fShmAudioPool.clear();
  1010. return false;
  1011. }
  1012. if (! fShmNonRtClientControl.initializeServer())
  1013. {
  1014. carla_stderr("Failed to initialize Non-RT client control");
  1015. fShmRtClientControl.clear();
  1016. fShmAudioPool.clear();
  1017. return false;
  1018. }
  1019. if (! fShmNonRtServerControl.initializeServer())
  1020. {
  1021. carla_stderr("Failed to initialize Non-RT server control");
  1022. fShmNonRtClientControl.clear();
  1023. fShmRtClientControl.clear();
  1024. fShmAudioPool.clear();
  1025. return false;
  1026. }
  1027. // ---------------------------------------------------------------
  1028. // init bridge thread
  1029. {
  1030. char shmIdsStr[6*4+1];
  1031. carla_zeroChars(shmIdsStr, 6*4+1);
  1032. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1033. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1034. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1035. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1036. fBridgeThread.setData(shmIdsStr, label);
  1037. }
  1038. if (! restartBridgeThread())
  1039. return false;
  1040. // ---------------------------------------------------------------
  1041. // register client
  1042. if (pData->name == nullptr)
  1043. pData->name = pData->engine->getUniquePluginName("unknown");
  1044. pData->client = pData->engine->addClient(this);
  1045. if (pData->client == nullptr || ! pData->client->isOk())
  1046. {
  1047. pData->engine->setLastError("Failed to register plugin client");
  1048. return false;
  1049. }
  1050. return true;
  1051. }
  1052. private:
  1053. bool fInitiated;
  1054. bool fInitError;
  1055. bool fTimedOut;
  1056. bool fTimedError;
  1057. bool fProcCanceled;
  1058. uint fProcWaitTime;
  1059. int64_t fLastPingTime;
  1060. CarlaPluginJackThread fBridgeThread;
  1061. BridgeAudioPool fShmAudioPool;
  1062. BridgeRtClientControl fShmRtClientControl;
  1063. BridgeNonRtClientControl fShmNonRtClientControl;
  1064. BridgeNonRtServerControl fShmNonRtServerControl;
  1065. struct Info {
  1066. uint32_t aIns, aOuts;
  1067. uint32_t cvIns, cvOuts;
  1068. uint32_t mIns, mOuts;
  1069. PluginCategory category;
  1070. uint optionsAvailable;
  1071. CarlaString setupLabel;
  1072. std::vector<uint8_t> chunk;
  1073. Info()
  1074. : aIns(0),
  1075. aOuts(0),
  1076. cvIns(0),
  1077. cvOuts(0),
  1078. mIns(0),
  1079. mOuts(0),
  1080. category(PLUGIN_CATEGORY_NONE),
  1081. optionsAvailable(0),
  1082. setupLabel(),
  1083. chunk() {}
  1084. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1085. } fInfo;
  1086. void resizeAudioPool(const uint32_t bufferSize)
  1087. {
  1088. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, fInfo.cvIns+fInfo.cvOuts);
  1089. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1090. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1091. fShmRtClientControl.commitWrite();
  1092. waitForClient("resize-pool", 5000);
  1093. }
  1094. void waitForClient(const char* const action, const uint msecs)
  1095. {
  1096. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1097. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1098. if (fShmRtClientControl.waitForClient(msecs))
  1099. return;
  1100. fTimedOut = true;
  1101. carla_stderr("waitForClient(%s) timed out", action);
  1102. }
  1103. bool restartBridgeThread()
  1104. {
  1105. fInitiated = false;
  1106. fInitError = false;
  1107. fTimedError = false;
  1108. // reset memory
  1109. fProcCanceled = false;
  1110. fShmRtClientControl.data->procFlags = 0;
  1111. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1112. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1113. fShmRtClientControl.clearData();
  1114. fShmNonRtClientControl.clearData();
  1115. fShmNonRtServerControl.clearData();
  1116. // initial values
  1117. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientNull);
  1118. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1119. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1120. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1121. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetBufferSize);
  1122. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1123. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetSampleRate);
  1124. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1125. fShmNonRtClientControl.commitWrite();
  1126. if (fShmAudioPool.dataSize != 0)
  1127. {
  1128. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1129. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1130. fShmRtClientControl.commitWrite();
  1131. }
  1132. else
  1133. {
  1134. // testing dummy message
  1135. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1136. fShmRtClientControl.commitWrite();
  1137. }
  1138. fBridgeThread.startThread();
  1139. fLastPingTime = Time::currentTimeMillis();
  1140. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1141. static bool sFirstInit = true;
  1142. int64_t timeoutEnd = 5000;
  1143. if (sFirstInit)
  1144. timeoutEnd *= 2;
  1145. sFirstInit = false;
  1146. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1147. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1148. {
  1149. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1150. if (needsEngineIdle)
  1151. pData->engine->idle();
  1152. idle();
  1153. if (fInitiated)
  1154. break;
  1155. if (pData->engine->isAboutToClose())
  1156. break;
  1157. carla_msleep(20);
  1158. }
  1159. fLastPingTime = -1;
  1160. if (fInitError || ! fInitiated)
  1161. {
  1162. fBridgeThread.stopThread(6000);
  1163. if (! fInitError)
  1164. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1165. "(or the plugin crashed on initialization?)");
  1166. return false;
  1167. }
  1168. return true;
  1169. }
  1170. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1171. };
  1172. CARLA_BACKEND_END_NAMESPACE
  1173. #endif // CARLA_OS_LINUX
  1174. // -------------------------------------------------------------------------------------------------------------------
  1175. CARLA_BACKEND_START_NAMESPACE
  1176. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1177. {
  1178. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label);
  1179. #ifdef CARLA_OS_LINUX
  1180. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1181. if (! plugin->init(init.filename, init.name, init.label))
  1182. {
  1183. delete plugin;
  1184. return nullptr;
  1185. }
  1186. return plugin;
  1187. #else
  1188. init.engine->setLastError("JACK Application support not available");
  1189. return nullptr;
  1190. #endif
  1191. }
  1192. CARLA_BACKEND_END_NAMESPACE
  1193. // -------------------------------------------------------------------------------------------------------------------