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.

1619 lines
56KB

  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 "CarlaBackendUtils.hpp"
  22. #include "CarlaBridgeUtils.hpp"
  23. #include "CarlaEngineUtils.hpp"
  24. #include "CarlaMathUtils.hpp"
  25. #include "CarlaShmUtils.hpp"
  26. #include "CarlaThread.hpp"
  27. #include "jackbridge/JackBridge.hpp"
  28. #include <ctime>
  29. // -------------------------------------------------------------------------------------------------------------------
  30. using juce::ChildProcess;
  31. using juce::File;
  32. using juce::ScopedPointer;
  33. using juce::String;
  34. using juce::StringArray;
  35. using juce::Time;
  36. CARLA_BACKEND_START_NAMESPACE
  37. // -------------------------------------------------------------------------------------------------------------------
  38. // Fallback data
  39. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  40. // -------------------------------------------------------------------------------------------------------------------
  41. class CarlaPluginJackThread : public CarlaThread
  42. {
  43. public:
  44. CarlaPluginJackThread(CarlaEngine* const engine, CarlaPlugin* const plugin) noexcept
  45. : CarlaThread("CarlaPluginJackThread"),
  46. kEngine(engine),
  47. kPlugin(plugin),
  48. fShmIds(),
  49. fProcess() {}
  50. void setData(const char* const shmIds) noexcept
  51. {
  52. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && shmIds[0] != '\0',);
  53. CARLA_SAFE_ASSERT(! isThreadRunning());
  54. fShmIds = shmIds;
  55. }
  56. uintptr_t getProcessID() const noexcept
  57. {
  58. CARLA_SAFE_ASSERT_RETURN(fProcess != nullptr, 0);
  59. return (uintptr_t)fProcess->getPID();
  60. }
  61. protected:
  62. void run()
  63. {
  64. if (fProcess == nullptr)
  65. {
  66. fProcess = new ChildProcess();
  67. }
  68. else if (fProcess->isRunning())
  69. {
  70. carla_stderr("CarlaPluginJackThread::run() - already running");
  71. }
  72. String name(kPlugin->getName());
  73. String filename(kPlugin->getFilename());
  74. if (name.isEmpty())
  75. name = "(none)";
  76. CARLA_SAFE_ASSERT_RETURN(filename.isNotEmpty(),);
  77. StringArray arguments;
  78. // binary
  79. arguments.addTokens(filename, true);
  80. bool started;
  81. {
  82. char strBuf[STR_MAX+1];
  83. strBuf[STR_MAX] = '\0';
  84. const EngineOptions& options(kEngine->getOptions());
  85. const ScopedEngineEnvironmentLocker _seel(kEngine);
  86. #ifdef CARLA_OS_LINUX
  87. const char* const oldPreload(std::getenv("LD_PRELOAD"));
  88. if (oldPreload != nullptr)
  89. ::unsetenv("LD_PRELOAD");
  90. #endif
  91. std::snprintf(strBuf, STR_MAX, P_UINTPTR, options.frontendWinId);
  92. carla_setenv("CARLA_FRONTEND_WIN_ID", strBuf);
  93. carla_setenv("CARLA_SHM_IDS", fShmIds.toRawUTF8());
  94. carla_setenv("LD_LIBRARY_PATH", "/home/falktx/Personal/FOSS/GIT/falkTX/Carla/bin/jack");
  95. started = fProcess->start(arguments);
  96. #ifdef CARLA_OS_LINUX
  97. if (oldPreload != nullptr)
  98. ::setenv("LD_PRELOAD", oldPreload, 1);
  99. ::unsetenv("LD_LIBRARY_PATH");
  100. #endif
  101. }
  102. if (! started)
  103. {
  104. carla_stdout("failed!");
  105. fProcess = nullptr;
  106. return;
  107. }
  108. for (; fProcess->isRunning() && ! shouldThreadExit();)
  109. carla_sleep(1);
  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. }
  136. fProcess = nullptr;
  137. }
  138. private:
  139. CarlaEngine* const kEngine;
  140. CarlaPlugin* const kPlugin;
  141. String fShmIds;
  142. ScopedPointer<ChildProcess> fProcess;
  143. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJackThread)
  144. };
  145. // -------------------------------------------------------------------------------------------------------------------
  146. class CarlaPluginJack : public CarlaPlugin
  147. {
  148. public:
  149. CarlaPluginJack(CarlaEngine* const engine, const uint id)
  150. : CarlaPlugin(engine, id),
  151. fInitiated(false),
  152. fInitError(false),
  153. fTimedOut(false),
  154. fTimedError(false),
  155. fProcWaitTime(0),
  156. fLastPongTime(-1),
  157. fBridgeThread(engine, this),
  158. fShmAudioPool(),
  159. fShmRtClientControl(),
  160. fShmNonRtClientControl(),
  161. fShmNonRtServerControl(),
  162. fInfo()
  163. {
  164. carla_debug("CarlaPluginJack::CarlaPluginJack(%p, %i, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  165. pData->hints |= PLUGIN_IS_BRIDGE;
  166. }
  167. ~CarlaPluginJack() override
  168. {
  169. carla_debug("CarlaPluginJack::~CarlaPluginJack()");
  170. // close UI
  171. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  172. pData->transientTryCounter = 0;
  173. pData->singleMutex.lock();
  174. pData->masterMutex.lock();
  175. if (pData->client != nullptr && pData->client->isActive())
  176. pData->client->deactivate();
  177. if (pData->active)
  178. {
  179. deactivate();
  180. pData->active = false;
  181. }
  182. if (fBridgeThread.isThreadRunning())
  183. {
  184. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientQuit);
  185. fShmNonRtClientControl.commitWrite();
  186. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientQuit);
  187. fShmRtClientControl.commitWrite();
  188. if (! fTimedOut)
  189. waitForClient("stopping", 3000);
  190. }
  191. fBridgeThread.stopThread(3000);
  192. fShmNonRtServerControl.clear();
  193. fShmNonRtClientControl.clear();
  194. fShmRtClientControl.clear();
  195. fShmAudioPool.clear();
  196. clearBuffers();
  197. fInfo.chunk.clear();
  198. }
  199. // -------------------------------------------------------------------
  200. // Information (base)
  201. PluginType getType() const noexcept override
  202. {
  203. return PLUGIN_JACK;
  204. }
  205. PluginCategory getCategory() const noexcept override
  206. {
  207. return fInfo.category;
  208. }
  209. // -------------------------------------------------------------------
  210. // Information (count)
  211. uint32_t getMidiInCount() const noexcept override
  212. {
  213. return fInfo.mIns;
  214. }
  215. uint32_t getMidiOutCount() const noexcept override
  216. {
  217. return fInfo.mOuts;
  218. }
  219. // -------------------------------------------------------------------
  220. // Information (current data)
  221. // -------------------------------------------------------------------
  222. // Information (per-plugin data)
  223. uint getOptionsAvailable() const noexcept override
  224. {
  225. return fInfo.optionsAvailable;
  226. }
  227. void getLabel(char* const strBuf) const noexcept override
  228. {
  229. std::strncpy(strBuf, fInfo.label, STR_MAX);
  230. }
  231. void getMaker(char* const strBuf) const noexcept override
  232. {
  233. nullStrBuf(strBuf);
  234. }
  235. void getCopyright(char* const strBuf) const noexcept override
  236. {
  237. nullStrBuf(strBuf);
  238. }
  239. void getRealName(char* const strBuf) const noexcept override
  240. {
  241. std::strncpy(strBuf, fInfo.name, STR_MAX);
  242. }
  243. // -------------------------------------------------------------------
  244. // Set data (state)
  245. // -------------------------------------------------------------------
  246. // Set data (internal stuff)
  247. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  248. {
  249. {
  250. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  251. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetOption);
  252. fShmNonRtClientControl.writeUInt(option);
  253. fShmNonRtClientControl.writeBool(yesNo);
  254. fShmNonRtClientControl.commitWrite();
  255. }
  256. CarlaPlugin::setOption(option, yesNo, sendCallback);
  257. }
  258. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  259. {
  260. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  261. {
  262. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  263. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetCtrlChannel);
  264. fShmNonRtClientControl.writeShort(channel);
  265. fShmNonRtClientControl.commitWrite();
  266. }
  267. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  268. }
  269. // -------------------------------------------------------------------
  270. // Set data (plugin-specific stuff)
  271. // -------------------------------------------------------------------
  272. // Set ui stuff
  273. void idle() override
  274. {
  275. if (fBridgeThread.isThreadRunning())
  276. {
  277. if (fInitiated && fTimedOut && pData->active)
  278. setActive(false, true, true);
  279. {
  280. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  281. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientPing);
  282. fShmNonRtClientControl.commitWrite();
  283. }
  284. try {
  285. handleNonRtData();
  286. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  287. }
  288. else if (fInitiated)
  289. {
  290. fTimedOut = true;
  291. fTimedError = true;
  292. fInitiated = false;
  293. pData->engine->callback(ENGINE_CALLBACK_PLUGIN_UNAVAILABLE, pData->id, 0, 0, 0.0f,
  294. "Plugin bridge has been stopped or crashed");
  295. }
  296. CarlaPlugin::idle();
  297. }
  298. // -------------------------------------------------------------------
  299. // Plugin state
  300. void reload() override
  301. {
  302. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  303. carla_debug("CarlaPluginJack::reload() - start");
  304. const EngineProcessMode processMode(pData->engine->getProccessMode());
  305. // Safely disable plugin for reload
  306. const ScopedDisabler sd(this);
  307. // cleanup of previous data
  308. pData->audioIn.clear();
  309. pData->audioOut.clear();
  310. pData->cvIn.clear();
  311. pData->cvOut.clear();
  312. pData->event.clear();
  313. bool needsCtrlIn, needsCtrlOut;
  314. needsCtrlIn = needsCtrlOut = false;
  315. if (fInfo.aIns > 0)
  316. {
  317. pData->audioIn.createNew(fInfo.aIns);
  318. }
  319. if (fInfo.aOuts > 0)
  320. {
  321. pData->audioOut.createNew(fInfo.aOuts);
  322. needsCtrlIn = true;
  323. }
  324. if (fInfo.cvIns > 0)
  325. {
  326. pData->cvIn.createNew(fInfo.cvIns);
  327. }
  328. if (fInfo.cvOuts > 0)
  329. {
  330. pData->cvOut.createNew(fInfo.cvOuts);
  331. }
  332. if (fInfo.mIns > 0)
  333. needsCtrlIn = true;
  334. if (fInfo.mOuts > 0)
  335. needsCtrlOut = true;
  336. const uint portNameSize(pData->engine->getMaxPortNameSize());
  337. CarlaString portName;
  338. // Audio Ins
  339. for (uint32_t j=0; j < fInfo.aIns; ++j)
  340. {
  341. portName.clear();
  342. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  343. {
  344. portName = pData->name;
  345. portName += ":";
  346. }
  347. if (fInfo.aInNames != nullptr && fInfo.aInNames[j] != nullptr)
  348. {
  349. portName += fInfo.aInNames[j];
  350. }
  351. else if (fInfo.aIns > 1)
  352. {
  353. portName += "input_";
  354. portName += CarlaString(j+1);
  355. }
  356. else
  357. portName += "input";
  358. portName.truncate(portNameSize);
  359. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  360. pData->audioIn.ports[j].rindex = j;
  361. }
  362. // Audio Outs
  363. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  364. {
  365. portName.clear();
  366. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  367. {
  368. portName = pData->name;
  369. portName += ":";
  370. }
  371. if (fInfo.aOutNames != nullptr && fInfo.aOutNames[j] != nullptr)
  372. {
  373. portName += fInfo.aOutNames[j];
  374. }
  375. else if (fInfo.aOuts > 1)
  376. {
  377. portName += "output_";
  378. portName += CarlaString(j+1);
  379. }
  380. else
  381. portName += "output";
  382. portName.truncate(portNameSize);
  383. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  384. pData->audioOut.ports[j].rindex = j;
  385. }
  386. // TODO - MIDI
  387. // TODO - CV
  388. if (needsCtrlIn)
  389. {
  390. portName.clear();
  391. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  392. {
  393. portName = pData->name;
  394. portName += ":";
  395. }
  396. portName += "event-in";
  397. portName.truncate(portNameSize);
  398. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  399. }
  400. if (needsCtrlOut)
  401. {
  402. portName.clear();
  403. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  404. {
  405. portName = pData->name;
  406. portName += ":";
  407. }
  408. portName += "event-out";
  409. portName.truncate(portNameSize);
  410. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  411. }
  412. // extra plugin hints
  413. pData->extraHints = 0x0;
  414. if (fInfo.mIns > 0)
  415. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  416. if (fInfo.mOuts > 0)
  417. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  418. if (fInfo.aIns <= 2 && fInfo.aOuts <= 2 && (fInfo.aIns == fInfo.aOuts || fInfo.aIns == 0 || fInfo.aOuts == 0))
  419. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  420. bufferSizeChanged(pData->engine->getBufferSize());
  421. reloadPrograms(true);
  422. carla_debug("CarlaPluginJack::reload() - end");
  423. }
  424. // -------------------------------------------------------------------
  425. // Plugin processing
  426. void activate() noexcept override
  427. {
  428. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  429. {
  430. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  431. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientActivate);
  432. fShmNonRtClientControl.commitWrite();
  433. }
  434. fTimedOut = false;
  435. try {
  436. waitForClient("activate", 2000);
  437. } CARLA_SAFE_EXCEPTION("activate - waitForClient");
  438. }
  439. void deactivate() noexcept override
  440. {
  441. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  442. {
  443. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  444. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientDeactivate);
  445. fShmNonRtClientControl.commitWrite();
  446. }
  447. fTimedOut = false;
  448. try {
  449. waitForClient("deactivate", 2000);
  450. } CARLA_SAFE_EXCEPTION("deactivate - waitForClient");
  451. }
  452. void process(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames) override
  453. {
  454. // --------------------------------------------------------------------------------------------------------
  455. // Check if active
  456. if (fTimedOut || fTimedError || ! pData->active)
  457. {
  458. // disable any output sound
  459. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  460. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  461. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  462. FloatVectorOperations::clear(cvOut[i], static_cast<int>(frames));
  463. return;
  464. }
  465. // --------------------------------------------------------------------------------------------------------
  466. // Check if needs reset
  467. if (pData->needsReset)
  468. {
  469. // TODO
  470. pData->needsReset = false;
  471. }
  472. // --------------------------------------------------------------------------------------------------------
  473. // Event Input
  474. if (pData->event.portIn != nullptr)
  475. {
  476. // ----------------------------------------------------------------------------------------------------
  477. // MIDI Input (External)
  478. if (pData->extNotes.mutex.tryLock())
  479. {
  480. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  481. {
  482. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  483. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  484. uint8_t data1, data2, data3;
  485. data1 = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  486. data2 = note.note;
  487. data3 = note.velo;
  488. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  489. fShmRtClientControl.writeUInt(0); // time
  490. fShmRtClientControl.writeByte(0); // port
  491. fShmRtClientControl.writeByte(3); // size
  492. fShmRtClientControl.writeByte(data1);
  493. fShmRtClientControl.writeByte(data2);
  494. fShmRtClientControl.writeByte(data3);
  495. fShmRtClientControl.commitWrite();
  496. }
  497. pData->extNotes.data.clear();
  498. pData->extNotes.mutex.unlock();
  499. } // End of MIDI Input (External)
  500. // ----------------------------------------------------------------------------------------------------
  501. // Event Input (System)
  502. bool allNotesOffSent = false;
  503. for (uint32_t i=0, numEvents=pData->event.portIn->getEventCount(); i < numEvents; ++i)
  504. {
  505. const EngineEvent& event(pData->event.portIn->getEvent(i));
  506. // Control change
  507. switch (event.type)
  508. {
  509. case kEngineEventTypeNull:
  510. break;
  511. case kEngineEventTypeControl: {
  512. const EngineControlEvent& ctrlEvent = event.ctrl;
  513. switch (ctrlEvent.type)
  514. {
  515. case kEngineControlEventTypeNull:
  516. break;
  517. case kEngineControlEventTypeParameter:
  518. // Control backend stuff
  519. if (event.channel == pData->ctrlChannel)
  520. {
  521. float value;
  522. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  523. {
  524. value = ctrlEvent.value;
  525. setDryWet(value, false, false);
  526. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  527. }
  528. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  529. {
  530. value = ctrlEvent.value*127.0f/100.0f;
  531. setVolume(value, false, false);
  532. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  533. }
  534. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  535. {
  536. float left, right;
  537. value = ctrlEvent.value/0.5f - 1.0f;
  538. if (value < 0.0f)
  539. {
  540. left = -1.0f;
  541. right = (value*2.0f)+1.0f;
  542. }
  543. else if (value > 0.0f)
  544. {
  545. left = (value*2.0f)-1.0f;
  546. right = 1.0f;
  547. }
  548. else
  549. {
  550. left = -1.0f;
  551. right = 1.0f;
  552. }
  553. setBalanceLeft(left, false, false);
  554. setBalanceRight(right, false, false);
  555. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  556. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  557. }
  558. }
  559. break;
  560. case kEngineControlEventTypeMidiBank:
  561. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  562. {
  563. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiBank);
  564. fShmRtClientControl.writeUInt(event.time);
  565. fShmRtClientControl.writeByte(event.channel);
  566. fShmRtClientControl.writeUShort(event.ctrl.param);
  567. fShmRtClientControl.commitWrite();
  568. }
  569. break;
  570. case kEngineControlEventTypeMidiProgram:
  571. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  572. {
  573. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventMidiProgram);
  574. fShmRtClientControl.writeUInt(event.time);
  575. fShmRtClientControl.writeByte(event.channel);
  576. fShmRtClientControl.writeUShort(event.ctrl.param);
  577. fShmRtClientControl.commitWrite();
  578. }
  579. break;
  580. case kEngineControlEventTypeAllSoundOff:
  581. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  582. {
  583. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllSoundOff);
  584. fShmRtClientControl.writeUInt(event.time);
  585. fShmRtClientControl.writeByte(event.channel);
  586. fShmRtClientControl.commitWrite();
  587. }
  588. break;
  589. case kEngineControlEventTypeAllNotesOff:
  590. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  591. {
  592. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  593. {
  594. allNotesOffSent = true;
  595. sendMidiAllNotesOffToCallback();
  596. }
  597. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientControlEventAllNotesOff);
  598. fShmRtClientControl.writeUInt(event.time);
  599. fShmRtClientControl.writeByte(event.channel);
  600. fShmRtClientControl.commitWrite();
  601. }
  602. break;
  603. } // switch (ctrlEvent.type)
  604. break;
  605. } // case kEngineEventTypeControl
  606. case kEngineEventTypeMidi: {
  607. const EngineMidiEvent& midiEvent(event.midi);
  608. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  609. continue;
  610. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  611. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  612. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  613. continue;
  614. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  615. continue;
  616. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  617. continue;
  618. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  619. continue;
  620. // Fix bad note-off
  621. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  622. status = MIDI_STATUS_NOTE_OFF;
  623. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientMidiEvent);
  624. fShmRtClientControl.writeUInt(event.time);
  625. fShmRtClientControl.writeByte(midiEvent.port);
  626. fShmRtClientControl.writeByte(midiEvent.size);
  627. fShmRtClientControl.writeByte(uint8_t(midiData[0] | (event.channel & MIDI_CHANNEL_BIT)));
  628. for (uint8_t j=1; j < midiEvent.size; ++j)
  629. fShmRtClientControl.writeByte(midiData[j]);
  630. fShmRtClientControl.commitWrite();
  631. if (status == MIDI_STATUS_NOTE_ON)
  632. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  633. else if (status == MIDI_STATUS_NOTE_OFF)
  634. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  635. } break;
  636. }
  637. }
  638. pData->postRtEvents.trySplice();
  639. } // End of Event Input
  640. if (! processSingle(audioIn, audioOut, cvIn, cvOut, frames))
  641. return;
  642. // --------------------------------------------------------------------------------------------------------
  643. // MIDI Output
  644. if (pData->event.portOut != nullptr)
  645. {
  646. uint8_t size;
  647. uint32_t time;
  648. const uint8_t* midiData(fShmRtClientControl.data->midiOut);
  649. for (std::size_t read=0; read<kBridgeRtClientDataMidiOutSize;)
  650. {
  651. size = *midiData;
  652. if (size == 0)
  653. break;
  654. // advance 8 bits (1 byte)
  655. midiData = midiData + 1;
  656. // get time as 32bit
  657. time = *(const uint32_t*)midiData;
  658. // advance 32 bits (4 bytes)
  659. midiData = midiData + 4;
  660. // store midi data advancing as needed
  661. uint8_t data[size];
  662. for (uint8_t j=0; j<size; ++j)
  663. data[j] = *midiData++;
  664. pData->event.portOut->writeMidiEvent(time, size, data);
  665. read += 1U /* size*/ + 4U /* time */ + size;
  666. }
  667. } // End of Control and MIDI Output
  668. }
  669. bool processSingle(const float** const audioIn, float** const audioOut,
  670. const float** const cvIn, float** const cvOut, const uint32_t frames)
  671. {
  672. CARLA_SAFE_ASSERT_RETURN(! fTimedError, false);
  673. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  674. if (pData->audioIn.count > 0)
  675. {
  676. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  677. }
  678. if (pData->audioOut.count > 0)
  679. {
  680. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  681. }
  682. if (pData->cvIn.count > 0)
  683. {
  684. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  685. }
  686. if (pData->cvOut.count > 0)
  687. {
  688. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  689. }
  690. const int iframes(static_cast<int>(frames));
  691. // --------------------------------------------------------------------------------------------------------
  692. // Try lock, silence otherwise
  693. if (pData->engine->isOffline())
  694. {
  695. pData->singleMutex.lock();
  696. }
  697. else if (! pData->singleMutex.tryLock())
  698. {
  699. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  700. FloatVectorOperations::clear(audioOut[i], iframes);
  701. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  702. FloatVectorOperations::clear(cvOut[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. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  741. FloatVectorOperations::copy(audioOut[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), iframes);
  742. // --------------------------------------------------------------------------------------------------------
  743. // Post-processing (dry/wet, volume and balance)
  744. {
  745. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && carla_isNotEqual(pData->postProc.volume, 1.0f);
  746. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  747. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  748. const bool isMono = (pData->audioIn.count == 1);
  749. bool isPair;
  750. float bufValue, oldBufLeft[doBalance ? frames : 1];
  751. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  752. {
  753. // Dry/Wet
  754. if (doDryWet)
  755. {
  756. const uint32_t c = isMono ? 0 : i;
  757. for (uint32_t k=0; k < frames; ++k)
  758. {
  759. bufValue = audioIn[c][k];
  760. audioOut[i][k] = (audioOut[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  761. }
  762. }
  763. // Balance
  764. if (doBalance)
  765. {
  766. isPair = (i % 2 == 0);
  767. if (isPair)
  768. {
  769. CARLA_ASSERT(i+1 < pData->audioOut.count);
  770. FloatVectorOperations::copy(oldBufLeft, audioOut[i], iframes);
  771. }
  772. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  773. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  774. for (uint32_t k=0; k < frames; ++k)
  775. {
  776. if (isPair)
  777. {
  778. // left
  779. audioOut[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  780. audioOut[i][k] += audioOut[i+1][k] * (1.0f - balRangeR);
  781. }
  782. else
  783. {
  784. // right
  785. audioOut[i][k] = audioOut[i][k] * balRangeR;
  786. audioOut[i][k] += oldBufLeft[k] * balRangeL;
  787. }
  788. }
  789. }
  790. // Volume (and buffer copy)
  791. if (doVolume)
  792. {
  793. for (uint32_t k=0; k < frames; ++k)
  794. audioOut[i][k] *= pData->postProc.volume;
  795. }
  796. }
  797. } // End of Post-processing
  798. // --------------------------------------------------------------------------------------------------------
  799. pData->singleMutex.unlock();
  800. return true;
  801. }
  802. void bufferSizeChanged(const uint32_t newBufferSize) override
  803. {
  804. resizeAudioPool(newBufferSize);
  805. {
  806. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  807. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetBufferSize);
  808. fShmNonRtClientControl.writeUInt(newBufferSize);
  809. fShmNonRtClientControl.commitWrite();
  810. }
  811. //fProcWaitTime = newBufferSize*1000/pData->engine->getSampleRate();
  812. fProcWaitTime = 1000;
  813. waitForClient("buffersize", 1000);
  814. }
  815. void sampleRateChanged(const double newSampleRate) override
  816. {
  817. {
  818. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  819. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetSampleRate);
  820. fShmNonRtClientControl.writeDouble(newSampleRate);
  821. fShmNonRtClientControl.commitWrite();
  822. }
  823. //fProcWaitTime = pData->engine->getBufferSize()*1000/newSampleRate;
  824. fProcWaitTime = 1000;
  825. waitForClient("samplerate", 1000);
  826. }
  827. void offlineModeChanged(const bool isOffline) override
  828. {
  829. {
  830. const CarlaMutexLocker _cml(fShmNonRtClientControl.mutex);
  831. fShmNonRtClientControl.writeOpcode(isOffline ? kPluginBridgeNonRtClientSetOffline : kPluginBridgeNonRtClientSetOnline);
  832. fShmNonRtClientControl.commitWrite();
  833. }
  834. waitForClient("offline", 1000);
  835. }
  836. // -------------------------------------------------------------------
  837. // Post-poned UI Stuff
  838. // -------------------------------------------------------------------
  839. void handleNonRtData()
  840. {
  841. for (; fShmNonRtServerControl.isDataAvailableForReading();)
  842. {
  843. const PluginBridgeNonRtServerOpcode opcode(fShmNonRtServerControl.readOpcode());
  844. //#ifdef DEBUG
  845. if (opcode != kPluginBridgeNonRtServerPong)
  846. {
  847. carla_debug("CarlaPluginJack::handleNonRtData() - got opcode: %s", PluginBridgeNonRtServerOpcode2str(opcode));
  848. }
  849. //#endif
  850. if (opcode != kPluginBridgeNonRtServerNull && fLastPongTime > 0)
  851. fLastPongTime = Time::currentTimeMillis();
  852. switch (opcode)
  853. {
  854. case kPluginBridgeNonRtServerNull:
  855. case kPluginBridgeNonRtServerPong:
  856. break;
  857. case kPluginBridgeNonRtServerPluginInfo1:
  858. // uint/category, uint/hints, uint/optionsAvailable, uint/optionsEnabled, long/uniqueId
  859. fShmNonRtServerControl.readUInt();
  860. fShmNonRtServerControl.readUInt();
  861. fShmNonRtServerControl.readUInt();
  862. fShmNonRtServerControl.readUInt();
  863. fShmNonRtServerControl.readLong();
  864. break;
  865. case kPluginBridgeNonRtServerPluginInfo2: {
  866. // uint/size, str[] (realName), uint/size, str[] (label), uint/size, str[] (maker), uint/size, str[] (copyright)
  867. // realName
  868. const uint32_t realNameSize(fShmNonRtServerControl.readUInt());
  869. char realName[realNameSize+1];
  870. carla_zeroChars(realName, realNameSize+1);
  871. fShmNonRtServerControl.readCustomData(realName, realNameSize);
  872. // label
  873. const uint32_t labelSize(fShmNonRtServerControl.readUInt());
  874. char label[labelSize+1];
  875. carla_zeroChars(label, labelSize+1);
  876. fShmNonRtServerControl.readCustomData(label, labelSize);
  877. // maker
  878. const uint32_t makerSize(fShmNonRtServerControl.readUInt());
  879. char maker[makerSize+1];
  880. carla_zeroChars(maker, makerSize+1);
  881. fShmNonRtServerControl.readCustomData(maker, makerSize);
  882. // copyright
  883. const uint32_t copyrightSize(fShmNonRtServerControl.readUInt());
  884. char copyright[copyrightSize+1];
  885. carla_zeroChars(copyright, copyrightSize+1);
  886. fShmNonRtServerControl.readCustomData(copyright, copyrightSize);
  887. fInfo.name = realName;
  888. fInfo.label = label;
  889. if (pData->name == nullptr)
  890. pData->name = pData->engine->getUniquePluginName(realName);
  891. } break;
  892. case kPluginBridgeNonRtServerAudioCount:
  893. // uint/ins, uint/outs
  894. fInfo.aIns = fShmNonRtServerControl.readUInt();
  895. fInfo.aOuts = fShmNonRtServerControl.readUInt();
  896. CARLA_SAFE_ASSERT(fInfo.aInNames == nullptr);
  897. CARLA_SAFE_ASSERT(fInfo.aOutNames == nullptr);
  898. if (fInfo.aIns > 0)
  899. {
  900. fInfo.aInNames = new const char*[fInfo.aIns];
  901. carla_zeroPointers(fInfo.aInNames, fInfo.aIns);
  902. }
  903. if (fInfo.aOuts > 0)
  904. {
  905. fInfo.aOutNames = new const char*[fInfo.aOuts];
  906. carla_zeroPointers(fInfo.aOutNames, fInfo.aOuts);
  907. }
  908. break;
  909. case kPluginBridgeNonRtServerMidiCount:
  910. // uint/ins, uint/outs
  911. fInfo.mIns = fShmNonRtServerControl.readUInt();
  912. fInfo.mOuts = fShmNonRtServerControl.readUInt();
  913. break;
  914. case kPluginBridgeNonRtServerCvCount:
  915. // uint/ins, uint/outs
  916. fInfo.cvIns = fShmNonRtServerControl.readUInt();
  917. fInfo.cvOuts = fShmNonRtServerControl.readUInt();
  918. break;
  919. case kPluginBridgeNonRtServerParameterCount:
  920. // uint/count
  921. fShmNonRtServerControl.readUInt();
  922. break;
  923. case kPluginBridgeNonRtServerProgramCount:
  924. // uint/count
  925. fShmNonRtServerControl.readUInt();
  926. break;
  927. case kPluginBridgeNonRtServerMidiProgramCount:
  928. // uint/count
  929. fShmNonRtServerControl.readUInt();
  930. break;
  931. case kPluginBridgeNonRtServerPortName: {
  932. // byte/type, uint/index, uint/size, str[] (name)
  933. const uint8_t portType = fShmNonRtServerControl.readByte();
  934. const uint32_t index = fShmNonRtServerControl.readUInt();
  935. // name
  936. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  937. char* const name = new char[nameSize+1];
  938. carla_zeroChars(name, nameSize+1);
  939. fShmNonRtServerControl.readCustomData(name, nameSize);
  940. CARLA_SAFE_ASSERT_BREAK(portType > kPluginBridgePortNull && portType < kPluginBridgePortTypeCount);
  941. switch (portType)
  942. {
  943. case kPluginBridgePortAudioInput:
  944. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aIns);
  945. fInfo.aInNames[index] = name;
  946. break;
  947. case kPluginBridgePortAudioOutput:
  948. CARLA_SAFE_ASSERT_BREAK(index < fInfo.aOuts);
  949. fInfo.aOutNames[index] = name;
  950. break;
  951. }
  952. } break;
  953. case kPluginBridgeNonRtServerParameterData1:
  954. // uint/index, int/rindex, uint/type, uint/hints, int/cc
  955. fShmNonRtServerControl.readUInt();
  956. fShmNonRtServerControl.readInt();
  957. fShmNonRtServerControl.readUInt();
  958. fShmNonRtServerControl.readUInt();
  959. fShmNonRtServerControl.readShort();
  960. break;
  961. case kPluginBridgeNonRtServerParameterData2:
  962. // uint/index, uint/size, str[] (name), uint/size, str[] (unit)
  963. fShmNonRtServerControl.readUInt();
  964. if (const uint32_t size = fShmNonRtServerControl.readUInt())
  965. {
  966. char name[size];
  967. fShmNonRtServerControl.readCustomData(name, size);
  968. }
  969. if (const uint32_t size = fShmNonRtServerControl.readUInt())
  970. {
  971. char symbol[size];
  972. fShmNonRtServerControl.readCustomData(symbol, size);
  973. }
  974. if (const uint32_t size = fShmNonRtServerControl.readUInt())
  975. {
  976. char unit[size];
  977. fShmNonRtServerControl.readCustomData(unit, size);
  978. }
  979. break;
  980. case kPluginBridgeNonRtServerParameterRanges:
  981. // uint/index, float/def, float/min, float/max, float/step, float/stepSmall, float/stepLarge
  982. fShmNonRtServerControl.readUInt();
  983. fShmNonRtServerControl.readFloat();
  984. fShmNonRtServerControl.readFloat();
  985. fShmNonRtServerControl.readFloat();
  986. fShmNonRtServerControl.readFloat();
  987. fShmNonRtServerControl.readFloat();
  988. fShmNonRtServerControl.readFloat();
  989. break;
  990. case kPluginBridgeNonRtServerParameterValue:
  991. // uint/index, float/value
  992. fShmNonRtServerControl.readUInt();
  993. fShmNonRtServerControl.readFloat();
  994. break;
  995. case kPluginBridgeNonRtServerParameterValue2:
  996. // uint/index, float/value
  997. fShmNonRtServerControl.readUInt();
  998. fShmNonRtServerControl.readFloat();
  999. break;
  1000. case kPluginBridgeNonRtServerDefaultValue:
  1001. // uint/index, float/value
  1002. fShmNonRtServerControl.readUInt();
  1003. fShmNonRtServerControl.readFloat();
  1004. break;
  1005. case kPluginBridgeNonRtServerCurrentProgram:
  1006. // int/index
  1007. fShmNonRtServerControl.readInt();
  1008. break;
  1009. case kPluginBridgeNonRtServerCurrentMidiProgram: {
  1010. // int/index
  1011. fShmNonRtServerControl.readInt();
  1012. } break;
  1013. case kPluginBridgeNonRtServerProgramName: {
  1014. // uint/index, uint/size, str[] (name)
  1015. fShmNonRtServerControl.readUInt();
  1016. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1017. char name[nameSize];
  1018. fShmNonRtServerControl.readCustomData(name, nameSize);
  1019. } break;
  1020. case kPluginBridgeNonRtServerMidiProgramData: {
  1021. // uint/index, uint/bank, uint/program, uint/size, str[] (name)
  1022. fShmNonRtServerControl.readUInt();
  1023. fShmNonRtServerControl.readUInt();
  1024. fShmNonRtServerControl.readUInt();
  1025. const uint32_t nameSize(fShmNonRtServerControl.readUInt());
  1026. char name[nameSize];
  1027. fShmNonRtServerControl.readCustomData(name, nameSize);
  1028. } break;
  1029. case kPluginBridgeNonRtServerSetCustomData: {
  1030. // uint/size, str[], uint/size, str[], uint/size, str[]
  1031. // type
  1032. const uint32_t typeSize(fShmNonRtServerControl.readUInt());
  1033. char type[typeSize];
  1034. fShmNonRtServerControl.readCustomData(type, typeSize);
  1035. // key
  1036. const uint32_t keySize(fShmNonRtServerControl.readUInt());
  1037. char key[keySize];
  1038. fShmNonRtServerControl.readCustomData(key, keySize);
  1039. // value
  1040. const uint32_t valueSize(fShmNonRtServerControl.readUInt());
  1041. char value[valueSize];
  1042. fShmNonRtServerControl.readCustomData(value, valueSize);
  1043. } break;
  1044. case kPluginBridgeNonRtServerSetChunkDataFile: {
  1045. // uint/size, str[] (filename)
  1046. const uint32_t chunkFilePathSize(fShmNonRtServerControl.readUInt());
  1047. char chunkFilePath[chunkFilePathSize];
  1048. fShmNonRtServerControl.readCustomData(chunkFilePath, chunkFilePathSize);
  1049. } break;
  1050. case kPluginBridgeNonRtServerSetLatency:
  1051. // uint
  1052. fShmNonRtServerControl.readUInt();
  1053. break;
  1054. case kPluginBridgeNonRtServerReady:
  1055. fInitiated = true;
  1056. break;
  1057. case kPluginBridgeNonRtServerSaved:
  1058. case kPluginBridgeNonRtServerUiClosed:
  1059. break;
  1060. case kPluginBridgeNonRtServerError: {
  1061. // error
  1062. const uint32_t errorSize(fShmNonRtServerControl.readUInt());
  1063. char error[errorSize+1];
  1064. carla_zeroChars(error, errorSize+1);
  1065. fShmNonRtServerControl.readCustomData(error, errorSize);
  1066. if (fInitiated)
  1067. {
  1068. pData->engine->callback(ENGINE_CALLBACK_ERROR, pData->id, 0, 0, 0.0f, error);
  1069. // just in case
  1070. pData->engine->setLastError(error);
  1071. fInitError = true;
  1072. }
  1073. else
  1074. {
  1075. pData->engine->setLastError(error);
  1076. fInitError = true;
  1077. fInitiated = true;
  1078. }
  1079. } break;
  1080. }
  1081. }
  1082. }
  1083. // -------------------------------------------------------------------
  1084. uintptr_t getUiBridgeProcessId() const noexcept override
  1085. {
  1086. return fBridgeThread.getProcessID();
  1087. }
  1088. // -------------------------------------------------------------------
  1089. bool init(const char* const filename, const char* const name)
  1090. {
  1091. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1092. // ---------------------------------------------------------------
  1093. // first checks
  1094. if (pData->client != nullptr)
  1095. {
  1096. pData->engine->setLastError("Plugin client is already registered");
  1097. return false;
  1098. }
  1099. // ---------------------------------------------------------------
  1100. // set info
  1101. if (name != nullptr && name[0] != '\0')
  1102. pData->name = pData->engine->getUniquePluginName(name);
  1103. if (filename != nullptr && filename[0] != '\0')
  1104. pData->filename = carla_strdup(filename);
  1105. else
  1106. pData->filename = carla_strdup("");
  1107. std::srand(static_cast<uint>(std::time(nullptr)));
  1108. // ---------------------------------------------------------------
  1109. // init sem/shm
  1110. if (! fShmAudioPool.initializeServer())
  1111. {
  1112. carla_stderr("Failed to initialize shared memory audio pool");
  1113. return false;
  1114. }
  1115. if (! fShmRtClientControl.initializeServer())
  1116. {
  1117. carla_stderr("Failed to initialize RT client control");
  1118. fShmAudioPool.clear();
  1119. return false;
  1120. }
  1121. if (! fShmNonRtClientControl.initializeServer())
  1122. {
  1123. carla_stderr("Failed to initialize Non-RT client control");
  1124. fShmRtClientControl.clear();
  1125. fShmAudioPool.clear();
  1126. return false;
  1127. }
  1128. if (! fShmNonRtServerControl.initializeServer())
  1129. {
  1130. carla_stderr("Failed to initialize Non-RT server control");
  1131. fShmNonRtClientControl.clear();
  1132. fShmRtClientControl.clear();
  1133. fShmAudioPool.clear();
  1134. return false;
  1135. }
  1136. // ---------------------------------------------------------------
  1137. // initial values
  1138. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientNull);
  1139. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeRtClientData)));
  1140. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtClientData)));
  1141. fShmNonRtClientControl.writeUInt(static_cast<uint32_t>(sizeof(BridgeNonRtServerData)));
  1142. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetBufferSize);
  1143. fShmNonRtClientControl.writeUInt(pData->engine->getBufferSize());
  1144. fShmNonRtClientControl.writeOpcode(kPluginBridgeNonRtClientSetSampleRate);
  1145. fShmNonRtClientControl.writeDouble(pData->engine->getSampleRate());
  1146. fShmNonRtClientControl.commitWrite();
  1147. // testing dummy message
  1148. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientNull);
  1149. fShmRtClientControl.commitWrite();
  1150. // init bridge thread
  1151. {
  1152. char shmIdsStr[6*4+1];
  1153. carla_zeroChars(shmIdsStr, 6*4+1);
  1154. std::strncpy(shmIdsStr+6*0, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1155. std::strncpy(shmIdsStr+6*1, &fShmRtClientControl.filename[fShmRtClientControl.filename.length()-6], 6);
  1156. std::strncpy(shmIdsStr+6*2, &fShmNonRtClientControl.filename[fShmNonRtClientControl.filename.length()-6], 6);
  1157. std::strncpy(shmIdsStr+6*3, &fShmNonRtServerControl.filename[fShmNonRtServerControl.filename.length()-6], 6);
  1158. fBridgeThread.setData(shmIdsStr);
  1159. fBridgeThread.startThread();
  1160. }
  1161. fInitiated = false;
  1162. fLastPongTime = Time::currentTimeMillis();
  1163. CARLA_SAFE_ASSERT(fLastPongTime > 0);
  1164. static bool sFirstInit = true;
  1165. int64_t timeoutEnd = 5000;
  1166. if (sFirstInit)
  1167. timeoutEnd *= 2;
  1168. sFirstInit = false;
  1169. const bool needsEngineIdle = pData->engine->getType() != kEngineTypePlugin;
  1170. for (; Time::currentTimeMillis() < fLastPongTime + timeoutEnd && fBridgeThread.isThreadRunning();)
  1171. {
  1172. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1173. if (needsEngineIdle)
  1174. pData->engine->idle();
  1175. idle();
  1176. if (fInitiated)
  1177. break;
  1178. if (pData->engine->isAboutToClose())
  1179. break;
  1180. carla_msleep(20);
  1181. }
  1182. fLastPongTime = -1;
  1183. if (fInitError || ! fInitiated)
  1184. {
  1185. fBridgeThread.stopThread(6000);
  1186. if (! fInitError)
  1187. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n(or the plugin crashed on initialization?)");
  1188. return false;
  1189. }
  1190. // ---------------------------------------------------------------
  1191. // register client
  1192. if (pData->name == nullptr)
  1193. pData->name = pData->engine->getUniquePluginName("unknown");
  1194. pData->client = pData->engine->addClient(this);
  1195. if (pData->client == nullptr || ! pData->client->isOk())
  1196. {
  1197. pData->engine->setLastError("Failed to register plugin client");
  1198. return false;
  1199. }
  1200. return true;
  1201. }
  1202. private:
  1203. bool fInitiated;
  1204. bool fInitError;
  1205. bool fTimedOut;
  1206. bool fTimedError;
  1207. uint fProcWaitTime;
  1208. int64_t fLastPongTime;
  1209. CarlaPluginJackThread fBridgeThread;
  1210. BridgeAudioPool fShmAudioPool;
  1211. BridgeRtClientControl fShmRtClientControl;
  1212. BridgeNonRtClientControl fShmNonRtClientControl;
  1213. BridgeNonRtServerControl fShmNonRtServerControl;
  1214. struct Info {
  1215. uint32_t aIns, aOuts;
  1216. uint32_t cvIns, cvOuts;
  1217. uint32_t mIns, mOuts;
  1218. PluginCategory category;
  1219. uint optionsAvailable;
  1220. CarlaString name;
  1221. CarlaString label;
  1222. const char** aInNames;
  1223. const char** aOutNames;
  1224. std::vector<uint8_t> chunk;
  1225. Info()
  1226. : aIns(0),
  1227. aOuts(0),
  1228. cvIns(0),
  1229. cvOuts(0),
  1230. mIns(0),
  1231. mOuts(0),
  1232. category(PLUGIN_CATEGORY_NONE),
  1233. optionsAvailable(0),
  1234. name(),
  1235. label(),
  1236. aInNames(nullptr),
  1237. aOutNames(nullptr),
  1238. chunk() {}
  1239. CARLA_DECLARE_NON_COPY_STRUCT(Info)
  1240. } fInfo;
  1241. void resizeAudioPool(const uint32_t bufferSize)
  1242. {
  1243. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts, fInfo.cvIns+fInfo.cvOuts);
  1244. fShmRtClientControl.writeOpcode(kPluginBridgeRtClientSetAudioPool);
  1245. fShmRtClientControl.writeULong(static_cast<uint64_t>(fShmAudioPool.dataSize));
  1246. fShmRtClientControl.commitWrite();
  1247. waitForClient("resize-pool", 5000);
  1248. }
  1249. void waitForClient(const char* const action, const uint msecs)
  1250. {
  1251. CARLA_SAFE_ASSERT_RETURN(! fTimedOut,);
  1252. CARLA_SAFE_ASSERT_RETURN(! fTimedError,);
  1253. if (fShmRtClientControl.waitForClient(msecs))
  1254. return;
  1255. fTimedOut = true;
  1256. carla_stderr("waitForClient(%s) timed out", action);
  1257. }
  1258. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginJack)
  1259. };
  1260. CARLA_BACKEND_END_NAMESPACE
  1261. // -------------------------------------------------------------------------------------------------------------------
  1262. CARLA_BACKEND_START_NAMESPACE
  1263. CarlaPlugin* CarlaPlugin::newJackApp(const Initializer& init)
  1264. {
  1265. carla_debug("CarlaPlugin::newJackApp({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label);
  1266. CarlaPluginJack* const plugin(new CarlaPluginJack(init.engine, init.id));
  1267. if (! plugin->init(init.filename, init.name))
  1268. {
  1269. delete plugin;
  1270. return nullptr;
  1271. }
  1272. return plugin;
  1273. }
  1274. CARLA_BACKEND_END_NAMESPACE
  1275. // -------------------------------------------------------------------------------------------------------------------