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.

1296 lines
44KB

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