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.

juce_linux_JackAudio.cpp 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. //==============================================================================
  18. static void* juce_libjackHandle = nullptr;
  19. static void* juce_loadJackFunction (const char* const name)
  20. {
  21. if (juce_libjackHandle == nullptr)
  22. return nullptr;
  23. return dlsym (juce_libjackHandle, name);
  24. }
  25. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  26. return_type fn_name argument_types \
  27. { \
  28. typedef return_type (*fn_type) argument_types; \
  29. static fn_type fn = (fn_type) juce_loadJackFunction (#fn_name); \
  30. return (fn != nullptr) ? ((*fn) arguments) : (return_type) 0; \
  31. }
  32. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  33. void fn_name argument_types \
  34. { \
  35. typedef void (*fn_type) argument_types; \
  36. static fn_type fn = (fn_type) juce_loadJackFunction (#fn_name); \
  37. if (fn != nullptr) (*fn) arguments; \
  38. }
  39. //==============================================================================
  40. JUCE_DECL_JACK_FUNCTION (jack_client_t*, jack_client_open, (const char* client_name, jack_options_t options, jack_status_t* status, ...), (client_name, options, status));
  41. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  42. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  43. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  44. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  45. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  46. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  47. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  48. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  49. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_register, (jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size), (client, port_name, port_type, flags, buffer_size));
  50. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  51. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  52. JUCE_DECL_JACK_FUNCTION (const char**, jack_get_ports, (jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags), (client, port_name_pattern, type_name_pattern, flags));
  53. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  54. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  55. JUCE_DECL_JACK_FUNCTION (void*, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  56. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  57. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  58. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  59. #if JUCE_DEBUG
  60. #define JACK_LOGGING_ENABLED 1
  61. #endif
  62. #if JACK_LOGGING_ENABLED
  63. namespace
  64. {
  65. void jack_Log (const String& s)
  66. {
  67. std::cerr << s << std::endl;
  68. }
  69. const char* getJackErrorMessage (const jack_status_t status)
  70. {
  71. if (status & JackServerFailed
  72. || status & JackServerError) return "Unable to connect to JACK server";
  73. if (status & JackVersionError) return "Client's protocol version does not match";
  74. if (status & JackInvalidOption) return "The operation contained an invalid or unsupported option";
  75. if (status & JackNameNotUnique) return "The desired client name was not unique";
  76. if (status & JackNoSuchClient) return "Requested client does not exist";
  77. if (status & JackInitFailure) return "Unable to initialize client";
  78. return nullptr;
  79. }
  80. }
  81. #define JUCE_JACK_LOG_STATUS(x) { if (const char* m = getJackErrorMessage (x)) jack_Log (m); }
  82. #define JUCE_JACK_LOG(x) jack_Log(x)
  83. #else
  84. #define JUCE_JACK_LOG_STATUS(x) {}
  85. #define JUCE_JACK_LOG(x) {}
  86. #endif
  87. //==============================================================================
  88. #ifndef JUCE_JACK_CLIENT_NAME
  89. #define JUCE_JACK_CLIENT_NAME "JUCEJack"
  90. #endif
  91. struct JackPortIterator
  92. {
  93. JackPortIterator (jack_client_t* const client, const bool forInput)
  94. : ports (nullptr), index (-1)
  95. {
  96. if (client != nullptr)
  97. ports = juce::jack_get_ports (client, nullptr, nullptr,
  98. forInput ? JackPortIsOutput : JackPortIsInput);
  99. // (NB: This looks like it's the wrong way round, but it is correct!)
  100. }
  101. ~JackPortIterator()
  102. {
  103. ::free (ports);
  104. }
  105. bool next()
  106. {
  107. if (ports == nullptr || ports [index + 1] == nullptr)
  108. return false;
  109. name = CharPointer_UTF8 (ports[++index]);
  110. clientName = name.upToFirstOccurrenceOf (":", false, false);
  111. return true;
  112. }
  113. const char** ports;
  114. int index;
  115. String name;
  116. String clientName;
  117. };
  118. class JackAudioIODeviceType;
  119. static Array<JackAudioIODeviceType*> activeDeviceTypes;
  120. //==============================================================================
  121. class JackAudioIODevice : public AudioIODevice
  122. {
  123. public:
  124. JackAudioIODevice (const String& deviceName,
  125. const String& inId,
  126. const String& outId)
  127. : AudioIODevice (deviceName, "JACK"),
  128. inputId (inId),
  129. outputId (outId),
  130. deviceIsOpen (false),
  131. callback (nullptr),
  132. totalNumberOfInputChannels (0),
  133. totalNumberOfOutputChannels (0)
  134. {
  135. jassert (deviceName.isNotEmpty());
  136. jack_status_t status;
  137. client = juce::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  138. if (client == nullptr)
  139. {
  140. JUCE_JACK_LOG_STATUS (status);
  141. }
  142. else
  143. {
  144. juce::jack_set_error_function (errorCallback);
  145. // open input ports
  146. const StringArray inputChannels (getInputChannelNames());
  147. for (int i = 0; i < inputChannels.size(); ++i)
  148. {
  149. String inputName;
  150. inputName << "in_" << ++totalNumberOfInputChannels;
  151. inputPorts.add (juce::jack_port_register (client, inputName.toUTF8(),
  152. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  153. }
  154. // open output ports
  155. const StringArray outputChannels (getOutputChannelNames());
  156. for (int i = 0; i < outputChannels.size (); ++i)
  157. {
  158. String outputName;
  159. outputName << "out_" << ++totalNumberOfOutputChannels;
  160. outputPorts.add (juce::jack_port_register (client, outputName.toUTF8(),
  161. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  162. }
  163. inChans.calloc (totalNumberOfInputChannels + 2);
  164. outChans.calloc (totalNumberOfOutputChannels + 2);
  165. }
  166. }
  167. ~JackAudioIODevice()
  168. {
  169. close();
  170. if (client != nullptr)
  171. {
  172. juce::jack_client_close (client);
  173. client = nullptr;
  174. }
  175. }
  176. StringArray getChannelNames (bool forInput) const
  177. {
  178. StringArray names;
  179. for (JackPortIterator i (client, forInput); i.next();)
  180. if (i.clientName == getName())
  181. names.add (i.name.fromFirstOccurrenceOf (":", false, false));
  182. return names;
  183. }
  184. StringArray getOutputChannelNames() { return getChannelNames (false); }
  185. StringArray getInputChannelNames() { return getChannelNames (true); }
  186. int getNumSampleRates() { return client != nullptr ? 1 : 0; }
  187. double getSampleRate (int /*index*/) { return client != nullptr ? juce::jack_get_sample_rate (client) : 0; }
  188. int getNumBufferSizesAvailable() { return client != nullptr ? 1 : 0; }
  189. int getBufferSizeSamples (int /*index*/) { return getDefaultBufferSize(); }
  190. int getDefaultBufferSize() { return client != nullptr ? juce::jack_get_buffer_size (client) : 0; }
  191. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  192. double /* sampleRate */, int /* bufferSizeSamples */)
  193. {
  194. if (client == nullptr)
  195. {
  196. lastError = "No JACK client running";
  197. return lastError;
  198. }
  199. lastError = String::empty;
  200. close();
  201. juce::jack_set_process_callback (client, processCallback, this);
  202. juce::jack_set_port_connect_callback (client, portConnectCallback, this);
  203. juce::jack_on_shutdown (client, shutdownCallback, this);
  204. juce::jack_activate (client);
  205. deviceIsOpen = true;
  206. if (! inputChannels.isZero())
  207. {
  208. for (JackPortIterator i (client, true); i.next();)
  209. {
  210. if (inputChannels [i.index] && i.clientName == getName())
  211. {
  212. int error = juce::jack_connect (client, i.ports[i.index], juce::jack_port_name ((jack_port_t*) inputPorts[i.index]));
  213. if (error != 0)
  214. JUCE_JACK_LOG ("Cannot connect input port " + String (i.index) + " (" + i.name + "), error " + String (error));
  215. }
  216. }
  217. }
  218. if (! outputChannels.isZero())
  219. {
  220. for (JackPortIterator i (client, false); i.next();)
  221. {
  222. if (outputChannels [i.index] && i.clientName == getName())
  223. {
  224. int error = juce::jack_connect (client, juce::jack_port_name ((jack_port_t*) outputPorts[i.index]), i.ports[i.index]);
  225. if (error != 0)
  226. JUCE_JACK_LOG ("Cannot connect output port " + String (i.index) + " (" + i.name + "), error " + String (error));
  227. }
  228. }
  229. }
  230. return lastError;
  231. }
  232. void close()
  233. {
  234. stop();
  235. if (client != nullptr)
  236. {
  237. juce::jack_deactivate (client);
  238. juce::jack_set_process_callback (client, processCallback, nullptr);
  239. juce::jack_set_port_connect_callback (client, portConnectCallback, nullptr);
  240. juce::jack_on_shutdown (client, shutdownCallback, nullptr);
  241. }
  242. deviceIsOpen = false;
  243. }
  244. void start (AudioIODeviceCallback* newCallback)
  245. {
  246. if (deviceIsOpen && newCallback != callback)
  247. {
  248. if (newCallback != nullptr)
  249. newCallback->audioDeviceAboutToStart (this);
  250. AudioIODeviceCallback* const oldCallback = callback;
  251. {
  252. const ScopedLock sl (callbackLock);
  253. callback = newCallback;
  254. }
  255. if (oldCallback != nullptr)
  256. oldCallback->audioDeviceStopped();
  257. }
  258. }
  259. void stop()
  260. {
  261. start (nullptr);
  262. }
  263. bool isOpen() { return deviceIsOpen; }
  264. bool isPlaying() { return callback != nullptr; }
  265. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  266. double getCurrentSampleRate() { return getSampleRate (0); }
  267. int getCurrentBitDepth() { return 32; }
  268. String getLastError() { return lastError; }
  269. BigInteger getActiveOutputChannels() const { return activeOutputChannels; }
  270. BigInteger getActiveInputChannels() const { return activeInputChannels; }
  271. int getOutputLatencyInSamples()
  272. {
  273. int latency = 0;
  274. for (int i = 0; i < outputPorts.size(); i++)
  275. latency = jmax (latency, (int) juce::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  276. return latency;
  277. }
  278. int getInputLatencyInSamples()
  279. {
  280. int latency = 0;
  281. for (int i = 0; i < inputPorts.size(); i++)
  282. latency = jmax (latency, (int) juce::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  283. return latency;
  284. }
  285. String inputId, outputId;
  286. private:
  287. void process (const int numSamples)
  288. {
  289. int numActiveInChans = 0, numActiveOutChans = 0;
  290. for (int i = 0; i < totalNumberOfInputChannels; ++i)
  291. {
  292. if (activeInputChannels[i])
  293. if (jack_default_audio_sample_t* in
  294. = (jack_default_audio_sample_t*) juce::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples))
  295. inChans [numActiveInChans++] = (float*) in;
  296. }
  297. for (int i = 0; i < totalNumberOfOutputChannels; ++i)
  298. {
  299. if (activeOutputChannels[i])
  300. if (jack_default_audio_sample_t* out
  301. = (jack_default_audio_sample_t*) juce::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples))
  302. outChans [numActiveOutChans++] = (float*) out;
  303. }
  304. const ScopedLock sl (callbackLock);
  305. if (callback != nullptr)
  306. {
  307. if ((numActiveInChans + numActiveOutChans) > 0)
  308. callback->audioDeviceIOCallback (const_cast <const float**> (inChans.getData()), numActiveInChans,
  309. outChans, numActiveOutChans, numSamples);
  310. }
  311. else
  312. {
  313. for (int i = 0; i < numActiveOutChans; ++i)
  314. zeromem (outChans[i], sizeof (float) * numSamples);
  315. }
  316. }
  317. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  318. {
  319. if (callbackArgument != nullptr)
  320. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  321. return 0;
  322. }
  323. void updateActivePorts()
  324. {
  325. BigInteger newOutputChannels, newInputChannels;
  326. for (int i = 0; i < outputPorts.size(); ++i)
  327. if (juce::jack_port_connected ((jack_port_t*) outputPorts.getUnchecked(i)))
  328. newOutputChannels.setBit (i);
  329. for (int i = 0; i < inputPorts.size(); ++i)
  330. if (juce::jack_port_connected ((jack_port_t*) inputPorts.getUnchecked(i)))
  331. newInputChannels.setBit (i);
  332. if (newOutputChannels != activeOutputChannels
  333. || newInputChannels != activeInputChannels)
  334. {
  335. AudioIODeviceCallback* const oldCallback = callback;
  336. stop();
  337. activeOutputChannels = newOutputChannels;
  338. activeInputChannels = newInputChannels;
  339. if (oldCallback != nullptr)
  340. start (oldCallback);
  341. sendDeviceChangedCallback();
  342. }
  343. }
  344. static void portConnectCallback (jack_port_id_t, jack_port_id_t, int, void* arg)
  345. {
  346. if (JackAudioIODevice* device = static_cast <JackAudioIODevice*> (arg))
  347. device->updateActivePorts();
  348. }
  349. static void threadInitCallback (void* /* callbackArgument */)
  350. {
  351. JUCE_JACK_LOG ("JackAudioIODevice::initialise");
  352. }
  353. static void shutdownCallback (void* callbackArgument)
  354. {
  355. JUCE_JACK_LOG ("JackAudioIODevice::shutdown");
  356. if (JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument)
  357. {
  358. device->client = nullptr;
  359. device->close();
  360. }
  361. }
  362. static void errorCallback (const char* msg)
  363. {
  364. JUCE_JACK_LOG ("JackAudioIODevice::errorCallback " + String (msg));
  365. }
  366. static void sendDeviceChangedCallback();
  367. bool deviceIsOpen;
  368. jack_client_t* client;
  369. String lastError;
  370. AudioIODeviceCallback* callback;
  371. CriticalSection callbackLock;
  372. HeapBlock <float*> inChans, outChans;
  373. int totalNumberOfInputChannels;
  374. int totalNumberOfOutputChannels;
  375. Array<void*> inputPorts, outputPorts;
  376. BigInteger activeInputChannels, activeOutputChannels;
  377. };
  378. //==============================================================================
  379. class JackAudioIODeviceType : public AudioIODeviceType
  380. {
  381. public:
  382. JackAudioIODeviceType()
  383. : AudioIODeviceType ("JACK"),
  384. hasScanned (false)
  385. {
  386. activeDeviceTypes.add (this);
  387. }
  388. ~JackAudioIODeviceType()
  389. {
  390. activeDeviceTypes.removeFirstMatchingValue (this);
  391. }
  392. void scanForDevices()
  393. {
  394. hasScanned = true;
  395. inputNames.clear();
  396. inputIds.clear();
  397. outputNames.clear();
  398. outputIds.clear();
  399. if (juce_libjackHandle == nullptr)
  400. {
  401. juce_libjackHandle = dlopen ("libjack.so", RTLD_LAZY);
  402. if (juce_libjackHandle == nullptr)
  403. return;
  404. }
  405. jack_status_t status;
  406. // open a dummy client
  407. if (jack_client_t* const client = juce::jack_client_open ("JuceJackDummy", JackNoStartServer, &status))
  408. {
  409. // scan for output devices
  410. for (JackPortIterator i (client, false); i.next();)
  411. {
  412. if (i.clientName != (JUCE_JACK_CLIENT_NAME) && ! inputNames.contains (i.clientName))
  413. {
  414. inputNames.add (i.clientName);
  415. inputIds.add (i.ports [i.index]);
  416. }
  417. }
  418. // scan for input devices
  419. for (JackPortIterator i (client, true); i.next();)
  420. {
  421. if (i.clientName != (JUCE_JACK_CLIENT_NAME) && ! outputNames.contains (i.clientName))
  422. {
  423. outputNames.add (i.clientName);
  424. outputIds.add (i.ports [i.index]);
  425. }
  426. }
  427. juce::jack_client_close (client);
  428. }
  429. else
  430. {
  431. JUCE_JACK_LOG_STATUS (status);
  432. }
  433. }
  434. StringArray getDeviceNames (bool wantInputNames) const
  435. {
  436. jassert (hasScanned); // need to call scanForDevices() before doing this
  437. return wantInputNames ? inputNames : outputNames;
  438. }
  439. int getDefaultDeviceIndex (bool /* forInput */) const
  440. {
  441. jassert (hasScanned); // need to call scanForDevices() before doing this
  442. return 0;
  443. }
  444. bool hasSeparateInputsAndOutputs() const { return true; }
  445. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  446. {
  447. jassert (hasScanned); // need to call scanForDevices() before doing this
  448. if (JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device))
  449. return asInput ? inputIds.indexOf (d->inputId)
  450. : outputIds.indexOf (d->outputId);
  451. return -1;
  452. }
  453. AudioIODevice* createDevice (const String& outputDeviceName,
  454. const String& inputDeviceName)
  455. {
  456. jassert (hasScanned); // need to call scanForDevices() before doing this
  457. const int inputIndex = inputNames.indexOf (inputDeviceName);
  458. const int outputIndex = outputNames.indexOf (outputDeviceName);
  459. if (inputIndex >= 0 || outputIndex >= 0)
  460. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  461. : inputDeviceName,
  462. inputIds [inputIndex],
  463. outputIds [outputIndex]);
  464. return nullptr;
  465. }
  466. void portConnectionChange() { callDeviceChangeListeners(); }
  467. private:
  468. StringArray inputNames, outputNames, inputIds, outputIds;
  469. bool hasScanned;
  470. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType)
  471. };
  472. void JackAudioIODevice::sendDeviceChangedCallback()
  473. {
  474. for (int i = activeDeviceTypes.size(); --i >= 0;)
  475. if (JackAudioIODeviceType* d = activeDeviceTypes[i])
  476. d->portConnectionChange();
  477. }
  478. //==============================================================================
  479. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK()
  480. {
  481. return new JackAudioIODeviceType();
  482. }