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.

1526 lines
54KB

  1. /*
  2. * Carla JACK API for external applications
  3. * Copyright (C) 2016-2019 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_COPY_CLASS(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_COPY_CLASS(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. case kPluginBridgeRtClientControlEventMidiBank:
  499. case kPluginBridgeRtClientControlEventMidiProgram:
  500. case kPluginBridgeRtClientControlEventAllSoundOff:
  501. case kPluginBridgeRtClientControlEventAllNotesOff:
  502. break;
  503. case kPluginBridgeRtClientMidiEvent: {
  504. const uint32_t time(fShmRtClientControl.readUInt());
  505. const uint8_t port(fShmRtClientControl.readByte());
  506. const uint8_t size(fShmRtClientControl.readByte());
  507. CARLA_SAFE_ASSERT_BREAK(size > 0);
  508. if (port >= fServer.numMidiIns || size > JackMidiPortBufferBase::kMaxEventSize || ! fRealtimeThreadMutex.tryLock())
  509. {
  510. for (uint8_t i=0; i<size; ++i)
  511. fShmRtClientControl.readByte();
  512. break;
  513. }
  514. JackMidiPortBufferOnStack& midiPortBuf(fMidiInBuffers[port]);
  515. if (midiPortBuf.count < JackMidiPortBufferBase::kMaxEventCount &&
  516. midiPortBuf.bufferPoolPos + size < JackMidiPortBufferBase::kBufferPoolSize)
  517. {
  518. jack_midi_event_t& ev(midiPortBuf.events[midiPortBuf.count++]);
  519. ev.time = time;
  520. ev.size = size;
  521. ev.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  522. midiPortBuf.bufferPoolPos += size;
  523. for (uint8_t i=0; i<size; ++i)
  524. ev.buffer[i] = fShmRtClientControl.readByte();
  525. }
  526. fRealtimeThreadMutex.unlock(true);
  527. break;
  528. }
  529. case kPluginBridgeRtClientProcess: {
  530. const uint32_t frames(fShmRtClientControl.readUInt());
  531. CARLA_SAFE_ASSERT_UINT2_BREAK(frames == fServer.bufferSize, frames, fServer.bufferSize);
  532. // TODO tell client of xrun in case buffersize does not match
  533. const CarlaMutexTryLocker cmtl(fRealtimeThreadMutex, fIsOffline);
  534. if (cmtl.wasLocked())
  535. {
  536. CARLA_SAFE_ASSERT_BREAK(fShmAudioPool.data != nullptr);
  537. // mixdown is default, do buffer addition (for multiple clients) if requested
  538. const bool doBufferAddition = fSetupHints & LIBJACK_FLAG_AUDIO_BUFFERS_ADDITION;
  539. // mixdown midi outputs based on channel if requested
  540. const bool doMidiChanMixdown = fSetupHints & LIBJACK_FLAG_MIDI_OUTPUT_CHANNEL_MIXDOWN;
  541. // location to start of audio outputs (shm buffer)
  542. float* const fdataRealOuts = fShmAudioPool.data+(fServer.bufferSize*fServer.numAudioIns);
  543. if (doBufferAddition && fServer.numAudioOuts > 0)
  544. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  545. if (! fClients.isEmpty())
  546. {
  547. // save transport for all clients
  548. const BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  549. const bool transportChanged = fServer.playing != bridgeTimeInfo.playing ||
  550. (bridgeTimeInfo.playing && fServer.position.frame + frames != bridgeTimeInfo.frame);
  551. fServer.playing = bridgeTimeInfo.playing;
  552. fServer.position.frame = static_cast<jack_nframes_t>(bridgeTimeInfo.frame);
  553. fServer.position.usecs = bridgeTimeInfo.usecs;
  554. fServer.position.frame_rate = static_cast<jack_nframes_t>(fServer.sampleRate);
  555. if (bridgeTimeInfo.validFlags & kPluginBridgeTimeInfoValidBBT)
  556. {
  557. fServer.position.valid = JackPositionBBT;
  558. fServer.position.bar = bridgeTimeInfo.bar;
  559. fServer.position.beat = bridgeTimeInfo.beat;
  560. fServer.position.tick = static_cast<int32_t>(bridgeTimeInfo.tick + 0.5);
  561. fServer.position.beats_per_bar = bridgeTimeInfo.beatsPerBar;
  562. fServer.position.beat_type = bridgeTimeInfo.beatType;
  563. fServer.position.ticks_per_beat = bridgeTimeInfo.ticksPerBeat;
  564. fServer.position.beats_per_minute = bridgeTimeInfo.beatsPerMinute;
  565. fServer.position.bar_start_tick = bridgeTimeInfo.barStartTick;
  566. }
  567. else
  568. {
  569. fServer.position.valid = static_cast<jack_position_bits_t>(0x0);
  570. }
  571. int numClientOutputsProcessed = 0;
  572. // now go through each client
  573. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  574. {
  575. JackClientState* const jclient(it.getValue(nullptr));
  576. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  577. const CarlaMutexTryLocker cmtl2(jclient->mutex, fIsOffline);
  578. // check if we can process
  579. if (cmtl2.wasNotLocked() || jclient->processCb == nullptr || ! jclient->activated)
  580. {
  581. if (fServer.numAudioOuts > 0)
  582. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  583. if (jclient->deactivated)
  584. fShmRtClientControl.data->procFlags = 1;
  585. }
  586. else
  587. {
  588. // report transport sync changes if needed
  589. if (transportChanged && jclient->syncCb != nullptr)
  590. {
  591. jclient->syncCb(fServer.playing ? JackTransportRolling : JackTransportStopped,
  592. &fServer.position,
  593. jclient->syncCbPtr);
  594. }
  595. uint8_t i;
  596. // direct access to shm buffer, used only for inputs
  597. float* fdataReal = fShmAudioPool.data;
  598. // safe temp location for output, mixed down to shm buffer later on
  599. float* fdataCopy = fAudioPoolCopy;
  600. // wherever we're using fAudioTmpBuf
  601. bool needsTmpBufClear = false;
  602. // set audio inputs
  603. i = 0;
  604. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->audioIns.begin2(); it2.valid(); it2.next())
  605. {
  606. JackPortState* const jport = it2.getValue(nullptr);
  607. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  608. if (i++ < fServer.numAudioIns)
  609. {
  610. if (numClientOutputsProcessed == 0 || ! doBufferAddition)
  611. jport->buffer = fdataReal;
  612. else
  613. jport->buffer = fdataRealOuts + (i*fServer.bufferSize);
  614. fdataReal += fServer.bufferSize;
  615. fdataCopy += fServer.bufferSize;
  616. }
  617. else
  618. {
  619. jport->buffer = fAudioTmpBuf;
  620. needsTmpBufClear = true;
  621. }
  622. }
  623. if (i < fServer.numAudioIns)
  624. {
  625. const std::size_t remainingBufferSize = fServer.bufferSize * static_cast<uint8_t>(fServer.numAudioIns - i);
  626. //fdataReal += remainingBufferSize;
  627. fdataCopy += remainingBufferSize;
  628. }
  629. // location to start of audio outputs
  630. float* const fdataCopyOuts = fdataCopy;
  631. // set audio outputs
  632. i = 0;
  633. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->audioOuts.begin2(); it2.valid(); it2.next())
  634. {
  635. JackPortState* const jport = it2.getValue(nullptr);
  636. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  637. if (i++ < fServer.numAudioOuts)
  638. {
  639. jport->buffer = fdataCopy;
  640. fdataCopy += fServer.bufferSize;
  641. }
  642. else
  643. {
  644. jport->buffer = fAudioTmpBuf;
  645. needsTmpBufClear = true;
  646. }
  647. }
  648. if (i < fServer.numAudioOuts)
  649. {
  650. const std::size_t remainingBufferSize = fServer.bufferSize * static_cast<uint8_t>(fServer.numAudioOuts - i);
  651. carla_zeroFloats(fdataCopy, remainingBufferSize);
  652. //fdataCopy += remainingBufferSize;
  653. }
  654. // set midi inputs
  655. i = 0;
  656. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->midiIns.begin2(); it2.valid(); it2.next())
  657. {
  658. JackPortState* const jport = it2.getValue(nullptr);
  659. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  660. if (i++ < fServer.numMidiIns)
  661. jport->buffer = &fMidiInBuffers[i-1];
  662. else
  663. jport->buffer = &fDummyMidiInBuffer;
  664. }
  665. // set midi outputs
  666. i = 0;
  667. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->midiOuts.begin2(); it2.valid(); it2.next())
  668. {
  669. JackPortState* const jport = it2.getValue(nullptr);
  670. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  671. if (i++ < fServer.numMidiOuts)
  672. jport->buffer = &fMidiOutBuffers[i-1];
  673. else
  674. jport->buffer = &fDummyMidiOutBuffer;
  675. }
  676. if (needsTmpBufClear)
  677. carla_zeroFloats(fAudioTmpBuf, fServer.bufferSize);
  678. jclient->processCb(fServer.bufferSize, jclient->processCbPtr);
  679. if (fServer.numAudioOuts > 0)
  680. {
  681. if (++numClientOutputsProcessed == 1)
  682. {
  683. // first client, we can copy stuff over
  684. carla_copyFloats(fdataRealOuts, fdataCopyOuts,
  685. fServer.bufferSize*fServer.numAudioOuts);
  686. }
  687. else
  688. {
  689. // subsequent clients, add data (then divide by number of clients later on)
  690. carla_add(fdataRealOuts, fdataCopyOuts,
  691. fServer.bufferSize*fServer.numAudioOuts);
  692. if (doBufferAddition)
  693. {
  694. // for more than 1 client addition, we need to divide buffers now
  695. carla_multiply(fdataRealOuts,
  696. 1.0f/static_cast<float>(numClientOutputsProcessed),
  697. fServer.bufferSize*fServer.numAudioOuts);
  698. }
  699. }
  700. if (jclient->audioOuts.count() == 1 && fServer.numAudioOuts > 1)
  701. {
  702. for (uint8_t j=1; j<fServer.numAudioOuts; ++j)
  703. {
  704. carla_copyFloats(fdataRealOuts+(fServer.bufferSize*j),
  705. fdataCopyOuts,
  706. fServer.bufferSize);
  707. }
  708. }
  709. }
  710. }
  711. }
  712. if (numClientOutputsProcessed > 1 && ! doBufferAddition)
  713. {
  714. // more than 1 client active, need to divide buffers
  715. carla_multiply(fdataRealOuts,
  716. 1.0f/static_cast<float>(numClientOutputsProcessed),
  717. fServer.bufferSize*fServer.numAudioOuts);
  718. }
  719. }
  720. // fClients.isEmpty()
  721. else if (fServer.numAudioOuts > 0)
  722. {
  723. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  724. }
  725. for (uint8_t i=0; i<fServer.numMidiIns; ++i)
  726. {
  727. fMidiInBuffers[i].count = 0;
  728. fMidiInBuffers[i].bufferPoolPos = 0;
  729. }
  730. if (fServer.numMidiOuts > 0)
  731. {
  732. uint8_t* midiData = fShmRtClientControl.data->midiOut;
  733. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  734. std::size_t curMidiDataPos = 0;
  735. for (uint8_t i=0; i<fServer.numMidiOuts; ++i)
  736. {
  737. JackMidiPortBufferOnStack& midiPortBuf(fMidiOutBuffers[i]);
  738. for (uint16_t j=0; j<midiPortBuf.count; ++j)
  739. {
  740. jack_midi_event_t& jmevent(midiPortBuf.events[j]);
  741. if (curMidiDataPos + kBridgeBaseMidiOutHeaderSize + jmevent.size >= kBridgeRtClientDataMidiOutSize)
  742. break;
  743. if (doMidiChanMixdown && MIDI_IS_CHANNEL_MESSAGE(jmevent.buffer[0]))
  744. jmevent.buffer[0] = static_cast<jack_midi_data_t>(
  745. (jmevent.buffer[0] & MIDI_STATUS_BIT) | (i & MIDI_CHANNEL_BIT));
  746. // set time
  747. *(uint32_t*)midiData = jmevent.time;
  748. midiData += 4;
  749. // set port
  750. *midiData++ = doMidiChanMixdown ? 0 : i;
  751. // set size
  752. *midiData++ = static_cast<uint8_t>(jmevent.size);
  753. // set data
  754. std::memcpy(midiData, jmevent.buffer, jmevent.size);
  755. midiData += jmevent.size;
  756. curMidiDataPos += kBridgeBaseMidiOutHeaderSize + jmevent.size;
  757. }
  758. }
  759. // make last event null, so server stops when reaching it
  760. if (curMidiDataPos != 0 &&
  761. curMidiDataPos + kBridgeBaseMidiOutHeaderSize < kBridgeRtClientDataMidiOutSize)
  762. {
  763. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  764. // sort events in case of mixdown
  765. if (doMidiChanMixdown)
  766. {
  767. uint32_t time;
  768. uint8_t size, *midiDataPtr;
  769. uint8_t tmp[kBridgeBaseMidiOutHeaderSize + JackMidiPortBufferBase::kMaxEventSize];
  770. bool wasSorted = true;
  771. for (; wasSorted;)
  772. {
  773. midiDataPtr = fShmRtClientControl.data->midiOut;
  774. uint8_t* prevData = midiDataPtr;
  775. uint32_t prevTime = *(uint32_t*)midiDataPtr;
  776. uint8_t prevSize = *(midiDataPtr + 5);
  777. wasSorted = false;
  778. for (;;)
  779. {
  780. time = *(uint32_t*)midiDataPtr;
  781. size = *(midiDataPtr + 5); // time and port
  782. if (size == 0)
  783. break;
  784. if (prevTime > time)
  785. {
  786. // copy previous data to a temporary place
  787. std::memcpy(tmp, prevData, kBridgeBaseMidiOutHeaderSize + prevSize);
  788. // override previous data with new one (shifting left)
  789. std::memcpy(prevData, midiDataPtr, kBridgeBaseMidiOutHeaderSize + size);
  790. // override new data with old one
  791. std::memcpy(midiDataPtr, tmp, kBridgeBaseMidiOutHeaderSize + prevSize);
  792. // done swapping, flag it
  793. wasSorted = true;
  794. }
  795. prevTime = time;
  796. prevSize = size;
  797. prevData = midiDataPtr;
  798. midiDataPtr += 6 + size;
  799. }
  800. }
  801. }
  802. }
  803. }
  804. }
  805. else
  806. {
  807. carla_stderr2("CarlaJackAppClient: fRealtimeThreadMutex tryLock failed");
  808. }
  809. fServer.monotonic_frame += frames;
  810. break;
  811. }
  812. case kPluginBridgeRtClientQuit:
  813. ret = true;
  814. break;
  815. }
  816. #ifdef DEBUG
  817. if (opcode != kPluginBridgeRtClientProcess && opcode != kPluginBridgeRtClientMidiEvent) {
  818. carla_debug("CarlaJackAppClientRtThread::run() - opcode %s done", PluginBridgeRtClientOpcode2str(opcode));
  819. }
  820. #endif
  821. }
  822. return ret;
  823. }
  824. bool CarlaJackAppClient::handleNonRtData()
  825. {
  826. bool ret = false;
  827. for (; fShmNonRtClientControl.isDataAvailableForReading();)
  828. {
  829. const PluginBridgeNonRtClientOpcode opcode(fShmNonRtClientControl.readOpcode());
  830. #ifdef DEBUG
  831. if (opcode != kPluginBridgeNonRtClientPing) {
  832. carla_debug("CarlaJackAppClient::handleNonRtData() - got opcode: %s", PluginBridgeNonRtClientOpcode2str(opcode));
  833. }
  834. #endif
  835. if (opcode != kPluginBridgeNonRtClientNull && opcode != kPluginBridgeNonRtClientPingOnOff && fLastPingTime > 0)
  836. fLastPingTime = getCurrentTimeMilliseconds();
  837. switch (opcode)
  838. {
  839. case kPluginBridgeNonRtClientNull:
  840. break;
  841. case kPluginBridgeNonRtClientVersion: {
  842. const uint apiVersion = fShmNonRtServerControl.readUInt();
  843. CARLA_SAFE_ASSERT_UINT2(apiVersion == CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT,
  844. apiVersion, CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  845. } break;
  846. case kPluginBridgeNonRtClientPing: {
  847. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  848. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPong);
  849. fShmNonRtServerControl.commitWrite();
  850. } break;
  851. case kPluginBridgeNonRtClientPingOnOff: {
  852. const uint32_t onOff(fShmNonRtClientControl.readBool());
  853. fLastPingTime = onOff ? getCurrentTimeMilliseconds() : -1;
  854. } break;
  855. case kPluginBridgeNonRtClientActivate:
  856. case kPluginBridgeNonRtClientDeactivate:
  857. break;
  858. case kPluginBridgeNonRtClientInitialSetup:
  859. // should never happen!!
  860. fShmNonRtServerControl.readUInt();
  861. fShmNonRtServerControl.readDouble();
  862. break;
  863. case kPluginBridgeNonRtClientSetParameterValue:
  864. case kPluginBridgeNonRtClientSetParameterMidiChannel:
  865. case kPluginBridgeNonRtClientSetParameterMappedControlIndex:
  866. case kPluginBridgeNonRtClientSetParameterMappedRange:
  867. case kPluginBridgeNonRtClientSetProgram:
  868. case kPluginBridgeNonRtClientSetMidiProgram:
  869. case kPluginBridgeNonRtClientSetCustomData:
  870. case kPluginBridgeNonRtClientSetChunkDataFile:
  871. break;
  872. case kPluginBridgeNonRtClientSetOption:
  873. fShmNonRtClientControl.readUInt();
  874. fShmNonRtClientControl.readBool();
  875. break;
  876. case kPluginBridgeNonRtClientSetOptions:
  877. fShmNonRtClientControl.readUInt();
  878. break;
  879. case kPluginBridgeNonRtClientSetCtrlChannel:
  880. fShmNonRtClientControl.readShort();
  881. break;
  882. case kPluginBridgeNonRtClientGetParameterText:
  883. fShmNonRtClientControl.readUInt();
  884. break;
  885. case kPluginBridgeNonRtClientPrepareForSave:
  886. {
  887. if (fSessionManager == LIBJACK_SESSION_MANAGER_AUTO && std::getenv("NSM_URL") == nullptr)
  888. {
  889. struct sigaction sig;
  890. carla_zeroStruct(sig);
  891. sigaction(SIGUSR1, nullptr, &sig);
  892. if (sig.sa_handler != nullptr)
  893. fSessionManager = LIBJACK_SESSION_MANAGER_LADISH;
  894. }
  895. if (fSessionManager == LIBJACK_SESSION_MANAGER_LADISH)
  896. ::kill(::getpid(), SIGUSR1);
  897. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  898. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSaved);
  899. fShmNonRtServerControl.commitWrite();
  900. }
  901. break;
  902. case kPluginBridgeNonRtClientRestoreLV2State:
  903. break;
  904. case kPluginBridgeNonRtClientShowUI:
  905. if (jack_carla_interposed_action(LIBJACK_INTERPOSER_ACTION_SHOW_HIDE_GUI, 1, nullptr) == 1337)
  906. {
  907. // failed, LD_PRELOAD did not work?
  908. const char* const message("Cannot show UI, LD_PRELOAD not working?");
  909. const std::size_t messageSize(std::strlen(message));
  910. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  911. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerUiClosed);
  912. fShmNonRtServerControl.commitWrite();
  913. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  914. fShmNonRtServerControl.writeUInt(messageSize);
  915. fShmNonRtServerControl.writeCustomData(message, messageSize);
  916. fShmNonRtServerControl.commitWrite();
  917. }
  918. break;
  919. case kPluginBridgeNonRtClientHideUI:
  920. jack_carla_interposed_action(LIBJACK_INTERPOSER_ACTION_SHOW_HIDE_GUI, 0, nullptr);
  921. break;
  922. case kPluginBridgeNonRtClientUiParameterChange:
  923. case kPluginBridgeNonRtClientUiProgramChange:
  924. case kPluginBridgeNonRtClientUiMidiProgramChange:
  925. case kPluginBridgeNonRtClientUiNoteOn:
  926. case kPluginBridgeNonRtClientUiNoteOff:
  927. break;
  928. case kPluginBridgeNonRtClientQuit:
  929. ret = true;
  930. break;
  931. }
  932. #ifdef DEBUG
  933. if (opcode != kPluginBridgeNonRtClientPing) {
  934. carla_debug("CarlaJackAppClient::handleNonRtData() - opcode %s handled", PluginBridgeNonRtClientOpcode2str(opcode));
  935. }
  936. #endif
  937. }
  938. return ret;
  939. }
  940. void CarlaJackAppClient::runRealtimeThread()
  941. {
  942. carla_debug("CarlaJackAppClient runRealtimeThread START");
  943. #ifdef __SSE2_MATH__
  944. // Set FTZ and DAZ flags
  945. _mm_setcsr(_mm_getcsr() | 0x8040);
  946. #endif
  947. bool quitReceived = false;
  948. for (; ! fRealtimeThread.shouldThreadExit();)
  949. {
  950. if (handleRtData())
  951. {
  952. quitReceived = true;
  953. break;
  954. }
  955. }
  956. fNonRealtimeThread.signalThreadShouldExit();
  957. carla_debug("CarlaJackAppClient runRealtimeThread FINISHED");
  958. // TODO
  959. return; (void)quitReceived;
  960. }
  961. void CarlaJackAppClient::runNonRealtimeThread()
  962. {
  963. carla_debug("CarlaJackAppClient runNonRealtimeThread START");
  964. CARLA_SAFE_ASSERT_RETURN(initSharedMemmory(),);
  965. if (fServer.numMidiIns > 0)
  966. {
  967. fMidiInBuffers = new JackMidiPortBufferOnStack[fServer.numMidiIns];
  968. for (uint8_t i=0; i<fServer.numMidiIns; ++i)
  969. fMidiInBuffers[i].isInput = true;
  970. }
  971. if (fServer.numMidiOuts > 0)
  972. {
  973. fMidiOutBuffers = new JackMidiPortBufferOnStack[fServer.numMidiOuts];
  974. for (uint8_t i=0; i<fServer.numMidiOuts; ++i)
  975. fMidiOutBuffers[i].isInput = false;
  976. }
  977. fRealtimeThread.startThread(true);
  978. fLastPingTime = getCurrentTimeMilliseconds();
  979. carla_stdout("Carla Jack Client Ready!");
  980. bool quitReceived = false,
  981. timedOut = false;
  982. for (; ! fNonRealtimeThread.shouldThreadExit();)
  983. {
  984. carla_msleep(50);
  985. try {
  986. quitReceived = handleNonRtData();
  987. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  988. if (quitReceived)
  989. break;
  990. /*
  991. if (fLastPingTime > 0 && getCurrentTimeMilliseconds() > fLastPingTime + 30000)
  992. {
  993. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  994. timedOut = true;
  995. fRealtimeThread.signalThreadShouldExit();
  996. break;
  997. }
  998. */
  999. }
  1000. //callback(true, true, ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  1001. if (quitReceived)
  1002. {
  1003. ::kill(::getpid(), SIGTERM);
  1004. }
  1005. else if (timedOut)
  1006. {
  1007. // TODO send shutdown?
  1008. carla_stderr("CarlaJackAppClient error: runNonRealtimeThread ended with time out");
  1009. ::kill(::getpid(), SIGTERM);
  1010. }
  1011. else
  1012. {
  1013. bool activated;
  1014. {
  1015. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  1016. if (fClients.isEmpty())
  1017. {
  1018. activated = false;
  1019. }
  1020. else if (JackClientState* const jclient = fClients.getLast(nullptr))
  1021. {
  1022. const CarlaMutexLocker cms2(jclient->mutex);
  1023. activated = jclient->activated;
  1024. }
  1025. else
  1026. {
  1027. activated = true;
  1028. }
  1029. }
  1030. if (activated)
  1031. {
  1032. carla_stderr("CarlaJackAppClient error: runNonRealtimeThread ended while client is activated");
  1033. const char* const message("Plugin bridge error, process thread has stopped");
  1034. const std::size_t messageSize(std::strlen(message));
  1035. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  1036. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  1037. fShmNonRtServerControl.writeUInt(messageSize);
  1038. fShmNonRtServerControl.writeCustomData(message, messageSize);
  1039. fShmNonRtServerControl.commitWrite();
  1040. }
  1041. }
  1042. if (fRealtimeThread.isThreadRunning())
  1043. {
  1044. fRealtimeThread.signalThreadShouldExit();
  1045. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  1046. if (fShmRtClientControl.data != nullptr)
  1047. fShmRtClientControl.data->procFlags = 1;
  1048. }
  1049. clearSharedMemory();
  1050. fRealtimeThread.stopThread(5000);
  1051. carla_debug("CarlaJackAppClient runNonRealtimeThread FINISHED");
  1052. }
  1053. CARLA_BACKEND_END_NAMESPACE
  1054. // ---------------------------------------------------------------------------------------------------------------------
  1055. using CarlaBackend::CarlaJackAppClient;
  1056. using CarlaBackend::JackClientState;
  1057. static CarlaJackAppClient gClient;
  1058. CARLA_BACKEND_START_NAMESPACE
  1059. static int carla_interposed_callback(int cb_action, void* ptr)
  1060. {
  1061. return gClient.handleInterposerCallback(cb_action, ptr);
  1062. }
  1063. CARLA_BACKEND_END_NAMESPACE
  1064. // ---------------------------------------------------------------------------------------------------------------------
  1065. CARLA_EXPORT
  1066. jack_client_t* jack_client_open(const char* client_name, jack_options_t options, jack_status_t* status, ...)
  1067. {
  1068. carla_debug("%s(%s, 0x%x, %p)", __FUNCTION__, client_name, options, status);
  1069. if (JackClientState* const client = gClient.createClient(client_name))
  1070. {
  1071. if (status != nullptr)
  1072. *status = static_cast<JackStatus>(0x0);
  1073. return (jack_client_t*)client;
  1074. }
  1075. if (status != nullptr)
  1076. *status = JackServerError;
  1077. return nullptr;
  1078. // unused
  1079. (void)options;
  1080. }
  1081. CARLA_EXPORT
  1082. jack_client_t* jack_client_new(const char* client_name)
  1083. {
  1084. return jack_client_open(client_name, JackNullOption, nullptr);
  1085. }
  1086. CARLA_EXPORT
  1087. int jack_client_close(jack_client_t* client)
  1088. {
  1089. carla_debug("%s(%p)", __FUNCTION__, client);
  1090. JackClientState* const jclient = (JackClientState*)client;
  1091. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  1092. gClient.destroyClient(jclient);
  1093. return 0;
  1094. }
  1095. CARLA_EXPORT
  1096. int jack_activate(jack_client_t* client)
  1097. {
  1098. carla_debug("%s(%p)", __FUNCTION__, client);
  1099. JackClientState* const jclient = (JackClientState*)client;
  1100. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  1101. return gClient.activateClient(jclient) ? 0 : 1;
  1102. }
  1103. CARLA_EXPORT
  1104. int jack_deactivate(jack_client_t* client)
  1105. {
  1106. carla_debug("%s(%p)", __FUNCTION__, client);
  1107. JackClientState* const jclient = (JackClientState*)client;
  1108. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  1109. return gClient.deactivateClient(jclient) ? 0 : 1;
  1110. }
  1111. // ---------------------------------------------------------------------------------------------------------------------
  1112. CARLA_EXPORT
  1113. char* jack_get_client_name_by_uuid(jack_client_t* const client, const char* const uuidstr)
  1114. {
  1115. carla_debug("%s(%p, %s)", __FUNCTION__, client, uuidstr);
  1116. jack_uuid_t uuid = JACK_UUID_EMPTY_INITIALIZER;
  1117. CARLA_SAFE_ASSERT_RETURN(jack_uuid_parse(uuidstr, &uuid) == 0, nullptr);
  1118. JackClientState* const jclient = (JackClientState*)client;
  1119. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, nullptr);
  1120. const char* clientName;
  1121. if (jclient->server.uuid == uuid)
  1122. return strdup("system");
  1123. if (jclient->uuid == uuid)
  1124. {
  1125. clientName = jclient->name;
  1126. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr, nullptr);
  1127. }
  1128. else
  1129. {
  1130. CarlaJackAppClient* const jackAppPtr = jclient->server.jackAppPtr;
  1131. CARLA_SAFE_ASSERT_RETURN(jackAppPtr != nullptr && jackAppPtr == &gClient, nullptr);
  1132. clientName = jackAppPtr->getClientNameFromUUID(uuid);
  1133. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr, nullptr);
  1134. }
  1135. return strdup(clientName);
  1136. }
  1137. CARLA_EXPORT
  1138. char* jack_get_uuid_for_client_name(jack_client_t* client, const char* name)
  1139. {
  1140. carla_debug("%s(%p, %s)", __FUNCTION__, client, name);
  1141. JackClientState* const jclient = (JackClientState*)client;
  1142. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, nullptr);
  1143. if (std::strcmp(name, "system") == 0)
  1144. {
  1145. char* const uuidstr = static_cast<char*>(std::malloc(JACK_UUID_STRING_SIZE));
  1146. CARLA_SAFE_ASSERT_RETURN(uuidstr != nullptr, nullptr);
  1147. jack_uuid_unparse(jclient->server.uuid, uuidstr);
  1148. return uuidstr;
  1149. }
  1150. else
  1151. {
  1152. CarlaJackAppClient* const jackAppPtr = jclient->server.jackAppPtr;
  1153. CARLA_SAFE_ASSERT_RETURN(jackAppPtr != nullptr && jackAppPtr == &gClient, nullptr);
  1154. const jack_uuid_t uuid = jackAppPtr->getUUIDForClientName(name);
  1155. CARLA_SAFE_ASSERT_RETURN(uuid != JACK_UUID_EMPTY_INITIALIZER, nullptr);
  1156. char* const uuidstr = static_cast<char*>(std::malloc(JACK_UUID_STRING_SIZE));
  1157. CARLA_SAFE_ASSERT_RETURN(uuidstr != nullptr, nullptr);
  1158. jack_uuid_unparse(jclient->uuid, uuidstr);
  1159. return uuidstr;
  1160. }
  1161. }
  1162. // ---------------------------------------------------------------------------------------------------------------------
  1163. CARLA_EXPORT
  1164. pthread_t jack_client_thread_id(jack_client_t* client)
  1165. {
  1166. carla_debug("%s(%p)", __FUNCTION__, client);
  1167. JackClientState* const jclient = (JackClientState*)client;
  1168. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 0);
  1169. CarlaJackAppClient* const jackAppPtr = jclient->server.jackAppPtr;
  1170. CARLA_SAFE_ASSERT_RETURN(jackAppPtr != nullptr && jackAppPtr == &gClient, 0);
  1171. return jackAppPtr->getRealtimeThreadId();
  1172. }
  1173. // ---------------------------------------------------------------------------------------------------------------------
  1174. #include "jackbridge/JackBridge2.cpp"
  1175. #include "CarlaBridgeUtils.cpp"
  1176. // ---------------------------------------------------------------------------------------------------------------------
  1177. // TODO
  1178. CARLA_BACKEND_USE_NAMESPACE
  1179. CARLA_EXPORT
  1180. int jack_client_real_time_priority(jack_client_t* client)
  1181. {
  1182. carla_debug("%s(%p)", __FUNCTION__, client);
  1183. // code as used by water
  1184. const int minPriority = sched_get_priority_min(SCHED_RR);
  1185. const int maxPriority = sched_get_priority_max(SCHED_RR);
  1186. return ((maxPriority - minPriority) * 9) / 10 + minPriority;
  1187. // unused
  1188. (void)client;
  1189. }
  1190. int jack_client_create_thread(jack_client_t* client, pthread_t* thread, int priority,
  1191. int realtime, void *(*start_routine)(void*), void* arg)
  1192. {
  1193. carla_stderr2("%s(%p, %p, %i, %i, %p, %p)", __FUNCTION__, client, thread, priority, realtime, start_routine, arg);
  1194. return ENOSYS;
  1195. }
  1196. typedef void (*JackSessionCallback)(jack_session_event_t*, void*);
  1197. CARLA_EXPORT
  1198. int jack_set_session_callback(jack_client_t* client, JackSessionCallback callback, void* arg)
  1199. {
  1200. carla_stderr2("%s(%p, %p, %p)", __FUNCTION__, client, callback, arg);
  1201. return 0;
  1202. }
  1203. // ---------------------------------------------------------------------------------------------------------------------