The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

609 lines
22KB

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