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.

2219 lines
77KB

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