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.

1228 lines
42KB

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