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.

1500 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, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  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. uint8_t size;
  658. uint32_t time;
  659. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  660. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize;)
  661. {
  662. size = *midiData;
  663. if (size == 0)
  664. break;
  665. // advance 8 bits (1 byte)
  666. midiData = midiData + 1;
  667. // get time as 32bit
  668. time = *(const uint32_t*)midiData;
  669. // advance 32 bits (4 bytes)
  670. midiData = midiData + 4;
  671. // store midi data advancing as needed
  672. uint8_t data[size];
  673. for (uint8_t j=0; j<size; ++j)
  674. data[j] = *midiData++;
  675. pData->event.portOut->writeMidiEvent(time, size, data);
  676. read += 1U /* size*/ + 4U /* time */ + size;
  677. }
  678. } // End of Control and MIDI Output
  679. }
  680. bool processSingle(const float** const audioIn, float** const audioOut, const uint32_t frames)
  681. {
  682. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  683. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  684. if (pData->audioIn.count > 0)
  685. {
  686. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  687. }
  688. if (pData->audioOut.count > 0)
  689. {
  690. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  691. }
  692. const int iframes(static_cast<int>(frames));
  693. // --------------------------------------------------------------------------------------------------------
  694. // Try lock, silence otherwise
  695. if (pData->engine->isOffline())
  696. {
  697. pData->singleMutex.lock();
  698. }
  699. else if (! pData->singleMutex.tryLock())
  700. {
  701. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  702. FloatVectorOperations::clear(audioOut[i], iframes);
  703. return false;
  704. }
  705. // --------------------------------------------------------------------------------------------------------
  706. // Reset audio buffers
  707. for (uint32_t i=0; i < fInfo.aIns; ++i)
  708. FloatVectorOperations::copy(fShmAudioPool.data + (i * frames), audioIn[i], iframes);
  709. // --------------------------------------------------------------------------------------------------------
  710. // TimeInfo
  711. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  712. BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  713. bridgeTimeInfo.playing = timeInfo.playing;
  714. bridgeTimeInfo.frame = timeInfo.frame;
  715. bridgeTimeInfo.usecs = timeInfo.usecs;
  716. bridgeTimeInfo.valid = timeInfo.valid;
  717. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  718. {
  719. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  720. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  721. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  722. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  723. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  724. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  725. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  726. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  727. }
  728. // --------------------------------------------------------------------------------------------------------
  729. // Run plugin
  730. {
  731. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientProcess);
  732. fShmRtClientControl.commitWrite();
  733. }
  734. waitForClient("process", fProcWaitTime);
  735. if (fTimedOut)
  736. {
  737. pData->singleMutex.unlock();
  738. return false;
  739. }
  740. if (fShmRtClientControl.data->procFlags)
  741. {
  742. carla_stdout("PROC Flags active, disabling plugin");
  743. fInitiated = false;
  744. fProcCanceled = true;
  745. }
  746. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  747. FloatVectorOperations::copy(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), iframes);
  748. // --------------------------------------------------------------------------------------------------------
  749. // Post-processing (dry/wet, volume and balance)
  750. {
  751. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  752. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  753. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  754. const bool isMono = (pData->audioIn.count == 1);
  755. bool isPair;
  756. float bufValue, oldBufLeft[doBalance ? frames : 1];
  757. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  758. {
  759. // Dry/Wet
  760. if (doDryWet)
  761. {
  762. const uint32_t c = isMono ? 0 : i;
  763. for (uint32_t k=0; k < frames; ++k)
  764. {
  765. bufValue = audioIn[c][k];
  766. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  767. }
  768. }
  769. // Balance
  770. if (doBalance)
  771. {
  772. isPair = (i % 2 == 0);
  773. if (isPair)
  774. {
  775. CARLA_ASSERT(i+1 < pData->audioOut.count);
  776. FloatVectorOperations::copy(oldBufLeft, audioOut[i], iframes);
  777. }
  778. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  779. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  780. for (uint32_t k=0; k < frames; ++k)
  781. {
  782. if (isPair)
  783. {
  784. // left
  785. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  786. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  787. }
  788. else
  789. {
  790. // right
  791. audioOut[i][k] = audioOut[i][k] * balRangeR;
  792. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  793. }
  794. }
  795. }
  796. // Volume (and buffer copy)
  797. if (doVolume)
  798. {
  799. for (uint32_t k=0; k < frames; ++k)
  800. audioOut[i][k] *= pData->postProc.volume;
  801. }
  802. }
  803. } // End of Post-processing
  804. // --------------------------------------------------------------------------------------------------------
  805. pData->singleMutex.unlock();
  806. return true;
  807. }
  808. void bufferSizeChanged(const uint32_t newBufferSize) override
  809. {
  810. resizeAudioPool(newBufferSize);
  811. {
  812. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetBufferSize);
  813. fShmRtClientControl.writeUInt(newBufferSize);
  814. fShmRtClientControl.commitWrite();
  815. }
  816. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  817. fProcWaitTime = 1000;
  818. waitForClient("buffersize", 1000);
  819. }
  820. void sampleRateChanged(const double newSampleRate) override
  821. {
  822. {
  823. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetSampleRate);
  824. fShmRtClientControl.writeDouble(newSampleRate);
  825. fShmRtClientControl.commitWrite();
  826. }
  827. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  828. fProcWaitTime = 1000;
  829. waitForClient("samplerate", 1000);
  830. }
  831. void offlineModeChanged(const bool isOffline) override
  832. {
  833. {
  834. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetOnline);
  835. fShmRtClientControl.writeBool(isOffline);
  836. fShmRtClientControl.commitWrite();
  837. }
  838. waitForClient("offline", 1000);
  839. }
  840. // -------------------------------------------------------------------
  841. // Post-poned UI Stuff
  842. // -------------------------------------------------------------------
  843. void handleNonRtData()
  844. {
  845. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  846. {
  847. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  848. //#ifdef DEBUG
  849. if (opcode != kPluginBridgeNonRtServerPong)
  850. {
  851. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  852. }
  853. //#endif
  854. if (opcode != kPluginBridgeNonRtServerNull && fLastPingTime > 0)
  855. fLastPingTime = Time::currentTimeMillis();
  856. switch (opcode)
  857. {
  858. case kPluginBridgeNonRtServerNull:
  859. case kPluginBridgeNonRtServerPong:
  860. case kPluginBridgeNonRtServerPluginInfo1:
  861. case kPluginBridgeNonRtServerPluginInfo2:
  862. case kPluginBridgeNonRtServerAudioCount:
  863. case kPluginBridgeNonRtServerMidiCount:
  864. case kPluginBridgeNonRtServerCvCount:
  865. case kPluginBridgeNonRtServerParameterCount:
  866. case kPluginBridgeNonRtServerProgramCount:
  867. case kPluginBridgeNonRtServerMidiProgramCount:
  868. case kPluginBridgeNonRtServerPortName:
  869. case kPluginBridgeNonRtServerParameterData1:
  870. case kPluginBridgeNonRtServerParameterData2:
  871. case kPluginBridgeNonRtServerParameterRanges:
  872. case kPluginBridgeNonRtServerParameterValue:
  873. case kPluginBridgeNonRtServerParameterValue2:
  874. case kPluginBridgeNonRtServerDefaultValue:
  875. case kPluginBridgeNonRtServerCurrentProgram:
  876. case kPluginBridgeNonRtServerCurrentMidiProgram:
  877. case kPluginBridgeNonRtServerProgramName:
  878. case kPluginBridgeNonRtServerMidiProgramData:
  879. case kPluginBridgeNonRtServerSetCustomData:
  880. break;
  881. case kPluginBridgeNonRtServerSetChunkDataFile: {
  882. // uint/size, str[] (filename)
  883. const uint32_t chunkFilePathSize(fShmNonRtServerControl.readUInt());
  884. char chunkFilePath[chunkFilePathSize];
  885. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  886. } break;
  887. case kPluginBridgeNonRtServerSetLatency:
  888. break;
  889. case kPluginBridgeNonRtServerReady:
  890. fInitiated = true;
  891. break;
  892. case kPluginBridgeNonRtServerSaved:
  893. break;
  894. case kPluginBridgeNonRtServerUiClosed:
  895. carla_stdout("bridge closed cleanly?");
  896. pData->active = false;
  897. #ifdef HAVE_LIBLO
  898. if (pData->engine->isOscControlRegistered())
  899. pData->engine->oscSend_control_set_parameter_value(pData->id, PARAMETER_ACTIVE, 0.0f);
  900. #endif
  901. pData->engine->callback(ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED, pData->id, PARAMETER_ACTIVE, 0, 0.0f, nullptr);
  902. fBridgeThread.stopThread(1000);
  903. break;
  904. case kPluginBridgeNonRtServerError: {
  905. // error
  906. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  907. char error[errorSize+1];
  908. carla_zeroChars(error, errorSize+1);
  909. fShmNonRtServerControl.readCustomData(error, errorSize);
  910. if (fInitiated)
  911. {
  912. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  913. // just in case
  914. pData->engine->setLastError(error);
  915. fInitError = true;
  916. }
  917. else
  918. {
  919. pData->engine->setLastError(error);
  920. fInitError = true;
  921. fInitiated = true;
  922. }
  923. } break;
  924. }
  925. }
  926. }
  927. // -------------------------------------------------------------------
  928. uintptr_t getUiBridgeProcessId() const noexcept override
  929. {
  930. return fBridgeThread.getProcessID();
  931. }
  932. // -------------------------------------------------------------------
  933. bool init(const char* const filename, const char* const name, const char* const label)
  934. {
  935. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  936. // ---------------------------------------------------------------
  937. // first checks
  938. if (pData->client != nullptr)
  939. {
  940. pData->engine->setLastError("Plugin client is already registered");
  941. return false;
  942. }
  943. if (filename == nullptr || filename[0] == '\0')
  944. {
  945. pData->engine->setLastError("null filename");
  946. return false;
  947. }
  948. if (label == nullptr || label[0] == '\0')
  949. {
  950. pData->engine->setLastError("null label");
  951. return false;
  952. }
  953. // ---------------------------------------------------------------
  954. // check setup
  955. if (std::strlen(label) != 5)
  956. {
  957. pData->engine->setLastError("invalid application setup received");
  958. return false;
  959. }
  960. for (int i=4; --i >= 0;) {
  961. CARLA_SAFE_ASSERT_RETURN(label[i] >= '0' && label[i] <= '0'+64, false);
  962. }
  963. CARLA_SAFE_ASSERT_RETURN(label[4] >= '0' && label[4] < '0'+0x4f, false);
  964. fInfo.aIns = label[0] - '0';
  965. fInfo.aOuts = label[1] - '0';
  966. fInfo.mIns = carla_minPositive(label[4] - '0', 1);
  967. fInfo.mOuts = carla_minPositive(label[5] - '0', 1);
  968. fInfo.setupLabel = label;
  969. // ---------------------------------------------------------------
  970. // set info
  971. pData->filename = carla_strdup(filename);
  972. if (name != nullptr && name[0] != '\0')
  973. pData->name = pData->engine->getUniquePluginName(name);
  974. else
  975. pData->name = pData->engine->getUniquePluginName("Jack Application");
  976. std::srand(static_cast<uint>(std::time(nullptr)));
  977. // ---------------------------------------------------------------
  978. // init sem/shm
  979. if (! fShmAudioPool.initializeServer())
  980. {
  981. carla_stderr("Failed to initialize shared memory audio pool");
  982. return false;
  983. }
  984. if (! fShmRtClientControl.initializeServer())
  985. {
  986. carla_stderr("Failed to initialize RT client control");
  987. fShmAudioPool.clear();
  988. return false;
  989. }
  990. if (! fShmNonRtClientControl.initializeServer())
  991. {
  992. carla_stderr("Failed to initialize Non-RT client control");
  993. fShmRtClientControl.clear();
  994. fShmAudioPool.clear();
  995. return false;
  996. }
  997. if (! fShmNonRtServerControl.initializeServer())
  998. {
  999. carla_stderr("Failed to initialize Non-RT server control");
  1000. fShmNonRtClientControl.clear();
  1001. fShmRtClientControl.clear();
  1002. fShmAudioPool.clear();
  1003. return false;
  1004. }
  1005. // ---------------------------------------------------------------
  1006. // init bridge thread
  1007. {
  1008. char shmIdsStr[6*4+1];
  1009. carla_zeroChars(shmIdsStr, 6*4+1);
  1010. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1011. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1012. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1013. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1014. fBridgeThread.setData(shmIdsStr, label);
  1015. }
  1016. if (! restartBridgeThread())
  1017. return false;
  1018. // ---------------------------------------------------------------
  1019. // setup hints and options
  1020. // FIXME dryWet broken
  1021. pData->hints = PLUGIN_IS_BRIDGE | /*PLUGIN_CAN_DRYWET |*/ PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE | PLUGIN_NEEDS_FIXED_BUFFERS;
  1022. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  1023. //fInfo.optionsAvailable = optionAv;
  1024. // ---------------------------------------------------------------
  1025. // register client
  1026. if (pData->name == nullptr)
  1027. pData->name = pData->engine->getUniquePluginName("unknown");
  1028. pData->client = pData->engine->addClient(this);
  1029. if (pData->client == nullptr || ! pData->client->isOk())
  1030. {
  1031. pData->engine->setLastError("Failed to register plugin client");
  1032. return false;
  1033. }
  1034. return true;
  1035. }
  1036. private:
  1037. bool fInitiated;
  1038. bool fInitError;
  1039. bool fTimedOut;
  1040. bool fTimedError;
  1041. bool fProcCanceled;
  1042. uint fProcWaitTime;
  1043. int64_t fLastPingTime;
  1044. CarlaPluginJackThread fBridgeThread;
  1045. BridgeAudioPool fShmAudioPool;
  1046. BridgeRtClientControl fShmRtClientControl;
  1047. BridgeNonRtClientControl fShmNonRtClientControl;
  1048. BridgeNonRtServerControl fShmNonRtServerControl;
  1049. struct Info {
  1050. uint32_t aIns, aOuts;
  1051. uint32_t mIns, mOuts;
  1052. uint optionsAvailable;
  1053. CarlaString setupLabel;
  1054. std::vector<uint8_t> chunk;
  1055. Info()
  1056. : aIns(0),
  1057. aOuts(0),
  1058. mIns(0),
  1059. mOuts(0),
  1060. optionsAvailable(0),
  1061. setupLabel(),
  1062. chunk() {}
  1063. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1064. } fInfo;
  1065. void resizeAudioPool(const uint32_t bufferSize)
  1066. {
  1067. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, 0);
  1068. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1069. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1070. fShmRtClientControl.commitWrite();
  1071. waitForClient("resize-pool", 5000);
  1072. }
  1073. void waitForClient(const char* const action, const uint msecs)
  1074. {
  1075. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1076. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1077. if (fShmRtClientControl.waitForClient(msecs))
  1078. return;
  1079. fTimedOut = true;
  1080. carla_stderr("waitForClient(%s) timed out", action);
  1081. }
  1082. bool restartBridgeThread()
  1083. {
  1084. fInitiated = false;
  1085. fInitError = false;
  1086. fTimedError = false;
  1087. // reset memory
  1088. fProcCanceled = false;
  1089. fShmRtClientControl.data->procFlags = 0;
  1090. carla_zeroStruct(fShmRtClientControl.data->timeInfo);
  1091. carla_zeroBytes(fShmRtClientControl.data->midiOut, kBridgeRtClientDataMidiOutSize);
  1092. fShmRtClientControl.clearData();
  1093. fShmNonRtClientControl.clearData();
  1094. fShmNonRtServerControl.clearData();
  1095. // initial values
  1096. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientNull);
  1097. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1098. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1099. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1100. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientInitialSetup);
  1101. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1102. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1103. fShmNonRtClientControl.commitWrite();
  1104. if (fShmAudioPool.dataSize != 0)
  1105. {
  1106. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1107. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1108. fShmRtClientControl.commitWrite();
  1109. }
  1110. else
  1111. {
  1112. // testing dummy message
  1113. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1114. fShmRtClientControl.commitWrite();
  1115. }
  1116. fBridgeThread.startThread();
  1117. fLastPingTime = Time::currentTimeMillis();
  1118. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  1119. static bool sFirstInit = true;
  1120. int64_t timeoutEnd = 5000;
  1121. if (sFirstInit)
  1122. timeoutEnd *= 2;
  1123. sFirstInit = false;
  1124. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1125. for (; Time::currentTimeMillis() < fLastPingTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1126. {
  1127. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1128. if (needsEngineIdle)
  1129. pData->engine->idle();
  1130. idle();
  1131. if (fInitiated)
  1132. break;
  1133. if (pData->engine->isAboutToClose())
  1134. break;
  1135. carla_msleep(20);
  1136. }
  1137. fLastPingTime = -1;
  1138. if (fInitError || ! fInitiated)
  1139. {
  1140. fBridgeThread.stopThread(6000);
  1141. if (! fInitError)
  1142. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n"
  1143. "(or the plugin crashed on initialization?)");
  1144. return false;
  1145. }
  1146. return true;
  1147. }
  1148. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1149. };
  1150. CARLA_BACKEND_END_NAMESPACE
  1151. #endif // CARLA_OS_LINUX
  1152. // -------------------------------------------------------------------------------------------------------------------
  1153. CARLA_BACKEND_START_NAMESPACE
  1154. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1155. {
  1156. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label);
  1157. #ifdef CARLA_OS_LINUX
  1158. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1159. if (! plugin->init(init.filename, init.name, init.label))
  1160. {
  1161. delete plugin;
  1162. return nullptr;
  1163. }
  1164. return plugin;
  1165. #else
  1166. init.engine->setLastError("JACK Application support not available");
  1167. return nullptr;
  1168. #endif
  1169. }
  1170. CARLA_BACKEND_END_NAMESPACE
  1171. // -------------------------------------------------------------------------------------------------------------------