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.

2545 lines
90KB

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