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.

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