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.

1497 lines
50KB

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