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.

4688 lines
166KB

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