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.

1652 lines
59KB

  1. /*
  2. * Carla JACK API for external applications
  3. * Copyright (C) 2016-2022 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. #include "libjack.hpp"
  18. #include "CarlaThread.hpp"
  19. #include "CarlaJuceUtils.hpp"
  20. #include <signal.h>
  21. #include <sys/prctl.h>
  22. #include <sys/time.h>
  23. // ---------------------------------------------------------------------------------------------------------------------
  24. CARLA_BACKEND_START_NAMESPACE
  25. // ---------------------------------------------------------------------------------------------------------------------
  26. static int64_t getCurrentTimeMilliseconds() noexcept
  27. {
  28. struct timeval tv;
  29. gettimeofday (&tv, nullptr);
  30. return ((int64_t) tv.tv_sec) * 1000 + tv.tv_usec / 1000;
  31. }
  32. static int carla_interposed_callback(int, void*);
  33. // ---------------------------------------------------------------------------------------------------------------------
  34. class CarlaJackRealtimeThread : public CarlaThread
  35. {
  36. public:
  37. struct Callback {
  38. Callback() {}
  39. virtual ~Callback() {};
  40. virtual void runRealtimeThread() = 0;
  41. };
  42. CarlaJackRealtimeThread(Callback* const callback)
  43. : CarlaThread("CarlaJackRealtimeThread"),
  44. fCallback(callback) {}
  45. protected:
  46. void run() override
  47. {
  48. fCallback->runRealtimeThread();
  49. }
  50. private:
  51. Callback* const fCallback;
  52. CARLA_DECLARE_NON_COPYABLE(CarlaJackRealtimeThread)
  53. };
  54. // --------------------------------------------------------------------------------------------------------------------
  55. class CarlaJackNonRealtimeThread : public CarlaThread
  56. {
  57. public:
  58. struct Callback {
  59. Callback() {}
  60. virtual ~Callback() {};
  61. virtual void runNonRealtimeThread() = 0;
  62. };
  63. CarlaJackNonRealtimeThread(Callback* const callback)
  64. : CarlaThread("CarlaJackNonRealtimeThread"),
  65. fCallback(callback) {}
  66. protected:
  67. void run() override
  68. {
  69. fCallback->runNonRealtimeThread();
  70. }
  71. private:
  72. Callback* const fCallback;
  73. CARLA_DECLARE_NON_COPYABLE(CarlaJackNonRealtimeThread)
  74. };
  75. // ---------------------------------------------------------------------------------------------------------------------
  76. class CarlaJackAppClient : public CarlaJackRealtimeThread::Callback,
  77. public CarlaJackNonRealtimeThread::Callback
  78. {
  79. public:
  80. JackServerState fServer;
  81. LinkedList<JackClientState*> fClients;
  82. LinkedList<JackClientState*> fNewClients;
  83. CarlaJackAppClient()
  84. : fServer(this),
  85. fClients(),
  86. fNewClients(),
  87. fShmAudioPool(),
  88. fShmRtClientControl(),
  89. fShmNonRtClientControl(),
  90. fShmNonRtServerControl(),
  91. fAudioPoolCopy(nullptr),
  92. fAudioTmpBuf(nullptr),
  93. fDummyMidiInBuffer(true),
  94. fDummyMidiOutBuffer(false),
  95. fMidiInBuffers(nullptr),
  96. fMidiOutBuffers(nullptr),
  97. fInitialized(false),
  98. fIsOffline(false),
  99. fIsReady(false),
  100. fLastPingTime(-1),
  101. fSessionManager(0),
  102. fSetupHints(0),
  103. fRealtimeThread(this),
  104. fNonRealtimeThread(this),
  105. fRealtimeThreadMutex()
  106. #ifdef DEBUG
  107. ,leakDetector_CarlaJackAppClient()
  108. #endif
  109. {
  110. carla_debug("CarlaJackAppClient::CarlaJackAppClient() START");
  111. const char* const shmIds(std::getenv("CARLA_SHM_IDS"));
  112. CARLA_SAFE_ASSERT_INT2_RETURN(shmIds != nullptr && std::strlen(shmIds) == 6*4,
  113. shmIds != nullptr ? static_cast<int>(std::strlen(shmIds)) : -1, 6*4,);
  114. const char* const libjackSetup(std::getenv("CARLA_LIBJACK_SETUP"));
  115. CARLA_SAFE_ASSERT_INT_RETURN(libjackSetup != nullptr && std::strlen(libjackSetup) >= 6,
  116. libjackSetup != nullptr ? static_cast<int>(std::strlen(libjackSetup)) : -1,);
  117. // make sure we don't get loaded again
  118. carla_unsetenv("CARLA_SHM_IDS");
  119. // kill ourselves if main carla dies
  120. carla_terminateProcessOnParentExit(true);
  121. for (int i=4; --i >= 0;) {
  122. CARLA_SAFE_ASSERT_RETURN(libjackSetup[i] >= '0' && libjackSetup[i] <= '0'+64,);
  123. }
  124. CARLA_SAFE_ASSERT_RETURN(libjackSetup[4] >= '0' && libjackSetup[4] <= '0' + LIBJACK_SESSION_MANAGER_NSM,);
  125. CARLA_SAFE_ASSERT_RETURN(libjackSetup[5] >= '0' && libjackSetup[5] < '0'+0x4f,);
  126. std::memcpy(fBaseNameAudioPool, shmIds+6*0, 6);
  127. std::memcpy(fBaseNameRtClientControl, shmIds+6*1, 6);
  128. std::memcpy(fBaseNameNonRtClientControl, shmIds+6*2, 6);
  129. std::memcpy(fBaseNameNonRtServerControl, shmIds+6*3, 6);
  130. fBaseNameAudioPool[6] = '\0';
  131. fBaseNameRtClientControl[6] = '\0';
  132. fBaseNameNonRtClientControl[6] = '\0';
  133. fBaseNameNonRtServerControl[6] = '\0';
  134. fServer.numAudioIns = static_cast<uint8_t>(libjackSetup[0] - '0');
  135. fServer.numAudioOuts = static_cast<uint8_t>(libjackSetup[1] - '0');
  136. fServer.numMidiIns = static_cast<uint8_t>(libjackSetup[2] - '0');
  137. fServer.numMidiOuts = static_cast<uint8_t>(libjackSetup[3] - '0');
  138. fSessionManager = static_cast<uint>(libjackSetup[4] - '0');
  139. fSetupHints = static_cast<uint>(libjackSetup[5] - '0');
  140. if (fSetupHints & LIBJACK_FLAG_MIDI_OUTPUT_CHANNEL_MIXDOWN)
  141. fServer.numMidiOuts = 16;
  142. jack_carla_interposed_action(LIBJACK_INTERPOSER_ACTION_SET_HINTS_AND_CALLBACK,
  143. fSetupHints,
  144. (void*)carla_interposed_callback);
  145. jack_carla_interposed_action(LIBJACK_INTERPOSER_ACTION_SET_SESSION_MANAGER,
  146. fSessionManager,
  147. nullptr);
  148. fNonRealtimeThread.startThread(false);
  149. fInitialized = true;
  150. carla_debug("CarlaJackAppClient::CarlaJackAppClient() DONE");
  151. }
  152. ~CarlaJackAppClient() noexcept override
  153. {
  154. carla_debug("CarlaJackAppClient::~CarlaJackAppClient() START");
  155. fLastPingTime = -1;
  156. fNonRealtimeThread.stopThread(5000);
  157. {
  158. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  159. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  160. {
  161. JackClientState* const jclient(it.getValue(nullptr));
  162. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  163. delete jclient;
  164. }
  165. fClients.clear();
  166. fNewClients.clear();
  167. }
  168. clearSharedMemory();
  169. carla_debug("CarlaJackAppClient::~CarlaJackAppClient() DONE");
  170. }
  171. JackClientState* createClient(const char* const name)
  172. {
  173. if (! fInitialized)
  174. return nullptr;
  175. while (fNonRealtimeThread.isThreadRunning() && ! fIsReady)
  176. carla_sleep(1);
  177. return new JackClientState(fServer, name);
  178. }
  179. void destroyClient(JackClientState* const jclient)
  180. {
  181. {
  182. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  183. fClients.removeOne(jclient);
  184. }
  185. delete jclient;
  186. }
  187. bool activateClient(JackClientState* const jclient)
  188. {
  189. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  190. if (! fClients.append(jclient))
  191. return false;
  192. if (! fNewClients.append(jclient))
  193. {
  194. fClients.removeOne(jclient);
  195. return false;
  196. }
  197. jclient->activated = true;
  198. jclient->deactivated = false;
  199. return true;
  200. }
  201. bool deactivateClient(JackClientState* const jclient)
  202. {
  203. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  204. if (! fClients.removeOne(jclient))
  205. return false;
  206. jclient->activated = false;
  207. jclient->deactivated = true;
  208. return true;
  209. }
  210. const char* getClientNameFromUUID(const jack_uuid_t uuid) const noexcept
  211. {
  212. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  213. {
  214. JackClientState* const jclient(it.getValue(nullptr));
  215. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  216. if (jclient->uuid == uuid)
  217. return jclient->name;
  218. }
  219. return nullptr;
  220. }
  221. jack_uuid_t getUUIDForClientName(const char* const name) const noexcept
  222. {
  223. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  224. {
  225. JackClientState* const jclient(it.getValue(nullptr));
  226. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  227. if (std::strcmp(jclient->name, name) == 0)
  228. return jclient->uuid;
  229. }
  230. return JACK_UUID_EMPTY_INITIALIZER;
  231. }
  232. pthread_t getRealtimeThreadId() const noexcept
  233. {
  234. return (pthread_t)fRealtimeThread.getThreadId();
  235. }
  236. int handleInterposerCallback(const int cb_action, void* const ptr)
  237. {
  238. carla_debug("handleInterposerCallback(%o, %p)", cb_action, ptr);
  239. switch (cb_action)
  240. {
  241. case LIBJACK_INTERPOSER_CALLBACK_UI_HIDE: {
  242. const CarlaMutexLocker cml(fShmNonRtServerControl.mutex);
  243. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerUiClosed);
  244. fShmNonRtServerControl.commitWrite();
  245. break;
  246. }
  247. }
  248. return 0;
  249. // maybe unused
  250. (void)ptr;
  251. }
  252. // -------------------------------------------------------------------
  253. protected:
  254. void runRealtimeThread() override;
  255. void runNonRealtimeThread() override;
  256. private:
  257. bool initSharedMemmory();
  258. void clearSharedMemory() noexcept;
  259. bool handleRtData();
  260. bool handleNonRtData();
  261. BridgeAudioPool fShmAudioPool;
  262. BridgeRtClientControl fShmRtClientControl;
  263. BridgeNonRtClientControl fShmNonRtClientControl;
  264. BridgeNonRtServerControl fShmNonRtServerControl;
  265. float* fAudioPoolCopy;
  266. float* fAudioTmpBuf;
  267. JackMidiPortBufferDummy fDummyMidiInBuffer;
  268. JackMidiPortBufferDummy fDummyMidiOutBuffer;
  269. JackMidiPortBufferOnStack* fMidiInBuffers;
  270. JackMidiPortBufferOnStack* fMidiOutBuffers;
  271. char fBaseNameAudioPool[6+1];
  272. char fBaseNameRtClientControl[6+1];
  273. char fBaseNameNonRtClientControl[6+1];
  274. char fBaseNameNonRtServerControl[6+1];
  275. bool fInitialized;
  276. bool fIsOffline;
  277. volatile bool fIsReady;
  278. int64_t fLastPingTime;
  279. uint fSessionManager;
  280. uint fSetupHints;
  281. CarlaJackRealtimeThread fRealtimeThread;
  282. CarlaJackNonRealtimeThread fNonRealtimeThread;
  283. CarlaMutex fRealtimeThreadMutex;
  284. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaJackAppClient)
  285. };
  286. // ---------------------------------------------------------------------------------------------------------------------
  287. bool CarlaJackAppClient::initSharedMemmory()
  288. {
  289. if (! fShmAudioPool.attachClient(fBaseNameAudioPool))
  290. {
  291. carla_stderr("Failed to attach to audio pool shared memory");
  292. return false;
  293. }
  294. if (! fShmRtClientControl.attachClient(fBaseNameRtClientControl))
  295. {
  296. clearSharedMemory();
  297. carla_stderr("Failed to attach to rt client control shared memory");
  298. return false;
  299. }
  300. if (! fShmRtClientControl.mapData())
  301. {
  302. clearSharedMemory();
  303. carla_stderr("Failed to map rt client control shared memory");
  304. return false;
  305. }
  306. if (! fShmNonRtClientControl.attachClient(fBaseNameNonRtClientControl))
  307. {
  308. clearSharedMemory();
  309. carla_stderr("Failed to attach to non-rt client control shared memory");
  310. return false;
  311. }
  312. if (! fShmNonRtClientControl.mapData())
  313. {
  314. clearSharedMemory();
  315. carla_stderr("Failed to map non-rt control client shared memory");
  316. return false;
  317. }
  318. if (! fShmNonRtServerControl.attachClient(fBaseNameNonRtServerControl))
  319. {
  320. clearSharedMemory();
  321. carla_stderr("Failed to attach to non-rt server control shared memory");
  322. return false;
  323. }
  324. if (! fShmNonRtServerControl.mapData())
  325. {
  326. clearSharedMemory();
  327. carla_stderr("Failed to map non-rt control server shared memory");
  328. return false;
  329. }
  330. PluginBridgeNonRtClientOpcode opcode;
  331. opcode = fShmNonRtClientControl.readOpcode();
  332. CARLA_SAFE_ASSERT_RETURN(opcode == kPluginBridgeNonRtClientVersion, false);
  333. const uint32_t apiVersion = fShmNonRtClientControl.readUInt();
  334. CARLA_SAFE_ASSERT_RETURN(apiVersion == CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT, false);
  335. const uint32_t shmRtClientDataSize = fShmNonRtClientControl.readUInt();
  336. CARLA_SAFE_ASSERT_INT2(shmRtClientDataSize == sizeof(BridgeRtClientData), shmRtClientDataSize, sizeof(BridgeRtClientData));
  337. const uint32_t shmNonRtClientDataSize = fShmNonRtClientControl.readUInt();
  338. CARLA_SAFE_ASSERT_INT2(shmNonRtClientDataSize == sizeof(BridgeNonRtClientData), shmNonRtClientDataSize, sizeof(BridgeNonRtClientData));
  339. const uint32_t shmNonRtServerDataSize = fShmNonRtClientControl.readUInt();
  340. CARLA_SAFE_ASSERT_INT2(shmNonRtServerDataSize == sizeof(BridgeNonRtServerData), shmNonRtServerDataSize, sizeof(BridgeNonRtServerData));
  341. if (shmRtClientDataSize != sizeof(BridgeRtClientData) ||
  342. shmNonRtClientDataSize != sizeof(BridgeNonRtClientData) ||
  343. shmNonRtServerDataSize != sizeof(BridgeNonRtServerData))
  344. {
  345. carla_stderr2("CarlaJackAppClient: data size mismatch");
  346. return false;
  347. }
  348. opcode = fShmNonRtClientControl.readOpcode();
  349. CARLA_SAFE_ASSERT_RETURN(opcode == kPluginBridgeNonRtClientInitialSetup, false);
  350. fServer.bufferSize = fShmNonRtClientControl.readUInt();
  351. fServer.sampleRate = fShmNonRtClientControl.readDouble();
  352. if (fServer.bufferSize == 0 || carla_isZero(fServer.sampleRate))
  353. {
  354. carla_stderr2("CarlaJackAppClient: invalid empty state");
  355. return false;
  356. }
  357. fAudioTmpBuf = new float[fServer.bufferSize];
  358. carla_zeroFloats(fAudioTmpBuf, fServer.bufferSize);
  359. fLastPingTime = getCurrentTimeMilliseconds();
  360. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  361. {
  362. // tell backend we're live
  363. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  364. // ready!
  365. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerReady);
  366. fShmNonRtServerControl.commitWrite();
  367. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  368. }
  369. fIsReady = true;
  370. return true;
  371. }
  372. void CarlaJackAppClient::clearSharedMemory() noexcept
  373. {
  374. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  375. if (fAudioPoolCopy != nullptr)
  376. {
  377. delete[] fAudioPoolCopy;
  378. fAudioPoolCopy = nullptr;
  379. }
  380. if (fAudioTmpBuf != nullptr)
  381. {
  382. delete[] fAudioTmpBuf;
  383. fAudioTmpBuf = nullptr;
  384. }
  385. if (fMidiInBuffers != nullptr)
  386. {
  387. delete[] fMidiInBuffers;
  388. fMidiInBuffers = nullptr;
  389. }
  390. if (fMidiOutBuffers != nullptr)
  391. {
  392. delete[] fMidiOutBuffers;
  393. fMidiOutBuffers = nullptr;
  394. }
  395. fShmAudioPool.clear();
  396. fShmRtClientControl.clear();
  397. fShmNonRtClientControl.clear();
  398. fShmNonRtServerControl.clear();
  399. }
  400. bool CarlaJackAppClient::handleRtData()
  401. {
  402. if (fNewClients.count() != 0)
  403. {
  404. for (LinkedList<JackClientState*>::Itenerator it = fNewClients.begin2(); it.valid(); it.next())
  405. {
  406. JackClientState* const jclient(it.getValue(nullptr));
  407. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  408. if (jclient->threadInitCb != nullptr)
  409. jclient->threadInitCb(jclient->threadInitCbPtr);
  410. }
  411. fNewClients.clear();
  412. }
  413. const BridgeRtClientControl::WaitHelper helper(fShmRtClientControl);
  414. if (! helper.ok)
  415. return false;
  416. bool ret = false;
  417. for (; fShmRtClientControl.isDataAvailableForReading();)
  418. {
  419. const PluginBridgeRtClientOpcode opcode(fShmRtClientControl.readOpcode());
  420. #ifdef DEBUG
  421. if (opcode != kPluginBridgeRtClientProcess && opcode != kPluginBridgeRtClientMidiEvent) {
  422. carla_debug("CarlaJackAppClientRtThread::run() - got opcode: %s", PluginBridgeRtClientOpcode2str(opcode));
  423. }
  424. #endif
  425. switch (opcode)
  426. {
  427. case kPluginBridgeRtClientNull:
  428. break;
  429. case kPluginBridgeRtClientSetAudioPool: {
  430. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  431. if (fShmAudioPool.data != nullptr)
  432. {
  433. jackbridge_shm_unmap(fShmAudioPool.shm, fShmAudioPool.data);
  434. fShmAudioPool.data = nullptr;
  435. }
  436. if (fAudioPoolCopy != nullptr)
  437. {
  438. delete[] fAudioPoolCopy;
  439. fAudioPoolCopy = nullptr;
  440. }
  441. const uint64_t poolSize(fShmRtClientControl.readULong());
  442. CARLA_SAFE_ASSERT_BREAK(poolSize > 0);
  443. fShmAudioPool.data = (float*)jackbridge_shm_map(fShmAudioPool.shm, static_cast<size_t>(poolSize));
  444. fAudioPoolCopy = new float[poolSize];
  445. break;
  446. }
  447. case kPluginBridgeRtClientSetBufferSize:
  448. if (const uint32_t newBufferSize = fShmRtClientControl.readUInt())
  449. {
  450. if (fServer.bufferSize != newBufferSize)
  451. {
  452. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  453. fServer.bufferSize = newBufferSize;
  454. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  455. {
  456. JackClientState* const jclient(it.getValue(nullptr));
  457. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  458. if (jclient->bufferSizeCb != nullptr)
  459. jclient->bufferSizeCb(fServer.bufferSize, jclient->bufferSizeCbPtr);
  460. }
  461. delete[] fAudioTmpBuf;
  462. fAudioTmpBuf = new float[fServer.bufferSize];
  463. carla_zeroFloats(fAudioTmpBuf, fServer.bufferSize);
  464. }
  465. }
  466. break;
  467. case kPluginBridgeRtClientSetSampleRate: {
  468. const double newSampleRate = fShmRtClientControl.readDouble();
  469. if (carla_isNotZero(newSampleRate) && carla_isNotEqual(fServer.sampleRate, newSampleRate))
  470. {
  471. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  472. fServer.sampleRate = newSampleRate;
  473. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  474. {
  475. JackClientState* const jclient(it.getValue(nullptr));
  476. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  477. if (jclient->sampleRateCb != nullptr)
  478. jclient->sampleRateCb(static_cast<uint32_t>(fServer.sampleRate), jclient->sampleRateCbPtr);
  479. }
  480. }
  481. } break;
  482. case kPluginBridgeRtClientSetOnline: {
  483. const bool offline = fShmRtClientControl.readBool();
  484. if (fIsOffline != offline)
  485. {
  486. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  487. fIsOffline = offline;
  488. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  489. {
  490. JackClientState* const jclient(it.getValue(nullptr));
  491. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  492. if (jclient->freewheelCb != nullptr)
  493. jclient->freewheelCb(offline ? 1 : 0, jclient->freewheelCbPtr);
  494. }
  495. }
  496. } break;
  497. case kPluginBridgeRtClientControlEventParameter:
  498. break;
  499. case kPluginBridgeRtClientControlEventMidiBank: {
  500. const uint32_t time = fShmRtClientControl.readUInt();
  501. const uint8_t channel = fShmRtClientControl.readByte();
  502. const uint16_t value = fShmRtClientControl.readUShort();
  503. if (fServer.numMidiIns > 0 && fRealtimeThreadMutex.tryLock())
  504. {
  505. JackMidiPortBufferOnStack& midiPortBuf(fMidiInBuffers[0]);
  506. if (midiPortBuf.count+1U < JackMidiPortBufferBase::kMaxEventCount &&
  507. midiPortBuf.bufferPoolPos + 6U < JackMidiPortBufferBase::kBufferPoolSize)
  508. {
  509. jack_midi_event_t& ev1(midiPortBuf.events[midiPortBuf.count++]);
  510. ev1.time = time;
  511. ev1.size = 3;
  512. ev1.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  513. ev1.buffer[0] = jack_midi_data_t(MIDI_STATUS_CONTROL_CHANGE | (channel & MIDI_CHANNEL_BIT));
  514. ev1.buffer[1] = MIDI_CONTROL_BANK_SELECT;
  515. ev1.buffer[2] = 0;
  516. midiPortBuf.bufferPoolPos += 3;
  517. jack_midi_event_t& ev2(midiPortBuf.events[midiPortBuf.count++]);
  518. ev2.time = time;
  519. ev2.size = 3;
  520. ev2.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  521. ev2.buffer[0] = jack_midi_data_t(MIDI_STATUS_CONTROL_CHANGE | (channel & MIDI_CHANNEL_BIT));
  522. ev2.buffer[1] = MIDI_CONTROL_BANK_SELECT__LSB;
  523. ev2.buffer[2] = jack_midi_data_t(value);
  524. midiPortBuf.bufferPoolPos += 3;
  525. }
  526. fRealtimeThreadMutex.unlock(true);
  527. }
  528. break;
  529. }
  530. case kPluginBridgeRtClientControlEventMidiProgram: {
  531. const uint32_t time = fShmRtClientControl.readUInt();
  532. const uint8_t channel = fShmRtClientControl.readByte();
  533. const uint16_t value = fShmRtClientControl.readUShort();
  534. if (fServer.numMidiIns > 0 && fRealtimeThreadMutex.tryLock())
  535. {
  536. JackMidiPortBufferOnStack& midiPortBuf(fMidiInBuffers[0]);
  537. if (midiPortBuf.count < JackMidiPortBufferBase::kMaxEventCount &&
  538. midiPortBuf.bufferPoolPos + 2U < JackMidiPortBufferBase::kBufferPoolSize)
  539. {
  540. jack_midi_event_t& ev(midiPortBuf.events[midiPortBuf.count++]);
  541. ev.time = time;
  542. ev.size = 2;
  543. ev.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  544. ev.buffer[0] = jack_midi_data_t(MIDI_STATUS_PROGRAM_CHANGE | (channel & MIDI_CHANNEL_BIT));
  545. ev.buffer[1] = jack_midi_data_t(value);
  546. midiPortBuf.bufferPoolPos += 2;
  547. }
  548. fRealtimeThreadMutex.unlock(true);
  549. }
  550. break;
  551. }
  552. case kPluginBridgeRtClientControlEventAllSoundOff: {
  553. const uint32_t time = fShmRtClientControl.readUInt();
  554. const uint8_t channel = fShmRtClientControl.readByte();
  555. if (fServer.numMidiIns > 0 && fRealtimeThreadMutex.tryLock())
  556. {
  557. JackMidiPortBufferOnStack& midiPortBuf(fMidiInBuffers[0]);
  558. if (midiPortBuf.count < JackMidiPortBufferBase::kMaxEventCount &&
  559. midiPortBuf.bufferPoolPos + 3U < JackMidiPortBufferBase::kBufferPoolSize)
  560. {
  561. jack_midi_event_t& ev(midiPortBuf.events[midiPortBuf.count++]);
  562. ev.time = time;
  563. ev.size = 3;
  564. ev.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  565. ev.buffer[0] = jack_midi_data_t(MIDI_STATUS_CONTROL_CHANGE | (channel & MIDI_CHANNEL_BIT));
  566. ev.buffer[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  567. ev.buffer[2] = 0;
  568. midiPortBuf.bufferPoolPos += 3;
  569. }
  570. fRealtimeThreadMutex.unlock(true);
  571. }
  572. break;
  573. }
  574. case kPluginBridgeRtClientControlEventAllNotesOff: {
  575. const uint32_t time = fShmRtClientControl.readUInt();
  576. const uint8_t channel = fShmRtClientControl.readByte();
  577. if (fServer.numMidiIns > 0 && fRealtimeThreadMutex.tryLock())
  578. {
  579. JackMidiPortBufferOnStack& midiPortBuf(fMidiInBuffers[0]);
  580. if (midiPortBuf.count < JackMidiPortBufferBase::kMaxEventCount &&
  581. midiPortBuf.bufferPoolPos + 3U < JackMidiPortBufferBase::kBufferPoolSize)
  582. {
  583. jack_midi_event_t& ev(midiPortBuf.events[midiPortBuf.count++]);
  584. ev.time = time;
  585. ev.size = 3;
  586. ev.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  587. ev.buffer[0] = jack_midi_data_t(MIDI_STATUS_CONTROL_CHANGE | (channel & MIDI_CHANNEL_BIT));
  588. ev.buffer[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  589. ev.buffer[2] = 0;
  590. midiPortBuf.bufferPoolPos += 3;
  591. }
  592. fRealtimeThreadMutex.unlock(true);
  593. }
  594. break;
  595. }
  596. case kPluginBridgeRtClientMidiEvent: {
  597. const uint32_t time = fShmRtClientControl.readUInt();
  598. const uint8_t port = fShmRtClientControl.readByte();
  599. const uint8_t size = fShmRtClientControl.readByte();
  600. CARLA_SAFE_ASSERT_BREAK(size > 0);
  601. if (port >= fServer.numMidiIns || size > JackMidiPortBufferBase::kMaxEventSize || ! fRealtimeThreadMutex.tryLock())
  602. {
  603. for (uint8_t i=0; i<size; ++i)
  604. fShmRtClientControl.readByte();
  605. break;
  606. }
  607. JackMidiPortBufferOnStack& midiPortBuf(fMidiInBuffers[port]);
  608. if (midiPortBuf.count < JackMidiPortBufferBase::kMaxEventCount &&
  609. midiPortBuf.bufferPoolPos + size < JackMidiPortBufferBase::kBufferPoolSize)
  610. {
  611. jack_midi_event_t& ev(midiPortBuf.events[midiPortBuf.count++]);
  612. ev.time = time;
  613. ev.size = size;
  614. ev.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  615. midiPortBuf.bufferPoolPos += size;
  616. for (uint8_t i=0; i<size; ++i)
  617. ev.buffer[i] = fShmRtClientControl.readByte();
  618. }
  619. fRealtimeThreadMutex.unlock(true);
  620. break;
  621. }
  622. case kPluginBridgeRtClientProcess: {
  623. const uint32_t frames(fShmRtClientControl.readUInt());
  624. CARLA_SAFE_ASSERT_UINT2_BREAK(frames == fServer.bufferSize, frames, fServer.bufferSize);
  625. // TODO tell client of xrun in case buffersize does not match
  626. const CarlaMutexTryLocker cmtl(fRealtimeThreadMutex, fIsOffline);
  627. if (cmtl.wasLocked())
  628. {
  629. CARLA_SAFE_ASSERT_BREAK(fShmAudioPool.data != nullptr);
  630. // mixdown is default, do buffer addition (for multiple clients) if requested
  631. const bool doBufferAddition = fSetupHints & LIBJACK_FLAG_AUDIO_BUFFERS_ADDITION;
  632. // mixdown midi outputs based on channel if requested
  633. const bool doMidiChanMixdown = fSetupHints & LIBJACK_FLAG_MIDI_OUTPUT_CHANNEL_MIXDOWN;
  634. // location to start of audio outputs (shm buffer)
  635. float* const fdataRealOuts = fShmAudioPool.data+(fServer.bufferSize*fServer.numAudioIns);
  636. if (doBufferAddition && fServer.numAudioOuts > 0)
  637. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  638. if (! fClients.isEmpty())
  639. {
  640. // save transport for all clients
  641. const BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  642. const bool transportChanged = fServer.playing != bridgeTimeInfo.playing ||
  643. (bridgeTimeInfo.playing && fServer.position.frame + frames != bridgeTimeInfo.frame);
  644. fServer.playing = bridgeTimeInfo.playing;
  645. fServer.position.frame = static_cast<jack_nframes_t>(bridgeTimeInfo.frame);
  646. fServer.position.usecs = bridgeTimeInfo.usecs;
  647. fServer.position.frame_rate = static_cast<jack_nframes_t>(fServer.sampleRate);
  648. if (bridgeTimeInfo.validFlags & kPluginBridgeTimeInfoValidBBT)
  649. {
  650. fServer.position.bar = bridgeTimeInfo.bar;
  651. fServer.position.beat = bridgeTimeInfo.beat;
  652. fServer.position.tick = static_cast<int32_t>(bridgeTimeInfo.tick + 0.5);
  653. fServer.position.beats_per_bar = bridgeTimeInfo.beatsPerBar;
  654. fServer.position.beat_type = bridgeTimeInfo.beatType;
  655. fServer.position.ticks_per_beat = bridgeTimeInfo.ticksPerBeat;
  656. fServer.position.beats_per_minute = bridgeTimeInfo.beatsPerMinute;
  657. fServer.position.bar_start_tick = bridgeTimeInfo.barStartTick;
  658. #ifdef JACK_TICK_DOUBLE
  659. fServer.position.tick_double = bridgeTimeInfo.tick;
  660. fServer.position.valid = static_cast<jack_position_bits_t>(JackPositionBBT|JackTickDouble);
  661. #else
  662. fServer.position.valid = JackPositionBBT;
  663. #endif
  664. }
  665. else
  666. {
  667. fServer.position.valid = static_cast<jack_position_bits_t>(0x0);
  668. }
  669. int numClientOutputsProcessed = 0;
  670. // now go through each client
  671. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  672. {
  673. JackClientState* const jclient(it.getValue(nullptr));
  674. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  675. const CarlaMutexTryLocker cmtl2(jclient->mutex, fIsOffline);
  676. // check if we can process
  677. if (cmtl2.wasNotLocked() || jclient->processCb == nullptr || ! jclient->activated)
  678. {
  679. if (fServer.numAudioOuts > 0)
  680. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  681. if (jclient->deactivated)
  682. fShmRtClientControl.data->procFlags = 1;
  683. }
  684. else
  685. {
  686. // report transport sync changes if needed
  687. if (transportChanged && jclient->syncCb != nullptr)
  688. {
  689. jclient->syncCb(fServer.playing ? JackTransportRolling : JackTransportStopped,
  690. &fServer.position,
  691. jclient->syncCbPtr);
  692. }
  693. uint8_t i;
  694. // direct access to shm buffer, used only for inputs
  695. float* fdataReal = fShmAudioPool.data;
  696. // safe temp location for output, mixed down to shm buffer later on
  697. float* fdataCopy = fAudioPoolCopy;
  698. // wherever we're using fAudioTmpBuf
  699. bool needsTmpBufClear = false;
  700. // set audio inputs
  701. i = 0;
  702. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->audioIns.begin2(); it2.valid(); it2.next())
  703. {
  704. JackPortState* const jport = it2.getValue(nullptr);
  705. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  706. if (i++ < fServer.numAudioIns)
  707. {
  708. if (numClientOutputsProcessed == 0 || ! doBufferAddition)
  709. jport->buffer = fdataReal;
  710. else
  711. jport->buffer = fdataRealOuts + (i*fServer.bufferSize);
  712. fdataReal += fServer.bufferSize;
  713. fdataCopy += fServer.bufferSize;
  714. }
  715. else
  716. {
  717. jport->buffer = fAudioTmpBuf;
  718. needsTmpBufClear = true;
  719. }
  720. }
  721. if (i < fServer.numAudioIns)
  722. {
  723. const std::size_t remainingBufferSize = fServer.bufferSize * static_cast<uint8_t>(fServer.numAudioIns - i);
  724. //fdataReal += remainingBufferSize;
  725. fdataCopy += remainingBufferSize;
  726. }
  727. // location to start of audio outputs
  728. float* const fdataCopyOuts = fdataCopy;
  729. // set audio outputs
  730. i = 0;
  731. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->audioOuts.begin2(); it2.valid(); it2.next())
  732. {
  733. JackPortState* const jport = it2.getValue(nullptr);
  734. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  735. if (i++ < fServer.numAudioOuts)
  736. {
  737. jport->buffer = fdataCopy;
  738. fdataCopy += fServer.bufferSize;
  739. }
  740. else
  741. {
  742. jport->buffer = fAudioTmpBuf;
  743. needsTmpBufClear = true;
  744. }
  745. }
  746. if (i < fServer.numAudioOuts)
  747. {
  748. const std::size_t remainingBufferSize = fServer.bufferSize * static_cast<uint8_t>(fServer.numAudioOuts - i);
  749. carla_zeroFloats(fdataCopy, remainingBufferSize);
  750. //fdataCopy += remainingBufferSize;
  751. }
  752. // set midi inputs
  753. i = 0;
  754. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->midiIns.begin2(); it2.valid(); it2.next())
  755. {
  756. JackPortState* const jport = it2.getValue(nullptr);
  757. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  758. if (i++ < fServer.numMidiIns)
  759. jport->buffer = &fMidiInBuffers[i-1];
  760. else
  761. jport->buffer = &fDummyMidiInBuffer;
  762. }
  763. // set midi outputs
  764. i = 0;
  765. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->midiOuts.begin2(); it2.valid(); it2.next())
  766. {
  767. JackPortState* const jport = it2.getValue(nullptr);
  768. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  769. if (i++ < fServer.numMidiOuts)
  770. jport->buffer = &fMidiOutBuffers[i-1];
  771. else
  772. jport->buffer = &fDummyMidiOutBuffer;
  773. }
  774. if (needsTmpBufClear)
  775. carla_zeroFloats(fAudioTmpBuf, fServer.bufferSize);
  776. jclient->processCb(fServer.bufferSize, jclient->processCbPtr);
  777. if (fServer.numAudioOuts > 0)
  778. {
  779. if (++numClientOutputsProcessed == 1)
  780. {
  781. // first client, we can copy stuff over
  782. carla_copyFloats(fdataRealOuts, fdataCopyOuts,
  783. fServer.bufferSize*fServer.numAudioOuts);
  784. }
  785. else
  786. {
  787. // subsequent clients, add data (then divide by number of clients later on)
  788. carla_add(fdataRealOuts, fdataCopyOuts,
  789. fServer.bufferSize*fServer.numAudioOuts);
  790. if (doBufferAddition)
  791. {
  792. // for more than 1 client addition, we need to divide buffers now
  793. carla_multiply(fdataRealOuts,
  794. 1.0f/static_cast<float>(numClientOutputsProcessed),
  795. fServer.bufferSize*fServer.numAudioOuts);
  796. }
  797. }
  798. if (jclient->audioOuts.count() == 1 && fServer.numAudioOuts > 1)
  799. {
  800. for (uint8_t j=1; j<fServer.numAudioOuts; ++j)
  801. {
  802. carla_copyFloats(fdataRealOuts+(fServer.bufferSize*j),
  803. fdataCopyOuts,
  804. fServer.bufferSize);
  805. }
  806. }
  807. }
  808. }
  809. }
  810. if (numClientOutputsProcessed > 1 && ! doBufferAddition)
  811. {
  812. // more than 1 client active, need to divide buffers
  813. carla_multiply(fdataRealOuts,
  814. 1.0f/static_cast<float>(numClientOutputsProcessed),
  815. fServer.bufferSize*fServer.numAudioOuts);
  816. }
  817. }
  818. // fClients.isEmpty()
  819. else if (fServer.numAudioOuts > 0)
  820. {
  821. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  822. }
  823. for (uint8_t i=0; i<fServer.numMidiIns; ++i)
  824. {
  825. fMidiInBuffers[i].count = 0;
  826. fMidiInBuffers[i].bufferPoolPos = 0;
  827. }
  828. if (fServer.numMidiOuts > 0)
  829. {
  830. uint8_t* midiData = fShmRtClientControl.data->midiOut;
  831. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  832. std::size_t curMidiDataPos = 0;
  833. for (uint8_t i=0; i<fServer.numMidiOuts; ++i)
  834. {
  835. JackMidiPortBufferOnStack& midiPortBuf(fMidiOutBuffers[i]);
  836. for (uint16_t j=0; j<midiPortBuf.count; ++j)
  837. {
  838. jack_midi_event_t& jmevent(midiPortBuf.events[j]);
  839. if (curMidiDataPos + kBridgeBaseMidiOutHeaderSize + jmevent.size >= kBridgeRtClientDataMidiOutSize)
  840. break;
  841. if (doMidiChanMixdown && MIDI_IS_CHANNEL_MESSAGE(jmevent.buffer[0]))
  842. jmevent.buffer[0] = static_cast<jack_midi_data_t>(
  843. (jmevent.buffer[0] & MIDI_STATUS_BIT) | (i & MIDI_CHANNEL_BIT));
  844. // set time
  845. *(uint32_t*)midiData = jmevent.time;
  846. midiData += 4;
  847. // set port
  848. *midiData++ = doMidiChanMixdown ? 0 : i;
  849. // set size
  850. *midiData++ = static_cast<uint8_t>(jmevent.size);
  851. // set data
  852. std::memcpy(midiData, jmevent.buffer, jmevent.size);
  853. midiData += jmevent.size;
  854. curMidiDataPos += kBridgeBaseMidiOutHeaderSize + jmevent.size;
  855. }
  856. }
  857. // make last event null, so server stops when reaching it
  858. if (curMidiDataPos != 0 &&
  859. curMidiDataPos + kBridgeBaseMidiOutHeaderSize < kBridgeRtClientDataMidiOutSize)
  860. {
  861. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  862. // sort events in case of mixdown
  863. if (doMidiChanMixdown)
  864. {
  865. uint32_t time;
  866. uint8_t size, *midiDataPtr;
  867. uint8_t tmp[kBridgeBaseMidiOutHeaderSize + JackMidiPortBufferBase::kMaxEventSize];
  868. bool wasSorted = true;
  869. for (; wasSorted;)
  870. {
  871. midiDataPtr = fShmRtClientControl.data->midiOut;
  872. uint8_t* prevData = midiDataPtr;
  873. uint32_t prevTime = *(uint32_t*)midiDataPtr;
  874. uint8_t prevSize = *(midiDataPtr + 5);
  875. wasSorted = false;
  876. for (;;)
  877. {
  878. time = *(uint32_t*)midiDataPtr;
  879. size = *(midiDataPtr + 5); // time and port
  880. if (size == 0)
  881. break;
  882. if (prevTime > time)
  883. {
  884. // copy previous data to a temporary place
  885. std::memcpy(tmp, prevData, kBridgeBaseMidiOutHeaderSize + prevSize);
  886. // override previous data with new one (shifting left)
  887. std::memcpy(prevData, midiDataPtr, kBridgeBaseMidiOutHeaderSize + size);
  888. // override new data with old one
  889. std::memcpy(midiDataPtr, tmp, kBridgeBaseMidiOutHeaderSize + prevSize);
  890. // done swapping, flag it
  891. wasSorted = true;
  892. }
  893. prevTime = time;
  894. prevSize = size;
  895. prevData = midiDataPtr;
  896. midiDataPtr += 6 + size;
  897. }
  898. }
  899. }
  900. }
  901. }
  902. }
  903. else
  904. {
  905. carla_stderr2("CarlaJackAppClient: fRealtimeThreadMutex tryLock failed");
  906. }
  907. fServer.monotonic_frame += frames;
  908. break;
  909. }
  910. case kPluginBridgeRtClientQuit:
  911. ret = true;
  912. break;
  913. }
  914. #ifdef DEBUG
  915. if (opcode != kPluginBridgeRtClientProcess && opcode != kPluginBridgeRtClientMidiEvent) {
  916. carla_debug("CarlaJackAppClientRtThread::run() - opcode %s done", PluginBridgeRtClientOpcode2str(opcode));
  917. }
  918. #endif
  919. }
  920. return ret;
  921. }
  922. bool CarlaJackAppClient::handleNonRtData()
  923. {
  924. bool ret = false;
  925. for (; fShmNonRtClientControl.isDataAvailableForReading();)
  926. {
  927. const PluginBridgeNonRtClientOpcode opcode(fShmNonRtClientControl.readOpcode());
  928. #ifdef DEBUG
  929. if (opcode != kPluginBridgeNonRtClientPing) {
  930. carla_debug("CarlaJackAppClient::handleNonRtData() - got opcode: %s", PluginBridgeNonRtClientOpcode2str(opcode));
  931. }
  932. #endif
  933. if (opcode != kPluginBridgeNonRtClientNull && opcode != kPluginBridgeNonRtClientPingOnOff && fLastPingTime > 0)
  934. fLastPingTime = getCurrentTimeMilliseconds();
  935. switch (opcode)
  936. {
  937. case kPluginBridgeNonRtClientNull:
  938. break;
  939. case kPluginBridgeNonRtClientVersion: {
  940. const uint apiVersion = fShmNonRtServerControl.readUInt();
  941. CARLA_SAFE_ASSERT_UINT2(apiVersion == CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT,
  942. apiVersion, CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  943. } break;
  944. case kPluginBridgeNonRtClientPing: {
  945. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  946. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPong);
  947. fShmNonRtServerControl.commitWrite();
  948. } break;
  949. case kPluginBridgeNonRtClientPingOnOff: {
  950. const uint32_t onOff(fShmNonRtClientControl.readBool());
  951. fLastPingTime = onOff ? getCurrentTimeMilliseconds() : -1;
  952. } break;
  953. case kPluginBridgeNonRtClientActivate:
  954. case kPluginBridgeNonRtClientDeactivate:
  955. break;
  956. case kPluginBridgeNonRtClientInitialSetup:
  957. // should never happen!!
  958. fShmNonRtServerControl.readUInt();
  959. fShmNonRtServerControl.readDouble();
  960. break;
  961. case kPluginBridgeNonRtClientSetParameterValue:
  962. case kPluginBridgeNonRtClientSetParameterMidiChannel:
  963. case kPluginBridgeNonRtClientSetParameterMappedControlIndex:
  964. case kPluginBridgeNonRtClientSetParameterMappedRange:
  965. case kPluginBridgeNonRtClientSetProgram:
  966. case kPluginBridgeNonRtClientSetMidiProgram:
  967. case kPluginBridgeNonRtClientSetCustomData:
  968. case kPluginBridgeNonRtClientSetChunkDataFile:
  969. case kPluginBridgeNonRtClientSetWindowTitle:
  970. break;
  971. case kPluginBridgeNonRtClientSetOption:
  972. fShmNonRtClientControl.readUInt();
  973. fShmNonRtClientControl.readBool();
  974. break;
  975. case kPluginBridgeNonRtClientSetOptions:
  976. fShmNonRtClientControl.readUInt();
  977. break;
  978. case kPluginBridgeNonRtClientSetCtrlChannel:
  979. fShmNonRtClientControl.readShort();
  980. break;
  981. case kPluginBridgeNonRtClientGetParameterText:
  982. fShmNonRtClientControl.readUInt();
  983. break;
  984. case kPluginBridgeNonRtClientPrepareForSave:
  985. {
  986. if (fSessionManager == LIBJACK_SESSION_MANAGER_AUTO && std::getenv("NSM_URL") == nullptr)
  987. {
  988. struct sigaction sig;
  989. carla_zeroStruct(sig);
  990. sigaction(SIGUSR1, nullptr, &sig);
  991. if (sig.sa_handler != nullptr)
  992. fSessionManager = LIBJACK_SESSION_MANAGER_LADISH;
  993. }
  994. if (fSessionManager == LIBJACK_SESSION_MANAGER_LADISH)
  995. ::kill(::getpid(), SIGUSR1);
  996. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  997. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSaved);
  998. fShmNonRtServerControl.commitWrite();
  999. }
  1000. break;
  1001. case kPluginBridgeNonRtClientRestoreLV2State:
  1002. break;
  1003. case kPluginBridgeNonRtClientShowUI:
  1004. if (jack_carla_interposed_action(LIBJACK_INTERPOSER_ACTION_SHOW_HIDE_GUI, 1, nullptr) == 1337)
  1005. {
  1006. // failed, LD_PRELOAD did not work?
  1007. const char* const message("Cannot show UI, LD_PRELOAD not working?");
  1008. const std::size_t messageSize(std::strlen(message));
  1009. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  1010. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerUiClosed);
  1011. fShmNonRtServerControl.commitWrite();
  1012. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  1013. fShmNonRtServerControl.writeUInt(messageSize);
  1014. fShmNonRtServerControl.writeCustomData(message, messageSize);
  1015. fShmNonRtServerControl.commitWrite();
  1016. }
  1017. break;
  1018. case kPluginBridgeNonRtClientHideUI:
  1019. jack_carla_interposed_action(LIBJACK_INTERPOSER_ACTION_SHOW_HIDE_GUI, 0, nullptr);
  1020. break;
  1021. case kPluginBridgeNonRtClientUiParameterChange:
  1022. case kPluginBridgeNonRtClientUiProgramChange:
  1023. case kPluginBridgeNonRtClientUiMidiProgramChange:
  1024. case kPluginBridgeNonRtClientUiNoteOn:
  1025. case kPluginBridgeNonRtClientUiNoteOff:
  1026. break;
  1027. case kPluginBridgeNonRtClientEmbedUI:
  1028. fShmNonRtClientControl.readULong();
  1029. break;
  1030. case kPluginBridgeNonRtClientQuit:
  1031. ret = true;
  1032. break;
  1033. case kPluginBridgeNonRtClientReload:
  1034. break;
  1035. }
  1036. #ifdef DEBUG
  1037. if (opcode != kPluginBridgeNonRtClientPing) {
  1038. carla_debug("CarlaJackAppClient::handleNonRtData() - opcode %s handled", PluginBridgeNonRtClientOpcode2str(opcode));
  1039. }
  1040. #endif
  1041. }
  1042. return ret;
  1043. }
  1044. void CarlaJackAppClient::runRealtimeThread()
  1045. {
  1046. carla_debug("CarlaJackAppClient runRealtimeThread START");
  1047. #ifdef __SSE2_MATH__
  1048. // Set FTZ and DAZ flags
  1049. _mm_setcsr(_mm_getcsr() | 0x8040);
  1050. #endif
  1051. bool quitReceived = false;
  1052. for (; ! fRealtimeThread.shouldThreadExit();)
  1053. {
  1054. if (handleRtData())
  1055. {
  1056. quitReceived = true;
  1057. break;
  1058. }
  1059. }
  1060. fNonRealtimeThread.signalThreadShouldExit();
  1061. carla_debug("CarlaJackAppClient runRealtimeThread FINISHED");
  1062. // TODO
  1063. return; (void)quitReceived;
  1064. }
  1065. void CarlaJackAppClient::runNonRealtimeThread()
  1066. {
  1067. carla_debug("CarlaJackAppClient runNonRealtimeThread START");
  1068. CARLA_SAFE_ASSERT_RETURN(initSharedMemmory(),);
  1069. if (fServer.numMidiIns > 0)
  1070. {
  1071. fMidiInBuffers = new JackMidiPortBufferOnStack[fServer.numMidiIns];
  1072. for (uint8_t i=0; i<fServer.numMidiIns; ++i)
  1073. fMidiInBuffers[i].isInput = true;
  1074. }
  1075. if (fServer.numMidiOuts > 0)
  1076. {
  1077. fMidiOutBuffers = new JackMidiPortBufferOnStack[fServer.numMidiOuts];
  1078. for (uint8_t i=0; i<fServer.numMidiOuts; ++i)
  1079. fMidiOutBuffers[i].isInput = false;
  1080. }
  1081. fRealtimeThread.startThread(true);
  1082. fLastPingTime = getCurrentTimeMilliseconds();
  1083. carla_stdout("Carla Jack Client Ready!");
  1084. bool quitReceived = false,
  1085. timedOut = false;
  1086. for (; ! fNonRealtimeThread.shouldThreadExit();)
  1087. {
  1088. carla_msleep(50);
  1089. try {
  1090. quitReceived = handleNonRtData();
  1091. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  1092. if (quitReceived)
  1093. break;
  1094. /*
  1095. if (fLastPingTime > 0 && getCurrentTimeMilliseconds() > fLastPingTime + 30000)
  1096. {
  1097. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  1098. timedOut = true;
  1099. fRealtimeThread.signalThreadShouldExit();
  1100. break;
  1101. }
  1102. */
  1103. }
  1104. //callback(true, true, ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  1105. if (quitReceived)
  1106. {
  1107. ::kill(::getpid(), SIGTERM);
  1108. }
  1109. else if (timedOut)
  1110. {
  1111. // TODO send shutdown?
  1112. carla_stderr("CarlaJackAppClient error: runNonRealtimeThread ended with time out");
  1113. ::kill(::getpid(), SIGTERM);
  1114. }
  1115. else
  1116. {
  1117. bool activated;
  1118. {
  1119. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  1120. if (fClients.isEmpty())
  1121. {
  1122. activated = false;
  1123. }
  1124. else if (JackClientState* const jclient = fClients.getLast(nullptr))
  1125. {
  1126. const CarlaMutexLocker cms2(jclient->mutex);
  1127. activated = jclient->activated;
  1128. }
  1129. else
  1130. {
  1131. activated = true;
  1132. }
  1133. }
  1134. if (activated)
  1135. {
  1136. carla_stderr("CarlaJackAppClient error: runNonRealtimeThread ended while client is activated");
  1137. const char* const message("Plugin bridge error, process thread has stopped");
  1138. const std::size_t messageSize(std::strlen(message));
  1139. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  1140. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  1141. fShmNonRtServerControl.writeUInt(messageSize);
  1142. fShmNonRtServerControl.writeCustomData(message, messageSize);
  1143. fShmNonRtServerControl.commitWrite();
  1144. }
  1145. }
  1146. if (fRealtimeThread.isThreadRunning())
  1147. {
  1148. fRealtimeThread.signalThreadShouldExit();
  1149. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  1150. if (fShmRtClientControl.data != nullptr)
  1151. fShmRtClientControl.data->procFlags = 1;
  1152. }
  1153. clearSharedMemory();
  1154. fRealtimeThread.stopThread(5000);
  1155. carla_debug("CarlaJackAppClient runNonRealtimeThread FINISHED");
  1156. }
  1157. CARLA_BACKEND_END_NAMESPACE
  1158. // ---------------------------------------------------------------------------------------------------------------------
  1159. using CARLA_BACKEND_NAMESPACE::CarlaJackAppClient;
  1160. using CARLA_BACKEND_NAMESPACE::JackClientState;
  1161. static CarlaJackAppClient gClient;
  1162. CARLA_BACKEND_START_NAMESPACE
  1163. static int carla_interposed_callback(int cb_action, void* ptr)
  1164. {
  1165. return gClient.handleInterposerCallback(cb_action, ptr);
  1166. }
  1167. CARLA_BACKEND_END_NAMESPACE
  1168. // ---------------------------------------------------------------------------------------------------------------------
  1169. CARLA_PLUGIN_EXPORT
  1170. jack_client_t* jack_client_open(const char* client_name, jack_options_t options, jack_status_t* status, ...)
  1171. {
  1172. carla_debug("%s(%s, 0x%x, %p)", __FUNCTION__, client_name, options, status);
  1173. if (JackClientState* const client = gClient.createClient(client_name))
  1174. {
  1175. if (status != nullptr)
  1176. *status = static_cast<JackStatus>(0x0);
  1177. return (jack_client_t*)client;
  1178. }
  1179. if (status != nullptr)
  1180. *status = JackServerError;
  1181. return nullptr;
  1182. // unused
  1183. (void)options;
  1184. }
  1185. CARLA_PLUGIN_EXPORT
  1186. jack_client_t* jack_client_new(const char* client_name)
  1187. {
  1188. return jack_client_open(client_name, JackNullOption, nullptr);
  1189. }
  1190. CARLA_PLUGIN_EXPORT
  1191. int jack_client_close(jack_client_t* client)
  1192. {
  1193. carla_debug("%s(%p)", __FUNCTION__, client);
  1194. JackClientState* const jclient = (JackClientState*)client;
  1195. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  1196. gClient.destroyClient(jclient);
  1197. return 0;
  1198. }
  1199. CARLA_PLUGIN_EXPORT
  1200. int jack_activate(jack_client_t* client)
  1201. {
  1202. carla_debug("%s(%p)", __FUNCTION__, client);
  1203. JackClientState* const jclient = (JackClientState*)client;
  1204. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  1205. return gClient.activateClient(jclient) ? 0 : 1;
  1206. }
  1207. CARLA_PLUGIN_EXPORT
  1208. int jack_deactivate(jack_client_t* client)
  1209. {
  1210. carla_debug("%s(%p)", __FUNCTION__, client);
  1211. JackClientState* const jclient = (JackClientState*)client;
  1212. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  1213. return gClient.deactivateClient(jclient) ? 0 : 1;
  1214. }
  1215. // ---------------------------------------------------------------------------------------------------------------------
  1216. CARLA_PLUGIN_EXPORT
  1217. char* jack_get_client_name_by_uuid(jack_client_t* const client, const char* const uuidstr)
  1218. {
  1219. carla_debug("%s(%p, %s)", __FUNCTION__, client, uuidstr);
  1220. jack_uuid_t uuid = JACK_UUID_EMPTY_INITIALIZER;
  1221. CARLA_SAFE_ASSERT_RETURN(jack_uuid_parse(uuidstr, &uuid) == 0, nullptr);
  1222. JackClientState* const jclient = (JackClientState*)client;
  1223. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, nullptr);
  1224. const char* clientName;
  1225. if (jclient->server.uuid == uuid)
  1226. return strdup("system");
  1227. if (jclient->uuid == uuid)
  1228. {
  1229. clientName = jclient->name;
  1230. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr, nullptr);
  1231. }
  1232. else
  1233. {
  1234. CarlaJackAppClient* const jackAppPtr = jclient->server.jackAppPtr;
  1235. CARLA_SAFE_ASSERT_RETURN(jackAppPtr != nullptr && jackAppPtr == &gClient, nullptr);
  1236. clientName = jackAppPtr->getClientNameFromUUID(uuid);
  1237. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr, nullptr);
  1238. }
  1239. return strdup(clientName);
  1240. }
  1241. CARLA_PLUGIN_EXPORT
  1242. char* jack_get_uuid_for_client_name(jack_client_t* client, const char* name)
  1243. {
  1244. carla_debug("%s(%p, %s)", __FUNCTION__, client, name);
  1245. JackClientState* const jclient = (JackClientState*)client;
  1246. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, nullptr);
  1247. if (std::strcmp(name, "system") == 0)
  1248. {
  1249. char* const uuidstr = static_cast<char*>(std::malloc(JACK_UUID_STRING_SIZE));
  1250. CARLA_SAFE_ASSERT_RETURN(uuidstr != nullptr, nullptr);
  1251. jack_uuid_unparse(jclient->server.uuid, uuidstr);
  1252. return uuidstr;
  1253. }
  1254. else
  1255. {
  1256. CarlaJackAppClient* const jackAppPtr = jclient->server.jackAppPtr;
  1257. CARLA_SAFE_ASSERT_RETURN(jackAppPtr != nullptr && jackAppPtr == &gClient, nullptr);
  1258. const jack_uuid_t uuid = jackAppPtr->getUUIDForClientName(name);
  1259. CARLA_SAFE_ASSERT_RETURN(uuid != JACK_UUID_EMPTY_INITIALIZER, nullptr);
  1260. char* const uuidstr = static_cast<char*>(std::malloc(JACK_UUID_STRING_SIZE));
  1261. CARLA_SAFE_ASSERT_RETURN(uuidstr != nullptr, nullptr);
  1262. jack_uuid_unparse(jclient->uuid, uuidstr);
  1263. return uuidstr;
  1264. }
  1265. }
  1266. // ---------------------------------------------------------------------------------------------------------------------
  1267. CARLA_PLUGIN_EXPORT
  1268. pthread_t jack_client_thread_id(jack_client_t* client)
  1269. {
  1270. carla_debug("%s(%p)", __FUNCTION__, client);
  1271. JackClientState* const jclient = (JackClientState*)client;
  1272. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 0);
  1273. CarlaJackAppClient* const jackAppPtr = jclient->server.jackAppPtr;
  1274. CARLA_SAFE_ASSERT_RETURN(jackAppPtr != nullptr && jackAppPtr == &gClient, 0);
  1275. return jackAppPtr->getRealtimeThreadId();
  1276. }
  1277. // ---------------------------------------------------------------------------------------------------------------------
  1278. #include "jackbridge/JackBridge2.cpp"
  1279. #include "CarlaBridgeUtils.cpp"
  1280. // ---------------------------------------------------------------------------------------------------------------------
  1281. // TODO
  1282. CARLA_BACKEND_USE_NAMESPACE
  1283. CARLA_PLUGIN_EXPORT
  1284. int jack_client_real_time_priority(jack_client_t* client)
  1285. {
  1286. carla_debug("%s(%p)", __FUNCTION__, client);
  1287. // code as used by water
  1288. const int minPriority = sched_get_priority_min(SCHED_RR);
  1289. const int maxPriority = sched_get_priority_max(SCHED_RR);
  1290. return ((maxPriority - minPriority) * 9) / 10 + minPriority;
  1291. // unused
  1292. (void)client;
  1293. }
  1294. int jack_client_create_thread(jack_client_t* client, pthread_t* thread, int priority,
  1295. int realtime, void *(*start_routine)(void*), void* arg)
  1296. {
  1297. carla_stderr2("%s(%p, %p, %i, %i, %p, %p)", __FUNCTION__, client, thread, priority, realtime, start_routine, arg);
  1298. return ENOSYS;
  1299. }
  1300. typedef void (*JackSessionCallback)(jack_session_event_t*, void*);
  1301. CARLA_PLUGIN_EXPORT
  1302. int jack_set_session_callback(jack_client_t* client, JackSessionCallback callback, void* arg)
  1303. {
  1304. carla_stderr2("%s(%p, %p, %p)", __FUNCTION__, client, callback, arg);
  1305. return 0;
  1306. }
  1307. // ---------------------------------------------------------------------------------------------------------------------