2
0

AlsaSound.cpp 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. throwError("Cannot open sound device. (", snd_strerror(errorCode), ")\n");
  35. }
  36. snd_pcm_hw_params_t *hardwareParameters;
  37. snd_pcm_hw_params_alloca(&hardwareParameters);
  38. snd_pcm_hw_params_any(pcm, hardwareParameters);
  39. if ((errorCode = snd_pcm_hw_params_set_access(pcm, hardwareParameters, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
  40. terminateSound();
  41. throwError("Failed to select interleaved sound. (", snd_strerror(errorCode), ")\n");
  42. }
  43. if ((errorCode = snd_pcm_hw_params_set_format(pcm, hardwareParameters, SND_PCM_FORMAT_S16_LE)) < 0) {
  44. terminateSound();
  45. throwError("Failed to select sound format. (", snd_strerror(errorCode), ")\n");
  46. }
  47. if ((errorCode = snd_pcm_hw_params_set_channels(pcm, hardwareParameters, channels)) < 0) {
  48. terminateSound();
  49. throwError("Failed to select channel count. (", snd_strerror(errorCode), ")\n");
  50. }
  51. if ((errorCode = snd_pcm_hw_params_set_buffer_size(pcm, hardwareParameters, 2048)) < 0) {
  52. terminateSound();
  53. throwError("Failed to select buffer size. (", snd_strerror(errorCode), ")\n");
  54. }
  55. uint rate = sampleRate;
  56. if ((errorCode = snd_pcm_hw_params_set_rate_near(pcm, hardwareParameters, &rate, 0)) < 0) {
  57. terminateSound();
  58. throwError("Failed to select approximate sample rate. (", snd_strerror(errorCode), ")\n");
  59. }
  60. if ((errorCode = snd_pcm_hw_params(pcm, hardwareParameters)) < 0) {
  61. terminateSound();
  62. throwError("Failed to select hardware parameters. (", snd_strerror(errorCode), ")\n");
  63. }
  64. // Allocate a buffer for sending data to speakers
  65. snd_pcm_uframes_t samplesPerChannel;
  66. snd_pcm_hw_params_get_period_size(hardwareParameters, &samplesPerChannel, 0);
  67. // Allocate target buffers
  68. int totalSamples = samplesPerChannel * channels;
  69. allocateBuffers(totalSamples);
  70. while (true) {
  71. safeMemorySet(floatData, 0, totalSamples * sizeof(float));
  72. bool keepRunning = soundOutput(floatData, samplesPerChannel);
  73. // Convert to target format so that the sound can be played
  74. for (uint32_t t = 0; t < samplesPerChannel * channels; t+=8) {
  75. // SIMD vectorized sound conversion with scaling and clamping to signed 16-bit integers.
  76. F32x4 lowerFloats = F32x4::readAligned(floatData + t, "sound_streamToSpeakers: Reading lower floats");
  77. F32x4 upperFloats = F32x4::readAligned(floatData + t + 4, "sound_streamToSpeakers: Reading upper floats");
  78. I32x4 lowerInts = truncateToI32((lowerFloats * 32767.0f).clamp(-32768.0f, 32767.0f));
  79. I32x4 upperInts = truncateToI32((upperFloats * 32767.0f).clamp(-32768.0f, 32767.0f));
  80. // TODO: Create I16x8 SIMD vectors for processing sound as 16-bit integers?
  81. // Or just move unzip into simd.h with a fallback solution and remove simdExtra.h.
  82. // Or just implement reading and writing of 16-bit signed integers using multiple SIMD registers or smaller memory regions.
  83. IVector4D lower = lowerInts.get();
  84. IVector4D upper = upperInts.get();
  85. outputData[t+0] = (int16_t)lower.x;
  86. outputData[t+1] = (int16_t)lower.y;
  87. outputData[t+2] = (int16_t)lower.z;
  88. outputData[t+3] = (int16_t)lower.w;
  89. outputData[t+4] = (int16_t)upper.x;
  90. outputData[t+5] = (int16_t)upper.y;
  91. outputData[t+6] = (int16_t)upper.z;
  92. outputData[t+7] = (int16_t)upper.w;
  93. }
  94. errorCode = snd_pcm_writei(pcm, outputData.getUnsafe(), samplesPerChannel);
  95. if (errorCode == -EPIPE) {
  96. // Came too late! Not enough written samples to play.
  97. snd_pcm_prepare(pcm);
  98. } else if (errorCode < 0) {
  99. terminateSound();
  100. throwError("Failed writing data to PCM. (", snd_strerror(errorCode), ")\n");
  101. }
  102. if (!keepRunning) {
  103. break;
  104. }
  105. }
  106. terminateSound();
  107. return true;
  108. }