AlsaSound.cpp 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. 
  2. // Use -lasound for linking to the winmm library in GCC/G++
  3. // Install on Arch: sudo pacman -S libasound-dev
  4. // Install on Debian: sudo apt-get install libasound-dev
  5. #include "soundManagers.h"
  6. #include <alsa/asoundlib.h>
  7. using namespace dsr;
  8. snd_pcm_t *pcm = nullptr;
  9. static int bufferElements = 0;
  10. static Buffer outputBuffer, floatBuffer;
  11. static SafePointer<int16_t> outputData;
  12. static SafePointer<float> floatData;
  13. // Aligning memory to allow using the widest available floating-point SIMD vector.
  14. static const int soundBufferAlignment = DSR_FLOAT_ALIGNMENT;
  15. static void allocateBuffers(int neededElements) {
  16. outputBuffer = buffer_create(neededElements * sizeof(int16_t), soundBufferAlignment);
  17. floatBuffer = buffer_create(neededElements * sizeof(float), soundBufferAlignment);
  18. outputData = buffer_getSafeData<int16_t>(outputBuffer, "Output data");
  19. floatData = buffer_getSafeData<float>(floatBuffer, "Output data");
  20. bufferElements = neededElements;
  21. }
  22. static void terminateSound() {
  23. if (pcm) {
  24. snd_pcm_drop(pcm);
  25. snd_pcm_drain(pcm);
  26. snd_pcm_close(pcm);
  27. pcm = nullptr;
  28. }
  29. }
  30. bool sound_streamToSpeakers(int channels, int sampleRate, std::function<bool(SafePointer<float> data, int length)> soundOutput) {
  31. int errorCode;
  32. if ((errorCode = snd_pcm_open(&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
  33. terminateSound();
  34. sendWarning("Cannot open sound device. (", snd_strerror(errorCode), ")\n");
  35. return false;
  36. }
  37. snd_pcm_hw_params_t *hardwareParameters;
  38. snd_pcm_hw_params_alloca(&hardwareParameters);
  39. snd_pcm_hw_params_any(pcm, hardwareParameters);
  40. if ((errorCode = snd_pcm_hw_params_set_access(pcm, hardwareParameters, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
  41. terminateSound();
  42. sendWarning("Failed to select interleaved sound. (", snd_strerror(errorCode), ")\n");
  43. return false;
  44. }
  45. if ((errorCode = snd_pcm_hw_params_set_format(pcm, hardwareParameters, SND_PCM_FORMAT_S16_LE)) < 0) {
  46. terminateSound();
  47. sendWarning("Failed to select sound format. (", snd_strerror(errorCode), ")\n");
  48. return false;
  49. }
  50. if ((errorCode = snd_pcm_hw_params_set_channels(pcm, hardwareParameters, channels)) < 0) {
  51. terminateSound();
  52. sendWarning("Failed to select channel count. (", snd_strerror(errorCode), ")\n");
  53. return false;
  54. }
  55. if ((errorCode = snd_pcm_hw_params_set_buffer_size(pcm, hardwareParameters, 2048)) < 0) {
  56. terminateSound();
  57. sendWarning("Failed to select buffer size. (", snd_strerror(errorCode), ")\n");
  58. return false;
  59. }
  60. uint rate = sampleRate;
  61. if ((errorCode = snd_pcm_hw_params_set_rate_near(pcm, hardwareParameters, &rate, 0)) < 0) {
  62. terminateSound();
  63. sendWarning("Failed to select approximate sample rate. (", snd_strerror(errorCode), ")\n");
  64. return false;
  65. }
  66. if ((errorCode = snd_pcm_hw_params(pcm, hardwareParameters)) < 0) {
  67. terminateSound();
  68. sendWarning("Failed to select hardware parameters. (", snd_strerror(errorCode), ")\n");
  69. return false;
  70. }
  71. // Allocate a buffer for sending data to speakers
  72. snd_pcm_uframes_t samplesPerChannel;
  73. snd_pcm_hw_params_get_period_size(hardwareParameters, &samplesPerChannel, 0);
  74. // Allocate target buffers
  75. int totalSamples = samplesPerChannel * channels;
  76. allocateBuffers(totalSamples);
  77. while (true) {
  78. safeMemorySet(floatData, 0, totalSamples * sizeof(float));
  79. bool keepRunning = soundOutput(floatData, samplesPerChannel);
  80. // Convert to target format so that the sound can be played
  81. for (uint32_t t = 0; t < samplesPerChannel * channels; t+=8) {
  82. // SIMD vectorized sound conversion with scaling and clamping to signed 16-bit integers.
  83. F32x4 lowerFloats = F32x4::readAligned(floatData + t, "sound_streamToSpeakers: Reading lower floats");
  84. F32x4 upperFloats = F32x4::readAligned(floatData + t + 4, "sound_streamToSpeakers: Reading upper floats");
  85. I32x4 lowerInts = truncateToI32((lowerFloats * 32767.0f).clamp(-32768.0f, 32767.0f));
  86. I32x4 upperInts = truncateToI32((upperFloats * 32767.0f).clamp(-32768.0f, 32767.0f));
  87. // TODO: Create I16x8 SIMD vectors for processing sound as 16-bit integers?
  88. // Or just move unzip into simd.h with a fallback solution and remove simdExtra.h.
  89. // Or just implement reading and writing of 16-bit signed integers using multiple SIMD registers or smaller memory regions.
  90. IVector4D lower = lowerInts.get();
  91. IVector4D upper = upperInts.get();
  92. outputData[t+0] = (int16_t)lower.x;
  93. outputData[t+1] = (int16_t)lower.y;
  94. outputData[t+2] = (int16_t)lower.z;
  95. outputData[t+3] = (int16_t)lower.w;
  96. outputData[t+4] = (int16_t)upper.x;
  97. outputData[t+5] = (int16_t)upper.y;
  98. outputData[t+6] = (int16_t)upper.z;
  99. outputData[t+7] = (int16_t)upper.w;
  100. }
  101. errorCode = snd_pcm_writei(pcm, outputData.getUnsafe(), samplesPerChannel);
  102. if (errorCode == -EPIPE) {
  103. // Came too late! Not enough written samples to play.
  104. snd_pcm_prepare(pcm);
  105. } else if (errorCode < 0) {
  106. terminateSound();
  107. throwError("Failed writing data to PCM. (", snd_strerror(errorCode), ")\n");
  108. }
  109. if (!keepRunning) {
  110. break;
  111. }
  112. }
  113. terminateSound();
  114. return true;
  115. }