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.

juce_linux_ALSA.cpp 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  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<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, 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 (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.clear();
  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<double> 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() override { return internal.channelNamesOut; }
  641. StringArray getInputChannelNames() override { return internal.channelNamesIn; }
  642. Array<double> getAvailableSampleRates() override { return internal.sampleRates; }
  643. Array<int> getAvailableBufferSizes() override
  644. {
  645. Array<int> r;
  646. int n = 16;
  647. for (int i = 0; i < 50; ++i)
  648. {
  649. r.add (n);
  650. n += n < 64 ? 16
  651. : (n < 512 ? 32
  652. : (n < 1024 ? 64
  653. : (n < 2048 ? 128 : 256)));
  654. }
  655. return r;
  656. }
  657. int getDefaultBufferSize() override { return 512; }
  658. String open (const BigInteger& inputChannels,
  659. const BigInteger& outputChannels,
  660. double sampleRate,
  661. int bufferSizeSamples) override
  662. {
  663. close();
  664. if (bufferSizeSamples <= 0)
  665. bufferSizeSamples = getDefaultBufferSize();
  666. if (sampleRate <= 0)
  667. {
  668. for (int i = 0; i < internal.sampleRates.size(); ++i)
  669. {
  670. double rate = internal.sampleRates[i];
  671. if (rate >= 44100)
  672. {
  673. sampleRate = rate;
  674. break;
  675. }
  676. }
  677. }
  678. internal.open (inputChannels, outputChannels,
  679. sampleRate, bufferSizeSamples);
  680. isOpen_ = internal.error.isEmpty();
  681. return internal.error;
  682. }
  683. void close() override
  684. {
  685. stop();
  686. internal.close();
  687. isOpen_ = false;
  688. }
  689. bool isOpen() override { return isOpen_; }
  690. bool isPlaying() override { return isStarted && internal.error.isEmpty(); }
  691. String getLastError() override { return internal.error; }
  692. int getCurrentBufferSizeSamples() override { return internal.bufferSize; }
  693. double getCurrentSampleRate() override { return internal.sampleRate; }
  694. int getCurrentBitDepth() override { return internal.getBitDepth(); }
  695. BigInteger getActiveOutputChannels() const override { return internal.currentOutputChans; }
  696. BigInteger getActiveInputChannels() const override { return internal.currentInputChans; }
  697. int getOutputLatencyInSamples() override { return internal.outputLatency; }
  698. int getInputLatencyInSamples() override { return internal.inputLatency; }
  699. void start (AudioIODeviceCallback* callback) override
  700. {
  701. if (! isOpen_)
  702. callback = nullptr;
  703. if (callback != nullptr)
  704. callback->audioDeviceAboutToStart (this);
  705. internal.setCallback (callback);
  706. isStarted = (callback != nullptr);
  707. }
  708. void stop() override
  709. {
  710. AudioIODeviceCallback* const oldCallback = internal.callback;
  711. start (nullptr);
  712. if (oldCallback != nullptr)
  713. oldCallback->audioDeviceStopped();
  714. }
  715. String inputId, outputId;
  716. private:
  717. bool isOpen_, isStarted;
  718. ALSAThread internal;
  719. };
  720. //==============================================================================
  721. class ALSAAudioIODeviceType : public AudioIODeviceType
  722. {
  723. public:
  724. ALSAAudioIODeviceType (bool onlySoundcards, const String &typeName)
  725. : AudioIODeviceType (typeName),
  726. hasScanned (false),
  727. listOnlySoundcards (onlySoundcards)
  728. {
  729. #if ! JUCE_ALSA_LOGGING
  730. snd_lib_error_set_handler (&silentErrorHandler);
  731. #endif
  732. }
  733. ~ALSAAudioIODeviceType()
  734. {
  735. #if ! JUCE_ALSA_LOGGING
  736. snd_lib_error_set_handler (nullptr);
  737. #endif
  738. snd_config_update_free_global(); // prevent valgrind from screaming about alsa leaks
  739. }
  740. //==============================================================================
  741. void scanForDevices()
  742. {
  743. if (hasScanned)
  744. return;
  745. hasScanned = true;
  746. inputNames.clear();
  747. inputIds.clear();
  748. outputNames.clear();
  749. outputIds.clear();
  750. JUCE_ALSA_LOG ("scanForDevices()");
  751. if (listOnlySoundcards)
  752. enumerateAlsaSoundcards();
  753. else
  754. enumerateAlsaPCMDevices();
  755. inputNames.appendNumbersToDuplicates (false, true);
  756. outputNames.appendNumbersToDuplicates (false, true);
  757. }
  758. StringArray getDeviceNames (bool wantInputNames) const
  759. {
  760. jassert (hasScanned); // need to call scanForDevices() before doing this
  761. return wantInputNames ? inputNames : outputNames;
  762. }
  763. int getDefaultDeviceIndex (bool forInput) const
  764. {
  765. jassert (hasScanned); // need to call scanForDevices() before doing this
  766. const int idx = (forInput ? inputIds : outputIds).indexOf ("default");
  767. return idx >= 0 ? idx : 0;
  768. }
  769. bool hasSeparateInputsAndOutputs() const { return true; }
  770. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  771. {
  772. jassert (hasScanned); // need to call scanForDevices() before doing this
  773. if (ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device))
  774. return asInput ? inputIds.indexOf (d->inputId)
  775. : outputIds.indexOf (d->outputId);
  776. return -1;
  777. }
  778. AudioIODevice* createDevice (const String& outputDeviceName,
  779. const String& inputDeviceName)
  780. {
  781. jassert (hasScanned); // need to call scanForDevices() before doing this
  782. const int inputIndex = inputNames.indexOf (inputDeviceName);
  783. const int outputIndex = outputNames.indexOf (outputDeviceName);
  784. String deviceName (outputIndex >= 0 ? outputDeviceName
  785. : inputDeviceName);
  786. if (inputIndex >= 0 || outputIndex >= 0)
  787. return new ALSAAudioIODevice (deviceName, getTypeName(),
  788. inputIds [inputIndex],
  789. outputIds [outputIndex]);
  790. return nullptr;
  791. }
  792. private:
  793. //==============================================================================
  794. StringArray inputNames, outputNames, inputIds, outputIds;
  795. bool hasScanned, listOnlySoundcards;
  796. bool testDevice (const String &id, const String &outputName, const String &inputName)
  797. {
  798. unsigned int minChansOut = 0, maxChansOut = 0;
  799. unsigned int minChansIn = 0, maxChansIn = 0;
  800. Array<double> rates;
  801. bool isInput = inputName.isNotEmpty(), isOutput = outputName.isNotEmpty();
  802. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates, isOutput, isInput);
  803. isInput = maxChansIn > 0;
  804. isOutput = maxChansOut > 0;
  805. if ((isInput || isOutput) && rates.size() > 0)
  806. {
  807. JUCE_ALSA_LOG ("testDevice: '" << id.toUTF8().getAddress() << "' -> isInput: "
  808. << isInput << ", isOutput: " << isOutput);
  809. if (isInput)
  810. {
  811. inputNames.add (inputName);
  812. inputIds.add (id);
  813. }
  814. if (isOutput)
  815. {
  816. outputNames.add (outputName);
  817. outputIds.add (id);
  818. }
  819. return isInput || isOutput;
  820. }
  821. return false;
  822. }
  823. void enumerateAlsaSoundcards()
  824. {
  825. snd_ctl_t* handle = nullptr;
  826. snd_ctl_card_info_t* info = nullptr;
  827. snd_ctl_card_info_alloca (&info);
  828. int cardNum = -1;
  829. while (outputIds.size() + inputIds.size() <= 64)
  830. {
  831. snd_card_next (&cardNum);
  832. if (cardNum < 0)
  833. break;
  834. if (JUCE_CHECKED_RESULT (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK)) >= 0)
  835. {
  836. if (JUCE_CHECKED_RESULT (snd_ctl_card_info (handle, info)) >= 0)
  837. {
  838. String cardId (snd_ctl_card_info_get_id (info));
  839. if (cardId.removeCharacters ("0123456789").isEmpty())
  840. cardId = String (cardNum);
  841. String cardName = snd_ctl_card_info_get_name (info);
  842. if (cardName.isEmpty())
  843. cardName = cardId;
  844. int device = -1;
  845. snd_pcm_info_t* pcmInfo;
  846. snd_pcm_info_alloca (&pcmInfo);
  847. for (;;)
  848. {
  849. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  850. break;
  851. snd_pcm_info_set_device (pcmInfo, device);
  852. for (int subDevice = 0, nbSubDevice = 1; subDevice < nbSubDevice; ++subDevice)
  853. {
  854. snd_pcm_info_set_subdevice (pcmInfo, subDevice);
  855. snd_pcm_info_set_stream (pcmInfo, SND_PCM_STREAM_CAPTURE);
  856. const bool isInput = (snd_ctl_pcm_info (handle, pcmInfo) >= 0);
  857. snd_pcm_info_set_stream (pcmInfo, SND_PCM_STREAM_PLAYBACK);
  858. const bool isOutput = (snd_ctl_pcm_info (handle, pcmInfo) >= 0);
  859. if (! (isInput || isOutput))
  860. continue;
  861. if (nbSubDevice == 1)
  862. nbSubDevice = snd_pcm_info_get_subdevices_count (pcmInfo);
  863. String id, name;
  864. if (nbSubDevice == 1)
  865. {
  866. id << "hw:" << cardId << "," << device;
  867. name << cardName << ", " << snd_pcm_info_get_name (pcmInfo);
  868. }
  869. else
  870. {
  871. id << "hw:" << cardId << "," << device << "," << subDevice;
  872. name << cardName << ", " << snd_pcm_info_get_name (pcmInfo)
  873. << " {" << snd_pcm_info_get_subdevice_name (pcmInfo) << "}";
  874. }
  875. JUCE_ALSA_LOG ("Soundcard ID: " << id << ", name: '" << name
  876. << ", isInput:" << isInput << ", isOutput:" << isOutput << "\n");
  877. if (isInput)
  878. {
  879. inputNames.add (name);
  880. inputIds.add (id);
  881. }
  882. if (isOutput)
  883. {
  884. outputNames.add (name);
  885. outputIds.add (id);
  886. }
  887. }
  888. }
  889. }
  890. JUCE_CHECKED_RESULT (snd_ctl_close (handle));
  891. }
  892. }
  893. }
  894. /* Enumerates all ALSA output devices (as output by the command aplay -L)
  895. Does not try to open the devices (with "testDevice" for example),
  896. so that it also finds devices that are busy and not yet available.
  897. */
  898. void enumerateAlsaPCMDevices()
  899. {
  900. void** hints = nullptr;
  901. if (JUCE_CHECKED_RESULT (snd_device_name_hint (-1, "pcm", &hints)) == 0)
  902. {
  903. for (char** h = (char**) hints; *h; ++h)
  904. {
  905. const String id (hintToString (*h, "NAME"));
  906. const String description (hintToString (*h, "DESC"));
  907. const String ioid (hintToString (*h, "IOID"));
  908. JUCE_ALSA_LOG ("ID: " << id << "; desc: " << description << "; ioid: " << ioid);
  909. String ss = id.fromFirstOccurrenceOf ("=", false, false)
  910. .upToFirstOccurrenceOf (",", false, false);
  911. if (id.isEmpty()
  912. || id.startsWith ("default:") || id.startsWith ("sysdefault:")
  913. || id.startsWith ("plughw:") || id == "null")
  914. continue;
  915. String name (description.replace ("\n", "; "));
  916. if (name.isEmpty())
  917. name = id;
  918. bool isOutput = (ioid != "Input");
  919. bool isInput = (ioid != "Output");
  920. // alsa is stupid here, it advertises dmix and dsnoop as input/output devices, but
  921. // opening dmix as input, or dsnoop as output will trigger errors..
  922. isInput = isInput && ! id.startsWith ("dmix");
  923. isOutput = isOutput && ! id.startsWith ("dsnoop");
  924. if (isInput)
  925. {
  926. inputNames.add (name);
  927. inputIds.add (id);
  928. }
  929. if (isOutput)
  930. {
  931. outputNames.add (name);
  932. outputIds.add (id);
  933. }
  934. }
  935. snd_device_name_free_hint (hints);
  936. }
  937. // sometimes the "default" device is not listed, but it is nice to see it explicitely in the list
  938. if (! outputIds.contains ("default"))
  939. testDevice ("default", "Default ALSA Output", "Default ALSA Input");
  940. // same for the pulseaudio plugin
  941. if (! outputIds.contains ("pulse"))
  942. testDevice ("pulse", "Pulseaudio output", "Pulseaudio input");
  943. // make sure the default device is listed first, and followed by the pulse device (if present)
  944. int idx = outputIds.indexOf ("pulse");
  945. outputIds.move (idx, 0);
  946. outputNames.move (idx, 0);
  947. idx = inputIds.indexOf ("pulse");
  948. inputIds.move (idx, 0);
  949. inputNames.move (idx, 0);
  950. idx = outputIds.indexOf ("default");
  951. outputIds.move (idx, 0);
  952. outputNames.move (idx, 0);
  953. idx = inputIds.indexOf ("default");
  954. inputIds.move (idx, 0);
  955. inputNames.move (idx, 0);
  956. }
  957. static String hintToString (const void* hints, const char* type)
  958. {
  959. char* const hint = snd_device_name_get_hint (hints, type);
  960. const String s (String::fromUTF8 (hint));
  961. ::free (hint);
  962. return s;
  963. }
  964. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType)
  965. };
  966. }
  967. //==============================================================================
  968. AudioIODeviceType* createAudioIODeviceType_ALSA_Soundcards()
  969. {
  970. return new ALSAAudioIODeviceType (true, "ALSA HW");
  971. }
  972. AudioIODeviceType* createAudioIODeviceType_ALSA_PCMDevices()
  973. {
  974. return new ALSAAudioIODeviceType (false, "ALSA");
  975. }
  976. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA()
  977. {
  978. return createAudioIODeviceType_ALSA_PCMDevices();
  979. }