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.

4565 lines
161KB

  1. // SPDX-FileCopyrightText: 2011-2024 Filipe Coelho <falktx@falktx.com>
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "CarlaEngineClient.hpp"
  4. #include "CarlaEngineInit.hpp"
  5. #include "CarlaEngineInternal.hpp"
  6. #include "CarlaPlugin.hpp"
  7. #include "CarlaBackendUtils.hpp"
  8. #include "CarlaEngineUtils.hpp"
  9. #include "CarlaMathUtils.hpp"
  10. #include "CarlaMIDI.h"
  11. #include "CarlaPatchbayUtils.hpp"
  12. #include "CarlaStringList.hpp"
  13. #include "jackey.h"
  14. #ifdef __SSE2_MATH__
  15. # include <xmmintrin.h>
  16. #endif
  17. // must be last
  18. #include "jackbridge/JackBridge.hpp"
  19. #ifdef JACKBRIDGE_DIRECT
  20. # define JackPortIsControlVoltage 0x100
  21. #endif
  22. #define URI_CANVAS_ICON "http://kxstudio.sf.net/ns/canvas/icon"
  23. #define URI_MAIN_CLIENT_NAME "https://kx.studio/ns/carla/main-client-name"
  24. #define URI_POSITION "https://kx.studio/ns/carla/position"
  25. #define URI_PLUGIN_ICON "https://kx.studio/ns/carla/plugin-icon"
  26. #define URI_PLUGIN_ID "https://kx.studio/ns/carla/plugin-id"
  27. #define URI_TYPE_INTEGER "http://www.w3.org/2001/XMLSchema#integer"
  28. #define URI_TYPE_STRING "text/plain"
  29. CARLA_BACKEND_START_NAMESPACE
  30. class CarlaEngineJack;
  31. class CarlaEngineJackClient;
  32. #ifndef BUILD_BRIDGE
  33. struct CarlaJackPortHints {
  34. bool isHardware : 1;
  35. bool isInput : 1;
  36. bool isAudio : 1;
  37. bool isMIDI : 1;
  38. bool isCV : 1;
  39. bool isOSC : 1;
  40. // NOTE: assumes fThreadSafeMetadataMutex lock done from caller
  41. static CarlaJackPortHints fromPort(const jack_port_t* const jackPort)
  42. {
  43. CarlaJackPortHints ph = { false, false, false, false, false, false };
  44. const int portFlags = jackbridge_port_flags(jackPort);
  45. const char* const portType = jackbridge_port_type(jackPort);
  46. ph.isHardware = portFlags & JackPortIsPhysical;
  47. ph.isInput = portFlags & JackPortIsInput;
  48. ph.isAudio = portType != nullptr && std::strcmp(portType, JACK_DEFAULT_AUDIO_TYPE) == 0;
  49. ph.isMIDI = portType != nullptr && std::strcmp(portType, JACK_DEFAULT_MIDI_TYPE) == 0;
  50. ph.isCV = false;
  51. ph.isOSC = false;
  52. if (ph.isAudio && portFlags & JackPortIsControlVoltage)
  53. {
  54. ph.isAudio = false;
  55. ph.isCV = true;
  56. }
  57. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  58. {
  59. char* value = nullptr;
  60. char* type = nullptr;
  61. if (jackbridge_get_property(uuid, JACKEY_SIGNAL_TYPE, &value, &type)
  62. && value != nullptr
  63. && type != nullptr
  64. && std::strcmp(type, URI_TYPE_STRING) == 0)
  65. {
  66. ph.isCV = (std::strcmp(value, "CV") == 0);
  67. ph.isOSC = (std::strcmp(value, "OSC") == 0);
  68. if (ph.isCV)
  69. ph.isAudio = false;
  70. if (ph.isOSC)
  71. ph.isMIDI = false;
  72. jackbridge_free(value);
  73. jackbridge_free(type);
  74. }
  75. }
  76. return ph;
  77. }
  78. };
  79. #endif
  80. // -----------------------------------------------------------------------
  81. // Fallback data
  82. #ifndef BUILD_BRIDGE
  83. static const GroupNameToId kGroupNameToIdFallback = { 0, { '\0' } };
  84. static /* */ PortNameToId kPortNameToIdFallbackNC = { 0, 0, { '\0' }, { '\0' }, { '\0' } };
  85. static const PortNameToId kPortNameToIdFallback = { 0, 0, { '\0' }, { '\0' }, { '\0' } };
  86. static const ConnectionToId kConnectionToIdFallback = { 0, 0, 0, 0, 0 };
  87. #endif
  88. static EngineEvent kFallbackJackEngineEvent = {
  89. kEngineEventTypeNull, 0, 0, {{ kEngineControlEventTypeNull, 0, -1, 0.0f, true }}
  90. };
  91. // -----------------------------------------------------------------------
  92. // Carla Engine Port removal helper
  93. class CarlaEngineJackAudioPort;
  94. class CarlaEngineJackCVPort;
  95. class CarlaEngineJackEventPort;
  96. struct JackPortDeletionCallback {
  97. virtual ~JackPortDeletionCallback() noexcept {}
  98. virtual void jackAudioPortDeleted(CarlaEngineJackAudioPort* const) noexcept = 0;
  99. virtual void jackCVPortDeleted(CarlaEngineJackCVPort* const) noexcept = 0;
  100. virtual void jackEventPortDeleted(CarlaEngineJackEventPort* const) noexcept = 0;
  101. };
  102. // -----------------------------------------------------------------------
  103. // Carla Engine JACK-Audio port
  104. class CarlaEngineJackAudioPort : public CarlaEngineAudioPort
  105. {
  106. public:
  107. CarlaEngineJackAudioPort(const CarlaEngineClient& client,
  108. const bool isInputPort,
  109. const uint32_t indexOffset,
  110. jack_client_t* const jackClient,
  111. jack_port_t* const jackPort,
  112. CarlaRecursiveMutex& rmutex,
  113. JackPortDeletionCallback* const delCallback) noexcept
  114. : CarlaEngineAudioPort(client, isInputPort, indexOffset),
  115. fJackClient(jackClient),
  116. fJackPort(jackPort),
  117. fThreadSafeMetadataMutex(rmutex),
  118. kDeletionCallback(delCallback)
  119. {
  120. carla_debug("CarlaEngineJackAudioPort::CarlaEngineJackAudioPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  121. switch (kClient.getEngine().getProccessMode())
  122. {
  123. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  124. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  125. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  126. {
  127. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  128. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  129. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "AUDIO", URI_TYPE_STRING);
  130. }
  131. break;
  132. default:
  133. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  134. break;
  135. }
  136. }
  137. ~CarlaEngineJackAudioPort() noexcept override
  138. {
  139. carla_debug("CarlaEngineJackAudioPort::~CarlaEngineJackAudioPort()");
  140. if (fJackClient != nullptr && fJackPort != nullptr)
  141. {
  142. try {
  143. jackbridge_port_unregister(fJackClient, fJackPort);
  144. } CARLA_SAFE_EXCEPTION("Audio port unregister");
  145. fJackClient = nullptr;
  146. fJackPort = nullptr;
  147. }
  148. if (kDeletionCallback != nullptr)
  149. kDeletionCallback->jackAudioPortDeleted(this);
  150. }
  151. void initBuffer() noexcept override
  152. {
  153. if (fJackPort == nullptr)
  154. return CarlaEngineAudioPort::initBuffer();
  155. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  156. try {
  157. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  158. }
  159. catch(...) {
  160. fBuffer = nullptr;
  161. return;
  162. }
  163. if (! kIsInput)
  164. carla_zeroFloats(fBuffer, bufferSize);
  165. }
  166. void invalidate() noexcept
  167. {
  168. fJackClient = nullptr;
  169. fJackPort = nullptr;
  170. }
  171. void setMetaData(const char* const key, const char* const value, const char* const type) override
  172. {
  173. if (fJackPort == nullptr)
  174. return CarlaEngineAudioPort::setMetaData(key, value, type);
  175. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  176. try {
  177. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  178. jackbridge_set_property(fJackClient, uuid, key, value, type);
  179. } CARLA_SAFE_EXCEPTION("Port setMetaData");
  180. }
  181. private:
  182. jack_client_t* fJackClient;
  183. jack_port_t* fJackPort;
  184. CarlaRecursiveMutex& fThreadSafeMetadataMutex;
  185. JackPortDeletionCallback* const kDeletionCallback;
  186. friend class CarlaEngineJackClient;
  187. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackAudioPort)
  188. };
  189. // -----------------------------------------------------------------------
  190. // Carla Engine JACK-CV port
  191. class CarlaEngineJackCVPort : public CarlaEngineCVPort
  192. {
  193. public:
  194. CarlaEngineJackCVPort(const CarlaEngineClient& client,
  195. const bool isInputPort,
  196. const uint32_t indexOffset,
  197. jack_client_t* const jackClient,
  198. jack_port_t* const jackPort,
  199. CarlaRecursiveMutex& rmutex,
  200. JackPortDeletionCallback* const delCallback) noexcept
  201. : CarlaEngineCVPort(client, isInputPort, indexOffset),
  202. fJackClient(jackClient),
  203. fJackPort(jackPort),
  204. fThreadSafeMetadataMutex(rmutex),
  205. kDeletionCallback(delCallback)
  206. {
  207. carla_debug("CarlaEngineJackCVPort::CarlaEngineJackCVPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  208. switch (kClient.getEngine().getProccessMode())
  209. {
  210. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  211. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  212. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  213. {
  214. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  215. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  216. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "CV", URI_TYPE_STRING);
  217. }
  218. break;
  219. default:
  220. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  221. break;
  222. }
  223. }
  224. ~CarlaEngineJackCVPort() noexcept override
  225. {
  226. carla_debug("CarlaEngineJackCVPort::~CarlaEngineJackCVPort()");
  227. if (fJackClient != nullptr && fJackPort != nullptr)
  228. {
  229. try {
  230. jackbridge_port_unregister(fJackClient, fJackPort);
  231. } CARLA_SAFE_EXCEPTION("CV port unregister");
  232. fJackClient = nullptr;
  233. fJackPort = nullptr;
  234. }
  235. if (kDeletionCallback != nullptr)
  236. kDeletionCallback->jackCVPortDeleted(this);
  237. }
  238. void initBuffer() noexcept override
  239. {
  240. if (fJackPort == nullptr)
  241. return CarlaEngineCVPort::initBuffer();
  242. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  243. try {
  244. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  245. }
  246. catch(...) {
  247. fBuffer = nullptr;
  248. return;
  249. }
  250. if (! kIsInput)
  251. carla_zeroFloats(fBuffer, bufferSize);
  252. }
  253. void invalidate() noexcept
  254. {
  255. fJackClient = nullptr;
  256. fJackPort = nullptr;
  257. }
  258. void setMetaData(const char* const key, const char* const value, const char* const type) override
  259. {
  260. if (fJackPort == nullptr)
  261. return CarlaEngineCVPort::setMetaData(key, value, type);
  262. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  263. try {
  264. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  265. jackbridge_set_property(fJackClient, uuid, key, value, type);
  266. } CARLA_SAFE_EXCEPTION("Port setMetaData");
  267. }
  268. private:
  269. jack_client_t* fJackClient;
  270. jack_port_t* fJackPort;
  271. CarlaRecursiveMutex& fThreadSafeMetadataMutex;
  272. JackPortDeletionCallback* const kDeletionCallback;
  273. friend class CarlaEngineJackClient;
  274. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackCVPort)
  275. };
  276. // -----------------------------------------------------------------------
  277. // Carla Engine JACK-Event port
  278. class CarlaEngineJackEventPort : public CarlaEngineEventPort
  279. {
  280. public:
  281. CarlaEngineJackEventPort(const CarlaEngineClient& client,
  282. const bool isInputPort,
  283. const uint32_t indexOffset,
  284. jack_client_t* const jackClient,
  285. jack_port_t* const jackPort,
  286. CarlaRecursiveMutex& rmutex,
  287. JackPortDeletionCallback* const delCallback) noexcept
  288. : CarlaEngineEventPort(client, isInputPort, indexOffset),
  289. fJackClient(jackClient),
  290. fJackPort(jackPort),
  291. fJackBuffer(nullptr),
  292. fRetEvent(kFallbackJackEngineEvent),
  293. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  294. fCvSourceEvents(nullptr),
  295. fCvSourceEventCount(0),
  296. #endif
  297. fThreadSafeMetadataMutex(rmutex),
  298. kDeletionCallback(delCallback)
  299. {
  300. carla_debug("CarlaEngineJackEventPort::CarlaEngineJackEventPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  301. switch (kClient.getEngine().getProccessMode())
  302. {
  303. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  304. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  305. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  306. break;
  307. default:
  308. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  309. break;
  310. }
  311. }
  312. ~CarlaEngineJackEventPort() noexcept override
  313. {
  314. carla_debug("CarlaEngineJackEventPort::~CarlaEngineJackEventPort()");
  315. if (fJackClient != nullptr && fJackPort != nullptr)
  316. {
  317. try {
  318. jackbridge_port_unregister(fJackClient, fJackPort);
  319. } CARLA_SAFE_EXCEPTION("Event port unregister");
  320. fJackClient = nullptr;
  321. fJackPort = nullptr;
  322. }
  323. if (kDeletionCallback != nullptr)
  324. kDeletionCallback->jackEventPortDeleted(this);
  325. }
  326. void initBuffer() noexcept override
  327. {
  328. if (fJackPort == nullptr)
  329. return CarlaEngineEventPort::initBuffer();
  330. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  331. fCvSourceEvents = nullptr;
  332. fCvSourceEventCount = 0;
  333. #endif
  334. try {
  335. fJackBuffer = jackbridge_port_get_buffer(fJackPort, kClient.getEngine().getBufferSize());
  336. }
  337. catch(...) {
  338. fJackBuffer = nullptr;
  339. return;
  340. }
  341. if (! kIsInput)
  342. jackbridge_midi_clear_buffer(fJackBuffer);
  343. }
  344. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  345. void setCvSourceEvents(EngineEvent* const events, const uint32_t eventCount) noexcept
  346. {
  347. fCvSourceEvents = events;
  348. fCvSourceEventCount = eventCount;
  349. }
  350. #endif
  351. uint32_t getEventCount() const noexcept override
  352. {
  353. if (fJackPort == nullptr)
  354. return CarlaEngineEventPort::getEventCount();
  355. CARLA_SAFE_ASSERT_RETURN(kIsInput, 0);
  356. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, 0);
  357. try {
  358. return jackbridge_midi_get_event_count(fJackBuffer)
  359. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  360. + fCvSourceEventCount
  361. #endif
  362. ;
  363. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_get_event_count", 0);
  364. }
  365. EngineEvent& getEvent(const uint32_t index) const noexcept override
  366. {
  367. if (fJackPort == nullptr)
  368. return CarlaEngineEventPort::getEvent(index);
  369. CARLA_SAFE_ASSERT_RETURN(kIsInput, kFallbackJackEngineEvent);
  370. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, kFallbackJackEngineEvent);
  371. return getEventUnchecked(index);
  372. }
  373. EngineEvent& getEventUnchecked(uint32_t index) const noexcept override
  374. {
  375. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  376. if (index < fCvSourceEventCount)
  377. return fCvSourceEvents[index];
  378. index -= fCvSourceEventCount;
  379. #endif
  380. jack_midi_event_t jackEvent;
  381. bool test = false;
  382. try {
  383. test = jackbridge_midi_event_get(&jackEvent, fJackBuffer, index);
  384. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_get", kFallbackJackEngineEvent);
  385. if (! test)
  386. return kFallbackJackEngineEvent;
  387. CARLA_SAFE_ASSERT_RETURN(jackEvent.size < 0xFF /* uint8_t max */, kFallbackJackEngineEvent);
  388. uint8_t port;
  389. if (kIndexOffset < 0xFF /* uint8_t max */)
  390. {
  391. port = static_cast<uint8_t>(kIndexOffset);
  392. }
  393. else
  394. {
  395. port = 0;
  396. carla_safe_assert_uint("kIndexOffset < 0xFF", __FILE__, __LINE__, kIndexOffset);
  397. }
  398. fRetEvent.time = jackEvent.time;
  399. fRetEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer, port);
  400. return fRetEvent;
  401. }
  402. bool writeControlEvent(const uint32_t time, const uint8_t channel,
  403. const EngineControlEventType type,
  404. const uint16_t param,
  405. const int8_t midiValue,
  406. const float value) noexcept override
  407. {
  408. if (fJackPort == nullptr)
  409. return CarlaEngineEventPort::writeControlEvent(time, channel, type, param, midiValue, value);
  410. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  411. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  412. CARLA_SAFE_ASSERT_RETURN(type != kEngineControlEventTypeNull, false);
  413. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  414. CARLA_SAFE_ASSERT_RETURN(param < MAX_MIDI_VALUE, false);
  415. CARLA_SAFE_ASSERT(value >= 0.0f && value <= 1.0f);
  416. if (type == kEngineControlEventTypeParameter) {
  417. CARLA_SAFE_ASSERT(! MIDI_IS_CONTROL_BANK_SELECT(param));
  418. }
  419. uint8_t data[3] = { 0, 0, 0 };
  420. EngineControlEvent ctrlEvent = { type, param, midiValue, value, false };
  421. const uint8_t size = ctrlEvent.convertToMidiData(channel, data);
  422. if (size == 0)
  423. return false;
  424. try {
  425. return jackbridge_midi_event_write(fJackBuffer, time, data, size);
  426. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  427. }
  428. bool writeMidiEvent(const uint32_t time, const uint8_t channel, const uint8_t size, const uint8_t* const data) noexcept override
  429. {
  430. if (fJackPort == nullptr)
  431. return CarlaEngineEventPort::writeMidiEvent(time, channel, size, data);
  432. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  433. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  434. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  435. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  436. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  437. jack_midi_data_t jdata[size];
  438. jdata[0] = static_cast<jack_midi_data_t>(MIDI_GET_STATUS_FROM_DATA(data) + channel);
  439. for (uint8_t i=1; i < size; ++i)
  440. jdata[i] = data[i];
  441. try {
  442. return jackbridge_midi_event_write(fJackBuffer, time, jdata, size);
  443. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  444. }
  445. void invalidate() noexcept
  446. {
  447. fJackClient = nullptr;
  448. fJackPort = nullptr;
  449. }
  450. void setMetaData(const char* const key, const char* const value, const char* const type) override
  451. {
  452. if (fJackPort == nullptr)
  453. return CarlaEngineEventPort::setMetaData(key, value, type);
  454. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  455. try {
  456. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  457. jackbridge_set_property(fJackClient, uuid, key, value, type);
  458. } CARLA_SAFE_EXCEPTION("Port setMetaData");
  459. }
  460. private:
  461. jack_client_t* fJackClient;
  462. jack_port_t* fJackPort;
  463. void* fJackBuffer;
  464. mutable EngineEvent fRetEvent;
  465. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  466. EngineEvent* fCvSourceEvents;
  467. uint32_t fCvSourceEventCount;
  468. #endif
  469. CarlaRecursiveMutex& fThreadSafeMetadataMutex;
  470. JackPortDeletionCallback* const kDeletionCallback;
  471. friend class CarlaEngineJackClient;
  472. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackEventPort)
  473. };
  474. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  475. // -----------------------------------------------------------------------
  476. // Jack Engine CV source ports
  477. class CarlaEngineJackCVSourcePorts : public CarlaEngineCVSourcePorts
  478. {
  479. public:
  480. CarlaEngineJackCVSourcePorts(const bool useClient)
  481. : CarlaEngineCVSourcePorts(),
  482. fUseClient(useClient),
  483. fBuffer(nullptr),
  484. fBufferToDeleteLater(nullptr)
  485. {}
  486. ~CarlaEngineJackCVSourcePorts() override
  487. {
  488. if (fBufferToDeleteLater != nullptr)
  489. {
  490. delete[] fBufferToDeleteLater;
  491. fBufferToDeleteLater = nullptr;
  492. }
  493. }
  494. bool addCVSource(CarlaEngineCVPort* const port, const uint32_t portIndexOffset, const bool reconfigureNow) override
  495. {
  496. if (! fUseClient)
  497. return CarlaEngineCVSourcePorts::addCVSource(port, portIndexOffset, reconfigureNow);
  498. const CarlaRecursiveMutexLocker crml(pData->rmutex);
  499. if (! CarlaEngineCVSourcePorts::addCVSource(port, portIndexOffset, reconfigureNow))
  500. return false;
  501. if (pData->cvs.size() == 1 && fBuffer == nullptr)
  502. {
  503. EngineEvent* const buffer = new EngineEvent[kMaxEngineEventInternalCount];
  504. carla_zeroStructs(buffer, kMaxEngineEventInternalCount);
  505. fBuffer = buffer;
  506. }
  507. return true;
  508. }
  509. bool removeCVSource(const uint32_t portIndexOffset) override
  510. {
  511. if (! fUseClient)
  512. return CarlaEngineCVSourcePorts::removeCVSource(portIndexOffset);
  513. const CarlaRecursiveMutexLocker crml(pData->rmutex);
  514. if (! CarlaEngineCVSourcePorts::removeCVSource(portIndexOffset))
  515. return false;
  516. if (pData->cvs.size() == 0 && fBuffer != nullptr)
  517. {
  518. if (fBufferToDeleteLater != nullptr)
  519. delete[] fBufferToDeleteLater;
  520. fBufferToDeleteLater = fBuffer;
  521. fBuffer = nullptr;
  522. }
  523. return true;
  524. }
  525. void initPortBuffers(const float* const* const buffers,
  526. const uint32_t frames,
  527. const bool sampleAccurate,
  528. CarlaEngineEventPort* const eventPort) override
  529. {
  530. if (! fUseClient)
  531. return CarlaEngineCVSourcePorts::initPortBuffers(buffers, frames, sampleAccurate, eventPort);
  532. CARLA_SAFE_ASSERT_RETURN(buffers != nullptr,);
  533. CARLA_SAFE_ASSERT_RETURN(eventPort != nullptr,);
  534. const CarlaRecursiveMutexTryLocker crmtl(pData->rmutex);
  535. if (! crmtl.wasLocked())
  536. return;
  537. const int numCVs = pData->cvs.size();
  538. if (numCVs == 0)
  539. return;
  540. EngineEvent* const buffer = fBuffer;
  541. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr,);
  542. uint32_t eventCount = 0;
  543. float v, min, max;
  544. for (int i = 0; i < numCVs && eventCount < kMaxEngineEventInternalCount; ++i)
  545. {
  546. CarlaEngineEventCV& ecv(pData->cvs.getReference(i));
  547. CARLA_SAFE_ASSERT_CONTINUE(ecv.cvPort != nullptr);
  548. CARLA_SAFE_ASSERT_CONTINUE(buffers[i] != nullptr);
  549. float previousValue = ecv.previousValue;
  550. ecv.cvPort->getRange(min, max);
  551. v = buffers[i][0];
  552. if (carla_isNotEqual(v, previousValue))
  553. {
  554. previousValue = v;
  555. EngineEvent& event(buffer[eventCount++]);
  556. event.type = kEngineEventTypeControl;
  557. event.time = 0;
  558. event.channel = kEngineEventNonMidiChannel;
  559. event.ctrl.type = kEngineControlEventTypeParameter;
  560. event.ctrl.param = static_cast<uint16_t>(ecv.indexOffset);
  561. event.ctrl.midiValue = -1;
  562. event.ctrl.normalizedValue = carla_fixedValue(0.0f, 1.0f, (v - min) / (max - min));
  563. }
  564. ecv.previousValue = previousValue;
  565. }
  566. if (eventCount != 0)
  567. if (CarlaEngineJackEventPort* const jackEventPort = dynamic_cast<CarlaEngineJackEventPort*>(eventPort))
  568. jackEventPort->setCvSourceEvents(buffer, eventCount);
  569. }
  570. CarlaRecursiveMutex& getMutex() const noexcept
  571. {
  572. return pData->rmutex;
  573. }
  574. uint32_t getPortCount() const noexcept
  575. {
  576. return static_cast<uint32_t>(pData->cvs.size());
  577. }
  578. CarlaEngineCVPort* getPort(const uint32_t portIndexOffset) const
  579. {
  580. const int ioffset = static_cast<int>(portIndexOffset);
  581. return pData->cvs[ioffset].cvPort;
  582. }
  583. void resetGraphAndPlugin() noexcept
  584. {
  585. pData->graph = nullptr;
  586. pData->plugin.reset();
  587. }
  588. void setGraphAndPlugin(PatchbayGraph* const graph, const CarlaPluginPtr plugin) noexcept
  589. {
  590. pData->graph = graph;
  591. pData->plugin = plugin;
  592. }
  593. private:
  594. const bool fUseClient;
  595. EngineEvent* fBuffer;
  596. EngineEvent* fBufferToDeleteLater;
  597. CARLA_DECLARE_NON_COPYABLE(CarlaEngineJackCVSourcePorts)
  598. };
  599. #endif
  600. // -----------------------------------------------------------------------
  601. // Jack Engine client
  602. class CarlaEngineJackClient : public CarlaEngineClientForSubclassing,
  603. private JackPortDeletionCallback
  604. {
  605. public:
  606. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  607. CarlaEngineJackClient(const CarlaEngine& engine,
  608. EngineInternalGraph& egraph,
  609. CarlaRecursiveMutex& rmutex,
  610. const CarlaPluginPtr plugin,
  611. const CarlaString& mainClientName,
  612. jack_client_t* const jackClient)
  613. : CarlaEngineClientForSubclassing(engine, egraph, plugin),
  614. #else
  615. CarlaEngineJackClient(const CarlaEngine& engine,
  616. CarlaRecursiveMutex& rmutex,
  617. const CarlaString& mainClientName,
  618. jack_client_t* const jackClient)
  619. : CarlaEngineClientForSubclassing(engine),
  620. #endif
  621. fJackClient(jackClient),
  622. fUseClient(engine.getProccessMode() == ENGINE_PROCESS_MODE_SINGLE_CLIENT ||
  623. engine.getProccessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS),
  624. fAudioPorts(),
  625. fCVPorts(),
  626. fEventPorts(),
  627. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  628. fCVSourcePorts(fUseClient),
  629. fPreRenameMutex(),
  630. fPreRenameConnections(),
  631. fPreRenamePluginId(),
  632. fPreRenamePluginIcon(),
  633. fReservedPluginPtr(),
  634. #endif
  635. fThreadSafeMetadataMutex(rmutex),
  636. fMainClientName(mainClientName)
  637. {
  638. carla_debug("CarlaEngineJackClient::CarlaEngineJackClient(%p)", jackClient);
  639. if (fUseClient)
  640. {
  641. CARLA_SAFE_ASSERT(jackClient != nullptr);
  642. }
  643. else
  644. {
  645. CARLA_SAFE_ASSERT(jackClient == nullptr);
  646. }
  647. }
  648. ~CarlaEngineJackClient() noexcept override
  649. {
  650. carla_debug("CarlaEngineJackClient::~CarlaEngineJackClient()");
  651. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS && fJackClient != nullptr) // FIXME
  652. jackbridge_client_close(fJackClient);
  653. // ports must have been deleted by now!
  654. //fAudioPorts.clear();
  655. //fCVPorts.clear();
  656. //fEventPorts.clear();
  657. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  658. const CarlaMutexLocker cml(fPreRenameMutex);
  659. fPreRenameConnections.clear();
  660. fPreRenamePluginId.clear();
  661. fPreRenamePluginIcon.clear();
  662. #endif
  663. }
  664. void activate() noexcept override
  665. {
  666. carla_debug("CarlaEngineJackClient::activate()");
  667. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  668. {
  669. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && ! isActive(),);
  670. try {
  671. jackbridge_activate(fJackClient);
  672. } catch(...) {}
  673. }
  674. CarlaEngineClient::activate();
  675. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  676. const CarlaMutexLocker cml(fPreRenameMutex);
  677. if (fJackClient != nullptr)
  678. {
  679. // restore pre-rename connections
  680. const char* portNameA = nullptr;
  681. const char* portNameB = nullptr;
  682. bool doConnection = false;
  683. for (CarlaStringList::Itenerator it = fPreRenameConnections.begin2(); it.valid(); it.next())
  684. {
  685. const bool connectNow = doConnection;
  686. doConnection = !doConnection;
  687. if (connectNow)
  688. portNameB = it.getValue(nullptr);
  689. else
  690. portNameA = it.getValue(nullptr);
  691. if (! connectNow)
  692. continue;
  693. CARLA_SAFE_ASSERT_CONTINUE(portNameA != nullptr && portNameA[0] != '\0');
  694. CARLA_SAFE_ASSERT_CONTINUE(portNameB != nullptr && portNameB[0] != '\0');
  695. jackbridge_connect(fJackClient, portNameA, portNameB);
  696. }
  697. if (fPreRenamePluginId.isNotEmpty())
  698. {
  699. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  700. if (char* const uuidstr = jackbridge_client_get_uuid(fJackClient))
  701. {
  702. jack_uuid_t uuid;
  703. if (jackbridge_uuid_parse(uuidstr, &uuid))
  704. {
  705. jackbridge_set_property(fJackClient, uuid,
  706. URI_MAIN_CLIENT_NAME,
  707. fMainClientName,
  708. URI_TYPE_STRING);
  709. jackbridge_set_property(fJackClient, uuid,
  710. URI_PLUGIN_ID,
  711. fPreRenamePluginId,
  712. URI_TYPE_INTEGER);
  713. if (fPreRenamePluginIcon.isNotEmpty())
  714. jackbridge_set_property(fJackClient, uuid,
  715. URI_PLUGIN_ICON,
  716. fPreRenamePluginIcon,
  717. URI_TYPE_STRING);
  718. }
  719. jackbridge_free(uuidstr);
  720. }
  721. }
  722. }
  723. fPreRenameConnections.clear();
  724. fPreRenamePluginId.clear();
  725. fPreRenamePluginIcon.clear();
  726. #endif
  727. }
  728. void deactivate(const bool willClose) noexcept override
  729. {
  730. carla_debug("CarlaEngineJackClient::deactivate(%s)", bool2str(willClose));
  731. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  732. {
  733. if (fJackClient != nullptr && isActive())
  734. {
  735. try {
  736. jackbridge_deactivate(fJackClient);
  737. } catch(...) {}
  738. }
  739. }
  740. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  741. if (willClose)
  742. {
  743. fCVSourcePorts.resetGraphAndPlugin();
  744. fReservedPluginPtr = nullptr;
  745. }
  746. #endif
  747. CarlaEngineClient::deactivate(willClose);
  748. }
  749. bool isOk() const noexcept override
  750. {
  751. if (fUseClient)
  752. return (fJackClient != nullptr);
  753. return CarlaEngineClient::isOk();
  754. }
  755. CarlaEnginePort* addPort(const EnginePortType portType, const char* const name, const bool isInput, const uint32_t indexOffset) override
  756. {
  757. carla_debug("CarlaEngineJackClient::addPort(%i:%s, \"%s\", %s)", portType, EnginePortType2Str(portType), name, bool2str(isInput));
  758. jack_port_t* jackPort = nullptr;
  759. const char* realName = name;
  760. // Create JACK port first, if needed
  761. if (fUseClient)
  762. {
  763. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  764. realName = pData->getUniquePortName(name);
  765. switch (portType)
  766. {
  767. case kEnginePortTypeNull:
  768. break;
  769. case kEnginePortTypeAudio:
  770. jackPort = jackbridge_port_register(fJackClient,
  771. realName,
  772. JACK_DEFAULT_AUDIO_TYPE,
  773. isInput ? JackPortIsInput : JackPortIsOutput,
  774. 0);
  775. break;
  776. case kEnginePortTypeCV:
  777. jackPort = jackbridge_port_register(fJackClient,
  778. realName,
  779. JACK_DEFAULT_AUDIO_TYPE,
  780. static_cast<uint64_t>(JackPortIsControlVoltage |
  781. (isInput ? JackPortIsInput
  782. : JackPortIsOutput)),
  783. 0);
  784. break;
  785. case kEnginePortTypeEvent:
  786. jackPort = jackbridge_port_register(fJackClient,
  787. realName,
  788. JACK_DEFAULT_MIDI_TYPE,
  789. isInput ? JackPortIsInput : JackPortIsOutput,
  790. 0);
  791. break;
  792. }
  793. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr, nullptr);
  794. }
  795. // Create Engine port
  796. switch (portType)
  797. {
  798. case kEnginePortTypeNull:
  799. break;
  800. case kEnginePortTypeAudio: {
  801. pData->addAudioPortName(isInput, realName);
  802. if (realName != name) delete[] realName;
  803. CarlaEngineJackAudioPort* const enginePort(new CarlaEngineJackAudioPort(*this,
  804. isInput,
  805. indexOffset,
  806. fJackClient,
  807. jackPort,
  808. fThreadSafeMetadataMutex,
  809. this));
  810. fAudioPorts.append(enginePort);
  811. return enginePort;
  812. }
  813. case kEnginePortTypeCV: {
  814. pData->addCVPortName(isInput, realName);
  815. if (realName != name) delete[] realName;
  816. CarlaEngineJackCVPort* const enginePort(new CarlaEngineJackCVPort(*this,
  817. isInput,
  818. indexOffset,
  819. fJackClient,
  820. jackPort,
  821. fThreadSafeMetadataMutex,
  822. this));
  823. fCVPorts.append(enginePort);
  824. return enginePort;
  825. }
  826. case kEnginePortTypeEvent: {
  827. pData->addEventPortName(isInput, realName);
  828. if (realName != name) delete[] realName;
  829. CarlaEngineJackEventPort* const enginePort(new CarlaEngineJackEventPort(*this,
  830. isInput,
  831. indexOffset,
  832. fJackClient,
  833. jackPort,
  834. fThreadSafeMetadataMutex,
  835. this));
  836. fEventPorts.append(enginePort);
  837. return enginePort;
  838. }
  839. }
  840. carla_stderr("CarlaEngineJackClient::addPort(%i, \"%s\", %s) - invalid type", portType, name, bool2str(isInput));
  841. return nullptr;
  842. }
  843. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  844. CarlaEngineCVSourcePorts* createCVSourcePorts() override
  845. {
  846. fCVSourcePorts.setGraphAndPlugin(getPatchbayGraphOrNull(), getPlugin());
  847. return &fCVSourcePorts;
  848. }
  849. CarlaEngineJackCVSourcePorts& getCVSourcePorts() noexcept
  850. {
  851. return fCVSourcePorts;
  852. }
  853. #endif
  854. void invalidate() noexcept
  855. {
  856. for (LinkedList<CarlaEngineJackAudioPort*>::Itenerator it = fAudioPorts.begin2(); it.valid(); it.next())
  857. {
  858. CarlaEngineJackAudioPort* const port(it.getValue(nullptr));
  859. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  860. port->invalidate();
  861. }
  862. for (LinkedList<CarlaEngineJackCVPort*>::Itenerator it = fCVPorts.begin2(); it.valid(); it.next())
  863. {
  864. CarlaEngineJackCVPort* const port(it.getValue(nullptr));
  865. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  866. port->invalidate();
  867. }
  868. for (LinkedList<CarlaEngineJackEventPort*>::Itenerator it = fEventPorts.begin2(); it.valid(); it.next())
  869. {
  870. CarlaEngineJackEventPort* const port(it.getValue(nullptr));
  871. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  872. port->invalidate();
  873. }
  874. fJackClient = nullptr;
  875. CarlaEngineClient::deactivate(true);
  876. }
  877. const char* getJackClientName() const noexcept
  878. {
  879. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  880. try {
  881. return jackbridge_get_client_name(fJackClient);
  882. } CARLA_SAFE_EXCEPTION_RETURN("jack_get_client_name", nullptr);
  883. }
  884. void jackAudioPortDeleted(CarlaEngineJackAudioPort* const port) noexcept override
  885. {
  886. fAudioPorts.removeAll(port);
  887. }
  888. void jackCVPortDeleted(CarlaEngineJackCVPort* const port) noexcept override
  889. {
  890. fCVPorts.removeAll(port);
  891. }
  892. void jackEventPortDeleted(CarlaEngineJackEventPort* const port) noexcept override
  893. {
  894. fEventPorts.removeAll(port);
  895. }
  896. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  897. bool renameInSingleClient(const CarlaString& newClientName)
  898. {
  899. const CarlaString clientNamePrefix(newClientName + ":");
  900. return _renamePorts(fAudioPorts, clientNamePrefix) &&
  901. _renamePorts(fCVPorts, clientNamePrefix) &&
  902. _renamePorts(fEventPorts, clientNamePrefix);
  903. }
  904. void closeForRename(jack_client_t* const newClient, const CarlaString& newClientName) noexcept
  905. {
  906. if (fJackClient != nullptr)
  907. {
  908. if (isActive())
  909. {
  910. {
  911. const CarlaString clientNamePrefix(newClientName + ":");
  912. // store current client connections
  913. const CarlaMutexLocker cml(fPreRenameMutex);
  914. fPreRenameConnections.clear();
  915. fPreRenamePluginId.clear();
  916. fPreRenamePluginIcon.clear();
  917. _savePortsConnections(fAudioPorts, clientNamePrefix);
  918. _savePortsConnections(fCVPorts, clientNamePrefix);
  919. _savePortsConnections(fEventPorts, clientNamePrefix);
  920. _saveProperties();
  921. }
  922. try {
  923. jackbridge_deactivate(fJackClient);
  924. } catch(...) {}
  925. }
  926. try {
  927. jackbridge_client_close(fJackClient);
  928. } catch(...) {}
  929. invalidate();
  930. }
  931. fAudioPorts.clear();
  932. fCVPorts.clear();
  933. fEventPorts.clear();
  934. pData->clearPorts();
  935. fJackClient = newClient;
  936. }
  937. void reservePluginPtr(CarlaPluginPtr* const pluginPtr)
  938. {
  939. fReservedPluginPtr = pluginPtr;
  940. }
  941. void setNewPluginId(const uint id) const
  942. {
  943. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr,);
  944. // NOTE: no fThreadSafeMetadataMutex lock here, assumed done from caller
  945. if (char* const uuidstr = jackbridge_client_get_uuid(fJackClient))
  946. {
  947. jack_uuid_t uuid;
  948. if (jackbridge_uuid_parse(uuidstr, &uuid))
  949. {
  950. char buf[32];
  951. std::snprintf(buf, 31, "%u", id);
  952. buf[31] = '\0';
  953. jackbridge_set_property(fJackClient, uuid,
  954. URI_PLUGIN_ID,
  955. buf,
  956. URI_TYPE_INTEGER);
  957. }
  958. jackbridge_free(uuidstr);
  959. }
  960. }
  961. #endif
  962. private:
  963. jack_client_t* fJackClient;
  964. const bool fUseClient;
  965. LinkedList<CarlaEngineJackAudioPort*> fAudioPorts;
  966. LinkedList<CarlaEngineJackCVPort*> fCVPorts;
  967. LinkedList<CarlaEngineJackEventPort*> fEventPorts;
  968. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  969. CarlaEngineJackCVSourcePorts fCVSourcePorts;
  970. CarlaMutex fPreRenameMutex;
  971. CarlaStringList fPreRenameConnections;
  972. CarlaString fPreRenamePluginId;
  973. CarlaString fPreRenamePluginIcon;
  974. CarlaScopedPointer<CarlaPluginPtr> fReservedPluginPtr;
  975. template<typename T>
  976. bool _renamePorts(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  977. {
  978. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  979. {
  980. T* const port(it.getValue(nullptr));
  981. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  982. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  983. const char* shortPortName(jackbridge_port_short_name(port->fJackPort));
  984. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  985. const char* const oldClientNameSep(std::strstr(shortPortName, ":"));
  986. CARLA_SAFE_ASSERT_CONTINUE(oldClientNameSep != nullptr && oldClientNameSep[0] != '\0' && oldClientNameSep[1] != '\0');
  987. shortPortName += oldClientNameSep-shortPortName + 1;
  988. const CarlaString newPortName(clientNamePrefix + shortPortName);
  989. if (! jackbridge_port_rename(fJackClient, port->fJackPort, newPortName))
  990. return false;
  991. }
  992. return true;
  993. }
  994. template<typename T>
  995. void _savePortsConnections(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  996. {
  997. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  998. {
  999. T* const port(it.getValue(nullptr));
  1000. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  1001. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  1002. const char* const shortPortName(jackbridge_port_short_name(port->fJackPort));
  1003. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  1004. const CarlaString portName(clientNamePrefix + shortPortName);
  1005. if (const char** const connections = jackbridge_port_get_all_connections(fJackClient, port->fJackPort))
  1006. {
  1007. for (int i=0; connections[i] != nullptr; ++i)
  1008. {
  1009. if (port->kIsInput)
  1010. {
  1011. fPreRenameConnections.append(connections[i]);
  1012. fPreRenameConnections.append(portName);
  1013. }
  1014. else
  1015. {
  1016. fPreRenameConnections.append(portName);
  1017. fPreRenameConnections.append(connections[i]);
  1018. }
  1019. }
  1020. jackbridge_free(connections);
  1021. }
  1022. }
  1023. }
  1024. void _saveProperties()
  1025. {
  1026. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  1027. if (char* const uuidstr = jackbridge_client_get_uuid(fJackClient))
  1028. {
  1029. jack_uuid_t uuid;
  1030. const bool parsed = jackbridge_uuid_parse(uuidstr, &uuid);
  1031. jackbridge_free(uuidstr);
  1032. CARLA_CUSTOM_SAFE_ASSERT_ONCE_RETURN("JACK meta-data support unavailable", parsed,);
  1033. char* value = nullptr;
  1034. char* type = nullptr;
  1035. CARLA_SAFE_ASSERT_RETURN(jackbridge_get_property(uuid,
  1036. URI_PLUGIN_ID,
  1037. &value,
  1038. &type),);
  1039. CARLA_SAFE_ASSERT_RETURN(type != nullptr,);
  1040. CARLA_SAFE_ASSERT_RETURN(std::strcmp(type, URI_TYPE_INTEGER) == 0,);
  1041. fPreRenamePluginId = value;
  1042. jackbridge_free(value);
  1043. jackbridge_free(type);
  1044. value = type = nullptr;
  1045. if (jackbridge_get_property(uuid, URI_PLUGIN_ICON, &value, &type))
  1046. {
  1047. CARLA_SAFE_ASSERT_RETURN(type != nullptr,);
  1048. CARLA_SAFE_ASSERT_RETURN(std::strcmp(type, URI_TYPE_STRING) == 0,);
  1049. fPreRenamePluginIcon = value;
  1050. jackbridge_free(value);
  1051. jackbridge_free(type);
  1052. }
  1053. }
  1054. }
  1055. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1056. CarlaRecursiveMutex& fThreadSafeMetadataMutex;
  1057. const CarlaString& fMainClientName;
  1058. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackClient)
  1059. };
  1060. // -----------------------------------------------------------------------
  1061. // Jack Engine
  1062. class CarlaEngineJack : public CarlaEngine
  1063. #ifndef BUILD_BRIDGE
  1064. , private CarlaThread
  1065. #endif
  1066. {
  1067. public:
  1068. CarlaEngineJack()
  1069. : CarlaEngine(),
  1070. #ifndef BUILD_BRIDGE
  1071. CarlaThread("CarlaEngineJackCallbacks"),
  1072. #endif
  1073. fClient(nullptr),
  1074. fExternalPatchbayHost(true),
  1075. fExternalPatchbayOsc(true),
  1076. fFreewheel(false),
  1077. fClientName(),
  1078. fThreadSafeMetadataMutex(),
  1079. #ifdef BUILD_BRIDGE
  1080. fIsRunning(false)
  1081. #else
  1082. fClientNamePrefix(),
  1083. fTimebaseMaster(false),
  1084. fTimebaseRolling(false),
  1085. fTimebaseUsecs(0),
  1086. fUsedGroups(),
  1087. fUsedPorts(),
  1088. fUsedConnections(),
  1089. fPatchbayProcThreadProtectionMutex(),
  1090. fRetConns(),
  1091. fLastPatchbaySetGroupPos(),
  1092. fPostPonedEvents(),
  1093. fPostPonedEventsMutex(),
  1094. fIsInternalClient(false)
  1095. #endif
  1096. {
  1097. carla_debug("CarlaEngineJack::CarlaEngineJack()");
  1098. #ifdef BUILD_BRIDGE
  1099. pData->options.processMode = ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  1100. #else
  1101. carla_zeroPointers(fRackPorts, kRackPortCount);
  1102. #endif
  1103. }
  1104. ~CarlaEngineJack() noexcept override
  1105. {
  1106. carla_debug("CarlaEngineJack::~CarlaEngineJack()");
  1107. CARLA_SAFE_ASSERT(fClient == nullptr);
  1108. #ifndef BUILD_BRIDGE
  1109. fUsedGroups.clear();
  1110. fUsedPorts.clear();
  1111. fUsedConnections.clear();
  1112. CARLA_SAFE_ASSERT(fPostPonedEvents.count() == 0);
  1113. #endif
  1114. }
  1115. // -------------------------------------------------------------------
  1116. // Maximum values
  1117. uint getMaxClientNameSize() const noexcept override
  1118. {
  1119. #ifndef BUILD_BRIDGE
  1120. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT ||
  1121. pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1122. #endif
  1123. {
  1124. try {
  1125. return static_cast<uint>(jackbridge_client_name_size()-1);
  1126. } CARLA_SAFE_EXCEPTION_RETURN("jack_client_name_size", 32);
  1127. }
  1128. return CarlaEngine::getMaxClientNameSize();
  1129. }
  1130. uint getMaxPortNameSize() const noexcept override
  1131. {
  1132. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1133. {
  1134. try {
  1135. return static_cast<uint>(jackbridge_port_name_size()-1);
  1136. } CARLA_SAFE_EXCEPTION_RETURN("jack_port_name_size", 255);
  1137. }
  1138. return CarlaEngine::getMaxPortNameSize();
  1139. }
  1140. // -------------------------------------------------------------------
  1141. // Virtual, per-engine type calls
  1142. bool init(const char* const clientName) override
  1143. {
  1144. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr || (clientName != nullptr && clientName[0] != '\0'), false);
  1145. carla_debug("CarlaEngineJack::init(\"%s\")", clientName);
  1146. if (!jackbridge_is_ok())
  1147. {
  1148. setLastError("JACK is not available or installed");
  1149. return false;
  1150. }
  1151. fFreewheel = false;
  1152. fExternalPatchbayHost = true;
  1153. fExternalPatchbayOsc = true;
  1154. CarlaString truncatedClientName;
  1155. if (fClient == nullptr && clientName != nullptr)
  1156. {
  1157. truncatedClientName = clientName;
  1158. truncatedClientName.truncate(getMaxClientNameSize());
  1159. }
  1160. #ifdef BUILD_BRIDGE
  1161. fIsRunning = true;
  1162. if (! pData->init(truncatedClientName))
  1163. {
  1164. close();
  1165. setLastError("Failed to init internal data");
  1166. return false;
  1167. }
  1168. if (pData->bufferSize == 0 || carla_isEqual(pData->sampleRate, 0.0))
  1169. {
  1170. // open temp client to get initial buffer-size and sample-rate values
  1171. if (jack_client_t* const tmpClient = jackbridge_client_open(truncatedClientName, JackNoStartServer, nullptr))
  1172. {
  1173. pData->bufferSize = jackbridge_get_buffer_size(tmpClient);
  1174. pData->sampleRate = jackbridge_get_sample_rate(tmpClient);
  1175. jackbridge_client_close(tmpClient);
  1176. }
  1177. else
  1178. {
  1179. close();
  1180. setLastError("Failed to init temporary jack client");
  1181. return false;
  1182. }
  1183. }
  1184. return true;
  1185. #else // BUILD_BRIDGE
  1186. if (fClient == nullptr && clientName != nullptr)
  1187. fClient = jackbridge_client_open(truncatedClientName, JackNoStartServer, nullptr);
  1188. if (fClient == nullptr)
  1189. {
  1190. setLastError("Failed to create new JACK client");
  1191. return false;
  1192. }
  1193. const char* const jackClientName = jackbridge_get_client_name(fClient);
  1194. if (! pData->init(jackClientName))
  1195. {
  1196. jackbridge_client_close(fClient);
  1197. fClient = nullptr;
  1198. setLastError("Failed to init internal data");
  1199. return false;
  1200. }
  1201. // if main jack client does not match our requested one, setup client name prefix as needed
  1202. if (truncatedClientName != jackClientName)
  1203. {
  1204. if (const char* const suffix = std::strrchr(jackClientName, '-'))
  1205. {
  1206. if (fClientNamePrefix.isNotEmpty())
  1207. {
  1208. fClientNamePrefix.truncate(fClientNamePrefix.rfind('.') + 1);
  1209. }
  1210. else
  1211. {
  1212. fClientNamePrefix = truncatedClientName;
  1213. fClientNamePrefix += ".";
  1214. }
  1215. fClientNamePrefix += suffix + 1;
  1216. fClientNamePrefix += "/";
  1217. }
  1218. }
  1219. fClientName = jackClientName;
  1220. const EngineOptions& opts(pData->options);
  1221. pData->bufferSize = jackbridge_get_buffer_size(fClient);
  1222. pData->sampleRate = jackbridge_get_sample_rate(fClient);
  1223. pData->initTime(opts.transportExtra);
  1224. jackbridge_set_thread_init_callback(fClient, carla_jack_thread_init_callback, nullptr);
  1225. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback, this);
  1226. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback, this);
  1227. jackbridge_set_freewheel_callback(fClient, carla_jack_freewheel_callback, this);
  1228. // jackbridge_set_latency_callback(fClient, carla_jack_latency_callback, this);
  1229. jackbridge_set_process_callback(fClient, carla_jack_process_callback, this);
  1230. jackbridge_on_shutdown(fClient, carla_jack_shutdown_callback, this);
  1231. fTimebaseRolling = false;
  1232. if (opts.transportMode == ENGINE_TRANSPORT_MODE_JACK)
  1233. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  1234. else
  1235. fTimebaseMaster = false;
  1236. initJackPatchbay(true, false, jackClientName, pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY);
  1237. jackbridge_set_client_registration_callback(fClient, carla_jack_client_registration_callback, this);
  1238. jackbridge_set_port_registration_callback(fClient, carla_jack_port_registration_callback, this);
  1239. jackbridge_set_port_connect_callback(fClient, carla_jack_port_connect_callback, this);
  1240. jackbridge_set_port_rename_callback(fClient, carla_jack_port_rename_callback, this);
  1241. jackbridge_set_property_change_callback(fClient, carla_jack_property_change_callback, this);
  1242. jackbridge_set_xrun_callback(fClient, carla_jack_xrun_callback, this);
  1243. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1244. {
  1245. fRackPorts[kRackPortAudioIn1] = jackbridge_port_register(fClient, "audio-in1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  1246. fRackPorts[kRackPortAudioIn2] = jackbridge_port_register(fClient, "audio-in2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  1247. fRackPorts[kRackPortAudioOut1] = jackbridge_port_register(fClient, "audio-out1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  1248. fRackPorts[kRackPortAudioOut2] = jackbridge_port_register(fClient, "audio-out2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  1249. fRackPorts[kRackPortEventIn] = jackbridge_port_register(fClient, "events-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
  1250. fRackPorts[kRackPortEventOut] = jackbridge_port_register(fClient, "events-out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
  1251. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1252. {
  1253. // FIXME?
  1254. pData->graph.create(0, 0, 0, 0);
  1255. }
  1256. else
  1257. {
  1258. pData->graph.create(2, 2, 0, 0);
  1259. // pData->graph.setUsingExternalHost(true);
  1260. // pData->graph.setUsingExternalOSC(true);
  1261. patchbayRefresh(true, false, false);
  1262. }
  1263. }
  1264. # ifdef HAVE_LIBLO
  1265. {
  1266. const CarlaString& tcp(pData->osc.getServerPathTCP());
  1267. const CarlaString& udp(pData->osc.getServerPathUDP());
  1268. if (tcp.isNotEmpty() || udp.isNotEmpty())
  1269. {
  1270. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  1271. if (char* const uuidstr = jackbridge_client_get_uuid(fClient))
  1272. {
  1273. jack_uuid_t uuid;
  1274. if (jackbridge_uuid_parse(uuidstr, &uuid))
  1275. {
  1276. if (tcp.isNotEmpty())
  1277. jackbridge_set_property(fClient, uuid,
  1278. "https://kx.studio/ns/carla/osc-tcp", tcp, URI_TYPE_STRING);
  1279. if (udp.isNotEmpty())
  1280. jackbridge_set_property(fClient, uuid,
  1281. "https://kx.studio/ns/carla/osc-udp", udp, URI_TYPE_STRING);
  1282. }
  1283. jackbridge_free(uuidstr);
  1284. }
  1285. }
  1286. }
  1287. # endif
  1288. if (jackbridge_activate(fClient))
  1289. {
  1290. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1291. opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1292. {
  1293. if (pData->options.audioDevice != nullptr &&
  1294. std::strcmp(pData->options.audioDevice, "Auto-Connect ON") == 0 &&
  1295. std::getenv("LADISH_APP_NAME") == nullptr &&
  1296. std::getenv("NSM_URL") == nullptr)
  1297. {
  1298. char strBuf[STR_MAX];
  1299. if (jackbridge_port_by_name(fClient, "system:capture_1") != nullptr)
  1300. {
  1301. std::snprintf(strBuf, STR_MAX, "%s:audio-in1", jackClientName);
  1302. strBuf[STR_MAX-1] = '\0';
  1303. jackbridge_connect(fClient, "system:capture_1", strBuf);
  1304. std::snprintf(strBuf, STR_MAX, "%s:audio-in2", jackClientName);
  1305. strBuf[STR_MAX-1] = '\0';
  1306. if (jackbridge_port_by_name(fClient, "system:capture_2") != nullptr)
  1307. jackbridge_connect(fClient, "system:capture_2", strBuf);
  1308. else
  1309. jackbridge_connect(fClient, "system:capture_1", strBuf);
  1310. }
  1311. if (jackbridge_port_by_name(fClient, "system:playback_1") != nullptr)
  1312. {
  1313. std::snprintf(strBuf, STR_MAX, "%s:audio-out1", jackClientName);
  1314. strBuf[STR_MAX-1] = '\0';
  1315. jackbridge_connect(fClient, strBuf, "system:playback_1");
  1316. std::snprintf(strBuf, STR_MAX, "%s:audio-out2", jackClientName);
  1317. strBuf[STR_MAX-1] = '\0';
  1318. if (jackbridge_port_by_name(fClient, "system:playback_2") != nullptr)
  1319. jackbridge_connect(fClient, strBuf, "system:playback_2");
  1320. else
  1321. jackbridge_connect(fClient, strBuf, "system:playback_1");
  1322. }
  1323. }
  1324. }
  1325. if (fIsInternalClient)
  1326. startThread();
  1327. callback(true, true,
  1328. ENGINE_CALLBACK_ENGINE_STARTED, 0,
  1329. opts.processMode,
  1330. opts.transportMode,
  1331. static_cast<int>(pData->bufferSize),
  1332. static_cast<float>(pData->sampleRate),
  1333. getCurrentDriverName());
  1334. return true;
  1335. }
  1336. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1337. opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1338. {
  1339. pData->graph.destroy();
  1340. }
  1341. pData->close();
  1342. jackbridge_client_close(fClient);
  1343. fClient = nullptr;
  1344. setLastError("Failed to activate the JACK client");
  1345. return false;
  1346. #endif // BUILD_BRIDGE
  1347. }
  1348. #ifndef BUILD_BRIDGE
  1349. bool initInternal(jack_client_t* const client)
  1350. {
  1351. fClient = client;
  1352. fIsInternalClient = true;
  1353. return init(nullptr);
  1354. }
  1355. #endif
  1356. bool close() override
  1357. {
  1358. carla_debug("CarlaEngineJack::close()");
  1359. #ifdef BUILD_BRIDGE
  1360. fClient = nullptr;
  1361. fIsRunning = false;
  1362. CarlaEngine::close();
  1363. return true;
  1364. #else
  1365. if (fIsInternalClient)
  1366. stopThread(-1);
  1367. // deactivate client ASAP
  1368. if (fClient != nullptr)
  1369. jackbridge_deactivate(fClient);
  1370. // clear engine data
  1371. CarlaEngine::close();
  1372. // now close client
  1373. if (fClient != nullptr)
  1374. {
  1375. jackbridge_client_close(fClient);
  1376. fClient = nullptr;
  1377. }
  1378. fClientName.clear();
  1379. fUsedGroups.clear();
  1380. fUsedPorts.clear();
  1381. fUsedConnections.clear();
  1382. fPostPonedEvents.clear();
  1383. // clear rack/patchbay stuff
  1384. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1385. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1386. {
  1387. carla_zeroPointers(fRackPorts, kRackPortCount);
  1388. pData->graph.destroy();
  1389. }
  1390. return true;
  1391. #endif
  1392. }
  1393. bool hasIdleOnMainThread() const noexcept override
  1394. {
  1395. #ifndef BUILD_BRIDGE
  1396. return !fIsInternalClient;
  1397. #else
  1398. return true;
  1399. #endif
  1400. }
  1401. bool isRunning() const noexcept override
  1402. {
  1403. #ifdef BUILD_BRIDGE
  1404. return (fClient != nullptr || fIsRunning);
  1405. #else
  1406. return (fClient != nullptr);
  1407. #endif
  1408. }
  1409. bool isOffline() const noexcept override
  1410. {
  1411. return fFreewheel;
  1412. }
  1413. EngineType getType() const noexcept override
  1414. {
  1415. return kEngineTypeJack;
  1416. }
  1417. const char* getCurrentDriverName() const noexcept override
  1418. {
  1419. return "JACK";
  1420. }
  1421. #ifndef BUILD_BRIDGE
  1422. float getDSPLoad() const noexcept override
  1423. {
  1424. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, 0.0f);
  1425. return jackbridge_cpu_load(fClient);
  1426. }
  1427. void callback(const bool sendHost, const bool sendOsc,
  1428. const EngineCallbackOpcode action, const uint pluginId,
  1429. const int value1, const int value2, const int value3,
  1430. const float valuef, const char* const valueStr) noexcept override
  1431. {
  1432. if (action == ENGINE_CALLBACK_PROJECT_LOAD_FINISHED)
  1433. {
  1434. if (fTimebaseMaster)
  1435. {
  1436. // project finished loading, need to set bpm here, so we force an update of timebase master
  1437. transportRelocate(pData->timeInfo.frame);
  1438. }
  1439. }
  1440. CarlaEngine::callback(sendHost, sendOsc, action, pluginId, value1, value2, value3, valuef, valueStr);
  1441. }
  1442. void idle() noexcept override
  1443. {
  1444. LinkedList<PostPonedJackEvent> events;
  1445. const PostPonedJackEvent nullEvent = {};
  1446. {
  1447. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  1448. if (fPostPonedEvents.count() > 0)
  1449. fPostPonedEvents.moveTo(events);
  1450. }
  1451. for (LinkedList<PostPonedJackEvent>::Itenerator it = events.begin2(); it.valid(); it.next())
  1452. {
  1453. const PostPonedJackEvent& ev(it.getValue(nullEvent));
  1454. CARLA_SAFE_ASSERT_CONTINUE(ev.type != PostPonedJackEvent::kTypeNull);
  1455. switch (ev.type)
  1456. {
  1457. case PostPonedJackEvent::kTypeNull:
  1458. break;
  1459. case PostPonedJackEvent::kTypeClientUnregister:
  1460. handleJackClientUnregistrationCallback(ev.clientUnregister.name);
  1461. break;
  1462. case PostPonedJackEvent::kTypePortRegister:
  1463. handleJackPortRegistrationCallback(ev.portRegister.fullName,
  1464. ev.portRegister.shortName,
  1465. ev.portRegister.hints);
  1466. break;
  1467. case PostPonedJackEvent::kTypePortUnregister:
  1468. handleJackPortUnregistrationCallback(ev.portUnregister.fullName);
  1469. break;
  1470. case PostPonedJackEvent::kTypePortConnect:
  1471. handleJackPortConnectCallback(ev.portConnect.portNameA,
  1472. ev.portConnect.portNameB);
  1473. break;
  1474. case PostPonedJackEvent::kTypePortDisconnect:
  1475. handleJackPortDisconnectCallback(ev.portDisconnect.portNameA,
  1476. ev.portDisconnect.portNameB);
  1477. break;
  1478. case PostPonedJackEvent::kTypePortRename:
  1479. handleJackPortRenameCallback(ev.portRename.oldFullName,
  1480. ev.portRename.newFullName,
  1481. ev.portRename.newShortName);
  1482. break;
  1483. case PostPonedJackEvent::kTypeClientPositionChange:
  1484. handleJackClientPositionChangeCallback(ev.clientPositionChange.uuid);
  1485. break;
  1486. }
  1487. }
  1488. events.clear();
  1489. CarlaEngine::idle();
  1490. }
  1491. #endif
  1492. bool setBufferSizeAndSampleRate(const uint bufferSize, const double sampleRate) override
  1493. {
  1494. CARLA_SAFE_ASSERT_RETURN(carla_isEqual(pData->sampleRate, sampleRate), false);
  1495. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1496. try {
  1497. return jackbridge_set_buffer_size(fClient, bufferSize);
  1498. } CARLA_SAFE_EXCEPTION_RETURN("setBufferSizeAndSampleRate", false);
  1499. }
  1500. EngineTimeInfo getTimeInfo() const noexcept override
  1501. {
  1502. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1503. return CarlaEngine::getTimeInfo();
  1504. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1505. return CarlaEngine::getTimeInfo();
  1506. jack_position_t jpos;
  1507. // invalidate
  1508. jpos.unique_1 = 1;
  1509. jpos.unique_2 = 2;
  1510. EngineTimeInfo timeInfo;
  1511. const bool playing = jackbridge_transport_query(fClient, &jpos) == JackTransportRolling;
  1512. if (jpos.unique_1 != jpos.unique_2)
  1513. {
  1514. timeInfo.playing = false;
  1515. timeInfo.frame = 0;
  1516. timeInfo.usecs = 0;
  1517. timeInfo.bbt.valid = false;
  1518. return timeInfo;
  1519. }
  1520. timeInfo.playing = playing;
  1521. timeInfo.frame = jpos.frame;
  1522. timeInfo.usecs = jpos.usecs;
  1523. if (jpos.valid & JackPositionBBT)
  1524. {
  1525. timeInfo.bbt.valid = true;
  1526. timeInfo.bbt.bar = jpos.bar;
  1527. timeInfo.bbt.beat = jpos.beat;
  1528. #ifdef JACK_TICK_DOUBLE
  1529. if (jpos.valid & JackTickDouble)
  1530. timeInfo.bbt.tick = jpos.tick_double;
  1531. else
  1532. #endif
  1533. timeInfo.bbt.tick = jpos.tick;
  1534. timeInfo.bbt.barStartTick = jpos.bar_start_tick;
  1535. timeInfo.bbt.beatsPerBar = jpos.beats_per_bar;
  1536. timeInfo.bbt.beatType = jpos.beat_type;
  1537. timeInfo.bbt.ticksPerBeat = jpos.ticks_per_beat;
  1538. timeInfo.bbt.beatsPerMinute = jpos.beats_per_minute;
  1539. }
  1540. else
  1541. {
  1542. timeInfo.bbt.valid = false;
  1543. }
  1544. return timeInfo;
  1545. }
  1546. #ifndef BUILD_BRIDGE
  1547. void setOption(const EngineOption option, const int value, const char* const valueStr) noexcept override
  1548. {
  1549. if (option == ENGINE_OPTION_TRANSPORT_MODE && fClient != nullptr)
  1550. {
  1551. CARLA_SAFE_ASSERT_INT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED &&
  1552. value <= ENGINE_TRANSPORT_MODE_JACK, value,);
  1553. if (value == ENGINE_TRANSPORT_MODE_JACK)
  1554. {
  1555. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  1556. }
  1557. else
  1558. {
  1559. // jack transport cannot be disabled in multi-client
  1560. callback(true, true,
  1561. ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED, 0,
  1562. ENGINE_TRANSPORT_MODE_JACK,
  1563. 0, 0, 0.0f,
  1564. pData->options.transportExtra);
  1565. CARLA_SAFE_ASSERT_RETURN(pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS,);
  1566. jackbridge_release_timebase(fClient);
  1567. fTimebaseMaster = false;
  1568. }
  1569. }
  1570. else if (option == ENGINE_OPTION_CLIENT_NAME_PREFIX)
  1571. {
  1572. fClientNamePrefix = valueStr;
  1573. if (fClientNamePrefix.isNotEmpty())
  1574. {
  1575. if (! fClientNamePrefix.contains('.'))
  1576. fClientNamePrefix += ".0";
  1577. if (! fClientNamePrefix.endsWith('/'))
  1578. fClientNamePrefix += "/";
  1579. }
  1580. }
  1581. CarlaEngine::setOption(option, value, valueStr);
  1582. }
  1583. #endif
  1584. CarlaEngineClient* addClient(CarlaPluginPtr plugin) override
  1585. {
  1586. jack_client_t* client = nullptr;
  1587. #ifndef BUILD_BRIDGE
  1588. CARLA_CUSTOM_SAFE_ASSERT_RETURN("Not connected to JACK", fClient != nullptr, nullptr);
  1589. CarlaPluginPtr* pluginReserve = nullptr;
  1590. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1591. {
  1592. client = fClient;
  1593. }
  1594. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1595. #endif
  1596. {
  1597. #ifndef BUILD_BRIDGE
  1598. if (fClientNamePrefix.isNotEmpty())
  1599. {
  1600. client = jackbridge_client_open(fClientNamePrefix + plugin->getName(), JackNoStartServer, nullptr);
  1601. }
  1602. else
  1603. #endif
  1604. {
  1605. client = jackbridge_client_open(plugin->getName(), JackNoStartServer, nullptr);
  1606. }
  1607. CARLA_CUSTOM_SAFE_ASSERT_RETURN("Failure to open client", client != nullptr, nullptr);
  1608. jackbridge_set_thread_init_callback(client, carla_jack_thread_init_callback, nullptr);
  1609. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  1610. if (char* const uuidstr = jackbridge_client_get_uuid(client))
  1611. {
  1612. jack_uuid_t uuid;
  1613. if (jackbridge_uuid_parse(uuidstr, &uuid))
  1614. {
  1615. char strBufId[24];
  1616. std::snprintf(strBufId, 23, "%u", plugin->getId());
  1617. strBufId[23] = '\0';
  1618. #ifndef BUILD_BRIDGE
  1619. jackbridge_set_property(client, uuid,
  1620. URI_MAIN_CLIENT_NAME,
  1621. fClientName,
  1622. URI_TYPE_STRING);
  1623. jackbridge_set_property(client, uuid,
  1624. URI_PLUGIN_ID,
  1625. strBufId,
  1626. URI_TYPE_INTEGER);
  1627. #endif
  1628. if (const char* const pluginIcon = plugin->getIconName())
  1629. jackbridge_set_property(client, uuid,
  1630. URI_PLUGIN_ICON,
  1631. pluginIcon,
  1632. URI_TYPE_STRING);
  1633. }
  1634. jackbridge_free(uuidstr);
  1635. }
  1636. #ifndef BUILD_BRIDGE
  1637. pluginReserve = new CarlaPluginPtr(plugin);
  1638. /*
  1639. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback_plugin, pluginReserve);
  1640. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback_plugin, pluginReserve);
  1641. */
  1642. // jackbridge_set_latency_callback(client, carla_jack_latency_callback_plugin, pluginReserve);
  1643. jackbridge_set_process_callback(client, carla_jack_process_callback_plugin, pluginReserve);
  1644. jackbridge_on_shutdown(client, carla_jack_shutdown_callback_plugin, pluginReserve);
  1645. #else
  1646. fClient = client;
  1647. pData->bufferSize = jackbridge_get_buffer_size(client);
  1648. pData->sampleRate = jackbridge_get_sample_rate(client);
  1649. pData->initTime(nullptr);
  1650. jackbridge_set_buffer_size_callback(client, carla_jack_bufsize_callback, this);
  1651. jackbridge_set_sample_rate_callback(client, carla_jack_srate_callback, this);
  1652. jackbridge_set_freewheel_callback(client, carla_jack_freewheel_callback, this);
  1653. // jackbridge_set_latency_callback(client, carla_jack_latency_callback, this);
  1654. jackbridge_set_process_callback(client, carla_jack_process_callback, this);
  1655. jackbridge_on_shutdown(client, carla_jack_shutdown_callback, this);
  1656. fClientName = jackbridge_get_client_name(client);
  1657. #endif
  1658. }
  1659. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1660. carla_debug("new CarlaEngineJackClient");
  1661. CarlaEngineJackClient* const jclient = new CarlaEngineJackClient(*this,
  1662. pData->graph,
  1663. fThreadSafeMetadataMutex,
  1664. plugin, fClientName, client);
  1665. # ifndef BUILD_BRIDGE
  1666. if (pluginReserve != nullptr)
  1667. jclient->reservePluginPtr(pluginReserve);
  1668. # endif
  1669. return jclient;
  1670. #else
  1671. return new CarlaEngineJackClient(*this, fThreadSafeMetadataMutex, fClientName, client);
  1672. #endif
  1673. }
  1674. #ifndef BUILD_BRIDGE
  1675. bool removePlugin(const uint id) override
  1676. {
  1677. if (! CarlaEngine::removePlugin(id))
  1678. return false;
  1679. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1680. return true;
  1681. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  1682. for (uint i=id; i < pData->curPluginCount; ++i)
  1683. {
  1684. const CarlaPluginPtr plugin = pData->plugins[i].plugin;
  1685. CARLA_SAFE_ASSERT_BREAK(plugin.get() != nullptr);
  1686. CarlaEngineJackClient* const client = dynamic_cast<CarlaEngineJackClient*>(plugin->getEngineClient());
  1687. CARLA_SAFE_ASSERT_BREAK(client != nullptr);
  1688. client->setNewPluginId(i);
  1689. }
  1690. return true;
  1691. }
  1692. bool switchPlugins(const uint idA, const uint idB) noexcept override
  1693. {
  1694. if (! CarlaEngine::switchPlugins(idA, idB))
  1695. return false;
  1696. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1697. return true;
  1698. CarlaPluginPtr newPluginA = pData->plugins[idA].plugin;
  1699. CARLA_SAFE_ASSERT_RETURN(newPluginA.get() != nullptr, true);
  1700. CarlaPluginPtr newPluginB = pData->plugins[idB].plugin;
  1701. CARLA_SAFE_ASSERT_RETURN(newPluginB.get() != nullptr, true);
  1702. CarlaEngineJackClient* const clientA = dynamic_cast<CarlaEngineJackClient*>(newPluginA->getEngineClient());
  1703. CARLA_SAFE_ASSERT_RETURN(clientA != nullptr, true);
  1704. CarlaEngineJackClient* const clientB = dynamic_cast<CarlaEngineJackClient*>(newPluginB->getEngineClient());
  1705. CARLA_SAFE_ASSERT_RETURN(clientB != nullptr, true);
  1706. {
  1707. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  1708. clientA->setNewPluginId(idA);
  1709. clientB->setNewPluginId(idB);
  1710. }
  1711. return true;
  1712. }
  1713. bool renamePlugin(const uint id, const char* const newName) override
  1714. {
  1715. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1716. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1717. {
  1718. return CarlaEngine::renamePlugin(id, newName);
  1719. }
  1720. CARLA_SAFE_ASSERT_RETURN(pData->plugins != nullptr, false);
  1721. CARLA_SAFE_ASSERT_RETURN(pData->curPluginCount != 0, false);
  1722. CARLA_SAFE_ASSERT_RETURN(id < pData->curPluginCount, false);
  1723. CARLA_SAFE_ASSERT_RETURN(newName != nullptr && newName[0] != '\0', false);
  1724. CarlaPluginPtr plugin = pData->plugins[id].plugin;
  1725. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to rename");
  1726. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  1727. // before we stop the engine thread we might need to get the plugin data
  1728. const bool needsReinit = (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS);
  1729. const CarlaStateSave* saveStatePtr = nullptr;
  1730. if (needsReinit)
  1731. {
  1732. const CarlaStateSave& saveState(plugin->getStateSave());
  1733. saveStatePtr = &saveState;
  1734. }
  1735. CarlaString uniqueName;
  1736. try {
  1737. const char* const tmpName = getUniquePluginName(newName);
  1738. uniqueName = tmpName;
  1739. delete[] tmpName;
  1740. } CARLA_SAFE_EXCEPTION("JACK renamePlugin getUniquePluginName");
  1741. if (uniqueName.isEmpty())
  1742. {
  1743. setLastError("Failed to request new unique plugin name");
  1744. return false;
  1745. }
  1746. const ScopedRunnerStopper srs(this);
  1747. // rename on client client mode, just rename the ports
  1748. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1749. {
  1750. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  1751. if (! client->renameInSingleClient(uniqueName))
  1752. {
  1753. setLastError("Failed to rename some JACK ports, does your JACK version support proper port renaming?");
  1754. return false;
  1755. }
  1756. }
  1757. // rename in multiple client mode
  1758. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1759. {
  1760. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  1761. // we should not be able to do this, jack really needs to allow client rename
  1762. if (jack_client_t* const jackClient = jackbridge_client_open(fClientNamePrefix + uniqueName,
  1763. JackNoStartServer, nullptr))
  1764. {
  1765. // get new client name
  1766. fClientName = jackbridge_get_client_name(jackClient);
  1767. if (fClientNamePrefix.isNotEmpty())
  1768. uniqueName = fClientName.buffer() + fClientNamePrefix.length();
  1769. else
  1770. uniqueName = fClientName;
  1771. // close client
  1772. client->closeForRename(jackClient, fClientName);
  1773. // disable plugin
  1774. plugin->setEnabled(false);
  1775. // set new client data
  1776. CarlaPluginPtr* const pluginReserve = new CarlaPluginPtr(plugin);
  1777. client->reservePluginPtr(pluginReserve);
  1778. // jackbridge_set_latency_callback(jackClient, carla_jack_latency_callback_plugin, pluginReserve);
  1779. jackbridge_set_process_callback(jackClient, carla_jack_process_callback_plugin, pluginReserve);
  1780. jackbridge_on_shutdown(jackClient, carla_jack_shutdown_callback_plugin, pluginReserve);
  1781. // NOTE: jack1 locks up here
  1782. if (jackbridge_get_version_string() != nullptr)
  1783. jackbridge_set_thread_init_callback(jackClient, carla_jack_thread_init_callback, nullptr);
  1784. /* The following code is because of a tricky situation.
  1785. We cannot lock or do jack operations during jack callbacks on jack1. jack2 events are asynchronous.
  1786. When we close the client jack will trigger unregister-port callbacks, which we handle on a separate thread ASAP.
  1787. But before that happens we already registered a new client with the same ports (the "renamed" one),
  1788. and at this point the port we receive during that callback is actually the new one from the new client..
  1789. JACK2 seems to be reusing ports to save space, which is understandable.
  1790. Anyway, this means we have to remove all our port-related data before the new client ports are created.
  1791. (we also stop the separate jack-events thread to avoid any race conditions while modying our port data) */
  1792. if (fIsInternalClient)
  1793. stopThread(-1);
  1794. LinkedList<PortNameToId> ports;
  1795. LinkedList<ConnectionToId> conns;
  1796. {
  1797. const CarlaMutexLocker cml1(fUsedGroups.mutex);
  1798. if (const uint groupId = fUsedGroups.getGroupId(plugin->getName()))
  1799. {
  1800. const CarlaMutexLocker cml2(fUsedPorts.mutex);
  1801. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  1802. {
  1803. const PortNameToId& portNameToId(it.getValue(kPortNameToIdFallback));
  1804. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1805. if (portNameToId.group != groupId)
  1806. continue;
  1807. ports.append(portNameToId);
  1808. fUsedPorts.list.remove(it);
  1809. }
  1810. const CarlaMutexLocker cml3(fUsedConnections.mutex);
  1811. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1812. {
  1813. const ConnectionToId& connectionToId = it.getValue(kConnectionToIdFallback);
  1814. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1815. if (connectionToId.groupA != groupId && connectionToId.groupB != groupId)
  1816. continue;
  1817. conns.append(connectionToId);
  1818. fUsedConnections.list.remove(it);
  1819. }
  1820. }
  1821. }
  1822. for (LinkedList<ConnectionToId>::Itenerator it = conns.begin2(); it.valid(); it.next())
  1823. {
  1824. const ConnectionToId& connectionToId = it.getValue(kConnectionToIdFallback);
  1825. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1826. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1827. ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED,
  1828. connectionToId.id,
  1829. 0, 0, 0, 0.0f, nullptr);
  1830. }
  1831. for (LinkedList<PortNameToId>::Itenerator it = ports.begin2(); it.valid(); it.next())
  1832. {
  1833. const PortNameToId& portNameToId(it.getValue(kPortNameToIdFallback));
  1834. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1835. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  1836. ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED,
  1837. portNameToId.group,
  1838. static_cast<int>(portNameToId.port),
  1839. 0, 0, 0.0f, nullptr);
  1840. }
  1841. ports.clear();
  1842. conns.clear();
  1843. if (fIsInternalClient)
  1844. startThread();
  1845. }
  1846. else
  1847. {
  1848. setLastError("Failed to create new JACK client");
  1849. return false;
  1850. }
  1851. }
  1852. // Rename
  1853. plugin->setName(uniqueName);
  1854. if (needsReinit)
  1855. {
  1856. // reload plugin to recreate its ports
  1857. plugin->reload();
  1858. plugin->loadStateSave(*saveStatePtr);
  1859. plugin->setEnabled(true);
  1860. }
  1861. callback(true, true, ENGINE_CALLBACK_PLUGIN_RENAMED, id, 0, 0, 0, 0.0f, uniqueName);
  1862. return true;
  1863. }
  1864. // -------------------------------------------------------------------
  1865. // Patchbay
  1866. bool patchbayConnect(const bool external,
  1867. const uint groupA, const uint portA, const uint groupB, const uint portB) override
  1868. {
  1869. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1870. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1871. return CarlaEngine::patchbayConnect(false, groupA, portA, groupB, portB);
  1872. const CarlaMutexLocker cml(fUsedPorts.mutex);
  1873. const char* const fullPortNameA = fUsedPorts.getFullPortName(groupA, portA);
  1874. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1875. const char* const fullPortNameB = fUsedPorts.getFullPortName(groupB, portB);
  1876. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1877. if (! jackbridge_connect(fClient, fullPortNameA, fullPortNameB))
  1878. {
  1879. setLastError("JACK operation failed");
  1880. return false;
  1881. }
  1882. return true;
  1883. }
  1884. bool patchbayDisconnect(const bool external, const uint connectionId) override
  1885. {
  1886. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1887. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1888. return CarlaEngine::patchbayDisconnect(false, connectionId);
  1889. ConnectionToId connectionToId = { 0, 0, 0, 0, 0 };
  1890. {
  1891. const CarlaMutexLocker cml(fUsedConnections.mutex);
  1892. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1893. {
  1894. connectionToId = it.getValue(kConnectionToIdFallback);
  1895. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1896. if (connectionToId.id == connectionId)
  1897. break;
  1898. }
  1899. }
  1900. if (connectionToId.id == 0 || connectionToId.id != connectionId)
  1901. {
  1902. setLastError("Failed to find the requested connection");
  1903. return false;
  1904. }
  1905. const CarlaMutexLocker cml(fUsedPorts.mutex);
  1906. const char* const fullPortNameA = fUsedPorts.getFullPortName(connectionToId.groupA, connectionToId.portA);
  1907. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1908. const char* const fullPortNameB = fUsedPorts.getFullPortName(connectionToId.groupB, connectionToId.portB);
  1909. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1910. if (! jackbridge_disconnect(fClient, fullPortNameA, fullPortNameB))
  1911. {
  1912. setLastError("JACK operation failed");
  1913. return false;
  1914. }
  1915. return true;
  1916. }
  1917. bool patchbaySetGroupPos(const bool sendHost, const bool sendOSC, const bool external,
  1918. const uint groupId, const int x1, const int y1, const int x2, const int y2) override
  1919. {
  1920. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1921. CARLA_SAFE_ASSERT_RETURN(! pData->loadingProject, false);
  1922. carla_debug("CarlaEngineJack::patchbaySetGroupPos(%u, %i, %i, %i, %i)", groupId, x1, y1, x2, y2);
  1923. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1924. return CarlaEngine::patchbaySetGroupPos(sendHost, sendOSC, false, groupId, x1, y1, x2, y2);
  1925. const char* groupName;
  1926. {
  1927. const CarlaMutexLocker cml(fUsedGroups.mutex);
  1928. groupName = fUsedGroups.getGroupName(groupId);
  1929. CARLA_SAFE_ASSERT_RETURN(groupName != nullptr && groupName[0] != '\0', false);
  1930. }
  1931. bool ok;
  1932. {
  1933. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  1934. jack_uuid_t uuid;
  1935. {
  1936. char* const uuidstr = jackbridge_get_uuid_for_client_name(fClient, groupName);
  1937. CARLA_SAFE_ASSERT_RETURN(uuidstr != nullptr && uuidstr[0] != '\0', false);
  1938. const bool parsed = jackbridge_uuid_parse(uuidstr, &uuid);
  1939. jackbridge_free(uuidstr);
  1940. /* if parsing fails, meta-data is not available..
  1941. this could be because JACK version is old, or perhaps this is an internal client */
  1942. if (! parsed)
  1943. return false;
  1944. }
  1945. fLastPatchbaySetGroupPos.set(x1, y1, x2, y2);
  1946. char valueStr[STR_MAX];
  1947. std::snprintf(valueStr, STR_MAX-1, "%i:%i:%i:%i", x1, y1, x2, y2);
  1948. valueStr[STR_MAX-1] = '\0';
  1949. ok = jackbridge_set_property(fClient, uuid, URI_POSITION, valueStr, URI_TYPE_STRING);
  1950. }
  1951. callback(sendHost, sendOSC,
  1952. ENGINE_CALLBACK_PATCHBAY_CLIENT_POSITION_CHANGED,
  1953. groupId, x1, y1, x2, static_cast<float>(y2),
  1954. nullptr);
  1955. return ok;
  1956. }
  1957. bool patchbayRefresh(const bool sendHost, const bool sendOSC, const bool external) override
  1958. {
  1959. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1960. carla_debug("patchbayRefresh(%s, %s, %s)", bool2str(sendHost), bool2str(sendOSC), bool2str(external));
  1961. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1962. {
  1963. if (sendHost)
  1964. {
  1965. fExternalPatchbayHost = external;
  1966. pData->graph.setUsingExternalHost(external);
  1967. }
  1968. if (sendOSC)
  1969. {
  1970. fExternalPatchbayOsc = external;
  1971. pData->graph.setUsingExternalOSC(external);
  1972. }
  1973. if (! external)
  1974. CarlaEngine::patchbayRefresh(sendHost, sendOSC, false);
  1975. }
  1976. initJackPatchbay(sendHost, sendOSC, jackbridge_get_client_name(fClient),
  1977. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && !external);
  1978. return true;
  1979. }
  1980. // -------------------------------------------------------------------
  1981. // Transport
  1982. void transportPlay() noexcept override
  1983. {
  1984. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1985. return CarlaEngine::transportPlay();
  1986. if (fClient != nullptr)
  1987. {
  1988. if (! pData->timeInfo.bbt.valid)
  1989. {
  1990. // old timebase master no longer active, make ourselves master again
  1991. pData->time.setNeedsReset();
  1992. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  1993. }
  1994. try {
  1995. jackbridge_transport_start(fClient);
  1996. } catch(...) {}
  1997. }
  1998. }
  1999. void transportPause() noexcept override
  2000. {
  2001. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  2002. return CarlaEngine::transportPause();
  2003. if (fClient != nullptr)
  2004. {
  2005. try {
  2006. jackbridge_transport_stop(fClient);
  2007. } catch(...) {}
  2008. }
  2009. }
  2010. void transportBPM(const double bpm) noexcept override
  2011. {
  2012. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK || fTimebaseMaster)
  2013. return CarlaEngine::transportBPM(bpm);
  2014. if (fClient == nullptr)
  2015. return;
  2016. jack_position_t jpos;
  2017. // invalidate
  2018. jpos.unique_1 = 1;
  2019. jpos.unique_2 = 2;
  2020. jackbridge_transport_query(fClient, &jpos);
  2021. if (jpos.unique_1 == jpos.unique_2 && (jpos.valid & JackPositionBBT) != 0)
  2022. {
  2023. carla_stdout("NOTE: Changing BPM without being JACK timebase master");
  2024. jpos.beats_per_minute = bpm;
  2025. try {
  2026. jackbridge_transport_reposition(fClient, &jpos);
  2027. } catch(...) {}
  2028. }
  2029. }
  2030. void transportRelocate(const uint64_t frame) noexcept override
  2031. {
  2032. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  2033. return CarlaEngine::transportRelocate(frame);
  2034. if (fClient != nullptr)
  2035. {
  2036. try {
  2037. jackbridge_transport_locate(fClient, static_cast<jack_nframes_t>(frame));
  2038. } catch(...) {}
  2039. }
  2040. }
  2041. // -------------------------------------------------------------------
  2042. // Patchbay stuff
  2043. const char* const* getPatchbayConnections(const bool external) const override
  2044. {
  2045. CARLA_CUSTOM_SAFE_ASSERT_RETURN("Not connected to JACK, will not save patchbay connections",
  2046. fClient != nullptr, nullptr);
  2047. carla_debug("CarlaEngineJack::getPatchbayConnections(%s)", bool2str(external));
  2048. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  2049. return CarlaEngine::getPatchbayConnections(external);
  2050. CarlaStringList connList;
  2051. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  2052. {
  2053. for (int i=0; ports[i] != nullptr; ++i)
  2054. {
  2055. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, ports[i]));
  2056. const char* const fullPortName(ports[i]);
  2057. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  2058. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  2059. {
  2060. for (int j=0; connections[j] != nullptr; ++j)
  2061. {
  2062. connList.append(fullPortName);
  2063. connList.append(connections[j]);
  2064. }
  2065. jackbridge_free(connections);
  2066. }
  2067. }
  2068. jackbridge_free(ports);
  2069. }
  2070. if (connList.count() == 0)
  2071. return nullptr;
  2072. fRetConns = connList.toCharStringListPtr();
  2073. return fRetConns;
  2074. }
  2075. const PatchbayPosition* getPatchbayPositions(const bool external, uint& count) const override
  2076. {
  2077. CARLA_CUSTOM_SAFE_ASSERT_RETURN("Not connected to JACK, will not save patchbay positions",
  2078. fClient != nullptr, nullptr);
  2079. carla_debug("CarlaEngineJack::getPatchbayPositions(%s)", bool2str(external));
  2080. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  2081. return CarlaEngine::getPatchbayPositions(external, count);
  2082. const CarlaMutexLocker cml(fUsedGroups.mutex);
  2083. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  2084. if (const std::size_t maxCount = fUsedGroups.list.count())
  2085. {
  2086. PatchbayPosition* ret;
  2087. try {
  2088. ret = new CarlaEngine::PatchbayPosition[maxCount];
  2089. } CARLA_SAFE_EXCEPTION_RETURN("new CarlaEngine::PatchbayPosition", nullptr);
  2090. count = 0;
  2091. GroupNameToId groupNameToId;
  2092. for (LinkedList<GroupNameToId>::Itenerator it = fUsedGroups.list.begin2(); it.valid(); it.next())
  2093. {
  2094. groupNameToId = it.getValue(kGroupNameToIdFallback);
  2095. CARLA_SAFE_ASSERT_CONTINUE(groupNameToId.group != 0);
  2096. jack_uuid_t uuid;
  2097. {
  2098. char* const uuidstr = jackbridge_get_uuid_for_client_name(fClient, groupNameToId.name);
  2099. if (uuidstr == nullptr || uuidstr[0] == '\0')
  2100. continue;
  2101. const bool parsed = jackbridge_uuid_parse(uuidstr, &uuid);
  2102. jackbridge_free(uuidstr);
  2103. /* if parsing fails, meta-data is not available..
  2104. this could be because JACK version is old, or perhaps this is an internal client */
  2105. if (! parsed)
  2106. continue;
  2107. }
  2108. char* value = nullptr;
  2109. char* type = nullptr;
  2110. if (jackbridge_get_property(uuid, URI_POSITION, &value, &type)
  2111. && value != nullptr
  2112. && type != nullptr
  2113. && std::strcmp(type, URI_TYPE_STRING) == 0)
  2114. {
  2115. CarlaEngine::PatchbayPosition& ppos(ret[count++]);
  2116. ppos.name = carla_strdup_safe(groupNameToId.name);
  2117. ppos.dealloc = true;
  2118. ppos.pluginId = -1;
  2119. if (char* sep1 = std::strstr(value, ":"))
  2120. {
  2121. *sep1++ = '\0';
  2122. ppos.x1 = std::atoi(value);
  2123. if (char* sep2 = std::strstr(sep1, ":"))
  2124. {
  2125. *sep2++ = '\0';
  2126. ppos.y1 = std::atoi(sep1);
  2127. if (char* sep3 = std::strstr(sep2, ":"))
  2128. {
  2129. *sep3++ = '\0';
  2130. ppos.x2 = std::atoi(sep2);
  2131. ppos.y2 = std::atoi(sep3);
  2132. }
  2133. }
  2134. }
  2135. jackbridge_free(value);
  2136. jackbridge_free(type);
  2137. value = type = nullptr;
  2138. const bool clientBelongsToUs = (jackbridge_get_property(uuid, URI_MAIN_CLIENT_NAME, &value, &type)
  2139. && value != nullptr
  2140. && type != nullptr
  2141. && std::strcmp(type, URI_TYPE_STRING) == 0
  2142. && fClientName == value);
  2143. jackbridge_free(value);
  2144. jackbridge_free(type);
  2145. value = type = nullptr;
  2146. if (! clientBelongsToUs)
  2147. continue;
  2148. if (jackbridge_get_property(uuid, URI_PLUGIN_ID, &value, &type)
  2149. && value != nullptr
  2150. && type != nullptr
  2151. && std::strcmp(type, URI_TYPE_INTEGER) == 0)
  2152. {
  2153. ppos.pluginId = std::atoi(value);
  2154. }
  2155. jackbridge_free(value);
  2156. jackbridge_free(type);
  2157. }
  2158. }
  2159. return ret;
  2160. }
  2161. return nullptr;
  2162. }
  2163. void restorePatchbayConnection(const bool external,
  2164. const char* const connSource, const char* const connTarget) override
  2165. {
  2166. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr,);
  2167. CARLA_SAFE_ASSERT_RETURN(connSource != nullptr && connSource[0] != '\0',);
  2168. CARLA_SAFE_ASSERT_RETURN(connTarget != nullptr && connTarget[0] != '\0',);
  2169. carla_debug("CarlaEngineJack::restorePatchbayConnection(%s, \"%s\", \"%s\")",
  2170. bool2str(external), connSource, connTarget);
  2171. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  2172. return CarlaEngine::restorePatchbayConnection(external, connSource, connTarget);
  2173. if (const jack_port_t* const port = jackbridge_port_by_name(fClient, connSource))
  2174. {
  2175. if (jackbridge_port_by_name(fClient, connTarget) == nullptr)
  2176. return;
  2177. if (! jackbridge_port_connected_to(port, connTarget))
  2178. jackbridge_connect(fClient, connSource, connTarget);
  2179. }
  2180. }
  2181. bool restorePatchbayGroupPosition(const bool external, PatchbayPosition& ppos) override
  2182. {
  2183. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  2184. carla_debug("CarlaEngineJack::restorePatchbayGroupPosition(%s, {%i, %i, %i, %i, %i, \"%s\"})",
  2185. bool2str(external), ppos.pluginId, ppos.x1, ppos.y1, ppos.x2, ppos.y2, ppos.name);
  2186. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  2187. return CarlaEngine::restorePatchbayGroupPosition(external, ppos);
  2188. uint groupId = 0;
  2189. const char* const orig_name = ppos.name;
  2190. /* NOTE: When loading a project, it might take a bit to receive plugins' jack client registration callbacks.
  2191. * We try to wait a little for it, but not too much.
  2192. */
  2193. if (ppos.pluginId >= 0)
  2194. {
  2195. // strip client name prefix if already in place
  2196. if (const char* const rname2 = std::strstr(ppos.name, "."))
  2197. if (const char* const rname3 = std::strstr(rname2 + 1, "/"))
  2198. ppos.name = rname3 + 1;
  2199. if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  2200. {
  2201. if (fClientNamePrefix.isNotEmpty())
  2202. {
  2203. char* nname = (char*)std::malloc(fClientNamePrefix.length() + std::strlen(ppos.name) + 1);
  2204. std::strcpy(nname, fClientNamePrefix.buffer());
  2205. std::strcat(nname, ppos.name);
  2206. ppos.name = nname;
  2207. ppos.dealloc = true;
  2208. }
  2209. for (int i=20; --i >=0;)
  2210. {
  2211. {
  2212. const CarlaMutexLocker cml(fUsedGroups.mutex);
  2213. if (fUsedGroups.list.count() == 0)
  2214. break;
  2215. groupId = fUsedGroups.getGroupId(ppos.name);
  2216. }
  2217. if (groupId != 0)
  2218. break;
  2219. carla_msleep(100);
  2220. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2221. }
  2222. }
  2223. }
  2224. else
  2225. {
  2226. const CarlaMutexLocker cml(fUsedGroups.mutex);
  2227. if (fUsedGroups.list.count() != 0)
  2228. groupId = fUsedGroups.getGroupId(ppos.name);
  2229. }
  2230. if (groupId == 0)
  2231. {
  2232. if (ppos.pluginId < 0 || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  2233. carla_stdout("Previously saved client '%s' not found", ppos.name);
  2234. }
  2235. else
  2236. {
  2237. for (;;)
  2238. {
  2239. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  2240. jack_uuid_t uuid;
  2241. {
  2242. char* const uuidstr = jackbridge_get_uuid_for_client_name(fClient, ppos.name);
  2243. CARLA_SAFE_ASSERT_BREAK(uuidstr != nullptr && uuidstr[0] != '\0');
  2244. const bool parsed = jackbridge_uuid_parse(uuidstr, &uuid);
  2245. jackbridge_free(uuidstr);
  2246. CARLA_CUSTOM_SAFE_ASSERT_ONCE_BREAK("JACK meta-data support unavailable", parsed);
  2247. }
  2248. char valueStr[STR_MAX];
  2249. std::snprintf(valueStr, STR_MAX-1, "%i:%i:%i:%i", ppos.x1, ppos.y1, ppos.x2, ppos.y2);
  2250. valueStr[STR_MAX-1] = '\0';
  2251. jackbridge_set_property(fClient, uuid, URI_POSITION, valueStr, URI_TYPE_STRING);
  2252. break;
  2253. }
  2254. callback(true, true,
  2255. ENGINE_CALLBACK_PATCHBAY_CLIENT_POSITION_CHANGED,
  2256. groupId, ppos.x1, ppos.y1, ppos.x2, static_cast<float>(ppos.y2),
  2257. nullptr);
  2258. }
  2259. return ppos.name != orig_name;
  2260. }
  2261. #endif
  2262. // -------------------------------------------------------------------
  2263. protected:
  2264. void handleJackBufferSizeCallback(const uint32_t newBufferSize)
  2265. {
  2266. if (pData->bufferSize == newBufferSize)
  2267. return;
  2268. #ifndef BUILD_BRIDGE
  2269. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  2270. #endif
  2271. pData->bufferSize = newBufferSize;
  2272. bufferSizeChanged(newBufferSize);
  2273. }
  2274. void handleJackSampleRateCallback(const double newSampleRate)
  2275. {
  2276. if (carla_isEqual(pData->sampleRate, newSampleRate))
  2277. return;
  2278. #ifndef BUILD_BRIDGE
  2279. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  2280. #endif
  2281. pData->sampleRate = newSampleRate;
  2282. sampleRateChanged(newSampleRate);
  2283. }
  2284. void handleJackFreewheelCallback(const bool isFreewheel)
  2285. {
  2286. if (fFreewheel == isFreewheel)
  2287. return;
  2288. #ifndef BUILD_BRIDGE
  2289. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  2290. #endif
  2291. fFreewheel = isFreewheel;
  2292. offlineModeChanged(isFreewheel);
  2293. }
  2294. void handleJackProcessCallback(const uint32_t nframes)
  2295. {
  2296. const PendingRtEventsRunner prt(this, nframes);
  2297. CARLA_SAFE_ASSERT_INT2_RETURN(nframes == pData->bufferSize, nframes, pData->bufferSize,);
  2298. #ifdef BUILD_BRIDGE
  2299. CarlaPluginPtr plugin = pData->plugins[0].plugin;
  2300. if (plugin.get() != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  2301. {
  2302. plugin->initBuffers();
  2303. processPlugin(plugin, nframes);
  2304. plugin->unlock();
  2305. }
  2306. #else
  2307. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_JACK && !fTimebaseMaster)
  2308. {
  2309. jack_position_t jpos;
  2310. // invalidate
  2311. jpos.unique_1 = 1;
  2312. jpos.unique_2 = 2;
  2313. EngineTimeInfo timeInfo;
  2314. const bool playing = jackbridge_transport_query(fClient, &jpos) == JackTransportRolling;
  2315. if (jpos.unique_1 != jpos.unique_2)
  2316. {
  2317. timeInfo.playing = false;
  2318. timeInfo.frame = 0;
  2319. timeInfo.usecs = 0;
  2320. timeInfo.bbt.valid = false;
  2321. }
  2322. else
  2323. {
  2324. timeInfo.playing = playing;
  2325. timeInfo.frame = jpos.frame;
  2326. timeInfo.usecs = jpos.usecs;
  2327. if (jpos.valid & JackPositionBBT)
  2328. {
  2329. timeInfo.bbt.valid = true;
  2330. timeInfo.bbt.bar = jpos.bar;
  2331. timeInfo.bbt.beat = jpos.beat;
  2332. #ifdef JACK_TICK_DOUBLE
  2333. if (jpos.valid & JackTickDouble)
  2334. timeInfo.bbt.tick = jpos.tick_double;
  2335. else
  2336. #endif
  2337. timeInfo.bbt.tick = jpos.tick;
  2338. timeInfo.bbt.barStartTick = jpos.bar_start_tick;
  2339. timeInfo.bbt.beatsPerBar = jpos.beats_per_bar;
  2340. timeInfo.bbt.beatType = jpos.beat_type;
  2341. timeInfo.bbt.ticksPerBeat = jpos.ticks_per_beat;
  2342. timeInfo.bbt.beatsPerMinute = jpos.beats_per_minute;
  2343. }
  2344. else
  2345. {
  2346. timeInfo.bbt.valid = false;
  2347. }
  2348. }
  2349. pData->timeInfo = timeInfo;
  2350. }
  2351. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  2352. {
  2353. if (pData->aboutToClose)
  2354. {
  2355. if (float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes))
  2356. carla_zeroFloats(audioOut1, nframes);
  2357. if (float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes))
  2358. carla_zeroFloats(audioOut2, nframes);
  2359. }
  2360. else if (pData->curPluginCount == 0)
  2361. {
  2362. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  2363. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  2364. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  2365. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  2366. // assert buffers
  2367. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  2368. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  2369. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  2370. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  2371. // pass-through
  2372. carla_copyFloats(audioOut1, audioIn1, nframes);
  2373. carla_copyFloats(audioOut2, audioIn2, nframes);
  2374. // TODO pass-through MIDI as well
  2375. if (void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes))
  2376. jackbridge_midi_clear_buffer(eventOut);
  2377. return;
  2378. }
  2379. }
  2380. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  2381. {
  2382. for (uint i=0; i < pData->curPluginCount; ++i)
  2383. {
  2384. if (CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2385. {
  2386. if (plugin->isEnabled() && plugin->tryLock(fFreewheel))
  2387. {
  2388. plugin->initBuffers();
  2389. processPlugin(plugin, nframes);
  2390. plugin->unlock();
  2391. }
  2392. }
  2393. }
  2394. }
  2395. else if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  2396. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2397. {
  2398. CARLA_SAFE_ASSERT_RETURN(pData->events.in != nullptr,);
  2399. CARLA_SAFE_ASSERT_RETURN(pData->events.out != nullptr,);
  2400. // get buffers from jack
  2401. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  2402. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  2403. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  2404. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  2405. void* const eventIn = jackbridge_port_get_buffer(fRackPorts[kRackPortEventIn], nframes);
  2406. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes);
  2407. // assert buffers
  2408. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  2409. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  2410. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  2411. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  2412. // create audio buffers
  2413. const float* inBuf[2] = { audioIn1, audioIn2 };
  2414. /**/ float* outBuf[2] = { audioOut1, audioOut2 };
  2415. // initialize events
  2416. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  2417. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  2418. if (eventIn != nullptr)
  2419. {
  2420. ushort engineEventIndex = 0;
  2421. jack_midi_event_t jackEvent;
  2422. const uint32_t jackEventCount(jackbridge_midi_get_event_count(eventIn));
  2423. for (uint32_t jackEventIndex=0; jackEventIndex < jackEventCount; ++jackEventIndex)
  2424. {
  2425. if (! jackbridge_midi_event_get(&jackEvent, eventIn, jackEventIndex))
  2426. continue;
  2427. CARLA_SAFE_ASSERT_CONTINUE(jackEvent.size < 0xFF /* uint8_t max */);
  2428. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  2429. engineEvent.time = jackEvent.time;
  2430. engineEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer, 0);
  2431. if (engineEventIndex >= kMaxEngineEventInternalCount)
  2432. break;
  2433. }
  2434. }
  2435. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  2436. {
  2437. pData->graph.processRack(pData, inBuf, outBuf, nframes);
  2438. }
  2439. else
  2440. {
  2441. const CarlaMutexLocker cml(fPatchbayProcThreadProtectionMutex);
  2442. pData->graph.process(pData, inBuf, outBuf, nframes);
  2443. }
  2444. // output control
  2445. if (eventOut != nullptr)
  2446. {
  2447. jackbridge_midi_clear_buffer(eventOut);
  2448. uint8_t size = 0;
  2449. uint8_t mdata[3] = { 0, 0, 0 };
  2450. uint8_t mdataTmp[EngineMidiEvent::kDataSize];
  2451. const uint8_t* mdataPtr;
  2452. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  2453. {
  2454. const EngineEvent& engineEvent(pData->events.out[i]);
  2455. /**/ if (engineEvent.type == kEngineEventTypeNull)
  2456. {
  2457. break;
  2458. }
  2459. else if (engineEvent.type == kEngineEventTypeControl)
  2460. {
  2461. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  2462. size = ctrlEvent.convertToMidiData(engineEvent.channel, mdata);
  2463. mdataPtr = mdata;
  2464. }
  2465. else if (engineEvent.type == kEngineEventTypeMidi)
  2466. {
  2467. const EngineMidiEvent& midiEvent(engineEvent.midi);
  2468. size = midiEvent.size;
  2469. CARLA_SAFE_ASSERT_CONTINUE(size > 0);
  2470. if (size > EngineMidiEvent::kDataSize)
  2471. {
  2472. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.dataExt != nullptr);
  2473. mdataPtr = midiEvent.dataExt;
  2474. }
  2475. else
  2476. {
  2477. // set first byte
  2478. mdataTmp[0] = static_cast<uint8_t>(midiEvent.data[0] | (engineEvent.channel & MIDI_CHANNEL_BIT));
  2479. if (size > 1)
  2480. {
  2481. // copy rest
  2482. carla_copy<uint8_t>(mdataTmp+1, midiEvent.data+1, size-1U);
  2483. }
  2484. // done
  2485. mdataPtr = mdataTmp;
  2486. }
  2487. }
  2488. else
  2489. {
  2490. continue;
  2491. }
  2492. if (size > 0)
  2493. jackbridge_midi_event_write(eventOut, engineEvent.time, mdataPtr, size);
  2494. }
  2495. }
  2496. }
  2497. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_JACK)
  2498. {
  2499. if (fTimebaseMaster)
  2500. {
  2501. const bool playing = jackbridge_transport_query(fClient, nullptr) == JackTransportRolling;
  2502. if (fTimebaseRolling != playing)
  2503. {
  2504. fTimebaseRolling = playing;
  2505. pData->timeInfo.playing = playing;
  2506. }
  2507. // Check if we are no longer timebase master
  2508. if (playing && fTimebaseUsecs != 0 && fTimebaseUsecs == pData->timeInfo.usecs)
  2509. {
  2510. carla_debug("No longer timerbase master");
  2511. fTimebaseMaster = false;
  2512. }
  2513. }
  2514. fTimebaseUsecs = pData->timeInfo.usecs;
  2515. }
  2516. #endif // ! BUILD_BRIDGE
  2517. }
  2518. void handleJackLatencyCallback(const jack_latency_callback_mode_t /*mode*/)
  2519. {
  2520. // TODO
  2521. }
  2522. #ifndef BUILD_BRIDGE
  2523. void handleJackTimebaseCallback(jack_nframes_t nframes, jack_position_t* const pos, const int new_pos)
  2524. {
  2525. if (new_pos)
  2526. pData->time.setNeedsReset();
  2527. pData->timeInfo.playing = fTimebaseRolling;
  2528. pData->timeInfo.frame = pos->frame;
  2529. pData->timeInfo.usecs = pos->usecs;
  2530. pData->time.fillJackTimeInfo(pos, nframes);
  2531. }
  2532. void handleJackClientUnregistrationCallback(const char* const name)
  2533. {
  2534. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  2535. uint groupId;
  2536. {
  2537. const CarlaMutexLocker cml(fUsedGroups.mutex);
  2538. groupId = fUsedGroups.getGroupId(name);
  2539. // clients might have been registered without ports
  2540. if (groupId == 0) return;
  2541. GroupNameToId groupNameToId;
  2542. groupNameToId.setData(groupId, name);
  2543. fUsedGroups.list.removeOne(groupNameToId);
  2544. }
  2545. // ignore callback if on internal patchbay mode
  2546. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  2547. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  2548. #else
  2549. if (! fExternalPatchbayHost) return;
  2550. #endif
  2551. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2552. ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED,
  2553. groupId,
  2554. 0, 0, 0, 0.0f, nullptr);
  2555. }
  2556. void handleJackClientPositionChangeCallback(const jack_uuid_t uuid)
  2557. {
  2558. // ignore this if on internal patchbay mode
  2559. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  2560. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  2561. #else
  2562. if (! fExternalPatchbayHost) return;
  2563. #endif
  2564. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  2565. char uuidstr[JACK_UUID_STRING_SIZE] = {};
  2566. jackbridge_uuid_unparse(uuid, uuidstr);
  2567. if (char* const clientName = jackbridge_get_client_name_by_uuid(fClient, uuidstr))
  2568. {
  2569. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr && clientName[0] != '\0',);
  2570. uint groupId;
  2571. {
  2572. const CarlaMutexLocker cml(fUsedGroups.mutex);
  2573. groupId = fUsedGroups.getGroupId(clientName);
  2574. }
  2575. jackbridge_free(clientName);
  2576. CARLA_SAFE_ASSERT_RETURN(groupId != 0,);
  2577. char* value = nullptr;
  2578. char* type = nullptr;
  2579. if (jackbridge_get_property(uuid, URI_POSITION, &value, &type)
  2580. && value != nullptr
  2581. && type != nullptr
  2582. && std::strcmp(type, URI_TYPE_STRING) == 0)
  2583. {
  2584. if (char* sep1 = std::strstr(value, ":"))
  2585. {
  2586. LastPatchbaySetGroupPos pos;
  2587. *sep1++ = '\0';
  2588. pos.x1 = std::atoi(value);
  2589. if (char* sep2 = std::strstr(sep1, ":"))
  2590. {
  2591. *sep2++ = '\0';
  2592. pos.y1 = std::atoi(sep1);
  2593. if (char* sep3 = std::strstr(sep2, ":"))
  2594. {
  2595. *sep3++ = '\0';
  2596. pos.x2 = std::atoi(sep2);
  2597. pos.y2 = std::atoi(sep3);
  2598. }
  2599. if (fLastPatchbaySetGroupPos != pos)
  2600. {
  2601. fLastPatchbaySetGroupPos.clear();
  2602. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2603. ENGINE_CALLBACK_PATCHBAY_CLIENT_POSITION_CHANGED,
  2604. groupId, pos.x1, pos.y1, pos.x2, static_cast<float>(pos.y2),
  2605. nullptr);
  2606. }
  2607. }
  2608. }
  2609. jackbridge_free(value);
  2610. jackbridge_free(type);
  2611. }
  2612. }
  2613. }
  2614. void handleJackPortRegistrationCallback(const char* const portName,
  2615. const char* const shortPortName,
  2616. const CarlaJackPortHints& jackPortHints)
  2617. {
  2618. bool groupFound;
  2619. CarlaString groupName(portName);
  2620. groupName.truncate(groupName.rfind(shortPortName, &groupFound)-1);
  2621. CARLA_SAFE_ASSERT_RETURN(groupFound,);
  2622. groupFound = false;
  2623. GroupToIdData groupData;
  2624. PortToIdData portData;
  2625. {
  2626. const CarlaMutexLocker cml1(fUsedGroups.mutex);
  2627. groupData.id = fUsedGroups.getGroupId(groupName);
  2628. if (groupData.id == 0)
  2629. {
  2630. groupData.id = ++fUsedGroups.lastId;
  2631. GroupNameToId groupNameToId;
  2632. groupNameToId.setData(groupData.id, groupName);
  2633. int pluginId = -1;
  2634. PatchbayIcon icon = jackPortHints.isHardware ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  2635. findPluginIdAndIcon(groupName, pluginId, icon);
  2636. fUsedGroups.list.append(groupNameToId);
  2637. groupFound = true;
  2638. groupData.icon = icon;
  2639. groupData.pluginId = pluginId;
  2640. std::strncpy(groupData.strVal, groupName, STR_MAX-1);
  2641. groupData.strVal[STR_MAX-1] = '\0';
  2642. }
  2643. }
  2644. // ignore the rest if on internal patchbay mode
  2645. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  2646. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  2647. #else
  2648. if (! fExternalPatchbayHost) return;
  2649. #endif
  2650. {
  2651. uint canvasPortFlags = 0x0;
  2652. canvasPortFlags |= jackPortHints.isInput ? PATCHBAY_PORT_IS_INPUT : 0x0;
  2653. /**/ if (jackPortHints.isCV)
  2654. canvasPortFlags |= PATCHBAY_PORT_TYPE_CV;
  2655. else if (jackPortHints.isOSC)
  2656. canvasPortFlags |= PATCHBAY_PORT_TYPE_OSC;
  2657. else if (jackPortHints.isAudio)
  2658. canvasPortFlags |= PATCHBAY_PORT_TYPE_AUDIO;
  2659. else if (jackPortHints.isMIDI)
  2660. canvasPortFlags |= PATCHBAY_PORT_TYPE_MIDI;
  2661. const CarlaMutexLocker cml2(fUsedPorts.mutex);
  2662. portData.group = groupData.id;
  2663. portData.port = ++fUsedPorts.lastId;
  2664. portData.flags = canvasPortFlags;
  2665. std::strncpy(portData.strVal, shortPortName, STR_MAX-1);
  2666. portData.strVal[STR_MAX-1] = '\0';
  2667. PortNameToId portNameToId;
  2668. portNameToId.setData(portData.group, portData.port, shortPortName, portName);
  2669. fUsedPorts.list.append(portNameToId);
  2670. }
  2671. if (groupFound)
  2672. {
  2673. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2674. ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED,
  2675. groupData.id,
  2676. groupData.icon,
  2677. groupData.pluginId,
  2678. 0, 0.0f,
  2679. groupData.strVal);
  2680. }
  2681. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2682. ENGINE_CALLBACK_PATCHBAY_PORT_ADDED,
  2683. portData.group,
  2684. static_cast<int>(portData.port),
  2685. static_cast<int>(portData.flags),
  2686. 0, 0.0f,
  2687. portData.strVal);
  2688. }
  2689. void handleJackPortUnregistrationCallback(const char* const portName)
  2690. {
  2691. // ignore this if on internal patchbay mode
  2692. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  2693. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  2694. #else
  2695. if (! fExternalPatchbayHost) return;
  2696. #endif
  2697. uint groupId, portId;
  2698. {
  2699. const CarlaMutexLocker cml(fUsedPorts.mutex);
  2700. const PortNameToId& portNameToId(fUsedPorts.getPortNameToId(portName));
  2701. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  2702. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  2703. if (portNameToId.group <= 0 || portNameToId.port <= 0) return;
  2704. groupId = portNameToId.group;
  2705. portId = portNameToId.port;
  2706. fUsedPorts.list.removeOne(portNameToId);
  2707. }
  2708. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2709. ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED,
  2710. groupId,
  2711. static_cast<int>(portId),
  2712. 0, 0, 0.0f, nullptr);
  2713. }
  2714. void handleJackPortConnectCallback(const char* const portNameA, const char* const portNameB)
  2715. {
  2716. // ignore this if on internal patchbay mode
  2717. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  2718. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  2719. #else
  2720. if (! fExternalPatchbayHost) return;
  2721. #endif
  2722. char strBuf[STR_MAX];
  2723. uint connectionId;
  2724. {
  2725. const CarlaMutexLocker cml1(fUsedPorts.mutex);
  2726. const PortNameToId& portNameToIdA(fUsedPorts.getPortNameToId(portNameA));
  2727. const PortNameToId& portNameToIdB(fUsedPorts.getPortNameToId(portNameB));
  2728. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  2729. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  2730. if (portNameToIdA.group <= 0 || portNameToIdA.port <= 0) return;
  2731. if (portNameToIdB.group <= 0 || portNameToIdB.port <= 0) return;
  2732. const CarlaMutexLocker cml2(fUsedConnections.mutex);
  2733. std::snprintf(strBuf, STR_MAX-1, "%i:%i:%i:%i",
  2734. portNameToIdA.group, portNameToIdA.port,
  2735. portNameToIdB.group, portNameToIdB.port);
  2736. strBuf[STR_MAX-1] = '\0';
  2737. connectionId = ++fUsedConnections.lastId;
  2738. ConnectionToId connectionToId;
  2739. connectionToId.setData(connectionId,
  2740. portNameToIdA.group, portNameToIdA.port,
  2741. portNameToIdB.group, portNameToIdB.port);
  2742. fUsedConnections.list.append(connectionToId);
  2743. }
  2744. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2745. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  2746. connectionId,
  2747. 0, 0, 0, 0.0f,
  2748. strBuf);
  2749. }
  2750. void handleJackPortDisconnectCallback(const char* const portNameA, const char* const portNameB)
  2751. {
  2752. // ignore this if on internal patchbay mode
  2753. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  2754. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  2755. #else
  2756. if (! fExternalPatchbayHost) return;
  2757. #endif
  2758. uint connectionId = 0;
  2759. {
  2760. const CarlaMutexLocker cml1(fUsedPorts.mutex);
  2761. const PortNameToId& portNameToIdA(fUsedPorts.getPortNameToId(portNameA));
  2762. const PortNameToId& portNameToIdB(fUsedPorts.getPortNameToId(portNameB));
  2763. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  2764. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  2765. if (portNameToIdA.group <= 0 || portNameToIdA.port <= 0) return;
  2766. if (portNameToIdB.group <= 0 || portNameToIdB.port <= 0) return;
  2767. const CarlaMutexLocker cml2(fUsedConnections.mutex);
  2768. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  2769. {
  2770. const ConnectionToId& connectionToId = it.getValue(kConnectionToIdFallback);
  2771. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  2772. if (connectionToId.groupA == portNameToIdA.group && connectionToId.portA == portNameToIdA.port &&
  2773. connectionToId.groupB == portNameToIdB.group && connectionToId.portB == portNameToIdB.port)
  2774. {
  2775. connectionId = connectionToId.id;
  2776. fUsedConnections.list.remove(it);
  2777. break;
  2778. }
  2779. }
  2780. }
  2781. if (connectionId != 0) {
  2782. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2783. ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED,
  2784. connectionId,
  2785. 0, 0, 0, 0.0f, nullptr);
  2786. }
  2787. }
  2788. void handleJackPortRenameCallback(const char* const oldFullName,
  2789. const char* const newFullName,
  2790. const char* const newShortName)
  2791. {
  2792. // ignore this if on internal patchbay mode
  2793. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  2794. if (! (fExternalPatchbayHost || (fExternalPatchbayOsc && pData->osc.isControlRegisteredForTCP()))) return;
  2795. #else
  2796. if (! fExternalPatchbayHost) return;
  2797. #endif
  2798. CARLA_SAFE_ASSERT_RETURN(oldFullName != nullptr && oldFullName[0] != '\0',);
  2799. CARLA_SAFE_ASSERT_RETURN(newFullName != nullptr && newFullName[0] != '\0',);
  2800. bool found;
  2801. CarlaString groupName(newFullName);
  2802. groupName.truncate(groupName.rfind(newShortName, &found)-1);
  2803. CARLA_SAFE_ASSERT_RETURN(found,);
  2804. uint groupId, portId = 0;
  2805. char portName[STR_MAX];
  2806. found = false;
  2807. {
  2808. const CarlaMutexLocker cml1(fUsedGroups.mutex);
  2809. groupId = fUsedGroups.getGroupId(groupName);
  2810. CARLA_SAFE_ASSERT_RETURN(groupId != 0,);
  2811. const CarlaMutexLocker cml2(fUsedPorts.mutex);
  2812. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  2813. {
  2814. PortNameToId& portNameToId(it.getValue(kPortNameToIdFallbackNC));
  2815. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  2816. if (std::strncmp(portNameToId.fullName, oldFullName, STR_MAX) == 0)
  2817. {
  2818. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group == groupId);
  2819. found = true;
  2820. portId = portNameToId.port;
  2821. std::strncpy(portName, newShortName, STR_MAX-1);
  2822. portName[STR_MAX-1] = '\0';
  2823. portNameToId.rename(newShortName, newFullName);
  2824. break;
  2825. }
  2826. }
  2827. }
  2828. if (found)
  2829. {
  2830. callback(fExternalPatchbayHost, fExternalPatchbayOsc,
  2831. ENGINE_CALLBACK_PATCHBAY_PORT_CHANGED,
  2832. groupId,
  2833. static_cast<int>(portId),
  2834. 0, 0, 0.0f,
  2835. portName);
  2836. }
  2837. }
  2838. #endif
  2839. void handleJackShutdownCallback()
  2840. {
  2841. #ifndef BUILD_BRIDGE
  2842. if (fIsInternalClient)
  2843. stopThread(-1);
  2844. #endif
  2845. {
  2846. const PendingRtEventsRunner prt(this, pData->bufferSize);
  2847. for (uint i=0; i < pData->curPluginCount; ++i)
  2848. {
  2849. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2850. {
  2851. plugin->tryLock(true);
  2852. if (CarlaEngineJackClient* const client = (CarlaEngineJackClient*)plugin->getEngineClient())
  2853. client->invalidate();
  2854. plugin->unlock();
  2855. }
  2856. }
  2857. }
  2858. pData->runner.stopRunner();
  2859. fClient = nullptr;
  2860. #ifdef BUILD_BRIDGE
  2861. fIsRunning = false;
  2862. #else
  2863. carla_zeroPointers(fRackPorts, kRackPortCount);
  2864. #endif
  2865. callback(true, true, ENGINE_CALLBACK_ERROR, 0, 0, 0, 0, 0.0f,
  2866. "Carla has been killed by JACK, or JACK has stopped.\n"
  2867. "You can still save if you want, but you will lose patchbay connections and positions.");
  2868. }
  2869. // -------------------------------------------------------------------
  2870. void handlePluginJackShutdownCallback(const CarlaPluginPtr plugin)
  2871. {
  2872. CarlaEngineJackClient* const engineClient((CarlaEngineJackClient*)plugin->getEngineClient());
  2873. CARLA_SAFE_ASSERT_RETURN(engineClient != nullptr,);
  2874. plugin->tryLock(true);
  2875. engineClient->invalidate();
  2876. plugin->unlock();
  2877. callback(true, true, ENGINE_CALLBACK_PLUGIN_UNAVAILABLE, plugin->getId(), 0, 0, 0, 0.0f, "Killed by JACK");
  2878. }
  2879. // -------------------------------------------------------------------
  2880. private:
  2881. jack_client_t* fClient;
  2882. bool fExternalPatchbayHost;
  2883. bool fExternalPatchbayOsc;
  2884. bool fFreewheel;
  2885. CarlaString fClientName;
  2886. CarlaRecursiveMutex fThreadSafeMetadataMutex;
  2887. // -------------------------------------------------------------------
  2888. #ifdef BUILD_BRIDGE
  2889. bool fIsRunning;
  2890. #else
  2891. CarlaString fClientNamePrefix;
  2892. enum RackPorts {
  2893. kRackPortAudioIn1 = 0,
  2894. kRackPortAudioIn2 = 1,
  2895. kRackPortAudioOut1 = 2,
  2896. kRackPortAudioOut2 = 3,
  2897. kRackPortEventIn = 4,
  2898. kRackPortEventOut = 5,
  2899. kRackPortCount = 6
  2900. };
  2901. jack_port_t* fRackPorts[kRackPortCount];
  2902. bool fTimebaseMaster;
  2903. bool fTimebaseRolling;
  2904. uint64_t fTimebaseUsecs;
  2905. PatchbayGroupList fUsedGroups;
  2906. PatchbayPortList fUsedPorts;
  2907. PatchbayConnectionList fUsedConnections;
  2908. CarlaMutex fPatchbayProcThreadProtectionMutex;
  2909. mutable CharStringListPtr fRetConns;
  2910. void findPluginIdAndIcon(const char* const clientName, int& pluginId, PatchbayIcon& icon) const noexcept
  2911. {
  2912. carla_debug("CarlaEngineJack::findPluginIdAndIcon(\"%s\", ...)", clientName);
  2913. // TODO - this currently only works in multi-client mode
  2914. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  2915. return;
  2916. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  2917. jack_uuid_t uuid;
  2918. {
  2919. char* const uuidstr = jackbridge_get_uuid_for_client_name(fClient, clientName);
  2920. CARLA_SAFE_ASSERT_RETURN(uuidstr != nullptr && uuidstr[0] != '\0',);
  2921. const bool parsed = jackbridge_uuid_parse(uuidstr, &uuid);
  2922. jackbridge_free(uuidstr);
  2923. /* if parsing fails, meta-data is not available..
  2924. this could be because JACK version is old, or perhaps this is an internal client */
  2925. if (! parsed)
  2926. return;
  2927. }
  2928. bool clientBelongsToUs;
  2929. {
  2930. char* value = nullptr;
  2931. char* type = nullptr;
  2932. if (! jackbridge_get_property(uuid, URI_MAIN_CLIENT_NAME, &value, &type))
  2933. return;
  2934. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  2935. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  2936. CARLA_SAFE_ASSERT_RETURN(std::strcmp(type, URI_TYPE_STRING) == 0,);
  2937. clientBelongsToUs = fClientName == value;
  2938. jackbridge_free(value);
  2939. jackbridge_free(type);
  2940. }
  2941. {
  2942. char* value = nullptr;
  2943. char* type = nullptr;
  2944. if (! jackbridge_get_property(uuid, URI_PLUGIN_ID, &value, &type))
  2945. return;
  2946. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  2947. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  2948. CARLA_SAFE_ASSERT_RETURN(std::strcmp(type, URI_TYPE_INTEGER) == 0,);
  2949. if (clientBelongsToUs)
  2950. pluginId = std::atoi(value);
  2951. icon = PATCHBAY_ICON_PLUGIN;
  2952. jackbridge_free(value);
  2953. jackbridge_free(type);
  2954. }
  2955. {
  2956. char* value = nullptr;
  2957. char* type = nullptr;
  2958. if (! jackbridge_get_property(uuid, URI_PLUGIN_ICON, &value, &type))
  2959. return;
  2960. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  2961. CARLA_SAFE_ASSERT_RETURN(value != nullptr && value[0] != '\0',);
  2962. CARLA_SAFE_ASSERT_RETURN(std::strcmp(type, URI_TYPE_STRING) == 0,);
  2963. /**/ if (std::strcmp(value, "app") == 0)
  2964. icon = PATCHBAY_ICON_APPLICATION;
  2965. else if (std::strcmp(value, "application") == 0)
  2966. icon = PATCHBAY_ICON_APPLICATION;
  2967. else if (std::strcmp(value, "plugin") == 0)
  2968. icon = PATCHBAY_ICON_PLUGIN;
  2969. else if (std::strcmp(value, "hardware") == 0)
  2970. icon = PATCHBAY_ICON_HARDWARE;
  2971. else if (std::strcmp(value, "carla") == 0)
  2972. icon = PATCHBAY_ICON_CARLA;
  2973. else if (std::strcmp(value, "distrho") == 0)
  2974. icon = PATCHBAY_ICON_DISTRHO;
  2975. else if (std::strcmp(value, "file") == 0)
  2976. icon = PATCHBAY_ICON_FILE;
  2977. jackbridge_free(value);
  2978. jackbridge_free(type);
  2979. }
  2980. }
  2981. // prevent recursion on patchbay group position changes
  2982. struct LastPatchbaySetGroupPos {
  2983. int x1, y1, x2, y2;
  2984. LastPatchbaySetGroupPos()
  2985. : x1(0), y1(0), x2(0), y2(0) {}
  2986. void clear() noexcept
  2987. {
  2988. x1 = y1 = x2 = y2 = 0;
  2989. }
  2990. void set(const int _x1, const int _y1, const int _x2, const int _y2) noexcept
  2991. {
  2992. x1 = _x1;
  2993. y1 = _y1;
  2994. x2 = _x2;
  2995. y2 = _y2;
  2996. }
  2997. bool operator!=(const LastPatchbaySetGroupPos& pos) const noexcept
  2998. {
  2999. return pos.x1 != x1 || pos.y1 != y1 || pos.x2 != x2 || pos.y2 != y2;
  3000. }
  3001. } fLastPatchbaySetGroupPos;
  3002. // handy stuff only needed for initJackPatchbay
  3003. struct GroupToIdData {
  3004. uint id;
  3005. PatchbayIcon icon;
  3006. int pluginId;
  3007. char strVal[STR_MAX];
  3008. };
  3009. struct PortToIdData {
  3010. uint group;
  3011. uint port;
  3012. uint flags;
  3013. char strVal[STR_MAX];
  3014. };
  3015. struct ConnectionToIdData {
  3016. uint id;
  3017. char strVal[STR_MAX];
  3018. };
  3019. void initJackPatchbay(const bool sendHost, const bool sendOSC, const char* const ourName, const bool groupsOnly)
  3020. {
  3021. CARLA_SAFE_ASSERT_RETURN(ourName != nullptr && ourName[0] != '\0',);
  3022. fLastPatchbaySetGroupPos.clear();
  3023. uint id, carlaId;
  3024. CarlaStringList parsedGroups;
  3025. LinkedList<GroupToIdData> groupCallbackData;
  3026. LinkedList<PortToIdData> portsCallbackData;
  3027. LinkedList<ConnectionToIdData> connCallbackData;
  3028. {
  3029. const CarlaMutexLocker cml1(fUsedGroups.mutex);
  3030. const CarlaMutexLocker cml2(fUsedPorts.mutex);
  3031. const CarlaMutexLocker cml3(fUsedConnections.mutex);
  3032. const CarlaMutexLocker cml4(fPostPonedEventsMutex);
  3033. fUsedGroups.clear();
  3034. fUsedPorts.clear();
  3035. fUsedConnections.clear();
  3036. fPostPonedEvents.clear();
  3037. // add our client first
  3038. {
  3039. carlaId = ++fUsedGroups.lastId;
  3040. parsedGroups.append(ourName);
  3041. GroupNameToId groupNameToId;
  3042. groupNameToId.setData(carlaId, ourName);
  3043. fUsedGroups.list.append(groupNameToId);
  3044. }
  3045. // query all jack ports
  3046. {
  3047. const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, 0);
  3048. CARLA_SAFE_ASSERT_RETURN(ports != nullptr,);
  3049. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  3050. for (int i=0; ports[i] != nullptr; ++i)
  3051. {
  3052. const char* const fullPortName(ports[i]);
  3053. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  3054. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  3055. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  3056. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  3057. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  3058. const CarlaJackPortHints jackPortHints(CarlaJackPortHints::fromPort(jackPort));
  3059. uint groupId = 0;
  3060. bool found;
  3061. CarlaString groupName(fullPortName);
  3062. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  3063. CARLA_SAFE_ASSERT_CONTINUE(found);
  3064. if (parsedGroups.contains(groupName))
  3065. {
  3066. groupId = fUsedGroups.getGroupId(groupName);
  3067. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  3068. }
  3069. else
  3070. {
  3071. groupId = ++fUsedGroups.lastId;
  3072. parsedGroups.append(groupName);
  3073. GroupNameToId groupNameToId;
  3074. groupNameToId.setData(groupId, groupName);
  3075. int pluginId = -1;
  3076. PatchbayIcon icon = jackPortHints.isHardware ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  3077. findPluginIdAndIcon(groupName, pluginId, icon);
  3078. fUsedGroups.list.append(groupNameToId);
  3079. if (! groupsOnly)
  3080. {
  3081. GroupToIdData groupData;
  3082. groupData.id = groupId;
  3083. groupData.icon = icon;
  3084. groupData.pluginId = pluginId;
  3085. std::strncpy(groupData.strVal, groupName, STR_MAX-1);
  3086. groupData.strVal[STR_MAX-1] = '\0';
  3087. groupCallbackData.append(groupData);
  3088. }
  3089. }
  3090. if (groupsOnly)
  3091. continue;
  3092. uint canvasPortFlags = 0x0;
  3093. canvasPortFlags |= jackPortHints.isInput ? PATCHBAY_PORT_IS_INPUT : 0x0;
  3094. /**/ if (jackPortHints.isCV)
  3095. canvasPortFlags |= PATCHBAY_PORT_TYPE_CV;
  3096. else if (jackPortHints.isOSC)
  3097. canvasPortFlags |= PATCHBAY_PORT_TYPE_OSC;
  3098. else if (jackPortHints.isAudio)
  3099. canvasPortFlags |= PATCHBAY_PORT_TYPE_AUDIO;
  3100. else if (jackPortHints.isMIDI)
  3101. canvasPortFlags |= PATCHBAY_PORT_TYPE_MIDI;
  3102. id = ++fUsedPorts.lastId;
  3103. PortNameToId portNameToId;
  3104. portNameToId.setData(groupId, id, shortPortName, fullPortName);
  3105. fUsedPorts.list.append(portNameToId);
  3106. PortToIdData portData;
  3107. portData.group = groupId;
  3108. portData.port = id;
  3109. portData.flags = canvasPortFlags;
  3110. std::strncpy(portData.strVal, shortPortName, STR_MAX-1);
  3111. portData.strVal[STR_MAX-1] = '\0';
  3112. portsCallbackData.append(portData);
  3113. }
  3114. jackbridge_free(ports);
  3115. }
  3116. if (groupsOnly)
  3117. return;
  3118. // query connections, after all ports are in place
  3119. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  3120. {
  3121. for (int i=0; ports[i] != nullptr; ++i)
  3122. {
  3123. const char* const fullPortName(ports[i]);
  3124. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  3125. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  3126. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  3127. const PortNameToId& thisPort(fUsedPorts.getPortNameToId(fullPortName));
  3128. CARLA_SAFE_ASSERT_CONTINUE(thisPort.group > 0);
  3129. CARLA_SAFE_ASSERT_CONTINUE(thisPort.port > 0);
  3130. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  3131. {
  3132. for (int j=0; connections[j] != nullptr; ++j)
  3133. {
  3134. const char* const connection(connections[j]);
  3135. CARLA_SAFE_ASSERT_CONTINUE(connection != nullptr && connection[0] != '\0');
  3136. const PortNameToId& targetPort(fUsedPorts.getPortNameToId(connection));
  3137. CARLA_SAFE_ASSERT_CONTINUE(targetPort.group > 0);
  3138. CARLA_SAFE_ASSERT_CONTINUE(targetPort.port > 0);
  3139. id = ++fUsedConnections.lastId;
  3140. ConnectionToId connectionToId;
  3141. connectionToId.setData(id, thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  3142. fUsedConnections.list.append(connectionToId);
  3143. ConnectionToIdData connData;
  3144. connData.id = id;
  3145. std::snprintf(connData.strVal, STR_MAX-1, "%i:%i:%i:%i",
  3146. thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  3147. connData.strVal[STR_MAX-1] = '\0';
  3148. connCallbackData.append(connData);
  3149. }
  3150. jackbridge_free(connections);
  3151. }
  3152. }
  3153. jackbridge_free(ports);
  3154. }
  3155. }
  3156. const GroupToIdData groupFallback = { 0, PATCHBAY_ICON_PLUGIN, -1, { '\0' } };
  3157. const PortToIdData portFallback = { 0, 0, 0, { '\0' } };
  3158. const ConnectionToIdData connFallback = { 0, { '\0' } };
  3159. callback(sendHost, sendOSC,
  3160. ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED,
  3161. carlaId,
  3162. PATCHBAY_ICON_CARLA,
  3163. MAIN_CARLA_PLUGIN_ID,
  3164. 0, 0.0f,
  3165. ourName);
  3166. {
  3167. const CarlaRecursiveMutexLocker crml(fThreadSafeMetadataMutex);
  3168. for (LinkedList<GroupToIdData>::Itenerator it = groupCallbackData.begin2(); it.valid(); it.next())
  3169. {
  3170. const GroupToIdData& group(it.getValue(groupFallback));
  3171. callback(sendHost, sendOSC,
  3172. ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED,
  3173. group.id,
  3174. group.icon,
  3175. group.pluginId,
  3176. 0, 0.0f,
  3177. group.strVal);
  3178. jack_uuid_t uuid;
  3179. {
  3180. char* const uuidstr = jackbridge_get_uuid_for_client_name(fClient, group.strVal);
  3181. CARLA_SAFE_ASSERT_CONTINUE(uuidstr != nullptr && uuidstr[0] != '\0');
  3182. const bool parsed = jackbridge_uuid_parse(uuidstr, &uuid);
  3183. jackbridge_free(uuidstr);
  3184. /* if parsing fails, meta-data is not available..
  3185. this could be because JACK version is old, or perhaps this is an internal client */
  3186. if (! parsed)
  3187. continue;
  3188. }
  3189. char* value = nullptr;
  3190. char* type = nullptr;
  3191. if (jackbridge_get_property(uuid, URI_POSITION, &value, &type)
  3192. && value != nullptr
  3193. && type != nullptr
  3194. && std::strcmp(type, URI_TYPE_STRING) == 0)
  3195. {
  3196. if (char* sep1 = std::strstr(value, ":"))
  3197. {
  3198. int x1, y1 = 0, x2 = 0, y2 = 0;
  3199. *sep1++ = '\0';
  3200. x1 = std::atoi(value);
  3201. if (char* sep2 = std::strstr(sep1, ":"))
  3202. {
  3203. *sep2++ = '\0';
  3204. y1 = std::atoi(sep1);
  3205. if (char* sep3 = std::strstr(sep2, ":"))
  3206. {
  3207. *sep3++ = '\0';
  3208. x2 = std::atoi(sep2);
  3209. y2 = std::atoi(sep3);
  3210. }
  3211. }
  3212. jackbridge_free(value);
  3213. jackbridge_free(type);
  3214. callback(sendHost, sendOSC,
  3215. ENGINE_CALLBACK_PATCHBAY_CLIENT_POSITION_CHANGED,
  3216. group.id, x1, y1, x2, static_cast<float>(y2),
  3217. nullptr);
  3218. }
  3219. }
  3220. }
  3221. }
  3222. for (LinkedList<PortToIdData>::Itenerator it = portsCallbackData.begin2(); it.valid(); it.next())
  3223. {
  3224. const PortToIdData& port(it.getValue(portFallback));
  3225. callback(sendHost, sendOSC,
  3226. ENGINE_CALLBACK_PATCHBAY_PORT_ADDED,
  3227. port.group,
  3228. static_cast<int>(port.port),
  3229. static_cast<int>(port.flags),
  3230. 0, 0.0f,
  3231. port.strVal);
  3232. }
  3233. for (LinkedList<ConnectionToIdData>::Itenerator it = connCallbackData.begin2(); it.valid(); it.next())
  3234. {
  3235. const ConnectionToIdData& conn(it.getValue(connFallback));
  3236. callback(sendHost, sendOSC,
  3237. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  3238. conn.id,
  3239. 0, 0, 0, 0.0f,
  3240. conn.strVal);
  3241. }
  3242. groupCallbackData.clear();
  3243. portsCallbackData.clear();
  3244. connCallbackData.clear();
  3245. }
  3246. #endif
  3247. // -------------------------------------------------------------------
  3248. void processPlugin(CarlaPluginPtr& plugin, const uint32_t nframes)
  3249. {
  3250. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3251. CarlaEngineJackClient* const client = (CarlaEngineJackClient*)plugin->getEngineClient();
  3252. CarlaEngineJackCVSourcePorts& cvSourcePorts(client->getCVSourcePorts());
  3253. const CarlaRecursiveMutexTryLocker crmtl(cvSourcePorts.getMutex(), fFreewheel);
  3254. // const CarlaRecursiveMutexLocker crml(cvSourcePorts.getMutex());
  3255. #endif
  3256. /*
  3257. const uint32_t audioInCount = client->getPortCount(kEnginePortTypeAudio, true);
  3258. const uint32_t audioOutCount = client->getPortCount(kEnginePortTypeAudio, false);
  3259. const uint32_t cvInCount = client->getPortCount(kEnginePortTypeCV, true);
  3260. const uint32_t cvOutCount = client->getPortCount(kEnginePortTypeCV, false);
  3261. */
  3262. const uint32_t audioInCount = plugin->getAudioInCount();
  3263. const uint32_t audioOutCount = plugin->getAudioOutCount();
  3264. const uint32_t cvInCount = plugin->getCVInCount();
  3265. const uint32_t cvOutCount = plugin->getCVOutCount();
  3266. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3267. const uint32_t cvsInCount = crmtl.wasLocked() ? cvSourcePorts.getPortCount() : 0;
  3268. #else
  3269. const uint32_t cvsInCount = 0;
  3270. #endif
  3271. const float* audioIn[audioInCount];
  3272. /* */ float* audioOut[audioOutCount];
  3273. const float* cvIn[cvInCount+cvsInCount];
  3274. /* */ float* cvOut[cvOutCount];
  3275. for (uint32_t i=0; i < audioInCount; ++i)
  3276. {
  3277. if (CarlaEngineAudioPort* const port = plugin->getAudioInPort(i))
  3278. audioIn[i] = port->getBuffer();
  3279. else
  3280. audioIn[i] = nullptr;
  3281. }
  3282. for (uint32_t i=0; i < audioOutCount; ++i)
  3283. {
  3284. if (CarlaEngineAudioPort* const port = plugin->getAudioOutPort(i))
  3285. audioOut[i] = port->getBuffer();
  3286. else
  3287. audioOut[i] = nullptr;
  3288. }
  3289. for (uint32_t i=0; i < cvInCount; ++i)
  3290. {
  3291. if (CarlaEngineCVPort* const port = plugin->getCVInPort(i))
  3292. cvIn[i] = port->getBuffer();
  3293. else
  3294. cvIn[i] = nullptr;
  3295. }
  3296. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3297. for (uint32_t i=cvInCount, j=0; j < cvsInCount; ++i, ++j)
  3298. {
  3299. if (CarlaEngineCVPort* const port = cvSourcePorts.getPort(j))
  3300. {
  3301. port->initBuffer();
  3302. cvIn[i] = port->getBuffer();
  3303. }
  3304. else
  3305. {
  3306. cvIn[i] = nullptr;
  3307. }
  3308. }
  3309. #endif
  3310. for (uint32_t i=0; i < cvOutCount; ++i)
  3311. {
  3312. if (CarlaEngineCVPort* const port = plugin->getCVOutPort(i))
  3313. cvOut[i] = port->getBuffer();
  3314. else
  3315. cvOut[i] = nullptr;
  3316. }
  3317. float inPeaks[2] = { 0.0f };
  3318. float outPeaks[2] = { 0.0f };
  3319. for (uint32_t i=0; i < audioInCount && i < 2; ++i)
  3320. {
  3321. for (uint32_t j=0; j < nframes; ++j)
  3322. {
  3323. const float absV(std::abs(audioIn[i][j]));
  3324. if (absV > inPeaks[i])
  3325. inPeaks[i] = absV;
  3326. }
  3327. }
  3328. plugin->process(audioIn, audioOut, cvIn, cvOut, nframes);
  3329. for (uint32_t i=0; i < audioOutCount && i < 2; ++i)
  3330. {
  3331. for (uint32_t j=0; j < nframes; ++j)
  3332. {
  3333. const float absV(std::abs(audioOut[i][j]));
  3334. if (absV > outPeaks[i])
  3335. outPeaks[i] = absV;
  3336. }
  3337. }
  3338. setPluginPeaksRT(plugin->getId(), inPeaks, outPeaks);
  3339. }
  3340. #ifndef BUILD_BRIDGE
  3341. // -------------------------------------------------------------------
  3342. struct PostPonedJackEvent {
  3343. enum Type {
  3344. kTypeNull = 0,
  3345. kTypeClientUnregister,
  3346. kTypeClientPositionChange,
  3347. kTypePortRegister,
  3348. kTypePortUnregister,
  3349. kTypePortConnect,
  3350. kTypePortDisconnect,
  3351. kTypePortRename
  3352. };
  3353. Type type;
  3354. union {
  3355. struct {
  3356. char name[STR_MAX+1];
  3357. } clientRegister;
  3358. struct {
  3359. char name[STR_MAX+1];
  3360. } clientUnregister;
  3361. struct {
  3362. jack_uuid_t uuid;
  3363. } clientPositionChange;
  3364. struct {
  3365. char shortName[STR_MAX+1];
  3366. char fullName[STR_MAX+1];
  3367. CarlaJackPortHints hints;
  3368. } portRegister;
  3369. struct {
  3370. char fullName[STR_MAX+1];
  3371. } portUnregister;
  3372. struct {
  3373. char oldFullName[STR_MAX+1];
  3374. char newFullName[STR_MAX+1];
  3375. char newShortName[STR_MAX+1];
  3376. } portRename;
  3377. struct {
  3378. char portNameA[STR_MAX+1];
  3379. char portNameB[STR_MAX+1];
  3380. } portConnect;
  3381. struct {
  3382. char portNameA[STR_MAX+1];
  3383. char portNameB[STR_MAX+1];
  3384. } portDisconnect;
  3385. };
  3386. };
  3387. LinkedList<PostPonedJackEvent> fPostPonedEvents;
  3388. CarlaMutex fPostPonedEventsMutex;
  3389. bool fIsInternalClient;
  3390. void postponeJackCallback(PostPonedJackEvent& ev)
  3391. {
  3392. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  3393. fPostPonedEvents.append(ev);
  3394. }
  3395. void run() override
  3396. {
  3397. for (; ! shouldThreadExit();)
  3398. {
  3399. if (fIsInternalClient)
  3400. idle();
  3401. if (fClient == nullptr)
  3402. break;
  3403. carla_msleep(200);
  3404. }
  3405. }
  3406. #endif // BUILD_BRIDGE
  3407. // -------------------------------------------------------------------
  3408. // disable -Wattributes warnings
  3409. #if defined(__clang__)
  3410. # pragma clang diagnostic push
  3411. # pragma clang diagnostic ignored "-Wattributes"
  3412. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  3413. # pragma GCC diagnostic push
  3414. # pragma GCC diagnostic ignored "-Wattributes"
  3415. #endif
  3416. #define handlePtr ((CarlaEngineJack*)arg)
  3417. static void JACKBRIDGE_API carla_jack_thread_init_callback(void*)
  3418. {
  3419. #ifdef __SSE2_MATH__
  3420. // Set FTZ and DAZ flags
  3421. _mm_setcsr(_mm_getcsr() | 0x8040);
  3422. #endif
  3423. }
  3424. static int JACKBRIDGE_API carla_jack_bufsize_callback(jack_nframes_t newBufferSize, void* arg)
  3425. {
  3426. handlePtr->handleJackBufferSizeCallback(newBufferSize);
  3427. return 0;
  3428. }
  3429. static int JACKBRIDGE_API carla_jack_srate_callback(jack_nframes_t newSampleRate, void* arg)
  3430. {
  3431. handlePtr->handleJackSampleRateCallback(newSampleRate);
  3432. return 0;
  3433. }
  3434. static void JACKBRIDGE_API carla_jack_freewheel_callback(int starting, void* arg)
  3435. {
  3436. handlePtr->handleJackFreewheelCallback(bool(starting));
  3437. }
  3438. static void JACKBRIDGE_API carla_jack_latency_callback(jack_latency_callback_mode_t mode, void* arg)
  3439. {
  3440. handlePtr->handleJackLatencyCallback(mode);
  3441. }
  3442. static int JACKBRIDGE_API carla_jack_process_callback(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  3443. {
  3444. handlePtr->handleJackProcessCallback(nframes);
  3445. return 0;
  3446. }
  3447. #ifndef BUILD_BRIDGE
  3448. static void JACKBRIDGE_API carla_jack_timebase_callback(jack_transport_state_t, jack_nframes_t nframes, jack_position_t* pos, int new_pos, void* arg) __attribute__((annotate("realtime")))
  3449. {
  3450. handlePtr->handleJackTimebaseCallback(nframes, pos, new_pos);
  3451. }
  3452. static void JACKBRIDGE_API carla_jack_client_registration_callback(const char* name, int reg, void* arg)
  3453. {
  3454. if (reg == 0)
  3455. return;
  3456. PostPonedJackEvent ev;
  3457. carla_zeroStruct(ev);
  3458. ev.type = PostPonedJackEvent::kTypeClientUnregister;
  3459. std::strncpy(ev.clientUnregister.name, name, STR_MAX);
  3460. handlePtr->postponeJackCallback(ev);
  3461. }
  3462. static void JACKBRIDGE_API carla_jack_port_registration_callback(jack_port_id_t port_id, int reg, void* arg)
  3463. {
  3464. const jack_port_t* const port = jackbridge_port_by_id(handlePtr->fClient, port_id);
  3465. CARLA_SAFE_ASSERT_RETURN(port != nullptr,);
  3466. const char* const fullName = jackbridge_port_name(port);
  3467. CARLA_SAFE_ASSERT_RETURN(fullName != nullptr && fullName[0] != '\0',);
  3468. PostPonedJackEvent ev;
  3469. carla_zeroStruct(ev);
  3470. if (reg != 0)
  3471. {
  3472. const char* const shortName = jackbridge_port_short_name(port);
  3473. CARLA_SAFE_ASSERT_RETURN(shortName != nullptr && shortName[0] != '\0',);
  3474. ev.type = PostPonedJackEvent::kTypePortRegister;
  3475. std::strncpy(ev.portRegister.fullName, fullName, STR_MAX);
  3476. std::strncpy(ev.portRegister.shortName, shortName, STR_MAX);
  3477. const CarlaRecursiveMutexLocker crml(handlePtr->fThreadSafeMetadataMutex);
  3478. ev.portRegister.hints = CarlaJackPortHints::fromPort(port);
  3479. }
  3480. else
  3481. {
  3482. ev.type = PostPonedJackEvent::kTypePortUnregister;
  3483. std::strncpy(ev.portUnregister.fullName, fullName, STR_MAX);
  3484. }
  3485. handlePtr->postponeJackCallback(ev);
  3486. }
  3487. static void JACKBRIDGE_API carla_jack_port_connect_callback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg)
  3488. {
  3489. const jack_port_t* const portA = jackbridge_port_by_id(handlePtr->fClient, a);
  3490. CARLA_SAFE_ASSERT_RETURN(portA != nullptr,);
  3491. const jack_port_t* const portB = jackbridge_port_by_id(handlePtr->fClient, b);
  3492. CARLA_SAFE_ASSERT_RETURN(portB != nullptr,);
  3493. const char* const fullNameA = jackbridge_port_name(portA);
  3494. CARLA_SAFE_ASSERT_RETURN(fullNameA != nullptr && fullNameA[0] != '\0',);
  3495. const char* const fullNameB = jackbridge_port_name(portB);
  3496. CARLA_SAFE_ASSERT_RETURN(fullNameB != nullptr && fullNameB[0] != '\0',);
  3497. PostPonedJackEvent ev;
  3498. carla_zeroStruct(ev);
  3499. if (connect != 0)
  3500. {
  3501. ev.type = PostPonedJackEvent::kTypePortConnect;
  3502. std::strncpy(ev.portConnect.portNameA, fullNameA, STR_MAX);
  3503. std::strncpy(ev.portConnect.portNameB, fullNameB, STR_MAX);
  3504. }
  3505. else
  3506. {
  3507. ev.type = PostPonedJackEvent::kTypePortDisconnect;
  3508. std::strncpy(ev.portDisconnect.portNameA, fullNameA, STR_MAX);
  3509. std::strncpy(ev.portDisconnect.portNameB, fullNameB, STR_MAX);
  3510. }
  3511. handlePtr->postponeJackCallback(ev);
  3512. }
  3513. static void JACKBRIDGE_API carla_jack_port_rename_callback(jack_port_id_t port_id, const char* oldName, const char* newName, void* arg)
  3514. {
  3515. const jack_port_t* const port = jackbridge_port_by_id(handlePtr->fClient, port_id);
  3516. CARLA_SAFE_ASSERT_RETURN(port != nullptr,);
  3517. const char* const shortName = jackbridge_port_short_name(port);
  3518. CARLA_SAFE_ASSERT_RETURN(shortName != nullptr && shortName[0] != '\0',);
  3519. PostPonedJackEvent ev;
  3520. carla_zeroStruct(ev);
  3521. ev.type = PostPonedJackEvent::kTypePortRename;
  3522. std::strncpy(ev.portRename.oldFullName, oldName, STR_MAX);
  3523. std::strncpy(ev.portRename.newFullName, newName, STR_MAX);
  3524. std::strncpy(ev.portRename.newShortName, shortName, STR_MAX);
  3525. handlePtr->postponeJackCallback(ev);
  3526. }
  3527. static void carla_jack_property_change_callback(jack_uuid_t subject, const char* key, jack_property_change_t change, void* arg)
  3528. {
  3529. if (change != PropertyChanged)
  3530. return;
  3531. if (std::strcmp(key, URI_POSITION) != 0)
  3532. return;
  3533. PostPonedJackEvent ev;
  3534. carla_zeroStruct(ev);
  3535. ev.type = PostPonedJackEvent::kTypeClientPositionChange;
  3536. ev.clientPositionChange.uuid = subject;
  3537. handlePtr->postponeJackCallback(ev);
  3538. }
  3539. static int JACKBRIDGE_API carla_jack_xrun_callback(void* arg)
  3540. {
  3541. ++(handlePtr->pData->xruns);
  3542. return 0;
  3543. }
  3544. #endif
  3545. static void JACKBRIDGE_API carla_jack_shutdown_callback(void* arg)
  3546. {
  3547. handlePtr->handleJackShutdownCallback();
  3548. }
  3549. #undef handlePtr
  3550. // -------------------------------------------------------------------
  3551. #ifndef BUILD_BRIDGE
  3552. static int JACKBRIDGE_API carla_jack_process_callback_plugin(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  3553. {
  3554. CarlaPluginPtr* const pluginPtr = static_cast<CarlaPluginPtr*>(arg);
  3555. CARLA_SAFE_ASSERT_RETURN(pluginPtr != nullptr, 0);
  3556. CarlaPluginPtr plugin = *pluginPtr;
  3557. CARLA_SAFE_ASSERT_RETURN(plugin.get() != nullptr && plugin->isEnabled(), 0);
  3558. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  3559. CARLA_SAFE_ASSERT_RETURN(engine != nullptr, 0);
  3560. if (plugin->tryLock(engine->fFreewheel))
  3561. {
  3562. plugin->initBuffers();
  3563. engine->processPlugin(plugin, nframes);
  3564. plugin->unlock();
  3565. }
  3566. return 0;
  3567. }
  3568. /*
  3569. static int JACKBRIDGE_API carla_jack_bufsize_callback_plugin(jack_nframes_t nframes, void* arg)
  3570. {
  3571. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  3572. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  3573. plugin->bufferSizeChanged(nframes);
  3574. return 1;
  3575. }
  3576. static int JACKBRIDGE_API carla_jack_srate_callback_plugin(jack_nframes_t nframes, void* arg)
  3577. {
  3578. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  3579. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  3580. plugin->sampleRateChanged(nframes);
  3581. return 1;
  3582. }
  3583. */
  3584. static void JACKBRIDGE_API carla_jack_latency_callback_plugin(jack_latency_callback_mode_t /*mode*/, void* /*arg*/)
  3585. {
  3586. // TODO
  3587. }
  3588. static void JACKBRIDGE_API carla_jack_shutdown_callback_plugin(void* arg)
  3589. {
  3590. CarlaPluginPtr* const pluginPtr = static_cast<CarlaPluginPtr*>(arg);
  3591. CARLA_SAFE_ASSERT_RETURN(pluginPtr != nullptr,);
  3592. CarlaPluginPtr plugin = *pluginPtr;
  3593. CARLA_SAFE_ASSERT_RETURN(plugin.get() != nullptr,);
  3594. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  3595. CARLA_SAFE_ASSERT_RETURN(engine != nullptr,);
  3596. engine->handlePluginJackShutdownCallback(plugin);
  3597. }
  3598. #endif
  3599. // enable -Wattributes again
  3600. #if defined(__clang__)
  3601. # pragma clang diagnostic pop
  3602. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  3603. # pragma GCC diagnostic pop
  3604. #endif
  3605. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJack)
  3606. };
  3607. // -----------------------------------------------------------------------
  3608. namespace EngineInit {
  3609. CarlaEngine* newJack()
  3610. {
  3611. carla_debug("EngineInit::newJack()");
  3612. return new CarlaEngineJack();
  3613. }
  3614. }
  3615. // -----------------------------------------------------------------------
  3616. CARLA_BACKEND_END_NAMESPACE
  3617. #if defined(JACKBRIDGE_DIRECT) && !defined(BUILD_BRIDGE)
  3618. // -----------------------------------------------------------------------
  3619. // internal jack client
  3620. CARLA_PLUGIN_EXPORT
  3621. int jack_initialize(jack_client_t *client, const char *load_init);
  3622. CARLA_PLUGIN_EXPORT
  3623. void jack_finish(void *arg);
  3624. #ifdef CARLA_OS_UNIX
  3625. # include "ThreadSafeFFTW.hpp"
  3626. #endif
  3627. // -----------------------------------------------------------------------
  3628. CARLA_PLUGIN_EXPORT
  3629. int jack_initialize(jack_client_t* const client, const char* const load_init)
  3630. {
  3631. CARLA_BACKEND_USE_NAMESPACE
  3632. #ifdef CARLA_OS_UNIX
  3633. static const ThreadSafeFFTW sThreadSafeFFTW;
  3634. #endif
  3635. EngineProcessMode mode;
  3636. if (load_init != nullptr && std::strcmp(load_init, "rack") == 0)
  3637. mode = ENGINE_PROCESS_MODE_CONTINUOUS_RACK;
  3638. else
  3639. mode = ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  3640. CarlaEngineJack* const engine = new CarlaEngineJack();
  3641. engine->setOption(ENGINE_OPTION_FORCE_STEREO, 1, nullptr);
  3642. engine->setOption(ENGINE_OPTION_AUDIO_DRIVER, 0, "JACK");
  3643. engine->setOption(ENGINE_OPTION_AUDIO_DEVICE, 0, "Auto-Connect ON");
  3644. engine->setOption(ENGINE_OPTION_OSC_ENABLED, 1, nullptr);
  3645. engine->setOption(ENGINE_OPTION_OSC_PORT_TCP, 22752, nullptr);
  3646. engine->setOption(ENGINE_OPTION_OSC_PORT_UDP, 22752, nullptr);
  3647. engine->setOption(ENGINE_OPTION_PROCESS_MODE, mode, nullptr);
  3648. engine->setOption(ENGINE_OPTION_TRANSPORT_MODE, ENGINE_TRANSPORT_MODE_JACK, nullptr);
  3649. #ifdef __MOD_DEVICES__
  3650. engine->setOption(ENGINE_OPTION_FILE_PATH, FILE_AUDIO, "/data/user-files/Audio Loops:/data/user-files/Audio Tracks");
  3651. engine->setOption(ENGINE_OPTION_FILE_PATH, FILE_MIDI, "/data/user-files/MIDI Songs");
  3652. #endif
  3653. // FIXME
  3654. engine->setOption(ENGINE_OPTION_PATH_BINARIES, 0, "/usr/lib/carla");
  3655. engine->setOption(ENGINE_OPTION_PATH_RESOURCES, 0, "/usr/share/resources");
  3656. if (engine->initInternal(client))
  3657. return 0;
  3658. delete engine;
  3659. return 1;
  3660. }
  3661. CARLA_PLUGIN_EXPORT
  3662. void jack_finish(void *arg)
  3663. {
  3664. CARLA_BACKEND_USE_NAMESPACE
  3665. CarlaEngineJack* const engine = (CarlaEngineJack*)arg;;
  3666. CARLA_SAFE_ASSERT_RETURN(engine != nullptr,);
  3667. engine->setAboutToClose();
  3668. engine->removeAllPlugins();
  3669. engine->close();
  3670. delete engine;
  3671. }
  3672. // -----------------------------------------------------------------------
  3673. #endif // defined(JACKBRIDGE_DIRECT) && !defined(BUILD_BRIDGE)