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.

1268 lines
43KB

  1. /*
  2. * Carla JACK API for external applications
  3. * Copyright (C) 2016-2018 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 <signal.h>
  20. #include <sys/prctl.h>
  21. #include <sys/time.h>
  22. typedef int (*CarlaInterposedCallback)(int, void*);
  23. CARLA_EXPORT
  24. int jack_carla_interposed_action(int, int, void*)
  25. {
  26. carla_stderr2("Non-export jack_carla_interposed_action called, this should not happen!!");
  27. return 1337;
  28. }
  29. CARLA_BACKEND_START_NAMESPACE
  30. static int64_t getCurrentTimeMilliseconds() noexcept
  31. {
  32. struct timeval tv;
  33. gettimeofday (&tv, nullptr);
  34. return ((int64_t) tv.tv_sec) * 1000 + tv.tv_usec / 1000;
  35. }
  36. // ---------------------------------------------------------------------------------------------------------------------
  37. class CarlaJackRealtimeThread : public CarlaThread
  38. {
  39. public:
  40. struct Callback {
  41. Callback() {}
  42. virtual ~Callback() {};
  43. virtual void runRealtimeThread() = 0;
  44. };
  45. CarlaJackRealtimeThread(Callback* const callback)
  46. : CarlaThread("CarlaJackRealtimeThread"),
  47. fCallback(callback) {}
  48. protected:
  49. void run() override
  50. {
  51. fCallback->runRealtimeThread();
  52. }
  53. private:
  54. Callback* const fCallback;
  55. CARLA_DECLARE_NON_COPY_CLASS(CarlaJackRealtimeThread)
  56. };
  57. // --------------------------------------------------------------------------------------------------------------------
  58. class CarlaJackNonRealtimeThread : public CarlaThread
  59. {
  60. public:
  61. struct Callback {
  62. Callback() {}
  63. virtual ~Callback() {};
  64. virtual void runNonRealtimeThread() = 0;
  65. };
  66. CarlaJackNonRealtimeThread(Callback* const callback)
  67. : CarlaThread("CarlaJackNonRealtimeThread"),
  68. fCallback(callback) {}
  69. protected:
  70. void run() override
  71. {
  72. fCallback->runNonRealtimeThread();
  73. }
  74. private:
  75. Callback* const fCallback;
  76. CARLA_DECLARE_NON_COPY_CLASS(CarlaJackNonRealtimeThread)
  77. };
  78. static int carla_interposed_callback(int, void*);
  79. // ---------------------------------------------------------------------------------------------------------------------
  80. class CarlaJackAppClient : public CarlaJackRealtimeThread::Callback,
  81. public CarlaJackNonRealtimeThread::Callback
  82. {
  83. public:
  84. JackServerState fServer;
  85. LinkedList<JackClientState*> fClients;
  86. CarlaJackAppClient()
  87. : fServer(this),
  88. fClients(),
  89. fShmAudioPool(),
  90. fShmRtClientControl(),
  91. fShmNonRtClientControl(),
  92. fShmNonRtServerControl(),
  93. fAudioPoolCopy(nullptr),
  94. fAudioTmpBuf(nullptr),
  95. fDummyMidiInBuffer(true, "ignored"),
  96. fDummyMidiOutBuffer(false, "ignored"),
  97. fMidiInBuffers(nullptr),
  98. fMidiOutBuffers(nullptr),
  99. fIsOffline(false),
  100. fLastPingTime(-1),
  101. fSessionManager(0),
  102. fSetupHints(0),
  103. fRealtimeThread(this),
  104. fNonRealtimeThread(this)
  105. {
  106. carla_debug("CarlaJackAppClient::CarlaJackAppClient()");
  107. const char* const shmIds(std::getenv("CARLA_SHM_IDS"));
  108. CARLA_SAFE_ASSERT_RETURN(shmIds != nullptr && std::strlen(shmIds) == 6*4,);
  109. const char* const libjackSetup(std::getenv("CARLA_LIBJACK_SETUP"));
  110. CARLA_SAFE_ASSERT_RETURN(libjackSetup != nullptr && std::strlen(libjackSetup) == 6,);
  111. // make sure we don't get loaded again
  112. carla_unsetenv("CARLA_SHM_IDS");
  113. // kill ourselves if main carla dies
  114. ::prctl(PR_SET_PDEATHSIG, SIGKILL);
  115. for (int i=4; --i >= 0;) {
  116. CARLA_SAFE_ASSERT_RETURN(libjackSetup[i] >= '0' && libjackSetup[i] <= '0'+64,);
  117. }
  118. for (int i=6; --i >= 4;) {
  119. CARLA_SAFE_ASSERT_RETURN(libjackSetup[i] >= '0' && libjackSetup[i] < '0'+0x4f,);
  120. }
  121. std::memcpy(fBaseNameAudioPool, shmIds+6*0, 6);
  122. std::memcpy(fBaseNameRtClientControl, shmIds+6*1, 6);
  123. std::memcpy(fBaseNameNonRtClientControl, shmIds+6*2, 6);
  124. std::memcpy(fBaseNameNonRtServerControl, shmIds+6*3, 6);
  125. fBaseNameAudioPool[6] = '\0';
  126. fBaseNameRtClientControl[6] = '\0';
  127. fBaseNameNonRtClientControl[6] = '\0';
  128. fBaseNameNonRtServerControl[6] = '\0';
  129. fServer.numAudioIns = static_cast<uint8_t>(libjackSetup[0] - '0');
  130. fServer.numAudioOuts = static_cast<uint8_t>(libjackSetup[1] - '0');
  131. fServer.numMidiIns = static_cast<uint8_t>(libjackSetup[2] - '0');
  132. fServer.numMidiOuts = static_cast<uint8_t>(libjackSetup[3] - '0');
  133. fSessionManager = libjackSetup[4] - '0';
  134. fSetupHints = libjackSetup[5] - '0';
  135. jack_carla_interposed_action(1, fSetupHints, (void*)carla_interposed_callback);
  136. jack_carla_interposed_action(2, fSessionManager, nullptr);
  137. fNonRealtimeThread.startThread(false);
  138. }
  139. ~CarlaJackAppClient() noexcept override
  140. {
  141. carla_debug("CarlaJackAppClient::~CarlaJackAppClient()");
  142. fLastPingTime = -1;
  143. fNonRealtimeThread.stopThread(5000);
  144. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  145. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  146. {
  147. JackClientState* const jclient(it.getValue(nullptr));
  148. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  149. delete jclient;
  150. }
  151. fClients.clear();
  152. }
  153. JackClientState* createClient(const char* const name)
  154. {
  155. return new JackClientState(fServer, name);
  156. }
  157. void destroyClient(JackClientState* const jclient)
  158. {
  159. {
  160. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  161. fClients.removeOne(jclient);
  162. }
  163. delete jclient;
  164. }
  165. bool activateClient(JackClientState* const jclient)
  166. {
  167. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  168. if (! fClients.append(jclient))
  169. return false;
  170. jclient->activated = true;
  171. jclient->deactivated = false;
  172. return true;
  173. }
  174. bool deactivateClient(JackClientState* const jclient)
  175. {
  176. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  177. if (! fClients.removeOne(jclient))
  178. return false;
  179. jclient->activated = false;
  180. jclient->deactivated = true;
  181. return true;
  182. }
  183. pthread_t getRealtimeThreadId() const noexcept
  184. {
  185. return (pthread_t)fRealtimeThread.getThreadId();
  186. }
  187. int handleInterposerCallback(const int cb_action, void* const ptr)
  188. {
  189. carla_stdout("handleInterposerCallback(%o, %p)", cb_action, ptr);
  190. switch (cb_action)
  191. {
  192. case 1: {
  193. const CarlaMutexLocker cml(fShmNonRtServerControl.mutex);
  194. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerUiClosed);
  195. fShmNonRtServerControl.commitWrite();
  196. break;
  197. }
  198. }
  199. return 0;
  200. }
  201. // -------------------------------------------------------------------
  202. protected:
  203. void runRealtimeThread() override;
  204. void runNonRealtimeThread() override;
  205. private:
  206. bool initSharedMemmory();
  207. void clearSharedMemory() noexcept;
  208. bool handleRtData();
  209. bool handleNonRtData();
  210. BridgeAudioPool fShmAudioPool;
  211. BridgeRtClientControl fShmRtClientControl;
  212. BridgeNonRtClientControl fShmNonRtClientControl;
  213. BridgeNonRtServerControl fShmNonRtServerControl;
  214. float* fAudioPoolCopy;
  215. float* fAudioTmpBuf;
  216. JackMidiPortBuffer fDummyMidiInBuffer;
  217. JackMidiPortBuffer fDummyMidiOutBuffer;
  218. JackMidiPortBuffer* fMidiInBuffers;
  219. JackMidiPortBuffer* fMidiOutBuffers;
  220. char fBaseNameAudioPool[6+1];
  221. char fBaseNameRtClientControl[6+1];
  222. char fBaseNameNonRtClientControl[6+1];
  223. char fBaseNameNonRtServerControl[6+1];
  224. bool fIsOffline;
  225. int64_t fLastPingTime;
  226. int fSessionManager;
  227. int fSetupHints;
  228. CarlaJackRealtimeThread fRealtimeThread;
  229. CarlaJackNonRealtimeThread fNonRealtimeThread;
  230. CarlaMutex fRealtimeThreadMutex;
  231. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaJackAppClient)
  232. };
  233. // ---------------------------------------------------------------------------------------------------------------------
  234. bool CarlaJackAppClient::initSharedMemmory()
  235. {
  236. if (! fShmAudioPool.attachClient(fBaseNameAudioPool))
  237. {
  238. carla_stderr("Failed to attach to audio pool shared memory");
  239. return false;
  240. }
  241. if (! fShmRtClientControl.attachClient(fBaseNameRtClientControl))
  242. {
  243. clearSharedMemory();
  244. carla_stderr("Failed to attach to rt client control shared memory");
  245. return false;
  246. }
  247. if (! fShmRtClientControl.mapData())
  248. {
  249. clearSharedMemory();
  250. carla_stderr("Failed to map rt client control shared memory");
  251. return false;
  252. }
  253. if (! fShmNonRtClientControl.attachClient(fBaseNameNonRtClientControl))
  254. {
  255. clearSharedMemory();
  256. carla_stderr("Failed to attach to non-rt client control shared memory");
  257. return false;
  258. }
  259. if (! fShmNonRtClientControl.mapData())
  260. {
  261. clearSharedMemory();
  262. carla_stderr("Failed to map non-rt control client shared memory");
  263. return false;
  264. }
  265. if (! fShmNonRtServerControl.attachClient(fBaseNameNonRtServerControl))
  266. {
  267. clearSharedMemory();
  268. carla_stderr("Failed to attach to non-rt server control shared memory");
  269. return false;
  270. }
  271. if (! fShmNonRtServerControl.mapData())
  272. {
  273. clearSharedMemory();
  274. carla_stderr("Failed to map non-rt control server shared memory");
  275. return false;
  276. }
  277. PluginBridgeNonRtClientOpcode opcode;
  278. opcode = fShmNonRtClientControl.readOpcode();
  279. CARLA_SAFE_ASSERT_RETURN(opcode == kPluginBridgeNonRtClientVersion, false);
  280. const uint32_t apiVersion = fShmNonRtClientControl.readUInt();
  281. CARLA_SAFE_ASSERT_RETURN(apiVersion == CARLA_PLUGIN_BRIDGE_API_VERSION, false);
  282. const uint32_t shmRtClientDataSize = fShmNonRtClientControl.readUInt();
  283. CARLA_SAFE_ASSERT_INT2(shmRtClientDataSize == sizeof(BridgeRtClientData), shmRtClientDataSize, sizeof(BridgeRtClientData));
  284. const uint32_t shmNonRtClientDataSize = fShmNonRtClientControl.readUInt();
  285. CARLA_SAFE_ASSERT_INT2(shmNonRtClientDataSize == sizeof(BridgeNonRtClientData), shmNonRtClientDataSize, sizeof(BridgeNonRtClientData));
  286. const uint32_t shmNonRtServerDataSize = fShmNonRtClientControl.readUInt();
  287. CARLA_SAFE_ASSERT_INT2(shmNonRtServerDataSize == sizeof(BridgeNonRtServerData), shmNonRtServerDataSize, sizeof(BridgeNonRtServerData));
  288. if (shmRtClientDataSize != sizeof(BridgeRtClientData) ||
  289. shmNonRtClientDataSize != sizeof(BridgeNonRtClientData) ||
  290. shmNonRtServerDataSize != sizeof(BridgeNonRtServerData))
  291. {
  292. carla_stderr2("CarlaJackAppClient: data size mismatch");
  293. return false;
  294. }
  295. opcode = fShmNonRtClientControl.readOpcode();
  296. CARLA_SAFE_ASSERT_RETURN(opcode == kPluginBridgeNonRtClientInitialSetup, false);
  297. fServer.bufferSize = fShmNonRtClientControl.readUInt();
  298. fServer.sampleRate = fShmNonRtClientControl.readDouble();
  299. if (fServer.bufferSize == 0 || carla_isZero(fServer.sampleRate))
  300. {
  301. carla_stderr2("CarlaJackAppClient: invalid empty state");
  302. return false;
  303. }
  304. fAudioTmpBuf = new float[fServer.bufferSize];
  305. carla_zeroFloats(fAudioTmpBuf, fServer.bufferSize);
  306. // tell backend we're live
  307. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  308. fLastPingTime = getCurrentTimeMilliseconds();
  309. CARLA_SAFE_ASSERT(fLastPingTime > 0);
  310. // ready!
  311. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerReady);
  312. fShmNonRtServerControl.commitWrite();
  313. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  314. return true;
  315. }
  316. void CarlaJackAppClient::clearSharedMemory() noexcept
  317. {
  318. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  319. if (fAudioPoolCopy != nullptr)
  320. {
  321. delete[] fAudioPoolCopy;
  322. fAudioPoolCopy = nullptr;
  323. }
  324. if (fAudioTmpBuf != nullptr)
  325. {
  326. delete[] fAudioTmpBuf;
  327. fAudioTmpBuf = nullptr;
  328. }
  329. if (fMidiInBuffers != nullptr)
  330. {
  331. delete[] fMidiInBuffers;
  332. fMidiInBuffers = nullptr;
  333. }
  334. if (fMidiOutBuffers != nullptr)
  335. {
  336. delete[] fMidiOutBuffers;
  337. fMidiOutBuffers = nullptr;
  338. }
  339. fShmAudioPool.clear();
  340. fShmRtClientControl.clear();
  341. fShmNonRtClientControl.clear();
  342. fShmNonRtServerControl.clear();
  343. }
  344. bool CarlaJackAppClient::handleRtData()
  345. {
  346. const BridgeRtClientControl::WaitHelper helper(fShmRtClientControl);
  347. if (! helper.ok)
  348. return false;
  349. bool ret = false;
  350. for (; fShmRtClientControl.isDataAvailableForReading();)
  351. {
  352. const PluginBridgeRtClientOpcode opcode(fShmRtClientControl.readOpcode());
  353. #ifdef DEBUG
  354. if (opcode != kPluginBridgeRtClientProcess && opcode != kPluginBridgeRtClientMidiEvent) {
  355. carla_debug("CarlaJackAppClientRtThread::run() - got opcode: %s", PluginBridgeRtClientOpcode2str(opcode));
  356. }
  357. #endif
  358. switch (opcode)
  359. {
  360. case kPluginBridgeRtClientNull:
  361. break;
  362. case kPluginBridgeRtClientSetAudioPool: {
  363. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  364. if (fShmAudioPool.data != nullptr)
  365. {
  366. jackbridge_shm_unmap(fShmAudioPool.shm, fShmAudioPool.data);
  367. fShmAudioPool.data = nullptr;
  368. }
  369. if (fAudioPoolCopy != nullptr)
  370. {
  371. delete[] fAudioPoolCopy;
  372. fAudioPoolCopy = nullptr;
  373. }
  374. const uint64_t poolSize(fShmRtClientControl.readULong());
  375. CARLA_SAFE_ASSERT_BREAK(poolSize > 0);
  376. fShmAudioPool.data = (float*)jackbridge_shm_map(fShmAudioPool.shm, static_cast<size_t>(poolSize));
  377. fAudioPoolCopy = new float[poolSize];
  378. break;
  379. }
  380. case kPluginBridgeRtClientSetBufferSize:
  381. if (const uint32_t newBufferSize = fShmRtClientControl.readUInt())
  382. {
  383. if (fServer.bufferSize != newBufferSize)
  384. {
  385. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  386. fServer.bufferSize = newBufferSize;
  387. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  388. {
  389. JackClientState* const jclient(it.getValue(nullptr));
  390. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  391. jclient->bufferSizeCb(fServer.bufferSize, jclient->bufferSizeCbPtr);
  392. }
  393. delete[] fAudioTmpBuf;
  394. fAudioTmpBuf = new float[fServer.bufferSize];
  395. carla_zeroFloats(fAudioTmpBuf, fServer.bufferSize);
  396. }
  397. }
  398. break;
  399. case kPluginBridgeRtClientSetSampleRate: {
  400. const double newSampleRate = fShmRtClientControl.readDouble();
  401. if (carla_isNotZero(newSampleRate) && carla_isNotEqual(fServer.sampleRate, newSampleRate))
  402. {
  403. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  404. fServer.sampleRate = newSampleRate;
  405. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  406. {
  407. JackClientState* const jclient(it.getValue(nullptr));
  408. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  409. jclient->sampleRateCb(static_cast<uint32_t>(fServer.sampleRate), jclient->sampleRateCbPtr);
  410. }
  411. }
  412. } break;
  413. case kPluginBridgeRtClientSetOnline:
  414. // TODO inform changes
  415. fIsOffline = fShmRtClientControl.readBool();
  416. //offlineModeChanged(fIsOffline);
  417. break;
  418. case kPluginBridgeRtClientControlEventParameter:
  419. case kPluginBridgeRtClientControlEventMidiBank:
  420. case kPluginBridgeRtClientControlEventMidiProgram:
  421. case kPluginBridgeRtClientControlEventAllSoundOff:
  422. case kPluginBridgeRtClientControlEventAllNotesOff:
  423. break;
  424. case kPluginBridgeRtClientMidiEvent: {
  425. const uint32_t time(fShmRtClientControl.readUInt());
  426. const uint8_t port(fShmRtClientControl.readByte());
  427. const uint8_t size(fShmRtClientControl.readByte());
  428. CARLA_SAFE_ASSERT_BREAK(size > 0);
  429. if (port >= fServer.numMidiIns || size > JackMidiPortBuffer::kMaxEventSize || ! fRealtimeThreadMutex.tryLock())
  430. {
  431. for (uint8_t i=0; i<size; ++i)
  432. fShmRtClientControl.readByte();
  433. break;
  434. }
  435. JackMidiPortBuffer& midiPortBuf(fMidiInBuffers[port]);
  436. if (midiPortBuf.count < JackMidiPortBuffer::kMaxEventCount &&
  437. midiPortBuf.bufferPoolPos + size < JackMidiPortBuffer::kBufferPoolSize)
  438. {
  439. jack_midi_event_t& ev(midiPortBuf.events[midiPortBuf.count++]);
  440. ev.time = time;
  441. ev.size = size;
  442. ev.buffer = midiPortBuf.bufferPool + midiPortBuf.bufferPoolPos;
  443. midiPortBuf.bufferPoolPos += size;
  444. for (uint8_t i=0; i<size; ++i)
  445. ev.buffer[i] = fShmRtClientControl.readByte();
  446. }
  447. fRealtimeThreadMutex.unlock(true);
  448. break;
  449. }
  450. case kPluginBridgeRtClientProcess: {
  451. const uint32_t frames(fShmRtClientControl.readUInt());
  452. CARLA_SAFE_ASSERT_UINT2_BREAK(frames == fServer.bufferSize, frames, fServer.bufferSize);
  453. // TODO tell client of xrun in case buffersize does not match
  454. // FIXME - lock if offline
  455. const CarlaMutexTryLocker cmtl(fRealtimeThreadMutex);
  456. if (cmtl.wasLocked())
  457. {
  458. CARLA_SAFE_ASSERT_BREAK(fShmAudioPool.data != nullptr);
  459. // mixdown is default, do buffer addition (for multiple clients) if requested
  460. const bool doBufferAddition = fSetupHints & 0x10;
  461. // location to start of audio outputs (shm buffer)
  462. float* const fdataRealOuts = fShmAudioPool.data+(fServer.bufferSize*fServer.numAudioIns);
  463. if (doBufferAddition && fServer.numAudioOuts > 0)
  464. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  465. if (! fClients.isEmpty())
  466. {
  467. // save tranport for all clients
  468. const BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  469. fServer.playing = bridgeTimeInfo.playing;
  470. fServer.position.frame = bridgeTimeInfo.frame;
  471. fServer.position.usecs = bridgeTimeInfo.usecs;
  472. if (bridgeTimeInfo.validFlags & kPluginBridgeTimeInfoValidBBT)
  473. {
  474. fServer.position.valid = JackPositionBBT;
  475. fServer.position.bar = bridgeTimeInfo.bar;
  476. fServer.position.beat = bridgeTimeInfo.beat;
  477. fServer.position.tick = static_cast<int32_t>(bridgeTimeInfo.tick + 0.5);
  478. fServer.position.beats_per_bar = bridgeTimeInfo.beatsPerBar;
  479. fServer.position.beat_type = bridgeTimeInfo.beatType;
  480. fServer.position.ticks_per_beat = bridgeTimeInfo.ticksPerBeat;
  481. fServer.position.beats_per_minute = bridgeTimeInfo.beatsPerMinute;
  482. fServer.position.bar_start_tick = bridgeTimeInfo.barStartTick;
  483. }
  484. else
  485. {
  486. fServer.position.valid = static_cast<jack_position_bits_t>(0x0);
  487. }
  488. int numClientOutputsProcessed = 0;
  489. // now go through each client
  490. for (LinkedList<JackClientState*>::Itenerator it = fClients.begin2(); it.valid(); it.next())
  491. {
  492. JackClientState* const jclient(it.getValue(nullptr));
  493. CARLA_SAFE_ASSERT_CONTINUE(jclient != nullptr);
  494. // FIXME - lock if offline
  495. const CarlaMutexTryLocker cmtl2(jclient->mutex);
  496. // check if we can process
  497. if (cmtl2.wasNotLocked() || jclient->processCb == nullptr || ! jclient->activated)
  498. {
  499. if (fServer.numAudioOuts > 0)
  500. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  501. if (jclient->deactivated)
  502. fShmRtClientControl.data->procFlags = 1;
  503. }
  504. else
  505. {
  506. uint8_t i;
  507. // direct access to shm buffer, used only for inputs
  508. float* fdataReal = fShmAudioPool.data;
  509. // safe temp location for output, mixed down to shm buffer later on
  510. float* fdataCopy = fAudioPoolCopy;
  511. // wherever we're using fAudioTmpBuf
  512. bool needsTmpBufClear = false;
  513. // set audio inputs
  514. i = 0;
  515. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->audioIns.begin2(); it2.valid(); it2.next())
  516. {
  517. JackPortState* const jport = it2.getValue(nullptr);
  518. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  519. if (i++ < fServer.numAudioIns)
  520. {
  521. if (numClientOutputsProcessed == 0 || ! doBufferAddition)
  522. jport->buffer = fdataReal;
  523. else
  524. jport->buffer = fdataRealOuts + (i*fServer.bufferSize);
  525. fdataReal += fServer.bufferSize;
  526. fdataCopy += fServer.bufferSize;
  527. }
  528. else
  529. {
  530. jport->buffer = fAudioTmpBuf;
  531. needsTmpBufClear = true;
  532. }
  533. }
  534. if (i < fServer.numAudioIns)
  535. {
  536. const std::size_t remainingBufferSize = fServer.bufferSize * (fServer.numAudioIns - i);
  537. //fdataReal += remainingBufferSize;
  538. fdataCopy += remainingBufferSize;
  539. }
  540. // location to start of audio outputs
  541. float* const fdataCopyOuts = fdataCopy;
  542. // set audio ouputs
  543. i = 0;
  544. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->audioOuts.begin2(); it2.valid(); it2.next())
  545. {
  546. JackPortState* const jport = it2.getValue(nullptr);
  547. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  548. if (i++ < fServer.numAudioOuts)
  549. {
  550. jport->buffer = fdataCopy;
  551. fdataCopy += fServer.bufferSize;
  552. }
  553. else
  554. {
  555. jport->buffer = fAudioTmpBuf;
  556. needsTmpBufClear = true;
  557. }
  558. }
  559. if (i < fServer.numAudioOuts)
  560. {
  561. const std::size_t remainingBufferSize = fServer.bufferSize * (fServer.numAudioOuts - i);
  562. carla_zeroFloats(fdataCopy, remainingBufferSize);
  563. //fdataCopy += remainingBufferSize;
  564. }
  565. // set midi inputs
  566. i = 0;
  567. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->midiIns.begin2(); it2.valid(); it2.next())
  568. {
  569. JackPortState* const jport = it2.getValue(nullptr);
  570. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  571. if (i++ < fServer.numMidiIns)
  572. jport->buffer = &fMidiInBuffers[i-1];
  573. else
  574. jport->buffer = &fDummyMidiInBuffer;
  575. }
  576. // set midi outputs
  577. i = 0;
  578. for (LinkedList<JackPortState*>::Itenerator it2 = jclient->midiOuts.begin2(); it2.valid(); it2.next())
  579. {
  580. JackPortState* const jport = it2.getValue(nullptr);
  581. CARLA_SAFE_ASSERT_CONTINUE(jport != nullptr);
  582. if (i++ < fServer.numMidiOuts)
  583. jport->buffer = &fMidiOutBuffers[i-1];
  584. else
  585. jport->buffer = &fDummyMidiOutBuffer;
  586. }
  587. if (needsTmpBufClear)
  588. carla_zeroFloats(fAudioTmpBuf, fServer.bufferSize);
  589. jclient->processCb(fServer.bufferSize, jclient->processCbPtr);
  590. if (fServer.numAudioOuts > 0)
  591. {
  592. if (++numClientOutputsProcessed == 1)
  593. {
  594. // first client, we can copy stuff over
  595. carla_copyFloats(fdataRealOuts, fdataCopyOuts,
  596. fServer.bufferSize*fServer.numAudioOuts);
  597. }
  598. else
  599. {
  600. // subsequent clients, add data (then divide by number of clients later on)
  601. carla_add(fdataRealOuts, fdataCopyOuts,
  602. fServer.bufferSize*fServer.numAudioOuts);
  603. if (doBufferAddition)
  604. {
  605. // for more than 1 client addition, we need to divide buffers now
  606. carla_multiply(fdataRealOuts,
  607. 1.0f/static_cast<float>(numClientOutputsProcessed),
  608. fServer.bufferSize*fServer.numAudioOuts);
  609. }
  610. }
  611. if (jclient->audioOuts.count() == 1 && fServer.numAudioOuts > 1)
  612. {
  613. for (uint8_t j=1; j<fServer.numAudioOuts; ++j)
  614. {
  615. carla_copyFloats(fdataRealOuts+(fServer.bufferSize*j),
  616. fdataCopyOuts,
  617. fServer.bufferSize);
  618. }
  619. }
  620. }
  621. }
  622. }
  623. if (numClientOutputsProcessed > 1 && ! doBufferAddition)
  624. {
  625. // more than 1 client active, need to divide buffers
  626. carla_multiply(fdataRealOuts,
  627. 1.0f/static_cast<float>(numClientOutputsProcessed),
  628. fServer.bufferSize*fServer.numAudioOuts);
  629. }
  630. }
  631. // fClients.isEmpty()
  632. else if (fServer.numAudioOuts > 0)
  633. {
  634. carla_zeroFloats(fdataRealOuts, fServer.bufferSize*fServer.numAudioOuts);
  635. }
  636. for (uint8_t i=0; i<fServer.numMidiIns; ++i)
  637. {
  638. fMidiInBuffers[i].count = 0;
  639. fMidiInBuffers[i].bufferPoolPos = 0;
  640. }
  641. if (fServer.numMidiOuts > 0)
  642. {
  643. uint8_t* midiData(fShmRtClientControl.data->midiOut);
  644. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  645. std::size_t curMidiDataPos = 0;
  646. for (uint8_t i=0; i<fServer.numMidiOuts; ++i)
  647. {
  648. JackMidiPortBuffer& midiPortBuf(fMidiOutBuffers[i]);
  649. for (uint16_t j=0; j<midiPortBuf.count; ++j)
  650. {
  651. jack_midi_event_t& jmevent(midiPortBuf.events[j]);
  652. if (curMidiDataPos + kBridgeBaseMidiOutHeaderSize + jmevent.size >= kBridgeRtClientDataMidiOutSize)
  653. break;
  654. // set time
  655. *(uint32_t*)midiData = jmevent.time;
  656. midiData += 4;
  657. // set port
  658. *midiData++ = i;
  659. // set size
  660. *midiData++ = static_cast<uint8_t>(jmevent.size);
  661. // set data
  662. std::memcpy(midiData, jmevent.buffer, jmevent.size);
  663. midiData += jmevent.size;
  664. curMidiDataPos += kBridgeBaseMidiOutHeaderSize + jmevent.size;
  665. }
  666. }
  667. if (curMidiDataPos != 0 &&
  668. curMidiDataPos + kBridgeBaseMidiOutHeaderSize < kBridgeRtClientDataMidiOutSize)
  669. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  670. }
  671. }
  672. else
  673. {
  674. carla_stderr2("CarlaJackAppClient: fRealtimeThreadMutex tryLock failed");
  675. }
  676. break;
  677. }
  678. case kPluginBridgeRtClientQuit:
  679. ret = true;
  680. break;
  681. }
  682. #ifdef DEBUG
  683. if (opcode != kPluginBridgeRtClientProcess && opcode != kPluginBridgeRtClientMidiEvent) {
  684. carla_debug("CarlaJackAppClientRtThread::run() - opcode %s done", PluginBridgeRtClientOpcode2str(opcode));
  685. }
  686. #endif
  687. }
  688. return ret;
  689. }
  690. bool CarlaJackAppClient::handleNonRtData()
  691. {
  692. bool ret = false;
  693. for (; fShmNonRtClientControl.isDataAvailableForReading();)
  694. {
  695. const PluginBridgeNonRtClientOpcode opcode(fShmNonRtClientControl.readOpcode());
  696. #ifdef DEBUG
  697. if (opcode != kPluginBridgeNonRtClientPing) {
  698. carla_debug("CarlaJackAppClient::handleNonRtData() - got opcode: %s", PluginBridgeNonRtClientOpcode2str(opcode));
  699. }
  700. #endif
  701. if (opcode != kPluginBridgeNonRtClientNull && opcode != kPluginBridgeNonRtClientPingOnOff && fLastPingTime > 0)
  702. fLastPingTime = getCurrentTimeMilliseconds();
  703. switch (opcode)
  704. {
  705. case kPluginBridgeNonRtClientNull:
  706. break;
  707. case kPluginBridgeNonRtClientVersion: {
  708. const uint apiVersion = fShmNonRtServerControl.readUInt();
  709. CARLA_SAFE_ASSERT_UINT2(apiVersion == CARLA_PLUGIN_BRIDGE_API_VERSION, apiVersion, CARLA_PLUGIN_BRIDGE_API_VERSION);
  710. } break;
  711. case kPluginBridgeNonRtClientPing: {
  712. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  713. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPong);
  714. fShmNonRtServerControl.commitWrite();
  715. } break;
  716. case kPluginBridgeNonRtClientPingOnOff: {
  717. const uint32_t onOff(fShmNonRtClientControl.readBool());
  718. fLastPingTime = onOff ? getCurrentTimeMilliseconds() : -1;
  719. } break;
  720. case kPluginBridgeNonRtClientActivate:
  721. case kPluginBridgeNonRtClientDeactivate:
  722. break;
  723. case kPluginBridgeNonRtClientInitialSetup:
  724. // should never happen!!
  725. fShmNonRtServerControl.readUInt();
  726. fShmNonRtServerControl.readDouble();
  727. break;
  728. case kPluginBridgeNonRtClientSetParameterValue:
  729. case kPluginBridgeNonRtClientSetParameterMidiChannel:
  730. case kPluginBridgeNonRtClientSetParameterMidiCC:
  731. case kPluginBridgeNonRtClientSetProgram:
  732. case kPluginBridgeNonRtClientSetMidiProgram:
  733. case kPluginBridgeNonRtClientSetCustomData:
  734. case kPluginBridgeNonRtClientSetChunkDataFile:
  735. break;
  736. case kPluginBridgeNonRtClientSetOption:
  737. fShmNonRtClientControl.readUInt();
  738. fShmNonRtClientControl.readBool();
  739. break;
  740. case kPluginBridgeNonRtClientSetCtrlChannel:
  741. fShmNonRtClientControl.readShort();
  742. break;
  743. case kPluginBridgeNonRtClientGetParameterText:
  744. fShmNonRtClientControl.readUInt();
  745. break;
  746. case kPluginBridgeNonRtClientPrepareForSave:
  747. {
  748. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  749. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSaved);
  750. fShmNonRtServerControl.commitWrite();
  751. }
  752. break;
  753. case kPluginBridgeNonRtClientRestoreLV2State:
  754. break;
  755. case kPluginBridgeNonRtClientShowUI:
  756. if (jack_carla_interposed_action(3, 1, nullptr) == 1337)
  757. {
  758. // failed, LD_PRELOAD did not work?
  759. const char* const message("Cannot show UI, LD_PRELOAD not working?");
  760. const std::size_t messageSize(std::strlen(message));
  761. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  762. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerUiClosed);
  763. fShmNonRtServerControl.commitWrite();
  764. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  765. fShmNonRtServerControl.writeUInt(messageSize);
  766. fShmNonRtServerControl.writeCustomData(message, messageSize);
  767. fShmNonRtServerControl.commitWrite();
  768. }
  769. break;
  770. case kPluginBridgeNonRtClientHideUI:
  771. jack_carla_interposed_action(3, 0, nullptr);
  772. break;
  773. case kPluginBridgeNonRtClientUiParameterChange:
  774. case kPluginBridgeNonRtClientUiProgramChange:
  775. case kPluginBridgeNonRtClientUiMidiProgramChange:
  776. case kPluginBridgeNonRtClientUiNoteOn:
  777. case kPluginBridgeNonRtClientUiNoteOff:
  778. break;
  779. case kPluginBridgeNonRtClientQuit:
  780. ret = true;
  781. break;
  782. }
  783. #ifdef DEBUG
  784. if (opcode != kPluginBridgeNonRtClientPing) {
  785. carla_debug("CarlaJackAppClient::handleNonRtData() - opcode %s handled", PluginBridgeNonRtClientOpcode2str(opcode));
  786. }
  787. #endif
  788. }
  789. return ret;
  790. }
  791. void CarlaJackAppClient::runRealtimeThread()
  792. {
  793. carla_debug("CarlaJackAppClient runRealtimeThread START");
  794. #ifdef __SSE2_MATH__
  795. // Set FTZ and DAZ flags
  796. _mm_setcsr(_mm_getcsr() | 0x8040);
  797. #endif
  798. bool quitReceived = false;
  799. for (; ! fRealtimeThread.shouldThreadExit();)
  800. {
  801. if (handleRtData())
  802. {
  803. quitReceived = true;
  804. break;
  805. }
  806. }
  807. fNonRealtimeThread.signalThreadShouldExit();
  808. carla_debug("CarlaJackAppClient runRealtimeThread FINISHED");
  809. // TODO
  810. return; (void)quitReceived;
  811. }
  812. void CarlaJackAppClient::runNonRealtimeThread()
  813. {
  814. carla_debug("CarlaJackAppClient runNonRealtimeThread START");
  815. CARLA_SAFE_ASSERT_RETURN(initSharedMemmory(),);
  816. if (fServer.numMidiIns > 0)
  817. {
  818. fMidiInBuffers = new JackMidiPortBuffer[fServer.numMidiIns];
  819. for (uint8_t i=0; i<fServer.numMidiIns; ++i)
  820. fMidiInBuffers[i].isInput = true;
  821. }
  822. if (fServer.numMidiOuts > 0)
  823. {
  824. fMidiOutBuffers = new JackMidiPortBuffer[fServer.numMidiOuts];
  825. for (uint8_t i=0; i<fServer.numMidiOuts; ++i)
  826. fMidiOutBuffers[i].isInput = false;
  827. }
  828. fRealtimeThread.startThread(true);
  829. fLastPingTime = getCurrentTimeMilliseconds();
  830. carla_stdout("Carla Jack Client Ready!");
  831. bool quitReceived = false,
  832. timedOut = false;
  833. for (; ! fNonRealtimeThread.shouldThreadExit();)
  834. {
  835. carla_msleep(50);
  836. try {
  837. quitReceived = handleNonRtData();
  838. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  839. if (quitReceived)
  840. break;
  841. /*
  842. if (fLastPingTime > 0 && getCurrentTimeMilliseconds() > fLastPingTime + 30000)
  843. {
  844. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  845. timedOut = true;
  846. fRealtimeThread.signalThreadShouldExit();
  847. break;
  848. }
  849. */
  850. }
  851. //callback(ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  852. if (quitReceived)
  853. {
  854. ::kill(::getpid(), SIGTERM);
  855. }
  856. else if (timedOut)
  857. {
  858. // TODO send shutdown?
  859. carla_stderr("CarlaJackAppClient error: runNonRealtimeThread ended with time out");
  860. ::kill(::getpid(), SIGTERM);
  861. }
  862. else
  863. {
  864. bool activated;
  865. {
  866. const CarlaMutexLocker cms(fRealtimeThreadMutex);
  867. if (fClients.isEmpty())
  868. {
  869. activated = false;
  870. }
  871. else if (JackClientState* const jclient = fClients.getLast(nullptr))
  872. {
  873. const CarlaMutexLocker cms2(jclient->mutex);
  874. activated = jclient->activated;
  875. }
  876. else
  877. {
  878. activated = true;
  879. }
  880. }
  881. if (activated)
  882. {
  883. carla_stderr("CarlaJackAppClient error: runNonRealtimeThread ended while client is activated");
  884. const char* const message("Plugin bridge error, process thread has stopped");
  885. const std::size_t messageSize(std::strlen(message));
  886. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  887. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  888. fShmNonRtServerControl.writeUInt(messageSize);
  889. fShmNonRtServerControl.writeCustomData(message, messageSize);
  890. fShmNonRtServerControl.commitWrite();
  891. }
  892. }
  893. if (fRealtimeThread.isThreadRunning())
  894. {
  895. fRealtimeThread.signalThreadShouldExit();
  896. const CarlaMutexLocker cml(fRealtimeThreadMutex);
  897. if (fShmRtClientControl.data != nullptr)
  898. fShmRtClientControl.data->procFlags = 1;
  899. }
  900. clearSharedMemory();
  901. fRealtimeThread.stopThread(5000);
  902. carla_debug("CarlaJackAppClient runNonRealtimeThread FINISHED");
  903. }
  904. // ---------------------------------------------------------------------------------------------------------------------
  905. static CarlaJackAppClient gClient;
  906. static int carla_interposed_callback(int cb_action, void* ptr)
  907. {
  908. return gClient.handleInterposerCallback(cb_action, ptr);
  909. }
  910. // ---------------------------------------------------------------------------------------------------------------------
  911. CARLA_EXPORT
  912. jack_client_t* jack_client_open(const char* client_name, jack_options_t options, jack_status_t* status, ...)
  913. {
  914. carla_debug("%s(%s, 0x%x, %p)", __FUNCTION__, client_name, options, status);
  915. if (JackClientState* const client = gClient.createClient(client_name))
  916. {
  917. if (status != nullptr)
  918. *status = static_cast<JackStatus>(0x0);
  919. return (jack_client_t*)client;
  920. }
  921. if (status != nullptr)
  922. *status = JackServerError;
  923. return nullptr;
  924. // unused
  925. (void)options;
  926. }
  927. CARLA_EXPORT
  928. jack_client_t* jack_client_new(const char* client_name)
  929. {
  930. return jack_client_open(client_name, JackNullOption, nullptr);
  931. }
  932. CARLA_EXPORT
  933. int jack_client_close(jack_client_t* client)
  934. {
  935. carla_debug("%s(%p)", __FUNCTION__, client);
  936. JackClientState* const jclient = (JackClientState*)client;
  937. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  938. gClient.destroyClient(jclient);
  939. return 0;
  940. }
  941. CARLA_EXPORT
  942. int jack_activate(jack_client_t* client)
  943. {
  944. carla_debug("%s(%p)", __FUNCTION__, client);
  945. JackClientState* const jclient = (JackClientState*)client;
  946. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  947. return gClient.activateClient(jclient) ? 0 : 1;
  948. }
  949. CARLA_EXPORT
  950. int jack_deactivate(jack_client_t* client)
  951. {
  952. carla_debug("%s(%p)", __FUNCTION__, client);
  953. JackClientState* const jclient = (JackClientState*)client;
  954. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 1);
  955. return gClient.deactivateClient(jclient) ? 0 : 1;
  956. }
  957. // ---------------------------------------------------------------------------------------------------------------------
  958. CARLA_EXPORT
  959. pthread_t jack_client_thread_id(jack_client_t* client)
  960. {
  961. carla_debug("%s(%p)", __FUNCTION__, client);
  962. JackClientState* const jclient = (JackClientState*)client;
  963. CARLA_SAFE_ASSERT_RETURN(jclient != nullptr, 0);
  964. CarlaJackAppClient* const jackAppPtr = jclient->server.jackAppPtr;
  965. CARLA_SAFE_ASSERT_RETURN(jackAppPtr != nullptr && jackAppPtr == &gClient, 0);
  966. return jackAppPtr->getRealtimeThreadId();
  967. }
  968. CARLA_BACKEND_END_NAMESPACE
  969. // ---------------------------------------------------------------------------------------------------------------------
  970. #include "jackbridge/JackBridge2.cpp"
  971. #include "CarlaBridgeUtils.cpp"
  972. // ---------------------------------------------------------------------------------------------------------------------
  973. // TODO
  974. CARLA_BACKEND_USE_NAMESPACE
  975. CARLA_EXPORT
  976. int jack_client_real_time_priority(jack_client_t* client)
  977. {
  978. carla_debug("%s(%p)", __FUNCTION__, client);
  979. // code as used by water
  980. const int minPriority = sched_get_priority_min(SCHED_RR);
  981. const int maxPriority = sched_get_priority_max(SCHED_RR);
  982. return ((maxPriority - minPriority) * 9) / 10 + minPriority;
  983. // unused
  984. (void)client;
  985. }
  986. int jack_client_create_thread(jack_client_t* client, pthread_t* thread, int priority,
  987. int realtime, void *(*start_routine)(void*), void* arg)
  988. {
  989. carla_stderr2("%s(%p, %p, %i, %i, %p, %p)", __FUNCTION__, client, thread, priority, realtime, start_routine, arg);
  990. return ENOSYS;
  991. }
  992. typedef void (*JackSessionCallback)(jack_session_event_t*, void*);
  993. CARLA_EXPORT
  994. int jack_set_session_callback(jack_client_t* client, JackSessionCallback callback, void* arg)
  995. {
  996. carla_stderr2("%s(%p, %p, %p)", __FUNCTION__, client, callback, arg);
  997. return 0;
  998. }
  999. // ---------------------------------------------------------------------------------------------------------------------