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.

629 lines
23KB

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