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.

2233 lines
76KB

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