WinMMSound.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. 
  2. // Use -lwinmm for linking to the winmm library in GCC/G++
  3. #include "soundManagers.h"
  4. #include <windows.h>
  5. #include <mmsystem.h>
  6. using namespace dsr;
  7. static const int samplesPerChannel = 2048;
  8. static int bufferElements = 0;
  9. static Buffer outputBuffer, floatBuffer;
  10. static SafePointer<int16_t> outputData[2];
  11. static SafePointer<float> floatData;
  12. // Aligning memory to allow using the widest available floating-point SIMD vector.
  13. static const int soundBufferAlignment = DSR_FLOAT_ALIGNMENT;
  14. static void allocateBuffers(int neededElements) {
  15. int64_t roundedElements = roundUp(neededElements, soundBufferAlignment / 2);
  16. int64_t outputSize = roundedElements * sizeof(int16_t);
  17. outputBuffer = buffer_create(outputSize * 2);
  18. floatBuffer = buffer_create(roundedElements * sizeof(float), soundBufferAlignment);
  19. SafePointer<int16_t> allOutputData = buffer_getSafeData<int16_t>(outputBuffer, "Output data");
  20. outputData[0] = allOutputData.slice("Output data 0", 0, outputSize);
  21. outputData[1] = allOutputData.slice("Output data 1", outputSize, outputSize);
  22. floatData = buffer_getSafeData<float>(floatBuffer, "Output data");
  23. bufferElements = neededElements;
  24. }
  25. static HWAVEOUT waveOutput;
  26. static WAVEHDR header[2] = {0};
  27. static HANDLE bufferEndEvent = 0;
  28. static bool running = true;
  29. static void terminateSound() {
  30. printText("Terminating sound.\n");
  31. running = false;
  32. if (waveOutput) {
  33. waveOutReset(waveOutput);
  34. for (int b = 0; b < 2; b++) {
  35. waveOutUnprepareHeader(waveOutput, &header[b], sizeof(WAVEHDR));
  36. }
  37. waveOutClose(waveOutput);
  38. waveOutput = 0;
  39. }
  40. if (bufferEndEvent) {
  41. CloseHandle(bufferEndEvent);
  42. bufferEndEvent = 0;
  43. }
  44. }
  45. bool sound_streamToSpeakers(int channels, int sampleRate, std::function<bool(SafePointer<float> data, int length)> soundOutput) {
  46. bufferEndEvent = CreateEvent(0, FALSE, FALSE, 0);
  47. if (bufferEndEvent == 0) {
  48. terminateSound();
  49. sendWarning(U"Failed to create buffer end event!");
  50. return false;
  51. }
  52. int totalSamples = samplesPerChannel * channels;
  53. allocateBuffers(totalSamples);
  54. WAVEFORMATEX format;
  55. ZeroMemory(&format, sizeof(WAVEFORMATEX));
  56. format.nChannels = (WORD)channels;
  57. format.nSamplesPerSec = (DWORD)sampleRate;
  58. format.wFormatTag = WAVE_FORMAT_PCM;
  59. format.wBitsPerSample = 16;
  60. format.nBlockAlign = format.nChannels * sizeof(int16_t);
  61. format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
  62. format.cbSize = 0;
  63. if(waveOutOpen(&waveOutput, WAVE_MAPPER, &format, (DWORD_PTR)bufferEndEvent, (DWORD_PTR)NULL, CALLBACK_EVENT) != MMSYSERR_NOERROR) {
  64. terminateSound();
  65. sendWarning(U"Failed to open wave output!");
  66. return false;
  67. }
  68. if(waveOutSetVolume(waveOutput, 0xFFFFFFFF) != MMSYSERR_NOERROR) {
  69. terminateSound();
  70. sendWarning(U"Failed to set volume!");
  71. return false;
  72. }
  73. for (int b = 0; b < 2; b++) {
  74. ZeroMemory(&header[b], sizeof(WAVEHDR));
  75. header[b].dwBufferLength = totalSamples * sizeof(int16_t);
  76. header[b].lpData = (LPSTR)(outputData[b].getUnsafe());
  77. if (waveOutPrepareHeader(waveOutput, &header[b], sizeof(WAVEHDR)) != MMSYSERR_NOERROR) {
  78. terminateSound();
  79. sendWarning(U"Failed to prepare buffer for streaming!");
  80. return false;
  81. }
  82. }
  83. running = true;
  84. while (running) {
  85. for (int b = 0; b < 2; b++) {
  86. if ((header[b].dwFlags & WHDR_INQUEUE) == 0) {
  87. // When one of the buffers is done playing, generate new sound and write more data to the output.
  88. safeMemorySet(floatData, 0, totalSamples * sizeof(float));
  89. running = soundOutput(floatData, samplesPerChannel);
  90. //for (int i = 0; i < totalSamples; i++) {
  91. // outputData[b][i] = sound_convertF32ToI16(floatBuffer[i]);
  92. //}
  93. SafePointer<int16_t> target = outputData[b];
  94. // Convert to target format so that the sound can be played
  95. for (uint32_t t = 0; t < totalSamples; t+=8) {
  96. // SIMD vectorized sound conversion with scaling and clamping to signed 16-bit integers.
  97. F32x4 lowerFloats = F32x4::readAligned(floatData + t, "sound_streamToSpeakers: Reading lower floats");
  98. F32x4 upperFloats = F32x4::readAligned(floatData + t + 4, "sound_streamToSpeakers: Reading upper floats");
  99. I32x4 lowerInts = truncateToI32((lowerFloats * 32767.0f).clamp(-32768.0f, 32767.0f));
  100. I32x4 upperInts = truncateToI32((upperFloats * 32767.0f).clamp(-32768.0f, 32767.0f));
  101. // TODO: Create I16x8 SIMD vectors for processing sound as 16-bit integers?
  102. // Or just move unzip into simd.h with a fallback solution and remove simdExtra.h.
  103. // Or just implement reading and writing of 16-bit signed integers using multiple SIMD registers or smaller memory regions.
  104. IVector4D lower = lowerInts.get();
  105. IVector4D upper = upperInts.get();
  106. target[t+0] = (int16_t)lower.x;
  107. target[t+1] = (int16_t)lower.y;
  108. target[t+2] = (int16_t)lower.z;
  109. target[t+3] = (int16_t)lower.w;
  110. target[t+4] = (int16_t)upper.x;
  111. target[t+5] = (int16_t)upper.y;
  112. target[t+6] = (int16_t)upper.z;
  113. target[t+7] = (int16_t)upper.w;
  114. }
  115. if (waveOutWrite(waveOutput, &header[b], sizeof(WAVEHDR)) != MMSYSERR_NOERROR) {
  116. terminateSound();
  117. sendWarning(U"Failed to write wave output!");
  118. return false;
  119. }
  120. if (!running) { break; }
  121. }
  122. }
  123. WaitForSingleObject(bufferEndEvent, INFINITE);
  124. }
  125. terminateSound();
  126. return true;
  127. }