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.

2709 lines
96KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2018 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 data[3] = { 0, 0, 0 };
  306. EngineControlEvent ctrlEvent = { type, param, value };
  307. const uint8_t size = ctrlEvent.convertToMidiData(channel, data);
  308. if (size == 0)
  309. return false;
  310. try {
  311. return jackbridge_midi_event_write(fJackBuffer, time, data, size);
  312. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  313. }
  314. bool writeMidiEvent(const uint32_t time, const uint8_t channel, const uint8_t size, const uint8_t* const data) noexcept override
  315. {
  316. if (fJackPort == nullptr)
  317. return CarlaEngineEventPort::writeMidiEvent(time, channel, size, data);
  318. CARLA_SAFE_ASSERT_RETURN(! kIsInput, false);
  319. CARLA_SAFE_ASSERT_RETURN(fJackBuffer != nullptr, false);
  320. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  321. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  322. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  323. jack_midi_data_t jdata[size];
  324. jdata[0] = static_cast<jack_midi_data_t>(MIDI_GET_STATUS_FROM_DATA(data) + channel);
  325. for (uint8_t i=1; i < size; ++i)
  326. jdata[i] = data[i];
  327. try {
  328. return jackbridge_midi_event_write(fJackBuffer, time, jdata, size);
  329. } CARLA_SAFE_EXCEPTION_RETURN("jack_midi_event_write", false);
  330. }
  331. void invalidate() noexcept
  332. {
  333. fJackClient = nullptr;
  334. fJackPort = nullptr;
  335. }
  336. private:
  337. jack_client_t* fJackClient;
  338. jack_port_t* fJackPort;
  339. void* fJackBuffer;
  340. mutable EngineEvent fRetEvent;
  341. JackPortDeletionCallback* const kDeletionCallback;
  342. friend class CarlaEngineJackClient;
  343. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackEventPort)
  344. };
  345. // -----------------------------------------------------------------------
  346. // Jack Engine client
  347. class CarlaEngineJackClient : public CarlaEngineClient,
  348. private JackPortDeletionCallback
  349. {
  350. public:
  351. CarlaEngineJackClient(const CarlaEngine& engine, jack_client_t* const jackClient)
  352. : CarlaEngineClient(engine),
  353. fJackClient(jackClient),
  354. fUseClient(engine.getProccessMode() == ENGINE_PROCESS_MODE_SINGLE_CLIENT || engine.getProccessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS),
  355. fAudioPorts(),
  356. fCVPorts(),
  357. fEventPorts(),
  358. fPreRenameMutex(),
  359. fPreRenameConnections()
  360. {
  361. carla_debug("CarlaEngineJackClient::CarlaEngineJackClient(%p)", jackClient);
  362. if (fUseClient)
  363. {
  364. CARLA_SAFE_ASSERT(jackClient != nullptr);
  365. }
  366. else
  367. {
  368. CARLA_SAFE_ASSERT(jackClient == nullptr);
  369. }
  370. }
  371. ~CarlaEngineJackClient() noexcept override
  372. {
  373. carla_debug("CarlaEngineJackClient::~CarlaEngineJackClient()");
  374. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS && fJackClient != nullptr) // FIXME
  375. jackbridge_client_close(fJackClient);
  376. // ports must have been deleted by now!
  377. //fAudioPorts.clear();
  378. //fCVPorts.clear();
  379. //fEventPorts.clear();
  380. }
  381. void activate() noexcept override
  382. {
  383. carla_debug("CarlaEngineJackClient::activate()");
  384. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  385. {
  386. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && ! isActive(),);
  387. try {
  388. jackbridge_activate(fJackClient);
  389. } catch(...) {}
  390. }
  391. CarlaEngineClient::activate();
  392. const CarlaMutexLocker cml(fPreRenameMutex);
  393. if (fJackClient != nullptr)
  394. {
  395. // restore pre-rename connections
  396. const char* portNameA = nullptr;
  397. const char* portNameB = nullptr;
  398. bool doConnection = false;
  399. for (CarlaStringList::Itenerator it = fPreRenameConnections.begin2(); it.valid(); it.next())
  400. {
  401. const bool connectNow = doConnection;
  402. doConnection = !doConnection;
  403. if (connectNow)
  404. portNameB = it.getValue(nullptr);
  405. else
  406. portNameA = it.getValue(nullptr);
  407. if (! connectNow)
  408. continue;
  409. CARLA_SAFE_ASSERT_CONTINUE(portNameA != nullptr && portNameA[0] != '\0');
  410. CARLA_SAFE_ASSERT_CONTINUE(portNameB != nullptr && portNameB[0] != '\0');
  411. jackbridge_connect(fJackClient, portNameA, portNameB);
  412. }
  413. }
  414. fPreRenameConnections.clear();
  415. }
  416. void deactivate() noexcept override
  417. {
  418. carla_debug("CarlaEngineJackClient::deactivate()");
  419. if (getProcessMode() == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  420. {
  421. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr && isActive(),);
  422. try {
  423. jackbridge_deactivate(fJackClient);
  424. } catch(...) {}
  425. }
  426. CarlaEngineClient::deactivate();
  427. }
  428. bool isOk() const noexcept override
  429. {
  430. if (fUseClient)
  431. return (fJackClient != nullptr);
  432. return CarlaEngineClient::isOk();
  433. }
  434. CarlaEnginePort* addPort(const EnginePortType portType, const char* const name, const bool isInput, const uint32_t indexOffset) override
  435. {
  436. carla_debug("CarlaEngineJackClient::addPort(%i:%s, \"%s\", %s)", portType, EnginePortType2Str(portType), name, bool2str(isInput));
  437. jack_port_t* jackPort = nullptr;
  438. const char* realName = name;
  439. // Create JACK port first, if needed
  440. if (fUseClient)
  441. {
  442. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  443. realName = _getUniquePortName(name);
  444. switch (portType)
  445. {
  446. case kEnginePortTypeNull:
  447. break;
  448. case kEnginePortTypeAudio:
  449. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  450. break;
  451. case kEnginePortTypeCV:
  452. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  453. break;
  454. case kEnginePortTypeEvent:
  455. jackPort = jackbridge_port_register(fJackClient, realName, JACK_DEFAULT_MIDI_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  456. break;
  457. }
  458. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr, nullptr);
  459. }
  460. // Create Engine port
  461. switch (portType)
  462. {
  463. case kEnginePortTypeNull:
  464. break;
  465. case kEnginePortTypeAudio: {
  466. _addAudioPortName(isInput, realName);
  467. if (realName != name) delete[] realName;
  468. CarlaEngineJackAudioPort* const enginePort(new CarlaEngineJackAudioPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  469. fAudioPorts.append(enginePort);
  470. return enginePort;
  471. }
  472. case kEnginePortTypeCV: {
  473. _addCVPortName(isInput, realName);
  474. if (realName != name) delete[] realName;
  475. CarlaEngineJackCVPort* const enginePort(new CarlaEngineJackCVPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  476. fCVPorts.append(enginePort);
  477. return enginePort;
  478. }
  479. case kEnginePortTypeEvent: {
  480. _addEventPortName(isInput, realName);
  481. if (realName != name) delete[] realName;
  482. CarlaEngineJackEventPort* const enginePort(new CarlaEngineJackEventPort(*this, isInput, indexOffset, fJackClient, jackPort, this));
  483. fEventPorts.append(enginePort);
  484. return enginePort;
  485. }
  486. }
  487. carla_stderr("CarlaEngineJackClient::addPort(%i, \"%s\", %s) - invalid type", portType, name, bool2str(isInput));
  488. return nullptr;
  489. }
  490. void invalidate() noexcept
  491. {
  492. for (LinkedList<CarlaEngineJackAudioPort*>::Itenerator it = fAudioPorts.begin2(); it.valid(); it.next())
  493. {
  494. CarlaEngineJackAudioPort* const port(it.getValue(nullptr));
  495. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  496. port->invalidate();
  497. }
  498. for (LinkedList<CarlaEngineJackCVPort*>::Itenerator it = fCVPorts.begin2(); it.valid(); it.next())
  499. {
  500. CarlaEngineJackCVPort* const port(it.getValue(nullptr));
  501. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  502. port->invalidate();
  503. }
  504. for (LinkedList<CarlaEngineJackEventPort*>::Itenerator it = fEventPorts.begin2(); it.valid(); it.next())
  505. {
  506. CarlaEngineJackEventPort* const port(it.getValue(nullptr));
  507. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  508. port->invalidate();
  509. }
  510. fJackClient = nullptr;
  511. CarlaEngineClient::deactivate();
  512. }
  513. const char* getJackClientName() const noexcept
  514. {
  515. CARLA_SAFE_ASSERT_RETURN(fJackClient != nullptr, nullptr);
  516. try {
  517. return jackbridge_get_client_name(fJackClient);
  518. } CARLA_SAFE_EXCEPTION_RETURN("jack_get_client_name", nullptr);
  519. }
  520. void jackAudioPortDeleted(CarlaEngineJackAudioPort* const port) noexcept override
  521. {
  522. fAudioPorts.removeAll(port);
  523. }
  524. void jackCVPortDeleted(CarlaEngineJackCVPort* const port) noexcept override
  525. {
  526. fCVPorts.removeAll(port);
  527. }
  528. void jackEventPortDeleted(CarlaEngineJackEventPort* const port) noexcept override
  529. {
  530. fEventPorts.removeAll(port);
  531. }
  532. bool renameInSingleClient(const CarlaString& newClientName)
  533. {
  534. const CarlaString clientNamePrefix(newClientName + ":");
  535. return _renamePorts(fAudioPorts, clientNamePrefix) &&
  536. _renamePorts(fCVPorts, clientNamePrefix) &&
  537. _renamePorts(fEventPorts, clientNamePrefix);
  538. }
  539. void closeForRename(jack_client_t* const newClient, const CarlaString& newClientName) noexcept
  540. {
  541. if (fJackClient != nullptr)
  542. {
  543. if (isActive())
  544. {
  545. {
  546. const CarlaString clientNamePrefix(newClientName + ":");
  547. // store current client connections
  548. const CarlaMutexLocker cml(fPreRenameMutex);
  549. fPreRenameConnections.clear();
  550. _savePortsConnections(fAudioPorts, clientNamePrefix);
  551. _savePortsConnections(fCVPorts, clientNamePrefix);
  552. _savePortsConnections(fEventPorts, clientNamePrefix);
  553. }
  554. try {
  555. jackbridge_deactivate(fJackClient);
  556. } catch(...) {}
  557. }
  558. try {
  559. jackbridge_client_close(fJackClient);
  560. } catch(...) {}
  561. invalidate();
  562. }
  563. fAudioPorts.clear();
  564. fCVPorts.clear();
  565. fEventPorts.clear();
  566. _clearPorts();
  567. fJackClient = newClient;
  568. }
  569. private:
  570. jack_client_t* fJackClient;
  571. const bool fUseClient;
  572. LinkedList<CarlaEngineJackAudioPort*> fAudioPorts;
  573. LinkedList<CarlaEngineJackCVPort*> fCVPorts;
  574. LinkedList<CarlaEngineJackEventPort*> fEventPorts;
  575. CarlaMutex fPreRenameMutex;
  576. CarlaStringList fPreRenameConnections;
  577. template<typename T>
  578. bool _renamePorts(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  579. {
  580. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  581. {
  582. T* const port(it.getValue(nullptr));
  583. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  584. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  585. const char* shortPortName(jackbridge_port_short_name(port->fJackPort));
  586. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  587. const char* const oldClientNameSep(std::strstr(shortPortName, ":"));
  588. CARLA_SAFE_ASSERT_CONTINUE(oldClientNameSep != nullptr && oldClientNameSep[0] != '\0' && oldClientNameSep[1] != '\0');
  589. shortPortName += oldClientNameSep-shortPortName + 1;
  590. const CarlaString newPortName(clientNamePrefix + shortPortName);
  591. if (! jackbridge_port_rename(fJackClient, port->fJackPort, newPortName))
  592. return false;
  593. }
  594. return true;
  595. }
  596. template<typename T>
  597. void _savePortsConnections(const LinkedList<T*>& t, const CarlaString& clientNamePrefix)
  598. {
  599. for (typename LinkedList<T*>::Itenerator it = t.begin2(); it.valid(); it.next())
  600. {
  601. T* const port(it.getValue(nullptr));
  602. CARLA_SAFE_ASSERT_CONTINUE(port != nullptr);
  603. CARLA_SAFE_ASSERT_CONTINUE(port->fJackPort != nullptr);
  604. const char* const shortPortName(jackbridge_port_short_name(port->fJackPort));
  605. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  606. const CarlaString portName(clientNamePrefix + shortPortName);
  607. if (const char** const connections = jackbridge_port_get_all_connections(fJackClient, port->fJackPort))
  608. {
  609. for (int i=0; connections[i] != nullptr; ++i)
  610. {
  611. if (port->kIsInput)
  612. {
  613. fPreRenameConnections.append(connections[i]);
  614. fPreRenameConnections.append(portName);
  615. }
  616. else
  617. {
  618. fPreRenameConnections.append(portName);
  619. fPreRenameConnections.append(connections[i]);
  620. }
  621. }
  622. jackbridge_free(connections);
  623. }
  624. }
  625. }
  626. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackClient)
  627. };
  628. // -----------------------------------------------------------------------
  629. // Jack Engine
  630. class CarlaEngineJack : public CarlaEngine
  631. #ifndef BUILD_BRIDGE
  632. , private CarlaThread
  633. #endif
  634. {
  635. public:
  636. CarlaEngineJack()
  637. : CarlaEngine(),
  638. #ifndef BUILD_BRIDGE
  639. CarlaThread("CarlaEngineJackCallbacks"),
  640. #endif
  641. fClient(nullptr),
  642. fExternalPatchbay(true),
  643. fFreewheel(false),
  644. #ifdef BUILD_BRIDGE
  645. fIsRunning(false)
  646. #else
  647. fTimebaseMaster(false),
  648. fTimebaseRolling(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. const EngineOptions& opts(pData->options);
  754. pData->bufferSize = jackbridge_get_buffer_size(fClient);
  755. pData->sampleRate = jackbridge_get_sample_rate(fClient);
  756. pData->initTime(opts.transportExtra);
  757. jackbridge_set_thread_init_callback(fClient, carla_jack_thread_init_callback, nullptr);
  758. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback, this);
  759. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback, this);
  760. jackbridge_set_freewheel_callback(fClient, carla_jack_freewheel_callback, this);
  761. jackbridge_set_latency_callback(fClient, carla_jack_latency_callback, this);
  762. jackbridge_set_process_callback(fClient, carla_jack_process_callback, this);
  763. jackbridge_on_shutdown(fClient, carla_jack_shutdown_callback, this);
  764. fTimebaseRolling = false;
  765. if (opts.transportMode == ENGINE_TRANSPORT_MODE_JACK)
  766. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  767. else
  768. fTimebaseMaster = false;
  769. if (opts.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  770. initJackPatchbay(jackClientName);
  771. jackbridge_set_client_registration_callback(fClient, carla_jack_client_registration_callback, this);
  772. jackbridge_set_port_registration_callback(fClient, carla_jack_port_registration_callback, this);
  773. jackbridge_set_port_connect_callback(fClient, carla_jack_port_connect_callback, this);
  774. jackbridge_set_port_rename_callback(fClient, carla_jack_port_rename_callback, this);
  775. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  776. {
  777. fRackPorts[kRackPortAudioIn1] = jackbridge_port_register(fClient, "audio-in1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  778. fRackPorts[kRackPortAudioIn2] = jackbridge_port_register(fClient, "audio-in2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  779. fRackPorts[kRackPortAudioOut1] = jackbridge_port_register(fClient, "audio-out1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  780. fRackPorts[kRackPortAudioOut2] = jackbridge_port_register(fClient, "audio-out2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  781. fRackPorts[kRackPortEventIn] = jackbridge_port_register(fClient, "events-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
  782. fRackPorts[kRackPortEventOut] = jackbridge_port_register(fClient, "events-out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
  783. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  784. {
  785. // FIXME?
  786. pData->graph.create(0, 0);
  787. }
  788. else
  789. {
  790. pData->graph.create(2, 2);
  791. patchbayRefresh(false);
  792. }
  793. }
  794. if (jackbridge_activate(fClient))
  795. {
  796. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  797. opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  798. {
  799. if (pData->options.audioDevice != nullptr &&
  800. std::strcmp(pData->options.audioDevice, "Auto-Connect ON") == 0 &&
  801. std::getenv("LADISH_APP_NAME") == nullptr &&
  802. std::getenv("NSM_URL") == nullptr)
  803. {
  804. char strBuf[STR_MAX];
  805. strBuf[STR_MAX-1] = '\0';
  806. if (jackbridge_port_by_name(fClient, "system:capture_1") != nullptr)
  807. {
  808. std::snprintf(strBuf, STR_MAX-2, "%s:audio-in1", jackClientName);
  809. jackbridge_connect(fClient, "system:capture_1", strBuf);
  810. std::snprintf(strBuf, STR_MAX-2, "%s:audio-in2", jackClientName);
  811. if (jackbridge_port_by_name(fClient, "system:capture_2") != nullptr)
  812. jackbridge_connect(fClient, "system:capture_2", strBuf);
  813. else
  814. jackbridge_connect(fClient, "system:capture_1", strBuf);
  815. }
  816. if (jackbridge_port_by_name(fClient, "system:playback_1") != nullptr)
  817. {
  818. std::snprintf(strBuf, STR_MAX-2, "%s:audio-out1", jackClientName);
  819. jackbridge_connect(fClient, strBuf, "system:playback_1");
  820. std::snprintf(strBuf, STR_MAX-2, "%s:audio-out2", jackClientName);
  821. if (jackbridge_port_by_name(fClient, "system:playback_2") != nullptr)
  822. jackbridge_connect(fClient, strBuf, "system:playback_2");
  823. else
  824. jackbridge_connect(fClient, strBuf, "system:playback_1");
  825. }
  826. }
  827. }
  828. startThread();
  829. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0,
  830. opts.processMode, opts.transportMode,
  831. pData->sampleRate,
  832. getCurrentDriverName());
  833. return true;
  834. }
  835. if (opts.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  836. opts.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  837. {
  838. pData->graph.destroy();
  839. }
  840. pData->close();
  841. jackbridge_client_close(fClient);
  842. fClient = nullptr;
  843. setLastError("Failed to activate the JACK client");
  844. return false;
  845. #endif
  846. }
  847. bool close() override
  848. {
  849. carla_debug("CarlaEngineJack::close()");
  850. #ifdef BUILD_BRIDGE
  851. fClient = nullptr;
  852. fIsRunning = false;
  853. CarlaEngine::close();
  854. return true;
  855. #else
  856. stopThread(-1);
  857. fPostPonedEvents.clear();
  858. CARLA_SAFE_ASSERT_RETURN_ERR(fClient != nullptr, "JACK Client is null");
  859. // deactivate first
  860. const bool deactivated(jackbridge_deactivate(fClient));
  861. // clear engine data
  862. CarlaEngine::close();
  863. fUsedGroups.clear();
  864. fUsedPorts.clear();
  865. fUsedConnections.clear();
  866. fNewGroups.clear();
  867. fPostPonedEvents.clear();
  868. // clear rack/patchbay stuff
  869. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  870. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  871. {
  872. if (deactivated)
  873. {
  874. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioIn1]);
  875. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioIn2]);
  876. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioOut1]);
  877. jackbridge_port_unregister(fClient, fRackPorts[kRackPortAudioOut2]);
  878. jackbridge_port_unregister(fClient, fRackPorts[kRackPortEventIn]);
  879. jackbridge_port_unregister(fClient, fRackPorts[kRackPortEventOut]);
  880. }
  881. carla_zeroPointers(fRackPorts, kRackPortCount);
  882. pData->graph.destroy();
  883. }
  884. // close client
  885. if (deactivated)
  886. jackbridge_client_close(fClient);
  887. fClient = nullptr;
  888. return true;
  889. #endif
  890. }
  891. bool isRunning() const noexcept override
  892. {
  893. #ifdef BUILD_BRIDGE
  894. return (fClient != nullptr || fIsRunning);
  895. #else
  896. return (fClient != nullptr);
  897. #endif
  898. }
  899. bool isOffline() const noexcept override
  900. {
  901. return fFreewheel;
  902. }
  903. EngineType getType() const noexcept override
  904. {
  905. return kEngineTypeJack;
  906. }
  907. const char* getCurrentDriverName() const noexcept override
  908. {
  909. return "JACK";
  910. }
  911. EngineTimeInfo getTimeInfo() const noexcept override
  912. {
  913. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  914. return CarlaEngine::getTimeInfo();
  915. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  916. return CarlaEngine::getTimeInfo();
  917. jack_position_t jpos;
  918. // invalidate
  919. jpos.unique_1 = 1;
  920. jpos.unique_2 = 2;
  921. EngineTimeInfo timeInfo;
  922. const bool playing = jackbridge_transport_query(fClient, &jpos) == JackTransportRolling;
  923. if (jpos.unique_1 != jpos.unique_2)
  924. {
  925. timeInfo.playing = false;
  926. timeInfo.frame = 0;
  927. timeInfo.usecs = 0;
  928. timeInfo.bbt.valid = false;
  929. return timeInfo;
  930. }
  931. timeInfo.playing = playing;
  932. timeInfo.frame = jpos.frame;
  933. timeInfo.usecs = jpos.usecs;
  934. if (jpos.valid & JackPositionBBT)
  935. {
  936. timeInfo.bbt.valid = true;
  937. timeInfo.bbt.bar = jpos.bar;
  938. timeInfo.bbt.beat = jpos.beat;
  939. timeInfo.bbt.tick = jpos.tick;
  940. timeInfo.bbt.barStartTick = jpos.bar_start_tick;
  941. timeInfo.bbt.beatsPerBar = jpos.beats_per_bar;
  942. timeInfo.bbt.beatType = jpos.beat_type;
  943. timeInfo.bbt.ticksPerBeat = jpos.ticks_per_beat;
  944. timeInfo.bbt.beatsPerMinute = jpos.beats_per_minute;
  945. }
  946. else
  947. {
  948. timeInfo.bbt.valid = false;
  949. }
  950. return timeInfo;
  951. }
  952. #ifndef BUILD_BRIDGE
  953. void setOption(const EngineOption option, const int value, const char* const valueStr) noexcept override
  954. {
  955. if (option == ENGINE_OPTION_TRANSPORT_MODE && fClient != nullptr)
  956. {
  957. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_JACK,);
  958. if (value == ENGINE_TRANSPORT_MODE_JACK)
  959. {
  960. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  961. }
  962. else
  963. {
  964. // jack transport cannot be disabled in multi-client
  965. callback(ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED, 0,
  966. ENGINE_TRANSPORT_MODE_JACK, 0, 0.0f,
  967. pData->options.transportExtra);
  968. CARLA_SAFE_ASSERT_RETURN(pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS,);
  969. jackbridge_release_timebase(fClient);
  970. fTimebaseMaster = false;
  971. }
  972. }
  973. CarlaEngine::setOption(option, value, valueStr);
  974. }
  975. #endif
  976. CarlaEngineClient* addClient(CarlaPlugin* const plugin) override
  977. {
  978. jack_client_t* client = nullptr;
  979. #ifndef BUILD_BRIDGE
  980. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  981. {
  982. client = fClient;
  983. }
  984. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  985. #endif
  986. {
  987. client = jackbridge_client_open(plugin->getName(), JackNullOption, nullptr);
  988. CARLA_SAFE_ASSERT_RETURN(client != nullptr, nullptr);
  989. jackbridge_set_thread_init_callback(client, carla_jack_thread_init_callback, nullptr);
  990. #ifndef BUILD_BRIDGE
  991. /*
  992. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback_plugin, plugin);
  993. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback_plugin, plugin);
  994. */
  995. jackbridge_set_latency_callback(client, carla_jack_latency_callback_plugin, plugin);
  996. jackbridge_set_process_callback(client, carla_jack_process_callback_plugin, plugin);
  997. jackbridge_on_shutdown(client, carla_jack_shutdown_callback_plugin, plugin);
  998. #else
  999. fClient = client;
  1000. pData->bufferSize = jackbridge_get_buffer_size(client);
  1001. pData->sampleRate = jackbridge_get_sample_rate(client);
  1002. pData->initTime(nullptr);
  1003. jackbridge_set_buffer_size_callback(client, carla_jack_bufsize_callback, this);
  1004. jackbridge_set_sample_rate_callback(client, carla_jack_srate_callback, this);
  1005. jackbridge_set_freewheel_callback(client, carla_jack_freewheel_callback, this);
  1006. jackbridge_set_latency_callback(client, carla_jack_latency_callback, this);
  1007. jackbridge_set_process_callback(client, carla_jack_process_callback, this);
  1008. jackbridge_on_shutdown(client, carla_jack_shutdown_callback, this);
  1009. #endif
  1010. }
  1011. return new CarlaEngineJackClient(*this, client);
  1012. }
  1013. #ifndef BUILD_BRIDGE
  1014. const char* renamePlugin(const uint id, const char* const newName) override
  1015. {
  1016. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1017. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1018. {
  1019. return CarlaEngine::renamePlugin(id, newName);
  1020. }
  1021. CARLA_SAFE_ASSERT_RETURN(pData->plugins != nullptr, nullptr);
  1022. CARLA_SAFE_ASSERT_RETURN(pData->curPluginCount != 0, nullptr);
  1023. CARLA_SAFE_ASSERT_RETURN(id < pData->curPluginCount, nullptr);
  1024. CARLA_SAFE_ASSERT_RETURN(newName != nullptr && newName[0] != '\0', nullptr);
  1025. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  1026. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  1027. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  1028. // before we stop the engine thread we might need to get the plugin data
  1029. const bool needsReinit = (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS);
  1030. const CarlaStateSave* saveStatePtr = nullptr;
  1031. if (needsReinit)
  1032. {
  1033. const CarlaStateSave& saveState(plugin->getStateSave());
  1034. saveStatePtr = &saveState;
  1035. }
  1036. CarlaString uniqueName;
  1037. try {
  1038. const char* const tmpName = getUniquePluginName(newName);
  1039. uniqueName = tmpName;
  1040. delete[] tmpName;
  1041. } CARLA_SAFE_EXCEPTION("JACK renamePlugin getUniquePluginName");
  1042. if (uniqueName.isEmpty())
  1043. {
  1044. setLastError("Failed to request new unique plugin name");
  1045. return nullptr;
  1046. }
  1047. const ScopedThreadStopper sts(this);
  1048. // rename on client client mode, just rename the ports
  1049. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1050. {
  1051. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  1052. if (! client->renameInSingleClient(uniqueName))
  1053. {
  1054. setLastError("Failed to rename some JACK ports, does your JACK version support proper port renaming?");
  1055. return nullptr;
  1056. }
  1057. }
  1058. // rename in multiple client mode
  1059. else if (pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1060. {
  1061. CarlaEngineJackClient* const client((CarlaEngineJackClient*)plugin->getEngineClient());
  1062. // we should not be able to do this, jack really needs to allow client rename
  1063. if (jack_client_t* const jackClient = jackbridge_client_open(uniqueName, JackNullOption, nullptr))
  1064. {
  1065. // get new client name
  1066. uniqueName = jackbridge_get_client_name(jackClient);
  1067. // close client
  1068. client->closeForRename(jackClient, uniqueName);
  1069. // disable plugin
  1070. plugin->setEnabled(false);
  1071. // set new client data
  1072. jackbridge_set_latency_callback(jackClient, carla_jack_latency_callback_plugin, plugin);
  1073. jackbridge_set_process_callback(jackClient, carla_jack_process_callback_plugin, plugin);
  1074. jackbridge_on_shutdown(jackClient, carla_jack_shutdown_callback_plugin, plugin);
  1075. // NOTE: jack1 locks up here
  1076. if (jackbridge_get_version_string() != nullptr)
  1077. jackbridge_set_thread_init_callback(jackClient, carla_jack_thread_init_callback, nullptr);
  1078. /* The following code is because of a tricky situation.
  1079. We cannot lock or do jack operations during jack callbacks on jack1. jack2 events are asynchronous.
  1080. When we close the client jack will trigger unregister-port callbacks, which we handle on a separate thread ASAP.
  1081. But before that happens we already registered a new client with the same ports (the "renamed" one),
  1082. and at this point the port we receive during that callback is actually the new one from the new client..
  1083. JACK2 seems to be reusing ports to save space, which is understandable.
  1084. Anyway, this means we have to remove all our port-related data before the new client ports are created.
  1085. (we also stop the separate jack-events thread to avoid any race conditions while modying our port data) */
  1086. stopThread(-1);
  1087. const uint groupId(fUsedGroups.getGroupId(plugin->getName()));
  1088. if (groupId > 0)
  1089. {
  1090. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  1091. {
  1092. for (LinkedList<ConnectionToId>::Itenerator it2 = fUsedConnections.list.begin2(); it2.valid(); it2.next())
  1093. {
  1094. static ConnectionToId connectionFallback = { 0, 0, 0, 0, 0 };
  1095. ConnectionToId& connectionToId = it2.getValue(connectionFallback);
  1096. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1097. if (connectionToId.groupA != groupId && connectionToId.groupB != groupId)
  1098. continue;
  1099. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED, connectionToId.id, 0, 0, 0.0f, nullptr);
  1100. fUsedConnections.list.remove(it2);
  1101. }
  1102. static PortNameToId portNameFallback = { 0, 0, { '\0' }, { '\0' } };
  1103. PortNameToId& portNameToId(it.getValue(portNameFallback));
  1104. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1105. if (portNameToId.group != groupId)
  1106. continue;
  1107. callback(ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, nullptr);
  1108. fUsedPorts.list.remove(it);
  1109. }
  1110. }
  1111. startThread();
  1112. }
  1113. else
  1114. {
  1115. setLastError("Failed to create new JACK client");
  1116. return nullptr;
  1117. }
  1118. }
  1119. // Rename
  1120. plugin->setName(uniqueName);
  1121. if (needsReinit)
  1122. {
  1123. // reload plugin to recreate its ports
  1124. plugin->reload();
  1125. plugin->loadStateSave(*saveStatePtr);
  1126. plugin->setEnabled(true);
  1127. }
  1128. return plugin->getName();
  1129. }
  1130. // -------------------------------------------------------------------
  1131. // Patchbay
  1132. bool patchbayConnect(const uint groupA, const uint portA, const uint groupB, const uint portB) override
  1133. {
  1134. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1135. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! fExternalPatchbay)
  1136. return CarlaEngine::patchbayConnect(groupA, portA, groupB, portB);
  1137. const char* const fullPortNameA = fUsedPorts.getFullPortName(groupA, portA);
  1138. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1139. const char* const fullPortNameB = fUsedPorts.getFullPortName(groupB, portB);
  1140. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1141. if (! jackbridge_connect(fClient, fullPortNameA, fullPortNameB))
  1142. {
  1143. setLastError("JACK operation failed");
  1144. return false;
  1145. }
  1146. return true;
  1147. }
  1148. bool patchbayDisconnect(const uint connectionId) override
  1149. {
  1150. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1151. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! fExternalPatchbay)
  1152. return CarlaEngine::patchbayDisconnect(connectionId);
  1153. ConnectionToId connectionToId = { 0, 0, 0, 0, 0 };
  1154. {
  1155. const CarlaMutexLocker cml(fUsedConnections.mutex);
  1156. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1157. {
  1158. connectionToId = it.getValue(connectionToId);
  1159. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1160. if (connectionToId.id == connectionId)
  1161. break;
  1162. }
  1163. }
  1164. if (connectionToId.id == 0 || connectionToId.id != connectionId)
  1165. {
  1166. setLastError("Failed to find the requested connection");
  1167. return false;
  1168. }
  1169. const char* const fullPortNameA = fUsedPorts.getFullPortName(connectionToId.groupA, connectionToId.portA);
  1170. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0', false);
  1171. const char* const fullPortNameB = fUsedPorts.getFullPortName(connectionToId.groupB, connectionToId.portB);
  1172. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0', false);
  1173. if (! jackbridge_disconnect(fClient, fullPortNameA, fullPortNameB))
  1174. {
  1175. setLastError("JACK operation failed");
  1176. return false;
  1177. }
  1178. return true;
  1179. }
  1180. bool patchbayRefresh(const bool external) override
  1181. {
  1182. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, false);
  1183. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1184. {
  1185. fExternalPatchbay = external;
  1186. pData->graph.setUsingExternal(external);
  1187. if (! external)
  1188. return CarlaEngine::patchbayRefresh(false);
  1189. }
  1190. fUsedGroups.clear();
  1191. fUsedPorts.clear();
  1192. fUsedConnections.clear();
  1193. fNewGroups.clear();
  1194. initJackPatchbay(jackbridge_get_client_name(fClient));
  1195. return true;
  1196. }
  1197. // -------------------------------------------------------------------
  1198. // Transport
  1199. void transportPlay() noexcept override
  1200. {
  1201. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1202. return CarlaEngine::transportPlay();
  1203. if (fClient != nullptr)
  1204. {
  1205. if (! pData->timeInfo.bbt.valid)
  1206. {
  1207. // old timebase master no longer active, make ourselves master again
  1208. pData->time.setNeedsReset();
  1209. fTimebaseMaster = jackbridge_set_timebase_callback(fClient, true, carla_jack_timebase_callback, this);
  1210. }
  1211. try {
  1212. jackbridge_transport_start(fClient);
  1213. } catch(...) {}
  1214. }
  1215. }
  1216. void transportPause() noexcept override
  1217. {
  1218. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1219. return CarlaEngine::transportPause();
  1220. if (fClient != nullptr)
  1221. {
  1222. try {
  1223. jackbridge_transport_stop(fClient);
  1224. } catch(...) {}
  1225. }
  1226. }
  1227. void transportBPM(const double bpm) noexcept override
  1228. {
  1229. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK || fTimebaseMaster)
  1230. return CarlaEngine::transportBPM(bpm);
  1231. if (fClient == nullptr)
  1232. return;
  1233. jack_position_t jpos;
  1234. // invalidate
  1235. jpos.unique_1 = 1;
  1236. jpos.unique_2 = 2;
  1237. jackbridge_transport_query(fClient, &jpos);
  1238. if (jpos.unique_1 == jpos.unique_2 && (jpos.valid & JackPositionBBT) != 0)
  1239. {
  1240. carla_stdout("NOTE: Changing BPM without being JACK timebase master");
  1241. jpos.beats_per_minute = bpm;
  1242. try {
  1243. jackbridge_transport_reposition(fClient, &jpos);
  1244. } catch(...) {}
  1245. }
  1246. }
  1247. void transportRelocate(const uint64_t frame) noexcept override
  1248. {
  1249. if (pData->options.transportMode != ENGINE_TRANSPORT_MODE_JACK)
  1250. return CarlaEngine::transportRelocate(frame);
  1251. if (fClient != nullptr)
  1252. {
  1253. try {
  1254. jackbridge_transport_locate(fClient, static_cast<jack_nframes_t>(frame));
  1255. } catch(...) {}
  1256. }
  1257. }
  1258. // -------------------------------------------------------------------
  1259. // Patchbay stuff
  1260. const char* const* getPatchbayConnections(const bool external) const override
  1261. {
  1262. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr, nullptr);
  1263. carla_debug("CarlaEngineJack::getPatchbayConnections(%s)", bool2str(external));
  1264. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1265. return CarlaEngine::getPatchbayConnections(external);
  1266. CarlaStringList connList;
  1267. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  1268. {
  1269. for (int i=0; ports[i] != nullptr; ++i)
  1270. {
  1271. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, ports[i]));
  1272. const char* const fullPortName(ports[i]);
  1273. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1274. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  1275. {
  1276. for (int j=0; connections[j] != nullptr; ++j)
  1277. {
  1278. connList.append(fullPortName);
  1279. connList.append(connections[j]);
  1280. }
  1281. jackbridge_free(connections);
  1282. }
  1283. }
  1284. jackbridge_free(ports);
  1285. }
  1286. if (connList.count() == 0)
  1287. return nullptr;
  1288. fRetConns = connList.toCharStringListPtr();
  1289. return fRetConns;
  1290. }
  1291. void restorePatchbayConnection(const bool external, const char* const connSource, const char* const connTarget, const bool sendCallback) override
  1292. {
  1293. CARLA_SAFE_ASSERT_RETURN(fClient != nullptr,);
  1294. CARLA_SAFE_ASSERT_RETURN(connSource != nullptr && connSource[0] != '\0',);
  1295. CARLA_SAFE_ASSERT_RETURN(connTarget != nullptr && connTarget[0] != '\0',);
  1296. carla_debug("CarlaEngineJack::restorePatchbayConnection(\"%s\", \"%s\")", connSource, connTarget);
  1297. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY && ! external)
  1298. return CarlaEngine::restorePatchbayConnection(external, connSource, connTarget, sendCallback);
  1299. if (const jack_port_t* const port = jackbridge_port_by_name(fClient, connSource))
  1300. {
  1301. if (jackbridge_port_by_name(fClient, connTarget) == nullptr)
  1302. return;
  1303. if (! jackbridge_port_connected_to(port, connTarget))
  1304. jackbridge_connect(fClient, connSource, connTarget);
  1305. }
  1306. }
  1307. #endif
  1308. // -------------------------------------------------------------------
  1309. protected:
  1310. void handleJackBufferSizeCallback(const uint32_t newBufferSize)
  1311. {
  1312. if (pData->bufferSize == newBufferSize)
  1313. return;
  1314. pData->bufferSize = newBufferSize;
  1315. bufferSizeChanged(newBufferSize);
  1316. }
  1317. void handleJackSampleRateCallback(const double newSampleRate)
  1318. {
  1319. if (carla_isEqual(pData->sampleRate, newSampleRate))
  1320. return;
  1321. pData->sampleRate = newSampleRate;
  1322. sampleRateChanged(newSampleRate);
  1323. }
  1324. void handleJackFreewheelCallback(const bool isFreewheel)
  1325. {
  1326. if (fFreewheel == isFreewheel)
  1327. return;
  1328. fFreewheel = isFreewheel;
  1329. offlineModeChanged(isFreewheel);
  1330. }
  1331. void handleJackProcessCallback(const uint32_t nframes)
  1332. {
  1333. const PendingRtEventsRunner prt(this, nframes);
  1334. CARLA_SAFE_ASSERT_INT2_RETURN(nframes == pData->bufferSize, nframes, pData->bufferSize,);
  1335. #ifdef BUILD_BRIDGE
  1336. CarlaPlugin* const plugin(pData->plugins[0].plugin);
  1337. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1338. {
  1339. plugin->initBuffers();
  1340. processPlugin(plugin, nframes);
  1341. plugin->unlock();
  1342. }
  1343. #else
  1344. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1345. {
  1346. if (pData->aboutToClose)
  1347. {
  1348. if (float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes))
  1349. carla_zeroFloats(audioOut1, nframes);
  1350. if (float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes))
  1351. carla_zeroFloats(audioOut2, nframes);
  1352. }
  1353. else if (pData->curPluginCount == 0)
  1354. {
  1355. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1356. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1357. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1358. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1359. // assert buffers
  1360. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  1361. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  1362. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  1363. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  1364. // pass-through
  1365. carla_copyFloats(audioOut1, audioIn1, nframes);
  1366. carla_copyFloats(audioOut2, audioIn2, nframes);
  1367. // TODO pass-through MIDI as well
  1368. if (void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes))
  1369. jackbridge_midi_clear_buffer(eventOut);
  1370. return;
  1371. }
  1372. }
  1373. if (pData->options.processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1374. {
  1375. for (uint i=0; i < pData->curPluginCount; ++i)
  1376. {
  1377. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1378. if (plugin != nullptr && plugin->isEnabled() && plugin->tryLock(fFreewheel))
  1379. {
  1380. plugin->initBuffers();
  1381. processPlugin(plugin, nframes);
  1382. plugin->unlock();
  1383. }
  1384. }
  1385. }
  1386. else if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1387. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1388. {
  1389. CARLA_SAFE_ASSERT_RETURN(pData->events.in != nullptr,);
  1390. CARLA_SAFE_ASSERT_RETURN(pData->events.out != nullptr,);
  1391. // get buffers from jack
  1392. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn1], nframes);
  1393. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioIn2], nframes);
  1394. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut1], nframes);
  1395. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[kRackPortAudioOut2], nframes);
  1396. void* const eventIn = jackbridge_port_get_buffer(fRackPorts[kRackPortEventIn], nframes);
  1397. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[kRackPortEventOut], nframes);
  1398. // assert buffers
  1399. CARLA_SAFE_ASSERT_RETURN(audioIn1 != nullptr,);
  1400. CARLA_SAFE_ASSERT_RETURN(audioIn2 != nullptr,);
  1401. CARLA_SAFE_ASSERT_RETURN(audioOut1 != nullptr,);
  1402. CARLA_SAFE_ASSERT_RETURN(audioOut2 != nullptr,);
  1403. // create audio buffers
  1404. const float* inBuf[2] = { audioIn1, audioIn2 };
  1405. /**/ float* outBuf[2] = { audioOut1, audioOut2 };
  1406. // initialize events
  1407. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  1408. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  1409. if (eventIn != nullptr)
  1410. {
  1411. ushort engineEventIndex = 0;
  1412. jack_midi_event_t jackEvent;
  1413. const uint32_t jackEventCount(jackbridge_midi_get_event_count(eventIn));
  1414. for (uint32_t jackEventIndex=0; jackEventIndex < jackEventCount; ++jackEventIndex)
  1415. {
  1416. if (! jackbridge_midi_event_get(&jackEvent, eventIn, jackEventIndex))
  1417. continue;
  1418. CARLA_SAFE_ASSERT_CONTINUE(jackEvent.size < 0xFF /* uint8_t max */);
  1419. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  1420. engineEvent.time = jackEvent.time;
  1421. engineEvent.fillFromMidiData(static_cast<uint8_t>(jackEvent.size), jackEvent.buffer, 0);
  1422. if (engineEventIndex >= kMaxEngineEventInternalCount)
  1423. break;
  1424. }
  1425. }
  1426. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  1427. pData->graph.processRack(pData, inBuf, outBuf, nframes);
  1428. else
  1429. pData->graph.process(pData, inBuf, outBuf, nframes);
  1430. // output control
  1431. if (eventOut != nullptr)
  1432. {
  1433. jackbridge_midi_clear_buffer(eventOut);
  1434. uint8_t size = 0;
  1435. uint8_t mdata[3] = { 0, 0, 0 };
  1436. uint8_t mdataTmp[EngineMidiEvent::kDataSize];
  1437. const uint8_t* mdataPtr;
  1438. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  1439. {
  1440. const EngineEvent& engineEvent(pData->events.out[i]);
  1441. /**/ if (engineEvent.type == kEngineEventTypeNull)
  1442. {
  1443. break;
  1444. }
  1445. else if (engineEvent.type == kEngineEventTypeControl)
  1446. {
  1447. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  1448. size = ctrlEvent.convertToMidiData(engineEvent.channel, mdata);
  1449. mdataPtr = mdata;
  1450. }
  1451. else if (engineEvent.type == kEngineEventTypeMidi)
  1452. {
  1453. const EngineMidiEvent& midiEvent(engineEvent.midi);
  1454. size = midiEvent.size;
  1455. CARLA_SAFE_ASSERT_CONTINUE(size > 0);
  1456. if (size > EngineMidiEvent::kDataSize)
  1457. {
  1458. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.dataExt != nullptr);
  1459. mdataPtr = midiEvent.dataExt;
  1460. }
  1461. else
  1462. {
  1463. // set first byte
  1464. mdataTmp[0] = static_cast<uint8_t>(midiEvent.data[0] | (engineEvent.channel & MIDI_CHANNEL_BIT));
  1465. // copy rest
  1466. carla_copy<uint8_t>(mdataTmp+1, midiEvent.data+1, size-1);
  1467. // done
  1468. mdataPtr = mdataTmp;
  1469. }
  1470. }
  1471. else
  1472. {
  1473. continue;
  1474. }
  1475. if (size > 0)
  1476. jackbridge_midi_event_write(eventOut, engineEvent.time, mdataPtr, size);
  1477. }
  1478. }
  1479. }
  1480. if (fTimebaseMaster)
  1481. {
  1482. const bool playing = jackbridge_transport_query(fClient, nullptr) == JackTransportRolling;
  1483. if (fTimebaseRolling != playing)
  1484. {
  1485. fTimebaseRolling = playing;
  1486. pData->timeInfo.playing = playing;
  1487. }
  1488. }
  1489. #endif // ! BUILD_BRIDGE
  1490. }
  1491. void handleJackLatencyCallback(const jack_latency_callback_mode_t /*mode*/)
  1492. {
  1493. // TODO
  1494. }
  1495. #ifndef BUILD_BRIDGE
  1496. void handleJackTimebaseCallback(jack_nframes_t nframes, jack_position_t* const pos, const int new_pos)
  1497. {
  1498. if (new_pos)
  1499. pData->time.setNeedsReset();
  1500. pData->timeInfo.playing = fTimebaseRolling;
  1501. pData->timeInfo.frame = pos->frame;
  1502. pData->timeInfo.usecs = pos->usecs;
  1503. pData->time.fillJackTimeInfo(pos, nframes);
  1504. }
  1505. void handleJackClientRegistrationCallback(const char* const name, const bool reg)
  1506. {
  1507. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',);
  1508. // ignore this if on internal patchbay mode
  1509. if (! fExternalPatchbay) return;
  1510. // do nothing on client registration, wait for first port
  1511. if (reg) return;
  1512. const uint groupId(fUsedGroups.getGroupId(name));
  1513. // clients might have been registered without ports
  1514. if (groupId == 0) return;
  1515. GroupNameToId groupNameToId;
  1516. groupNameToId.setData(groupId, name);
  1517. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED, groupNameToId.group, 0, 0, 0.0f, nullptr);
  1518. fUsedGroups.list.removeOne(groupNameToId);
  1519. }
  1520. void handleJackPortRegistrationCallback(const jack_port_id_t port, const bool reg)
  1521. {
  1522. // ignore this if on internal patchbay mode
  1523. if (! fExternalPatchbay) return;
  1524. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1525. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1526. const char* const fullPortName(jackbridge_port_name(jackPort));
  1527. CARLA_SAFE_ASSERT_RETURN(fullPortName != nullptr && fullPortName[0] != '\0',);
  1528. if (reg)
  1529. {
  1530. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1531. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1532. bool found;
  1533. CarlaString groupName(fullPortName);
  1534. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1535. CARLA_SAFE_ASSERT_RETURN(found,);
  1536. const int jackPortFlags(jackbridge_port_flags(jackPort));
  1537. uint groupId(fUsedGroups.getGroupId(groupName));
  1538. if (groupId == 0)
  1539. {
  1540. groupId = ++fUsedGroups.lastId;
  1541. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  1542. GroupNameToId groupNameToId;
  1543. groupNameToId.setData(groupId, groupName);
  1544. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, icon, -1, 0.0f, groupNameToId.name);
  1545. fNewGroups.append(groupId);
  1546. fUsedGroups.list.append(groupNameToId);
  1547. }
  1548. addPatchbayJackPort(groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  1549. }
  1550. else
  1551. {
  1552. const PortNameToId& portNameToId(fUsedPorts.getPortNameToId(fullPortName));
  1553. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  1554. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  1555. if (portNameToId.group <= 0 || portNameToId.port <= 0) return;
  1556. callback(ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, nullptr);
  1557. fUsedPorts.list.removeOne(portNameToId);
  1558. }
  1559. }
  1560. void handleJackPortConnectCallback(const jack_port_id_t a, const jack_port_id_t b, const bool connect)
  1561. {
  1562. // ignore this if on internal patchbay mode
  1563. if (! fExternalPatchbay) return;
  1564. const jack_port_t* const jackPortA(jackbridge_port_by_id(fClient, a));
  1565. CARLA_SAFE_ASSERT_RETURN(jackPortA != nullptr,);
  1566. const jack_port_t* const jackPortB(jackbridge_port_by_id(fClient, b));
  1567. CARLA_SAFE_ASSERT_RETURN(jackPortB != nullptr,);
  1568. const char* const fullPortNameA(jackbridge_port_name(jackPortA));
  1569. CARLA_SAFE_ASSERT_RETURN(fullPortNameA != nullptr && fullPortNameA[0] != '\0',);
  1570. const char* const fullPortNameB(jackbridge_port_name(jackPortB));
  1571. CARLA_SAFE_ASSERT_RETURN(fullPortNameB != nullptr && fullPortNameB[0] != '\0',);
  1572. const PortNameToId& portNameToIdA(fUsedPorts.getPortNameToId(fullPortNameA));
  1573. const PortNameToId& portNameToIdB(fUsedPorts.getPortNameToId(fullPortNameB));
  1574. /* NOTE: Due to JACK2 async behaviour the port we get here might be the same of a previous rename-plugin request.
  1575. See the comment on CarlaEngineJack::renamePlugin() for more information. */
  1576. if (portNameToIdA.group <= 0 || portNameToIdA.port <= 0) return;
  1577. if (portNameToIdB.group <= 0 || portNameToIdB.port <= 0) return;
  1578. if (connect)
  1579. {
  1580. char strBuf[STR_MAX+1];
  1581. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1582. strBuf[STR_MAX] = '\0';
  1583. ConnectionToId connectionToId;
  1584. connectionToId.setData(++fUsedConnections.lastId, portNameToIdA.group, portNameToIdA.port, portNameToIdB.group, portNameToIdB.port);
  1585. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  1586. fUsedConnections.list.append(connectionToId);
  1587. }
  1588. else
  1589. {
  1590. ConnectionToId connectionToId = { 0, 0, 0, 0, 0 };
  1591. bool found = false;
  1592. {
  1593. const CarlaMutexLocker cml(fUsedConnections.mutex);
  1594. for (LinkedList<ConnectionToId>::Itenerator it = fUsedConnections.list.begin2(); it.valid(); it.next())
  1595. {
  1596. connectionToId = it.getValue(connectionToId);
  1597. CARLA_SAFE_ASSERT_CONTINUE(connectionToId.id != 0);
  1598. if (connectionToId.groupA == portNameToIdA.group && connectionToId.portA == portNameToIdA.port &&
  1599. connectionToId.groupB == portNameToIdB.group && connectionToId.portB == portNameToIdB.port)
  1600. {
  1601. found = true;
  1602. fUsedConnections.list.remove(it);
  1603. break;
  1604. }
  1605. }
  1606. }
  1607. if (found)
  1608. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED, connectionToId.id, 0, 0, 0.0f, nullptr);
  1609. }
  1610. }
  1611. void handleJackPortRenameCallback(const jack_port_id_t port, const char* const oldFullName, const char* const newFullName)
  1612. {
  1613. // ignore this if on internal patchbay mode
  1614. if (! fExternalPatchbay) return;
  1615. CARLA_SAFE_ASSERT_RETURN(oldFullName != nullptr && oldFullName[0] != '\0',);
  1616. CARLA_SAFE_ASSERT_RETURN(newFullName != nullptr && newFullName[0] != '\0',);
  1617. const jack_port_t* const jackPort(jackbridge_port_by_id(fClient, port));
  1618. CARLA_SAFE_ASSERT_RETURN(jackPort != nullptr,);
  1619. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1620. CARLA_SAFE_ASSERT_RETURN(shortPortName != nullptr && shortPortName[0] != '\0',);
  1621. bool found;
  1622. CarlaString groupName(newFullName);
  1623. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1624. CARLA_SAFE_ASSERT_RETURN(found,);
  1625. const uint groupId(fUsedGroups.getGroupId(groupName));
  1626. CARLA_SAFE_ASSERT_RETURN(groupId > 0,);
  1627. for (LinkedList<PortNameToId>::Itenerator it = fUsedPorts.list.begin2(); it.valid(); it.next())
  1628. {
  1629. static PortNameToId portNameFallback = { 0, 0, { '\0' }, { '\0' } };
  1630. PortNameToId& portNameToId(it.getValue(portNameFallback));
  1631. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group != 0);
  1632. if (std::strncmp(portNameToId.fullName, oldFullName, STR_MAX) == 0)
  1633. {
  1634. CARLA_SAFE_ASSERT_CONTINUE(portNameToId.group == groupId);
  1635. portNameToId.rename(shortPortName, newFullName);
  1636. callback(ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED, portNameToId.group, static_cast<int>(portNameToId.port), 0, 0.0f, portNameToId.name);
  1637. break;
  1638. }
  1639. }
  1640. }
  1641. #endif
  1642. void handleJackShutdownCallback()
  1643. {
  1644. #ifndef BUILD_BRIDGE
  1645. signalThreadShouldExit();
  1646. #endif
  1647. const PendingRtEventsRunner prt(this, pData->bufferSize);
  1648. for (uint i=0; i < pData->curPluginCount; ++i)
  1649. {
  1650. if (CarlaPlugin* const plugin = pData->plugins[i].plugin)
  1651. {
  1652. plugin->tryLock(true);
  1653. if (CarlaEngineJackClient* const client = (CarlaEngineJackClient*)plugin->getEngineClient())
  1654. client->invalidate();
  1655. plugin->unlock();
  1656. }
  1657. }
  1658. fClient = nullptr;
  1659. #ifndef BUILD_BRIDGE
  1660. carla_zeroPointers(fRackPorts, kRackPortCount);
  1661. #endif
  1662. callback(ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  1663. }
  1664. // -------------------------------------------------------------------
  1665. void handlePluginJackShutdownCallback(CarlaPlugin* const plugin)
  1666. {
  1667. CarlaEngineJackClient* const engineClient((CarlaEngineJackClient*)plugin->getEngineClient());
  1668. CARLA_SAFE_ASSERT_RETURN(engineClient != nullptr,);
  1669. plugin->tryLock(true);
  1670. engineClient->invalidate();
  1671. plugin->unlock();
  1672. //if (pData->nextAction.pluginId == plugin->getId())
  1673. // pData->nextAction.clearAndReset();
  1674. callback(ENGINE_CALLBACK_PLUGIN_UNAVAILABLE, plugin->getId(), 0, 0, 0.0f, "Killed by JACK");
  1675. }
  1676. // -------------------------------------------------------------------
  1677. private:
  1678. jack_client_t* fClient;
  1679. bool fExternalPatchbay;
  1680. bool fFreewheel;
  1681. // -------------------------------------------------------------------
  1682. #ifdef BUILD_BRIDGE
  1683. bool fIsRunning;
  1684. #else
  1685. enum RackPorts {
  1686. kRackPortAudioIn1 = 0,
  1687. kRackPortAudioIn2 = 1,
  1688. kRackPortAudioOut1 = 2,
  1689. kRackPortAudioOut2 = 3,
  1690. kRackPortEventIn = 4,
  1691. kRackPortEventOut = 5,
  1692. kRackPortCount = 6
  1693. };
  1694. jack_port_t* fRackPorts[kRackPortCount];
  1695. bool fTimebaseMaster;
  1696. bool fTimebaseRolling;
  1697. PatchbayGroupList fUsedGroups;
  1698. PatchbayPortList fUsedPorts;
  1699. PatchbayConnectionList fUsedConnections;
  1700. LinkedList<uint> fNewGroups;
  1701. mutable CharStringListPtr fRetConns;
  1702. bool findPluginIdAndIcon(const char* const clientName, int& pluginId, PatchbayIcon& icon) noexcept
  1703. {
  1704. carla_debug("CarlaEngineJack::findPluginIdAndIcon(\"%s\", ...)", clientName);
  1705. // TODO - this currently only works in multi-client mode
  1706. if (pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS)
  1707. return false;
  1708. for (uint i=0; i < pData->curPluginCount; ++i)
  1709. {
  1710. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1711. if (plugin == nullptr || ! plugin->isEnabled())
  1712. continue;
  1713. const CarlaEngineJackClient* const engineClient((const CarlaEngineJackClient*)plugin->getEngineClient());
  1714. CARLA_SAFE_ASSERT_CONTINUE(engineClient != nullptr);
  1715. const char* const engineClientName(engineClient->getJackClientName());
  1716. CARLA_SAFE_ASSERT_CONTINUE(engineClientName != nullptr && engineClientName[0] != '\0');
  1717. if (std::strcmp(clientName, engineClientName) != 0)
  1718. continue;
  1719. pluginId = static_cast<int>(i);
  1720. icon = PATCHBAY_ICON_PLUGIN;
  1721. if (const char* const pluginIcon = plugin->getIconName())
  1722. {
  1723. if (pluginIcon[0] == '\0')
  1724. pass();
  1725. else if (std::strcmp(pluginIcon, "app") == 0 || std::strcmp(pluginIcon, "application") == 0)
  1726. icon = PATCHBAY_ICON_APPLICATION;
  1727. else if (std::strcmp(pluginIcon, "plugin") == 0)
  1728. icon = PATCHBAY_ICON_PLUGIN;
  1729. else if (std::strcmp(pluginIcon, "hardware") == 0)
  1730. icon = PATCHBAY_ICON_HARDWARE;
  1731. else if (std::strcmp(pluginIcon, "carla") == 0)
  1732. icon = PATCHBAY_ICON_CARLA;
  1733. else if (std::strcmp(pluginIcon, "distrho") == 0)
  1734. icon = PATCHBAY_ICON_DISTRHO;
  1735. else if (std::strcmp(pluginIcon, "file") == 0)
  1736. icon = PATCHBAY_ICON_FILE;
  1737. }
  1738. return true;
  1739. }
  1740. return false;
  1741. }
  1742. void initJackPatchbay(const char* const ourName)
  1743. {
  1744. CARLA_SAFE_ASSERT_RETURN(pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY || fExternalPatchbay,);
  1745. CARLA_SAFE_ASSERT_RETURN(ourName != nullptr && ourName[0] != '\0',);
  1746. CarlaStringList parsedGroups;
  1747. // add our client first
  1748. {
  1749. parsedGroups.append(ourName);
  1750. GroupNameToId groupNameToId;
  1751. groupNameToId.setData(++fUsedGroups.lastId, ourName);
  1752. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, PATCHBAY_ICON_CARLA, -1, 0.0f, groupNameToId.name);
  1753. fUsedGroups.list.append(groupNameToId);
  1754. }
  1755. // query all jack ports
  1756. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, 0))
  1757. {
  1758. for (int i=0; ports[i] != nullptr; ++i)
  1759. {
  1760. const char* const fullPortName(ports[i]);
  1761. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  1762. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  1763. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1764. const char* const shortPortName(jackbridge_port_short_name(jackPort));
  1765. CARLA_SAFE_ASSERT_CONTINUE(shortPortName != nullptr && shortPortName[0] != '\0');
  1766. const int jackPortFlags(jackbridge_port_flags(jackPort));
  1767. uint groupId = 0;
  1768. bool found;
  1769. CarlaString groupName(fullPortName);
  1770. groupName.truncate(groupName.rfind(shortPortName, &found)-1);
  1771. CARLA_SAFE_ASSERT_CONTINUE(found);
  1772. if (parsedGroups.contains(groupName))
  1773. {
  1774. groupId = fUsedGroups.getGroupId(groupName);
  1775. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  1776. }
  1777. else
  1778. {
  1779. groupId = ++fUsedGroups.lastId;
  1780. parsedGroups.append(groupName);
  1781. int pluginId = -1;
  1782. PatchbayIcon icon = (jackPortFlags & JackPortIsPhysical) ? PATCHBAY_ICON_HARDWARE : PATCHBAY_ICON_APPLICATION;
  1783. findPluginIdAndIcon(groupName, pluginId, icon);
  1784. GroupNameToId groupNameToId;
  1785. groupNameToId.setData(groupId, groupName);
  1786. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, groupNameToId.group, icon, pluginId, 0.0f, groupNameToId.name);
  1787. fUsedGroups.list.append(groupNameToId);
  1788. }
  1789. addPatchbayJackPort(groupId, jackPort, shortPortName, fullPortName, jackPortFlags);
  1790. }
  1791. jackbridge_free(ports);
  1792. }
  1793. // query connections, after all ports are in place
  1794. if (const char** const ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  1795. {
  1796. char strBuf[STR_MAX+1];
  1797. for (int i=0; ports[i] != nullptr; ++i)
  1798. {
  1799. const char* const fullPortName(ports[i]);
  1800. CARLA_SAFE_ASSERT_CONTINUE(fullPortName != nullptr && fullPortName[0] != '\0');
  1801. const jack_port_t* const jackPort(jackbridge_port_by_name(fClient, fullPortName));
  1802. CARLA_SAFE_ASSERT_CONTINUE(jackPort != nullptr);
  1803. const PortNameToId& thisPort(fUsedPorts.getPortNameToId(fullPortName));
  1804. CARLA_SAFE_ASSERT_CONTINUE(thisPort.group > 0);
  1805. CARLA_SAFE_ASSERT_CONTINUE(thisPort.port > 0);
  1806. if (const char** const connections = jackbridge_port_get_all_connections(fClient, jackPort))
  1807. {
  1808. for (int j=0; connections[j] != nullptr; ++j)
  1809. {
  1810. const char* const connection(connections[j]);
  1811. CARLA_SAFE_ASSERT_CONTINUE(connection != nullptr && connection[0] != '\0');
  1812. const PortNameToId& targetPort(fUsedPorts.getPortNameToId(connection));
  1813. CARLA_SAFE_ASSERT_CONTINUE(targetPort.group > 0);
  1814. CARLA_SAFE_ASSERT_CONTINUE(targetPort.port > 0);
  1815. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  1816. strBuf[STR_MAX] = '\0';
  1817. ConnectionToId connectionToId;
  1818. connectionToId.setData(++fUsedConnections.lastId, thisPort.group, thisPort.port, targetPort.group, targetPort.port);
  1819. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  1820. fUsedConnections.list.append(connectionToId);
  1821. }
  1822. jackbridge_free(connections);
  1823. }
  1824. }
  1825. jackbridge_free(ports);
  1826. }
  1827. }
  1828. void addPatchbayJackPort(const uint groupId, const jack_port_t* const jackPort, const char* const shortPortName, const char* const fullPortName, const int jackPortFlags)
  1829. {
  1830. bool portIsInput = (jackPortFlags & JackPortIsInput);
  1831. bool portIsAudio = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_AUDIO_TYPE) == 0);
  1832. bool portIsMIDI = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_MIDI_TYPE) == 0);
  1833. bool portIsCV = false;
  1834. bool portIsOSC = false;
  1835. if (const jack_uuid_t uuid = jackbridge_port_uuid(jackPort))
  1836. {
  1837. char* value = nullptr;
  1838. char* type = nullptr;
  1839. if (jackbridge_get_property(uuid, JACKEY_SIGNAL_TYPE, &value, &type)
  1840. && value != nullptr
  1841. && type != nullptr
  1842. && std::strcmp(type, "text/plain") == 0)
  1843. {
  1844. portIsCV = (std::strcmp(value, "CV") == 0);
  1845. portIsOSC = (std::strcmp(value, "OSC") == 0);
  1846. }
  1847. }
  1848. uint canvasPortFlags = 0x0;
  1849. canvasPortFlags |= portIsInput ? PATCHBAY_PORT_IS_INPUT : 0x0;
  1850. /**/ if (portIsCV)
  1851. canvasPortFlags |= PATCHBAY_PORT_TYPE_CV;
  1852. else if (portIsOSC)
  1853. canvasPortFlags |= PATCHBAY_PORT_TYPE_OSC;
  1854. else if (portIsAudio)
  1855. canvasPortFlags |= PATCHBAY_PORT_TYPE_AUDIO;
  1856. else if (portIsMIDI)
  1857. canvasPortFlags |= PATCHBAY_PORT_TYPE_MIDI;
  1858. PortNameToId portNameToId;
  1859. portNameToId.setData(groupId, ++fUsedPorts.lastId, shortPortName, fullPortName);
  1860. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, portNameToId.group, static_cast<int>(portNameToId.port), static_cast<int>(canvasPortFlags), 0.0f, portNameToId.name);
  1861. fUsedPorts.list.append(portNameToId);
  1862. }
  1863. #endif
  1864. // -------------------------------------------------------------------
  1865. void processPlugin(CarlaPlugin* const plugin, const uint32_t nframes)
  1866. {
  1867. const uint32_t audioInCount(plugin->getAudioInCount());
  1868. const uint32_t audioOutCount(plugin->getAudioOutCount());
  1869. const uint32_t cvInCount(plugin->getCVInCount());
  1870. const uint32_t cvOutCount(plugin->getCVOutCount());
  1871. const float* audioIn[audioInCount];
  1872. /* */ float* audioOut[audioOutCount];
  1873. const float* cvIn[cvInCount];
  1874. /* */ float* cvOut[cvOutCount];
  1875. for (uint32_t i=0; i < audioInCount; ++i)
  1876. {
  1877. CarlaEngineAudioPort* const port(plugin->getAudioInPort(i));
  1878. audioIn[i] = port->getBuffer();
  1879. }
  1880. for (uint32_t i=0; i < audioOutCount; ++i)
  1881. {
  1882. CarlaEngineAudioPort* const port(plugin->getAudioOutPort(i));
  1883. audioOut[i] = port->getBuffer();
  1884. }
  1885. for (uint32_t i=0; i < cvInCount; ++i)
  1886. {
  1887. CarlaEngineCVPort* const port(plugin->getCVInPort(i));
  1888. cvIn[i] = port->getBuffer();
  1889. }
  1890. for (uint32_t i=0; i < cvOutCount; ++i)
  1891. {
  1892. CarlaEngineCVPort* const port(plugin->getCVOutPort(i));
  1893. cvOut[i] = port->getBuffer();
  1894. }
  1895. float inPeaks[2] = { 0.0f };
  1896. float outPeaks[2] = { 0.0f };
  1897. for (uint32_t i=0; i < audioInCount && i < 2; ++i)
  1898. {
  1899. for (uint32_t j=0; j < nframes; ++j)
  1900. {
  1901. const float absV(std::abs(audioIn[i][j]));
  1902. if (absV > inPeaks[i])
  1903. inPeaks[i] = absV;
  1904. }
  1905. }
  1906. plugin->process(audioIn, audioOut, cvIn, cvOut, nframes);
  1907. for (uint32_t i=0; i < audioOutCount && i < 2; ++i)
  1908. {
  1909. for (uint32_t j=0; j < nframes; ++j)
  1910. {
  1911. const float absV(std::abs(audioOut[i][j]));
  1912. if (absV > outPeaks[i])
  1913. outPeaks[i] = absV;
  1914. }
  1915. }
  1916. setPluginPeaks(plugin->getId(), inPeaks, outPeaks);
  1917. }
  1918. #ifndef BUILD_BRIDGE
  1919. // -------------------------------------------------------------------
  1920. struct PostPonedJackEvent {
  1921. enum Type {
  1922. kTypeNull = 0,
  1923. kTypeClientRegister,
  1924. kTypePortRegister,
  1925. kTypePortConnect,
  1926. kTypePortRename
  1927. };
  1928. Type type;
  1929. bool action; // register or connect
  1930. jack_port_id_t port1;
  1931. jack_port_id_t port2;
  1932. char name1[STR_MAX+1];
  1933. char name2[STR_MAX+1];
  1934. };
  1935. LinkedList<PostPonedJackEvent> fPostPonedEvents;
  1936. CarlaMutex fPostPonedEventsMutex;
  1937. void postPoneJackCallback(const PostPonedJackEvent& ev)
  1938. {
  1939. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  1940. fPostPonedEvents.append(ev);
  1941. }
  1942. void run() override
  1943. {
  1944. LinkedList<PostPonedJackEvent> events;
  1945. LinkedList<uint> newPlugins;
  1946. PostPonedJackEvent nullEvent;
  1947. carla_zeroStruct(nullEvent);
  1948. for (; ! shouldThreadExit();)
  1949. {
  1950. {
  1951. const CarlaMutexLocker cml(fPostPonedEventsMutex);
  1952. if (fPostPonedEvents.count() > 0)
  1953. fPostPonedEvents.moveTo(events);
  1954. if (fNewGroups.count() > 0)
  1955. fNewGroups.moveTo(newPlugins);
  1956. }
  1957. if (fClient == nullptr)
  1958. break;
  1959. if (events.count() == 0 && newPlugins.count() == 0)
  1960. {
  1961. carla_msleep(200);
  1962. continue;
  1963. }
  1964. for (LinkedList<PostPonedJackEvent>::Itenerator it = events.begin2(); it.valid(); it.next())
  1965. {
  1966. const PostPonedJackEvent& ev(it.getValue(nullEvent));
  1967. CARLA_SAFE_ASSERT_CONTINUE(ev.type != PostPonedJackEvent::kTypeNull);
  1968. switch (ev.type)
  1969. {
  1970. case PostPonedJackEvent::kTypeNull:
  1971. break;
  1972. case PostPonedJackEvent::kTypeClientRegister:
  1973. handleJackClientRegistrationCallback(ev.name1, ev.action);
  1974. break;
  1975. case PostPonedJackEvent::kTypePortRegister:
  1976. handleJackPortRegistrationCallback(ev.port1, ev.action);
  1977. break;
  1978. case PostPonedJackEvent::kTypePortConnect:
  1979. handleJackPortConnectCallback(ev.port1, ev.port2, ev.action);
  1980. break;
  1981. case PostPonedJackEvent::kTypePortRename:
  1982. handleJackPortRenameCallback(ev.port1, ev.name1, ev.name2);
  1983. break;
  1984. }
  1985. }
  1986. for (LinkedList<uint>::Itenerator it = newPlugins.begin2(); it.valid(); it.next())
  1987. {
  1988. const uint groupId(it.getValue(0));
  1989. CARLA_SAFE_ASSERT_CONTINUE(groupId > 0);
  1990. const char* const groupName(fUsedGroups.getGroupName(groupId));
  1991. CARLA_SAFE_ASSERT_CONTINUE(groupName != nullptr && groupName[0] != '\0');
  1992. int pluginId = -1;
  1993. PatchbayIcon icon = PATCHBAY_ICON_PLUGIN;
  1994. if (findPluginIdAndIcon(groupName, pluginId, icon))
  1995. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED, groupId, icon, pluginId, 0.0f, nullptr);
  1996. }
  1997. events.clear();
  1998. newPlugins.clear();
  1999. }
  2000. events.clear();
  2001. newPlugins.clear();
  2002. }
  2003. #endif // BUILD_BRIDGE
  2004. // -------------------------------------------------------------------
  2005. // disable -Wattributes warnings
  2006. #if defined(__clang__)
  2007. # pragma clang diagnostic push
  2008. # pragma clang diagnostic ignored "-Wattributes"
  2009. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  2010. # pragma GCC diagnostic push
  2011. # pragma GCC diagnostic ignored "-Wattributes"
  2012. #endif
  2013. #define handlePtr ((CarlaEngineJack*)arg)
  2014. static void JACKBRIDGE_API carla_jack_thread_init_callback(void*)
  2015. {
  2016. #ifdef __SSE2_MATH__
  2017. // Set FTZ and DAZ flags
  2018. _mm_setcsr(_mm_getcsr() | 0x8040);
  2019. #endif
  2020. }
  2021. static int JACKBRIDGE_API carla_jack_bufsize_callback(jack_nframes_t newBufferSize, void* arg)
  2022. {
  2023. handlePtr->handleJackBufferSizeCallback(newBufferSize);
  2024. return 0;
  2025. }
  2026. static int JACKBRIDGE_API carla_jack_srate_callback(jack_nframes_t newSampleRate, void* arg)
  2027. {
  2028. handlePtr->handleJackSampleRateCallback(newSampleRate);
  2029. return 0;
  2030. }
  2031. static void JACKBRIDGE_API carla_jack_freewheel_callback(int starting, void* arg)
  2032. {
  2033. handlePtr->handleJackFreewheelCallback(bool(starting));
  2034. }
  2035. static void JACKBRIDGE_API carla_jack_latency_callback(jack_latency_callback_mode_t mode, void* arg)
  2036. {
  2037. handlePtr->handleJackLatencyCallback(mode);
  2038. }
  2039. static int JACKBRIDGE_API carla_jack_process_callback(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  2040. {
  2041. handlePtr->handleJackProcessCallback(nframes);
  2042. return 0;
  2043. }
  2044. #ifndef BUILD_BRIDGE
  2045. 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")))
  2046. {
  2047. handlePtr->handleJackTimebaseCallback(nframes, pos, new_pos);
  2048. }
  2049. static void JACKBRIDGE_API carla_jack_client_registration_callback(const char* name, int reg, void* arg)
  2050. {
  2051. PostPonedJackEvent ev;
  2052. carla_zeroStruct(ev);
  2053. ev.type = PostPonedJackEvent::kTypeClientRegister;
  2054. ev.action = (reg != 0);
  2055. std::strncpy(ev.name1, name, STR_MAX);
  2056. handlePtr->postPoneJackCallback(ev);
  2057. }
  2058. static void JACKBRIDGE_API carla_jack_port_registration_callback(jack_port_id_t port, int reg, void* arg)
  2059. {
  2060. PostPonedJackEvent ev;
  2061. carla_zeroStruct(ev);
  2062. ev.type = PostPonedJackEvent::kTypePortRegister;
  2063. ev.action = (reg != 0);
  2064. ev.port1 = port;
  2065. handlePtr->postPoneJackCallback(ev);
  2066. }
  2067. static void JACKBRIDGE_API carla_jack_port_connect_callback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg)
  2068. {
  2069. PostPonedJackEvent ev;
  2070. carla_zeroStruct(ev);
  2071. ev.type = PostPonedJackEvent::kTypePortConnect;
  2072. ev.action = (connect != 0);
  2073. ev.port1 = a;
  2074. ev.port2 = b;
  2075. handlePtr->postPoneJackCallback(ev);
  2076. }
  2077. static void JACKBRIDGE_API carla_jack_port_rename_callback(jack_port_id_t port, const char* oldName, const char* newName, void* arg)
  2078. {
  2079. PostPonedJackEvent ev;
  2080. carla_zeroStruct(ev);
  2081. ev.type = PostPonedJackEvent::kTypePortRename;
  2082. ev.port1 = port;
  2083. std::strncpy(ev.name1, oldName, STR_MAX);
  2084. std::strncpy(ev.name2, newName, STR_MAX);
  2085. handlePtr->postPoneJackCallback(ev);
  2086. }
  2087. #endif
  2088. static void JACKBRIDGE_API carla_jack_shutdown_callback(void* arg)
  2089. {
  2090. handlePtr->handleJackShutdownCallback();
  2091. }
  2092. #undef handlePtr
  2093. // -------------------------------------------------------------------
  2094. #ifndef BUILD_BRIDGE
  2095. static int JACKBRIDGE_API carla_jack_process_callback_plugin(jack_nframes_t nframes, void* arg) __attribute__((annotate("realtime")))
  2096. {
  2097. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2098. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  2099. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  2100. CARLA_SAFE_ASSERT_RETURN(engine != nullptr, 0);
  2101. if (plugin->tryLock(engine->fFreewheel))
  2102. {
  2103. plugin->initBuffers();
  2104. engine->processPlugin(plugin, nframes);
  2105. plugin->unlock();
  2106. }
  2107. return 0;
  2108. }
  2109. /*
  2110. static int JACKBRIDGE_API carla_jack_bufsize_callback_plugin(jack_nframes_t nframes, void* arg)
  2111. {
  2112. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2113. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  2114. plugin->bufferSizeChanged(nframes);
  2115. return 1;
  2116. }
  2117. static int JACKBRIDGE_API carla_jack_srate_callback_plugin(jack_nframes_t nframes, void* arg)
  2118. {
  2119. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2120. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr && plugin->isEnabled(), 0);
  2121. plugin->sampleRateChanged(nframes);
  2122. return 1;
  2123. }
  2124. */
  2125. static void JACKBRIDGE_API carla_jack_latency_callback_plugin(jack_latency_callback_mode_t /*mode*/, void* /*arg*/)
  2126. {
  2127. // TODO
  2128. }
  2129. static void JACKBRIDGE_API carla_jack_shutdown_callback_plugin(void* arg)
  2130. {
  2131. CarlaPlugin* const plugin((CarlaPlugin*)arg);
  2132. CARLA_SAFE_ASSERT_RETURN(plugin != nullptr,);
  2133. CarlaEngineJack* const engine((CarlaEngineJack*)plugin->getEngine());
  2134. CARLA_SAFE_ASSERT_RETURN(engine != nullptr,);
  2135. engine->handlePluginJackShutdownCallback(plugin);
  2136. }
  2137. #endif
  2138. // enable -Wattributes again
  2139. #if defined(__clang__)
  2140. # pragma clang diagnostic pop
  2141. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  2142. # pragma GCC diagnostic pop
  2143. #endif
  2144. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJack)
  2145. };
  2146. // -----------------------------------------------------------------------
  2147. CarlaEngine* CarlaEngine::newJack()
  2148. {
  2149. carla_debug("CarlaEngine::newJack()");
  2150. return new CarlaEngineJack();
  2151. }
  2152. // -----------------------------------------------------------------------
  2153. CARLA_BACKEND_END_NAMESPACE