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.

4448 lines
157KB

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