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.

juce_win32_DirectSound.cpp 44KB

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