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.

1819 lines
60KB

  1. /*
  2. * Carla JACK Engine
  3. * Copyright (C) 2012-2013 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 GPL.txt file
  16. */
  17. #include "CarlaEngineInternal.hpp"
  18. #include "CarlaBackendUtils.hpp"
  19. #include "CarlaMIDI.h"
  20. #ifdef JACKBRIDGE_EXPORT
  21. # include "jackbridge/JackBridge.hpp"
  22. #else
  23. # include "jackbridge/JackBridge1.cpp"
  24. # include "jackbridge/JackBridge2.cpp"
  25. #endif
  26. #include <cmath>
  27. #include <QtCore/QStringList>
  28. CARLA_BACKEND_START_NAMESPACE
  29. #if 0
  30. } // Fix editor indentation
  31. #endif
  32. // -------------------------------------------------------------------------------------------------------------------
  33. // Fallback data
  34. static const EngineEvent kFallbackJackEngineEvent;
  35. // -------------------------------------------------------------------------------------------------------------------
  36. // Plugin Helpers, defined in CarlaPlugin.cpp
  37. extern CarlaEngine* CarlaPluginGetEngine(CarlaPlugin* const plugin);
  38. extern CarlaEngineClient* CarlaPluginGetEngineClient(CarlaPlugin* const plugin);
  39. extern CarlaEngineAudioPort* CarlaPluginGetAudioInPort(CarlaPlugin* const plugin, uint32_t index);
  40. extern CarlaEngineAudioPort* CarlaPluginGetAudioOutPort(CarlaPlugin* const plugin, uint32_t index);
  41. // -------------------------------------------------------------------------------------------------------------------
  42. // Carla Engine JACK-Audio port
  43. class CarlaEngineJackAudioPort : public CarlaEngineAudioPort
  44. {
  45. public:
  46. CarlaEngineJackAudioPort(const bool isInput, const ProcessMode processMode, jack_client_t* const client, jack_port_t* const port)
  47. : CarlaEngineAudioPort(isInput, processMode),
  48. kClient(client),
  49. kPort(port)
  50. {
  51. carla_debug("CarlaEngineJackAudioPort::CarlaEngineJackAudioPort(%s, %s, %p, %p)", bool2str(isInput), ProcessMode2Str(processMode), client, port);
  52. if (processMode == PROCESS_MODE_SINGLE_CLIENT || processMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  53. {
  54. CARLA_ASSERT(client != nullptr && port != nullptr);
  55. }
  56. else
  57. {
  58. CARLA_ASSERT(client == nullptr && port == nullptr);
  59. }
  60. }
  61. ~CarlaEngineJackAudioPort() override
  62. {
  63. carla_debug("CarlaEngineJackAudioPort::~CarlaEngineJackAudioPort()");
  64. if (kClient != nullptr && kPort != nullptr)
  65. jackbridge_port_unregister(kClient, kPort);
  66. }
  67. void initBuffer(CarlaEngine* const engine) override
  68. {
  69. CARLA_ASSERT(engine != nullptr);
  70. if (engine == nullptr)
  71. {
  72. fBuffer = nullptr;
  73. return;
  74. }
  75. if (kPort == nullptr)
  76. return CarlaEngineAudioPort::initBuffer(engine);
  77. fBuffer = (float*)jackbridge_port_get_buffer(kPort, engine->getBufferSize());
  78. if (! kIsInput)
  79. carla_zeroFloat(fBuffer, engine->getBufferSize());
  80. }
  81. private:
  82. jack_client_t* const kClient;
  83. jack_port_t* const kPort;
  84. friend class CarlaEngineJack;
  85. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackAudioPort)
  86. };
  87. // -------------------------------------------------------------------------------------------------------------------
  88. // Carla Engine JACK-Event port
  89. class CarlaEngineJackEventPort : public CarlaEngineEventPort
  90. {
  91. public:
  92. CarlaEngineJackEventPort(const bool isInput, const ProcessMode processMode, jack_client_t* const client, jack_port_t* const port)
  93. : CarlaEngineEventPort(isInput, processMode),
  94. kClient(client),
  95. kPort(port),
  96. fJackBuffer(nullptr)
  97. {
  98. carla_debug("CarlaEngineJackEventPort::CarlaEngineJackEventPort(%s, %s, %p, %p)", bool2str(isInput), ProcessMode2Str(processMode), client, port);
  99. if (processMode == PROCESS_MODE_SINGLE_CLIENT || processMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  100. {
  101. CARLA_ASSERT(client != nullptr && port != nullptr);
  102. }
  103. else
  104. {
  105. CARLA_ASSERT(client == nullptr && port == nullptr);
  106. }
  107. }
  108. ~CarlaEngineJackEventPort() override
  109. {
  110. carla_debug("CarlaEngineJackEventPort::~CarlaEngineJackEventPort()");
  111. if (kClient != nullptr && kPort != nullptr)
  112. jackbridge_port_unregister(kClient, kPort);
  113. }
  114. void initBuffer(CarlaEngine* const engine) override
  115. {
  116. CARLA_ASSERT(engine != nullptr);
  117. if (engine == nullptr)
  118. {
  119. fJackBuffer = nullptr;
  120. return;
  121. }
  122. if (kPort == nullptr)
  123. return CarlaEngineEventPort::initBuffer(engine);
  124. fJackBuffer = jackbridge_port_get_buffer(kPort, engine->getBufferSize());
  125. if (! kIsInput)
  126. jackbridge_midi_clear_buffer(fJackBuffer);
  127. }
  128. uint32_t getEventCount() const override
  129. {
  130. if (kPort == nullptr)
  131. return CarlaEngineEventPort::getEventCount();
  132. CARLA_ASSERT(kIsInput);
  133. CARLA_ASSERT(fJackBuffer != nullptr);
  134. if (! kIsInput)
  135. return 0;
  136. if (fJackBuffer == nullptr)
  137. return 0;
  138. return jackbridge_midi_get_event_count(fJackBuffer);
  139. }
  140. const EngineEvent& getEvent(const uint32_t index) override
  141. {
  142. if (kPort == nullptr)
  143. return CarlaEngineEventPort::getEvent(index);
  144. CARLA_ASSERT(kIsInput);
  145. CARLA_ASSERT(fJackBuffer != nullptr);
  146. if (! kIsInput)
  147. return kFallbackJackEngineEvent;
  148. if (fJackBuffer == nullptr)
  149. return kFallbackJackEngineEvent;
  150. jack_midi_event_t jackEvent;
  151. carla_zeroStruct<jack_midi_event_t>(jackEvent);
  152. if (! jackbridge_midi_event_get(&jackEvent, fJackBuffer, index))
  153. return kFallbackJackEngineEvent;
  154. if (jackEvent.size == 0 || jackEvent.size > 4)
  155. return kFallbackJackEngineEvent;
  156. fRetEvent.clear();
  157. const uint8_t midiStatus = MIDI_GET_STATUS_FROM_DATA(jackEvent.buffer);
  158. const uint8_t midiChannel = MIDI_GET_CHANNEL_FROM_DATA(jackEvent.buffer);
  159. fRetEvent.time = jackEvent.time;
  160. fRetEvent.channel = midiChannel;
  161. if (MIDI_IS_STATUS_CONTROL_CHANGE(midiStatus))
  162. {
  163. CARLA_ASSERT(jackEvent.size == 2 || jackEvent.size == 3);
  164. const uint8_t midiControl = jackEvent.buffer[1];
  165. fRetEvent.type = kEngineEventTypeControl;
  166. if (MIDI_IS_CONTROL_BANK_SELECT(midiControl))
  167. {
  168. const uint8_t midiBank = jackEvent.buffer[2];
  169. fRetEvent.ctrl.type = kEngineControlEventTypeMidiBank;
  170. fRetEvent.ctrl.param = midiBank;
  171. fRetEvent.ctrl.value = 0.0f;
  172. }
  173. else if (midiControl == MIDI_CONTROL_ALL_SOUND_OFF)
  174. {
  175. fRetEvent.ctrl.type = kEngineControlEventTypeAllSoundOff;
  176. fRetEvent.ctrl.param = 0;
  177. fRetEvent.ctrl.value = 0.0f;
  178. }
  179. else if (midiControl == MIDI_CONTROL_ALL_NOTES_OFF)
  180. {
  181. fRetEvent.ctrl.type = kEngineControlEventTypeAllNotesOff;
  182. fRetEvent.ctrl.param = 0;
  183. fRetEvent.ctrl.value = 0.0f;
  184. }
  185. else
  186. {
  187. CARLA_ASSERT(jackEvent.size == 3);
  188. const uint8_t midiValue = jackEvent.buffer[2];
  189. fRetEvent.ctrl.type = kEngineControlEventTypeParameter;
  190. fRetEvent.ctrl.param = midiControl;
  191. fRetEvent.ctrl.value = float(midiValue)/127.0f;
  192. }
  193. }
  194. else if (MIDI_IS_STATUS_PROGRAM_CHANGE(midiStatus))
  195. {
  196. CARLA_ASSERT(jackEvent.size == 2);
  197. const uint8_t midiProgram = jackEvent.buffer[1];
  198. fRetEvent.type = kEngineEventTypeControl;
  199. fRetEvent.ctrl.type = kEngineControlEventTypeMidiProgram;
  200. fRetEvent.ctrl.param = midiProgram;
  201. fRetEvent.ctrl.value = 0.0f;
  202. }
  203. else
  204. {
  205. fRetEvent.type = kEngineEventTypeMidi;
  206. fRetEvent.midi.data[0] = midiStatus;
  207. fRetEvent.midi.size = static_cast<uint8_t>(jackEvent.size);
  208. if (jackEvent.size > 1)
  209. carla_copy<uint8_t>(fRetEvent.midi.data+1, jackEvent.buffer+1, jackEvent.size-1);
  210. }
  211. return fRetEvent;
  212. }
  213. void writeControlEvent(const uint32_t time, const uint8_t channel, const EngineControlEventType type, const uint16_t param, const float value) override
  214. {
  215. if (kPort == nullptr)
  216. return CarlaEngineEventPort::writeControlEvent(time, channel, type, param, value);
  217. CARLA_ASSERT(! kIsInput);
  218. CARLA_ASSERT(fJackBuffer != nullptr);
  219. CARLA_ASSERT(type != kEngineControlEventTypeNull);
  220. CARLA_ASSERT(channel < MAX_MIDI_CHANNELS);
  221. CARLA_ASSERT(param < MAX_MIDI_VALUE);
  222. CARLA_SAFE_ASSERT(value >= 0.0f && value <= 1.0f);
  223. if (kIsInput)
  224. return;
  225. if (fJackBuffer == nullptr)
  226. return;
  227. if (type == kEngineControlEventTypeNull)
  228. return;
  229. if (channel >= MAX_MIDI_CHANNELS)
  230. return;
  231. if (param >= MAX_MIDI_VALUE)
  232. return;
  233. if (type == kEngineControlEventTypeParameter)
  234. {
  235. CARLA_ASSERT(! MIDI_IS_CONTROL_BANK_SELECT(param));
  236. }
  237. const float fixedValue(carla_fixValue<float>(0.0f, 1.0f, value));
  238. size_t size = 0;
  239. jack_midi_data_t data[4] = { 0 };
  240. switch (type)
  241. {
  242. case kEngineControlEventTypeNull:
  243. break;
  244. case kEngineControlEventTypeParameter:
  245. data[0] = MIDI_STATUS_CONTROL_CHANGE + channel;
  246. data[1] = param;
  247. data[2] = fixedValue * 127.0f;
  248. size = 3;
  249. break;
  250. case kEngineControlEventTypeMidiBank:
  251. data[0] = MIDI_STATUS_CONTROL_CHANGE + channel;
  252. data[1] = MIDI_CONTROL_BANK_SELECT;
  253. data[2] = param;
  254. size = 3;
  255. break;
  256. case kEngineControlEventTypeMidiProgram:
  257. data[0] = MIDI_STATUS_PROGRAM_CHANGE + channel;
  258. data[1] = param;
  259. size = 2;
  260. break;
  261. case kEngineControlEventTypeAllSoundOff:
  262. data[0] = MIDI_STATUS_CONTROL_CHANGE + channel;
  263. data[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  264. data[2] = 0;
  265. size = 3;
  266. break;
  267. case kEngineControlEventTypeAllNotesOff:
  268. data[0] = MIDI_STATUS_CONTROL_CHANGE + channel;
  269. data[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  270. data[2] = 0;
  271. size = 3;
  272. break;
  273. }
  274. if (size > 0)
  275. jackbridge_midi_event_write(fJackBuffer, time, data, size);
  276. }
  277. void writeMidiEvent(const uint32_t time, const uint8_t channel, const uint8_t port, const uint8_t* const data, const uint8_t size) override
  278. {
  279. if (kPort == nullptr)
  280. return CarlaEngineEventPort::writeMidiEvent(time, channel, port, data, size);
  281. CARLA_ASSERT(! kIsInput);
  282. CARLA_ASSERT(fJackBuffer != nullptr);
  283. CARLA_ASSERT(channel < MAX_MIDI_CHANNELS);
  284. CARLA_ASSERT(data != nullptr);
  285. CARLA_ASSERT(size > 0);
  286. if (kIsInput)
  287. return;
  288. if (fJackBuffer == nullptr)
  289. return;
  290. if (channel >= MAX_MIDI_CHANNELS)
  291. return;
  292. if (data == nullptr)
  293. return;
  294. if (size == 0)
  295. return;
  296. uint8_t jdata[size];
  297. carla_copy<uint8_t>(jdata, data, size);
  298. jdata[0] = MIDI_GET_STATUS_FROM_DATA(data) + channel;
  299. jackbridge_midi_event_write(fJackBuffer, time, jdata, size);
  300. }
  301. private:
  302. jack_client_t* const kClient;
  303. jack_port_t* const kPort;
  304. void* fJackBuffer;
  305. EngineEvent fRetEvent;
  306. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackEventPort)
  307. };
  308. // -------------------------------------------------------------------------------------------------------------------
  309. // Jack Engine client
  310. class CarlaEngineJackClient : public CarlaEngineClient
  311. {
  312. public:
  313. CarlaEngineJackClient(const EngineType engineType, const ProcessMode processMode, jack_client_t* const client)
  314. : CarlaEngineClient(engineType, processMode),
  315. kClient(client),
  316. kUseClient(processMode == PROCESS_MODE_SINGLE_CLIENT || processMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  317. {
  318. carla_debug("CarlaEngineJackClient::CarlaEngineJackClient(%s, %s, %p)", EngineType2Str(engineType), ProcessMode2Str(processMode), client);
  319. if (kUseClient)
  320. {
  321. CARLA_ASSERT(kClient != nullptr);
  322. }
  323. else
  324. {
  325. CARLA_ASSERT(kClient == nullptr);
  326. }
  327. }
  328. ~CarlaEngineJackClient() override
  329. {
  330. carla_debug("CarlaEngineClient::~CarlaEngineClient()");
  331. if (kProcessMode == PROCESS_MODE_MULTIPLE_CLIENTS && kClient != nullptr)
  332. jackbridge_client_close(kClient);
  333. }
  334. void activate() override
  335. {
  336. carla_debug("CarlaEngineJackClient::activate()");
  337. if (kProcessMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  338. {
  339. CARLA_ASSERT(kClient != nullptr && ! fActive);
  340. if (kClient != nullptr && ! fActive)
  341. jackbridge_activate(kClient);
  342. }
  343. CarlaEngineClient::activate();
  344. }
  345. void deactivate() override
  346. {
  347. carla_debug("CarlaEngineJackClient::deactivate()");
  348. if (kProcessMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  349. {
  350. CARLA_ASSERT(kClient != nullptr && fActive);
  351. if (kClient != nullptr && fActive)
  352. jackbridge_deactivate(kClient);
  353. }
  354. CarlaEngineClient::deactivate();
  355. }
  356. bool isOk() const override
  357. {
  358. carla_debug("CarlaEngineJackClient::isOk()");
  359. if (kUseClient)
  360. return (kClient != nullptr);
  361. return CarlaEngineClient::isOk();
  362. }
  363. #if 0
  364. void setLatency(const uint32_t samples) override
  365. {
  366. CarlaEngineClient::setLatency(samples);
  367. if (kUseClient)
  368. jackbridge_recompute_total_latencies(kClient);
  369. }
  370. #endif
  371. CarlaEnginePort* addPort(const EnginePortType portType, const char* const name, const bool isInput) override
  372. {
  373. carla_debug("CarlaEngineJackClient::addPort(%s, \"%s\", %s)", EnginePortType2Str(portType), name, bool2str(isInput));
  374. jack_port_t* port = nullptr;
  375. // Create JACK port first, if needed
  376. if (kUseClient)
  377. {
  378. switch (portType)
  379. {
  380. case kEnginePortTypeNull:
  381. break;
  382. case kEnginePortTypeAudio:
  383. port = jackbridge_port_register(kClient, name, JACK_DEFAULT_AUDIO_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  384. break;
  385. case kEnginePortTypeEvent:
  386. port = jackbridge_port_register(kClient, name, JACK_DEFAULT_MIDI_TYPE, isInput ? JackPortIsInput : JackPortIsOutput, 0);
  387. break;
  388. }
  389. }
  390. // Create Engine port
  391. switch (portType)
  392. {
  393. case kEnginePortTypeNull:
  394. break;
  395. case kEnginePortTypeAudio:
  396. return new CarlaEngineJackAudioPort(isInput, kProcessMode, kClient, port);
  397. case kEnginePortTypeEvent:
  398. return new CarlaEngineJackEventPort(isInput, kProcessMode, kClient, port);
  399. }
  400. carla_stderr("CarlaEngineJackClient::addPort(%s, \"%s\", %s) - invalid type", EnginePortType2Str(portType), name, bool2str(isInput));
  401. return nullptr;
  402. }
  403. private:
  404. jack_client_t* const kClient;
  405. const bool kUseClient;
  406. friend class CarlaEngineJack;
  407. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJackClient)
  408. };
  409. // -------------------------------------------------------------------------------------------------------------------
  410. // Jack Engine
  411. class CarlaEngineJack : public CarlaEngine
  412. {
  413. public:
  414. CarlaEngineJack()
  415. : CarlaEngine(),
  416. fClient(nullptr),
  417. fTransportState(JackTransportStopped),
  418. fFreewheel(false),
  419. #ifdef BUILD_BRIDGE
  420. fHasQuit(false)
  421. #else
  422. # ifdef CARLA_PROPER_CPP11_SUPPORT
  423. fRackPorts{nullptr},
  424. # endif
  425. fLastGroupId(0),
  426. fLastPortId(0),
  427. fLastConnectionId(0)
  428. #endif
  429. {
  430. carla_debug("CarlaEngineJack::CarlaEngineJack()");
  431. #ifdef BUILD_BRIDGE
  432. fOptions.processMode = PROCESS_MODE_MULTIPLE_CLIENTS;
  433. #else
  434. # ifndef CARLA_PROPER_CPP11_SUPPORT
  435. carla_zeroStruct<jack_port_t*>(fRackPorts, rackPortCount);
  436. # endif
  437. #endif
  438. // FIXME: Always enable JACK transport for now
  439. fOptions.transportMode = TRANSPORT_MODE_JACK;
  440. carla_zeroStruct<jack_position_t>(fTransportPos);
  441. }
  442. ~CarlaEngineJack() override
  443. {
  444. carla_debug("CarlaEngineJack::~CarlaEngineJack()");
  445. CARLA_ASSERT(fClient == nullptr);
  446. #ifndef BUILD_BRIDGE
  447. fUsedGroupNames.clear();
  448. fUsedPortNames.clear();
  449. fUsedConnections.clear();
  450. #endif
  451. }
  452. // -------------------------------------------------------------------
  453. // Maximum values
  454. unsigned int maxClientNameSize() const override
  455. {
  456. if (fOptions.processMode == PROCESS_MODE_SINGLE_CLIENT || fOptions.processMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  457. return static_cast<unsigned int>(jackbridge_client_name_size());
  458. return CarlaEngine::maxClientNameSize();
  459. }
  460. unsigned int maxPortNameSize() const override
  461. {
  462. if (fOptions.processMode == PROCESS_MODE_SINGLE_CLIENT || fOptions.processMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  463. return static_cast<unsigned int>(jackbridge_port_name_size());
  464. return CarlaEngine::maxPortNameSize();
  465. }
  466. // -------------------------------------------------------------------
  467. // Virtual, per-engine type calls
  468. bool init(const char* const clientName) override
  469. {
  470. carla_debug("CarlaEngineJack::init(\"%s\")", clientName);
  471. fFreewheel = false;
  472. fTransportState = JackTransportStopped;
  473. carla_zeroStruct<jack_position_t>(fTransportPos);
  474. #ifndef BUILD_BRIDGE
  475. fLastGroupId = 0;
  476. fLastPortId = 0;
  477. fLastConnectionId = 0;
  478. fUsedGroupNames.clear();
  479. fUsedPortNames.clear();
  480. fUsedConnections.clear();
  481. fClient = jackbridge_client_open(clientName, JackNullOption, nullptr);
  482. if (fClient != nullptr)
  483. {
  484. fBufferSize = jackbridge_get_buffer_size(fClient);
  485. fSampleRate = jackbridge_get_sample_rate(fClient);
  486. jackbridge_set_buffer_size_callback(fClient, carla_jack_bufsize_callback, this);
  487. jackbridge_set_sample_rate_callback(fClient, carla_jack_srate_callback, this);
  488. jackbridge_set_freewheel_callback(fClient, carla_jack_freewheel_callback, this);
  489. jackbridge_set_process_callback(fClient, carla_jack_process_callback, this);
  490. jackbridge_on_shutdown(fClient, carla_jack_shutdown_callback, this);
  491. # if 0
  492. jackbridge_set_latency_callback(fClient, carla_jack_latency_callback, this);
  493. # endif
  494. const char* const jackClientName(jackbridge_get_client_name(fClient));
  495. initJackPatchbay(jackClientName);
  496. jackbridge_set_client_registration_callback(fClient, carla_jack_client_registration_callback, this);
  497. jackbridge_set_port_registration_callback(fClient, carla_jack_port_registration_callback, this);
  498. jackbridge_set_port_connect_callback(fClient, carla_jack_port_connect_callback, this);
  499. jackbridge_set_port_rename_callback(fClient, carla_jack_port_rename_callback, this);
  500. if (fOptions.processMode == PROCESS_MODE_CONTINUOUS_RACK)
  501. {
  502. fRackPorts[rackPortAudioIn1] = jackbridge_port_register(fClient, "audio-in1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  503. fRackPorts[rackPortAudioIn2] = jackbridge_port_register(fClient, "audio-in2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  504. fRackPorts[rackPortAudioOut1] = jackbridge_port_register(fClient, "audio-out1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  505. fRackPorts[rackPortAudioOut2] = jackbridge_port_register(fClient, "audio-out2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  506. fRackPorts[rackPortEventIn] = jackbridge_port_register(fClient, "events-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
  507. fRackPorts[rackPortEventOut] = jackbridge_port_register(fClient, "events-out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
  508. }
  509. if (jackbridge_activate(fClient))
  510. {
  511. return CarlaEngine::init(jackClientName);
  512. }
  513. else
  514. {
  515. setLastError("Failed to activate the JACK client");
  516. jackbridge_client_close(fClient);
  517. fClient = nullptr;
  518. }
  519. }
  520. else
  521. setLastError("Failed to create new JACK client");
  522. return false;
  523. #else
  524. if (fBufferSize == 0 || fSampleRate == 0.0)
  525. {
  526. // open temp client to get initial buffer-size and sample-rate values
  527. if (jack_client_t* tmpClient = jackbridge_client_open(clientName, JackNullOption, nullptr))
  528. {
  529. fBufferSize = jackbridge_get_buffer_size(tmpClient);
  530. fSampleRate = jackbridge_get_sample_rate(tmpClient);
  531. jackbridge_client_close(tmpClient);
  532. }
  533. }
  534. return CarlaEngine::init(clientName);
  535. #endif
  536. }
  537. bool close() override
  538. {
  539. carla_debug("CarlaEngineJack::close()");
  540. CarlaEngine::close();
  541. #ifdef BUILD_BRIDGE
  542. fClient = nullptr;
  543. fHasQuit = true;
  544. return true;
  545. #else
  546. if (jackbridge_deactivate(fClient))
  547. {
  548. if (fOptions.processMode == PROCESS_MODE_CONTINUOUS_RACK)
  549. {
  550. jackbridge_port_unregister(fClient, fRackPorts[rackPortAudioIn1]);
  551. jackbridge_port_unregister(fClient, fRackPorts[rackPortAudioIn2]);
  552. jackbridge_port_unregister(fClient, fRackPorts[rackPortAudioOut1]);
  553. jackbridge_port_unregister(fClient, fRackPorts[rackPortAudioOut2]);
  554. jackbridge_port_unregister(fClient, fRackPorts[rackPortEventIn]);
  555. jackbridge_port_unregister(fClient, fRackPorts[rackPortEventOut]);
  556. }
  557. if (jackbridge_client_close(fClient))
  558. {
  559. fClient = nullptr;
  560. return true;
  561. }
  562. else
  563. setLastError("Failed to close the JACK client");
  564. }
  565. else
  566. setLastError("Failed to deactivate the JACK client");
  567. fClient = nullptr;
  568. fUsedGroupNames.clear();
  569. fUsedPortNames.clear();
  570. fUsedConnections.clear();
  571. #endif
  572. return false;
  573. }
  574. bool isRunning() const override
  575. {
  576. #ifdef BUILD_BRIDGE
  577. return (fClient != nullptr || ! fHasQuit);
  578. #else
  579. return (fClient != nullptr);
  580. #endif
  581. }
  582. bool isOffline() const override
  583. {
  584. return fFreewheel;
  585. }
  586. EngineType type() const override
  587. {
  588. return kEngineTypeJack;
  589. }
  590. CarlaEngineClient* addClient(CarlaPlugin* const plugin) override
  591. {
  592. jack_client_t* client = nullptr;
  593. #ifdef BUILD_BRIDGE
  594. client = fClient = jackbridge_client_open(plugin->name(), JackNullOption, nullptr);
  595. fBufferSize = jackbridge_get_buffer_size(client);
  596. fSampleRate = jackbridge_get_sample_rate(client);
  597. jackbridge_set_buffer_size_callback(client, carla_jack_bufsize_callback, this);
  598. jackbridge_set_sample_rate_callback(client, carla_jack_srate_callback, this);
  599. jackbridge_set_freewheel_callback(client, carla_jack_freewheel_callback, this);
  600. jackbridge_set_process_callback(client, carla_jack_process_callback, this);
  601. jackbridge_on_shutdown(client, carla_jack_shutdown_callback, this);
  602. # if 0
  603. jackbridge_set_latency_callback(client, carla_jack_latency_callback, this);
  604. # endif
  605. #else
  606. if (fOptions.processMode == PROCESS_MODE_SINGLE_CLIENT)
  607. {
  608. client = fClient;
  609. }
  610. else if (fOptions.processMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  611. {
  612. client = jackbridge_client_open(plugin->name(), JackNullOption, nullptr);
  613. jackbridge_set_process_callback(client, carla_jack_process_callback_plugin, plugin);
  614. # if 0
  615. jackbridge_set_latency_callback(client, carla_jack_latency_callback_plugin, plugin);
  616. # endif
  617. }
  618. #endif
  619. return new CarlaEngineJackClient(kEngineTypeJack, fOptions.processMode, client);
  620. }
  621. #ifndef BUILD_BRIDGE
  622. const char* renamePlugin(const unsigned int id, const char* const newName) override
  623. {
  624. CARLA_ASSERT(kData->curPluginCount > 0);
  625. CARLA_ASSERT(id < kData->curPluginCount);
  626. CARLA_ASSERT(kData->plugins != nullptr);
  627. CARLA_ASSERT(newName != nullptr);
  628. if (kData->plugins == nullptr)
  629. {
  630. setLastError("Critical error: no plugins are currently loaded!");
  631. return nullptr;
  632. }
  633. CarlaPlugin* const plugin = kData->plugins[id].plugin;
  634. if (plugin == nullptr)
  635. {
  636. carla_stderr("CarlaEngine::clonePlugin(%i) - could not find plugin", id);
  637. return nullptr;
  638. }
  639. CARLA_ASSERT(plugin->id() == id);
  640. bool needsReinit = (fOptions.processMode == PROCESS_MODE_SINGLE_CLIENT);
  641. const char* name = getUniquePluginName(newName);
  642. // JACK client rename
  643. if (fOptions.processMode == PROCESS_MODE_MULTIPLE_CLIENTS)
  644. {
  645. CarlaEngineJackClient* const client((CarlaEngineJackClient*)CarlaPluginGetEngineClient(plugin));
  646. if (bridge.client_rename_ptr != nullptr)
  647. {
  648. name = bridge.client_rename_ptr(client->kClient, name);
  649. }
  650. else
  651. {
  652. // we should not be able to do this, jack really needs to allow client rename
  653. needsReinit = true;
  654. plugin->setEnabled(false);
  655. if (client->isActive())
  656. client->deactivate();
  657. plugin->clearBuffers();
  658. jackbridge_client_close(client->kClient);
  659. jack_client_t* jclient = jackbridge_client_open(name, JackNullOption, nullptr);
  660. name = jackbridge_get_client_name(jclient);
  661. jackbridge_set_process_callback(jclient, carla_jack_process_callback_plugin, plugin);
  662. # if 0
  663. jackbridge_set_latency_callback(jclient, carla_jack_latency_callback_plugin, plugin);
  664. # endif
  665. std::memcpy((jack_client_t**)&client->kClient, &jclient, sizeof(jack_client_t**));
  666. }
  667. }
  668. if (name == nullptr)
  669. return nullptr;
  670. // Rename
  671. plugin->setName(name);
  672. if (needsReinit)
  673. {
  674. // reload plugin to recreate its ports
  675. const SaveState& saveState(plugin->getSaveState());
  676. plugin->reload();
  677. plugin->loadSaveState(saveState);
  678. }
  679. return name;
  680. }
  681. // -------------------------------------------------------------------
  682. // Patchbay
  683. bool patchbayConnect(int portA, int portB) override
  684. {
  685. CARLA_ASSERT(fClient != nullptr);
  686. if (fClient == nullptr)
  687. {
  688. setLastError("Invalid JACK client");
  689. return false;
  690. }
  691. const char* const portNameA = getFullPortName(portA).toUtf8().constData();
  692. const char* const portNameB = getFullPortName(portB).toUtf8().constData();
  693. if (! jackbridge_connect(fClient, portNameA, portNameB))
  694. {
  695. setLastError("JACK operation failed");
  696. return false;
  697. }
  698. return true;
  699. }
  700. bool patchbayDisconnect(int connectionId) override
  701. {
  702. CARLA_ASSERT(fClient != nullptr);
  703. if (fClient == nullptr)
  704. {
  705. setLastError("Invalid JACK client");
  706. return false;
  707. }
  708. for (int i=0, count=fUsedConnections.count(); i < count; ++i)
  709. {
  710. if (fUsedConnections[i].id == connectionId)
  711. {
  712. const char* const portNameA = getFullPortName(fUsedConnections[i].portOut).toUtf8().constData();
  713. const char* const portNameB = getFullPortName(fUsedConnections[i].portIn).toUtf8().constData();
  714. if (! jackbridge_disconnect(fClient, portNameA, portNameB))
  715. {
  716. setLastError("JACK operation failed");
  717. return false;
  718. }
  719. return true;
  720. }
  721. }
  722. setLastError("Failed to find the requested connection");
  723. return false;
  724. }
  725. void patchbayRefresh() override
  726. {
  727. CARLA_ASSERT(fClient != nullptr);
  728. if (fClient == nullptr)
  729. return;
  730. fLastGroupId = 0;
  731. fLastPortId = 0;
  732. fLastConnectionId = 0;
  733. fUsedGroupNames.clear();
  734. fUsedPortNames.clear();
  735. fUsedConnections.clear();
  736. initJackPatchbay(jackbridge_get_client_name(fClient));
  737. }
  738. #endif
  739. // -------------------------------------------------------------------
  740. // Transport
  741. void transportPlay() override
  742. {
  743. if (fOptions.transportMode == TRANSPORT_MODE_INTERNAL)
  744. CarlaEngine::transportPlay();
  745. else if (fClient != nullptr)
  746. jackbridge_transport_start(fClient);
  747. }
  748. void transportPause() override
  749. {
  750. if (fOptions.transportMode == TRANSPORT_MODE_INTERNAL)
  751. CarlaEngine::transportPause();
  752. else if (fClient != nullptr)
  753. jackbridge_transport_stop(fClient);
  754. }
  755. void transportRelocate(const uint32_t frame) override
  756. {
  757. if (fOptions.transportMode == TRANSPORT_MODE_INTERNAL)
  758. CarlaEngine::transportRelocate(frame);
  759. else if (fClient != nullptr)
  760. jackbridge_transport_locate(fClient, frame);
  761. }
  762. // -------------------------------------
  763. protected:
  764. void handleJackBufferSizeCallback(const uint32_t newBufferSize)
  765. {
  766. if (fBufferSize == newBufferSize)
  767. return;
  768. fBufferSize = newBufferSize;
  769. bufferSizeChanged(newBufferSize);
  770. }
  771. void handleJackSampleRateCallback(const double newSampleRate)
  772. {
  773. if (fSampleRate == newSampleRate)
  774. return;
  775. fSampleRate = newSampleRate;
  776. sampleRateChanged(newSampleRate);
  777. }
  778. void handleJackFreewheelCallback(const bool isFreewheel)
  779. {
  780. fFreewheel = isFreewheel;
  781. }
  782. void saveTransportInfo()
  783. {
  784. if (fOptions.transportMode != TRANSPORT_MODE_JACK)
  785. return;
  786. fTransportPos.unique_1 = fTransportPos.unique_2 + 1; // invalidate
  787. fTransportState = jackbridge_transport_query(fClient, &fTransportPos);
  788. fTimeInfo.playing = (fTransportState == JackTransportRolling);
  789. if (fTransportPos.unique_1 == fTransportPos.unique_2)
  790. {
  791. fTimeInfo.frame = fTransportPos.frame;
  792. fTimeInfo.usecs = fTransportPos.usecs;
  793. if (fTransportPos.valid & JackPositionBBT)
  794. {
  795. fTimeInfo.valid = EngineTimeInfo::ValidBBT;
  796. fTimeInfo.bbt.bar = fTransportPos.bar;
  797. fTimeInfo.bbt.beat = fTransportPos.beat;
  798. fTimeInfo.bbt.tick = fTransportPos.tick;
  799. fTimeInfo.bbt.barStartTick = fTransportPos.bar_start_tick;
  800. fTimeInfo.bbt.beatsPerBar = fTransportPos.beats_per_bar;
  801. fTimeInfo.bbt.beatType = fTransportPos.beat_type;
  802. fTimeInfo.bbt.ticksPerBeat = fTransportPos.ticks_per_beat;
  803. fTimeInfo.bbt.beatsPerMinute = fTransportPos.beats_per_minute;
  804. }
  805. else
  806. fTimeInfo.valid = 0x0;
  807. }
  808. else
  809. {
  810. fTimeInfo.frame = 0;
  811. fTimeInfo.valid = 0x0;
  812. }
  813. }
  814. void handleJackProcessCallback(const uint32_t nframes)
  815. {
  816. saveTransportInfo();
  817. #ifndef BUILD_BRIDGE
  818. if (kData->curPluginCount == 0)
  819. {
  820. // pass-through
  821. if (fOptions.processMode == PROCESS_MODE_CONTINUOUS_RACK)
  822. {
  823. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioIn1], nframes);
  824. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioIn2], nframes);
  825. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioOut1], nframes);
  826. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioOut2], nframes);
  827. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[rackPortEventOut], nframes);
  828. CARLA_ASSERT(audioIn1 != nullptr);
  829. CARLA_ASSERT(audioIn2 != nullptr);
  830. CARLA_ASSERT(audioOut1 != nullptr);
  831. CARLA_ASSERT(audioOut2 != nullptr);
  832. CARLA_ASSERT(eventOut != nullptr);
  833. carla_copyFloat(audioOut1, audioIn1, nframes);
  834. carla_copyFloat(audioOut2, audioIn2, nframes);
  835. jackbridge_midi_clear_buffer(eventOut);
  836. }
  837. return proccessPendingEvents();
  838. }
  839. #endif
  840. #ifdef BUILD_BRIDGE
  841. CarlaPlugin* const plugin = getPluginUnchecked(0);
  842. if (plugin && plugin->enabled() && plugin->tryLock())
  843. {
  844. plugin->initBuffers();
  845. processPlugin(plugin, nframes);
  846. plugin->unlock();
  847. }
  848. #else
  849. if (fOptions.processMode == PROCESS_MODE_SINGLE_CLIENT)
  850. {
  851. for (unsigned int i=0; i < kData->curPluginCount; ++i)
  852. {
  853. CarlaPlugin* const plugin = getPluginUnchecked(i);
  854. if (plugin && plugin->enabled() && plugin->tryLock())
  855. {
  856. plugin->initBuffers();
  857. processPlugin(plugin, nframes);
  858. plugin->unlock();
  859. }
  860. }
  861. }
  862. else if (fOptions.processMode == PROCESS_MODE_CONTINUOUS_RACK)
  863. {
  864. // get buffers from jack
  865. float* const audioIn1 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioIn1], nframes);
  866. float* const audioIn2 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioIn2], nframes);
  867. float* const audioOut1 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioOut1], nframes);
  868. float* const audioOut2 = (float*)jackbridge_port_get_buffer(fRackPorts[rackPortAudioOut2], nframes);
  869. void* const eventIn = jackbridge_port_get_buffer(fRackPorts[rackPortEventIn], nframes);
  870. void* const eventOut = jackbridge_port_get_buffer(fRackPorts[rackPortEventOut], nframes);
  871. // assert buffers
  872. CARLA_ASSERT(audioIn1 != nullptr);
  873. CARLA_ASSERT(audioIn2 != nullptr);
  874. CARLA_ASSERT(audioOut1 != nullptr);
  875. CARLA_ASSERT(audioOut2 != nullptr);
  876. CARLA_ASSERT(eventIn != nullptr);
  877. CARLA_ASSERT(eventOut != nullptr);
  878. // create audio buffers
  879. float* inBuf[2] = { audioIn1, audioIn2 };
  880. float* outBuf[2] = { audioOut1, audioOut2 };
  881. // initialize input events
  882. carla_zeroStruct<EngineEvent>(kData->bufEvent.in, INTERNAL_EVENT_COUNT);
  883. {
  884. uint32_t engineEventIndex = 0;
  885. jack_midi_event_t jackEvent;
  886. const uint32_t jackEventCount = jackbridge_midi_get_event_count(eventIn);
  887. for (uint32_t jackEventIndex=0; jackEventIndex < jackEventCount; ++jackEventIndex)
  888. {
  889. if (jackbridge_midi_event_get(&jackEvent, eventIn, jackEventIndex) != 0)
  890. continue;
  891. EngineEvent* const engineEvent = &kData->bufEvent.in[engineEventIndex++];
  892. engineEvent->clear();
  893. const uint8_t midiStatus = MIDI_GET_STATUS_FROM_DATA(jackEvent.buffer);
  894. const uint8_t midiChannel = MIDI_GET_CHANNEL_FROM_DATA(jackEvent.buffer);
  895. engineEvent->time = jackEvent.time;
  896. engineEvent->channel = midiChannel;
  897. if (MIDI_IS_STATUS_CONTROL_CHANGE(midiStatus))
  898. {
  899. const uint8_t midiControl = jackEvent.buffer[1];
  900. engineEvent->type = kEngineEventTypeControl;
  901. if (MIDI_IS_CONTROL_BANK_SELECT(midiControl))
  902. {
  903. const uint8_t midiBank = jackEvent.buffer[2];
  904. engineEvent->ctrl.type = kEngineControlEventTypeMidiBank;
  905. engineEvent->ctrl.param = midiBank;
  906. engineEvent->ctrl.value = 0.0f;
  907. }
  908. else if (midiControl == MIDI_CONTROL_ALL_SOUND_OFF)
  909. {
  910. engineEvent->ctrl.type = kEngineControlEventTypeAllSoundOff;
  911. engineEvent->ctrl.param = 0;
  912. engineEvent->ctrl.value = 0.0f;
  913. }
  914. else if (midiControl == MIDI_CONTROL_ALL_NOTES_OFF)
  915. {
  916. engineEvent->ctrl.type = kEngineControlEventTypeAllNotesOff;
  917. engineEvent->ctrl.param = 0;
  918. engineEvent->ctrl.value = 0.0f;
  919. }
  920. else
  921. {
  922. const uint8_t midiValue = jackEvent.buffer[2];
  923. engineEvent->ctrl.type = kEngineControlEventTypeParameter;
  924. engineEvent->ctrl.param = midiControl;
  925. engineEvent->ctrl.value = float(midiValue)/127.0f;
  926. }
  927. }
  928. else if (MIDI_IS_STATUS_PROGRAM_CHANGE(midiStatus))
  929. {
  930. const uint8_t midiProgram = jackEvent.buffer[1];
  931. engineEvent->type = kEngineEventTypeControl;
  932. engineEvent->ctrl.type = kEngineControlEventTypeMidiProgram;
  933. engineEvent->ctrl.param = midiProgram;
  934. engineEvent->ctrl.value = 0.0f;
  935. }
  936. else if (jackEvent.size <= 4)
  937. {
  938. engineEvent->type = kEngineEventTypeMidi;
  939. carla_copy<uint8_t>(engineEvent->midi.data, jackEvent.buffer, jackEvent.size);
  940. engineEvent->midi.data[0] = midiStatus;
  941. engineEvent->midi.size = static_cast<uint8_t>(jackEvent.size);
  942. }
  943. if (engineEventIndex >= INTERNAL_EVENT_COUNT)
  944. break;
  945. }
  946. }
  947. // process rack
  948. processRack(inBuf, outBuf, nframes);
  949. // output control
  950. {
  951. jackbridge_midi_clear_buffer(eventOut);
  952. for (unsigned short i=0; i < INTERNAL_EVENT_COUNT; ++i)
  953. {
  954. EngineEvent* const engineEvent = &kData->bufEvent.out[i];
  955. uint8_t data[3] = { 0 };
  956. uint8_t size = 0;
  957. switch (engineEvent->type)
  958. {
  959. case kEngineEventTypeNull:
  960. break;
  961. case kEngineEventTypeControl:
  962. {
  963. EngineControlEvent* const ctrlEvent = &engineEvent->ctrl;
  964. if (ctrlEvent->type == kEngineControlEventTypeParameter && MIDI_IS_CONTROL_BANK_SELECT(ctrlEvent->param))
  965. {
  966. // FIXME?
  967. ctrlEvent->type = kEngineControlEventTypeMidiBank;
  968. ctrlEvent->param = ctrlEvent->value;
  969. ctrlEvent->value = 0.0f;
  970. }
  971. switch (ctrlEvent->type)
  972. {
  973. case kEngineControlEventTypeNull:
  974. break;
  975. case kEngineControlEventTypeParameter:
  976. data[0] = MIDI_STATUS_CONTROL_CHANGE + engineEvent->channel;
  977. data[1] = static_cast<uint8_t>(ctrlEvent->param);
  978. data[2] = uint8_t(ctrlEvent->value * 127.0f);
  979. size = 3;
  980. break;
  981. case kEngineControlEventTypeMidiBank:
  982. data[0] = MIDI_STATUS_CONTROL_CHANGE + engineEvent->channel;
  983. data[1] = MIDI_CONTROL_BANK_SELECT;
  984. data[2] = static_cast<uint8_t>(ctrlEvent->param);
  985. size = 3;
  986. break;
  987. case kEngineControlEventTypeMidiProgram:
  988. data[0] = MIDI_STATUS_PROGRAM_CHANGE + engineEvent->channel;
  989. data[1] = static_cast<uint8_t>(ctrlEvent->param);
  990. size = 2;
  991. break;
  992. case kEngineControlEventTypeAllSoundOff:
  993. data[0] = MIDI_STATUS_CONTROL_CHANGE + engineEvent->channel;
  994. data[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  995. size = 2;
  996. break;
  997. case kEngineControlEventTypeAllNotesOff:
  998. data[0] = MIDI_STATUS_CONTROL_CHANGE + engineEvent->channel;
  999. data[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1000. size = 2;
  1001. break;
  1002. }
  1003. break;
  1004. }
  1005. case kEngineEventTypeMidi:
  1006. {
  1007. EngineMidiEvent* const midiEvent = &engineEvent->midi;
  1008. data[0] = midiEvent->data[0];
  1009. data[1] = midiEvent->data[1];
  1010. data[2] = midiEvent->data[2];
  1011. size = midiEvent->size;
  1012. break;
  1013. }
  1014. }
  1015. if (size > 0)
  1016. jackbridge_midi_event_write(eventOut, engineEvent->time, data, size);
  1017. }
  1018. }
  1019. }
  1020. #endif // ! BUILD_BRIDGE
  1021. proccessPendingEvents();
  1022. }
  1023. #if 0
  1024. void handleJackLatencyCallback(const jack_latency_callback_mode_t mode)
  1025. {
  1026. if (fOptions.processMode != PROCESS_MODE_SINGLE_CLIENT)
  1027. return;
  1028. for (unsigned int i=0; i < kData->curPluginCount; ++i)
  1029. {
  1030. CarlaPlugin* const plugin = getPluginUnchecked(i);
  1031. if (plugin && plugin->enabled())
  1032. latencyPlugin(plugin, mode);
  1033. }
  1034. }
  1035. #endif
  1036. #ifndef BUILD_BRIDGE
  1037. void handleJackClientRegistrationCallback(const char* name, bool reg)
  1038. {
  1039. if (reg)
  1040. {
  1041. GroupNameToId groupNameToId;
  1042. groupNameToId.id = fLastGroupId;
  1043. groupNameToId.name = name;
  1044. callback(CALLBACK_PATCHBAY_CLIENT_ADDED, 0, fLastGroupId, 0, 0.0f, name);
  1045. fUsedGroupNames.append(groupNameToId);
  1046. fLastGroupId++;
  1047. }
  1048. else
  1049. {
  1050. for (int i=0, count=fUsedGroupNames.count(); i < count; ++i)
  1051. {
  1052. if (fUsedGroupNames[i].name == name)
  1053. {
  1054. callback(CALLBACK_PATCHBAY_CLIENT_REMOVED, 0, fUsedGroupNames[i].id, 0, 0.0f, nullptr);
  1055. fUsedGroupNames.takeAt(i);
  1056. break;
  1057. }
  1058. }
  1059. }
  1060. }
  1061. void handleJackPortRegistrationCallback(jack_port_id_t port, bool reg)
  1062. {
  1063. jack_port_t* jackPort = jackbridge_port_by_id(fClient, port);
  1064. QString fullName(jackbridge_port_name(jackPort));
  1065. QString groupName = fullName.split(":").at(0);
  1066. int groupId = getGroupId(groupName);
  1067. const char* portName = jackbridge_port_short_name(jackPort);
  1068. if (reg)
  1069. {
  1070. bool portIsInput = (jackbridge_port_flags(jackPort) & JackPortIsInput);
  1071. bool portIsAudio = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_AUDIO_TYPE) == 0);
  1072. unsigned int portFlags = 0x0;
  1073. portFlags |= portIsInput ? PATCHBAY_PORT_IS_INPUT : PATCHBAY_PORT_IS_OUTPUT;
  1074. portFlags |= portIsAudio ? PATCHBAY_PORT_IS_AUDIO : PATCHBAY_PORT_IS_MIDI;
  1075. PortNameToId portNameToId;
  1076. portNameToId.groupId = groupId;
  1077. portNameToId.portId = fLastPortId;
  1078. portNameToId.name = portName;
  1079. portNameToId.fullName = fullName;
  1080. fUsedPortNames.append(portNameToId);
  1081. callback(CALLBACK_PATCHBAY_PORT_ADDED, 0, groupId, fLastPortId, portFlags, portName);
  1082. fLastPortId++;
  1083. }
  1084. else
  1085. {
  1086. for (int i=0, count=fUsedPortNames.count(); i < count; ++i)
  1087. {
  1088. if (fUsedPortNames[i].groupId == groupId && fUsedPortNames[i].name == portName)
  1089. {
  1090. callback(CALLBACK_PATCHBAY_PORT_REMOVED, 0, fUsedPortNames[i].portId, 0, 0.0f, nullptr);
  1091. fUsedPortNames.takeAt(i);
  1092. break;
  1093. }
  1094. }
  1095. }
  1096. }
  1097. void handleJackPortConnectCallback(jack_port_id_t a, jack_port_id_t b, bool connect)
  1098. {
  1099. jack_port_t* jackPortA = jackbridge_port_by_id(fClient, a);
  1100. jack_port_t* jackPortB = jackbridge_port_by_id(fClient, b);
  1101. int portIdA = getPortId(QString(jackbridge_port_name(jackPortA)));
  1102. int portIdB = getPortId(QString(jackbridge_port_name(jackPortB)));
  1103. if (connect)
  1104. {
  1105. ConnectionToId connectionToId;
  1106. connectionToId.id = fLastConnectionId;
  1107. connectionToId.portOut = portIdA;
  1108. connectionToId.portIn = portIdB;
  1109. fUsedConnections.append(connectionToId);
  1110. callback(CALLBACK_PATCHBAY_CONNECTION_ADDED, 0, fLastConnectionId, portIdA, portIdB, nullptr);
  1111. fLastConnectionId++;
  1112. }
  1113. else
  1114. {
  1115. for (int i=0, count=fUsedConnections.count(); i < count; ++i)
  1116. {
  1117. if (fUsedConnections[i].portOut == portIdA && fUsedConnections[i].portIn == portIdB)
  1118. {
  1119. callback(CALLBACK_PATCHBAY_CONNECTION_REMOVED, 0, fUsedConnections[i].id, 0, 0.0f, nullptr);
  1120. fUsedConnections.takeAt(i);
  1121. break;
  1122. }
  1123. }
  1124. }
  1125. }
  1126. void handleJackPortRenameCallback(jack_port_id_t port, const char* oldName, const char* newName)
  1127. {
  1128. jack_port_t* jackPort = jackbridge_port_by_id(fClient, port);
  1129. QString fullName(oldName);
  1130. QString groupName = fullName.split(":").at(0);
  1131. int groupId = getGroupId(groupName);
  1132. const char* portName = jackbridge_port_short_name(jackPort);
  1133. for (int i=0, count=fUsedPortNames.count(); i < count; ++i)
  1134. {
  1135. if (fUsedPortNames[i].groupId == groupId && fUsedPortNames[i].name == portName)
  1136. {
  1137. callback(CALLBACK_PATCHBAY_PORT_RENAMED, 0, fUsedPortNames[i].portId, 0, 0.0f, newName);
  1138. fUsedPortNames[i].name = newName;
  1139. break;
  1140. }
  1141. }
  1142. }
  1143. #endif
  1144. void handleJackShutdownCallback()
  1145. {
  1146. for (unsigned int i=0; i < kData->curPluginCount; ++i)
  1147. {
  1148. //CarlaPlugin* const plugin = getPluginUnchecked(i);
  1149. //if (plugin)
  1150. // plugin->x_client = nullptr;
  1151. }
  1152. fClient = nullptr;
  1153. callback(CALLBACK_QUIT, 0, 0, 0, 0.0f, nullptr);
  1154. }
  1155. // -------------------------------------
  1156. private:
  1157. jack_client_t* fClient;
  1158. jack_position_t fTransportPos;
  1159. jack_transport_state_t fTransportState;
  1160. bool fFreewheel;
  1161. // -------------------------------------
  1162. #ifdef BUILD_BRIDGE
  1163. bool fHasQuit;
  1164. #else
  1165. enum RackPorts {
  1166. rackPortAudioIn1 = 0,
  1167. rackPortAudioIn2 = 1,
  1168. rackPortAudioOut1 = 2,
  1169. rackPortAudioOut2 = 3,
  1170. rackPortEventIn = 4,
  1171. rackPortEventOut = 5,
  1172. rackPortCount = 8
  1173. };
  1174. jack_port_t* fRackPorts[rackPortCount];
  1175. struct GroupNameToId {
  1176. int id;
  1177. QString name;
  1178. };
  1179. struct PortNameToId {
  1180. int groupId;
  1181. int portId;
  1182. QString name;
  1183. QString fullName;
  1184. };
  1185. struct ConnectionToId {
  1186. int id;
  1187. int portOut;
  1188. int portIn;
  1189. };
  1190. int fLastGroupId;
  1191. int fLastPortId;
  1192. int fLastConnectionId;
  1193. QList<GroupNameToId> fUsedGroupNames;
  1194. QList<PortNameToId> fUsedPortNames;
  1195. QList<ConnectionToId> fUsedConnections;
  1196. int getGroupId(QString groupName)
  1197. {
  1198. for (int i=0, count=fUsedGroupNames.count(); i < count; ++i)
  1199. {
  1200. if (fUsedGroupNames[i].name == groupName)
  1201. {
  1202. return fUsedGroupNames[i].id;
  1203. }
  1204. }
  1205. return -1;
  1206. }
  1207. int getPortId(QString fullPortName)
  1208. {
  1209. QString groupName = fullPortName.split(":").at(0);
  1210. QString portName = fullPortName.replace(groupName+":", "");
  1211. int groupId = getGroupId(groupName);
  1212. for (int i=0, count=fUsedPortNames.count(); i < count; ++i)
  1213. {
  1214. if (fUsedPortNames[i].groupId == groupId && fUsedPortNames[i].name == portName)
  1215. {
  1216. return fUsedPortNames[i].portId;
  1217. }
  1218. }
  1219. return -1;
  1220. }
  1221. QString& getFullPortName(int portId)
  1222. {
  1223. static QString fallbackString;
  1224. for (int i=0, count=fUsedPortNames.count(); i < count; ++i)
  1225. {
  1226. if (fUsedPortNames[i].portId == portId)
  1227. {
  1228. return fUsedPortNames[i].fullName;
  1229. }
  1230. }
  1231. return fallbackString;
  1232. }
  1233. void initJackPatchbay(const char* const ourName)
  1234. {
  1235. // query initial jack ports
  1236. QList<QString> parsedGroups;
  1237. // our client
  1238. {
  1239. GroupNameToId groupNameToId;
  1240. groupNameToId.id = fLastGroupId;
  1241. groupNameToId.name = ourName;
  1242. callback(CALLBACK_PATCHBAY_CLIENT_ADDED, 0, fLastGroupId, 0, 0.0f, ourName);
  1243. fUsedGroupNames.append(groupNameToId);
  1244. fLastGroupId++;
  1245. parsedGroups.append(QString(ourName));
  1246. }
  1247. if (const char** ports = jackbridge_get_ports(fClient, nullptr, nullptr, 0))
  1248. {
  1249. for (int i=0; ports[i] != nullptr; ++i)
  1250. {
  1251. jack_port_t* jackPort = jackbridge_port_by_name(fClient, ports[i]);
  1252. const char* portName = jackbridge_port_short_name(jackPort);
  1253. QString fullName(ports[i]);
  1254. QString groupName(fullName.split(":").at(0));
  1255. int groupId = -1;
  1256. //if (groupName == ourName)
  1257. // continue;
  1258. if (parsedGroups.contains(groupName))
  1259. {
  1260. groupId = getGroupId(groupName);
  1261. }
  1262. else
  1263. {
  1264. groupId = fLastGroupId++;
  1265. GroupNameToId groupNameToId;
  1266. groupNameToId.id = groupId;
  1267. groupNameToId.name = groupName;
  1268. fUsedGroupNames.append(groupNameToId);
  1269. parsedGroups.append(groupName);
  1270. callback(CALLBACK_PATCHBAY_CLIENT_ADDED, 0, groupId, 0, 0.0f, groupName.toUtf8().constData());
  1271. }
  1272. bool portIsInput = (jackbridge_port_flags(jackPort) & JackPortIsInput);
  1273. bool portIsAudio = (std::strcmp(jackbridge_port_type(jackPort), JACK_DEFAULT_AUDIO_TYPE) == 0);
  1274. unsigned int portFlags = 0x0;
  1275. portFlags |= portIsInput ? PATCHBAY_PORT_IS_INPUT : PATCHBAY_PORT_IS_OUTPUT;
  1276. portFlags |= portIsAudio ? PATCHBAY_PORT_IS_AUDIO : PATCHBAY_PORT_IS_MIDI;
  1277. PortNameToId portNameToId;
  1278. portNameToId.groupId = groupId;
  1279. portNameToId.portId = fLastPortId;
  1280. portNameToId.name = portName;
  1281. portNameToId.fullName = fullName;
  1282. fUsedPortNames.append(portNameToId);
  1283. callback(CALLBACK_PATCHBAY_PORT_ADDED, 0, groupId, fLastPortId, portFlags, portName);
  1284. fLastPortId++;
  1285. }
  1286. jackbridge_free(ports);
  1287. }
  1288. // query connections, after all ports are in place
  1289. if (const char** ports = jackbridge_get_ports(fClient, nullptr, nullptr, JackPortIsOutput))
  1290. {
  1291. for (int i=0; ports[i] != nullptr; ++i)
  1292. {
  1293. jack_port_t* jackPort = jackbridge_port_by_name(fClient, ports[i]);
  1294. int thisPortId = getPortId(QString(ports[i]));
  1295. if (const char** jackConnections = jackbridge_port_get_connections(jackPort))
  1296. {
  1297. for (int j=0; jackConnections[j] != nullptr; ++j)
  1298. {
  1299. int targetPortId = getPortId(QString(jackConnections[j]));
  1300. ConnectionToId connectionToId;
  1301. connectionToId.id = fLastConnectionId;
  1302. connectionToId.portOut = thisPortId;
  1303. connectionToId.portIn = targetPortId;
  1304. fUsedConnections.append(connectionToId);
  1305. callback(CALLBACK_PATCHBAY_CONNECTION_ADDED, 0, fLastConnectionId, thisPortId, targetPortId, nullptr);
  1306. fLastConnectionId++;
  1307. }
  1308. jackbridge_free(jackConnections);
  1309. }
  1310. }
  1311. jackbridge_free(ports);
  1312. }
  1313. }
  1314. #endif
  1315. // -------------------------------------
  1316. void processPlugin(CarlaPlugin* const plugin, const uint32_t nframes)
  1317. {
  1318. const uint32_t inCount = plugin->audioInCount();
  1319. const uint32_t outCount = plugin->audioOutCount();
  1320. float* inBuffer[inCount];
  1321. float* outBuffer[outCount];
  1322. float inPeaks[inCount];
  1323. float outPeaks[outCount];
  1324. if (inCount > 0)
  1325. carla_zeroFloat(inPeaks, inCount);
  1326. if (outCount > 0)
  1327. carla_zeroFloat(outPeaks, outCount);
  1328. for (uint32_t i=0; i < inCount; ++i)
  1329. {
  1330. CarlaEngineAudioPort* const port = CarlaPluginGetAudioInPort(plugin, i);
  1331. inBuffer[i] = port->getBuffer();
  1332. }
  1333. for (uint32_t i=0; i < outCount; ++i)
  1334. {
  1335. CarlaEngineAudioPort* const port = CarlaPluginGetAudioOutPort(plugin, i);
  1336. outBuffer[i] = port->getBuffer();
  1337. }
  1338. for (uint32_t i=0; i < inCount; ++i)
  1339. {
  1340. for (uint32_t j=0; j < nframes; ++j)
  1341. {
  1342. const float absV = std::fabs(inBuffer[i][j]);
  1343. if (absV > inPeaks[i])
  1344. inPeaks[i] = absV;
  1345. }
  1346. }
  1347. plugin->process(inBuffer, outBuffer, nframes);
  1348. for (uint32_t i=0; i < outCount; ++i)
  1349. {
  1350. for (uint32_t j=0; j < nframes; ++j)
  1351. {
  1352. const float absV = std::fabs(outBuffer[i][j]);
  1353. if (absV > outPeaks[i])
  1354. outPeaks[i] = absV;
  1355. }
  1356. }
  1357. setPeaks(plugin->id(), inPeaks, outPeaks);
  1358. }
  1359. #if 0
  1360. void latencyPlugin(CarlaPlugin* const plugin, jack_latency_callback_mode_t mode)
  1361. {
  1362. const uint32_t inCount = plugin->audioInCount();
  1363. const uint32_t outCount = plugin->audioOutCount();
  1364. jack_latency_range_t range;
  1365. uint32_t pluginLatency = plugin->latency();
  1366. if (pluginLatency == 0)
  1367. return;
  1368. if (mode == JackCaptureLatency)
  1369. {
  1370. for (uint32_t i=0; i < inCount; ++i)
  1371. {
  1372. uint32_t aOutI = (i >= outCount) ? outCount : i;
  1373. jack_port_t* const portIn = ((CarlaEngineJackAudioPort*)CarlaPluginGetAudioInPort(plugin, i))->kPort;
  1374. jack_port_t* const portOut = ((CarlaEngineJackAudioPort*)CarlaPluginGetAudioOutPort(plugin, aOutI))->kPort;
  1375. jackbridge_port_get_latency_range(portIn, mode, &range);
  1376. range.min += pluginLatency;
  1377. range.max += pluginLatency;
  1378. jackbridge_port_set_latency_range(portOut, mode, &range);
  1379. }
  1380. }
  1381. else
  1382. {
  1383. for (uint32_t i=0; i < outCount; ++i)
  1384. {
  1385. uint32_t aInI = (i >= inCount) ? inCount : i;
  1386. jack_port_t* const portIn = ((CarlaEngineJackAudioPort*)CarlaPluginGetAudioInPort(plugin, aInI))->kPort;
  1387. jack_port_t* const portOut = ((CarlaEngineJackAudioPort*)CarlaPluginGetAudioOutPort(plugin, i))->kPort;
  1388. jackbridge_port_get_latency_range(portOut, mode, &range);
  1389. range.min += pluginLatency;
  1390. range.max += pluginLatency;
  1391. jackbridge_port_set_latency_range(portIn, mode, &range);
  1392. }
  1393. }
  1394. }
  1395. #endif
  1396. // -------------------------------------
  1397. #define handlePtr ((CarlaEngineJack*)arg)
  1398. static int carla_jack_srate_callback(jack_nframes_t newSampleRate, void* arg)
  1399. {
  1400. handlePtr->handleJackSampleRateCallback(newSampleRate);
  1401. return 0;
  1402. }
  1403. static int carla_jack_bufsize_callback(jack_nframes_t newBufferSize, void* arg)
  1404. {
  1405. handlePtr->handleJackBufferSizeCallback(newBufferSize);
  1406. return 0;
  1407. }
  1408. static void carla_jack_freewheel_callback(int starting, void* arg)
  1409. {
  1410. handlePtr->handleJackFreewheelCallback(bool(starting));
  1411. }
  1412. static int carla_jack_process_callback(jack_nframes_t nframes, void* arg)
  1413. {
  1414. handlePtr->handleJackProcessCallback(nframes);
  1415. return 0;
  1416. }
  1417. #if 0
  1418. static void carla_jack_latency_callback(jack_latency_callback_mode_t mode, void* arg)
  1419. {
  1420. handlePtr->handleJackLatencyCallback(mode);
  1421. }
  1422. #endif
  1423. #ifndef BUILD_BRIDGE
  1424. static void carla_jack_client_registration_callback(const char* name, int reg, void* arg)
  1425. {
  1426. handlePtr->handleJackClientRegistrationCallback(name, (reg != 0));
  1427. }
  1428. static void carla_jack_port_registration_callback(jack_port_id_t port, int reg, void* arg)
  1429. {
  1430. handlePtr->handleJackPortRegistrationCallback(port, (reg != 0));
  1431. }
  1432. static void carla_jack_port_connect_callback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg)
  1433. {
  1434. handlePtr->handleJackPortConnectCallback(a, b, (connect != 0));
  1435. }
  1436. static int carla_jack_port_rename_callback(jack_port_id_t port, const char* oldName, const char* newName, void* arg)
  1437. {
  1438. handlePtr->handleJackPortRenameCallback(port, oldName, newName);
  1439. return 0;
  1440. }
  1441. #endif
  1442. static void carla_jack_shutdown_callback(void* arg)
  1443. {
  1444. handlePtr->handleJackShutdownCallback();
  1445. }
  1446. #undef handlePtr
  1447. // -------------------------------------
  1448. #ifndef BUILD_BRIDGE
  1449. static int carla_jack_process_callback_plugin(jack_nframes_t nframes, void* arg)
  1450. {
  1451. CarlaPlugin* const plugin = (CarlaPlugin*)arg;
  1452. if (plugin != nullptr && plugin->enabled() && plugin->tryLock())
  1453. {
  1454. CarlaEngineJack* const engine = (CarlaEngineJack*)CarlaPluginGetEngine(plugin);
  1455. plugin->initBuffers();
  1456. engine->saveTransportInfo();
  1457. engine->processPlugin(plugin, nframes);
  1458. plugin->unlock();
  1459. }
  1460. else
  1461. carla_stdout("Plugin not enabled or locked");
  1462. return 0;
  1463. }
  1464. # if 0
  1465. static void carla_jack_latency_callback_plugin(jack_latency_callback_mode_t mode, void* arg)
  1466. {
  1467. CarlaPlugin* const plugin = (CarlaPlugin*)arg;
  1468. if (plugin != nullptr && plugin->enabled())
  1469. {
  1470. CarlaEngineJack* const engine = (CarlaEngineJack*)CarlaPluginGetEngine(plugin);
  1471. engine->latencyPlugin(plugin, mode);
  1472. }
  1473. }
  1474. # endif
  1475. #endif
  1476. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJack)
  1477. };
  1478. // -----------------------------------------
  1479. CarlaEngine* CarlaEngine::newJack()
  1480. {
  1481. return new CarlaEngineJack();
  1482. }
  1483. // -----------------------------------------
  1484. CARLA_BACKEND_END_NAMESPACE