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.

625 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. }
  389. static void sendDeviceChangedCallback();
  390. bool deviceIsOpen;
  391. jack_client_t* client;
  392. String lastError;
  393. AudioIODeviceCallback* callback;
  394. CriticalSection callbackLock;
  395. HeapBlock<float*> inChans, outChans;
  396. int totalNumberOfInputChannels;
  397. int totalNumberOfOutputChannels;
  398. Array<void*> inputPorts, outputPorts;
  399. BigInteger activeInputChannels, activeOutputChannels;
  400. int xruns;
  401. };
  402. //==============================================================================
  403. class JackAudioIODeviceType : public AudioIODeviceType
  404. {
  405. public:
  406. JackAudioIODeviceType()
  407. : AudioIODeviceType ("JACK"),
  408. hasScanned (false)
  409. {
  410. activeDeviceTypes.add (this);
  411. }
  412. ~JackAudioIODeviceType()
  413. {
  414. activeDeviceTypes.removeFirstMatchingValue (this);
  415. }
  416. void scanForDevices()
  417. {
  418. hasScanned = true;
  419. inputNames.clear();
  420. inputIds.clear();
  421. outputNames.clear();
  422. outputIds.clear();
  423. if (juce_libjackHandle == nullptr) juce_libjackHandle = dlopen ("libjack.so.0", RTLD_LAZY);
  424. if (juce_libjackHandle == nullptr) juce_libjackHandle = dlopen ("libjack.so", RTLD_LAZY);
  425. if (juce_libjackHandle == nullptr) return;
  426. jack_status_t status;
  427. // open a dummy client
  428. if (jack_client_t* const client = juce::jack_client_open ("JuceJackDummy", JackNoStartServer, &status))
  429. {
  430. // scan for output devices
  431. for (JackPortIterator i (client, false); i.next();)
  432. {
  433. if (i.clientName != (JUCE_JACK_CLIENT_NAME) && ! inputNames.contains (i.clientName))
  434. {
  435. inputNames.add (i.clientName);
  436. inputIds.add (i.ports [i.index]);
  437. }
  438. }
  439. // scan for input devices
  440. for (JackPortIterator i (client, true); i.next();)
  441. {
  442. if (i.clientName != (JUCE_JACK_CLIENT_NAME) && ! outputNames.contains (i.clientName))
  443. {
  444. outputNames.add (i.clientName);
  445. outputIds.add (i.ports [i.index]);
  446. }
  447. }
  448. juce::jack_client_close (client);
  449. }
  450. else
  451. {
  452. JUCE_JACK_LOG_STATUS (status);
  453. }
  454. }
  455. StringArray getDeviceNames (bool wantInputNames) const
  456. {
  457. jassert (hasScanned); // need to call scanForDevices() before doing this
  458. return wantInputNames ? inputNames : outputNames;
  459. }
  460. int getDefaultDeviceIndex (bool /* forInput */) const
  461. {
  462. jassert (hasScanned); // need to call scanForDevices() before doing this
  463. return 0;
  464. }
  465. bool hasSeparateInputsAndOutputs() const { return true; }
  466. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  467. {
  468. jassert (hasScanned); // need to call scanForDevices() before doing this
  469. if (JackAudioIODevice* d = dynamic_cast<JackAudioIODevice*> (device))
  470. return asInput ? inputIds.indexOf (d->inputId)
  471. : outputIds.indexOf (d->outputId);
  472. return -1;
  473. }
  474. AudioIODevice* createDevice (const String& outputDeviceName,
  475. const String& inputDeviceName)
  476. {
  477. jassert (hasScanned); // need to call scanForDevices() before doing this
  478. const int inputIndex = inputNames.indexOf (inputDeviceName);
  479. const int outputIndex = outputNames.indexOf (outputDeviceName);
  480. if (inputIndex >= 0 || outputIndex >= 0)
  481. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  482. : inputDeviceName,
  483. inputIds [inputIndex],
  484. outputIds [outputIndex]);
  485. return nullptr;
  486. }
  487. void portConnectionChange() { callDeviceChangeListeners(); }
  488. private:
  489. StringArray inputNames, outputNames, inputIds, outputIds;
  490. bool hasScanned;
  491. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType)
  492. };
  493. void JackAudioIODevice::sendDeviceChangedCallback()
  494. {
  495. for (int i = activeDeviceTypes.size(); --i >= 0;)
  496. if (JackAudioIODeviceType* d = activeDeviceTypes[i])
  497. d->portConnectionChange();
  498. }
  499. //==============================================================================
  500. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK()
  501. {
  502. return new JackAudioIODeviceType();
  503. }
  504. } // namespace juce