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.

4593 lines
162KB

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