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.

1303 lines
46KB

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