AlsaSound.cpp 4.9 KB

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