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.

4684 lines
166KB

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