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.

563 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  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 (int, 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. void dumpJackErrorMessage (const jack_status_t status)
  71. {
  72. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  73. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  74. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  75. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  76. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  77. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  78. }
  79. }
  80. #else
  81. #define dumpJackErrorMessage(a) {}
  82. #define jack_Log(...) {}
  83. #endif
  84. //==============================================================================
  85. #ifndef JUCE_JACK_CLIENT_NAME
  86. #define JUCE_JACK_CLIENT_NAME "JUCEJack"
  87. #endif
  88. static const char** getJackPorts (jack_client_t* const client, const bool forInput)
  89. {
  90. return juce::jack_get_ports (client, nullptr, nullptr,
  91. forInput ? JackPortIsOutput : JackPortIsInput);
  92. // (NB: This looks like it's the wrong way round, but it is correct!)
  93. }
  94. //==============================================================================
  95. class JackAudioIODevice : public AudioIODevice
  96. {
  97. public:
  98. JackAudioIODevice (const String& deviceName,
  99. const String& inId,
  100. const String& outId)
  101. : AudioIODevice (deviceName, "JACK"),
  102. inputId (inId),
  103. outputId (outId),
  104. isOpen_ (false),
  105. callback (nullptr),
  106. totalNumberOfInputChannels (0),
  107. totalNumberOfOutputChannels (0)
  108. {
  109. jassert (deviceName.isNotEmpty());
  110. jack_status_t status;
  111. client = juce::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  112. if (client == nullptr)
  113. {
  114. dumpJackErrorMessage (status);
  115. }
  116. else
  117. {
  118. juce::jack_set_error_function (errorCallback);
  119. // open input ports
  120. const StringArray inputChannels (getInputChannelNames());
  121. for (int i = 0; i < inputChannels.size(); ++i)
  122. {
  123. String inputName;
  124. inputName << "in_" << ++totalNumberOfInputChannels;
  125. inputPorts.add (juce::jack_port_register (client, inputName.toUTF8(),
  126. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  127. }
  128. // open output ports
  129. const StringArray outputChannels (getOutputChannelNames());
  130. for (int i = 0; i < outputChannels.size (); ++i)
  131. {
  132. String outputName;
  133. outputName << "out_" << ++totalNumberOfOutputChannels;
  134. outputPorts.add (juce::jack_port_register (client, outputName.toUTF8(),
  135. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  136. }
  137. inChans.calloc (totalNumberOfInputChannels + 2);
  138. outChans.calloc (totalNumberOfOutputChannels + 2);
  139. }
  140. }
  141. ~JackAudioIODevice()
  142. {
  143. close();
  144. if (client != nullptr)
  145. {
  146. juce::jack_client_close (client);
  147. client = nullptr;
  148. }
  149. }
  150. StringArray getChannelNames (bool forInput) const
  151. {
  152. StringArray names;
  153. if (const char** const ports = getJackPorts (client, forInput))
  154. {
  155. for (int j = 0; ports[j] != nullptr; ++j)
  156. {
  157. const String portName (ports [j]);
  158. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  159. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  160. }
  161. free (ports);
  162. }
  163. return names;
  164. }
  165. StringArray getOutputChannelNames() { return getChannelNames (false); }
  166. StringArray getInputChannelNames() { return getChannelNames (true); }
  167. int getNumSampleRates() { return client != nullptr ? 1 : 0; }
  168. double getSampleRate (int /*index*/) { return client != nullptr ? juce::jack_get_sample_rate (client) : 0; }
  169. int getNumBufferSizesAvailable() { return client != nullptr ? 1 : 0; }
  170. int getBufferSizeSamples (int /*index*/) { return getDefaultBufferSize(); }
  171. int getDefaultBufferSize() { return client != nullptr ? juce::jack_get_buffer_size (client) : 0; }
  172. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  173. double /* sampleRate */, int /* bufferSizeSamples */)
  174. {
  175. if (client == nullptr)
  176. {
  177. lastError = "No JACK client running";
  178. return lastError;
  179. }
  180. lastError = String::empty;
  181. close();
  182. juce::jack_set_process_callback (client, processCallback, this);
  183. juce::jack_on_shutdown (client, shutdownCallback, this);
  184. juce::jack_activate (client);
  185. isOpen_ = true;
  186. if (! inputChannels.isZero())
  187. {
  188. if (const char** const ports = getJackPorts (client, true))
  189. {
  190. const int numInputChannels = inputChannels.getHighestBit() + 1;
  191. for (int i = 0; i < numInputChannels; ++i)
  192. {
  193. const String portName (ports[i]);
  194. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  195. {
  196. int error = juce::jack_connect (client, ports[i], juce::jack_port_name ((jack_port_t*) inputPorts[i]));
  197. if (error != 0)
  198. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  199. }
  200. }
  201. free (ports);
  202. }
  203. }
  204. if (! outputChannels.isZero())
  205. {
  206. if (const char** const ports = getJackPorts (client, false))
  207. {
  208. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  209. for (int i = 0; i < numOutputChannels; ++i)
  210. {
  211. const String portName (ports[i]);
  212. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  213. {
  214. int error = juce::jack_connect (client, juce::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  215. if (error != 0)
  216. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  217. }
  218. }
  219. free (ports);
  220. }
  221. }
  222. return lastError;
  223. }
  224. void close()
  225. {
  226. stop();
  227. if (client != nullptr)
  228. {
  229. juce::jack_deactivate (client);
  230. juce::jack_set_process_callback (client, processCallback, nullptr);
  231. juce::jack_on_shutdown (client, shutdownCallback, nullptr);
  232. }
  233. isOpen_ = false;
  234. }
  235. void start (AudioIODeviceCallback* newCallback)
  236. {
  237. if (isOpen_ && newCallback != callback)
  238. {
  239. if (newCallback != nullptr)
  240. newCallback->audioDeviceAboutToStart (this);
  241. AudioIODeviceCallback* const oldCallback = callback;
  242. {
  243. const ScopedLock sl (callbackLock);
  244. callback = newCallback;
  245. }
  246. if (oldCallback != nullptr)
  247. oldCallback->audioDeviceStopped();
  248. }
  249. }
  250. void stop()
  251. {
  252. start (nullptr);
  253. }
  254. bool isOpen() { return isOpen_; }
  255. bool isPlaying() { return callback != nullptr; }
  256. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  257. double getCurrentSampleRate() { return getSampleRate (0); }
  258. int getCurrentBitDepth() { return 32; }
  259. String getLastError() { return lastError; }
  260. BigInteger getActiveOutputChannels() const
  261. {
  262. BigInteger outputBits;
  263. for (int i = 0; i < outputPorts.size(); i++)
  264. if (juce::jack_port_connected ((jack_port_t*) outputPorts [i]))
  265. outputBits.setBit (i);
  266. return outputBits;
  267. }
  268. BigInteger getActiveInputChannels() const
  269. {
  270. BigInteger inputBits;
  271. for (int i = 0; i < inputPorts.size(); i++)
  272. if (juce::jack_port_connected ((jack_port_t*) inputPorts [i]))
  273. inputBits.setBit (i);
  274. return inputBits;
  275. }
  276. int getOutputLatencyInSamples()
  277. {
  278. int latency = 0;
  279. for (int i = 0; i < outputPorts.size(); i++)
  280. latency = jmax (latency, (int) juce::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  281. return latency;
  282. }
  283. int getInputLatencyInSamples()
  284. {
  285. int latency = 0;
  286. for (int i = 0; i < inputPorts.size(); i++)
  287. latency = jmax (latency, (int) juce::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  288. return latency;
  289. }
  290. String inputId, outputId;
  291. private:
  292. void process (const int numSamples)
  293. {
  294. int numActiveInChans = 0, numActiveOutChans = 0;
  295. for (int i = 0; i < totalNumberOfInputChannels; ++i)
  296. {
  297. if (jack_default_audio_sample_t* in
  298. = (jack_default_audio_sample_t*) juce::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples))
  299. inChans [numActiveInChans++] = (float*) in;
  300. }
  301. for (int i = 0; i < totalNumberOfOutputChannels; ++i)
  302. {
  303. if (jack_default_audio_sample_t* out
  304. = (jack_default_audio_sample_t*) juce::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples))
  305. outChans [numActiveOutChans++] = (float*) out;
  306. }
  307. const ScopedLock sl (callbackLock);
  308. if (callback != nullptr)
  309. {
  310. callback->audioDeviceIOCallback (const_cast <const float**> (inChans.getData()), numActiveInChans,
  311. outChans, numActiveOutChans, numSamples);
  312. }
  313. else
  314. {
  315. for (int i = 0; i < numActiveOutChans; ++i)
  316. zeromem (outChans[i], sizeof (float) * numSamples);
  317. }
  318. }
  319. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  320. {
  321. if (callbackArgument != nullptr)
  322. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  323. return 0;
  324. }
  325. static void threadInitCallback (void* /* callbackArgument */)
  326. {
  327. jack_Log ("JackAudioIODevice::initialise");
  328. }
  329. static void shutdownCallback (void* callbackArgument)
  330. {
  331. jack_Log ("JackAudioIODevice::shutdown");
  332. if (JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument)
  333. {
  334. device->client = nullptr;
  335. device->close();
  336. }
  337. }
  338. static void errorCallback (const char* msg)
  339. {
  340. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  341. }
  342. bool isOpen_;
  343. jack_client_t* client;
  344. String lastError;
  345. AudioIODeviceCallback* callback;
  346. CriticalSection callbackLock;
  347. HeapBlock <float*> inChans, outChans;
  348. int totalNumberOfInputChannels;
  349. int totalNumberOfOutputChannels;
  350. Array<void*> inputPorts, outputPorts;
  351. };
  352. //==============================================================================
  353. class JackAudioIODeviceType : public AudioIODeviceType
  354. {
  355. public:
  356. JackAudioIODeviceType()
  357. : AudioIODeviceType ("JACK"),
  358. hasScanned (false)
  359. {
  360. }
  361. void scanForDevices()
  362. {
  363. hasScanned = true;
  364. inputNames.clear();
  365. inputIds.clear();
  366. outputNames.clear();
  367. outputIds.clear();
  368. if (juce_libjackHandle == nullptr)
  369. {
  370. juce_libjackHandle = dlopen ("libjack.so", RTLD_LAZY);
  371. if (juce_libjackHandle == nullptr)
  372. return;
  373. }
  374. jack_status_t status;
  375. // open a dummy client
  376. if (jack_client_t* const client = juce::jack_client_open ("JuceJackDummy", JackNoStartServer, &status))
  377. {
  378. // scan for output devices
  379. if (const char** const ports = getJackPorts (client, false))
  380. {
  381. for (int j = 0; ports[j] != nullptr; ++j)
  382. {
  383. String clientName (ports[j]);
  384. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  385. if (clientName != (JUCE_JACK_CLIENT_NAME) && ! inputNames.contains (clientName))
  386. {
  387. inputNames.add (clientName);
  388. inputIds.add (ports [j]);
  389. }
  390. }
  391. free (ports);
  392. }
  393. // scan for input devices
  394. if (const char** const ports = getJackPorts (client, true))
  395. {
  396. for (int j = 0; ports[j] != nullptr; ++j)
  397. {
  398. String clientName (ports[j]);
  399. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  400. if (clientName != (JUCE_JACK_CLIENT_NAME) && ! outputNames.contains (clientName))
  401. {
  402. outputNames.add (clientName);
  403. outputIds.add (ports [j]);
  404. }
  405. }
  406. free (ports);
  407. }
  408. juce::jack_client_close (client);
  409. }
  410. else
  411. {
  412. dumpJackErrorMessage (status);
  413. }
  414. }
  415. StringArray getDeviceNames (bool wantInputNames) const
  416. {
  417. jassert (hasScanned); // need to call scanForDevices() before doing this
  418. return wantInputNames ? inputNames : outputNames;
  419. }
  420. int getDefaultDeviceIndex (bool /* forInput */) const
  421. {
  422. jassert (hasScanned); // need to call scanForDevices() before doing this
  423. return 0;
  424. }
  425. bool hasSeparateInputsAndOutputs() const { return true; }
  426. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  427. {
  428. jassert (hasScanned); // need to call scanForDevices() before doing this
  429. if (JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device))
  430. return asInput ? inputIds.indexOf (d->inputId)
  431. : outputIds.indexOf (d->outputId);
  432. return -1;
  433. }
  434. AudioIODevice* createDevice (const String& outputDeviceName,
  435. const String& inputDeviceName)
  436. {
  437. jassert (hasScanned); // need to call scanForDevices() before doing this
  438. const int inputIndex = inputNames.indexOf (inputDeviceName);
  439. const int outputIndex = outputNames.indexOf (outputDeviceName);
  440. if (inputIndex >= 0 || outputIndex >= 0)
  441. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  442. : inputDeviceName,
  443. inputIds [inputIndex],
  444. outputIds [outputIndex]);
  445. return nullptr;
  446. }
  447. private:
  448. StringArray inputNames, outputNames, inputIds, outputIds;
  449. bool hasScanned;
  450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  451. };
  452. //==============================================================================
  453. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK()
  454. {
  455. return new JackAudioIODeviceType();
  456. }