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.

1238 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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 <int>& 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, ratesToTry[i], 0) == 0)
  45. {
  46. rates.addIfNotAlreadyThere (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 <int>& 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 (0),
  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 != 0)
  148. {
  149. snd_pcm_close (handle);
  150. handle = 0;
  151. }
  152. }
  153. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  154. {
  155. if (handle == 0)
  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 = 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, 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 = frames * (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 data = outputChannelBuffer.getArrayOfChannels();
  255. snd_pcm_sframes_t numDone = 0;
  256. if (isInterleaved)
  257. {
  258. scratch.ensureSize (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(), 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, numSamples);
  268. }
  269. if (numDone < 0 && JUCE_ALSA_FAILED (snd_pcm_recover (handle, 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 data = inputChannelBuffer.getArrayOfChannels();
  279. if (isInterleaved)
  280. {
  281. scratch.ensureSize (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(), numSamples);
  284. if (num < 0 && JUCE_ALSA_FAILED (snd_pcm_recover (handle, 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, numSamples);
  294. if (num < 0 && JUCE_ALSA_FAILED (snd_pcm_recover (handle, 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 = String::empty;
  389. sampleRate = newSampleRate;
  390. bufferSize = newBufferSize;
  391. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  392. inputChannelBuffer.clear();
  393. inputChannelDataForCallback.clear();
  394. currentInputChans.clear();
  395. if (inputChannels.getHighestBit() >= 0)
  396. {
  397. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  398. {
  399. if (inputChannels[i])
  400. {
  401. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  402. currentInputChans.setBit (i);
  403. }
  404. }
  405. }
  406. ensureMinimumNumBitsSet (outputChannels, minChansOut);
  407. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  408. outputChannelBuffer.clear();
  409. outputChannelDataForCallback.clear();
  410. currentOutputChans.clear();
  411. if (outputChannels.getHighestBit() >= 0)
  412. {
  413. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  414. {
  415. if (outputChannels[i])
  416. {
  417. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  418. currentOutputChans.setBit (i);
  419. }
  420. }
  421. }
  422. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  423. {
  424. outputDevice = new ALSADevice (outputId, false);
  425. if (outputDevice->error.isNotEmpty())
  426. {
  427. error = outputDevice->error;
  428. outputDevice = nullptr;
  429. return;
  430. }
  431. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  432. jlimit ((int) minChansOut, (int) maxChansOut,
  433. currentOutputChans.getHighestBit() + 1),
  434. bufferSize))
  435. {
  436. error = outputDevice->error;
  437. outputDevice = nullptr;
  438. return;
  439. }
  440. outputLatency = outputDevice->latency;
  441. }
  442. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  443. {
  444. inputDevice = new ALSADevice (inputId, true);
  445. if (inputDevice->error.isNotEmpty())
  446. {
  447. error = inputDevice->error;
  448. inputDevice = nullptr;
  449. return;
  450. }
  451. ensureMinimumNumBitsSet (currentInputChans, minChansIn);
  452. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  453. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  454. bufferSize))
  455. {
  456. error = inputDevice->error;
  457. inputDevice = nullptr;
  458. return;
  459. }
  460. inputLatency = inputDevice->latency;
  461. }
  462. if (outputDevice == nullptr && inputDevice == nullptr)
  463. {
  464. error = "no channels";
  465. return;
  466. }
  467. if (outputDevice != nullptr && inputDevice != nullptr)
  468. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  469. if (inputDevice != nullptr && JUCE_ALSA_FAILED (snd_pcm_prepare (inputDevice->handle)))
  470. return;
  471. if (outputDevice != nullptr && JUCE_ALSA_FAILED (snd_pcm_prepare (outputDevice->handle)))
  472. return;
  473. startThread (9);
  474. int count = 1000;
  475. while (numCallbacks == 0)
  476. {
  477. sleep (5);
  478. if (--count < 0 || ! isThreadRunning())
  479. {
  480. error = "device didn't start";
  481. break;
  482. }
  483. }
  484. }
  485. void close()
  486. {
  487. if (isThreadRunning())
  488. {
  489. // problem: when pulseaudio is suspended (with pasuspend) , the ALSAThread::run is just stuck in
  490. // snd_pcm_writei -- no error, no nothing it just stays stuck. So the only way I found to exit "nicely"
  491. // (that is without the "killing thread by force" of stopThread) , is to just call snd_pcm_close from
  492. // here which will cause the thread to resume, and exit
  493. signalThreadShouldExit();
  494. const int callbacksToStop = numCallbacks;
  495. if ((! waitForThreadToExit (400)) && audioIoInProgress && numCallbacks == callbacksToStop)
  496. {
  497. JUCE_ALSA_LOG ("Thread is stuck in i/o.. Is pulseaudio suspended?");
  498. if (outputDevice != nullptr) outputDevice->closeNow();
  499. if (inputDevice != nullptr) inputDevice->closeNow();
  500. }
  501. }
  502. stopThread (6000);
  503. inputDevice = nullptr;
  504. outputDevice = nullptr;
  505. inputChannelBuffer.setSize (1, 1);
  506. outputChannelBuffer.setSize (1, 1);
  507. numCallbacks = 0;
  508. }
  509. void setCallback (AudioIODeviceCallback* const newCallback) noexcept
  510. {
  511. const ScopedLock sl (callbackLock);
  512. callback = newCallback;
  513. }
  514. void run() override
  515. {
  516. while (! threadShouldExit())
  517. {
  518. if (inputDevice != nullptr && inputDevice->handle)
  519. {
  520. audioIoInProgress = true;
  521. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  522. {
  523. JUCE_ALSA_LOG ("Read failure");
  524. break;
  525. }
  526. audioIoInProgress = false;
  527. }
  528. if (threadShouldExit())
  529. break;
  530. {
  531. const ScopedLock sl (callbackLock);
  532. ++numCallbacks;
  533. if (callback != nullptr)
  534. {
  535. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  536. inputChannelDataForCallback.size(),
  537. outputChannelDataForCallback.getRawDataPointer(),
  538. outputChannelDataForCallback.size(),
  539. bufferSize);
  540. }
  541. else
  542. {
  543. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  544. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  545. }
  546. }
  547. if (outputDevice != nullptr && outputDevice->handle)
  548. {
  549. JUCE_ALSA_FAILED (snd_pcm_wait (outputDevice->handle, 2000));
  550. if (threadShouldExit())
  551. break;
  552. snd_pcm_sframes_t avail = snd_pcm_avail_update (outputDevice->handle);
  553. if (avail < 0)
  554. JUCE_ALSA_FAILED (snd_pcm_recover (outputDevice->handle, avail, 0));
  555. audioIoInProgress = true;
  556. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  557. {
  558. JUCE_ALSA_LOG ("write failure");
  559. break;
  560. }
  561. audioIoInProgress = false;
  562. }
  563. }
  564. audioIoInProgress = false;
  565. }
  566. int getBitDepth() const noexcept
  567. {
  568. if (outputDevice != nullptr)
  569. return outputDevice->bitDepth;
  570. if (inputDevice != nullptr)
  571. return inputDevice->bitDepth;
  572. return 16;
  573. }
  574. //==============================================================================
  575. String error;
  576. double sampleRate;
  577. int bufferSize, outputLatency, inputLatency;
  578. BigInteger currentInputChans, currentOutputChans;
  579. Array <int> sampleRates;
  580. StringArray channelNamesOut, channelNamesIn;
  581. AudioIODeviceCallback* callback;
  582. private:
  583. //==============================================================================
  584. const String inputId, outputId;
  585. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  586. int numCallbacks;
  587. bool audioIoInProgress;
  588. CriticalSection callbackLock;
  589. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  590. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  591. unsigned int minChansOut, maxChansOut;
  592. unsigned int minChansIn, maxChansIn;
  593. bool failed (const int errorNum)
  594. {
  595. if (errorNum >= 0)
  596. return false;
  597. error = snd_strerror (errorNum);
  598. JUCE_ALSA_LOG ("ALSA error: " << error);
  599. return true;
  600. }
  601. void initialiseRatesAndChannels()
  602. {
  603. sampleRates.clear();
  604. channelNamesOut.clear();
  605. channelNamesIn.clear();
  606. minChansOut = 0;
  607. maxChansOut = 0;
  608. minChansIn = 0;
  609. maxChansIn = 0;
  610. unsigned int dummy = 0;
  611. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates, false, true);
  612. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates, true, false);
  613. for (unsigned int i = 0; i < maxChansOut; ++i)
  614. channelNamesOut.add ("channel " + String ((int) i + 1));
  615. for (unsigned int i = 0; i < maxChansIn; ++i)
  616. channelNamesIn.add ("channel " + String ((int) i + 1));
  617. }
  618. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread)
  619. };
  620. //==============================================================================
  621. class ALSAAudioIODevice : public AudioIODevice
  622. {
  623. public:
  624. ALSAAudioIODevice (const String& deviceName,
  625. const String& typeName,
  626. const String& inputDeviceID,
  627. const String& outputDeviceID)
  628. : AudioIODevice (deviceName, typeName),
  629. inputId (inputDeviceID),
  630. outputId (outputDeviceID),
  631. isOpen_ (false),
  632. isStarted (false),
  633. internal (inputDeviceID, outputDeviceID)
  634. {
  635. }
  636. ~ALSAAudioIODevice()
  637. {
  638. close();
  639. }
  640. StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  641. StringArray getInputChannelNames() { return internal.channelNamesIn; }
  642. int getNumSampleRates() { return internal.sampleRates.size(); }
  643. double getSampleRate (int index) { return internal.sampleRates [index]; }
  644. int getDefaultBufferSize() { return 512; }
  645. int getNumBufferSizesAvailable() { return 50; }
  646. int getBufferSizeSamples (int index)
  647. {
  648. int n = 16;
  649. for (int i = 0; i < index; ++i)
  650. n += n < 64 ? 16
  651. : (n < 512 ? 32
  652. : (n < 1024 ? 64
  653. : (n < 2048 ? 128 : 256)));
  654. return n;
  655. }
  656. String open (const BigInteger& inputChannels,
  657. const BigInteger& outputChannels,
  658. double sampleRate,
  659. int bufferSizeSamples)
  660. {
  661. close();
  662. if (bufferSizeSamples <= 0)
  663. bufferSizeSamples = getDefaultBufferSize();
  664. if (sampleRate <= 0)
  665. {
  666. for (int i = 0; i < getNumSampleRates(); ++i)
  667. {
  668. if (getSampleRate (i) >= 44100)
  669. {
  670. sampleRate = getSampleRate (i);
  671. break;
  672. }
  673. }
  674. }
  675. internal.open (inputChannels, outputChannels,
  676. sampleRate, bufferSizeSamples);
  677. isOpen_ = internal.error.isEmpty();
  678. return internal.error;
  679. }
  680. void close()
  681. {
  682. stop();
  683. internal.close();
  684. isOpen_ = false;
  685. }
  686. bool isOpen() { return isOpen_; }
  687. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  688. String getLastError() { return internal.error; }
  689. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  690. double getCurrentSampleRate() { return internal.sampleRate; }
  691. int getCurrentBitDepth() { return internal.getBitDepth(); }
  692. BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  693. BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  694. int getOutputLatencyInSamples() { return internal.outputLatency; }
  695. int getInputLatencyInSamples() { return internal.inputLatency; }
  696. void start (AudioIODeviceCallback* callback)
  697. {
  698. if (! isOpen_)
  699. callback = nullptr;
  700. if (callback != nullptr)
  701. callback->audioDeviceAboutToStart (this);
  702. internal.setCallback (callback);
  703. isStarted = (callback != nullptr);
  704. }
  705. void stop()
  706. {
  707. AudioIODeviceCallback* const oldCallback = internal.callback;
  708. start (nullptr);
  709. if (oldCallback != nullptr)
  710. oldCallback->audioDeviceStopped();
  711. }
  712. String inputId, outputId;
  713. private:
  714. bool isOpen_, isStarted;
  715. ALSAThread internal;
  716. };
  717. //==============================================================================
  718. class ALSAAudioIODeviceType : public AudioIODeviceType
  719. {
  720. public:
  721. ALSAAudioIODeviceType (bool onlySoundcards, const String &typeName)
  722. : AudioIODeviceType (typeName),
  723. hasScanned (false),
  724. listOnlySoundcards (onlySoundcards)
  725. {
  726. #if ! JUCE_ALSA_LOGGING
  727. snd_lib_error_set_handler (&silentErrorHandler);
  728. #endif
  729. }
  730. ~ALSAAudioIODeviceType()
  731. {
  732. #if ! JUCE_ALSA_LOGGING
  733. snd_lib_error_set_handler (nullptr);
  734. #endif
  735. snd_config_update_free_global(); // prevent valgrind from screaming about alsa leaks
  736. }
  737. //==============================================================================
  738. void scanForDevices()
  739. {
  740. if (hasScanned)
  741. return;
  742. hasScanned = true;
  743. inputNames.clear();
  744. inputIds.clear();
  745. outputNames.clear();
  746. outputIds.clear();
  747. JUCE_ALSA_LOG ("scanForDevices()");
  748. if (listOnlySoundcards)
  749. enumerateAlsaSoundcards();
  750. else
  751. enumerateAlsaPCMDevices();
  752. inputNames.appendNumbersToDuplicates (false, true);
  753. outputNames.appendNumbersToDuplicates (false, true);
  754. }
  755. StringArray getDeviceNames (bool wantInputNames) const
  756. {
  757. jassert (hasScanned); // need to call scanForDevices() before doing this
  758. return wantInputNames ? inputNames : outputNames;
  759. }
  760. int getDefaultDeviceIndex (bool forInput) const
  761. {
  762. jassert (hasScanned); // need to call scanForDevices() before doing this
  763. const int idx = (forInput ? inputIds : outputIds).indexOf ("default");
  764. return idx >= 0 ? idx : 0;
  765. }
  766. bool hasSeparateInputsAndOutputs() const { return true; }
  767. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  768. {
  769. jassert (hasScanned); // need to call scanForDevices() before doing this
  770. if (ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device))
  771. return asInput ? inputIds.indexOf (d->inputId)
  772. : outputIds.indexOf (d->outputId);
  773. return -1;
  774. }
  775. AudioIODevice* createDevice (const String& outputDeviceName,
  776. const String& inputDeviceName)
  777. {
  778. jassert (hasScanned); // need to call scanForDevices() before doing this
  779. const int inputIndex = inputNames.indexOf (inputDeviceName);
  780. const int outputIndex = outputNames.indexOf (outputDeviceName);
  781. String deviceName (outputIndex >= 0 ? outputDeviceName
  782. : inputDeviceName);
  783. if (inputIndex >= 0 || outputIndex >= 0)
  784. return new ALSAAudioIODevice (deviceName, getTypeName(),
  785. inputIds [inputIndex],
  786. outputIds [outputIndex]);
  787. return nullptr;
  788. }
  789. private:
  790. //==============================================================================
  791. StringArray inputNames, outputNames, inputIds, outputIds;
  792. bool hasScanned, listOnlySoundcards;
  793. bool testDevice (const String &id, const String &outputName, const String &inputName)
  794. {
  795. unsigned int minChansOut = 0, maxChansOut = 0;
  796. unsigned int minChansIn = 0, maxChansIn = 0;
  797. Array <int> rates;
  798. bool isInput = inputName.isNotEmpty(), isOutput = outputName.isNotEmpty();
  799. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates, isOutput, isInput);
  800. isInput = maxChansIn > 0;
  801. isOutput = maxChansOut > 0;
  802. if ((isInput || isOutput) && rates.size() > 0)
  803. {
  804. JUCE_ALSA_LOG ("testDevice: '" << id.toUTF8().getAddress() << "' -> isInput: "
  805. << isInput << ", isOutput: " << isOutput);
  806. if (isInput)
  807. {
  808. inputNames.add (inputName);
  809. inputIds.add (id);
  810. }
  811. if (isOutput)
  812. {
  813. outputNames.add (outputName);
  814. outputIds.add (id);
  815. }
  816. return isInput || isOutput;
  817. }
  818. return false;
  819. }
  820. void enumerateAlsaSoundcards()
  821. {
  822. snd_ctl_t* handle = nullptr;
  823. snd_ctl_card_info_t* info = nullptr;
  824. snd_ctl_card_info_alloca (&info);
  825. int cardNum = -1;
  826. while (outputIds.size() + inputIds.size() <= 64)
  827. {
  828. snd_card_next (&cardNum);
  829. if (cardNum < 0)
  830. break;
  831. if (JUCE_CHECKED_RESULT (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK)) >= 0)
  832. {
  833. if (JUCE_CHECKED_RESULT (snd_ctl_card_info (handle, info)) >= 0)
  834. {
  835. String cardId (snd_ctl_card_info_get_id (info));
  836. if (cardId.removeCharacters ("0123456789").isEmpty())
  837. cardId = String (cardNum);
  838. String cardName = snd_ctl_card_info_get_name (info);
  839. if (cardName.isEmpty())
  840. cardName = cardId;
  841. int device = -1;
  842. snd_pcm_info_t* pcmInfo;
  843. snd_pcm_info_alloca (&pcmInfo);
  844. for (;;)
  845. {
  846. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  847. break;
  848. snd_pcm_info_set_device (pcmInfo, device);
  849. for (int subDevice = 0, nbSubDevice = 1; subDevice < nbSubDevice; ++subDevice)
  850. {
  851. snd_pcm_info_set_subdevice (pcmInfo, subDevice);
  852. snd_pcm_info_set_stream (pcmInfo, SND_PCM_STREAM_CAPTURE);
  853. const bool isInput = (snd_ctl_pcm_info (handle, pcmInfo) >= 0);
  854. snd_pcm_info_set_stream (pcmInfo, SND_PCM_STREAM_PLAYBACK);
  855. const bool isOutput = (snd_ctl_pcm_info (handle, pcmInfo) >= 0);
  856. if (! (isInput || isOutput))
  857. continue;
  858. if (nbSubDevice == 1)
  859. nbSubDevice = snd_pcm_info_get_subdevices_count (pcmInfo);
  860. String id, name;
  861. if (nbSubDevice == 1)
  862. {
  863. id << "hw:" << cardId << "," << device;
  864. name << cardName << ", " << snd_pcm_info_get_name (pcmInfo);
  865. }
  866. else
  867. {
  868. id << "hw:" << cardId << "," << device << "," << subDevice;
  869. name << cardName << ", " << snd_pcm_info_get_name (pcmInfo)
  870. << " {" << snd_pcm_info_get_subdevice_name (pcmInfo) << "}";
  871. }
  872. JUCE_ALSA_LOG ("Soundcard ID: " << id << ", name: '" << name
  873. << ", isInput:" << isInput << ", isOutput:" << isOutput << "\n");
  874. if (isInput)
  875. {
  876. inputNames.add (name);
  877. inputIds.add (id);
  878. }
  879. if (isOutput)
  880. {
  881. outputNames.add (name);
  882. outputIds.add (id);
  883. }
  884. }
  885. }
  886. }
  887. JUCE_CHECKED_RESULT (snd_ctl_close (handle));
  888. }
  889. }
  890. }
  891. /* Enumerates all ALSA output devices (as output by the command aplay -L)
  892. Does not try to open the devices (with "testDevice" for example),
  893. so that it also finds devices that are busy and not yet available.
  894. */
  895. void enumerateAlsaPCMDevices()
  896. {
  897. void** hints = nullptr;
  898. if (JUCE_CHECKED_RESULT (snd_device_name_hint (-1, "pcm", &hints)) == 0)
  899. {
  900. for (char** h = (char**) hints; *h; ++h)
  901. {
  902. const String id (hintToString (*h, "NAME"));
  903. const String description (hintToString (*h, "DESC"));
  904. const String ioid (hintToString (*h, "IOID"));
  905. JUCE_ALSA_LOG ("ID: " << id << "; desc: " << description << "; ioid: " << ioid);
  906. String ss = id.fromFirstOccurrenceOf ("=", false, false)
  907. .upToFirstOccurrenceOf (",", false, false);
  908. if (id.isEmpty()
  909. || id.startsWith ("default:") || id.startsWith ("sysdefault:")
  910. || id.startsWith ("plughw:") || id == "null")
  911. continue;
  912. String name (description.replace ("\n", "; "));
  913. if (name.isEmpty())
  914. name = id;
  915. bool isOutput = (ioid != "Input");
  916. bool isInput = (ioid != "Output");
  917. // alsa is stupid here, it advertises dmix and dsnoop as input/output devices, but
  918. // opening dmix as input, or dsnoop as output will trigger errors..
  919. isInput = isInput && ! id.startsWith ("dmix");
  920. isOutput = isOutput && ! id.startsWith ("dsnoop");
  921. if (isInput)
  922. {
  923. inputNames.add (name);
  924. inputIds.add (id);
  925. }
  926. if (isOutput)
  927. {
  928. outputNames.add (name);
  929. outputIds.add (id);
  930. }
  931. }
  932. snd_device_name_free_hint (hints);
  933. }
  934. // sometimes the "default" device is not listed, but it is nice to see it explicitely in the list
  935. if (! outputIds.contains ("default"))
  936. testDevice ("default", "Default ALSA Output", "Default ALSA Input");
  937. // same for the pulseaudio plugin
  938. if (! outputIds.contains ("pulse"))
  939. testDevice ("pulse", "Pulseaudio output", "Pulseaudio input");
  940. // make sure the default device is listed first, and followed by the pulse device (if present)
  941. int idx = outputIds.indexOf ("pulse");
  942. outputIds.move (idx, 0);
  943. outputNames.move (idx, 0);
  944. idx = inputIds.indexOf ("pulse");
  945. inputIds.move (idx, 0);
  946. inputNames.move (idx, 0);
  947. idx = outputIds.indexOf ("default");
  948. outputIds.move (idx, 0);
  949. outputNames.move (idx, 0);
  950. idx = inputIds.indexOf ("default");
  951. inputIds.move (idx, 0);
  952. inputNames.move (idx, 0);
  953. }
  954. static String hintToString (const void* hints, const char* type)
  955. {
  956. char* const hint = snd_device_name_get_hint (hints, type);
  957. const String s (hint);
  958. ::free (hint);
  959. return s;
  960. }
  961. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType)
  962. };
  963. }
  964. //==============================================================================
  965. AudioIODeviceType* createAudioIODeviceType_ALSA_Soundcards()
  966. {
  967. return new ALSAAudioIODeviceType (true, "ALSA HW");
  968. }
  969. AudioIODeviceType* createAudioIODeviceType_ALSA_PCMDevices()
  970. {
  971. return new ALSAAudioIODeviceType (false, "ALSA");
  972. }
  973. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA()
  974. {
  975. return createAudioIODeviceType_ALSA_PCMDevices();
  976. }