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.

626 lines
23KB

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