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.

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