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.

1264 lines
45KB

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