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.

578 lines
22KB

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