AlsaSound.cpp 5.1 KB

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