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.

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