Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1286 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. extern "C"
  18. {
  19. // Declare just the minimum number of interfaces for the DSound objects that we need..
  20. struct DSBUFFERDESC
  21. {
  22. DWORD dwSize;
  23. DWORD dwFlags;
  24. DWORD dwBufferBytes;
  25. DWORD dwReserved;
  26. LPWAVEFORMATEX lpwfxFormat;
  27. GUID guid3DAlgorithm;
  28. };
  29. struct IDirectSoundBuffer;
  30. #undef INTERFACE
  31. #define INTERFACE IDirectSound
  32. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  33. {
  34. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  35. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  36. STDMETHOD_(ULONG,Release) (THIS) PURE;
  37. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  38. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  39. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  40. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  41. STDMETHOD(Compact) (THIS) PURE;
  42. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  43. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  44. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  45. };
  46. #undef INTERFACE
  47. #define INTERFACE IDirectSoundBuffer
  48. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  49. {
  50. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  51. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  52. STDMETHOD_(ULONG,Release) (THIS) PURE;
  53. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  54. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  55. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  56. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  57. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  58. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  59. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  60. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  61. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  62. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  63. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  64. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  65. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  66. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  67. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  68. STDMETHOD(Stop) (THIS) PURE;
  69. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  70. STDMETHOD(Restore) (THIS) PURE;
  71. };
  72. //==============================================================================
  73. struct DSCBUFFERDESC
  74. {
  75. DWORD dwSize;
  76. DWORD dwFlags;
  77. DWORD dwBufferBytes;
  78. DWORD dwReserved;
  79. LPWAVEFORMATEX lpwfxFormat;
  80. };
  81. struct IDirectSoundCaptureBuffer;
  82. #undef INTERFACE
  83. #define INTERFACE IDirectSoundCapture
  84. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  85. {
  86. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  87. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  88. STDMETHOD_(ULONG,Release) (THIS) PURE;
  89. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  90. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  91. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  92. };
  93. #undef INTERFACE
  94. #define INTERFACE IDirectSoundCaptureBuffer
  95. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  96. {
  97. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  98. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  99. STDMETHOD_(ULONG,Release) (THIS) PURE;
  100. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  101. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  102. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  103. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  104. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  105. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  106. STDMETHOD(Start) (THIS_ DWORD) PURE;
  107. STDMETHOD(Stop) (THIS) PURE;
  108. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  109. };
  110. #undef INTERFACE
  111. }
  112. namespace juce
  113. {
  114. //==============================================================================
  115. namespace DSoundLogging
  116. {
  117. String getErrorMessage (HRESULT hr)
  118. {
  119. const char* result = nullptr;
  120. switch (hr)
  121. {
  122. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  123. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  124. case E_INVALIDARG: result = "Invalid parameter"; break;
  125. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  126. case E_FAIL: result = "Generic error"; break;
  127. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  128. case E_OUTOFMEMORY: result = "Out of memory"; break;
  129. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  130. case E_NOTIMPL: result = "Unsupported function"; break;
  131. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  132. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  133. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  134. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  135. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  136. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  137. case E_NOINTERFACE: result = "No interface"; break;
  138. case S_OK: result = "No error"; break;
  139. default: return "Unknown error: " + String ((int) hr);
  140. }
  141. return result;
  142. }
  143. //==============================================================================
  144. #if JUCE_DIRECTSOUND_LOGGING
  145. static void logMessage (String message)
  146. {
  147. message = "DSOUND: " + message;
  148. DBG (message);
  149. Logger::writeToLog (message);
  150. }
  151. static void logError (HRESULT hr, int lineNum)
  152. {
  153. if (FAILED (hr))
  154. {
  155. String error ("Error at line ");
  156. error << lineNum << ": " << getErrorMessage (hr);
  157. logMessage (error);
  158. }
  159. }
  160. #define JUCE_DS_LOG(a) DSoundLogging::logMessage(a);
  161. #define JUCE_DS_LOG_ERROR(a) DSoundLogging::logError(a, __LINE__);
  162. #else
  163. #define JUCE_DS_LOG(a)
  164. #define JUCE_DS_LOG_ERROR(a)
  165. #endif
  166. }
  167. //==============================================================================
  168. namespace
  169. {
  170. #define DSOUND_FUNCTION(functionName, params) \
  171. typedef HRESULT (WINAPI *type##functionName) params; \
  172. static type##functionName ds##functionName = nullptr;
  173. #define DSOUND_FUNCTION_LOAD(functionName) \
  174. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  175. jassert (ds##functionName != nullptr);
  176. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  177. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  178. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  179. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  180. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  181. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  182. void initialiseDSoundFunctions()
  183. {
  184. if (dsDirectSoundCreate == nullptr)
  185. {
  186. HMODULE h = LoadLibraryA ("dsound.dll");
  187. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  188. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  189. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  190. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  191. }
  192. }
  193. // the overall size of buffer used is this value x the block size
  194. enum { blocksPerOverallBuffer = 16 };
  195. }
  196. //==============================================================================
  197. class DSoundInternalOutChannel
  198. {
  199. public:
  200. DSoundInternalOutChannel (const String& name_, const GUID& guid_, int rate,
  201. int bufferSize, float* left, float* right)
  202. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  203. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  204. pDirectSound (nullptr), pOutputBuffer (nullptr)
  205. {
  206. }
  207. ~DSoundInternalOutChannel()
  208. {
  209. close();
  210. }
  211. void close()
  212. {
  213. if (pOutputBuffer != nullptr)
  214. {
  215. JUCE_DS_LOG ("closing output: " + name);
  216. HRESULT hr = pOutputBuffer->Stop();
  217. JUCE_DS_LOG_ERROR (hr); ignoreUnused (hr);
  218. pOutputBuffer->Release();
  219. pOutputBuffer = nullptr;
  220. }
  221. if (pDirectSound != nullptr)
  222. {
  223. pDirectSound->Release();
  224. pDirectSound = nullptr;
  225. }
  226. }
  227. String open()
  228. {
  229. JUCE_DS_LOG ("opening output: " + name + " rate=" + String (sampleRate)
  230. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  231. pDirectSound = nullptr;
  232. pOutputBuffer = nullptr;
  233. writeOffset = 0;
  234. xruns = 0;
  235. firstPlayTime = true;
  236. lastPlayTime = 0;
  237. String error;
  238. HRESULT hr = E_NOINTERFACE;
  239. if (dsDirectSoundCreate != nullptr)
  240. hr = dsDirectSoundCreate (&guid, &pDirectSound, nullptr);
  241. if (SUCCEEDED (hr))
  242. {
  243. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  244. ticksPerBuffer = bytesPerBuffer * Time::getHighResolutionTicksPerSecond() / (sampleRate * (bitDepth >> 2));
  245. totalBytesPerBuffer = (blocksPerOverallBuffer * bytesPerBuffer) & ~15;
  246. const int numChannels = 2;
  247. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  248. JUCE_DS_LOG_ERROR (hr);
  249. if (SUCCEEDED (hr))
  250. {
  251. IDirectSoundBuffer* pPrimaryBuffer;
  252. DSBUFFERDESC primaryDesc = {};
  253. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  254. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  255. primaryDesc.dwBufferBytes = 0;
  256. primaryDesc.lpwfxFormat = 0;
  257. JUCE_DS_LOG ("co-op level set");
  258. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  259. JUCE_DS_LOG_ERROR (hr);
  260. if (SUCCEEDED (hr))
  261. {
  262. WAVEFORMATEX wfFormat;
  263. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  264. wfFormat.nChannels = (unsigned short) numChannels;
  265. wfFormat.nSamplesPerSec = (DWORD) sampleRate;
  266. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  267. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  268. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  269. wfFormat.cbSize = 0;
  270. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  271. JUCE_DS_LOG_ERROR (hr);
  272. if (SUCCEEDED (hr))
  273. {
  274. DSBUFFERDESC secondaryDesc = {};
  275. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  276. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  277. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  278. secondaryDesc.dwBufferBytes = (DWORD) totalBytesPerBuffer;
  279. secondaryDesc.lpwfxFormat = &wfFormat;
  280. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  281. JUCE_DS_LOG_ERROR (hr);
  282. if (SUCCEEDED (hr))
  283. {
  284. JUCE_DS_LOG ("buffer created");
  285. DWORD dwDataLen;
  286. unsigned char* pDSBuffData;
  287. hr = pOutputBuffer->Lock (0, (DWORD) totalBytesPerBuffer,
  288. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  289. JUCE_DS_LOG_ERROR (hr);
  290. if (SUCCEEDED (hr))
  291. {
  292. zeromem (pDSBuffData, dwDataLen);
  293. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  294. if (SUCCEEDED (hr))
  295. {
  296. hr = pOutputBuffer->SetCurrentPosition (0);
  297. if (SUCCEEDED (hr))
  298. {
  299. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  300. if (SUCCEEDED (hr))
  301. return {};
  302. }
  303. }
  304. }
  305. }
  306. }
  307. }
  308. }
  309. }
  310. error = DSoundLogging::getErrorMessage (hr);
  311. close();
  312. return error;
  313. }
  314. void synchronisePosition()
  315. {
  316. if (pOutputBuffer != nullptr)
  317. {
  318. DWORD playCursor;
  319. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  320. }
  321. }
  322. bool service()
  323. {
  324. if (pOutputBuffer == 0)
  325. return true;
  326. DWORD playCursor, writeCursor;
  327. for (;;)
  328. {
  329. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  330. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  331. {
  332. pOutputBuffer->Restore();
  333. continue;
  334. }
  335. if (SUCCEEDED (hr))
  336. break;
  337. JUCE_DS_LOG_ERROR (hr);
  338. jassertfalse;
  339. return true;
  340. }
  341. auto currentPlayTime = Time::getHighResolutionTicks();
  342. if (! firstPlayTime)
  343. {
  344. auto expectedBuffers = (currentPlayTime - lastPlayTime) / ticksPerBuffer;
  345. playCursor += static_cast<DWORD> (expectedBuffers * bytesPerBuffer);
  346. }
  347. else
  348. firstPlayTime = false;
  349. lastPlayTime = currentPlayTime;
  350. int playWriteGap = (int) (writeCursor - playCursor);
  351. if (playWriteGap < 0)
  352. playWriteGap += totalBytesPerBuffer;
  353. int bytesEmpty = (int) (playCursor - writeOffset);
  354. if (bytesEmpty < 0)
  355. bytesEmpty += totalBytesPerBuffer;
  356. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  357. {
  358. writeOffset = writeCursor;
  359. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  360. // buffer underflow
  361. xruns++;
  362. }
  363. if (bytesEmpty >= bytesPerBuffer)
  364. {
  365. int* buf1 = nullptr;
  366. int* buf2 = nullptr;
  367. DWORD dwSize1 = 0;
  368. DWORD dwSize2 = 0;
  369. HRESULT hr = pOutputBuffer->Lock (writeOffset, (DWORD) bytesPerBuffer,
  370. (void**) &buf1, &dwSize1,
  371. (void**) &buf2, &dwSize2, 0);
  372. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  373. {
  374. pOutputBuffer->Restore();
  375. hr = pOutputBuffer->Lock (writeOffset, (DWORD) bytesPerBuffer,
  376. (void**) &buf1, &dwSize1,
  377. (void**) &buf2, &dwSize2, 0);
  378. }
  379. if (SUCCEEDED (hr))
  380. {
  381. if (bitDepth == 16)
  382. {
  383. const float* left = leftBuffer;
  384. const float* right = rightBuffer;
  385. int samples1 = (int) (dwSize1 >> 2);
  386. int samples2 = (int) (dwSize2 >> 2);
  387. if (left == nullptr)
  388. {
  389. for (int* dest = buf1; --samples1 >= 0;) *dest++ = convertInputValues (0, *right++);
  390. for (int* dest = buf2; --samples2 >= 0;) *dest++ = convertInputValues (0, *right++);
  391. }
  392. else if (right == nullptr)
  393. {
  394. for (int* dest = buf1; --samples1 >= 0;) *dest++ = convertInputValues (*left++, 0);
  395. for (int* dest = buf2; --samples2 >= 0;) *dest++ = convertInputValues (*left++, 0);
  396. }
  397. else
  398. {
  399. for (int* dest = buf1; --samples1 >= 0;) *dest++ = convertInputValues (*left++, *right++);
  400. for (int* dest = buf2; --samples2 >= 0;) *dest++ = convertInputValues (*left++, *right++);
  401. }
  402. }
  403. else
  404. {
  405. jassertfalse;
  406. }
  407. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  408. pOutputBuffer->Unlock (buf1, dwSize1, buf2, dwSize2);
  409. }
  410. else
  411. {
  412. jassertfalse;
  413. JUCE_DS_LOG_ERROR (hr);
  414. }
  415. bytesEmpty -= bytesPerBuffer;
  416. return true;
  417. }
  418. else
  419. {
  420. return false;
  421. }
  422. }
  423. int bitDepth, xruns;
  424. bool doneFlag;
  425. private:
  426. String name;
  427. GUID guid;
  428. int sampleRate, bufferSizeSamples;
  429. float* leftBuffer;
  430. float* rightBuffer;
  431. IDirectSound* pDirectSound;
  432. IDirectSoundBuffer* pOutputBuffer;
  433. DWORD writeOffset;
  434. int totalBytesPerBuffer, bytesPerBuffer;
  435. bool firstPlayTime;
  436. int64 lastPlayTime, ticksPerBuffer;
  437. static int convertInputValues (const float l, const float r) noexcept
  438. {
  439. return jlimit (-32768, 32767, roundToInt (32767.0f * r)) << 16
  440. | (0xffff & jlimit (-32768, 32767, roundToInt (32767.0f * l)));
  441. }
  442. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel)
  443. };
  444. //==============================================================================
  445. struct DSoundInternalInChannel
  446. {
  447. public:
  448. DSoundInternalInChannel (const String& name_, const GUID& guid_, int rate,
  449. int bufferSize, float* left, float* right)
  450. : name (name_), guid (guid_), sampleRate (rate),
  451. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right)
  452. {
  453. }
  454. ~DSoundInternalInChannel()
  455. {
  456. close();
  457. }
  458. void close()
  459. {
  460. if (pInputBuffer != nullptr)
  461. {
  462. JUCE_DS_LOG ("closing input: " + name);
  463. HRESULT hr = pInputBuffer->Stop();
  464. JUCE_DS_LOG_ERROR (hr); ignoreUnused (hr);
  465. pInputBuffer->Release();
  466. pInputBuffer = nullptr;
  467. }
  468. if (pDirectSoundCapture != nullptr)
  469. {
  470. pDirectSoundCapture->Release();
  471. pDirectSoundCapture = nullptr;
  472. }
  473. if (pDirectSound != nullptr)
  474. {
  475. pDirectSound->Release();
  476. pDirectSound = nullptr;
  477. }
  478. }
  479. String open()
  480. {
  481. JUCE_DS_LOG ("opening input: " + name
  482. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  483. pDirectSound = nullptr;
  484. pDirectSoundCapture = nullptr;
  485. pInputBuffer = nullptr;
  486. readOffset = 0;
  487. totalBytesPerBuffer = 0;
  488. HRESULT hr = dsDirectSoundCaptureCreate != nullptr
  489. ? dsDirectSoundCaptureCreate (&guid, &pDirectSoundCapture, nullptr)
  490. : E_NOINTERFACE;
  491. if (SUCCEEDED (hr))
  492. {
  493. const int numChannels = 2;
  494. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  495. totalBytesPerBuffer = (blocksPerOverallBuffer * bytesPerBuffer) & ~15;
  496. WAVEFORMATEX wfFormat;
  497. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  498. wfFormat.nChannels = (unsigned short)numChannels;
  499. wfFormat.nSamplesPerSec = (DWORD) sampleRate;
  500. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  501. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  502. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  503. wfFormat.cbSize = 0;
  504. DSCBUFFERDESC captureDesc = {};
  505. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  506. captureDesc.dwFlags = 0;
  507. captureDesc.dwBufferBytes = (DWORD) totalBytesPerBuffer;
  508. captureDesc.lpwfxFormat = &wfFormat;
  509. JUCE_DS_LOG ("object created");
  510. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  511. if (SUCCEEDED (hr))
  512. {
  513. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  514. if (SUCCEEDED (hr))
  515. return {};
  516. }
  517. }
  518. JUCE_DS_LOG_ERROR (hr);
  519. const String error (DSoundLogging::getErrorMessage (hr));
  520. close();
  521. return error;
  522. }
  523. void synchronisePosition()
  524. {
  525. if (pInputBuffer != nullptr)
  526. {
  527. DWORD capturePos;
  528. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*) &readOffset);
  529. }
  530. }
  531. bool service()
  532. {
  533. if (pInputBuffer == 0)
  534. return true;
  535. DWORD capturePos, readPos;
  536. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  537. JUCE_DS_LOG_ERROR (hr);
  538. if (FAILED (hr))
  539. return true;
  540. int bytesFilled = (int) (readPos - readOffset);
  541. if (bytesFilled < 0)
  542. bytesFilled += totalBytesPerBuffer;
  543. if (bytesFilled >= bytesPerBuffer)
  544. {
  545. short* buf1 = nullptr;
  546. short* buf2 = nullptr;
  547. DWORD dwsize1 = 0;
  548. DWORD dwsize2 = 0;
  549. hr = pInputBuffer->Lock ((DWORD) readOffset, (DWORD) bytesPerBuffer,
  550. (void**) &buf1, &dwsize1,
  551. (void**) &buf2, &dwsize2, 0);
  552. if (SUCCEEDED (hr))
  553. {
  554. if (bitDepth == 16)
  555. {
  556. const float g = 1.0f / 32768.0f;
  557. float* destL = leftBuffer;
  558. float* destR = rightBuffer;
  559. int samples1 = (int) (dwsize1 >> 2);
  560. int samples2 = (int) (dwsize2 >> 2);
  561. if (destL == nullptr)
  562. {
  563. for (const short* src = buf1; --samples1 >= 0;) { ++src; *destR++ = *src++ * g; }
  564. for (const short* src = buf2; --samples2 >= 0;) { ++src; *destR++ = *src++ * g; }
  565. }
  566. else if (destR == nullptr)
  567. {
  568. for (const short* src = buf1; --samples1 >= 0;) { *destL++ = *src++ * g; ++src; }
  569. for (const short* src = buf2; --samples2 >= 0;) { *destL++ = *src++ * g; ++src; }
  570. }
  571. else
  572. {
  573. for (const short* src = buf1; --samples1 >= 0;) { *destL++ = *src++ * g; *destR++ = *src++ * g; }
  574. for (const short* src = buf2; --samples2 >= 0;) { *destL++ = *src++ * g; *destR++ = *src++ * g; }
  575. }
  576. }
  577. else
  578. {
  579. jassertfalse;
  580. }
  581. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  582. pInputBuffer->Unlock (buf1, dwsize1, buf2, dwsize2);
  583. }
  584. else
  585. {
  586. JUCE_DS_LOG_ERROR (hr);
  587. jassertfalse;
  588. }
  589. bytesFilled -= bytesPerBuffer;
  590. return true;
  591. }
  592. else
  593. {
  594. return false;
  595. }
  596. }
  597. unsigned int readOffset;
  598. int bytesPerBuffer, totalBytesPerBuffer;
  599. int bitDepth = 16;
  600. bool doneFlag;
  601. private:
  602. String name;
  603. GUID guid;
  604. int sampleRate, bufferSizeSamples;
  605. float* leftBuffer;
  606. float* rightBuffer;
  607. IDirectSound* pDirectSound = nullptr;
  608. IDirectSoundCapture* pDirectSoundCapture = nullptr;
  609. IDirectSoundCaptureBuffer* pInputBuffer = nullptr;
  610. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel)
  611. };
  612. //==============================================================================
  613. class DSoundAudioIODevice : public AudioIODevice,
  614. public Thread
  615. {
  616. public:
  617. DSoundAudioIODevice (const String& deviceName,
  618. const int outputDeviceIndex_,
  619. const int inputDeviceIndex_)
  620. : AudioIODevice (deviceName, "DirectSound"),
  621. Thread ("JUCE DSound"),
  622. outputDeviceIndex (outputDeviceIndex_),
  623. inputDeviceIndex (inputDeviceIndex_)
  624. {
  625. if (outputDeviceIndex_ >= 0)
  626. {
  627. outChannels.add (TRANS("Left"));
  628. outChannels.add (TRANS("Right"));
  629. }
  630. if (inputDeviceIndex_ >= 0)
  631. {
  632. inChannels.add (TRANS("Left"));
  633. inChannels.add (TRANS("Right"));
  634. }
  635. }
  636. ~DSoundAudioIODevice()
  637. {
  638. close();
  639. }
  640. String open (const BigInteger& inputChannels,
  641. const BigInteger& outputChannels,
  642. double newSampleRate, int newBufferSize) override
  643. {
  644. lastError = openDevice (inputChannels, outputChannels, newSampleRate, newBufferSize);
  645. isOpen_ = lastError.isEmpty();
  646. return lastError;
  647. }
  648. void close() override
  649. {
  650. stop();
  651. if (isOpen_)
  652. {
  653. closeDevice();
  654. isOpen_ = false;
  655. }
  656. }
  657. bool isOpen() override { return isOpen_ && isThreadRunning(); }
  658. int getCurrentBufferSizeSamples() override { return bufferSizeSamples; }
  659. double getCurrentSampleRate() override { return sampleRate; }
  660. BigInteger getActiveOutputChannels() const override { return enabledOutputs; }
  661. BigInteger getActiveInputChannels() const override { return enabledInputs; }
  662. int getOutputLatencyInSamples() override { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  663. int getInputLatencyInSamples() override { return getOutputLatencyInSamples(); }
  664. StringArray getOutputChannelNames() override { return outChannels; }
  665. StringArray getInputChannelNames() override { return inChannels; }
  666. Array<double> getAvailableSampleRates() override
  667. {
  668. return { 44100.0, 48000.0, 88200.0, 96000.0 };
  669. }
  670. Array<int> getAvailableBufferSizes() override
  671. {
  672. Array<int> r;
  673. int n = 64;
  674. for (int i = 0; i < 50; ++i)
  675. {
  676. r.add (n);
  677. n += (n < 512) ? 32
  678. : ((n < 1024) ? 64
  679. : ((n < 2048) ? 128 : 256));
  680. }
  681. return r;
  682. }
  683. int getDefaultBufferSize() override { return 2560; }
  684. int getCurrentBitDepth() override
  685. {
  686. int bits = 256;
  687. for (int i = inChans.size(); --i >= 0;)
  688. bits = jmin (bits, inChans[i]->bitDepth);
  689. for (int i = outChans.size(); --i >= 0;)
  690. bits = jmin (bits, outChans[i]->bitDepth);
  691. if (bits > 32)
  692. bits = 16;
  693. return bits;
  694. }
  695. void start (AudioIODeviceCallback* call) override
  696. {
  697. if (isOpen_ && call != nullptr && ! isStarted)
  698. {
  699. if (! isThreadRunning())
  700. {
  701. // something gone wrong and the thread's stopped..
  702. isOpen_ = false;
  703. return;
  704. }
  705. call->audioDeviceAboutToStart (this);
  706. const ScopedLock sl (startStopLock);
  707. callback = call;
  708. isStarted = true;
  709. }
  710. }
  711. void stop() override
  712. {
  713. if (isStarted)
  714. {
  715. auto* callbackLocal = callback;
  716. {
  717. const ScopedLock sl (startStopLock);
  718. isStarted = false;
  719. }
  720. if (callbackLocal != nullptr)
  721. callbackLocal->audioDeviceStopped();
  722. }
  723. }
  724. bool isPlaying() override { return isStarted && isOpen_ && isThreadRunning(); }
  725. String getLastError() override { return lastError; }
  726. int getXRunCount() const noexcept override
  727. {
  728. return outChans[0] != nullptr ? outChans[0]->xruns : -1;
  729. }
  730. //==============================================================================
  731. StringArray inChannels, outChannels;
  732. int outputDeviceIndex, inputDeviceIndex;
  733. private:
  734. bool isOpen_ = false;
  735. bool isStarted = false;
  736. String lastError;
  737. OwnedArray<DSoundInternalInChannel> inChans;
  738. OwnedArray<DSoundInternalOutChannel> outChans;
  739. WaitableEvent startEvent;
  740. int bufferSizeSamples = 0;
  741. double sampleRate = 0;
  742. BigInteger enabledInputs, enabledOutputs;
  743. AudioBuffer<float> inputBuffers, outputBuffers;
  744. AudioIODeviceCallback* callback = nullptr;
  745. CriticalSection startStopLock;
  746. String openDevice (const BigInteger& inputChannels,
  747. const BigInteger& outputChannels,
  748. double sampleRate_, int bufferSizeSamples_);
  749. void closeDevice()
  750. {
  751. isStarted = false;
  752. stopThread (5000);
  753. inChans.clear();
  754. outChans.clear();
  755. }
  756. void resync()
  757. {
  758. if (! threadShouldExit())
  759. {
  760. sleep (5);
  761. for (int i = 0; i < outChans.size(); ++i)
  762. outChans.getUnchecked(i)->synchronisePosition();
  763. for (int i = 0; i < inChans.size(); ++i)
  764. inChans.getUnchecked(i)->synchronisePosition();
  765. }
  766. }
  767. public:
  768. void run() override
  769. {
  770. while (! threadShouldExit())
  771. {
  772. if (wait (100))
  773. break;
  774. }
  775. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  776. const int maxTimeMS = jmax (5, 3 * latencyMs);
  777. while (! threadShouldExit())
  778. {
  779. int numToDo = 0;
  780. uint32 startTime = Time::getMillisecondCounter();
  781. for (int i = inChans.size(); --i >= 0;)
  782. {
  783. inChans.getUnchecked(i)->doneFlag = false;
  784. ++numToDo;
  785. }
  786. for (int i = outChans.size(); --i >= 0;)
  787. {
  788. outChans.getUnchecked(i)->doneFlag = false;
  789. ++numToDo;
  790. }
  791. if (numToDo > 0)
  792. {
  793. const int maxCount = 3;
  794. int count = maxCount;
  795. for (;;)
  796. {
  797. for (int i = inChans.size(); --i >= 0;)
  798. {
  799. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  800. if ((! in->doneFlag) && in->service())
  801. {
  802. in->doneFlag = true;
  803. --numToDo;
  804. }
  805. }
  806. for (int i = outChans.size(); --i >= 0;)
  807. {
  808. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  809. if ((! out->doneFlag) && out->service())
  810. {
  811. out->doneFlag = true;
  812. --numToDo;
  813. }
  814. }
  815. if (numToDo <= 0)
  816. break;
  817. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  818. {
  819. resync();
  820. break;
  821. }
  822. if (--count <= 0)
  823. {
  824. Sleep (1);
  825. count = maxCount;
  826. }
  827. if (threadShouldExit())
  828. return;
  829. }
  830. }
  831. else
  832. {
  833. sleep (1);
  834. }
  835. const ScopedLock sl (startStopLock);
  836. if (isStarted)
  837. {
  838. callback->audioDeviceIOCallback (inputBuffers.getArrayOfReadPointers(), inputBuffers.getNumChannels(),
  839. outputBuffers.getArrayOfWritePointers(), outputBuffers.getNumChannels(),
  840. bufferSizeSamples);
  841. }
  842. else
  843. {
  844. outputBuffers.clear();
  845. sleep (1);
  846. }
  847. }
  848. }
  849. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice)
  850. };
  851. //==============================================================================
  852. struct DSoundDeviceList
  853. {
  854. StringArray outputDeviceNames, inputDeviceNames;
  855. Array<GUID> outputGuids, inputGuids;
  856. void scan()
  857. {
  858. outputDeviceNames.clear();
  859. inputDeviceNames.clear();
  860. outputGuids.clear();
  861. inputGuids.clear();
  862. if (dsDirectSoundEnumerateW != 0)
  863. {
  864. dsDirectSoundEnumerateW (outputEnumProcW, this);
  865. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  866. }
  867. }
  868. bool operator!= (const DSoundDeviceList& other) const noexcept
  869. {
  870. return outputDeviceNames != other.outputDeviceNames
  871. || inputDeviceNames != other.inputDeviceNames
  872. || outputGuids != other.outputGuids
  873. || inputGuids != other.inputGuids;
  874. }
  875. private:
  876. static BOOL enumProc (LPGUID lpGUID, String desc, StringArray& names, Array<GUID>& guids)
  877. {
  878. desc = desc.trim();
  879. if (desc.isNotEmpty())
  880. {
  881. const String origDesc (desc);
  882. int n = 2;
  883. while (names.contains (desc))
  884. desc = origDesc + " (" + String (n++) + ")";
  885. names.add (desc);
  886. guids.add (lpGUID != nullptr ? *lpGUID : GUID());
  887. }
  888. return TRUE;
  889. }
  890. BOOL outputEnumProc (LPGUID guid, LPCWSTR desc) { return enumProc (guid, desc, outputDeviceNames, outputGuids); }
  891. BOOL inputEnumProc (LPGUID guid, LPCWSTR desc) { return enumProc (guid, desc, inputDeviceNames, inputGuids); }
  892. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  893. {
  894. return static_cast<DSoundDeviceList*> (object)->outputEnumProc (lpGUID, description);
  895. }
  896. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  897. {
  898. return static_cast<DSoundDeviceList*> (object)->inputEnumProc (lpGUID, description);
  899. }
  900. };
  901. //==============================================================================
  902. String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  903. const BigInteger& outputChannels,
  904. double sampleRate_, int bufferSizeSamples_)
  905. {
  906. closeDevice();
  907. sampleRate = sampleRate_ > 0.0 ? sampleRate_ : 44100.0;
  908. if (bufferSizeSamples_ <= 0)
  909. bufferSizeSamples_ = 960; // use as a default size if none is set.
  910. bufferSizeSamples = bufferSizeSamples_ & ~7;
  911. DSoundDeviceList dlh;
  912. dlh.scan();
  913. enabledInputs = inputChannels;
  914. enabledInputs.setRange (inChannels.size(),
  915. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  916. false);
  917. inputBuffers.setSize (enabledInputs.countNumberOfSetBits(), bufferSizeSamples);
  918. inputBuffers.clear();
  919. int numIns = 0;
  920. for (int i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  921. {
  922. float* left = enabledInputs[i] ? inputBuffers.getWritePointer (numIns++) : nullptr;
  923. float* right = enabledInputs[i + 1] ? inputBuffers.getWritePointer (numIns++) : nullptr;
  924. if (left != nullptr || right != nullptr)
  925. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  926. dlh.inputGuids [inputDeviceIndex],
  927. (int) sampleRate, bufferSizeSamples,
  928. left, right));
  929. }
  930. enabledOutputs = outputChannels;
  931. enabledOutputs.setRange (outChannels.size(),
  932. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  933. false);
  934. outputBuffers.setSize (enabledOutputs.countNumberOfSetBits(), bufferSizeSamples);
  935. outputBuffers.clear();
  936. int numOuts = 0;
  937. for (int i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  938. {
  939. float* left = enabledOutputs[i] ? outputBuffers.getWritePointer (numOuts++) : nullptr;
  940. float* right = enabledOutputs[i + 1] ? outputBuffers.getWritePointer (numOuts++) : nullptr;
  941. if (left != nullptr || right != nullptr)
  942. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  943. dlh.outputGuids [outputDeviceIndex],
  944. (int) sampleRate, bufferSizeSamples,
  945. left, right));
  946. }
  947. String error;
  948. // boost our priority while opening the devices to try to get better sync between them
  949. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  950. const DWORD oldProcPri = GetPriorityClass (GetCurrentProcess());
  951. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  952. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  953. for (int i = 0; i < outChans.size(); ++i)
  954. {
  955. error = outChans[i]->open();
  956. if (error.isNotEmpty())
  957. {
  958. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  959. break;
  960. }
  961. }
  962. if (error.isEmpty())
  963. {
  964. for (int i = 0; i < inChans.size(); ++i)
  965. {
  966. error = inChans[i]->open();
  967. if (error.isNotEmpty())
  968. {
  969. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  970. break;
  971. }
  972. }
  973. }
  974. if (error.isEmpty())
  975. {
  976. for (int i = 0; i < outChans.size(); ++i)
  977. outChans.getUnchecked(i)->synchronisePosition();
  978. for (int i = 0; i < inChans.size(); ++i)
  979. inChans.getUnchecked(i)->synchronisePosition();
  980. startThread (9);
  981. sleep (10);
  982. notify();
  983. }
  984. else
  985. {
  986. JUCE_DS_LOG ("Opening failed: " + error);
  987. }
  988. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  989. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  990. return error;
  991. }
  992. //==============================================================================
  993. class DSoundAudioIODeviceType : public AudioIODeviceType,
  994. private DeviceChangeDetector
  995. {
  996. public:
  997. DSoundAudioIODeviceType()
  998. : AudioIODeviceType ("DirectSound"),
  999. DeviceChangeDetector (L"DirectSound")
  1000. {
  1001. initialiseDSoundFunctions();
  1002. }
  1003. void scanForDevices() override
  1004. {
  1005. hasScanned = true;
  1006. deviceList.scan();
  1007. }
  1008. StringArray getDeviceNames (bool wantInputNames) const override
  1009. {
  1010. jassert (hasScanned); // need to call scanForDevices() before doing this
  1011. return wantInputNames ? deviceList.inputDeviceNames
  1012. : deviceList.outputDeviceNames;
  1013. }
  1014. int getDefaultDeviceIndex (bool /*forInput*/) const override
  1015. {
  1016. jassert (hasScanned); // need to call scanForDevices() before doing this
  1017. return 0;
  1018. }
  1019. int getIndexOfDevice (AudioIODevice* device, bool asInput) const override
  1020. {
  1021. jassert (hasScanned); // need to call scanForDevices() before doing this
  1022. if (DSoundAudioIODevice* const d = dynamic_cast<DSoundAudioIODevice*> (device))
  1023. return asInput ? d->inputDeviceIndex
  1024. : d->outputDeviceIndex;
  1025. return -1;
  1026. }
  1027. bool hasSeparateInputsAndOutputs() const override { return true; }
  1028. AudioIODevice* createDevice (const String& outputDeviceName,
  1029. const String& inputDeviceName) override
  1030. {
  1031. jassert (hasScanned); // need to call scanForDevices() before doing this
  1032. const int outputIndex = deviceList.outputDeviceNames.indexOf (outputDeviceName);
  1033. const int inputIndex = deviceList.inputDeviceNames.indexOf (inputDeviceName);
  1034. if (outputIndex >= 0 || inputIndex >= 0)
  1035. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1036. : inputDeviceName,
  1037. outputIndex, inputIndex);
  1038. return nullptr;
  1039. }
  1040. private:
  1041. DSoundDeviceList deviceList;
  1042. bool hasScanned = false;
  1043. void systemDeviceChanged() override
  1044. {
  1045. DSoundDeviceList newList;
  1046. newList.scan();
  1047. if (newList != deviceList)
  1048. {
  1049. deviceList = newList;
  1050. callDeviceChangeListeners();
  1051. }
  1052. }
  1053. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType)
  1054. };
  1055. } // namespace juce