The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

1293 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 = { 0 };
  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 = { 0 };
  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. unsigned int lastPlayCursor;
  436. bool firstPlayTime;
  437. int64 lastPlayTime, ticksPerBuffer;
  438. static inline int convertInputValues (const float l, const float r) noexcept
  439. {
  440. return jlimit (-32768, 32767, roundToInt (32767.0f * r)) << 16
  441. | (0xffff & jlimit (-32768, 32767, roundToInt (32767.0f * l)));
  442. }
  443. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel)
  444. };
  445. //==============================================================================
  446. struct DSoundInternalInChannel
  447. {
  448. public:
  449. DSoundInternalInChannel (const String& name_, const GUID& guid_, int rate,
  450. int bufferSize, float* left, float* right)
  451. : name (name_), guid (guid_), sampleRate (rate),
  452. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right)
  453. {
  454. }
  455. ~DSoundInternalInChannel()
  456. {
  457. close();
  458. }
  459. void close()
  460. {
  461. if (pInputBuffer != nullptr)
  462. {
  463. JUCE_DS_LOG ("closing input: " + name);
  464. HRESULT hr = pInputBuffer->Stop();
  465. JUCE_DS_LOG_ERROR (hr); ignoreUnused (hr);
  466. pInputBuffer->Release();
  467. pInputBuffer = nullptr;
  468. }
  469. if (pDirectSoundCapture != nullptr)
  470. {
  471. pDirectSoundCapture->Release();
  472. pDirectSoundCapture = nullptr;
  473. }
  474. if (pDirectSound != nullptr)
  475. {
  476. pDirectSound->Release();
  477. pDirectSound = nullptr;
  478. }
  479. }
  480. String open()
  481. {
  482. JUCE_DS_LOG ("opening input: " + name
  483. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  484. pDirectSound = nullptr;
  485. pDirectSoundCapture = nullptr;
  486. pInputBuffer = nullptr;
  487. readOffset = 0;
  488. totalBytesPerBuffer = 0;
  489. HRESULT hr = dsDirectSoundCaptureCreate != nullptr
  490. ? dsDirectSoundCaptureCreate (&guid, &pDirectSoundCapture, nullptr)
  491. : E_NOINTERFACE;
  492. if (SUCCEEDED (hr))
  493. {
  494. const int numChannels = 2;
  495. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  496. totalBytesPerBuffer = (blocksPerOverallBuffer * bytesPerBuffer) & ~15;
  497. WAVEFORMATEX wfFormat;
  498. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  499. wfFormat.nChannels = (unsigned short)numChannels;
  500. wfFormat.nSamplesPerSec = (DWORD) sampleRate;
  501. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  502. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  503. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  504. wfFormat.cbSize = 0;
  505. DSCBUFFERDESC captureDesc = { 0 };
  506. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  507. captureDesc.dwFlags = 0;
  508. captureDesc.dwBufferBytes = (DWORD) totalBytesPerBuffer;
  509. captureDesc.lpwfxFormat = &wfFormat;
  510. JUCE_DS_LOG ("object created");
  511. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  512. if (SUCCEEDED (hr))
  513. {
  514. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  515. if (SUCCEEDED (hr))
  516. return {};
  517. }
  518. }
  519. JUCE_DS_LOG_ERROR (hr);
  520. const String error (DSoundLogging::getErrorMessage (hr));
  521. close();
  522. return error;
  523. }
  524. void synchronisePosition()
  525. {
  526. if (pInputBuffer != nullptr)
  527. {
  528. DWORD capturePos;
  529. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*) &readOffset);
  530. }
  531. }
  532. bool service()
  533. {
  534. if (pInputBuffer == 0)
  535. return true;
  536. DWORD capturePos, readPos;
  537. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  538. JUCE_DS_LOG_ERROR (hr);
  539. if (FAILED (hr))
  540. return true;
  541. int bytesFilled = (int) (readPos - readOffset);
  542. if (bytesFilled < 0)
  543. bytesFilled += totalBytesPerBuffer;
  544. if (bytesFilled >= bytesPerBuffer)
  545. {
  546. short* buf1 = nullptr;
  547. short* buf2 = nullptr;
  548. DWORD dwsize1 = 0;
  549. DWORD dwsize2 = 0;
  550. hr = pInputBuffer->Lock ((DWORD) readOffset, (DWORD) bytesPerBuffer,
  551. (void**) &buf1, &dwsize1,
  552. (void**) &buf2, &dwsize2, 0);
  553. if (SUCCEEDED (hr))
  554. {
  555. if (bitDepth == 16)
  556. {
  557. const float g = 1.0f / 32768.0f;
  558. float* destL = leftBuffer;
  559. float* destR = rightBuffer;
  560. int samples1 = (int) (dwsize1 >> 2);
  561. int samples2 = (int) (dwsize2 >> 2);
  562. if (destL == nullptr)
  563. {
  564. for (const short* src = buf1; --samples1 >= 0;) { ++src; *destR++ = *src++ * g; }
  565. for (const short* src = buf2; --samples2 >= 0;) { ++src; *destR++ = *src++ * g; }
  566. }
  567. else if (destR == nullptr)
  568. {
  569. for (const short* src = buf1; --samples1 >= 0;) { *destL++ = *src++ * g; ++src; }
  570. for (const short* src = buf2; --samples2 >= 0;) { *destL++ = *src++ * g; ++src; }
  571. }
  572. else
  573. {
  574. for (const short* src = buf1; --samples1 >= 0;) { *destL++ = *src++ * g; *destR++ = *src++ * g; }
  575. for (const short* src = buf2; --samples2 >= 0;) { *destL++ = *src++ * g; *destR++ = *src++ * g; }
  576. }
  577. }
  578. else
  579. {
  580. jassertfalse;
  581. }
  582. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  583. pInputBuffer->Unlock (buf1, dwsize1, buf2, dwsize2);
  584. }
  585. else
  586. {
  587. JUCE_DS_LOG_ERROR (hr);
  588. jassertfalse;
  589. }
  590. bytesFilled -= bytesPerBuffer;
  591. return true;
  592. }
  593. else
  594. {
  595. return false;
  596. }
  597. }
  598. unsigned int readOffset;
  599. int bytesPerBuffer, totalBytesPerBuffer;
  600. int bitDepth = 16;
  601. bool doneFlag;
  602. private:
  603. String name;
  604. GUID guid;
  605. int sampleRate, bufferSizeSamples;
  606. float* leftBuffer;
  607. float* rightBuffer;
  608. IDirectSound* pDirectSound = nullptr;
  609. IDirectSoundCapture* pDirectSoundCapture = nullptr;
  610. IDirectSoundCaptureBuffer* pInputBuffer = nullptr;
  611. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel)
  612. };
  613. //==============================================================================
  614. class DSoundAudioIODevice : public AudioIODevice,
  615. public Thread
  616. {
  617. public:
  618. DSoundAudioIODevice (const String& deviceName,
  619. const int outputDeviceIndex_,
  620. const int inputDeviceIndex_)
  621. : AudioIODevice (deviceName, "DirectSound"),
  622. Thread ("JUCE DSound"),
  623. outputDeviceIndex (outputDeviceIndex_),
  624. inputDeviceIndex (inputDeviceIndex_)
  625. {
  626. if (outputDeviceIndex_ >= 0)
  627. {
  628. outChannels.add (TRANS("Left"));
  629. outChannels.add (TRANS("Right"));
  630. }
  631. if (inputDeviceIndex_ >= 0)
  632. {
  633. inChannels.add (TRANS("Left"));
  634. inChannels.add (TRANS("Right"));
  635. }
  636. }
  637. ~DSoundAudioIODevice()
  638. {
  639. close();
  640. }
  641. String open (const BigInteger& inputChannels,
  642. const BigInteger& outputChannels,
  643. double newSampleRate, int newBufferSize) override
  644. {
  645. lastError = openDevice (inputChannels, outputChannels, newSampleRate, newBufferSize);
  646. isOpen_ = lastError.isEmpty();
  647. return lastError;
  648. }
  649. void close() override
  650. {
  651. stop();
  652. if (isOpen_)
  653. {
  654. closeDevice();
  655. isOpen_ = false;
  656. }
  657. }
  658. bool isOpen() override { return isOpen_ && isThreadRunning(); }
  659. int getCurrentBufferSizeSamples() override { return bufferSizeSamples; }
  660. double getCurrentSampleRate() override { return sampleRate; }
  661. BigInteger getActiveOutputChannels() const override { return enabledOutputs; }
  662. BigInteger getActiveInputChannels() const override { return enabledInputs; }
  663. int getOutputLatencyInSamples() override { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  664. int getInputLatencyInSamples() override { return getOutputLatencyInSamples(); }
  665. StringArray getOutputChannelNames() override { return outChannels; }
  666. StringArray getInputChannelNames() override { return inChannels; }
  667. Array<double> getAvailableSampleRates() override
  668. {
  669. return { 44100.0, 48000.0, 88200.0, 96000.0 };
  670. }
  671. Array<int> getAvailableBufferSizes() override
  672. {
  673. Array<int> r;
  674. int n = 64;
  675. for (int i = 0; i < 50; ++i)
  676. {
  677. r.add (n);
  678. n += (n < 512) ? 32
  679. : ((n < 1024) ? 64
  680. : ((n < 2048) ? 128 : 256));
  681. }
  682. return r;
  683. }
  684. int getDefaultBufferSize() override { return 2560; }
  685. int getCurrentBitDepth() override
  686. {
  687. int bits = 256;
  688. for (int i = inChans.size(); --i >= 0;)
  689. bits = jmin (bits, inChans[i]->bitDepth);
  690. for (int i = outChans.size(); --i >= 0;)
  691. bits = jmin (bits, outChans[i]->bitDepth);
  692. if (bits > 32)
  693. bits = 16;
  694. return bits;
  695. }
  696. void start (AudioIODeviceCallback* call) override
  697. {
  698. if (isOpen_ && call != nullptr && ! isStarted)
  699. {
  700. if (! isThreadRunning())
  701. {
  702. // something gone wrong and the thread's stopped..
  703. isOpen_ = false;
  704. return;
  705. }
  706. call->audioDeviceAboutToStart (this);
  707. const ScopedLock sl (startStopLock);
  708. callback = call;
  709. isStarted = true;
  710. }
  711. }
  712. void stop() override
  713. {
  714. if (isStarted)
  715. {
  716. auto* callbackLocal = callback;
  717. {
  718. const ScopedLock sl (startStopLock);
  719. isStarted = false;
  720. }
  721. if (callbackLocal != nullptr)
  722. callbackLocal->audioDeviceStopped();
  723. }
  724. }
  725. bool isPlaying() override { return isStarted && isOpen_ && isThreadRunning(); }
  726. String getLastError() override { return lastError; }
  727. int getXRunCount() const noexcept override
  728. {
  729. return outChans[0] != nullptr ? outChans[0]->xruns : -1;
  730. }
  731. //==============================================================================
  732. StringArray inChannels, outChannels;
  733. int outputDeviceIndex, inputDeviceIndex;
  734. private:
  735. bool isOpen_ = false;
  736. bool isStarted = false;
  737. String lastError;
  738. OwnedArray<DSoundInternalInChannel> inChans;
  739. OwnedArray<DSoundInternalOutChannel> outChans;
  740. WaitableEvent startEvent;
  741. int bufferSizeSamples = 0;
  742. double sampleRate = 0;
  743. BigInteger enabledInputs, enabledOutputs;
  744. AudioBuffer<float> inputBuffers, outputBuffers;
  745. AudioIODeviceCallback* callback = nullptr;
  746. CriticalSection startStopLock;
  747. String openDevice (const BigInteger& inputChannels,
  748. const BigInteger& outputChannels,
  749. double sampleRate_, int bufferSizeSamples_);
  750. void closeDevice()
  751. {
  752. isStarted = false;
  753. stopThread (5000);
  754. inChans.clear();
  755. outChans.clear();
  756. }
  757. void resync()
  758. {
  759. if (! threadShouldExit())
  760. {
  761. sleep (5);
  762. for (int i = 0; i < outChans.size(); ++i)
  763. outChans.getUnchecked(i)->synchronisePosition();
  764. for (int i = 0; i < inChans.size(); ++i)
  765. inChans.getUnchecked(i)->synchronisePosition();
  766. }
  767. }
  768. public:
  769. void run() override
  770. {
  771. while (! threadShouldExit())
  772. {
  773. if (wait (100))
  774. break;
  775. }
  776. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  777. const int maxTimeMS = jmax (5, 3 * latencyMs);
  778. while (! threadShouldExit())
  779. {
  780. int numToDo = 0;
  781. uint32 startTime = Time::getMillisecondCounter();
  782. for (int i = inChans.size(); --i >= 0;)
  783. {
  784. inChans.getUnchecked(i)->doneFlag = false;
  785. ++numToDo;
  786. }
  787. for (int i = outChans.size(); --i >= 0;)
  788. {
  789. outChans.getUnchecked(i)->doneFlag = false;
  790. ++numToDo;
  791. }
  792. if (numToDo > 0)
  793. {
  794. const int maxCount = 3;
  795. int count = maxCount;
  796. for (;;)
  797. {
  798. for (int i = inChans.size(); --i >= 0;)
  799. {
  800. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  801. if ((! in->doneFlag) && in->service())
  802. {
  803. in->doneFlag = true;
  804. --numToDo;
  805. }
  806. }
  807. for (int i = outChans.size(); --i >= 0;)
  808. {
  809. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  810. if ((! out->doneFlag) && out->service())
  811. {
  812. out->doneFlag = true;
  813. --numToDo;
  814. }
  815. }
  816. if (numToDo <= 0)
  817. break;
  818. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  819. {
  820. resync();
  821. break;
  822. }
  823. if (--count <= 0)
  824. {
  825. Sleep (1);
  826. count = maxCount;
  827. }
  828. if (threadShouldExit())
  829. return;
  830. }
  831. }
  832. else
  833. {
  834. sleep (1);
  835. }
  836. const ScopedLock sl (startStopLock);
  837. if (isStarted)
  838. {
  839. callback->audioDeviceIOCallback (inputBuffers.getArrayOfReadPointers(), inputBuffers.getNumChannels(),
  840. outputBuffers.getArrayOfWritePointers(), outputBuffers.getNumChannels(),
  841. bufferSizeSamples);
  842. }
  843. else
  844. {
  845. outputBuffers.clear();
  846. sleep (1);
  847. }
  848. }
  849. }
  850. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice)
  851. };
  852. //==============================================================================
  853. struct DSoundDeviceList
  854. {
  855. StringArray outputDeviceNames, inputDeviceNames;
  856. Array<GUID> outputGuids, inputGuids;
  857. void scan()
  858. {
  859. outputDeviceNames.clear();
  860. inputDeviceNames.clear();
  861. outputGuids.clear();
  862. inputGuids.clear();
  863. if (dsDirectSoundEnumerateW != 0)
  864. {
  865. dsDirectSoundEnumerateW (outputEnumProcW, this);
  866. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  867. }
  868. }
  869. bool operator!= (const DSoundDeviceList& other) const noexcept
  870. {
  871. return outputDeviceNames != other.outputDeviceNames
  872. || inputDeviceNames != other.inputDeviceNames
  873. || outputGuids != other.outputGuids
  874. || inputGuids != other.inputGuids;
  875. }
  876. private:
  877. static BOOL enumProc (LPGUID lpGUID, String desc, StringArray& names, Array<GUID>& guids)
  878. {
  879. desc = desc.trim();
  880. if (desc.isNotEmpty())
  881. {
  882. const String origDesc (desc);
  883. int n = 2;
  884. while (names.contains (desc))
  885. desc = origDesc + " (" + String (n++) + ")";
  886. names.add (desc);
  887. guids.add (lpGUID != nullptr ? *lpGUID : GUID());
  888. }
  889. return TRUE;
  890. }
  891. BOOL outputEnumProc (LPGUID guid, LPCWSTR desc) { return enumProc (guid, desc, outputDeviceNames, outputGuids); }
  892. BOOL inputEnumProc (LPGUID guid, LPCWSTR desc) { return enumProc (guid, desc, inputDeviceNames, inputGuids); }
  893. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  894. {
  895. return static_cast<DSoundDeviceList*> (object)->outputEnumProc (lpGUID, description);
  896. }
  897. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  898. {
  899. return static_cast<DSoundDeviceList*> (object)->inputEnumProc (lpGUID, description);
  900. }
  901. };
  902. //==============================================================================
  903. String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  904. const BigInteger& outputChannels,
  905. double sampleRate_, int bufferSizeSamples_)
  906. {
  907. closeDevice();
  908. sampleRate = sampleRate_;
  909. if (bufferSizeSamples_ <= 0)
  910. bufferSizeSamples_ = 960; // use as a default size if none is set.
  911. bufferSizeSamples = bufferSizeSamples_ & ~7;
  912. DSoundDeviceList dlh;
  913. dlh.scan();
  914. enabledInputs = inputChannels;
  915. enabledInputs.setRange (inChannels.size(),
  916. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  917. false);
  918. inputBuffers.setSize (enabledInputs.countNumberOfSetBits(), bufferSizeSamples);
  919. inputBuffers.clear();
  920. int numIns = 0;
  921. for (int i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  922. {
  923. float* left = enabledInputs[i] ? inputBuffers.getWritePointer (numIns++) : nullptr;
  924. float* right = enabledInputs[i + 1] ? inputBuffers.getWritePointer (numIns++) : nullptr;
  925. if (left != nullptr || right != nullptr)
  926. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  927. dlh.inputGuids [inputDeviceIndex],
  928. (int) sampleRate, bufferSizeSamples,
  929. left, right));
  930. }
  931. enabledOutputs = outputChannels;
  932. enabledOutputs.setRange (outChannels.size(),
  933. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  934. false);
  935. outputBuffers.setSize (enabledOutputs.countNumberOfSetBits(), bufferSizeSamples);
  936. outputBuffers.clear();
  937. int numOuts = 0;
  938. for (int i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  939. {
  940. float* left = enabledOutputs[i] ? outputBuffers.getWritePointer (numOuts++) : nullptr;
  941. float* right = enabledOutputs[i + 1] ? outputBuffers.getWritePointer (numOuts++) : nullptr;
  942. if (left != nullptr || right != nullptr)
  943. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  944. dlh.outputGuids [outputDeviceIndex],
  945. (int) sampleRate, bufferSizeSamples,
  946. left, right));
  947. }
  948. String error;
  949. // boost our priority while opening the devices to try to get better sync between them
  950. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  951. const DWORD oldProcPri = GetPriorityClass (GetCurrentProcess());
  952. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  953. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  954. for (int i = 0; i < outChans.size(); ++i)
  955. {
  956. error = outChans[i]->open();
  957. if (error.isNotEmpty())
  958. {
  959. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  960. break;
  961. }
  962. }
  963. if (error.isEmpty())
  964. {
  965. for (int i = 0; i < inChans.size(); ++i)
  966. {
  967. error = inChans[i]->open();
  968. if (error.isNotEmpty())
  969. {
  970. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  971. break;
  972. }
  973. }
  974. }
  975. if (error.isEmpty())
  976. {
  977. for (int i = 0; i < outChans.size(); ++i)
  978. outChans.getUnchecked(i)->synchronisePosition();
  979. for (int i = 0; i < inChans.size(); ++i)
  980. inChans.getUnchecked(i)->synchronisePosition();
  981. startThread (9);
  982. sleep (10);
  983. notify();
  984. }
  985. else
  986. {
  987. JUCE_DS_LOG ("Opening failed: " + error);
  988. }
  989. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  990. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  991. return error;
  992. }
  993. //==============================================================================
  994. class DSoundAudioIODeviceType : public AudioIODeviceType,
  995. private DeviceChangeDetector
  996. {
  997. public:
  998. DSoundAudioIODeviceType()
  999. : AudioIODeviceType ("DirectSound"),
  1000. DeviceChangeDetector (L"DirectSound")
  1001. {
  1002. initialiseDSoundFunctions();
  1003. }
  1004. void scanForDevices()
  1005. {
  1006. hasScanned = true;
  1007. deviceList.scan();
  1008. }
  1009. StringArray getDeviceNames (bool wantInputNames) const
  1010. {
  1011. jassert (hasScanned); // need to call scanForDevices() before doing this
  1012. return wantInputNames ? deviceList.inputDeviceNames
  1013. : deviceList.outputDeviceNames;
  1014. }
  1015. int getDefaultDeviceIndex (bool /*forInput*/) const
  1016. {
  1017. jassert (hasScanned); // need to call scanForDevices() before doing this
  1018. return 0;
  1019. }
  1020. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  1021. {
  1022. jassert (hasScanned); // need to call scanForDevices() before doing this
  1023. if (DSoundAudioIODevice* const d = dynamic_cast<DSoundAudioIODevice*> (device))
  1024. return asInput ? d->inputDeviceIndex
  1025. : d->outputDeviceIndex;
  1026. return -1;
  1027. }
  1028. bool hasSeparateInputsAndOutputs() const { return true; }
  1029. AudioIODevice* createDevice (const String& outputDeviceName,
  1030. const String& inputDeviceName)
  1031. {
  1032. jassert (hasScanned); // need to call scanForDevices() before doing this
  1033. const int outputIndex = deviceList.outputDeviceNames.indexOf (outputDeviceName);
  1034. const int inputIndex = deviceList.inputDeviceNames.indexOf (inputDeviceName);
  1035. if (outputIndex >= 0 || inputIndex >= 0)
  1036. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1037. : inputDeviceName,
  1038. outputIndex, inputIndex);
  1039. return nullptr;
  1040. }
  1041. private:
  1042. DSoundDeviceList deviceList;
  1043. bool hasScanned = false;
  1044. void systemDeviceChanged() override
  1045. {
  1046. DSoundDeviceList newList;
  1047. newList.scan();
  1048. if (newList != deviceList)
  1049. {
  1050. deviceList = newList;
  1051. callDeviceChangeListeners();
  1052. }
  1053. }
  1054. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType)
  1055. };
  1056. //==============================================================================
  1057. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound()
  1058. {
  1059. return new DSoundAudioIODeviceType();
  1060. }
  1061. } // namespace juce