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.

1972 lines
70KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #ifndef JUCE_WASAPI_LOGGING
  20. #define JUCE_WASAPI_LOGGING 0
  21. #endif
  22. //==============================================================================
  23. namespace WasapiClasses
  24. {
  25. void logFailure (HRESULT hr)
  26. {
  27. ignoreUnused (hr);
  28. jassert (hr != (HRESULT) 0x800401f0); // If you hit this, it means you're trying to call from
  29. // a thread which hasn't been initialised with CoInitialize().
  30. #if JUCE_WASAPI_LOGGING
  31. if (FAILED (hr))
  32. {
  33. const char* m = nullptr;
  34. switch (hr)
  35. {
  36. case E_POINTER: m = "E_POINTER"; break;
  37. case E_INVALIDARG: m = "E_INVALIDARG"; break;
  38. case E_NOINTERFACE: m = "E_NOINTERFACE"; break;
  39. #define JUCE_WASAPI_ERR(desc, n) \
  40. case MAKE_HRESULT(1, 0x889, n): m = #desc; break;
  41. JUCE_WASAPI_ERR (AUDCLNT_E_NOT_INITIALIZED, 0x001)
  42. JUCE_WASAPI_ERR (AUDCLNT_E_ALREADY_INITIALIZED, 0x002)
  43. JUCE_WASAPI_ERR (AUDCLNT_E_WRONG_ENDPOINT_TYPE, 0x003)
  44. JUCE_WASAPI_ERR (AUDCLNT_E_DEVICE_INVALIDATED, 0x004)
  45. JUCE_WASAPI_ERR (AUDCLNT_E_NOT_STOPPED, 0x005)
  46. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_TOO_LARGE, 0x006)
  47. JUCE_WASAPI_ERR (AUDCLNT_E_OUT_OF_ORDER, 0x007)
  48. JUCE_WASAPI_ERR (AUDCLNT_E_UNSUPPORTED_FORMAT, 0x008)
  49. JUCE_WASAPI_ERR (AUDCLNT_E_INVALID_SIZE, 0x009)
  50. JUCE_WASAPI_ERR (AUDCLNT_E_DEVICE_IN_USE, 0x00a)
  51. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_OPERATION_PENDING, 0x00b)
  52. JUCE_WASAPI_ERR (AUDCLNT_E_THREAD_NOT_REGISTERED, 0x00c)
  53. JUCE_WASAPI_ERR (AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED, 0x00e)
  54. JUCE_WASAPI_ERR (AUDCLNT_E_ENDPOINT_CREATE_FAILED, 0x00f)
  55. JUCE_WASAPI_ERR (AUDCLNT_E_SERVICE_NOT_RUNNING, 0x010)
  56. JUCE_WASAPI_ERR (AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED, 0x011)
  57. JUCE_WASAPI_ERR (AUDCLNT_E_EXCLUSIVE_MODE_ONLY, 0x012)
  58. JUCE_WASAPI_ERR (AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL, 0x013)
  59. JUCE_WASAPI_ERR (AUDCLNT_E_EVENTHANDLE_NOT_SET, 0x014)
  60. JUCE_WASAPI_ERR (AUDCLNT_E_INCORRECT_BUFFER_SIZE, 0x015)
  61. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_SIZE_ERROR, 0x016)
  62. JUCE_WASAPI_ERR (AUDCLNT_E_CPUUSAGE_EXCEEDED, 0x017)
  63. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_ERROR, 0x018)
  64. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED, 0x019)
  65. JUCE_WASAPI_ERR (AUDCLNT_E_INVALID_DEVICE_PERIOD, 0x020)
  66. default: break;
  67. }
  68. Logger::writeToLog ("WASAPI error: " + (m != nullptr ? String (m)
  69. : String::toHexString ((int) hr)));
  70. }
  71. #endif
  72. }
  73. #undef check
  74. bool check (HRESULT hr)
  75. {
  76. logFailure (hr);
  77. return SUCCEEDED (hr);
  78. }
  79. //==============================================================================
  80. }
  81. #if JUCE_MINGW
  82. struct PROPERTYKEY
  83. {
  84. GUID fmtid;
  85. DWORD pid;
  86. };
  87. WINOLEAPI PropVariantClear (PROPVARIANT*);
  88. #endif
  89. #if JUCE_MINGW && defined (KSDATAFORMAT_SUBTYPE_PCM)
  90. #undef KSDATAFORMAT_SUBTYPE_PCM
  91. #undef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
  92. #endif
  93. #ifndef KSDATAFORMAT_SUBTYPE_PCM
  94. #define KSDATAFORMAT_SUBTYPE_PCM uuidFromString ("00000001-0000-0010-8000-00aa00389b71")
  95. #define KSDATAFORMAT_SUBTYPE_IEEE_FLOAT uuidFromString ("00000003-0000-0010-8000-00aa00389b71")
  96. #endif
  97. enum EDataFlow
  98. {
  99. eRender = 0,
  100. eCapture = (eRender + 1),
  101. eAll = (eCapture + 1)
  102. };
  103. enum
  104. {
  105. DEVICE_STATE_ACTIVE = 1
  106. };
  107. enum
  108. {
  109. AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY = 1,
  110. AUDCLNT_BUFFERFLAGS_SILENT = 2
  111. };
  112. JUCE_IUNKNOWNCLASS (IPropertyStore, "886d8eeb-8cf2-4446-8d02-cdba1dbdcf99")
  113. {
  114. JUCE_COMCALL GetCount (DWORD*) = 0;
  115. JUCE_COMCALL GetAt (DWORD, PROPERTYKEY*) = 0;
  116. JUCE_COMCALL GetValue (const PROPERTYKEY&, PROPVARIANT*) = 0;
  117. JUCE_COMCALL SetValue (const PROPERTYKEY&, const PROPVARIANT&) = 0;
  118. JUCE_COMCALL Commit() = 0;
  119. };
  120. JUCE_IUNKNOWNCLASS (IMMDevice, "D666063F-1587-4E43-81F1-B948E807363F")
  121. {
  122. JUCE_COMCALL Activate (REFIID, DWORD, PROPVARIANT*, void**) = 0;
  123. JUCE_COMCALL OpenPropertyStore (DWORD, IPropertyStore**) = 0;
  124. JUCE_COMCALL GetId (LPWSTR*) = 0;
  125. JUCE_COMCALL GetState (DWORD*) = 0;
  126. };
  127. JUCE_IUNKNOWNCLASS (IMMEndpoint, "1BE09788-6894-4089-8586-9A2A6C265AC5")
  128. {
  129. JUCE_COMCALL GetDataFlow (EDataFlow*) = 0;
  130. };
  131. struct IMMDeviceCollection : public IUnknown
  132. {
  133. JUCE_COMCALL GetCount (UINT*) = 0;
  134. JUCE_COMCALL Item (UINT, IMMDevice**) = 0;
  135. };
  136. enum ERole
  137. {
  138. eConsole = 0,
  139. eMultimedia = (eConsole + 1),
  140. eCommunications = (eMultimedia + 1)
  141. };
  142. JUCE_IUNKNOWNCLASS (IMMNotificationClient, "7991EEC9-7E89-4D85-8390-6C703CEC60C0")
  143. {
  144. JUCE_COMCALL OnDeviceStateChanged (LPCWSTR, DWORD) = 0;
  145. JUCE_COMCALL OnDeviceAdded (LPCWSTR) = 0;
  146. JUCE_COMCALL OnDeviceRemoved (LPCWSTR) = 0;
  147. JUCE_COMCALL OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) = 0;
  148. JUCE_COMCALL OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) = 0;
  149. };
  150. JUCE_IUNKNOWNCLASS (IMMDeviceEnumerator, "A95664D2-9614-4F35-A746-DE8DB63617E6")
  151. {
  152. JUCE_COMCALL EnumAudioEndpoints (EDataFlow, DWORD, IMMDeviceCollection**) = 0;
  153. JUCE_COMCALL GetDefaultAudioEndpoint (EDataFlow, ERole, IMMDevice**) = 0;
  154. JUCE_COMCALL GetDevice (LPCWSTR, IMMDevice**) = 0;
  155. JUCE_COMCALL RegisterEndpointNotificationCallback (IMMNotificationClient*) = 0;
  156. JUCE_COMCALL UnregisterEndpointNotificationCallback (IMMNotificationClient*) = 0;
  157. };
  158. JUCE_COMCLASS (MMDeviceEnumerator, "BCDE0395-E52F-467C-8E3D-C4579291692E");
  159. using REFERENCE_TIME = LONGLONG;
  160. enum AVRT_PRIORITY
  161. {
  162. AVRT_PRIORITY_LOW = -1,
  163. AVRT_PRIORITY_NORMAL,
  164. AVRT_PRIORITY_HIGH,
  165. AVRT_PRIORITY_CRITICAL
  166. };
  167. enum AUDCLNT_SHAREMODE
  168. {
  169. AUDCLNT_SHAREMODE_SHARED,
  170. AUDCLNT_SHAREMODE_EXCLUSIVE
  171. };
  172. enum AUDIO_STREAM_CATEGORY
  173. {
  174. AudioCategory_Other = 0,
  175. AudioCategory_ForegroundOnlyMedia,
  176. AudioCategory_BackgroundCapableMedia,
  177. AudioCategory_Communications,
  178. AudioCategory_Alerts,
  179. AudioCategory_SoundEffects,
  180. AudioCategory_GameEffects,
  181. AudioCategory_GameMedia,
  182. AudioCategory_GameChat,
  183. AudioCategory_Speech,
  184. AudioCategory_Movie,
  185. AudioCategory_Media
  186. };
  187. struct AudioClientProperties
  188. {
  189. UINT32 cbSize;
  190. BOOL bIsOffload;
  191. AUDIO_STREAM_CATEGORY eCategory;
  192. };
  193. JUCE_IUNKNOWNCLASS (IAudioClient, "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")
  194. {
  195. JUCE_COMCALL Initialize (AUDCLNT_SHAREMODE, DWORD, REFERENCE_TIME, REFERENCE_TIME, const WAVEFORMATEX*, LPCGUID) = 0;
  196. JUCE_COMCALL GetBufferSize (UINT32*) = 0;
  197. JUCE_COMCALL GetStreamLatency (REFERENCE_TIME*) = 0;
  198. JUCE_COMCALL GetCurrentPadding (UINT32*) = 0;
  199. JUCE_COMCALL IsFormatSupported (AUDCLNT_SHAREMODE, const WAVEFORMATEX*, WAVEFORMATEX**) = 0;
  200. JUCE_COMCALL GetMixFormat (WAVEFORMATEX**) = 0;
  201. JUCE_COMCALL GetDevicePeriod (REFERENCE_TIME*, REFERENCE_TIME*) = 0;
  202. JUCE_COMCALL Start() = 0;
  203. JUCE_COMCALL Stop() = 0;
  204. JUCE_COMCALL Reset() = 0;
  205. JUCE_COMCALL SetEventHandle (HANDLE) = 0;
  206. JUCE_COMCALL GetService (REFIID, void**) = 0;
  207. };
  208. JUCE_COMCLASS (IAudioClient2, "726778CD-F60A-4eda-82DE-E47610CD78AA") : public IAudioClient
  209. {
  210. JUCE_COMCALL IsOffloadCapable (AUDIO_STREAM_CATEGORY, BOOL*) = 0;
  211. JUCE_COMCALL SetClientProperties (const AudioClientProperties*) = 0;
  212. JUCE_COMCALL GetBufferSizeLimits (const WAVEFORMATEX*, BOOL, REFERENCE_TIME*, REFERENCE_TIME*) = 0;
  213. };
  214. JUCE_COMCLASS (IAudioClient3, "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2") : public IAudioClient2
  215. {
  216. JUCE_COMCALL GetSharedModeEnginePeriod (const WAVEFORMATEX*, UINT32*, UINT32*, UINT32*, UINT32*) = 0;
  217. JUCE_COMCALL GetCurrentSharedModeEnginePeriod (WAVEFORMATEX**, UINT32*) = 0;
  218. JUCE_COMCALL InitializeSharedAudioStream (DWORD, UINT32, const WAVEFORMATEX*, LPCGUID) = 0;
  219. };
  220. JUCE_IUNKNOWNCLASS (IAudioCaptureClient, "C8ADBD64-E71E-48a0-A4DE-185C395CD317")
  221. {
  222. JUCE_COMCALL GetBuffer (BYTE**, UINT32*, DWORD*, UINT64*, UINT64*) = 0;
  223. JUCE_COMCALL ReleaseBuffer (UINT32) = 0;
  224. JUCE_COMCALL GetNextPacketSize (UINT32*) = 0;
  225. };
  226. JUCE_IUNKNOWNCLASS (IAudioRenderClient, "F294ACFC-3146-4483-A7BF-ADDCA7C260E2")
  227. {
  228. JUCE_COMCALL GetBuffer (UINT32, BYTE**) = 0;
  229. JUCE_COMCALL ReleaseBuffer (UINT32, DWORD) = 0;
  230. };
  231. JUCE_IUNKNOWNCLASS (IAudioEndpointVolume, "5CDF2C82-841E-4546-9722-0CF74078229A")
  232. {
  233. JUCE_COMCALL RegisterControlChangeNotify (void*) = 0;
  234. JUCE_COMCALL UnregisterControlChangeNotify (void*) = 0;
  235. JUCE_COMCALL GetChannelCount (UINT*) = 0;
  236. JUCE_COMCALL SetMasterVolumeLevel (float, LPCGUID) = 0;
  237. JUCE_COMCALL SetMasterVolumeLevelScalar (float, LPCGUID) = 0;
  238. JUCE_COMCALL GetMasterVolumeLevel (float*) = 0;
  239. JUCE_COMCALL GetMasterVolumeLevelScalar (float*) = 0;
  240. JUCE_COMCALL SetChannelVolumeLevel (UINT, float, LPCGUID) = 0;
  241. JUCE_COMCALL SetChannelVolumeLevelScalar (UINT, float, LPCGUID) = 0;
  242. JUCE_COMCALL GetChannelVolumeLevel (UINT, float*) = 0;
  243. JUCE_COMCALL GetChannelVolumeLevelScalar (UINT, float*) = 0;
  244. JUCE_COMCALL SetMute (BOOL, LPCGUID) = 0;
  245. JUCE_COMCALL GetMute (BOOL*) = 0;
  246. JUCE_COMCALL GetVolumeStepInfo (UINT*, UINT*) = 0;
  247. JUCE_COMCALL VolumeStepUp (LPCGUID) = 0;
  248. JUCE_COMCALL VolumeStepDown (LPCGUID) = 0;
  249. JUCE_COMCALL QueryHardwareSupport (DWORD*) = 0;
  250. JUCE_COMCALL GetVolumeRange (float*, float*, float*) = 0;
  251. };
  252. enum AudioSessionDisconnectReason
  253. {
  254. DisconnectReasonDeviceRemoval = 0,
  255. DisconnectReasonServerShutdown = 1,
  256. DisconnectReasonFormatChanged = 2,
  257. DisconnectReasonSessionLogoff = 3,
  258. DisconnectReasonSessionDisconnected = 4,
  259. DisconnectReasonExclusiveModeOverride = 5
  260. };
  261. enum AudioSessionState
  262. {
  263. AudioSessionStateInactive = 0,
  264. AudioSessionStateActive = 1,
  265. AudioSessionStateExpired = 2
  266. };
  267. JUCE_IUNKNOWNCLASS (IAudioSessionEvents, "24918ACC-64B3-37C1-8CA9-74A66E9957A8")
  268. {
  269. JUCE_COMCALL OnDisplayNameChanged (LPCWSTR, LPCGUID) = 0;
  270. JUCE_COMCALL OnIconPathChanged (LPCWSTR, LPCGUID) = 0;
  271. JUCE_COMCALL OnSimpleVolumeChanged (float, BOOL, LPCGUID) = 0;
  272. JUCE_COMCALL OnChannelVolumeChanged (DWORD, float*, DWORD, LPCGUID) = 0;
  273. JUCE_COMCALL OnGroupingParamChanged (LPCGUID, LPCGUID) = 0;
  274. JUCE_COMCALL OnStateChanged (AudioSessionState) = 0;
  275. JUCE_COMCALL OnSessionDisconnected (AudioSessionDisconnectReason) = 0;
  276. };
  277. JUCE_IUNKNOWNCLASS (IAudioSessionControl, "F4B1A599-7266-4319-A8CA-E70ACB11E8CD")
  278. {
  279. JUCE_COMCALL GetState (AudioSessionState*) = 0;
  280. JUCE_COMCALL GetDisplayName (LPWSTR*) = 0;
  281. JUCE_COMCALL SetDisplayName (LPCWSTR, LPCGUID) = 0;
  282. JUCE_COMCALL GetIconPath (LPWSTR*) = 0;
  283. JUCE_COMCALL SetIconPath (LPCWSTR, LPCGUID) = 0;
  284. JUCE_COMCALL GetGroupingParam (GUID*) = 0;
  285. JUCE_COMCALL SetGroupingParam (LPCGUID, LPCGUID) = 0;
  286. JUCE_COMCALL RegisterAudioSessionNotification (IAudioSessionEvents*) = 0;
  287. JUCE_COMCALL UnregisterAudioSessionNotification (IAudioSessionEvents*) = 0;
  288. };
  289. //==============================================================================
  290. namespace WasapiClasses
  291. {
  292. String getDeviceID (IMMDevice* device)
  293. {
  294. String s;
  295. WCHAR* deviceId = nullptr;
  296. if (check (device->GetId (&deviceId)))
  297. {
  298. s = String (deviceId);
  299. CoTaskMemFree (deviceId);
  300. }
  301. return s;
  302. }
  303. static EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  304. {
  305. EDataFlow flow = eRender;
  306. if (auto endpoint = device.getInterface<IMMEndpoint>())
  307. (void) check (endpoint->GetDataFlow (&flow));
  308. return flow;
  309. }
  310. static int refTimeToSamples (const REFERENCE_TIME& t, double sampleRate) noexcept
  311. {
  312. return roundToInt (sampleRate * ((double) t) * 0.0000001);
  313. }
  314. static REFERENCE_TIME samplesToRefTime (int numSamples, double sampleRate) noexcept
  315. {
  316. return (REFERENCE_TIME) ((numSamples * 10000.0 * 1000.0 / sampleRate) + 0.5);
  317. }
  318. static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* src) noexcept
  319. {
  320. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  321. : sizeof (WAVEFORMATEX));
  322. }
  323. static bool isExclusiveMode (WASAPIDeviceMode deviceMode) noexcept
  324. {
  325. return deviceMode == WASAPIDeviceMode::exclusive;
  326. }
  327. static bool isLowLatencyMode (WASAPIDeviceMode deviceMode) noexcept
  328. {
  329. return deviceMode == WASAPIDeviceMode::sharedLowLatency;
  330. }
  331. static bool supportsSampleRateConversion (WASAPIDeviceMode deviceMode) noexcept
  332. {
  333. return deviceMode == WASAPIDeviceMode::shared;
  334. }
  335. //==============================================================================
  336. class WASAPIDeviceBase
  337. {
  338. public:
  339. WASAPIDeviceBase (const ComSmartPtr<IMMDevice>& d, WASAPIDeviceMode mode)
  340. : device (d),
  341. deviceMode (mode)
  342. {
  343. clientEvent = CreateEvent (nullptr, false, false, nullptr);
  344. ComSmartPtr<IAudioClient> tempClient (createClient());
  345. if (tempClient == nullptr)
  346. return;
  347. WAVEFORMATEXTENSIBLE format;
  348. if (! getClientMixFormat (tempClient, format))
  349. return;
  350. actualNumChannels = numChannels = format.Format.nChannels;
  351. defaultSampleRate = format.Format.nSamplesPerSec;
  352. rates.addUsingDefaultSort (defaultSampleRate);
  353. mixFormatChannelMask = format.dwChannelMask;
  354. if (isExclusiveMode (deviceMode))
  355. findSupportedFormat (tempClient, defaultSampleRate, mixFormatChannelMask, format);
  356. querySupportedBufferSizes (format, tempClient);
  357. querySupportedSampleRates (format, tempClient);
  358. }
  359. virtual ~WASAPIDeviceBase()
  360. {
  361. device = nullptr;
  362. CloseHandle (clientEvent);
  363. }
  364. bool isOk() const noexcept { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  365. bool openClient (const double newSampleRate, const BigInteger& newChannels, const int bufferSizeSamples)
  366. {
  367. sampleRate = newSampleRate;
  368. channels = newChannels;
  369. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  370. numChannels = channels.getHighestBit() + 1;
  371. if (numChannels == 0)
  372. return true;
  373. client = createClient();
  374. if (client != nullptr
  375. && tryInitialisingWithBufferSize (bufferSizeSamples))
  376. {
  377. sampleRateHasChanged = false;
  378. shouldShutdown = false;
  379. channelMaps.clear();
  380. for (int i = 0; i <= channels.getHighestBit(); ++i)
  381. if (channels[i])
  382. channelMaps.add (i);
  383. REFERENCE_TIME latency;
  384. if (check (client->GetStreamLatency (&latency)))
  385. latencySamples = refTimeToSamples (latency, sampleRate);
  386. (void) check (client->GetBufferSize (&actualBufferSize));
  387. createSessionEventCallback();
  388. return check (client->SetEventHandle (clientEvent));
  389. }
  390. return false;
  391. }
  392. void closeClient()
  393. {
  394. if (client != nullptr)
  395. client->Stop();
  396. // N.B. this is needed to prevent a double-deletion of the IAudioSessionEvents object
  397. // on older versions of Windows
  398. Thread::sleep (5);
  399. deleteSessionEventCallback();
  400. client = nullptr;
  401. ResetEvent (clientEvent);
  402. }
  403. void deviceSampleRateChanged()
  404. {
  405. sampleRateHasChanged = true;
  406. }
  407. void deviceSessionBecameInactive()
  408. {
  409. isActive = false;
  410. }
  411. void deviceSessionExpired()
  412. {
  413. shouldShutdown = true;
  414. }
  415. void deviceSessionBecameActive()
  416. {
  417. isActive = true;
  418. }
  419. //==============================================================================
  420. ComSmartPtr<IMMDevice> device;
  421. ComSmartPtr<IAudioClient> client;
  422. WASAPIDeviceMode deviceMode;
  423. double sampleRate = 0, defaultSampleRate = 0;
  424. int numChannels = 0, actualNumChannels = 0;
  425. int minBufferSize = 0, defaultBufferSize = 0, latencySamples = 0;
  426. int lowLatencyBufferSizeMultiple = 0, lowLatencyMaxBufferSize = 0;
  427. DWORD mixFormatChannelMask = 0;
  428. Array<double> rates;
  429. HANDLE clientEvent = {};
  430. BigInteger channels;
  431. Array<int> channelMaps;
  432. UINT32 actualBufferSize = 0;
  433. int bytesPerSample = 0, bytesPerFrame = 0;
  434. std::atomic<bool> sampleRateHasChanged { false }, shouldShutdown { false }, isActive { true };
  435. virtual void updateFormat (bool isFloat) = 0;
  436. private:
  437. //==============================================================================
  438. struct SessionEventCallback : public ComBaseClassHelper<IAudioSessionEvents>
  439. {
  440. SessionEventCallback (WASAPIDeviceBase& d) : owner (d) {}
  441. JUCE_COMRESULT OnDisplayNameChanged (LPCWSTR, LPCGUID) { return S_OK; }
  442. JUCE_COMRESULT OnIconPathChanged (LPCWSTR, LPCGUID) { return S_OK; }
  443. JUCE_COMRESULT OnSimpleVolumeChanged (float, BOOL, LPCGUID) { return S_OK; }
  444. JUCE_COMRESULT OnChannelVolumeChanged (DWORD, float*, DWORD, LPCGUID) { return S_OK; }
  445. JUCE_COMRESULT OnGroupingParamChanged (LPCGUID, LPCGUID) { return S_OK; }
  446. JUCE_COMRESULT OnStateChanged (AudioSessionState state)
  447. {
  448. switch (state)
  449. {
  450. case AudioSessionStateInactive:
  451. owner.deviceSessionBecameInactive();
  452. break;
  453. case AudioSessionStateExpired:
  454. owner.deviceSessionExpired();
  455. break;
  456. case AudioSessionStateActive:
  457. owner.deviceSessionBecameActive();
  458. break;
  459. }
  460. return S_OK;
  461. }
  462. JUCE_COMRESULT OnSessionDisconnected (AudioSessionDisconnectReason reason)
  463. {
  464. if (reason == DisconnectReasonFormatChanged)
  465. owner.deviceSampleRateChanged();
  466. return S_OK;
  467. }
  468. WASAPIDeviceBase& owner;
  469. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionEventCallback)
  470. };
  471. ComSmartPtr<IAudioSessionControl> audioSessionControl;
  472. ComSmartPtr<SessionEventCallback> sessionEventCallback;
  473. void createSessionEventCallback()
  474. {
  475. deleteSessionEventCallback();
  476. client->GetService (__uuidof (IAudioSessionControl),
  477. (void**) audioSessionControl.resetAndGetPointerAddress());
  478. if (audioSessionControl != nullptr)
  479. {
  480. sessionEventCallback = new SessionEventCallback (*this);
  481. audioSessionControl->RegisterAudioSessionNotification (sessionEventCallback);
  482. sessionEventCallback->Release(); // (required because ComBaseClassHelper objects are constructed with a ref count of 1)
  483. }
  484. }
  485. void deleteSessionEventCallback()
  486. {
  487. if (audioSessionControl != nullptr && sessionEventCallback != nullptr)
  488. audioSessionControl->UnregisterAudioSessionNotification (sessionEventCallback);
  489. audioSessionControl = nullptr;
  490. sessionEventCallback = nullptr;
  491. }
  492. //==============================================================================
  493. ComSmartPtr<IAudioClient> createClient()
  494. {
  495. ComSmartPtr<IAudioClient> newClient;
  496. if (device != nullptr)
  497. logFailure (device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER,
  498. nullptr, (void**) newClient.resetAndGetPointerAddress()));
  499. return newClient;
  500. }
  501. static bool getClientMixFormat (ComSmartPtr<IAudioClient>& client, WAVEFORMATEXTENSIBLE& format)
  502. {
  503. WAVEFORMATEX* mixFormat = nullptr;
  504. if (! check (client->GetMixFormat (&mixFormat)))
  505. return false;
  506. copyWavFormat (format, mixFormat);
  507. CoTaskMemFree (mixFormat);
  508. return true;
  509. }
  510. //==============================================================================
  511. void querySupportedBufferSizes (WAVEFORMATEXTENSIBLE format, ComSmartPtr<IAudioClient>& audioClient)
  512. {
  513. if (isLowLatencyMode (deviceMode))
  514. {
  515. if (auto audioClient3 = audioClient.getInterface<IAudioClient3>())
  516. {
  517. UINT32 defaultPeriod = 0, fundamentalPeriod = 0, minPeriod = 0, maxPeriod = 0;
  518. if (check (audioClient3->GetSharedModeEnginePeriod ((WAVEFORMATEX*) &format,
  519. &defaultPeriod,
  520. &fundamentalPeriod,
  521. &minPeriod,
  522. &maxPeriod)))
  523. {
  524. minBufferSize = minPeriod;
  525. defaultBufferSize = defaultPeriod;
  526. lowLatencyMaxBufferSize = maxPeriod;
  527. lowLatencyBufferSizeMultiple = fundamentalPeriod;
  528. }
  529. }
  530. }
  531. else
  532. {
  533. REFERENCE_TIME defaultPeriod, minPeriod;
  534. if (! check (audioClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  535. return;
  536. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  537. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  538. }
  539. }
  540. void querySupportedSampleRates (WAVEFORMATEXTENSIBLE format, ComSmartPtr<IAudioClient>& audioClient)
  541. {
  542. for (auto rate : { 8000, 11025, 16000, 22050, 32000,
  543. 44100, 48000, 88200, 96000, 176400,
  544. 192000, 352800, 384000, 705600, 768000 })
  545. {
  546. if (rates.contains (rate))
  547. continue;
  548. format.Format.nSamplesPerSec = (DWORD) rate;
  549. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nChannels * format.Format.wBitsPerSample / 8);
  550. WAVEFORMATEX* nearestFormat = nullptr;
  551. if (SUCCEEDED (audioClient->IsFormatSupported (isExclusiveMode (deviceMode) ? AUDCLNT_SHAREMODE_EXCLUSIVE
  552. : AUDCLNT_SHAREMODE_SHARED,
  553. (WAVEFORMATEX*) &format,
  554. isExclusiveMode (deviceMode) ? nullptr
  555. : &nearestFormat)))
  556. {
  557. if (nearestFormat != nullptr)
  558. rate = nearestFormat->nSamplesPerSec;
  559. if (! rates.contains (rate))
  560. rates.addUsingDefaultSort (rate);
  561. }
  562. CoTaskMemFree (nearestFormat);
  563. }
  564. }
  565. struct AudioSampleFormat
  566. {
  567. bool useFloat;
  568. int bitsPerSampleToTry;
  569. int bytesPerSampleContainer;
  570. };
  571. bool tryFormat (const AudioSampleFormat sampleFormat, IAudioClient* clientToUse, double newSampleRate,
  572. DWORD newMixFormatChannelMask, WAVEFORMATEXTENSIBLE& format) const
  573. {
  574. zerostruct (format);
  575. if (numChannels <= 2 && sampleFormat.bitsPerSampleToTry <= 16)
  576. {
  577. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  578. }
  579. else
  580. {
  581. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  582. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  583. }
  584. format.Format.nSamplesPerSec = (DWORD) newSampleRate;
  585. format.Format.nChannels = (WORD) numChannels;
  586. format.Format.wBitsPerSample = (WORD) (8 * sampleFormat.bytesPerSampleContainer);
  587. format.Samples.wValidBitsPerSample = (WORD) (sampleFormat.bitsPerSampleToTry);
  588. format.Format.nBlockAlign = (WORD) (format.Format.nChannels * format.Format.wBitsPerSample / 8);
  589. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nBlockAlign);
  590. format.SubFormat = sampleFormat.useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  591. format.dwChannelMask = newMixFormatChannelMask;
  592. WAVEFORMATEX* nearestFormat = nullptr;
  593. HRESULT hr = clientToUse->IsFormatSupported (isExclusiveMode (deviceMode) ? AUDCLNT_SHAREMODE_EXCLUSIVE
  594. : AUDCLNT_SHAREMODE_SHARED,
  595. (WAVEFORMATEX*) &format,
  596. isExclusiveMode (deviceMode) ? nullptr
  597. : &nearestFormat);
  598. logFailure (hr);
  599. auto supportsSRC = supportsSampleRateConversion (deviceMode);
  600. if (hr == S_FALSE
  601. && nearestFormat != nullptr
  602. && (format.Format.nSamplesPerSec == nearestFormat->nSamplesPerSec
  603. || supportsSRC))
  604. {
  605. copyWavFormat (format, nearestFormat);
  606. if (supportsSRC)
  607. {
  608. format.Format.nSamplesPerSec = (DWORD) newSampleRate;
  609. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nBlockAlign);
  610. }
  611. hr = S_OK;
  612. }
  613. CoTaskMemFree (nearestFormat);
  614. return hr == S_OK;
  615. }
  616. bool findSupportedFormat (IAudioClient* clientToUse, double newSampleRate,
  617. DWORD newMixFormatChannelMask, WAVEFORMATEXTENSIBLE& format) const
  618. {
  619. static const AudioSampleFormat formats[] =
  620. {
  621. { true, 32, 4 },
  622. { false, 32, 4 },
  623. { false, 24, 4 },
  624. { false, 24, 3 },
  625. { false, 20, 4 },
  626. { false, 20, 3 },
  627. { false, 16, 2 }
  628. };
  629. for (int i = 0; i < numElementsInArray (formats); ++i)
  630. if (tryFormat (formats[i], clientToUse, newSampleRate, newMixFormatChannelMask, format))
  631. return true;
  632. return false;
  633. }
  634. DWORD getStreamFlags()
  635. {
  636. DWORD streamFlags = 0x40000; /*AUDCLNT_STREAMFLAGS_EVENTCALLBACK*/
  637. if (supportsSampleRateConversion (deviceMode))
  638. streamFlags |= (0x80000000 /*AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM*/
  639. | 0x8000000); /*AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY*/
  640. return streamFlags;
  641. }
  642. bool initialiseLowLatencyClient (int bufferSizeSamples, WAVEFORMATEXTENSIBLE format)
  643. {
  644. if (auto audioClient3 = client.getInterface<IAudioClient3>())
  645. return check (audioClient3->InitializeSharedAudioStream (getStreamFlags(),
  646. bufferSizeSamples,
  647. (WAVEFORMATEX*) &format,
  648. nullptr));
  649. return false;
  650. }
  651. bool initialiseStandardClient (int bufferSizeSamples, WAVEFORMATEXTENSIBLE format)
  652. {
  653. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  654. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  655. if (isExclusiveMode (deviceMode) && bufferSizeSamples > 0)
  656. defaultPeriod = jmax (minPeriod, samplesToRefTime (bufferSizeSamples, format.Format.nSamplesPerSec));
  657. for (;;)
  658. {
  659. GUID session;
  660. auto hr = client->Initialize (isExclusiveMode (deviceMode) ? AUDCLNT_SHAREMODE_EXCLUSIVE
  661. : AUDCLNT_SHAREMODE_SHARED,
  662. getStreamFlags(),
  663. defaultPeriod,
  664. isExclusiveMode (deviceMode) ? defaultPeriod : 0,
  665. (WAVEFORMATEX*) &format,
  666. &session);
  667. if (check (hr))
  668. return true;
  669. // Handle the "alignment dance" : http://msdn.microsoft.com/en-us/library/windows/desktop/dd370875(v=vs.85).aspx (see Remarks)
  670. if (hr != MAKE_HRESULT (1, 0x889, 0x19)) // AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
  671. break;
  672. UINT32 numFrames = 0;
  673. if (! check (client->GetBufferSize (&numFrames)))
  674. break;
  675. // Recreate client
  676. client = nullptr;
  677. client = createClient();
  678. defaultPeriod = samplesToRefTime (numFrames, format.Format.nSamplesPerSec);
  679. }
  680. return false;
  681. }
  682. bool tryInitialisingWithBufferSize (int bufferSizeSamples)
  683. {
  684. WAVEFORMATEXTENSIBLE format;
  685. if (findSupportedFormat (client, sampleRate, mixFormatChannelMask, format))
  686. {
  687. auto isInitialised = isLowLatencyMode (deviceMode) ? initialiseLowLatencyClient (bufferSizeSamples, format)
  688. : initialiseStandardClient (bufferSizeSamples, format);
  689. if (isInitialised)
  690. {
  691. actualNumChannels = format.Format.nChannels;
  692. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  693. bytesPerSample = format.Format.wBitsPerSample / 8;
  694. bytesPerFrame = format.Format.nBlockAlign;
  695. updateFormat (isFloat);
  696. return true;
  697. }
  698. }
  699. return false;
  700. }
  701. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase)
  702. };
  703. //==============================================================================
  704. class WASAPIInputDevice : public WASAPIDeviceBase
  705. {
  706. public:
  707. WASAPIInputDevice (const ComSmartPtr<IMMDevice>& d, WASAPIDeviceMode mode)
  708. : WASAPIDeviceBase (d, mode)
  709. {
  710. }
  711. ~WASAPIInputDevice()
  712. {
  713. close();
  714. }
  715. bool open (double newSampleRate, const BigInteger& newChannels, int bufferSizeSamples)
  716. {
  717. return openClient (newSampleRate, newChannels, bufferSizeSamples)
  718. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  719. (void**) captureClient.resetAndGetPointerAddress())));
  720. }
  721. void close()
  722. {
  723. closeClient();
  724. captureClient = nullptr;
  725. reservoir.reset();
  726. reservoirReadPos = 0;
  727. reservoirWritePos = 0;
  728. }
  729. template <class SourceType>
  730. void updateFormatWithType (SourceType*) noexcept
  731. {
  732. using NativeType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  733. converter.reset (new AudioData::ConverterInstance<AudioData::Pointer<SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1));
  734. }
  735. void updateFormat (bool isFloat) override
  736. {
  737. if (isFloat) updateFormatWithType ((AudioData::Float32*) nullptr);
  738. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) nullptr);
  739. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) nullptr);
  740. else updateFormatWithType ((AudioData::Int16*) nullptr);
  741. }
  742. bool start (int userBufferSize)
  743. {
  744. reservoirSize = actualBufferSize + userBufferSize;
  745. reservoirMask = nextPowerOfTwo (reservoirSize) - 1;
  746. reservoir.setSize ((reservoirMask + 1) * bytesPerFrame, true);
  747. reservoirReadPos = 0;
  748. reservoirWritePos = 0;
  749. xruns = 0;
  750. if (! check (client->Start()))
  751. return false;
  752. purgeInputBuffers();
  753. isActive = true;
  754. return true;
  755. }
  756. void purgeInputBuffers()
  757. {
  758. uint8* inputData;
  759. UINT32 numSamplesAvailable;
  760. DWORD flags;
  761. while (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, nullptr, nullptr)
  762. != MAKE_HRESULT (0, 0x889, 0x1) /* AUDCLNT_S_BUFFER_EMPTY */)
  763. captureClient->ReleaseBuffer (numSamplesAvailable);
  764. }
  765. int getNumSamplesInReservoir() const noexcept { return reservoirWritePos.load() - reservoirReadPos.load(); }
  766. void handleDeviceBuffer()
  767. {
  768. if (numChannels <= 0)
  769. return;
  770. uint8* inputData;
  771. UINT32 numSamplesAvailable;
  772. DWORD flags;
  773. while (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, nullptr, nullptr)) && numSamplesAvailable > 0)
  774. {
  775. if ((flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0)
  776. xruns++;
  777. int samplesLeft = (int) numSamplesAvailable;
  778. while (samplesLeft > 0)
  779. {
  780. auto localWrite = reservoirWritePos.load() & reservoirMask;
  781. auto samplesToDo = jmin (samplesLeft, reservoirMask + 1 - localWrite);
  782. auto samplesToDoBytes = samplesToDo * bytesPerFrame;
  783. void* reservoirPtr = addBytesToPointer (reservoir.getData(), localWrite * bytesPerFrame);
  784. if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0)
  785. zeromem (reservoirPtr, samplesToDoBytes);
  786. else
  787. memcpy (reservoirPtr, inputData, samplesToDoBytes);
  788. reservoirWritePos += samplesToDo;
  789. inputData += samplesToDoBytes;
  790. samplesLeft -= samplesToDo;
  791. }
  792. if (getNumSamplesInReservoir() > reservoirSize)
  793. reservoirReadPos = reservoirWritePos.load() - reservoirSize;
  794. captureClient->ReleaseBuffer (numSamplesAvailable);
  795. }
  796. }
  797. void copyBuffersFromReservoir (float** destBuffers, int numDestBuffers, int bufferSize)
  798. {
  799. if ((numChannels <= 0 && bufferSize == 0) || reservoir.isEmpty())
  800. return;
  801. int offset = jmax (0, bufferSize - getNumSamplesInReservoir());
  802. if (offset > 0)
  803. {
  804. for (int i = 0; i < numDestBuffers; ++i)
  805. zeromem (destBuffers[i], offset * sizeof (float));
  806. bufferSize -= offset;
  807. reservoirReadPos -= offset / 2;
  808. }
  809. while (bufferSize > 0)
  810. {
  811. auto localRead = reservoirReadPos.load() & reservoirMask;
  812. auto samplesToDo = jmin (bufferSize, getNumSamplesInReservoir(), reservoirMask + 1 - localRead);
  813. if (samplesToDo <= 0)
  814. break;
  815. auto reservoirOffset = localRead * bytesPerFrame;
  816. for (int i = 0; i < numDestBuffers; ++i)
  817. converter->convertSamples (destBuffers[i] + offset, 0, addBytesToPointer (reservoir.getData(), reservoirOffset), channelMaps.getUnchecked(i), samplesToDo);
  818. bufferSize -= samplesToDo;
  819. offset += samplesToDo;
  820. reservoirReadPos += samplesToDo;
  821. }
  822. }
  823. ComSmartPtr<IAudioCaptureClient> captureClient;
  824. MemoryBlock reservoir;
  825. int reservoirSize, reservoirMask, xruns;
  826. std::atomic<int> reservoirReadPos, reservoirWritePos;
  827. std::unique_ptr<AudioData::Converter> converter;
  828. private:
  829. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice)
  830. };
  831. //==============================================================================
  832. class WASAPIOutputDevice : public WASAPIDeviceBase
  833. {
  834. public:
  835. WASAPIOutputDevice (const ComSmartPtr<IMMDevice>& d, WASAPIDeviceMode mode)
  836. : WASAPIDeviceBase (d, mode)
  837. {
  838. }
  839. ~WASAPIOutputDevice()
  840. {
  841. close();
  842. }
  843. bool open (double newSampleRate, const BigInteger& newChannels, int bufferSizeSamples)
  844. {
  845. return openClient (newSampleRate, newChannels, bufferSizeSamples)
  846. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient),
  847. (void**) renderClient.resetAndGetPointerAddress())));
  848. }
  849. void close()
  850. {
  851. closeClient();
  852. renderClient = nullptr;
  853. }
  854. template <class DestType>
  855. void updateFormatWithType (DestType*)
  856. {
  857. using NativeType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  858. converter.reset (new AudioData::ConverterInstance<NativeType, AudioData::Pointer<DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst>> (1, actualNumChannels));
  859. }
  860. void updateFormat (bool isFloat) override
  861. {
  862. if (isFloat) updateFormatWithType ((AudioData::Float32*) nullptr);
  863. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) nullptr);
  864. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) nullptr);
  865. else updateFormatWithType ((AudioData::Int16*) nullptr);
  866. }
  867. bool start()
  868. {
  869. auto samplesToDo = getNumSamplesAvailableToCopy();
  870. uint8* outputData;
  871. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  872. renderClient->ReleaseBuffer (samplesToDo, AUDCLNT_BUFFERFLAGS_SILENT);
  873. if (! check (client->Start()))
  874. return false;
  875. isActive = true;
  876. return true;
  877. }
  878. int getNumSamplesAvailableToCopy() const
  879. {
  880. if (numChannels <= 0)
  881. return 0;
  882. if (! isExclusiveMode (deviceMode))
  883. {
  884. UINT32 padding = 0;
  885. if (check (client->GetCurrentPadding (&padding)))
  886. return actualBufferSize - (int) padding;
  887. }
  888. return actualBufferSize;
  889. }
  890. void copyBuffers (const float** srcBuffers, int numSrcBuffers, int bufferSize,
  891. WASAPIInputDevice* inputDevice, Thread& thread)
  892. {
  893. if (numChannels <= 0)
  894. return;
  895. int offset = 0;
  896. while (bufferSize > 0)
  897. {
  898. // This is needed in order not to drop any input data if the output device endpoint buffer was full
  899. if ((! isExclusiveMode (deviceMode)) && inputDevice != nullptr
  900. && WaitForSingleObject (inputDevice->clientEvent, 0) == WAIT_OBJECT_0)
  901. inputDevice->handleDeviceBuffer();
  902. int samplesToDo = jmin (getNumSamplesAvailableToCopy(), bufferSize);
  903. if (samplesToDo == 0)
  904. {
  905. // This can ONLY occur in non-exclusive mode
  906. if (! thread.threadShouldExit() && WaitForSingleObject (clientEvent, 1000) == WAIT_OBJECT_0)
  907. continue;
  908. break;
  909. }
  910. if (isExclusiveMode (deviceMode) && WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  911. break;
  912. uint8* outputData = nullptr;
  913. if (check (renderClient->GetBuffer ((UINT32) samplesToDo, &outputData)))
  914. {
  915. for (int i = 0; i < numSrcBuffers; ++i)
  916. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  917. renderClient->ReleaseBuffer ((UINT32) samplesToDo, 0);
  918. }
  919. bufferSize -= samplesToDo;
  920. offset += samplesToDo;
  921. }
  922. }
  923. ComSmartPtr<IAudioRenderClient> renderClient;
  924. std::unique_ptr<AudioData::Converter> converter;
  925. private:
  926. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice)
  927. };
  928. //==============================================================================
  929. class WASAPIAudioIODevice : public AudioIODevice,
  930. public Thread,
  931. private AsyncUpdater
  932. {
  933. public:
  934. WASAPIAudioIODevice (const String& deviceName,
  935. const String& typeName,
  936. const String& outputDeviceID,
  937. const String& inputDeviceID,
  938. WASAPIDeviceMode mode)
  939. : AudioIODevice (deviceName, typeName),
  940. Thread ("JUCE WASAPI"),
  941. outputDeviceId (outputDeviceID),
  942. inputDeviceId (inputDeviceID),
  943. deviceMode (mode)
  944. {
  945. }
  946. ~WASAPIAudioIODevice()
  947. {
  948. cancelPendingUpdate();
  949. close();
  950. }
  951. bool initialise()
  952. {
  953. latencyIn = latencyOut = 0;
  954. Array<double> ratesIn, ratesOut;
  955. if (createDevices())
  956. {
  957. jassert (inputDevice != nullptr || outputDevice != nullptr);
  958. sampleRates.clear();
  959. if (inputDevice != nullptr && outputDevice != nullptr)
  960. {
  961. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  962. minBufferSize = jmax (inputDevice->minBufferSize, outputDevice->minBufferSize);
  963. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  964. if (isLowLatencyMode (deviceMode))
  965. {
  966. lowLatencyMaxBufferSize = jmin (inputDevice->lowLatencyMaxBufferSize, outputDevice->lowLatencyMaxBufferSize);
  967. lowLatencyBufferSizeMultiple = jmax (inputDevice->lowLatencyBufferSizeMultiple, outputDevice->lowLatencyBufferSizeMultiple);
  968. }
  969. sampleRates.addArray (inputDevice->rates);
  970. if (supportsSampleRateConversion (deviceMode))
  971. {
  972. for (auto r : outputDevice->rates)
  973. if (! sampleRates.contains (r))
  974. sampleRates.addUsingDefaultSort (r);
  975. }
  976. else
  977. {
  978. sampleRates.removeValuesNotIn (outputDevice->rates);
  979. }
  980. }
  981. else
  982. {
  983. auto* d = inputDevice != nullptr ? static_cast<WASAPIDeviceBase*> (inputDevice.get())
  984. : static_cast<WASAPIDeviceBase*> (outputDevice.get());
  985. defaultSampleRate = d->defaultSampleRate;
  986. minBufferSize = d->minBufferSize;
  987. defaultBufferSize = d->defaultBufferSize;
  988. if (isLowLatencyMode (deviceMode))
  989. {
  990. lowLatencyMaxBufferSize = d->lowLatencyMaxBufferSize;
  991. lowLatencyBufferSizeMultiple = d->lowLatencyBufferSizeMultiple;
  992. }
  993. sampleRates = d->rates;
  994. }
  995. bufferSizes.clear();
  996. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  997. if (minBufferSize != defaultBufferSize)
  998. bufferSizes.addUsingDefaultSort (minBufferSize);
  999. if (isLowLatencyMode (deviceMode))
  1000. {
  1001. auto size = minBufferSize;
  1002. while (size < lowLatencyMaxBufferSize)
  1003. {
  1004. size += lowLatencyBufferSizeMultiple;
  1005. if (! bufferSizes.contains (size))
  1006. bufferSizes.addUsingDefaultSort (size);
  1007. }
  1008. }
  1009. else
  1010. {
  1011. int n = 64;
  1012. for (int i = 0; i < 40; ++i)
  1013. {
  1014. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  1015. bufferSizes.addUsingDefaultSort (n);
  1016. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  1017. }
  1018. }
  1019. return true;
  1020. }
  1021. return false;
  1022. }
  1023. StringArray getOutputChannelNames() override
  1024. {
  1025. StringArray outChannels;
  1026. if (outputDevice != nullptr)
  1027. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  1028. outChannels.add ("Output channel " + String (i));
  1029. return outChannels;
  1030. }
  1031. StringArray getInputChannelNames() override
  1032. {
  1033. StringArray inChannels;
  1034. if (inputDevice != nullptr)
  1035. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  1036. inChannels.add ("Input channel " + String (i));
  1037. return inChannels;
  1038. }
  1039. Array<double> getAvailableSampleRates() override { return sampleRates; }
  1040. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  1041. int getDefaultBufferSize() override { return defaultBufferSize; }
  1042. int getCurrentBufferSizeSamples() override { return currentBufferSizeSamples; }
  1043. double getCurrentSampleRate() override { return currentSampleRate; }
  1044. int getCurrentBitDepth() override { return 32; }
  1045. int getOutputLatencyInSamples() override { return latencyOut; }
  1046. int getInputLatencyInSamples() override { return latencyIn; }
  1047. BigInteger getActiveOutputChannels() const override { return outputDevice != nullptr ? outputDevice->channels : BigInteger(); }
  1048. BigInteger getActiveInputChannels() const override { return inputDevice != nullptr ? inputDevice->channels : BigInteger(); }
  1049. String getLastError() override { return lastError; }
  1050. int getXRunCount() const noexcept override { return inputDevice != nullptr ? inputDevice->xruns : -1; }
  1051. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  1052. double sampleRate, int bufferSizeSamples) override
  1053. {
  1054. close();
  1055. lastError.clear();
  1056. if (sampleRates.size() == 0 && inputDevice != nullptr && outputDevice != nullptr)
  1057. {
  1058. lastError = TRANS("The input and output devices don't share a common sample rate!");
  1059. return lastError;
  1060. }
  1061. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  1062. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  1063. lastKnownInputChannels = inputChannels;
  1064. lastKnownOutputChannels = outputChannels;
  1065. if (inputDevice != nullptr && ! inputDevice->open (currentSampleRate, inputChannels, bufferSizeSamples))
  1066. {
  1067. lastError = TRANS("Couldn't open the input device!");
  1068. return lastError;
  1069. }
  1070. if (outputDevice != nullptr && ! outputDevice->open (currentSampleRate, outputChannels, bufferSizeSamples))
  1071. {
  1072. close();
  1073. lastError = TRANS("Couldn't open the output device!");
  1074. return lastError;
  1075. }
  1076. if (isExclusiveMode (deviceMode))
  1077. {
  1078. // This is to make sure that the callback uses actualBufferSize in case of exclusive mode
  1079. if (inputDevice != nullptr && outputDevice != nullptr && inputDevice->actualBufferSize != outputDevice->actualBufferSize)
  1080. {
  1081. close();
  1082. lastError = TRANS("Couldn't open the output device (buffer size mismatch)");
  1083. return lastError;
  1084. }
  1085. currentBufferSizeSamples = outputDevice != nullptr ? outputDevice->actualBufferSize
  1086. : inputDevice->actualBufferSize;
  1087. }
  1088. if (inputDevice != nullptr) ResetEvent (inputDevice->clientEvent);
  1089. if (outputDevice != nullptr) ResetEvent (outputDevice->clientEvent);
  1090. shouldShutdown = false;
  1091. deviceSampleRateChanged = false;
  1092. startThread (8);
  1093. Thread::sleep (5);
  1094. if (inputDevice != nullptr && inputDevice->client != nullptr)
  1095. {
  1096. latencyIn = (int) (inputDevice->latencySamples + currentBufferSizeSamples);
  1097. if (! inputDevice->start (currentBufferSizeSamples))
  1098. {
  1099. close();
  1100. lastError = TRANS("Couldn't start the input device!");
  1101. return lastError;
  1102. }
  1103. }
  1104. if (outputDevice != nullptr && outputDevice->client != nullptr)
  1105. {
  1106. latencyOut = (int) (outputDevice->latencySamples + currentBufferSizeSamples);
  1107. if (! outputDevice->start())
  1108. {
  1109. close();
  1110. lastError = TRANS("Couldn't start the output device!");
  1111. return lastError;
  1112. }
  1113. }
  1114. isOpen_ = true;
  1115. return lastError;
  1116. }
  1117. void close() override
  1118. {
  1119. stop();
  1120. signalThreadShouldExit();
  1121. if (inputDevice != nullptr) SetEvent (inputDevice->clientEvent);
  1122. if (outputDevice != nullptr) SetEvent (outputDevice->clientEvent);
  1123. stopThread (5000);
  1124. if (inputDevice != nullptr) inputDevice->close();
  1125. if (outputDevice != nullptr) outputDevice->close();
  1126. isOpen_ = false;
  1127. }
  1128. bool isOpen() override { return isOpen_ && isThreadRunning(); }
  1129. bool isPlaying() override { return isStarted && isOpen_ && isThreadRunning(); }
  1130. void start (AudioIODeviceCallback* call) override
  1131. {
  1132. if (isOpen_ && call != nullptr && ! isStarted)
  1133. {
  1134. if (! isThreadRunning())
  1135. {
  1136. // something's gone wrong and the thread's stopped..
  1137. isOpen_ = false;
  1138. return;
  1139. }
  1140. call->audioDeviceAboutToStart (this);
  1141. const ScopedLock sl (startStopLock);
  1142. callback = call;
  1143. isStarted = true;
  1144. }
  1145. }
  1146. void stop() override
  1147. {
  1148. if (isStarted)
  1149. {
  1150. auto* callbackLocal = callback;
  1151. {
  1152. const ScopedLock sl (startStopLock);
  1153. isStarted = false;
  1154. }
  1155. if (callbackLocal != nullptr)
  1156. callbackLocal->audioDeviceStopped();
  1157. }
  1158. }
  1159. void setMMThreadPriority()
  1160. {
  1161. DynamicLibrary dll ("avrt.dll");
  1162. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, (LPCWSTR, LPDWORD))
  1163. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, (HANDLE, AVRT_PRIORITY))
  1164. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  1165. {
  1166. DWORD dummy = 0;
  1167. if (auto h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy))
  1168. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  1169. }
  1170. }
  1171. void run() override
  1172. {
  1173. setMMThreadPriority();
  1174. auto bufferSize = currentBufferSizeSamples;
  1175. auto numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  1176. auto numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  1177. AudioBuffer<float> ins (jmax (1, numInputBuffers), bufferSize + 32);
  1178. AudioBuffer<float> outs (jmax (1, numOutputBuffers), bufferSize + 32);
  1179. auto inputBuffers = ins.getArrayOfWritePointers();
  1180. auto outputBuffers = outs.getArrayOfWritePointers();
  1181. ins.clear();
  1182. outs.clear();
  1183. while (! threadShouldExit())
  1184. {
  1185. if ((outputDevice != nullptr && outputDevice->shouldShutdown)
  1186. || (inputDevice != nullptr && inputDevice->shouldShutdown))
  1187. {
  1188. shouldShutdown = true;
  1189. triggerAsyncUpdate();
  1190. break;
  1191. }
  1192. auto inputDeviceActive = (inputDevice != nullptr && inputDevice->isActive);
  1193. auto outputDeviceActive = (outputDevice != nullptr && outputDevice->isActive);
  1194. if (! inputDeviceActive && ! outputDeviceActive)
  1195. continue;
  1196. if (inputDeviceActive)
  1197. {
  1198. if (outputDevice == nullptr)
  1199. {
  1200. if (WaitForSingleObject (inputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  1201. break;
  1202. inputDevice->handleDeviceBuffer();
  1203. if (inputDevice->getNumSamplesInReservoir() < bufferSize)
  1204. continue;
  1205. }
  1206. else
  1207. {
  1208. if (isExclusiveMode (deviceMode) && WaitForSingleObject (inputDevice->clientEvent, 0) == WAIT_OBJECT_0)
  1209. inputDevice->handleDeviceBuffer();
  1210. }
  1211. inputDevice->copyBuffersFromReservoir (inputBuffers, numInputBuffers, bufferSize);
  1212. if (inputDevice->sampleRateHasChanged)
  1213. {
  1214. deviceSampleRateChanged = true;
  1215. triggerAsyncUpdate();
  1216. break;
  1217. }
  1218. }
  1219. {
  1220. const ScopedTryLock sl (startStopLock);
  1221. if (sl.isLocked() && isStarted)
  1222. callback->audioDeviceIOCallback (const_cast<const float**> (inputBuffers), numInputBuffers,
  1223. outputBuffers, numOutputBuffers, bufferSize);
  1224. else
  1225. outs.clear();
  1226. }
  1227. if (outputDeviceActive)
  1228. {
  1229. // Note that this function is handed the input device so it can check for the event and make sure
  1230. // the input reservoir is filled up correctly even when bufferSize > device actualBufferSize
  1231. outputDevice->copyBuffers (const_cast<const float**> (outputBuffers), numOutputBuffers, bufferSize, inputDevice.get(), *this);
  1232. if (outputDevice->sampleRateHasChanged)
  1233. {
  1234. deviceSampleRateChanged = true;
  1235. triggerAsyncUpdate();
  1236. break;
  1237. }
  1238. }
  1239. }
  1240. }
  1241. //==============================================================================
  1242. String outputDeviceId, inputDeviceId;
  1243. String lastError;
  1244. private:
  1245. // Device stats...
  1246. std::unique_ptr<WASAPIInputDevice> inputDevice;
  1247. std::unique_ptr<WASAPIOutputDevice> outputDevice;
  1248. WASAPIDeviceMode deviceMode;
  1249. double defaultSampleRate = 0;
  1250. int minBufferSize = 0, defaultBufferSize = 0;
  1251. int lowLatencyMaxBufferSize = 0, lowLatencyBufferSizeMultiple = 0;
  1252. int latencyIn = 0, latencyOut = 0;
  1253. Array<double> sampleRates;
  1254. Array<int> bufferSizes;
  1255. // Active state...
  1256. bool isOpen_ = false, isStarted = false;
  1257. int currentBufferSizeSamples = 0;
  1258. double currentSampleRate = 0;
  1259. AudioIODeviceCallback* callback = {};
  1260. CriticalSection startStopLock;
  1261. std::atomic<bool> shouldShutdown { false }, deviceSampleRateChanged { false };
  1262. BigInteger lastKnownInputChannels, lastKnownOutputChannels;
  1263. //==============================================================================
  1264. bool createDevices()
  1265. {
  1266. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1267. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1268. return false;
  1269. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  1270. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  1271. return false;
  1272. UINT32 numDevices = 0;
  1273. if (! check (deviceCollection->GetCount (&numDevices)))
  1274. return false;
  1275. for (UINT32 i = 0; i < numDevices; ++i)
  1276. {
  1277. ComSmartPtr<IMMDevice> device;
  1278. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1279. continue;
  1280. auto deviceId = getDeviceID (device);
  1281. if (deviceId.isEmpty())
  1282. continue;
  1283. auto flow = getDataFlow (device);
  1284. if (deviceId == inputDeviceId && flow == eCapture)
  1285. inputDevice.reset (new WASAPIInputDevice (device, deviceMode));
  1286. else if (deviceId == outputDeviceId && flow == eRender)
  1287. outputDevice.reset (new WASAPIOutputDevice (device, deviceMode));
  1288. }
  1289. return (outputDeviceId.isEmpty() || (outputDevice != nullptr && outputDevice->isOk()))
  1290. && (inputDeviceId.isEmpty() || (inputDevice != nullptr && inputDevice->isOk()));
  1291. }
  1292. //==============================================================================
  1293. void handleAsyncUpdate() override
  1294. {
  1295. auto closeDevices = [this]
  1296. {
  1297. close();
  1298. outputDevice = nullptr;
  1299. inputDevice = nullptr;
  1300. };
  1301. if (shouldShutdown)
  1302. {
  1303. closeDevices();
  1304. }
  1305. else if (deviceSampleRateChanged)
  1306. {
  1307. auto sampleRateChangedByInput = (inputDevice != nullptr && inputDevice->sampleRateHasChanged);
  1308. closeDevices();
  1309. initialise();
  1310. auto changedSampleRate = [this, sampleRateChangedByInput]()
  1311. {
  1312. if (inputDevice != nullptr && sampleRateChangedByInput)
  1313. return inputDevice->defaultSampleRate;
  1314. if (outputDevice != nullptr && ! sampleRateChangedByInput)
  1315. return outputDevice->defaultSampleRate;
  1316. return 0.0;
  1317. }();
  1318. open (lastKnownInputChannels, lastKnownOutputChannels,
  1319. changedSampleRate, currentBufferSizeSamples);
  1320. start (callback);
  1321. }
  1322. }
  1323. //==============================================================================
  1324. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice)
  1325. };
  1326. //==============================================================================
  1327. class WASAPIAudioIODeviceType : public AudioIODeviceType,
  1328. private DeviceChangeDetector
  1329. {
  1330. public:
  1331. WASAPIAudioIODeviceType (WASAPIDeviceMode mode)
  1332. : AudioIODeviceType (getDeviceTypename (mode)),
  1333. DeviceChangeDetector (L"Windows Audio"),
  1334. deviceMode (mode)
  1335. {
  1336. }
  1337. ~WASAPIAudioIODeviceType()
  1338. {
  1339. if (notifyClient != nullptr)
  1340. enumerator->UnregisterEndpointNotificationCallback (notifyClient);
  1341. }
  1342. //==============================================================================
  1343. void scanForDevices() override
  1344. {
  1345. hasScanned = true;
  1346. outputDeviceNames.clear();
  1347. inputDeviceNames.clear();
  1348. outputDeviceIds.clear();
  1349. inputDeviceIds.clear();
  1350. scan (outputDeviceNames, inputDeviceNames,
  1351. outputDeviceIds, inputDeviceIds);
  1352. }
  1353. StringArray getDeviceNames (bool wantInputNames) const override
  1354. {
  1355. jassert (hasScanned); // need to call scanForDevices() before doing this
  1356. return wantInputNames ? inputDeviceNames
  1357. : outputDeviceNames;
  1358. }
  1359. int getDefaultDeviceIndex (bool /*forInput*/) const override
  1360. {
  1361. jassert (hasScanned); // need to call scanForDevices() before doing this
  1362. return 0;
  1363. }
  1364. int getIndexOfDevice (AudioIODevice* device, bool asInput) const override
  1365. {
  1366. jassert (hasScanned); // need to call scanForDevices() before doing this
  1367. if (auto d = dynamic_cast<WASAPIAudioIODevice*> (device))
  1368. return asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  1369. : outputDeviceIds.indexOf (d->outputDeviceId);
  1370. return -1;
  1371. }
  1372. bool hasSeparateInputsAndOutputs() const override { return true; }
  1373. AudioIODevice* createDevice (const String& outputDeviceName,
  1374. const String& inputDeviceName) override
  1375. {
  1376. jassert (hasScanned); // need to call scanForDevices() before doing this
  1377. std::unique_ptr<WASAPIAudioIODevice> device;
  1378. auto outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  1379. auto inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  1380. if (outputIndex >= 0 || inputIndex >= 0)
  1381. {
  1382. device.reset (new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1383. : inputDeviceName,
  1384. getTypeName(),
  1385. outputDeviceIds [outputIndex],
  1386. inputDeviceIds [inputIndex],
  1387. deviceMode));
  1388. if (! device->initialise())
  1389. device = nullptr;
  1390. }
  1391. return device.release();
  1392. }
  1393. //==============================================================================
  1394. StringArray outputDeviceNames, outputDeviceIds;
  1395. StringArray inputDeviceNames, inputDeviceIds;
  1396. private:
  1397. WASAPIDeviceMode deviceMode;
  1398. bool hasScanned = false;
  1399. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1400. //==============================================================================
  1401. class ChangeNotificationClient : public ComBaseClassHelper<IMMNotificationClient>
  1402. {
  1403. public:
  1404. ChangeNotificationClient (WASAPIAudioIODeviceType* d)
  1405. : ComBaseClassHelper (0), device (d) {}
  1406. JUCE_COMRESULT OnDeviceAdded (LPCWSTR) { return notify(); }
  1407. JUCE_COMRESULT OnDeviceRemoved (LPCWSTR) { return notify(); }
  1408. JUCE_COMRESULT OnDeviceStateChanged(LPCWSTR, DWORD) { return notify(); }
  1409. JUCE_COMRESULT OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) { return notify(); }
  1410. JUCE_COMRESULT OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) { return notify(); }
  1411. private:
  1412. WeakReference<WASAPIAudioIODeviceType> device;
  1413. HRESULT notify()
  1414. {
  1415. if (device != nullptr)
  1416. device->triggerAsyncDeviceChangeCallback();
  1417. return S_OK;
  1418. }
  1419. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeNotificationClient)
  1420. };
  1421. ComSmartPtr<ChangeNotificationClient> notifyClient;
  1422. //==============================================================================
  1423. static String getDefaultEndpoint (IMMDeviceEnumerator* enumerator, bool forCapture)
  1424. {
  1425. String s;
  1426. IMMDevice* dev = nullptr;
  1427. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  1428. eMultimedia, &dev)))
  1429. {
  1430. WCHAR* deviceId = nullptr;
  1431. if (check (dev->GetId (&deviceId)))
  1432. {
  1433. s = deviceId;
  1434. CoTaskMemFree (deviceId);
  1435. }
  1436. dev->Release();
  1437. }
  1438. return s;
  1439. }
  1440. //==============================================================================
  1441. void scan (StringArray& outDeviceNames,
  1442. StringArray& inDeviceNames,
  1443. StringArray& outDeviceIds,
  1444. StringArray& inDeviceIds)
  1445. {
  1446. if (enumerator == nullptr)
  1447. {
  1448. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1449. return;
  1450. notifyClient = new ChangeNotificationClient (this);
  1451. enumerator->RegisterEndpointNotificationCallback (notifyClient);
  1452. }
  1453. auto defaultRenderer = getDefaultEndpoint (enumerator, false);
  1454. auto defaultCapture = getDefaultEndpoint (enumerator, true);
  1455. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  1456. UINT32 numDevices = 0;
  1457. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  1458. && check (deviceCollection->GetCount (&numDevices))))
  1459. return;
  1460. for (UINT32 i = 0; i < numDevices; ++i)
  1461. {
  1462. ComSmartPtr<IMMDevice> device;
  1463. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1464. continue;
  1465. DWORD state = 0;
  1466. if (! (check (device->GetState (&state)) && state == DEVICE_STATE_ACTIVE))
  1467. continue;
  1468. auto deviceId = getDeviceID (device);
  1469. String name;
  1470. {
  1471. ComSmartPtr<IPropertyStore> properties;
  1472. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  1473. continue;
  1474. PROPVARIANT value;
  1475. zerostruct (value);
  1476. const PROPERTYKEY PKEY_Device_FriendlyName
  1477. = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 };
  1478. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  1479. name = value.pwszVal;
  1480. PropVariantClear (&value);
  1481. }
  1482. auto flow = getDataFlow (device);
  1483. if (flow == eRender)
  1484. {
  1485. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  1486. outDeviceIds.insert (index, deviceId);
  1487. outDeviceNames.insert (index, name);
  1488. }
  1489. else if (flow == eCapture)
  1490. {
  1491. const int index = (deviceId == defaultCapture) ? 0 : -1;
  1492. inDeviceIds.insert (index, deviceId);
  1493. inDeviceNames.insert (index, name);
  1494. }
  1495. }
  1496. inDeviceNames.appendNumbersToDuplicates (false, false);
  1497. outDeviceNames.appendNumbersToDuplicates (false, false);
  1498. }
  1499. //==============================================================================
  1500. void systemDeviceChanged() override
  1501. {
  1502. StringArray newOutNames, newInNames, newOutIds, newInIds;
  1503. scan (newOutNames, newInNames, newOutIds, newInIds);
  1504. if (newOutNames != outputDeviceNames
  1505. || newInNames != inputDeviceNames
  1506. || newOutIds != outputDeviceIds
  1507. || newInIds != inputDeviceIds)
  1508. {
  1509. hasScanned = true;
  1510. outputDeviceNames = newOutNames;
  1511. inputDeviceNames = newInNames;
  1512. outputDeviceIds = newOutIds;
  1513. inputDeviceIds = newInIds;
  1514. }
  1515. callDeviceChangeListeners();
  1516. }
  1517. //==============================================================================
  1518. static String getDeviceTypename (WASAPIDeviceMode mode)
  1519. {
  1520. if (mode == WASAPIDeviceMode::shared) return "Windows Audio";
  1521. if (mode == WASAPIDeviceMode::sharedLowLatency) return "Windows Audio (Low Latency Mode)";
  1522. if (mode == WASAPIDeviceMode::exclusive) return "Windows Audio (Exclusive Mode)";
  1523. jassertfalse;
  1524. return {};
  1525. }
  1526. //==============================================================================
  1527. JUCE_DECLARE_WEAK_REFERENCEABLE (WASAPIAudioIODeviceType)
  1528. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType)
  1529. };
  1530. //==============================================================================
  1531. struct MMDeviceMasterVolume
  1532. {
  1533. MMDeviceMasterVolume()
  1534. {
  1535. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1536. if (check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1537. {
  1538. ComSmartPtr<IMMDevice> device;
  1539. if (check (enumerator->GetDefaultAudioEndpoint (eRender, eConsole, device.resetAndGetPointerAddress())))
  1540. check (device->Activate (__uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr,
  1541. (void**) endpointVolume.resetAndGetPointerAddress()));
  1542. }
  1543. }
  1544. float getGain() const
  1545. {
  1546. float vol = 0.0f;
  1547. if (endpointVolume != nullptr)
  1548. check (endpointVolume->GetMasterVolumeLevelScalar (&vol));
  1549. return vol;
  1550. }
  1551. bool setGain (float newGain) const
  1552. {
  1553. return endpointVolume != nullptr
  1554. && check (endpointVolume->SetMasterVolumeLevelScalar (jlimit (0.0f, 1.0f, newGain), nullptr));
  1555. }
  1556. bool isMuted() const
  1557. {
  1558. BOOL mute = 0;
  1559. return endpointVolume != nullptr
  1560. && check (endpointVolume->GetMute (&mute)) && mute != 0;
  1561. }
  1562. bool setMuted (bool shouldMute) const
  1563. {
  1564. return endpointVolume != nullptr
  1565. && check (endpointVolume->SetMute (shouldMute, nullptr));
  1566. }
  1567. ComSmartPtr<IAudioEndpointVolume> endpointVolume;
  1568. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MMDeviceMasterVolume)
  1569. };
  1570. }
  1571. //==============================================================================
  1572. #define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
  1573. float JUCE_CALLTYPE SystemAudioVolume::getGain() { return WasapiClasses::MMDeviceMasterVolume().getGain(); }
  1574. bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return WasapiClasses::MMDeviceMasterVolume().setGain (gain); }
  1575. bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return WasapiClasses::MMDeviceMasterVolume().isMuted(); }
  1576. bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return WasapiClasses::MMDeviceMasterVolume().setMuted (mute); }
  1577. } // namespace juce