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.

4579 lines
162KB

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