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.

2156 lines
75KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2014 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 "CarlaEngineInternal.hpp"
  18. #include "CarlaPlugin.hpp"
  19. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaEngineUtils.hpp"
  21. #include "CarlaMathUtils.hpp"
  22. #include "CarlaMIDI.h"
  23. #include "CarlaPatchbayUtils.hpp"
  24. #include "CarlaStringList.hpp"
  25. #include "jackbridge/JackBridge.hpp"
  26. #include "jackey.h"
  27. #include "juce_audio_basics.h"
  28. #ifdef __SSE2_MATH__
  29. # include <xmmintrin.h>
  30. #endif
  31. #define URI_CANVAS_ICON "http://kxstudio.sf.net/ns/canvas/icon"
  32. using juce::FloatVectorOperations;
  33. using juce::String;
  34. using juce::StringArray;
  35. CARLA_BACKEND_START_NAMESPACE
  36. class CarlaEngineJack;
  37. class CarlaEngineJackClient;
  38. // -----------------------------------------------------------------------
  39. // Fallback data
  40. static const EngineEvent kFallbackJackEngineEvent = { kEngineEventTypeNull, 0, 0, {{ kEngineControlEventTypeNull, 0, 0.0f }} };
  41. // -----------------------------------------------------------------------
  42. // Carla Engine Port removal helper
  43. class CarlaEngineJackAudioPort;
  44. class CarlaEngineJackCVPort;
  45. class CarlaEngineJackEventPort;
  46. struct JackPortDeletionCallback {
  47. virtual ~JackPortDeletionCallback() noexcept {}
  48. virtual void jackAudioPortDeleted(CarlaEngineJackAudioPort* const) noexcept = 0;
  49. virtual void jackCVPortDeleted(CarlaEngineJackCVPort* const) noexcept = 0;
  50. virtual void jackEventPortDeleted(CarlaEngineJackEventPort* const) noexcept = 0;
  51. };
  52. // -----------------------------------------------------------------------
  53. // Carla Engine JACK-Audio port
  54. class CarlaEngineJackAudioPort : public CarlaEngineAudioPort
  55. {
  56. public:
  57. CarlaEngineJackAudioPort(const CarlaEngineClient& client, const bool isInputPort, jack_client_t* const jackClient, jack_port_t* const jackPort, JackPortDeletionCallback* const delCallback) noexcept
  58. : CarlaEngineAudioPort(client, isInputPort),
  59. fJackClient(jackClient),
  60. fJackPort(jackPort),
  61. kDeletionCallback(delCallback),
  62. leakDetector_CarlaEngineJackAudioPort()
  63. {
  64. carla_debug("CarlaEngineJackAudioPort::CarlaEngineJackAudioPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  65. switch (kClient.getEngine().getProccessMode())
  66. {
  67. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  68. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  69. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  70. #ifndef BUILD_BRIDGE
  71. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  72. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "AUDIO", "text/plain");
  73. #endif
  74. break;
  75. default:
  76. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  77. break;
  78. }
  79. }
  80. ~CarlaEngineJackAudioPort() noexcept override
  81. {
  82. carla_debug("CarlaEngineJackAudioPort::~CarlaEngineJackAudioPort()");
  83. if (fJackClient != nullptr && fJackPort != nullptr)
  84. {
  85. #ifndef BUILD_BRIDGE
  86. try {
  87. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  88. jackbridge_remove_property(fJackClient, uuid, JACKEY_SIGNAL_TYPE);
  89. } CARLA_SAFE_EXCEPTION("Audio port remove meta type");
  90. #endif
  91. try {
  92. jackbridge_port_unregister(fJackClient, fJackPort);
  93. } CARLA_SAFE_EXCEPTION("Audio port unregister");
  94. fJackClient = nullptr;
  95. fJackPort = nullptr;
  96. }
  97. if (kDeletionCallback != nullptr)
  98. kDeletionCallback->jackAudioPortDeleted(this);
  99. }
  100. void initBuffer() noexcept override
  101. {
  102. if (fJackPort == nullptr)
  103. return CarlaEngineAudioPort::initBuffer();
  104. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  105. try {
  106. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  107. }
  108. catch(...) {
  109. fBuffer = nullptr;
  110. return;
  111. }
  112. if (! kIsInput)
  113. FloatVectorOperations::clear(fBuffer, static_cast<int>(bufferSize));
  114. }
  115. void invalidate() noexcept
  116. {
  117. fJackClient = nullptr;
  118. fJackPort = nullptr;
  119. }
  120. private:
  121. jack_client_t* fJackClient;
  122. jack_port_t* fJackPort;
  123. JackPortDeletionCallback* const kDeletionCallback;
  124. friend class CarlaEngineJackClient;
  125. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackAudioPort)
  126. };
  127. // -----------------------------------------------------------------------
  128. // Carla Engine JACK-CV port
  129. class CarlaEngineJackCVPort : public CarlaEngineCVPort
  130. {
  131. public:
  132. CarlaEngineJackCVPort(const CarlaEngineClient& client, const bool isInputPort, jack_client_t* const jackClient, jack_port_t* const jackPort, JackPortDeletionCallback* const delCallback) noexcept
  133. : CarlaEngineCVPort(client, isInputPort),
  134. fJackClient(jackClient),
  135. fJackPort(jackPort),
  136. kDeletionCallback(delCallback),
  137. leakDetector_CarlaEngineJackCVPort()
  138. {
  139. carla_debug("CarlaEngineJackCVPort::CarlaEngineJackCVPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  140. switch (kClient.getEngine().getProccessMode())
  141. {
  142. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  143. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  144. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  145. #ifndef BUILD_BRIDGE
  146. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  147. jackbridge_set_property(jackClient, uuid, JACKEY_SIGNAL_TYPE, "CV", "text/plain");
  148. #endif
  149. break;
  150. default:
  151. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  152. break;
  153. }
  154. }
  155. ~CarlaEngineJackCVPort() noexcept override
  156. {
  157. carla_debug("CarlaEngineJackCVPort::~CarlaEngineJackCVPort()");
  158. if (fJackClient != nullptr && fJackPort != nullptr)
  159. {
  160. #ifndef BUILD_BRIDGE
  161. try {
  162. if (const jack_uuid_t uuid = jackbridge_port_uuid(fJackPort))
  163. jackbridge_remove_property(fJackClient, uuid, JACKEY_SIGNAL_TYPE);
  164. } CARLA_SAFE_EXCEPTION("CV port remove meta type");
  165. #endif
  166. try {
  167. jackbridge_port_unregister(fJackClient, fJackPort);
  168. } CARLA_SAFE_EXCEPTION("CV port unregister");
  169. fJackClient = nullptr;
  170. fJackPort = nullptr;
  171. }
  172. if (kDeletionCallback != nullptr)
  173. kDeletionCallback->jackCVPortDeleted(this);
  174. }
  175. void initBuffer() noexcept override
  176. {
  177. if (fJackPort == nullptr)
  178. return CarlaEngineCVPort::initBuffer();
  179. const uint32_t bufferSize(kClient.getEngine().getBufferSize());
  180. try {
  181. fBuffer = (float*)jackbridge_port_get_buffer(fJackPort, bufferSize);
  182. }
  183. catch(...) {
  184. fBuffer = nullptr;
  185. return;
  186. }
  187. if (! kIsInput)
  188. FloatVectorOperations::clear(fBuffer, static_cast<int>(bufferSize));
  189. }
  190. void invalidate() noexcept
  191. {
  192. fJackClient = nullptr;
  193. fJackPort = nullptr;
  194. }
  195. private:
  196. jack_client_t* fJackClient;
  197. jack_port_t* fJackPort;
  198. JackPortDeletionCallback* const kDeletionCallback;
  199. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackCVPort)
  200. };
  201. // -----------------------------------------------------------------------
  202. // Carla Engine JACK-Event port
  203. class CarlaEngineJackEventPort : public CarlaEngineEventPort
  204. {
  205. public:
  206. CarlaEngineJackEventPort(const CarlaEngineClient& client, const bool isInputPort, jack_client_t* const jackClient, jack_port_t* const jackPort, JackPortDeletionCallback* const delCallback) noexcept
  207. : CarlaEngineEventPort(client, isInputPort),
  208. fJackClient(jackClient),
  209. fJackPort(jackPort),
  210. fJackBuffer(nullptr),
  211. fRetEvent(kFallbackJackEngineEvent),
  212. kDeletionCallback(delCallback),
  213. leakDetector_CarlaEngineJackEventPort()
  214. {
  215. carla_debug("CarlaEngineJackEventPort::CarlaEngineJackEventPort(%s, %p, %p)", bool2str(isInputPort), jackClient, jackPort);
  216. switch (kClient.getEngine().getProccessMode())
  217. {
  218. case ENGINE_PROCESS_MODE_SINGLE_CLIENT:
  219. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  220. CARLA_SAFE_ASSERT_RETURN(jackClient != nullptr && jackPort != nullptr,);
  221. break;
  222. default:
  223. CARLA_SAFE_ASSERT(jackClient == nullptr && jackPort == nullptr);
  224. break;
  225. }
  226. }
  227. ~CarlaEngineJackEventPort() noexcept override
  228. {
  229. carla_debug("CarlaEngineJackEventPort::~CarlaEngineJackEventPort()");
  230. if (fJackClient != nullptr && fJackPort != nullptr)
  231. {
  232. try {
  233. jackbridge_port_unregister(fJackClient, fJackPort);
  234. } CARLA_SAFE_EXCEPTION("Event port unregister");
  235. fJackClient = nullptr;
  236. fJackPort = nullptr;
  237. }
  238. if (kDeletionCallback != nullptr)
  239. kDeletionCallback->jackEventPortDeleted(this);
  240. }
  241. void initBuffer() noexcept override
  242. {
  243. if (fJackPort == nullptr)
  244. return CarlaEngineEventPort::initBuffer();
  245. try {
  246. fJackBuffer = jackbridge_port_get_buffer(fJackPort, kClient.getEngine().getBufferSize());
  247. }
  248. catch(...) {
  249. fJackBuffer = nullptr;
  250. return;
  251. }
  252. if (! kIsInput)
  253. jackbridge_midi_clear_buffer(fJackBuffer);
  254. }
  255. uint32_t getEventCount() const noexcept override
  256. {
  257. if (fJackPort == nullptr)
  258. return CarlaEngineEventPort::getEventCount();
  259. CARLA_SAFE_ASSERT_RETURN(kIsInput, 0);
  260. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, 0);
  261. try {
  262. return jackbridge_midi_get_event_count(fJackBuffer);
  263. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_get_event_count", 0);
  264. }
  265. const EngineEvent& getEvent(const uint32_t index) const noexcept override
  266. {
  267. if (fJackPort == nullptr)
  268. return CarlaEngineEventPort::getEvent(index);
  269. CARLA_SAFE_ASSERT_RETURN(kIsInput, kFallbackJackEngineEvent);
  270. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, kFallbackJackEngineEvent);
  271. return getEventUnchecked(index);
  272. }
  273. const EngineEvent& getEventUnchecked(const uint32_t index) const noexcept override
  274. {
  275. jack_midi_event_t jackEvent;
  276. bool test = false;
  277. try {
  278. test = jackbridge_midi_event_get(&jackEvent, fJackBuffer, index);
  279. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_get", kFallbackJackEngineEvent);
  280. if (! test)
  281. return kFallbackJackEngineEvent;
  282. CARLA_SAFE_ASSERT_RETURN(jackEvent.size < UINT8_MAX, kFallbackJackEngineEvent);
  283. fRetEvent.time = jackEvent.time;
  284. fRetEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer);
  285. return fRetEvent;
  286. }
  287. bool writeControlEvent(const uint32_t time, const uint8_t channel, const EngineControlEventType type, const uint16_t param, const float value) noexcept override
  288. {
  289. if (fJackPort == nullptr)
  290. return CarlaEngineEventPort::writeControlEvent(time, channel, type, param, value);
  291. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  292. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  293. CARLA_SAFE_ASSERT_RETURN(type != kEngineControlEventTypeNull, false);
  294. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  295. CARLA_SAFE_ASSERT_RETURN(param < MAX_MIDI_CONTROL, false);
  296. CARLA_SAFE_ASSERT(value >= 0.0f && value <= 1.0f);
  297. if (type == kEngineControlEventTypeParameter) {
  298. CARLA_SAFE_ASSERT(! MIDI_IS_CONTROL_BANK_SELECT(param));
  299. }
  300. uint8_t size = 0;
  301. uint8_t data[3] = { 0, 0, 0 };
  302. EngineControlEvent ctrlEvent = { type, param, value };
  303. ctrlEvent.convertToMidiData(channel, size, data);
  304. if (size == 0)
  305. return false;
  306. try {
  307. return jackbridge_midi_event_write(fJackBuffer, time, data, size);
  308. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  309. }
  310. bool writeMidiEvent(const uint32_t time, const uint8_t channel, const uint8_t port, const uint8_t size, const uint8_t* const data) noexcept override
  311. {
  312. if (fJackPort == nullptr)
  313. return CarlaEngineEventPort::writeMidiEvent(time, channel, port, size, data);
  314. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  315. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  316. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  317. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  318. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  319. jack_midi_data_t jdata[size];
  320. jdata[0] = static_cast<jack_midi_data_t>(MIDI_GET_STATUS_FROM_DATA(data) + channel);
  321. for (uint8_t i=1; i < size; ++i)
  322. jdata[i] = data[i];
  323. try {
  324. return jackbridge_midi_event_write(fJackBuffer, time, jdata, size);
  325. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  326. }
  327. void invalidate() noexcept
  328. {
  329. fJackClient = nullptr;
  330. fJackPort = nullptr;
  331. }
  332. private:
  333. jack_client_t* fJackClient;
  334. jack_port_t* fJackPort;
  335. void* fJackBuffer;
  336. mutable EngineEvent fRetEvent;
  337. JackPortDeletionCallback* const kDeletionCallback;
  338. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackEventPort)
  339. };
  340. // -----------------------------------------------------------------------
  341. // Jack Engine client
  342. class CarlaEngineJackClient : public CarlaEngineClient,
  343. JackPortDeletionCallback
  344. {
  345. public:
  346. CarlaEngineJackClient(const CarlaEngine& engine, jack_client_t* const jackClient)
  347. : CarlaEngineClient(engine),
  348. fJackClient(jackClient),
  349. fUseClient(engine.getProccessMode() == ENGINE_PROCESS_MODE_SINGLE_CLIENT || engine.getProccessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS),
  350. fAudioPorts(),
  351. fCVPorts(),
  352. fEventPorts(),
  353. leakDetector_CarlaEngineJackClient()
  354. {
  355. carla_debug("CarlaEngineJackClient::CarlaEngineJackClient(%p)", jackClient);
  356. if (fUseClient)
  357. {
  358. CARLA_SAFE_ASSERT(jackClient != nullptr);
  359. }
  360. else
  361. {
  362. CARLA_SAFE_ASSERT(jackClient == nullptr);
  363. }
  364. }
  365. ~CarlaEngineJackClient() noexcept override
  366. {
  367. carla_debug("CarlaEngineJackClient::~CarlaEngineJackClient()");
  368. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS && fJackClient != nullptr) // FIXME
  369. jackbridge_client_close(fJackClient);
  370. // ports must have been deleted by now!
  371. //fAudioPorts.clear();
  372. //fCVPorts.clear();
  373. //fEventPorts.clear();
  374. }
  375. void activate() noexcept override
  376. {
  377. carla_debug("CarlaEngineJackClient::activate()");
  378. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  379. {
  380. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && ! isActive(),);
  381. try {
  382. jackbridge_activate(fJackClient);
  383. } catch(...) {}
  384. }
  385. CarlaEngineClient::activate();
  386. }
  387. void deactivate() noexcept override
  388. {
  389. carla_debug("CarlaEngineJackClient::deactivate()");
  390. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  391. {
  392. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && isActive(),);
  393. try {
  394. jackbridge_deactivate(fJackClient);
  395. } catch(...) {}
  396. }
  397. CarlaEngineClient::deactivate();
  398. }
  399. bool isOk() const noexcept override
  400. {
  401. if (fUseClient)
  402. return (fJackClient != nullptr);
  403. return CarlaEngineClient::isOk();
  404. }
  405. CarlaEnginePort* addPort(const EnginePortType portType, const char* const name, const bool isInput) override
  406. {
  407. carla_debug("CarlaEngineJackClient::addPort(%i:%s, \"%s\", %s)", portType, EnginePortType2Str(portType), name, bool2str(isInput));
  408. jack_port_t* jackPort = nullptr;
  409. // Create JACK port first, if needed
  410. if (fUseClient && fJackClient != nullptr)
  411. {
  412. switch (portType)
  413. {
  414. case kEnginePortTypeNull:
  415. break;
  416. case kEnginePortTypeAudio:
  417. jackPort = jackbridge_port_register(fJackClient, name, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  418. break;
  419. case kEnginePortTypeCV:
  420. jackPort = jackbridge_port_register(fJackClient, name, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  421. break;
  422. case kEnginePortTypeEvent:
  423. jackPort = jackbridge_port_register(fJackClient, name, JACK_DEFAULT_MIDI_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  424. break;
  425. }
  426. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr, nullptr);
  427. }
  428. _addName(isInput, name);
  429. // Create Engine port
  430. switch (portType)
  431. {
  432. case kEnginePortTypeNull:
  433. break;
  434. case kEnginePortTypeAudio: {
  435. CarlaEngineJackAudioPort* const enginePort(new CarlaEngineJackAudioPort(*this, isInput, fJackClient, jackPort, this));
  436. fAudioPorts.append(enginePort);
  437. return enginePort;
  438. }
  439. case kEnginePortTypeCV: {
  440. CarlaEngineJackCVPort* const enginePort(new CarlaEngineJackCVPort(*this, isInput, fJackClient, jackPort, this));
  441. fCVPorts.append(enginePort);
  442. return enginePort;
  443. }
  444. case kEnginePortTypeEvent: {
  445. CarlaEngineJackEventPort* const enginePort(new CarlaEngineJackEventPort(*this, isInput, fJackClient, jackPort, this));
  446. fEventPorts.append(enginePort);
  447. return enginePort;
  448. }
  449. }
  450. carla_stderr("CarlaEngineJackClient::addPort(%i, \"%s\", %s) - invalid type", portType, name, bool2str(isInput));
  451. return nullptr;
  452. }
  453. void invalidate() noexcept
  454. {
  455. for (LinkedList<CarlaEngineJackAudioPort*>::Itenerator it = fAudioPorts.begin(); it.valid(); it.next())
  456. {
  457. CarlaEngineJackAudioPort* const port(it.getValue());
  458. port->invalidate();
  459. }
  460. for (LinkedList<CarlaEngineJackCVPort*>::Itenerator it = fCVPorts.begin(); it.valid(); it.next())
  461. {
  462. CarlaEngineJackCVPort* const port(it.getValue());
  463. port->invalidate();
  464. }
  465. for (LinkedList<CarlaEngineJackEventPort*>::Itenerator it = fEventPorts.begin(); it.valid(); it.next())
  466. {
  467. CarlaEngineJackEventPort* const port(it.getValue());
  468. port->invalidate();
  469. }
  470. fJackClient = nullptr;
  471. CarlaEngineClient::deactivate();
  472. }
  473. const char* getJackClientName() const noexcept
  474. {
  475. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  476. try {
  477. return jackbridge_get_client_name(fJackClient);
  478. } CARLA_SAFE_EXCEPTION_RETURN("jack_get_client_name", nullptr);
  479. }
  480. void jackAudioPortDeleted(CarlaEngineJackAudioPort* const port) noexcept override
  481. {
  482. fAudioPorts.removeAll(port);
  483. }
  484. void jackCVPortDeleted(CarlaEngineJackCVPort* const port) noexcept override
  485. {
  486. fCVPorts.removeAll(port);
  487. }
  488. void jackEventPortDeleted(CarlaEngineJackEventPort* const port) noexcept override
  489. {
  490. fEventPorts.removeAll(port);
  491. }
  492. private:
  493. jack_client_t* fJackClient;
  494. const bool fUseClient;
  495. LinkedList<CarlaEngineJackAudioPort*> fAudioPorts;
  496. LinkedList<CarlaEngineJackCVPort*> fCVPorts;
  497. LinkedList<CarlaEngineJackEventPort*> fEventPorts;
  498. friend class CarlaEngineJack;
  499. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackClient)
  500. };
  501. // -----------------------------------------------------------------------
  502. // Jack Engine
  503. class CarlaEngineJack : public CarlaEngine
  504. {
  505. public:
  506. CarlaEngineJack()
  507. : CarlaEngine(),
  508. fClient(nullptr),
  509. fTransportPos(),
  510. fTransportState(JackTransportStopped),
  511. fExternalPatchbay(true),
  512. fFreewheel(false),
  513. #ifdef BUILD_BRIDGE
  514. fIsRunning(false),
  515. #else
  516. fUsedGroups(),
  517. fUsedPorts(),
  518. fUsedConnections(),
  519. fNewGroups(),
  520. fRetConns(),
  521. #endif
  522. leakDetector_CarlaEngineJack()
  523. {
  524. carla_debug("CarlaEngineJack::CarlaEngineJack()");
  525. #ifdef BUILD_BRIDGE
  526. pData->options.processMode = ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  527. #else
  528. carla_fill<jack_port_t*>(fRackPorts, nullptr, kRackPortCount);
  529. #endif
  530. // FIXME: Always enable JACK transport for now
  531. pData->options.transportMode = ENGINE_TRANSPORT_MODE_JACK;
  532. carla_zeroStruct<jack_position_t>(fTransportPos);
  533. }
  534. ~CarlaEngineJack() noexcept override
  535. {
  536. carla_debug("CarlaEngineJack::~CarlaEngineJack()");
  537. CARLA_SAFE_ASSERT(fClient == nullptr);
  538. #ifndef BUILD_BRIDGE
  539. fUsedGroups.clear();
  540. fUsedPorts.clear();
  541. fUsedConnections.clear();
  542. fNewGroups.clear();
  543. #endif
  544. }
  545. // -------------------------------------------------------------------
  546. // Maximum values
  547. uint getMaxClientNameSize() const noexcept override
  548. {
  549. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  550. {
  551. try {
  552. return static_cast<uint>(jackbridge_client_name_size());
  553. } CARLA_SAFE_EXCEPTION_RETURN("jack_client_name_size", 0);
  554. }
  555. return CarlaEngine::getMaxClientNameSize();
  556. }
  557. uint getMaxPortNameSize() const noexcept override
  558. {
  559. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT || pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  560. {
  561. try {
  562. return static_cast<uint>(jackbridge_port_name_size());
  563. } CARLA_SAFE_EXCEPTION_RETURN("jack_port_name_size", 0);
  564. }
  565. return CarlaEngine::getMaxPortNameSize();
  566. }
  567. // -------------------------------------------------------------------
  568. // Virtual, per-engine type calls
  569. bool init(const char* const clientName) override
  570. {
  571. CARLA_SAFE_ASSERT_RETURN(fClient == nullptr, false);
  572. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr && clientName[0] != '\0', false);
  573. CARLA_SAFE_ASSERT_RETURN(jackbridge_is_ok(), false);
  574. carla_debug("CarlaEngineJack::init(\"%s\")", clientName);
  575. fFreewheel = false;
  576. fTransportState = JackTransportStopped;
  577. fExternalPatchbay = true;
  578. carla_zeroStruct<jack_position_t>(fTransportPos);
  579. #ifdef BUILD_BRIDGE
  580. fIsRunning = true;
  581. if (! pData->init(clientName))
  582. {
  583. close();
  584. setLastError("Failed to init internal data");
  585. return false;
  586. }
  587. if (pData->bufferSize == 0 || carla_compareFloats(pData->sampleRate, 0.0))
  588. {
  589. // open temp client to get initial buffer-size and sample-rate values
  590. if (jack_client_t* const tmpClient = jackbridge_client_open(clientName, JackNoStartServer, nullptr))
  591. {
  592. pData->bufferSize = jackbridge_get_buffer_size(tmpClient);
  593. pData->sampleRate = jackbridge_get_sample_rate(tmpClient);
  594. jackbridge_client_close(tmpClient);
  595. }
  596. else
  597. {
  598. close();
  599. setLastError("Failed to init temporary jack client");
  600. return false;
  601. }
  602. }
  603. return true;
  604. #else
  605. fClient = jackbridge_client_open(clientName, JackNullOption, nullptr);
  606. if (fClient == nullptr)
  607. {
  608. setLastError("Failed to create new JACK client");
  609. return false;
  610. }
  611. const char* const jackClientName(jackbridge_get_client_name(fClient));
  612. if (! pData->init(jackClientName))
  613. {
  614. jackbridge_client_close(fClient);
  615. fClient = nullptr;
  616. setLastError("Failed to init internal data");
  617. return false;
  618. }
  619. pData->bufferSize = jackbridge_get_buffer_size(fClient);
  620. pData->sampleRate = jackbridge_get_sample_rate(fClient);
  621. jackbridge_set_thread_init_callback(fClient, carla_jack_thread_init_callback, nullptr);
  622. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback, this);
  623. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback, this);
  624. jackbridge_set_freewheel_callback(fClient, carla_jack_freewheel_callback, this);
  625. jackbridge_set_latency_callback(fClient, carla_jack_latency_callback, this);
  626. jackbridge_set_process_callback(fClient, carla_jack_process_callback, this);
  627. jackbridge_on_shutdown(fClient, carla_jack_shutdown_callback, this);
  628. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  629. initJackPatchbay(jackClientName);
  630. jackbridge_set_client_registration_callback(fClient, carla_jack_client_registration_callback, this);
  631. jackbridge_set_port_registration_callback(fClient, carla_jack_port_registration_callback, this);
  632. jackbridge_set_port_connect_callback(fClient, carla_jack_port_connect_callback, this);
  633. jackbridge_set_port_rename_callback(fClient, carla_jack_port_rename_callback, this);
  634. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  635. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  636. {
  637. fRackPorts[kRackPortAudioIn1] = jackbridge_port_register(fClient, "audio-in1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  638. fRackPorts[kRackPortAudioIn2] = jackbridge_port_register(fClient, "audio-in2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  639. fRackPorts[kRackPortAudioOut1] = jackbridge_port_register(fClient, "audio-out1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  640. fRackPorts[kRackPortAudioOut2] = jackbridge_port_register(fClient, "audio-out2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  641. fRackPorts[kRackPortEventIn] = jackbridge_port_register(fClient, "events-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
  642. fRackPorts[kRackPortEventOut] = jackbridge_port_register(fClient, "events-out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
  643. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  644. {
  645. pData->graph.create(true, pData->sampleRate, pData->bufferSize, 0, 0);
  646. }
  647. else
  648. {
  649. pData->graph.create(false, pData->sampleRate, pData->bufferSize, 2, 2);
  650. patchbayRefresh(false);
  651. }
  652. }
  653. if (jackbridge_activate(fClient))
  654. {
  655. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0, pData->options.processMode, pData->options.transportMode, 0.0f, getCurrentDriverName());
  656. return true;
  657. }
  658. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  659. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  660. {
  661. pData->graph.destroy();
  662. }
  663. pData->close();
  664. jackbridge_client_close(fClient);
  665. fClient = nullptr;
  666. setLastError("Failed to activate the JACK client");
  667. return false;
  668. #endif
  669. }
  670. bool close() override
  671. {
  672. carla_debug("CarlaEngineJack::close()");
  673. #ifdef BUILD_BRIDGE
  674. fClient = nullptr;
  675. fIsRunning = false;
  676. CarlaEngine::close();
  677. return true;
  678. #else
  679. CARLA_SAFE_ASSERT_RETURN_ERR(fClient != nullptr, "JACK Client is null");
  680. // deactivate first
  681. const bool deactivated(jackbridge_deactivate(fClient));
  682. // clear engine data
  683. CarlaEngine::close();
  684. fUsedGroups.clear();
  685. fUsedPorts.clear();
  686. fUsedConnections.clear();
  687. fNewGroups.clear();
  688. // clear rack/patchbay stuff
  689. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  690. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  691. {
  692. if (deactivated)
  693. {
  694. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioIn1]);
  695. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioIn2]);
  696. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioOut1]);
  697. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioOut2]);
  698. jackbridge_port_unregister(fClient, fRackPorts[kRackPortEventIn]);
  699. jackbridge_port_unregister(fClient, fRackPorts[kRackPortEventOut]);
  700. }
  701. carla_fill<jack_port_t*>(fRackPorts, nullptr, kRackPortCount);
  702. pData->graph.destroy();
  703. }
  704. // close client
  705. if (deactivated)
  706. jackbridge_client_close(fClient);
  707. fClient = nullptr;
  708. return true;
  709. #endif
  710. }
  711. #ifndef BUILD_BRIDGE
  712. void idle() noexcept override
  713. {
  714. CarlaEngine::idle();
  715. if (fNewGroups.count() == 0)
  716. return;
  717. LinkedList<uint> newPlugins;
  718. fNewGroups.spliceInsertInto(newPlugins);
  719. for (LinkedList<uint>::Itenerator it = newPlugins.begin(); it.valid(); it.next())
  720. {
  721. const uint groupId(it.getValue());
  722. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  723. const char* const groupName(fUsedGroups.getGroupName(groupId));
  724. CARLA_SAFE_ASSERT_CONTINUE(groupName != nullptr && groupName[0] != '\0');
  725. int pluginId = -1;
  726. PatchbayIcon icon = PATCHBAY_ICON_PLUGIN;
  727. if (findPluginIdAndIcon(groupName, pluginId, icon))
  728. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED, groupId, icon, pluginId, 0.0f, nullptr);
  729. }
  730. newPlugins.clear();
  731. }
  732. #endif
  733. bool isRunning() const noexcept override
  734. {
  735. #ifdef BUILD_BRIDGE
  736. return (fClient != nullptr || fIsRunning);
  737. #else
  738. return (fClient != nullptr);
  739. #endif
  740. }
  741. bool isOffline() const noexcept override
  742. {
  743. return fFreewheel;
  744. }
  745. EngineType getType() const noexcept override
  746. {
  747. return kEngineTypeJack;
  748. }
  749. const char* getCurrentDriverName() const noexcept override
  750. {
  751. return "JACK";
  752. }
  753. CarlaEngineClient* addClient(CarlaPlugin* const plugin) override
  754. {
  755. jack_client_t* client = nullptr;
  756. #ifndef BUILD_BRIDGE
  757. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  758. {
  759. client = fClient;
  760. }
  761. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  762. #endif
  763. {
  764. client = jackbridge_client_open(plugin->getName(), JackNullOption, nullptr);
  765. CARLA_SAFE_ASSERT_RETURN(client != nullptr, nullptr);
  766. jackbridge_set_thread_init_callback(client, carla_jack_thread_init_callback, nullptr);
  767. #ifndef BUILD_BRIDGE
  768. jackbridge_set_latency_callback(client, carla_jack_latency_callback_plugin, plugin);
  769. jackbridge_set_process_callback(client, carla_jack_process_callback_plugin, plugin);
  770. jackbridge_on_shutdown(client, carla_jack_shutdown_callback_plugin, plugin);
  771. #else
  772. fClient = client;
  773. pData->bufferSize = jackbridge_get_buffer_size(client);
  774. pData->sampleRate = jackbridge_get_sample_rate(client);
  775. jackbridge_set_buffer_size_callback(client, carla_jack_bufsize_callback, this);
  776. jackbridge_set_sample_rate_callback(client, carla_jack_srate_callback, this);
  777. jackbridge_set_freewheel_callback(client, carla_jack_freewheel_callback, this);
  778. jackbridge_set_latency_callback(client, carla_jack_latency_callback, this);
  779. jackbridge_set_process_callback(client, carla_jack_process_callback, this);
  780. jackbridge_on_shutdown(client, carla_jack_shutdown_callback, this);
  781. #endif
  782. }
  783. return new CarlaEngineJackClient(*this, client);
  784. }
  785. #ifndef BUILD_BRIDGE
  786. const char* renamePlugin(const uint id, const char* const newName) override
  787. {
  788. CARLA_SAFE_ASSERT_RETURN(pData->curPluginCount > 0, nullptr);
  789. CARLA_SAFE_ASSERT_RETURN(id < pData->curPluginCount, nullptr);
  790. CARLA_SAFE_ASSERT_RETURN(pData->plugins != nullptr, nullptr);
  791. CARLA_SAFE_ASSERT_RETURN(newName != nullptr && newName[0] != '\0', nullptr);
  792. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  793. if (plugin == nullptr)
  794. {
  795. carla_stderr("CarlaEngine::clonePlugin(%i) - could not find plugin", id);
  796. return nullptr;
  797. }
  798. CARLA_SAFE_ASSERT(plugin->getId() == id);
  799. CarlaString uniqueName;
  800. try {
  801. const char* const tmpName = getUniquePluginName(newName);
  802. uniqueName = tmpName;
  803. delete[] tmpName;
  804. } CARLA_SAFE_EXCEPTION("JACK renamePlugin");
  805. if (uniqueName.isEmpty())
  806. {
  807. setLastError("Failed to request new unique plugin name");
  808. return nullptr;
  809. }
  810. // single client always re-inits
  811. bool needsReinit = (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT);
  812. // rename in multiple client mode
  813. if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  814. {
  815. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  816. #if 0
  817. if (bridge.client_rename_ptr != nullptr)
  818. {
  819. newName = jackbridge_client_rename(client->fClient, newName);
  820. }
  821. else
  822. #endif
  823. {
  824. // we should not be able to do this, jack really needs to allow client rename
  825. if (jack_client_t* const jackClient = jackbridge_client_open(uniqueName, JackNullOption, nullptr))
  826. {
  827. // close old client
  828. plugin->setEnabled(false);
  829. if (client->isActive())
  830. client->deactivate();
  831. plugin->clearBuffers();
  832. jackbridge_client_close(client->fJackClient);
  833. // set new client data
  834. uniqueName = jackbridge_get_client_name(jackClient);
  835. jackbridge_set_thread_init_callback(jackClient, carla_jack_thread_init_callback, nullptr);
  836. jackbridge_set_process_callback(jackClient, carla_jack_process_callback_plugin, plugin);
  837. jackbridge_set_latency_callback(jackClient, carla_jack_latency_callback_plugin, plugin);
  838. jackbridge_on_shutdown(jackClient, carla_jack_shutdown_callback_plugin, plugin);
  839. client->fJackClient = jackClient;
  840. needsReinit = true;
  841. }
  842. else
  843. {
  844. setLastError("Failed to create new JACK client");
  845. return nullptr;
  846. }
  847. }
  848. }
  849. // Rename
  850. plugin->setName(uniqueName);
  851. if (needsReinit)
  852. {
  853. // reload plugin to recreate its ports
  854. const StateSave& saveState(plugin->getStateSave());
  855. plugin->reload();
  856. plugin->loadStateSave(saveState);
  857. }
  858. return plugin->getName();
  859. }
  860. // -------------------------------------------------------------------
  861. // Patchbay
  862. bool patchbayConnect(const uint groupA, const uint portA, const uint groupB, const uint portB) override
  863. {
  864. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  865. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! fExternalPatchbay)
  866. return CarlaEngine::patchbayConnect(groupA, portA, groupB, portB);
  867. const char* const fullPortNameA = fUsedPorts.getFullPortName(groupA, portA);
  868. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  869. const char* const fullPortNameB = fUsedPorts.getFullPortName(groupB, portB);
  870. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  871. carla_stdout("patchbayConnect(%u, %u, %u, %u => %s, %s)", groupA, portA, groupB, portB, fullPortNameA, fullPortNameB);
  872. if (! jackbridge_connect(fClient, fullPortNameA, fullPortNameB))
  873. {
  874. setLastError("JACK operation failed");
  875. return false;
  876. }
  877. return true;
  878. }
  879. bool patchbayDisconnect(const uint connectionId) override
  880. {
  881. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  882. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! fExternalPatchbay)
  883. return CarlaEngine::patchbayDisconnect(connectionId);
  884. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin(); it.valid(); it.next())
  885. {
  886. const ConnectionToId& connectionToId(it.getValue());
  887. if (connectionToId.id == connectionId)
  888. {
  889. const char* const fullPortNameA = fUsedPorts.getFullPortName(connectionToId.groupA, connectionToId.portA);
  890. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  891. const char* const fullPortNameB = fUsedPorts.getFullPortName(connectionToId.groupB, connectionToId.portB);
  892. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  893. if (! jackbridge_disconnect(fClient, fullPortNameA, fullPortNameB))
  894. {
  895. setLastError("JACK operation failed");
  896. return false;
  897. }
  898. return true;
  899. }
  900. }
  901. setLastError("Failed to find the requested connection");
  902. return false;
  903. }
  904. bool patchbayRefresh(const bool external) override
  905. {
  906. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  907. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  908. {
  909. fExternalPatchbay = external;
  910. pData->graph.setIgnorePatchbay(external);
  911. if (! external)
  912. return CarlaEngine::patchbayRefresh(false);
  913. }
  914. fUsedGroups.clear();
  915. fUsedPorts.clear();
  916. fUsedConnections.clear();
  917. fNewGroups.clear();
  918. initJackPatchbay(jackbridge_get_client_name(fClient));
  919. return true;
  920. }
  921. // -------------------------------------------------------------------
  922. // Transport
  923. void transportPlay() noexcept override
  924. {
  925. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  926. return CarlaEngine::transportPlay();
  927. if (fClient != nullptr)
  928. {
  929. try {
  930. jackbridge_transport_start(fClient);
  931. } catch(...) {}
  932. }
  933. }
  934. void transportPause() noexcept override
  935. {
  936. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  937. return CarlaEngine::transportPause();
  938. if (fClient != nullptr)
  939. {
  940. try {
  941. jackbridge_transport_stop(fClient);
  942. } catch(...) {}
  943. }
  944. }
  945. void transportRelocate(const uint64_t frame) noexcept override
  946. {
  947. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  948. return CarlaEngine::transportRelocate(frame);
  949. if (fClient != nullptr)
  950. {
  951. try {
  952. jackbridge_transport_locate(fClient, static_cast<jack_nframes_t>(frame));
  953. } catch(...) {}
  954. }
  955. }
  956. // -------------------------------------------------------------------
  957. // Patchbay stuff
  958. const char* const* getPatchbayConnections() const override
  959. {
  960. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, nullptr);
  961. carla_debug("CarlaEngineJack::getPatchbayConnections()");
  962. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  963. return CarlaEngine::getPatchbayConnections();
  964. CarlaStringList connList;
  965. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  966. {
  967. for (int i=0; ports[i] != nullptr; ++i)
  968. {
  969. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, ports[i]));
  970. const char* const fullPortName(ports[i]);
  971. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  972. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  973. {
  974. for (int j=0; connections[j] != nullptr; ++j)
  975. {
  976. connList.append(fullPortName);
  977. connList.append(connections[j]);
  978. }
  979. jackbridge_free(connections);
  980. }
  981. }
  982. jackbridge_free(ports);
  983. }
  984. if (connList.count() == 0)
  985. return nullptr;
  986. fRetConns = connList.toCharStringListPtr();
  987. return fRetConns;
  988. }
  989. void restorePatchbayConnection(const char* const connSource, const char* const connTarget) override
  990. {
  991. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr,);
  992. CARLA_SAFE_ASSERT_RETURN(connSource != nullptr && connSource[0] != '\0',);
  993. CARLA_SAFE_ASSERT_RETURN(connTarget != nullptr && connTarget[0] != '\0',);
  994. carla_debug("CarlaEngineJack::restorePatchbayConnection(\"%s\", \"%s\")", connSource, connTarget);
  995. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  996. return CarlaEngine::restorePatchbayConnection(connSource, connTarget);
  997. if (const jack_port_t* const port = jackbridge_port_by_name(fClient, connSource))
  998. {
  999. if (jackbridge_port_by_name(fClient, connTarget) == nullptr)
  1000. return;
  1001. if (! jackbridge_port_connected_to(port, connTarget))
  1002. jackbridge_connect(fClient, connSource, connTarget);
  1003. }
  1004. }
  1005. #endif
  1006. // -------------------------------------------------------------------
  1007. protected:
  1008. void handleJackBufferSizeCallback(const uint32_t newBufferSize)
  1009. {
  1010. if (pData->bufferSize == newBufferSize)
  1011. return;
  1012. pData->bufferSize = newBufferSize;
  1013. bufferSizeChanged(newBufferSize);
  1014. }
  1015. void handleJackSampleRateCallback(const double newSampleRate)
  1016. {
  1017. if (carla_compareFloats(pData->sampleRate, newSampleRate))
  1018. return;
  1019. pData->sampleRate = newSampleRate;
  1020. sampleRateChanged(newSampleRate);
  1021. }
  1022. void handleJackFreewheelCallback(const bool isFreewheel)
  1023. {
  1024. if (fFreewheel == isFreewheel)
  1025. return;
  1026. fFreewheel = isFreewheel;
  1027. offlineModeChanged(isFreewheel);
  1028. }
  1029. void saveTransportInfo()
  1030. {
  1031. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1032. return;
  1033. fTransportPos.unique_1 = fTransportPos.unique_2 + 1; // invalidate
  1034. fTransportState = jackbridge_transport_query(fClient, &fTransportPos);
  1035. pData->timeInfo.playing = (fTransportState == JackTransportRolling);
  1036. if (fTransportPos.unique_1 == fTransportPos.unique_2)
  1037. {
  1038. pData->timeInfo.frame = fTransportPos.frame;
  1039. pData->timeInfo.usecs = fTransportPos.usecs;
  1040. if (fTransportPos.valid & JackPositionBBT)
  1041. {
  1042. pData->timeInfo.valid = EngineTimeInfo::kValidBBT;
  1043. pData->timeInfo.bbt.bar = fTransportPos.bar;
  1044. pData->timeInfo.bbt.beat = fTransportPos.beat;
  1045. pData->timeInfo.bbt.tick = fTransportPos.tick;
  1046. pData->timeInfo.bbt.barStartTick = fTransportPos.bar_start_tick;
  1047. pData->timeInfo.bbt.beatsPerBar = fTransportPos.beats_per_bar;
  1048. pData->timeInfo.bbt.beatType = fTransportPos.beat_type;
  1049. pData->timeInfo.bbt.ticksPerBeat = fTransportPos.ticks_per_beat;
  1050. pData->timeInfo.bbt.beatsPerMinute = fTransportPos.beats_per_minute;
  1051. }
  1052. else
  1053. pData->timeInfo.valid = 0x0;
  1054. }
  1055. else
  1056. {
  1057. pData->timeInfo.frame = 0;
  1058. pData->timeInfo.valid = 0x0;
  1059. }
  1060. }
  1061. void handleJackProcessCallback(const uint32_t nframes)
  1062. {
  1063. const PendingRtEventsRunner prt(this);
  1064. saveTransportInfo();
  1065. #ifdef BUILD_BRIDGE
  1066. CarlaPlugin* const plugin(pData->plugins[0].plugin);
  1067. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1068. {
  1069. plugin->initBuffers();
  1070. processPlugin(plugin, nframes);
  1071. plugin->unlock();
  1072. }
  1073. #else
  1074. if (pData->curPluginCount == 0 && pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1075. {
  1076. // pass-through
  1077. // TODO MIDI as well
  1078. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1079. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1080. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1081. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1082. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes);
  1083. FloatVectorOperations::copy(audioOut1, audioIn1, static_cast<int>(nframes));
  1084. FloatVectorOperations::copy(audioOut2, audioIn2, static_cast<int>(nframes));
  1085. jackbridge_midi_clear_buffer(eventOut);
  1086. return;
  1087. }
  1088. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1089. {
  1090. for (uint i=0; i < pData->curPluginCount; ++i)
  1091. {
  1092. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1093. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1094. {
  1095. plugin->initBuffers();
  1096. processPlugin(plugin, nframes);
  1097. plugin->unlock();
  1098. }
  1099. }
  1100. }
  1101. else if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1102. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1103. {
  1104. CARLA_SAFE_ASSERT_RETURN(pData->events.in != nullptr,);
  1105. CARLA_SAFE_ASSERT_RETURN(pData->events.out != nullptr,);
  1106. // get buffers from jack
  1107. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1108. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1109. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1110. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1111. void* const eventIn = jackbridge_port_get_buffer(fRackPorts[kRackPortEventIn], nframes);
  1112. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes);
  1113. #if 1
  1114. // assert buffers
  1115. CARLA_SAFE_ASSERT(audioIn1 != nullptr);
  1116. CARLA_SAFE_ASSERT(audioIn2 != nullptr);
  1117. CARLA_SAFE_ASSERT(audioOut1 != nullptr);
  1118. CARLA_SAFE_ASSERT(audioOut2 != nullptr);
  1119. CARLA_SAFE_ASSERT(eventIn != nullptr);
  1120. CARLA_SAFE_ASSERT(eventOut != nullptr);
  1121. #endif
  1122. // create audio buffers
  1123. const float* inBuf[2] = { audioIn1, audioIn2 };
  1124. /**/ float* outBuf[2] = { audioOut1, audioOut2 };
  1125. // initialize events
  1126. carla_zeroStruct<EngineEvent>(pData->events.in, kMaxEngineEventInternalCount);
  1127. carla_zeroStruct<EngineEvent>(pData->events.out, kMaxEngineEventInternalCount);
  1128. {
  1129. ushort engineEventIndex = 0;
  1130. jack_midi_event_t jackEvent;
  1131. const uint32_t jackEventCount(jackbridge_midi_get_event_count(eventIn));
  1132. for (uint32_t jackEventIndex=0; jackEventIndex < jackEventCount; ++jackEventIndex)
  1133. {
  1134. if (! jackbridge_midi_event_get(&jackEvent, eventIn, jackEventIndex))
  1135. continue;
  1136. CARLA_SAFE_ASSERT_CONTINUE(jackEvent.size <= 0xFF /* uint8_t max */);
  1137. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  1138. engineEvent.time = jackEvent.time;
  1139. engineEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer);
  1140. if (engineEventIndex >= kMaxEngineEventInternalCount)
  1141. break;
  1142. }
  1143. }
  1144. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1145. pData->graph.processRack(pData, inBuf, outBuf, nframes);
  1146. else
  1147. pData->graph.process(pData, inBuf, outBuf, nframes);
  1148. // output control
  1149. {
  1150. jackbridge_midi_clear_buffer(eventOut);
  1151. uint8_t size = 0;
  1152. uint8_t data[3] = { 0, 0, 0 };
  1153. const uint8_t* dataPtr = data;
  1154. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  1155. {
  1156. const EngineEvent& engineEvent(pData->events.out[i]);
  1157. if (engineEvent.type == kEngineEventTypeNull)
  1158. break;
  1159. else if (engineEvent.type == kEngineEventTypeControl)
  1160. {
  1161. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  1162. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  1163. dataPtr = data;
  1164. }
  1165. else if (engineEvent.type == kEngineEventTypeMidi)
  1166. {
  1167. const EngineMidiEvent& midiEvent(engineEvent.midi);
  1168. size = midiEvent.size;
  1169. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  1170. dataPtr = midiEvent.dataExt;
  1171. else
  1172. dataPtr = midiEvent.data;
  1173. }
  1174. else
  1175. {
  1176. continue;
  1177. }
  1178. if (size > 0)
  1179. jackbridge_midi_event_write(eventOut, engineEvent.time, dataPtr, size);
  1180. }
  1181. }
  1182. }
  1183. #endif // ! BUILD_BRIDGE
  1184. }
  1185. void handleJackLatencyCallback(const jack_latency_callback_mode_t /*mode*/)
  1186. {
  1187. // TODO
  1188. }
  1189. #ifndef BUILD_BRIDGE
  1190. void handleJackClientRegistrationCallback(const char* const name, const bool reg)
  1191. {
  1192. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  1193. // ignore this if on internal patchbay mode
  1194. if (! fExternalPatchbay) return;
  1195. // do nothing on client registration, wait for first port
  1196. if (reg) return;
  1197. const uint groupId(fUsedGroups.getGroupId(name));
  1198. // clients might have been registered without ports
  1199. if (groupId == 0) return;
  1200. GroupNameToId groupNameToId;
  1201. groupNameToId.setData(groupId, name);
  1202. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED, groupNameToId.group, 0, 0, 0.0f, nullptr);
  1203. fUsedGroups.list.removeOne(groupNameToId);
  1204. }
  1205. void handleJackPortRegistrationCallback(const jack_port_id_t port, const bool reg)
  1206. {
  1207. // ignore this if on internal patchbay mode
  1208. if (! fExternalPatchbay) return;
  1209. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1210. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1211. const char* const fullPortName(jackbridge_port_name(jackPort));
  1212. CARLA_SAFE_ASSERT_RETURN(fullPortName != nullptr && fullPortName[0] != '\0',);
  1213. if (reg)
  1214. {
  1215. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1216. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1217. bool found;
  1218. CarlaString groupName(fullPortName);
  1219. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1220. CARLA_SAFE_ASSERT_RETURN(found,);
  1221. const int jackPortFlags(jackbridge_port_flags(jackPort));
  1222. uint groupId(fUsedGroups.getGroupId(groupName));
  1223. if (groupId == 0)
  1224. {
  1225. groupId = ++fUsedGroups.lastId;
  1226. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  1227. GroupNameToId groupNameToId;
  1228. groupNameToId.setData(groupId, groupName);
  1229. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, icon, -1, 0.0f, groupNameToId.name);
  1230. fNewGroups.append(groupId);
  1231. fUsedGroups.list.append(groupNameToId);
  1232. }
  1233. addPatchbayJackPort(groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  1234. }
  1235. else
  1236. {
  1237. const PortNameToId& portNameToId(fUsedPorts.getPortNameToId(fullPortName));
  1238. CARLA_SAFE_ASSERT_RETURN(portNameToId.group > 0 && portNameToId.port > 0,);
  1239. callback(ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, nullptr);
  1240. fUsedPorts.list.removeOne(portNameToId);
  1241. }
  1242. }
  1243. void handleJackPortConnectCallback(const jack_port_id_t a, const jack_port_id_t b, const bool connect)
  1244. {
  1245. // ignore this if on internal patchbay mode
  1246. if (! fExternalPatchbay) return;
  1247. const jack_port_t* const jackPortA(jackbridge_port_by_id(fClient, a));
  1248. CARLA_SAFE_ASSERT_RETURN(jackPortA != nullptr,);
  1249. const jack_port_t* const jackPortB(jackbridge_port_by_id(fClient, b));
  1250. CARLA_SAFE_ASSERT_RETURN(jackPortB != nullptr,);
  1251. const char* const fullPortNameA(jackbridge_port_name(jackPortA));
  1252. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0',);
  1253. const char* const fullPortNameB(jackbridge_port_name(jackPortB));
  1254. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0',);
  1255. const PortNameToId& portNameToIdA(fUsedPorts.getPortNameToId(fullPortNameA));
  1256. CARLA_SAFE_ASSERT_RETURN(portNameToIdA.group > 0 && portNameToIdA.port > 0,);
  1257. const PortNameToId& portNameToIdB(fUsedPorts.getPortNameToId(fullPortNameB));
  1258. CARLA_SAFE_ASSERT_RETURN(portNameToIdB.group > 0 && portNameToIdB.port > 0,);
  1259. if (connect)
  1260. {
  1261. char strBuf[STR_MAX+1];
  1262. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1263. strBuf[STR_MAX] = '\0';
  1264. ConnectionToId connectionToId;
  1265. connectionToId.setData(++fUsedConnections.lastId, portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1266. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  1267. fUsedConnections.list.append(connectionToId);
  1268. }
  1269. else
  1270. {
  1271. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin(); it.valid(); it.next())
  1272. {
  1273. const ConnectionToId& connectionToId(it.getValue());
  1274. if (connectionToId.groupA == portNameToIdA.group && connectionToId.portA == portNameToIdA.port &&
  1275. connectionToId.groupB == portNameToIdB.group && connectionToId.portB == portNameToIdB.port)
  1276. {
  1277. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED, connectionToId.id, 0, 0, 0.0f, nullptr);
  1278. fUsedConnections.list.remove(it);
  1279. break;
  1280. }
  1281. }
  1282. }
  1283. }
  1284. void handleJackClientRenameCallback(const char* const oldName, const char* const newName)
  1285. {
  1286. CARLA_SAFE_ASSERT_RETURN(oldName != nullptr && oldName[0] != '\0',);
  1287. CARLA_SAFE_ASSERT_RETURN(newName != nullptr && newName[0] != '\0',);
  1288. // ignore this if on internal patchbay mode
  1289. if (! fExternalPatchbay) return;
  1290. for (LinkedList<GroupNameToId>::Itenerator it = fUsedGroups.list.begin(); it.valid(); it.next())
  1291. {
  1292. GroupNameToId& groupNameToId(it.getValue());
  1293. if (std::strcmp(groupNameToId.name, oldName) == 0)
  1294. {
  1295. groupNameToId.rename(newName);
  1296. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_RENAMED, groupNameToId.group, 0, 0, 0.0f, groupNameToId.name);
  1297. break;
  1298. }
  1299. }
  1300. }
  1301. void handleJackPortRenameCallback(const jack_port_id_t port, const char* const oldFullName, const char* const newFullName)
  1302. {
  1303. CARLA_SAFE_ASSERT_RETURN(oldFullName != nullptr && oldFullName[0] != '\0',);
  1304. CARLA_SAFE_ASSERT_RETURN(newFullName != nullptr && newFullName[0] != '\0',);
  1305. // ignore this if on internal patchbay mode
  1306. if (! fExternalPatchbay) return;
  1307. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1308. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1309. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1310. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1311. bool found;
  1312. CarlaString groupName(newFullName);
  1313. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1314. CARLA_SAFE_ASSERT_RETURN(found,);
  1315. const uint groupId(fUsedGroups.getGroupId(groupName));
  1316. CARLA_SAFE_ASSERT_RETURN(groupId > 0,);
  1317. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin(); it.valid(); it.next())
  1318. {
  1319. PortNameToId& portNameToId(it.getValue());
  1320. if (std::strcmp(portNameToId.fullName, oldFullName) == 0)
  1321. {
  1322. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group == groupId);
  1323. portNameToId.rename(shortPortName, newFullName);
  1324. callback(ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, portNameToId.name);
  1325. break;
  1326. }
  1327. }
  1328. }
  1329. #endif
  1330. void handleJackShutdownCallback()
  1331. {
  1332. for (uint i=0; i < pData->curPluginCount; ++i)
  1333. {
  1334. if (CarlaPlugin* const plugin = pData->plugins[i].plugin)
  1335. {
  1336. plugin->tryLock(true);
  1337. if (CarlaEngineJackClient* const client = (CarlaEngineJackClient*)plugin->getEngineClient())
  1338. client->invalidate();
  1339. plugin->unlock();
  1340. }
  1341. }
  1342. fClient = nullptr;
  1343. #ifndef BUILD_BRIDGE
  1344. carla_fill<jack_port_t*>(fRackPorts, nullptr, kRackPortCount);
  1345. #endif
  1346. runPendingRtEvents();
  1347. callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  1348. }
  1349. // -------------------------------------------------------------------
  1350. void handlePluginJackShutdownCallback(CarlaPlugin* const plugin)
  1351. {
  1352. CarlaEngineJackClient* const engineClient((CarlaEngineJackClient*)plugin->getEngineClient());
  1353. CARLA_SAFE_ASSERT_RETURN(engineClient != nullptr,);
  1354. plugin->tryLock(true);
  1355. engineClient->invalidate();
  1356. plugin->unlock();
  1357. //if (pData->nextAction.pluginId == plugin->getId())
  1358. // pData->nextAction.clearAndReset();
  1359. callback(ENGINE_CALLBACK_PLUGIN_UNAVAILABLE, plugin->getId(), 0, 0, 0.0f, "Killed by JACK");
  1360. }
  1361. // -------------------------------------------------------------------
  1362. private:
  1363. jack_client_t* fClient;
  1364. jack_position_t fTransportPos;
  1365. jack_transport_state_t fTransportState;
  1366. bool fExternalPatchbay;
  1367. bool fFreewheel;
  1368. // -------------------------------------------------------------------
  1369. #ifdef BUILD_BRIDGE
  1370. bool fIsRunning;
  1371. #else
  1372. enum RackPorts {
  1373. kRackPortAudioIn1 = 0,
  1374. kRackPortAudioIn2 = 1,
  1375. kRackPortAudioOut1 = 2,
  1376. kRackPortAudioOut2 = 3,
  1377. kRackPortEventIn = 4,
  1378. kRackPortEventOut = 5,
  1379. kRackPortCount = 6
  1380. };
  1381. jack_port_t* fRackPorts[kRackPortCount];
  1382. PatchbayGroupList fUsedGroups;
  1383. PatchbayPortList fUsedPorts;
  1384. PatchbayConnectionList fUsedConnections;
  1385. LinkedList<uint> fNewGroups;
  1386. mutable CharStringListPtr fRetConns;
  1387. bool findPluginIdAndIcon(const char* const clientName, int& pluginId, PatchbayIcon& icon) noexcept
  1388. {
  1389. carla_debug("CarlaEngineJack::findPluginIdAndIcon(\"%s\", ...)", clientName);
  1390. // TODO - this currently only works in multi-client mode
  1391. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1392. return false;
  1393. for (uint i=0; i < pData->curPluginCount; ++i)
  1394. {
  1395. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1396. if (plugin == nullptr || ! plugin->isEnabled())
  1397. continue;
  1398. const CarlaEngineJackClient* const engineClient((const CarlaEngineJackClient*)plugin->getEngineClient());
  1399. CARLA_SAFE_ASSERT_CONTINUE(engineClient != nullptr);
  1400. const char* const engineClientName(engineClient->getJackClientName());
  1401. CARLA_SAFE_ASSERT_CONTINUE(engineClientName != nullptr && engineClientName[0] != '\0');
  1402. if (std::strcmp(clientName, engineClientName) != 0)
  1403. continue;
  1404. pluginId = static_cast<int>(i);
  1405. icon = PATCHBAY_ICON_PLUGIN;
  1406. if (const char* const pluginIcon = plugin->getIconName())
  1407. {
  1408. if (pluginIcon[0] == '\0')
  1409. pass();
  1410. else if (std::strcmp(pluginIcon, "app") == 0 || std::strcmp(pluginIcon, "application") == 0)
  1411. icon = PATCHBAY_ICON_APPLICATION;
  1412. else if (std::strcmp(pluginIcon, "plugin") == 0)
  1413. icon = PATCHBAY_ICON_PLUGIN;
  1414. else if (std::strcmp(pluginIcon, "hardware") == 0)
  1415. icon = PATCHBAY_ICON_HARDWARE;
  1416. else if (std::strcmp(pluginIcon, "carla") == 0)
  1417. icon = PATCHBAY_ICON_CARLA;
  1418. else if (std::strcmp(pluginIcon, "distrho") == 0)
  1419. icon = PATCHBAY_ICON_DISTRHO;
  1420. else if (std::strcmp(pluginIcon, "file") == 0)
  1421. icon = PATCHBAY_ICON_FILE;
  1422. }
  1423. return true;
  1424. }
  1425. return false;
  1426. }
  1427. void initJackPatchbay(const char* const ourName)
  1428. {
  1429. CARLA_SAFE_ASSERT_RETURN(pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY || fExternalPatchbay,);
  1430. CARLA_SAFE_ASSERT_RETURN(ourName != nullptr && ourName[0] != '\0',);
  1431. StringArray parsedGroups;
  1432. // add our client first
  1433. {
  1434. parsedGroups.add(String(ourName));
  1435. GroupNameToId groupNameToId;
  1436. groupNameToId.setData(++fUsedGroups.lastId, ourName);
  1437. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, PATCHBAY_ICON_CARLA, -1, 0.0f, groupNameToId.name);
  1438. fUsedGroups.list.append(groupNameToId);
  1439. }
  1440. // query all jack ports
  1441. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, 0))
  1442. {
  1443. for (int i=0; ports[i] != nullptr; ++i)
  1444. {
  1445. const char* const fullPortName(ports[i]);
  1446. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  1447. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  1448. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1449. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1450. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  1451. const int jackPortFlags(jackbridge_port_flags(jackPort));
  1452. uint groupId = 0;
  1453. bool found;
  1454. CarlaString groupName(fullPortName);
  1455. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1456. CARLA_SAFE_ASSERT_CONTINUE(found);
  1457. String jGroupName(groupName.buffer());
  1458. if (parsedGroups.contains(jGroupName))
  1459. {
  1460. groupId = fUsedGroups.getGroupId(groupName);
  1461. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  1462. }
  1463. else
  1464. {
  1465. groupId = ++fUsedGroups.lastId;
  1466. parsedGroups.add(jGroupName);
  1467. int pluginId = -1;
  1468. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  1469. findPluginIdAndIcon(groupName, pluginId, icon);
  1470. GroupNameToId groupNameToId;
  1471. groupNameToId.setData(groupId, groupName);
  1472. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, icon, pluginId, 0.0f, groupNameToId.name);
  1473. fUsedGroups.list.append(groupNameToId);
  1474. }
  1475. addPatchbayJackPort(groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  1476. }
  1477. jackbridge_free(ports);
  1478. }
  1479. // query connections, after all ports are in place
  1480. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  1481. {
  1482. char strBuf[STR_MAX+1];
  1483. for (int i=0; ports[i] != nullptr; ++i)
  1484. {
  1485. const char* const fullPortName(ports[i]);
  1486. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  1487. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  1488. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1489. const PortNameToId& thisPort(fUsedPorts.getPortNameToId(fullPortName));
  1490. CARLA_SAFE_ASSERT_CONTINUE(thisPort.group > 0);
  1491. CARLA_SAFE_ASSERT_CONTINUE(thisPort.port > 0);
  1492. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  1493. {
  1494. for (int j=0; connections[j] != nullptr; ++j)
  1495. {
  1496. const char* const connection(connections[j]);
  1497. CARLA_SAFE_ASSERT_CONTINUE(connection != nullptr && connection[0] != '\0');
  1498. const PortNameToId& targetPort(fUsedPorts.getPortNameToId(connection));
  1499. CARLA_SAFE_ASSERT_CONTINUE(targetPort.group > 0);
  1500. CARLA_SAFE_ASSERT_CONTINUE(targetPort.port > 0);
  1501. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  1502. strBuf[STR_MAX] = '\0';
  1503. ConnectionToId connectionToId;
  1504. connectionToId.setData(++fUsedConnections.lastId, thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  1505. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  1506. fUsedConnections.list.append(connectionToId);
  1507. }
  1508. jackbridge_free(connections);
  1509. }
  1510. }
  1511. jackbridge_free(ports);
  1512. }
  1513. }
  1514. void addPatchbayJackPort(const uint groupId, const jack_port_t* const jackPort, const char* const shortPortName, const char* const fullPortName, const int jackPortFlags)
  1515. {
  1516. bool portIsInput = (jackPortFlags & JackPortIsInput);
  1517. bool portIsAudio = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_AUDIO_TYPE) == 0);
  1518. bool portIsMIDI = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_MIDI_TYPE) == 0);
  1519. bool portIsCV = false;
  1520. bool portIsOSC = false;
  1521. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  1522. {
  1523. char* value = nullptr;
  1524. char* type = nullptr;
  1525. if (jackbridge_get_property(uuid, JACKEY_SIGNAL_TYPE, &value, &type) && value != nullptr && type != nullptr && std::strcmp(type, "text/plain") == 0)
  1526. {
  1527. portIsCV = (std::strcmp(value, "CV") == 0);
  1528. portIsOSC = (std::strcmp(value, "OSC") == 0);
  1529. }
  1530. }
  1531. uint canvasPortFlags = 0x0;
  1532. canvasPortFlags |= portIsInput ? PATCHBAY_PORT_IS_INPUT : 0x0;
  1533. if (portIsCV)
  1534. canvasPortFlags |= PATCHBAY_PORT_TYPE_CV;
  1535. else if (portIsAudio)
  1536. canvasPortFlags |= PATCHBAY_PORT_TYPE_AUDIO;
  1537. else if (portIsMIDI)
  1538. canvasPortFlags |= PATCHBAY_PORT_TYPE_MIDI;
  1539. PortNameToId portNameToId;
  1540. portNameToId.setData(groupId, ++fUsedPorts.lastId, shortPortName, fullPortName);
  1541. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, portNameToId.group, static_cast<int>(portNameToId.port), static_cast<int>(canvasPortFlags), 0.0f, portNameToId.name);
  1542. fUsedPorts.list.append(portNameToId);
  1543. return; // unused
  1544. (void)portIsOSC;
  1545. }
  1546. #endif
  1547. // -------------------------------------------------------------------
  1548. void processPlugin(CarlaPlugin* const plugin, const uint32_t nframes)
  1549. {
  1550. const uint32_t audioInCount(plugin->getAudioInCount());
  1551. const uint32_t audioOutCount(plugin->getAudioOutCount());
  1552. const uint32_t cvInCount(plugin->getCVInCount());
  1553. const uint32_t cvOutCount(plugin->getCVOutCount());
  1554. const float* audioIn[audioInCount];
  1555. /* */ float* audioOut[audioOutCount];
  1556. const float* cvIn[cvInCount];
  1557. /* */ float* cvOut[cvOutCount];
  1558. for (uint32_t i=0; i < audioInCount; ++i)
  1559. {
  1560. CarlaEngineAudioPort* const port(plugin->getAudioInPort(i));
  1561. audioIn[i] = port->getBuffer();
  1562. }
  1563. for (uint32_t i=0; i < audioOutCount; ++i)
  1564. {
  1565. CarlaEngineAudioPort* const port(plugin->getAudioOutPort(i));
  1566. audioOut[i] = port->getBuffer();
  1567. }
  1568. for (uint32_t i=0; i < cvInCount; ++i)
  1569. {
  1570. CarlaEngineCVPort* const port(plugin->getCVInPort(i));
  1571. cvIn[i] = port->getBuffer();
  1572. }
  1573. for (uint32_t i=0; i < cvOutCount; ++i)
  1574. {
  1575. CarlaEngineCVPort* const port(plugin->getCVOutPort(i));
  1576. cvOut[i] = port->getBuffer();
  1577. }
  1578. float inPeaks[2] = { 0.0f };
  1579. float outPeaks[2] = { 0.0f };
  1580. for (uint32_t i=0; i < audioInCount && i < 2; ++i)
  1581. {
  1582. for (uint32_t j=0; j < nframes; ++j)
  1583. {
  1584. const float absV(std::abs(audioIn[i][j]));
  1585. if (absV > inPeaks[i])
  1586. inPeaks[i] = absV;
  1587. }
  1588. }
  1589. plugin->process(audioIn, audioOut, cvIn, cvOut, nframes);
  1590. for (uint32_t i=0; i < audioOutCount && i < 2; ++i)
  1591. {
  1592. for (uint32_t j=0; j < nframes; ++j)
  1593. {
  1594. const float absV(std::abs(audioOut[i][j]));
  1595. if (absV > outPeaks[i])
  1596. outPeaks[i] = absV;
  1597. }
  1598. }
  1599. setPluginPeaks(plugin->getId(), inPeaks, outPeaks);
  1600. }
  1601. // -------------------------------------------------------------------
  1602. #define handlePtr ((CarlaEngineJack*)arg)
  1603. static void carla_jack_thread_init_callback(void*)
  1604. {
  1605. #ifdef __SSE2_MATH__
  1606. // Set FTZ and DAZ flags
  1607. _mm_setcsr(_mm_getcsr() | 0x8040);
  1608. #endif
  1609. }
  1610. static int carla_jack_bufsize_callback(jack_nframes_t newBufferSize, void* arg)
  1611. {
  1612. handlePtr->handleJackBufferSizeCallback(newBufferSize);
  1613. return 0;
  1614. }
  1615. static int carla_jack_srate_callback(jack_nframes_t newSampleRate, void* arg)
  1616. {
  1617. handlePtr->handleJackSampleRateCallback(newSampleRate);
  1618. return 0;
  1619. }
  1620. static void carla_jack_freewheel_callback(int starting, void* arg)
  1621. {
  1622. handlePtr->handleJackFreewheelCallback(bool(starting));
  1623. }
  1624. static int carla_jack_process_callback(jack_nframes_t nframes, void* arg)
  1625. {
  1626. handlePtr->handleJackProcessCallback(nframes);
  1627. return 0;
  1628. }
  1629. static void carla_jack_latency_callback(jack_latency_callback_mode_t mode, void* arg)
  1630. {
  1631. handlePtr->handleJackLatencyCallback(mode);
  1632. }
  1633. #ifndef BUILD_BRIDGE
  1634. static void carla_jack_client_registration_callback(const char* name, int reg, void* arg)
  1635. {
  1636. handlePtr->handleJackClientRegistrationCallback(name, (reg != 0));
  1637. }
  1638. static void carla_jack_port_registration_callback(jack_port_id_t port, int reg, void* arg)
  1639. {
  1640. handlePtr->handleJackPortRegistrationCallback(port, (reg != 0));
  1641. }
  1642. static void carla_jack_port_connect_callback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg)
  1643. {
  1644. handlePtr->handleJackPortConnectCallback(a, b, (connect != 0));
  1645. }
  1646. static int carla_jack_client_rename_callback(const char* oldName, const char* newName, void* arg)
  1647. {
  1648. handlePtr->handleJackClientRenameCallback(oldName, newName);
  1649. return 0;
  1650. }
  1651. // NOTE: JACK1 returns void, JACK2 returns int
  1652. static int carla_jack_port_rename_callback(jack_port_id_t port, const char* oldName, const char* newName, void* arg)
  1653. {
  1654. handlePtr->handleJackPortRenameCallback(port, oldName, newName);
  1655. return 0;
  1656. }
  1657. #endif
  1658. static void carla_jack_shutdown_callback(void* arg)
  1659. {
  1660. handlePtr->handleJackShutdownCallback();
  1661. }
  1662. #undef handlePtr
  1663. // -------------------------------------------------------------------
  1664. #ifndef BUILD_BRIDGE
  1665. static int carla_jack_process_callback_plugin(jack_nframes_t nframes, void* arg)
  1666. {
  1667. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  1668. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  1669. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  1670. CARLA_SAFE_ASSERT_RETURN(engine != nullptr, 0);
  1671. if (plugin->tryLock(engine->fFreewheel))
  1672. {
  1673. plugin->initBuffers();
  1674. engine->saveTransportInfo();
  1675. engine->processPlugin(plugin, nframes);
  1676. plugin->unlock();
  1677. }
  1678. return 0;
  1679. }
  1680. static void carla_jack_latency_callback_plugin(jack_latency_callback_mode_t /*mode*/, void* /*arg*/)
  1681. {
  1682. // TODO
  1683. }
  1684. static void carla_jack_shutdown_callback_plugin(void* arg)
  1685. {
  1686. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  1687. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr,);
  1688. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  1689. CARLA_SAFE_ASSERT_RETURN(engine != nullptr,);
  1690. engine->handlePluginJackShutdownCallback(plugin);
  1691. }
  1692. #endif
  1693. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJack)
  1694. };
  1695. // -----------------------------------------------------------------------
  1696. CarlaEngine* CarlaEngine::newJack()
  1697. {
  1698. carla_debug("CarlaEngine::newJack()");
  1699. return new CarlaEngineJack();
  1700. }
  1701. // -----------------------------------------------------------------------
  1702. CARLA_BACKEND_END_NAMESPACE