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.

2570 lines
91KB

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