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.

1270 lines
45KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. namespace
  24. {
  25. #ifndef JUCE_ALSA_LOGGING
  26. #define JUCE_ALSA_LOGGING 0
  27. #endif
  28. #if JUCE_ALSA_LOGGING
  29. #define JUCE_ALSA_LOG(dbgtext) { juce::String tempDbgBuf ("ALSA: "); tempDbgBuf << dbgtext; Logger::writeToLog (tempDbgBuf); DBG (tempDbgBuf); }
  30. #define JUCE_CHECKED_RESULT(x) (logErrorMessage (x, __LINE__))
  31. static int logErrorMessage (int err, int lineNum)
  32. {
  33. if (err < 0)
  34. JUCE_ALSA_LOG ("Error: line " << lineNum << ": code " << err << " (" << snd_strerror (err) << ")");
  35. return err;
  36. }
  37. #else
  38. #define JUCE_ALSA_LOG(x) {}
  39. #define JUCE_CHECKED_RESULT(x) (x)
  40. #endif
  41. #define JUCE_ALSA_FAILED(x) failed (x)
  42. static void getDeviceSampleRates (snd_pcm_t* handle, Array<double>& rates)
  43. {
  44. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  45. snd_pcm_hw_params_t* hwParams;
  46. snd_pcm_hw_params_alloca (&hwParams);
  47. for (int i = 0; ratesToTry[i] != 0; ++i)
  48. {
  49. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  50. && snd_pcm_hw_params_test_rate (handle, hwParams, (unsigned int) ratesToTry[i], 0) == 0)
  51. {
  52. rates.addIfNotAlreadyThere ((double) ratesToTry[i]);
  53. }
  54. }
  55. }
  56. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  57. {
  58. snd_pcm_hw_params_t *params;
  59. snd_pcm_hw_params_alloca (&params);
  60. if (snd_pcm_hw_params_any (handle, params) >= 0)
  61. {
  62. snd_pcm_hw_params_get_channels_min (params, minChans);
  63. snd_pcm_hw_params_get_channels_max (params, maxChans);
  64. JUCE_ALSA_LOG ("getDeviceNumChannels: " << (int) *minChans << " " << (int) *maxChans);
  65. // some virtual devices (dmix for example) report 10000 channels , we have to clamp these values
  66. *maxChans = jmin (*maxChans, 32u);
  67. *minChans = jmin (*minChans, *maxChans);
  68. }
  69. else
  70. {
  71. JUCE_ALSA_LOG ("getDeviceNumChannels failed");
  72. }
  73. }
  74. static void getDeviceProperties (const String& deviceID,
  75. unsigned int& minChansOut,
  76. unsigned int& maxChansOut,
  77. unsigned int& minChansIn,
  78. unsigned int& maxChansIn,
  79. Array<double>& rates,
  80. bool testOutput,
  81. bool testInput)
  82. {
  83. minChansOut = maxChansOut = minChansIn = maxChansIn = 0;
  84. if (deviceID.isEmpty())
  85. return;
  86. JUCE_ALSA_LOG ("getDeviceProperties(" << deviceID.toUTF8().getAddress() << ")");
  87. snd_pcm_info_t* info;
  88. snd_pcm_info_alloca (&info);
  89. if (testOutput)
  90. {
  91. snd_pcm_t* pcmHandle;
  92. if (JUCE_CHECKED_RESULT (snd_pcm_open (&pcmHandle, deviceID.toUTF8().getAddress(), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)) >= 0)
  93. {
  94. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  95. getDeviceSampleRates (pcmHandle, rates);
  96. snd_pcm_close (pcmHandle);
  97. }
  98. }
  99. if (testInput)
  100. {
  101. snd_pcm_t* pcmHandle;
  102. if (JUCE_CHECKED_RESULT (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) >= 0))
  103. {
  104. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  105. if (rates.size() == 0)
  106. getDeviceSampleRates (pcmHandle, rates);
  107. snd_pcm_close (pcmHandle);
  108. }
  109. }
  110. }
  111. static void ensureMinimumNumBitsSet (BigInteger& chans, int minNumChans)
  112. {
  113. int i = 0;
  114. while (chans.countNumberOfSetBits() < minNumChans)
  115. chans.setBit (i++);
  116. }
  117. static void silentErrorHandler (const char*, int, const char*, int, const char*,...) {}
  118. //==============================================================================
  119. class ALSADevice
  120. {
  121. public:
  122. ALSADevice (const String& devID, bool forInput)
  123. : handle (nullptr),
  124. bitDepth (16),
  125. numChannelsRunning (0),
  126. latency (0),
  127. deviceID (devID),
  128. isInput (forInput),
  129. isInterleaved (true)
  130. {
  131. JUCE_ALSA_LOG ("snd_pcm_open (" << deviceID.toUTF8().getAddress() << ", forInput=" << forInput << ")");
  132. int err = snd_pcm_open (&handle, deviceID.toUTF8(),
  133. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  134. SND_PCM_ASYNC);
  135. if (err < 0)
  136. {
  137. if (-err == EBUSY)
  138. error << "The device \"" << deviceID << "\" is busy (another application is using it).";
  139. else if (-err == ENOENT)
  140. error << "The device \"" << deviceID << "\" is not available.";
  141. else
  142. error << "Could not open " << (forInput ? "input" : "output") << " device \"" << deviceID
  143. << "\": " << snd_strerror(err) << " (" << err << ")";
  144. JUCE_ALSA_LOG ("snd_pcm_open failed; " << error);
  145. }
  146. }
  147. ~ALSADevice()
  148. {
  149. closeNow();
  150. }
  151. void closeNow()
  152. {
  153. if (handle != nullptr)
  154. {
  155. snd_pcm_close (handle);
  156. handle = nullptr;
  157. }
  158. }
  159. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  160. {
  161. if (handle == nullptr)
  162. return false;
  163. JUCE_ALSA_LOG ("ALSADevice::setParameters(" << deviceID << ", "
  164. << (int) sampleRate << ", " << numChannels << ", " << bufferSize << ")");
  165. snd_pcm_hw_params_t* hwParams;
  166. snd_pcm_hw_params_alloca (&hwParams);
  167. if (snd_pcm_hw_params_any (handle, hwParams) < 0)
  168. {
  169. // this is the error message that aplay returns when an error happens here,
  170. // it is a bit more explicit that "Invalid parameter"
  171. error = "Broken configuration for this PCM: no configurations available";
  172. return false;
  173. }
  174. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0) // works better for plughw..
  175. isInterleaved = true;
  176. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  177. isInterleaved = false;
  178. else
  179. {
  180. jassertfalse;
  181. return false;
  182. }
  183. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17, onlyUseLower24Bits = 1 << 18 };
  184. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  185. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  186. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  187. SND_PCM_FORMAT_S32_BE, 32,
  188. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  189. SND_PCM_FORMAT_S24_3BE, 24,
  190. SND_PCM_FORMAT_S24_LE, 32 | isLittleEndianBit | onlyUseLower24Bits,
  191. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  192. SND_PCM_FORMAT_S16_BE, 16 };
  193. bitDepth = 0;
  194. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  195. {
  196. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  197. {
  198. const int type = formatsToTry [i + 1];
  199. bitDepth = type & 255;
  200. converter = createConverter (isInput, bitDepth,
  201. (type & isFloatBit) != 0,
  202. (type & isLittleEndianBit) != 0,
  203. (type & onlyUseLower24Bits) != 0,
  204. numChannels);
  205. break;
  206. }
  207. }
  208. if (bitDepth == 0)
  209. {
  210. error = "device doesn't support a compatible PCM format";
  211. JUCE_ALSA_LOG ("Error: " + error);
  212. return false;
  213. }
  214. int dir = 0;
  215. unsigned int periods = 4;
  216. snd_pcm_uframes_t samplesPerPeriod = (snd_pcm_uframes_t) bufferSize;
  217. if (JUCE_ALSA_FAILED (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  218. || JUCE_ALSA_FAILED (snd_pcm_hw_params_set_channels (handle, hwParams, (unsigned int ) numChannels))
  219. || JUCE_ALSA_FAILED (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  220. || JUCE_ALSA_FAILED (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221. || JUCE_ALSA_FAILED (snd_pcm_hw_params (handle, hwParams)))
  222. {
  223. return false;
  224. }
  225. snd_pcm_uframes_t frames = 0;
  226. if (JUCE_ALSA_FAILED (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  227. || JUCE_ALSA_FAILED (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  228. latency = 0;
  229. else
  230. latency = (int) frames * ((int) periods - 1); // (this is the method JACK uses to guess the latency..)
  231. JUCE_ALSA_LOG ("frames: " << (int) frames << ", periods: " << (int) periods
  232. << ", samplesPerPeriod: " << (int) samplesPerPeriod);
  233. snd_pcm_sw_params_t* swParams;
  234. snd_pcm_sw_params_alloca (&swParams);
  235. snd_pcm_uframes_t boundary;
  236. if (JUCE_ALSA_FAILED (snd_pcm_sw_params_current (handle, swParams))
  237. || JUCE_ALSA_FAILED (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  238. || JUCE_ALSA_FAILED (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  239. || JUCE_ALSA_FAILED (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  240. || JUCE_ALSA_FAILED (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  241. || JUCE_ALSA_FAILED (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  242. || JUCE_ALSA_FAILED (snd_pcm_sw_params (handle, swParams)))
  243. {
  244. return false;
  245. }
  246. #if JUCE_ALSA_LOGGING
  247. // enable this to dump the config of the devices that get opened
  248. snd_output_t* out;
  249. snd_output_stdio_attach (&out, stderr, 0);
  250. snd_pcm_hw_params_dump (hwParams, out);
  251. snd_pcm_sw_params_dump (swParams, out);
  252. #endif
  253. numChannelsRunning = numChannels;
  254. return true;
  255. }
  256. //==============================================================================
  257. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  258. {
  259. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  260. float* const* const data = outputChannelBuffer.getArrayOfWritePointers();
  261. snd_pcm_sframes_t numDone = 0;
  262. if (isInterleaved)
  263. {
  264. scratch.ensureSize ((size_t) ((int) sizeof (float) * numSamples * numChannelsRunning), false);
  265. for (int i = 0; i < numChannelsRunning; ++i)
  266. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  267. numDone = snd_pcm_writei (handle, scratch.getData(), (snd_pcm_uframes_t) numSamples);
  268. }
  269. else
  270. {
  271. for (int i = 0; i < numChannelsRunning; ++i)
  272. converter->convertSamples (data[i], data[i], numSamples);
  273. numDone = snd_pcm_writen (handle, (void**) data, (snd_pcm_uframes_t) numSamples);
  274. }
  275. if (numDone < 0 && JUCE_ALSA_FAILED (snd_pcm_recover (handle, (int) numDone, 1 /* silent */)))
  276. return false;
  277. if (numDone < numSamples)
  278. JUCE_ALSA_LOG ("Did not write all samples: numDone: " << numDone << ", numSamples: " << numSamples);
  279. return true;
  280. }
  281. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  282. {
  283. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  284. float* const* const data = inputChannelBuffer.getArrayOfWritePointers();
  285. if (isInterleaved)
  286. {
  287. scratch.ensureSize ((size_t) ((int) sizeof (float) * numSamples * numChannelsRunning), false);
  288. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  289. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), (snd_pcm_uframes_t) numSamples);
  290. if (num < 0 && JUCE_ALSA_FAILED (snd_pcm_recover (handle, (int) num, 1 /* silent */)))
  291. return false;
  292. if (num < numSamples)
  293. JUCE_ALSA_LOG ("Did not read all samples: num: " << num << ", numSamples: " << numSamples);
  294. for (int i = 0; i < numChannelsRunning; ++i)
  295. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  296. }
  297. else
  298. {
  299. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, (snd_pcm_uframes_t) numSamples);
  300. if (num < 0 && JUCE_ALSA_FAILED (snd_pcm_recover (handle, (int) num, 1 /* silent */)))
  301. return false;
  302. if (num < numSamples)
  303. JUCE_ALSA_LOG ("Did not read all samples: num: " << num << ", numSamples: " << numSamples);
  304. for (int i = 0; i < numChannelsRunning; ++i)
  305. converter->convertSamples (data[i], data[i], numSamples);
  306. }
  307. return true;
  308. }
  309. //==============================================================================
  310. snd_pcm_t* handle;
  311. String error;
  312. int bitDepth, numChannelsRunning, latency;
  313. private:
  314. //==============================================================================
  315. String deviceID;
  316. const bool isInput;
  317. bool isInterleaved;
  318. MemoryBlock scratch;
  319. ScopedPointer<AudioData::Converter> converter;
  320. //==============================================================================
  321. template <class SampleType>
  322. struct ConverterHelper
  323. {
  324. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  325. {
  326. if (forInput)
  327. {
  328. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  329. if (isLittleEndian)
  330. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  331. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  332. }
  333. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  334. if (isLittleEndian)
  335. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  336. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  337. }
  338. };
  339. static AudioData::Converter* createConverter (bool forInput, int bitDepth,
  340. bool isFloat, bool isLittleEndian, bool useOnlyLower24Bits,
  341. int numInterleavedChannels)
  342. {
  343. JUCE_ALSA_LOG ("format: bitDepth=" << bitDepth << ", isFloat=" << isFloat
  344. << ", isLittleEndian=" << isLittleEndian << ", numChannels=" << numInterleavedChannels);
  345. if (isFloat) return ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  346. if (bitDepth == 16) return ConverterHelper <AudioData::Int16> ::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  347. if (bitDepth == 24) return ConverterHelper <AudioData::Int24> ::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  348. jassert (bitDepth == 32);
  349. if (useOnlyLower24Bits)
  350. return ConverterHelper <AudioData::Int24in32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  351. return ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  352. }
  353. //==============================================================================
  354. bool failed (const int errorNum)
  355. {
  356. if (errorNum >= 0)
  357. return false;
  358. error = snd_strerror (errorNum);
  359. JUCE_ALSA_LOG ("ALSA error: " << error);
  360. return true;
  361. }
  362. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice)
  363. };
  364. //==============================================================================
  365. class ALSAThread : public Thread
  366. {
  367. public:
  368. ALSAThread (const String& inputDeviceID, const String& outputDeviceID)
  369. : Thread ("Juce ALSA"),
  370. sampleRate (0),
  371. bufferSize (0),
  372. outputLatency (0),
  373. inputLatency (0),
  374. callback (0),
  375. inputId (inputDeviceID),
  376. outputId (outputDeviceID),
  377. numCallbacks (0),
  378. audioIoInProgress (false),
  379. inputChannelBuffer (1, 1),
  380. outputChannelBuffer (1, 1)
  381. {
  382. initialiseRatesAndChannels();
  383. }
  384. ~ALSAThread()
  385. {
  386. close();
  387. }
  388. void open (BigInteger inputChannels,
  389. BigInteger outputChannels,
  390. const double newSampleRate,
  391. const int newBufferSize)
  392. {
  393. close();
  394. error.clear();
  395. sampleRate = newSampleRate;
  396. bufferSize = newBufferSize;
  397. int maxInputsRequested = inputChannels.getHighestBit() + 1;
  398. maxInputsRequested = jmax ((int) minChansIn, jmin ((int) maxChansIn, maxInputsRequested));
  399. inputChannelBuffer.setSize (maxInputsRequested, bufferSize);
  400. inputChannelBuffer.clear();
  401. inputChannelDataForCallback.clear();
  402. currentInputChans.clear();
  403. if (inputChannels.getHighestBit() >= 0)
  404. {
  405. for (int i = 0; i < maxInputsRequested; ++i)
  406. {
  407. if (inputChannels[i])
  408. {
  409. inputChannelDataForCallback.add (inputChannelBuffer.getReadPointer (i));
  410. currentInputChans.setBit (i);
  411. }
  412. }
  413. }
  414. ensureMinimumNumBitsSet (outputChannels, (int) minChansOut);
  415. int maxOutputsRequested = outputChannels.getHighestBit() + 1;
  416. maxOutputsRequested = jmax ((int) minChansOut, jmin ((int) maxChansOut, maxOutputsRequested));
  417. outputChannelBuffer.setSize (maxOutputsRequested, bufferSize);
  418. outputChannelBuffer.clear();
  419. outputChannelDataForCallback.clear();
  420. currentOutputChans.clear();
  421. if (outputChannels.getHighestBit() >= 0)
  422. {
  423. for (int i = 0; i < maxOutputsRequested; ++i)
  424. {
  425. if (outputChannels[i])
  426. {
  427. outputChannelDataForCallback.add (outputChannelBuffer.getWritePointer (i));
  428. currentOutputChans.setBit (i);
  429. }
  430. }
  431. }
  432. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  433. {
  434. outputDevice = new ALSADevice (outputId, false);
  435. if (outputDevice->error.isNotEmpty())
  436. {
  437. error = outputDevice->error;
  438. outputDevice = nullptr;
  439. return;
  440. }
  441. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  442. jlimit ((int) minChansOut, (int) maxChansOut,
  443. currentOutputChans.getHighestBit() + 1),
  444. bufferSize))
  445. {
  446. error = outputDevice->error;
  447. outputDevice = nullptr;
  448. return;
  449. }
  450. outputLatency = outputDevice->latency;
  451. }
  452. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  453. {
  454. inputDevice = new ALSADevice (inputId, true);
  455. if (inputDevice->error.isNotEmpty())
  456. {
  457. error = inputDevice->error;
  458. inputDevice = nullptr;
  459. return;
  460. }
  461. ensureMinimumNumBitsSet (currentInputChans, (int) minChansIn);
  462. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  463. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  464. bufferSize))
  465. {
  466. error = inputDevice->error;
  467. inputDevice = nullptr;
  468. return;
  469. }
  470. inputLatency = inputDevice->latency;
  471. }
  472. if (outputDevice == nullptr && inputDevice == nullptr)
  473. {
  474. error = "no channels";
  475. return;
  476. }
  477. if (outputDevice != nullptr && inputDevice != nullptr)
  478. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  479. if (inputDevice != nullptr && JUCE_ALSA_FAILED (snd_pcm_prepare (inputDevice->handle)))
  480. return;
  481. if (outputDevice != nullptr && JUCE_ALSA_FAILED (snd_pcm_prepare (outputDevice->handle)))
  482. return;
  483. startThread (9);
  484. int count = 1000;
  485. while (numCallbacks == 0)
  486. {
  487. sleep (5);
  488. if (--count < 0 || ! isThreadRunning())
  489. {
  490. error = "device didn't start";
  491. break;
  492. }
  493. }
  494. }
  495. void close()
  496. {
  497. if (isThreadRunning())
  498. {
  499. // problem: when pulseaudio is suspended (with pasuspend) , the ALSAThread::run is just stuck in
  500. // snd_pcm_writei -- no error, no nothing it just stays stuck. So the only way I found to exit "nicely"
  501. // (that is without the "killing thread by force" of stopThread) , is to just call snd_pcm_close from
  502. // here which will cause the thread to resume, and exit
  503. signalThreadShouldExit();
  504. const int callbacksToStop = numCallbacks;
  505. if ((! waitForThreadToExit (400)) && audioIoInProgress && numCallbacks == callbacksToStop)
  506. {
  507. JUCE_ALSA_LOG ("Thread is stuck in i/o.. Is pulseaudio suspended?");
  508. if (outputDevice != nullptr) outputDevice->closeNow();
  509. if (inputDevice != nullptr) inputDevice->closeNow();
  510. }
  511. }
  512. stopThread (6000);
  513. inputDevice = nullptr;
  514. outputDevice = nullptr;
  515. inputChannelBuffer.setSize (1, 1);
  516. outputChannelBuffer.setSize (1, 1);
  517. numCallbacks = 0;
  518. }
  519. void setCallback (AudioIODeviceCallback* const newCallback) noexcept
  520. {
  521. const ScopedLock sl (callbackLock);
  522. callback = newCallback;
  523. }
  524. void run() override
  525. {
  526. while (! threadShouldExit())
  527. {
  528. if (inputDevice != nullptr && inputDevice->handle != nullptr)
  529. {
  530. if (outputDevice == nullptr || outputDevice->handle == nullptr)
  531. {
  532. JUCE_ALSA_FAILED (snd_pcm_wait (inputDevice->handle, 2000));
  533. if (threadShouldExit())
  534. break;
  535. snd_pcm_sframes_t avail = snd_pcm_avail_update (inputDevice->handle);
  536. if (avail < 0)
  537. JUCE_ALSA_FAILED (snd_pcm_recover (inputDevice->handle, (int) avail, 0));
  538. }
  539. audioIoInProgress = true;
  540. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  541. {
  542. JUCE_ALSA_LOG ("Read failure");
  543. break;
  544. }
  545. audioIoInProgress = false;
  546. }
  547. if (threadShouldExit())
  548. break;
  549. {
  550. const ScopedLock sl (callbackLock);
  551. ++numCallbacks;
  552. if (callback != nullptr)
  553. {
  554. callback->audioDeviceIOCallback (inputChannelDataForCallback.getRawDataPointer(),
  555. inputChannelDataForCallback.size(),
  556. outputChannelDataForCallback.getRawDataPointer(),
  557. outputChannelDataForCallback.size(),
  558. bufferSize);
  559. }
  560. else
  561. {
  562. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  563. zeromem (outputChannelDataForCallback[i], sizeof (float) * (size_t) bufferSize);
  564. }
  565. }
  566. if (outputDevice != nullptr && outputDevice->handle != nullptr)
  567. {
  568. JUCE_ALSA_FAILED (snd_pcm_wait (outputDevice->handle, 2000));
  569. if (threadShouldExit())
  570. break;
  571. snd_pcm_sframes_t avail = snd_pcm_avail_update (outputDevice->handle);
  572. if (avail < 0)
  573. JUCE_ALSA_FAILED (snd_pcm_recover (outputDevice->handle, (int) avail, 0));
  574. audioIoInProgress = true;
  575. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  576. {
  577. JUCE_ALSA_LOG ("write failure");
  578. break;
  579. }
  580. audioIoInProgress = false;
  581. }
  582. }
  583. audioIoInProgress = false;
  584. }
  585. int getBitDepth() const noexcept
  586. {
  587. if (outputDevice != nullptr)
  588. return outputDevice->bitDepth;
  589. if (inputDevice != nullptr)
  590. return inputDevice->bitDepth;
  591. return 16;
  592. }
  593. //==============================================================================
  594. String error;
  595. double sampleRate;
  596. int bufferSize, outputLatency, inputLatency;
  597. BigInteger currentInputChans, currentOutputChans;
  598. Array<double> sampleRates;
  599. StringArray channelNamesOut, channelNamesIn;
  600. AudioIODeviceCallback* callback;
  601. private:
  602. //==============================================================================
  603. const String inputId, outputId;
  604. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  605. int numCallbacks;
  606. bool audioIoInProgress;
  607. CriticalSection callbackLock;
  608. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  609. Array<const float*> inputChannelDataForCallback;
  610. Array<float*> outputChannelDataForCallback;
  611. unsigned int minChansOut, maxChansOut;
  612. unsigned int minChansIn, maxChansIn;
  613. bool failed (const int errorNum)
  614. {
  615. if (errorNum >= 0)
  616. return false;
  617. error = snd_strerror (errorNum);
  618. JUCE_ALSA_LOG ("ALSA error: " << error);
  619. return true;
  620. }
  621. void initialiseRatesAndChannels()
  622. {
  623. sampleRates.clear();
  624. channelNamesOut.clear();
  625. channelNamesIn.clear();
  626. minChansOut = 0;
  627. maxChansOut = 0;
  628. minChansIn = 0;
  629. maxChansIn = 0;
  630. unsigned int dummy = 0;
  631. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates, false, true);
  632. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates, true, false);
  633. for (unsigned int i = 0; i < maxChansOut; ++i)
  634. channelNamesOut.add ("channel " + String ((int) i + 1));
  635. for (unsigned int i = 0; i < maxChansIn; ++i)
  636. channelNamesIn.add ("channel " + String ((int) i + 1));
  637. }
  638. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread)
  639. };
  640. //==============================================================================
  641. class ALSAAudioIODevice : public AudioIODevice
  642. {
  643. public:
  644. ALSAAudioIODevice (const String& deviceName,
  645. const String& deviceTypeName,
  646. const String& inputDeviceID,
  647. const String& outputDeviceID)
  648. : AudioIODevice (deviceName, deviceTypeName),
  649. inputId (inputDeviceID),
  650. outputId (outputDeviceID),
  651. isOpen_ (false),
  652. isStarted (false),
  653. internal (inputDeviceID, outputDeviceID)
  654. {
  655. }
  656. ~ALSAAudioIODevice()
  657. {
  658. close();
  659. }
  660. StringArray getOutputChannelNames() override { return internal.channelNamesOut; }
  661. StringArray getInputChannelNames() override { return internal.channelNamesIn; }
  662. Array<double> getAvailableSampleRates() override { return internal.sampleRates; }
  663. Array<int> getAvailableBufferSizes() override
  664. {
  665. Array<int> r;
  666. int n = 16;
  667. for (int i = 0; i < 50; ++i)
  668. {
  669. r.add (n);
  670. n += n < 64 ? 16
  671. : (n < 512 ? 32
  672. : (n < 1024 ? 64
  673. : (n < 2048 ? 128 : 256)));
  674. }
  675. return r;
  676. }
  677. int getDefaultBufferSize() override { return 512; }
  678. String open (const BigInteger& inputChannels,
  679. const BigInteger& outputChannels,
  680. double sampleRate,
  681. int bufferSizeSamples) override
  682. {
  683. close();
  684. if (bufferSizeSamples <= 0)
  685. bufferSizeSamples = getDefaultBufferSize();
  686. if (sampleRate <= 0)
  687. {
  688. for (int i = 0; i < internal.sampleRates.size(); ++i)
  689. {
  690. double rate = internal.sampleRates[i];
  691. if (rate >= 44100)
  692. {
  693. sampleRate = rate;
  694. break;
  695. }
  696. }
  697. }
  698. internal.open (inputChannels, outputChannels,
  699. sampleRate, bufferSizeSamples);
  700. isOpen_ = internal.error.isEmpty();
  701. return internal.error;
  702. }
  703. void close() override
  704. {
  705. stop();
  706. internal.close();
  707. isOpen_ = false;
  708. }
  709. bool isOpen() override { return isOpen_; }
  710. bool isPlaying() override { return isStarted && internal.error.isEmpty(); }
  711. String getLastError() override { return internal.error; }
  712. int getCurrentBufferSizeSamples() override { return internal.bufferSize; }
  713. double getCurrentSampleRate() override { return internal.sampleRate; }
  714. int getCurrentBitDepth() override { return internal.getBitDepth(); }
  715. BigInteger getActiveOutputChannels() const override { return internal.currentOutputChans; }
  716. BigInteger getActiveInputChannels() const override { return internal.currentInputChans; }
  717. int getOutputLatencyInSamples() override { return internal.outputLatency; }
  718. int getInputLatencyInSamples() override { return internal.inputLatency; }
  719. void start (AudioIODeviceCallback* callback) override
  720. {
  721. if (! isOpen_)
  722. callback = nullptr;
  723. if (callback != nullptr)
  724. callback->audioDeviceAboutToStart (this);
  725. internal.setCallback (callback);
  726. isStarted = (callback != nullptr);
  727. }
  728. void stop() override
  729. {
  730. AudioIODeviceCallback* const oldCallback = internal.callback;
  731. start (nullptr);
  732. if (oldCallback != nullptr)
  733. oldCallback->audioDeviceStopped();
  734. }
  735. String inputId, outputId;
  736. private:
  737. bool isOpen_, isStarted;
  738. ALSAThread internal;
  739. };
  740. //==============================================================================
  741. class ALSAAudioIODeviceType : public AudioIODeviceType
  742. {
  743. public:
  744. ALSAAudioIODeviceType (bool onlySoundcards, const String &deviceTypeName)
  745. : AudioIODeviceType (deviceTypeName),
  746. hasScanned (false),
  747. listOnlySoundcards (onlySoundcards)
  748. {
  749. #if ! JUCE_ALSA_LOGGING
  750. snd_lib_error_set_handler (&silentErrorHandler);
  751. #endif
  752. }
  753. ~ALSAAudioIODeviceType()
  754. {
  755. #if ! JUCE_ALSA_LOGGING
  756. snd_lib_error_set_handler (nullptr);
  757. #endif
  758. snd_config_update_free_global(); // prevent valgrind from screaming about alsa leaks
  759. }
  760. //==============================================================================
  761. void scanForDevices()
  762. {
  763. if (hasScanned)
  764. return;
  765. hasScanned = true;
  766. inputNames.clear();
  767. inputIds.clear();
  768. outputNames.clear();
  769. outputIds.clear();
  770. JUCE_ALSA_LOG ("scanForDevices()");
  771. if (listOnlySoundcards)
  772. enumerateAlsaSoundcards();
  773. else
  774. enumerateAlsaPCMDevices();
  775. inputNames.appendNumbersToDuplicates (false, true);
  776. outputNames.appendNumbersToDuplicates (false, true);
  777. }
  778. StringArray getDeviceNames (bool wantInputNames) const
  779. {
  780. jassert (hasScanned); // need to call scanForDevices() before doing this
  781. return wantInputNames ? inputNames : outputNames;
  782. }
  783. int getDefaultDeviceIndex (bool forInput) const
  784. {
  785. jassert (hasScanned); // need to call scanForDevices() before doing this
  786. const int idx = (forInput ? inputIds : outputIds).indexOf ("default");
  787. return idx >= 0 ? idx : 0;
  788. }
  789. bool hasSeparateInputsAndOutputs() const { return true; }
  790. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  791. {
  792. jassert (hasScanned); // need to call scanForDevices() before doing this
  793. if (ALSAAudioIODevice* d = dynamic_cast<ALSAAudioIODevice*> (device))
  794. return asInput ? inputIds.indexOf (d->inputId)
  795. : outputIds.indexOf (d->outputId);
  796. return -1;
  797. }
  798. AudioIODevice* createDevice (const String& outputDeviceName,
  799. const String& inputDeviceName)
  800. {
  801. jassert (hasScanned); // need to call scanForDevices() before doing this
  802. const int inputIndex = inputNames.indexOf (inputDeviceName);
  803. const int outputIndex = outputNames.indexOf (outputDeviceName);
  804. String deviceName (outputIndex >= 0 ? outputDeviceName
  805. : inputDeviceName);
  806. if (inputIndex >= 0 || outputIndex >= 0)
  807. return new ALSAAudioIODevice (deviceName, getTypeName(),
  808. inputIds [inputIndex],
  809. outputIds [outputIndex]);
  810. return nullptr;
  811. }
  812. private:
  813. //==============================================================================
  814. StringArray inputNames, outputNames, inputIds, outputIds;
  815. bool hasScanned, listOnlySoundcards;
  816. bool testDevice (const String &id, const String &outputName, const String &inputName)
  817. {
  818. unsigned int minChansOut = 0, maxChansOut = 0;
  819. unsigned int minChansIn = 0, maxChansIn = 0;
  820. Array<double> rates;
  821. bool isInput = inputName.isNotEmpty(), isOutput = outputName.isNotEmpty();
  822. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates, isOutput, isInput);
  823. isInput = maxChansIn > 0;
  824. isOutput = maxChansOut > 0;
  825. if ((isInput || isOutput) && rates.size() > 0)
  826. {
  827. JUCE_ALSA_LOG ("testDevice: '" << id.toUTF8().getAddress() << "' -> isInput: "
  828. << isInput << ", isOutput: " << isOutput);
  829. if (isInput)
  830. {
  831. inputNames.add (inputName);
  832. inputIds.add (id);
  833. }
  834. if (isOutput)
  835. {
  836. outputNames.add (outputName);
  837. outputIds.add (id);
  838. }
  839. return isInput || isOutput;
  840. }
  841. return false;
  842. }
  843. void enumerateAlsaSoundcards()
  844. {
  845. snd_ctl_t* handle = nullptr;
  846. snd_ctl_card_info_t* info = nullptr;
  847. snd_ctl_card_info_alloca (&info);
  848. int cardNum = -1;
  849. while (outputIds.size() + inputIds.size() <= 64)
  850. {
  851. snd_card_next (&cardNum);
  852. if (cardNum < 0)
  853. break;
  854. if (JUCE_CHECKED_RESULT (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK)) >= 0)
  855. {
  856. if (JUCE_CHECKED_RESULT (snd_ctl_card_info (handle, info)) >= 0)
  857. {
  858. String cardId (snd_ctl_card_info_get_id (info));
  859. if (cardId.removeCharacters ("0123456789").isEmpty())
  860. cardId = String (cardNum);
  861. String cardName = snd_ctl_card_info_get_name (info);
  862. if (cardName.isEmpty())
  863. cardName = cardId;
  864. int device = -1;
  865. snd_pcm_info_t* pcmInfo;
  866. snd_pcm_info_alloca (&pcmInfo);
  867. for (;;)
  868. {
  869. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  870. break;
  871. snd_pcm_info_set_device (pcmInfo, (unsigned int) device);
  872. for (unsigned int subDevice = 0, nbSubDevice = 1; subDevice < nbSubDevice; ++subDevice)
  873. {
  874. snd_pcm_info_set_subdevice (pcmInfo, subDevice);
  875. snd_pcm_info_set_stream (pcmInfo, SND_PCM_STREAM_CAPTURE);
  876. const bool isInput = (snd_ctl_pcm_info (handle, pcmInfo) >= 0);
  877. snd_pcm_info_set_stream (pcmInfo, SND_PCM_STREAM_PLAYBACK);
  878. const bool isOutput = (snd_ctl_pcm_info (handle, pcmInfo) >= 0);
  879. if (! (isInput || isOutput))
  880. continue;
  881. if (nbSubDevice == 1)
  882. nbSubDevice = snd_pcm_info_get_subdevices_count (pcmInfo);
  883. String id, name;
  884. if (nbSubDevice == 1)
  885. {
  886. id << "hw:" << cardId << "," << device;
  887. name << cardName << ", " << snd_pcm_info_get_name (pcmInfo);
  888. }
  889. else
  890. {
  891. id << "hw:" << cardId << "," << device << "," << (int) subDevice;
  892. name << cardName << ", " << snd_pcm_info_get_name (pcmInfo)
  893. << " {" << snd_pcm_info_get_subdevice_name (pcmInfo) << "}";
  894. }
  895. JUCE_ALSA_LOG ("Soundcard ID: " << id << ", name: '" << name
  896. << ", isInput:" << isInput << ", isOutput:" << isOutput << "\n");
  897. if (isInput)
  898. {
  899. inputNames.add (name);
  900. inputIds.add (id);
  901. }
  902. if (isOutput)
  903. {
  904. outputNames.add (name);
  905. outputIds.add (id);
  906. }
  907. }
  908. }
  909. }
  910. JUCE_CHECKED_RESULT (snd_ctl_close (handle));
  911. }
  912. }
  913. }
  914. /* Enumerates all ALSA output devices (as output by the command aplay -L)
  915. Does not try to open the devices (with "testDevice" for example),
  916. so that it also finds devices that are busy and not yet available.
  917. */
  918. void enumerateAlsaPCMDevices()
  919. {
  920. void** hints = nullptr;
  921. if (JUCE_CHECKED_RESULT (snd_device_name_hint (-1, "pcm", &hints)) == 0)
  922. {
  923. for (char** h = (char**) hints; *h; ++h)
  924. {
  925. const String id (hintToString (*h, "NAME"));
  926. const String description (hintToString (*h, "DESC"));
  927. const String ioid (hintToString (*h, "IOID"));
  928. JUCE_ALSA_LOG ("ID: " << id << "; desc: " << description << "; ioid: " << ioid);
  929. String ss = id.fromFirstOccurrenceOf ("=", false, false)
  930. .upToFirstOccurrenceOf (",", false, false);
  931. if (id.isEmpty()
  932. || id.startsWith ("default:") || id.startsWith ("sysdefault:")
  933. || id.startsWith ("plughw:") || id == "null")
  934. continue;
  935. String name (description.replace ("\n", "; "));
  936. if (name.isEmpty())
  937. name = id;
  938. bool isOutput = (ioid != "Input");
  939. bool isInput = (ioid != "Output");
  940. // alsa is stupid here, it advertises dmix and dsnoop as input/output devices, but
  941. // opening dmix as input, or dsnoop as output will trigger errors..
  942. isInput = isInput && ! id.startsWith ("dmix");
  943. isOutput = isOutput && ! id.startsWith ("dsnoop");
  944. if (isInput)
  945. {
  946. inputNames.add (name);
  947. inputIds.add (id);
  948. }
  949. if (isOutput)
  950. {
  951. outputNames.add (name);
  952. outputIds.add (id);
  953. }
  954. }
  955. snd_device_name_free_hint (hints);
  956. }
  957. // sometimes the "default" device is not listed, but it is nice to see it explicitely in the list
  958. if (! outputIds.contains ("default"))
  959. testDevice ("default", "Default ALSA Output", "Default ALSA Input");
  960. // same for the pulseaudio plugin
  961. if (! outputIds.contains ("pulse"))
  962. testDevice ("pulse", "Pulseaudio output", "Pulseaudio input");
  963. // make sure the default device is listed first, and followed by the pulse device (if present)
  964. int idx = outputIds.indexOf ("pulse");
  965. outputIds.move (idx, 0);
  966. outputNames.move (idx, 0);
  967. idx = inputIds.indexOf ("pulse");
  968. inputIds.move (idx, 0);
  969. inputNames.move (idx, 0);
  970. idx = outputIds.indexOf ("default");
  971. outputIds.move (idx, 0);
  972. outputNames.move (idx, 0);
  973. idx = inputIds.indexOf ("default");
  974. inputIds.move (idx, 0);
  975. inputNames.move (idx, 0);
  976. }
  977. static String hintToString (const void* hints, const char* type)
  978. {
  979. char* const hint = snd_device_name_get_hint (hints, type);
  980. const String s (String::fromUTF8 (hint));
  981. ::free (hint);
  982. return s;
  983. }
  984. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType)
  985. };
  986. }
  987. //==============================================================================
  988. AudioIODeviceType* createAudioIODeviceType_ALSA_Soundcards()
  989. {
  990. return new ALSAAudioIODeviceType (true, "ALSA HW");
  991. }
  992. AudioIODeviceType* createAudioIODeviceType_ALSA_PCMDevices()
  993. {
  994. return new ALSAAudioIODeviceType (false, "ALSA");
  995. }
  996. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA()
  997. {
  998. return createAudioIODeviceType_ALSA_PCMDevices();
  999. }