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.

2020 lines
73KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. 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. static void logFailure ([[maybe_unused]] HRESULT hr)
  27. {
  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. static 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. } // namespace juce
  290. #ifdef __CRT_UUID_DECL
  291. __CRT_UUID_DECL (juce::IPropertyStore, 0x886d8eeb, 0x8cf2, 0x4446, 0x8d, 0x02, 0xcd, 0xba, 0x1d, 0xbd, 0xcf, 0x99)
  292. __CRT_UUID_DECL (juce::IMMDevice, 0xD666063F, 0x1587, 0x4E43, 0x81, 0xF1, 0xB9, 0x48, 0xE8, 0x07, 0x36, 0x3F)
  293. __CRT_UUID_DECL (juce::IMMEndpoint, 0x1BE09788, 0x6894, 0x4089, 0x85, 0x86, 0x9A, 0x2A, 0x6C, 0x26, 0x5A, 0xC5)
  294. __CRT_UUID_DECL (juce::IMMNotificationClient, 0x7991EEC9, 0x7E89, 0x4D85, 0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0)
  295. __CRT_UUID_DECL (juce::IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, 0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6)
  296. __CRT_UUID_DECL (juce::MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, 0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E)
  297. __CRT_UUID_DECL (juce::IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4c32, 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2)
  298. __CRT_UUID_DECL (juce::IAudioClient2, 0x726778CD, 0xF60A, 0x4eda, 0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA)
  299. __CRT_UUID_DECL (juce::IAudioClient3, 0x1CB9AD4C, 0xDBFA, 0x4c32, 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2)
  300. __CRT_UUID_DECL (juce::IAudioCaptureClient, 0xC8ADBD64, 0xE71E, 0x48a0, 0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17)
  301. __CRT_UUID_DECL (juce::IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, 0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2)
  302. __CRT_UUID_DECL (juce::IAudioEndpointVolume, 0x5CDF2C82, 0x841E, 0x4546, 0x97, 0x22, 0x0C, 0xF7, 0x40, 0x78, 0x22, 0x9A)
  303. __CRT_UUID_DECL (juce::IAudioSessionEvents, 0x24918ACC, 0x64B3, 0x37C1, 0x8C, 0xA9, 0x74, 0xA6, 0x6E, 0x99, 0x57, 0xA8)
  304. __CRT_UUID_DECL (juce::IAudioSessionControl, 0xF4B1A599, 0x7266, 0x4319, 0xA8, 0xCA, 0xE7, 0x0A, 0xCB, 0x11, 0xE8, 0xCD)
  305. #endif
  306. //==============================================================================
  307. namespace juce
  308. {
  309. namespace WasapiClasses
  310. {
  311. static String getDeviceID (IMMDevice* device)
  312. {
  313. String s;
  314. WCHAR* deviceId = nullptr;
  315. if (check (device->GetId (&deviceId)))
  316. {
  317. s = String (deviceId);
  318. CoTaskMemFree (deviceId);
  319. }
  320. return s;
  321. }
  322. static EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  323. {
  324. EDataFlow flow = eRender;
  325. if (auto endpoint = device.getInterface<IMMEndpoint>())
  326. (void) check (endpoint->GetDataFlow (&flow));
  327. return flow;
  328. }
  329. static int refTimeToSamples (const REFERENCE_TIME& t, double sampleRate) noexcept
  330. {
  331. return roundToInt (sampleRate * ((double) t) * 0.0000001);
  332. }
  333. static REFERENCE_TIME samplesToRefTime (int numSamples, double sampleRate) noexcept
  334. {
  335. return (REFERENCE_TIME) ((numSamples * 10000.0 * 1000.0 / sampleRate) + 0.5);
  336. }
  337. static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* src) noexcept
  338. {
  339. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  340. : sizeof (WAVEFORMATEX));
  341. }
  342. static bool isExclusiveMode (WASAPIDeviceMode deviceMode) noexcept
  343. {
  344. return deviceMode == WASAPIDeviceMode::exclusive;
  345. }
  346. static bool isLowLatencyMode (WASAPIDeviceMode deviceMode) noexcept
  347. {
  348. return deviceMode == WASAPIDeviceMode::sharedLowLatency;
  349. }
  350. static bool supportsSampleRateConversion (WASAPIDeviceMode deviceMode) noexcept
  351. {
  352. return deviceMode == WASAPIDeviceMode::shared;
  353. }
  354. //==============================================================================
  355. class WASAPIDeviceBase
  356. {
  357. public:
  358. WASAPIDeviceBase (const ComSmartPtr<IMMDevice>& d, WASAPIDeviceMode mode)
  359. : device (d),
  360. deviceMode (mode)
  361. {
  362. clientEvent = CreateEvent (nullptr, false, false, nullptr);
  363. ComSmartPtr<IAudioClient> tempClient (createClient());
  364. if (tempClient == nullptr)
  365. return;
  366. auto format = getClientMixFormat (tempClient);
  367. if (! format)
  368. return;
  369. defaultNumChannels = maxNumChannels = format->Format.nChannels;
  370. defaultSampleRate = format->Format.nSamplesPerSec;
  371. rates.addUsingDefaultSort (defaultSampleRate);
  372. defaultFormatChannelMask = format->dwChannelMask;
  373. if (isExclusiveMode (deviceMode))
  374. if (auto optFormat = findSupportedFormat (tempClient, defaultNumChannels, defaultSampleRate))
  375. format = optFormat;
  376. querySupportedBufferSizes (*format, tempClient);
  377. querySupportedSampleRates (*format, tempClient);
  378. maxNumChannels = queryMaxNumChannels (tempClient);
  379. }
  380. virtual ~WASAPIDeviceBase()
  381. {
  382. device = nullptr;
  383. CloseHandle (clientEvent);
  384. }
  385. bool isOk() const noexcept { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  386. bool openClient (const double newSampleRate, const BigInteger& newChannels, const int bufferSizeSamples)
  387. {
  388. sampleRate = newSampleRate;
  389. channels = newChannels;
  390. channels.setRange (maxNumChannels, channels.getHighestBit() + 1 - maxNumChannels, false);
  391. numChannels = channels.getHighestBit() + 1;
  392. if (numChannels == 0)
  393. return true;
  394. client = createClient();
  395. if (client != nullptr
  396. && tryInitialisingWithBufferSize (bufferSizeSamples))
  397. {
  398. sampleRateHasChanged = false;
  399. shouldShutdown = false;
  400. channelMaps.clear();
  401. for (int i = 0; i <= channels.getHighestBit(); ++i)
  402. if (channels[i])
  403. channelMaps.add (i);
  404. REFERENCE_TIME latency;
  405. if (check (client->GetStreamLatency (&latency)))
  406. latencySamples = refTimeToSamples (latency, sampleRate);
  407. (void) check (client->GetBufferSize (&actualBufferSize));
  408. createSessionEventCallback();
  409. return check (client->SetEventHandle (clientEvent));
  410. }
  411. return false;
  412. }
  413. void closeClient()
  414. {
  415. if (client != nullptr)
  416. client->Stop();
  417. // N.B. this is needed to prevent a double-deletion of the IAudioSessionEvents object
  418. // on older versions of Windows
  419. Thread::sleep (5);
  420. deleteSessionEventCallback();
  421. client = nullptr;
  422. ResetEvent (clientEvent);
  423. }
  424. void deviceSampleRateChanged()
  425. {
  426. sampleRateHasChanged = true;
  427. }
  428. void deviceSessionBecameInactive()
  429. {
  430. isActive = false;
  431. }
  432. void deviceSessionExpired()
  433. {
  434. shouldShutdown = true;
  435. }
  436. void deviceSessionBecameActive()
  437. {
  438. isActive = true;
  439. }
  440. //==============================================================================
  441. ComSmartPtr<IMMDevice> device;
  442. ComSmartPtr<IAudioClient> client;
  443. WASAPIDeviceMode deviceMode;
  444. double sampleRate = 0, defaultSampleRate = 0;
  445. int numChannels = 0, actualNumChannels = 0, maxNumChannels = 0, defaultNumChannels = 0;
  446. int minBufferSize = 0, defaultBufferSize = 0, latencySamples = 0;
  447. int lowLatencyBufferSizeMultiple = 0, lowLatencyMaxBufferSize = 0;
  448. DWORD defaultFormatChannelMask = 0;
  449. Array<double> rates;
  450. HANDLE clientEvent = {};
  451. BigInteger channels;
  452. Array<int> channelMaps;
  453. UINT32 actualBufferSize = 0;
  454. int bytesPerSample = 0, bytesPerFrame = 0;
  455. std::atomic<bool> sampleRateHasChanged { false }, shouldShutdown { false }, isActive { true };
  456. virtual void updateFormat (bool isFloat) = 0;
  457. private:
  458. //==============================================================================
  459. struct SessionEventCallback : public ComBaseClassHelper<IAudioSessionEvents>
  460. {
  461. SessionEventCallback (WASAPIDeviceBase& d) : owner (d) {}
  462. JUCE_COMRESULT OnDisplayNameChanged (LPCWSTR, LPCGUID) { return S_OK; }
  463. JUCE_COMRESULT OnIconPathChanged (LPCWSTR, LPCGUID) { return S_OK; }
  464. JUCE_COMRESULT OnSimpleVolumeChanged (float, BOOL, LPCGUID) { return S_OK; }
  465. JUCE_COMRESULT OnChannelVolumeChanged (DWORD, float*, DWORD, LPCGUID) { return S_OK; }
  466. JUCE_COMRESULT OnGroupingParamChanged (LPCGUID, LPCGUID) { return S_OK; }
  467. JUCE_COMRESULT OnStateChanged (AudioSessionState state)
  468. {
  469. switch (state)
  470. {
  471. case AudioSessionStateInactive:
  472. owner.deviceSessionBecameInactive();
  473. break;
  474. case AudioSessionStateExpired:
  475. owner.deviceSessionExpired();
  476. break;
  477. case AudioSessionStateActive:
  478. owner.deviceSessionBecameActive();
  479. break;
  480. }
  481. return S_OK;
  482. }
  483. JUCE_COMRESULT OnSessionDisconnected (AudioSessionDisconnectReason reason)
  484. {
  485. if (reason == DisconnectReasonFormatChanged)
  486. owner.deviceSampleRateChanged();
  487. return S_OK;
  488. }
  489. WASAPIDeviceBase& owner;
  490. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionEventCallback)
  491. };
  492. ComSmartPtr<IAudioSessionControl> audioSessionControl;
  493. ComSmartPtr<SessionEventCallback> sessionEventCallback;
  494. void createSessionEventCallback()
  495. {
  496. deleteSessionEventCallback();
  497. client->GetService (__uuidof (IAudioSessionControl),
  498. (void**) audioSessionControl.resetAndGetPointerAddress());
  499. if (audioSessionControl != nullptr)
  500. {
  501. sessionEventCallback = new SessionEventCallback (*this);
  502. audioSessionControl->RegisterAudioSessionNotification (sessionEventCallback);
  503. sessionEventCallback->Release(); // (required because ComBaseClassHelper objects are constructed with a ref count of 1)
  504. }
  505. }
  506. void deleteSessionEventCallback()
  507. {
  508. if (audioSessionControl != nullptr && sessionEventCallback != nullptr)
  509. audioSessionControl->UnregisterAudioSessionNotification (sessionEventCallback);
  510. audioSessionControl = nullptr;
  511. sessionEventCallback = nullptr;
  512. }
  513. //==============================================================================
  514. ComSmartPtr<IAudioClient> createClient()
  515. {
  516. ComSmartPtr<IAudioClient> newClient;
  517. if (device != nullptr)
  518. logFailure (device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER,
  519. nullptr, (void**) newClient.resetAndGetPointerAddress()));
  520. return newClient;
  521. }
  522. static std::optional<WAVEFORMATEXTENSIBLE> getClientMixFormat (ComSmartPtr<IAudioClient>& client)
  523. {
  524. WAVEFORMATEX* mixFormat = nullptr;
  525. if (! check (client->GetMixFormat (&mixFormat)))
  526. return {};
  527. WAVEFORMATEXTENSIBLE format;
  528. copyWavFormat (format, mixFormat);
  529. CoTaskMemFree (mixFormat);
  530. return format;
  531. }
  532. //==============================================================================
  533. void querySupportedBufferSizes (WAVEFORMATEXTENSIBLE format, ComSmartPtr<IAudioClient>& audioClient)
  534. {
  535. if (isLowLatencyMode (deviceMode))
  536. {
  537. if (auto audioClient3 = audioClient.getInterface<IAudioClient3>())
  538. {
  539. UINT32 defaultPeriod = 0, fundamentalPeriod = 0, minPeriod = 0, maxPeriod = 0;
  540. if (check (audioClient3->GetSharedModeEnginePeriod ((WAVEFORMATEX*) &format,
  541. &defaultPeriod,
  542. &fundamentalPeriod,
  543. &minPeriod,
  544. &maxPeriod)))
  545. {
  546. minBufferSize = (int) minPeriod;
  547. defaultBufferSize = (int) defaultPeriod;
  548. lowLatencyMaxBufferSize = (int) maxPeriod;
  549. lowLatencyBufferSizeMultiple = (int) fundamentalPeriod;
  550. }
  551. }
  552. }
  553. else
  554. {
  555. REFERENCE_TIME defaultPeriod, minPeriod;
  556. if (! check (audioClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  557. return;
  558. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  559. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  560. }
  561. }
  562. void querySupportedSampleRates (WAVEFORMATEXTENSIBLE format, ComSmartPtr<IAudioClient>& audioClient)
  563. {
  564. for (auto rate : SampleRateHelpers::getAllSampleRates())
  565. {
  566. if (rates.contains (rate))
  567. continue;
  568. format.Format.nSamplesPerSec = (DWORD) rate;
  569. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nChannels * format.Format.wBitsPerSample / 8);
  570. WAVEFORMATEX* nearestFormat = nullptr;
  571. if (SUCCEEDED (audioClient->IsFormatSupported (isExclusiveMode (deviceMode) ? AUDCLNT_SHAREMODE_EXCLUSIVE
  572. : AUDCLNT_SHAREMODE_SHARED,
  573. (WAVEFORMATEX*) &format,
  574. isExclusiveMode (deviceMode) ? nullptr
  575. : &nearestFormat)))
  576. {
  577. if (nearestFormat != nullptr)
  578. rate = (double) nearestFormat->nSamplesPerSec;
  579. if (! rates.contains (rate))
  580. rates.addUsingDefaultSort (rate);
  581. }
  582. CoTaskMemFree (nearestFormat);
  583. }
  584. }
  585. struct AudioSampleFormat
  586. {
  587. bool useFloat;
  588. int bitsPerSampleToTry;
  589. int bytesPerSampleContainer;
  590. };
  591. static constexpr AudioSampleFormat formatsToTry[] =
  592. {
  593. { true, 32, 4 },
  594. { false, 32, 4 },
  595. { false, 24, 4 },
  596. { false, 24, 3 },
  597. { false, 20, 4 },
  598. { false, 20, 3 },
  599. { false, 16, 2 }
  600. };
  601. static std::optional<WAVEFORMATEXTENSIBLE> tryFormat (const AudioSampleFormat sampleFormat, IAudioClient* clientToUse,
  602. WASAPIDeviceMode mode, int newNumChannels, double newSampleRate,
  603. DWORD newMixFormatChannelMask)
  604. {
  605. WAVEFORMATEXTENSIBLE format;
  606. zerostruct (format);
  607. if (newNumChannels <= 2 && sampleFormat.bitsPerSampleToTry <= 16)
  608. {
  609. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  610. }
  611. else
  612. {
  613. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  614. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  615. }
  616. format.Format.nSamplesPerSec = (DWORD) newSampleRate;
  617. format.Format.nChannels = (WORD) newNumChannels;
  618. format.Format.wBitsPerSample = (WORD) (8 * sampleFormat.bytesPerSampleContainer);
  619. format.Samples.wValidBitsPerSample = (WORD) (sampleFormat.bitsPerSampleToTry);
  620. format.Format.nBlockAlign = (WORD) (format.Format.nChannels * format.Format.wBitsPerSample / 8);
  621. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nBlockAlign);
  622. format.SubFormat = sampleFormat.useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  623. format.dwChannelMask = newMixFormatChannelMask;
  624. WAVEFORMATEX* nearestFormat = nullptr;
  625. HRESULT hr = clientToUse->IsFormatSupported (isExclusiveMode (mode) ? AUDCLNT_SHAREMODE_EXCLUSIVE
  626. : AUDCLNT_SHAREMODE_SHARED,
  627. (WAVEFORMATEX*) &format,
  628. isExclusiveMode (mode) ? nullptr
  629. : &nearestFormat);
  630. logFailure (hr);
  631. auto supportsSRC = supportsSampleRateConversion (mode);
  632. if (hr == S_FALSE
  633. && nearestFormat != nullptr
  634. && (format.Format.nSamplesPerSec == nearestFormat->nSamplesPerSec
  635. || supportsSRC))
  636. {
  637. copyWavFormat (format, nearestFormat);
  638. if (supportsSRC)
  639. {
  640. format.Format.nSamplesPerSec = (DWORD) newSampleRate;
  641. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nBlockAlign);
  642. }
  643. hr = S_OK;
  644. }
  645. CoTaskMemFree (nearestFormat);
  646. if (hr != S_OK)
  647. return {};
  648. return format;
  649. }
  650. std::optional<WAVEFORMATEXTENSIBLE> findSupportedFormat (IAudioClient* clientToUse, int newNumChannels, double newSampleRate) const
  651. {
  652. for (auto ch = newNumChannels; ch <= maxNumChannels; ++ch)
  653. {
  654. auto maskWithLowestNBitsSet = static_cast<DWORD> ((1 << ch) - 1);
  655. auto mixFormatChannelMask = (ch == defaultNumChannels ? defaultFormatChannelMask : maskWithLowestNBitsSet);
  656. for (auto const& sampleFormat: formatsToTry)
  657. if (auto format = tryFormat (sampleFormat, clientToUse, deviceMode, ch, newSampleRate, mixFormatChannelMask))
  658. return format;
  659. }
  660. return {};
  661. }
  662. int queryMaxNumChannels (IAudioClient* clientToUse) const
  663. {
  664. static constexpr auto maxNumChannelsToQuery = static_cast<int> (AudioChannelSet::maxChannelsOfNamedLayout);
  665. const auto fallbackNumChannels = defaultNumChannels;
  666. if (fallbackNumChannels >= maxNumChannelsToQuery)
  667. return fallbackNumChannels;
  668. auto result = fallbackNumChannels;
  669. for (auto ch = maxNumChannelsToQuery; ch > result; --ch)
  670. {
  671. auto channelMask = static_cast<DWORD> ((1 << ch) - 1);
  672. for (auto rate : rates)
  673. for (auto const& sampleFormat: formatsToTry)
  674. if (auto format = tryFormat (sampleFormat, clientToUse, deviceMode, ch, rate, channelMask))
  675. result = jmax (static_cast<int> (format->Format.nChannels), result);
  676. }
  677. return result;
  678. }
  679. DWORD getStreamFlags()
  680. {
  681. DWORD streamFlags = 0x40000; /*AUDCLNT_STREAMFLAGS_EVENTCALLBACK*/
  682. if (supportsSampleRateConversion (deviceMode))
  683. streamFlags |= (0x80000000 /*AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM*/
  684. | 0x8000000); /*AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY*/
  685. return streamFlags;
  686. }
  687. bool initialiseLowLatencyClient (int bufferSizeSamples, WAVEFORMATEXTENSIBLE format)
  688. {
  689. if (auto audioClient3 = client.getInterface<IAudioClient3>())
  690. return check (audioClient3->InitializeSharedAudioStream (getStreamFlags(),
  691. (UINT32) bufferSizeSamples,
  692. (WAVEFORMATEX*) &format,
  693. nullptr));
  694. return false;
  695. }
  696. bool initialiseStandardClient (int bufferSizeSamples, WAVEFORMATEXTENSIBLE format)
  697. {
  698. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  699. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  700. if (isExclusiveMode (deviceMode) && bufferSizeSamples > 0)
  701. defaultPeriod = jmax (minPeriod, samplesToRefTime (bufferSizeSamples, format.Format.nSamplesPerSec));
  702. for (;;)
  703. {
  704. GUID session;
  705. auto hr = client->Initialize (isExclusiveMode (deviceMode) ? AUDCLNT_SHAREMODE_EXCLUSIVE
  706. : AUDCLNT_SHAREMODE_SHARED,
  707. getStreamFlags(),
  708. defaultPeriod,
  709. isExclusiveMode (deviceMode) ? defaultPeriod : 0,
  710. (WAVEFORMATEX*) &format,
  711. &session);
  712. if (check (hr))
  713. return true;
  714. // Handle the "alignment dance" : http://msdn.microsoft.com/en-us/library/windows/desktop/dd370875(v=vs.85).aspx (see Remarks)
  715. if (hr != MAKE_HRESULT (1, 0x889, 0x19)) // AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
  716. break;
  717. UINT32 numFrames = 0;
  718. if (! check (client->GetBufferSize (&numFrames)))
  719. break;
  720. // Recreate client
  721. client = nullptr;
  722. client = createClient();
  723. defaultPeriod = samplesToRefTime ((int) numFrames, format.Format.nSamplesPerSec);
  724. }
  725. return false;
  726. }
  727. bool tryInitialisingWithBufferSize (int bufferSizeSamples)
  728. {
  729. if (auto format = findSupportedFormat (client, numChannels, sampleRate))
  730. {
  731. auto isInitialised = isLowLatencyMode (deviceMode) ? initialiseLowLatencyClient (bufferSizeSamples, *format)
  732. : initialiseStandardClient (bufferSizeSamples, *format);
  733. if (isInitialised)
  734. {
  735. actualNumChannels = format->Format.nChannels;
  736. const bool isFloat = format->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  737. bytesPerSample = format->Format.wBitsPerSample / 8;
  738. bytesPerFrame = format->Format.nBlockAlign;
  739. updateFormat (isFloat);
  740. return true;
  741. }
  742. }
  743. return false;
  744. }
  745. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase)
  746. };
  747. //==============================================================================
  748. class WASAPIInputDevice : public WASAPIDeviceBase
  749. {
  750. public:
  751. WASAPIInputDevice (const ComSmartPtr<IMMDevice>& d, WASAPIDeviceMode mode)
  752. : WASAPIDeviceBase (d, mode)
  753. {
  754. }
  755. ~WASAPIInputDevice() override
  756. {
  757. close();
  758. }
  759. bool open (double newSampleRate, const BigInteger& newChannels, int bufferSizeSamples)
  760. {
  761. return openClient (newSampleRate, newChannels, bufferSizeSamples)
  762. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  763. (void**) captureClient.resetAndGetPointerAddress())));
  764. }
  765. void close()
  766. {
  767. closeClient();
  768. captureClient = nullptr;
  769. reservoir.reset();
  770. queue = SingleThreadedAbstractFifo();
  771. }
  772. template <class SourceType>
  773. void updateFormatWithType (SourceType*) noexcept
  774. {
  775. using NativeType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  776. converter.reset (new AudioData::ConverterInstance<AudioData::Pointer<SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1));
  777. }
  778. void updateFormat (bool isFloat) override
  779. {
  780. if (isFloat) updateFormatWithType ((AudioData::Float32*) nullptr);
  781. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) nullptr);
  782. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) nullptr);
  783. else updateFormatWithType ((AudioData::Int16*) nullptr);
  784. }
  785. bool start (int userBufferSizeIn)
  786. {
  787. const auto reservoirSize = nextPowerOfTwo ((int) (actualBufferSize + (UINT32) userBufferSizeIn));
  788. queue = SingleThreadedAbstractFifo (reservoirSize);
  789. reservoir.setSize ((size_t) (queue.getSize() * bytesPerFrame), true);
  790. xruns = 0;
  791. if (! check (client->Start()))
  792. return false;
  793. purgeInputBuffers();
  794. isActive = true;
  795. return true;
  796. }
  797. void purgeInputBuffers()
  798. {
  799. uint8* inputData;
  800. UINT32 numSamplesAvailable;
  801. DWORD flags;
  802. while (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, nullptr, nullptr) != MAKE_HRESULT (0, 0x889, 0x1) /* AUDCLNT_S_BUFFER_EMPTY */)
  803. captureClient->ReleaseBuffer (numSamplesAvailable);
  804. }
  805. int getNumSamplesInReservoir() const noexcept { return queue.getNumReadable(); }
  806. void handleDeviceBuffer()
  807. {
  808. if (numChannels <= 0)
  809. return;
  810. uint8* inputData = nullptr;
  811. UINT32 numSamplesAvailable = 0;
  812. DWORD flags = 0;
  813. while (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, nullptr, nullptr)) && numSamplesAvailable > 0)
  814. {
  815. if ((flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0)
  816. xruns++;
  817. if (numSamplesAvailable > (UINT32) queue.getRemainingSpace())
  818. {
  819. captureClient->ReleaseBuffer (0);
  820. return;
  821. }
  822. auto offset = 0;
  823. for (const auto& block : queue.write ((int) numSamplesAvailable))
  824. {
  825. const auto samplesToDoBytes = block.getLength() * bytesPerFrame;
  826. auto* reservoirPtr = addBytesToPointer (reservoir.getData(), block.getStart() * bytesPerFrame);
  827. if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0)
  828. zeromem (reservoirPtr, (size_t) samplesToDoBytes);
  829. else
  830. memcpy (reservoirPtr, inputData + offset * bytesPerFrame, (size_t) samplesToDoBytes);
  831. offset += block.getLength();
  832. }
  833. captureClient->ReleaseBuffer (numSamplesAvailable);
  834. }
  835. }
  836. void copyBuffersFromReservoir (float* const* destBuffers, const int numDestBuffers, const int bufferSize)
  837. {
  838. if ((numChannels <= 0 && bufferSize == 0) || reservoir.isEmpty())
  839. return;
  840. auto offset = jmax (0, bufferSize - queue.getNumReadable());
  841. if (offset > 0)
  842. for (int i = 0; i < numDestBuffers; ++i)
  843. zeromem (destBuffers[i], (size_t) offset * sizeof (float));
  844. for (const auto& block : queue.read (jmin (queue.getNumReadable(), bufferSize)))
  845. {
  846. for (auto i = 0; i < numDestBuffers; ++i)
  847. converter->convertSamples (destBuffers[i] + offset,
  848. 0,
  849. addBytesToPointer (reservoir.getData(), block.getStart() * bytesPerFrame),
  850. channelMaps.getUnchecked (i),
  851. block.getLength());
  852. offset += block.getLength();
  853. }
  854. }
  855. ComSmartPtr<IAudioCaptureClient> captureClient;
  856. MemoryBlock reservoir;
  857. SingleThreadedAbstractFifo queue;
  858. int xruns = 0;
  859. std::unique_ptr<AudioData::Converter> converter;
  860. private:
  861. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice)
  862. };
  863. //==============================================================================
  864. class WASAPIOutputDevice : public WASAPIDeviceBase
  865. {
  866. public:
  867. WASAPIOutputDevice (const ComSmartPtr<IMMDevice>& d, WASAPIDeviceMode mode)
  868. : WASAPIDeviceBase (d, mode)
  869. {
  870. }
  871. ~WASAPIOutputDevice() override
  872. {
  873. close();
  874. }
  875. bool open (double newSampleRate, const BigInteger& newChannels, int bufferSizeSamples)
  876. {
  877. return openClient (newSampleRate, newChannels, bufferSizeSamples)
  878. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient),
  879. (void**) renderClient.resetAndGetPointerAddress())));
  880. }
  881. void close()
  882. {
  883. closeClient();
  884. renderClient = nullptr;
  885. }
  886. template <class DestType>
  887. void updateFormatWithType (DestType*)
  888. {
  889. using NativeType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  890. converter.reset (new AudioData::ConverterInstance<NativeType, AudioData::Pointer<DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst>> (1, actualNumChannels));
  891. }
  892. void updateFormat (bool isFloat) override
  893. {
  894. if (isFloat) updateFormatWithType ((AudioData::Float32*) nullptr);
  895. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) nullptr);
  896. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) nullptr);
  897. else updateFormatWithType ((AudioData::Int16*) nullptr);
  898. }
  899. bool start()
  900. {
  901. auto samplesToDo = getNumSamplesAvailableToCopy();
  902. uint8* outputData;
  903. if (check (renderClient->GetBuffer ((UINT32) samplesToDo, &outputData)))
  904. renderClient->ReleaseBuffer ((UINT32) samplesToDo, AUDCLNT_BUFFERFLAGS_SILENT);
  905. if (! check (client->Start()))
  906. return false;
  907. isActive = true;
  908. return true;
  909. }
  910. int getNumSamplesAvailableToCopy() const
  911. {
  912. if (numChannels <= 0)
  913. return 0;
  914. if (! isExclusiveMode (deviceMode))
  915. {
  916. UINT32 padding = 0;
  917. if (check (client->GetCurrentPadding (&padding)))
  918. return (int) actualBufferSize - (int) padding;
  919. }
  920. return (int) actualBufferSize;
  921. }
  922. void copyBuffers (const float* const* srcBuffers, int numSrcBuffers, int bufferSize,
  923. WASAPIInputDevice* inputDevice, Thread& thread)
  924. {
  925. if (numChannels <= 0)
  926. return;
  927. int offset = 0;
  928. while (bufferSize > 0)
  929. {
  930. // This is needed in order not to drop any input data if the output device endpoint buffer was full
  931. if ((! isExclusiveMode (deviceMode)) && inputDevice != nullptr
  932. && WaitForSingleObject (inputDevice->clientEvent, 0) == WAIT_OBJECT_0)
  933. inputDevice->handleDeviceBuffer();
  934. int samplesToDo = jmin (getNumSamplesAvailableToCopy(), bufferSize);
  935. if (samplesToDo == 0)
  936. {
  937. // This can ONLY occur in non-exclusive mode
  938. if (! thread.threadShouldExit() && WaitForSingleObject (clientEvent, 1000) == WAIT_OBJECT_0)
  939. continue;
  940. break;
  941. }
  942. if (isExclusiveMode (deviceMode) && WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  943. break;
  944. uint8* outputData = nullptr;
  945. if (check (renderClient->GetBuffer ((UINT32) samplesToDo, &outputData)))
  946. {
  947. for (int i = 0; i < numSrcBuffers; ++i)
  948. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  949. renderClient->ReleaseBuffer ((UINT32) samplesToDo, 0);
  950. }
  951. bufferSize -= samplesToDo;
  952. offset += samplesToDo;
  953. }
  954. }
  955. ComSmartPtr<IAudioRenderClient> renderClient;
  956. std::unique_ptr<AudioData::Converter> converter;
  957. private:
  958. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice)
  959. };
  960. //==============================================================================
  961. class WASAPIAudioIODevice : public AudioIODevice,
  962. public Thread,
  963. private AsyncUpdater
  964. {
  965. public:
  966. WASAPIAudioIODevice (const String& deviceName,
  967. const String& typeNameIn,
  968. const String& outputDeviceID,
  969. const String& inputDeviceID,
  970. WASAPIDeviceMode mode)
  971. : AudioIODevice (deviceName, typeNameIn),
  972. Thread ("JUCE WASAPI"),
  973. outputDeviceId (outputDeviceID),
  974. inputDeviceId (inputDeviceID),
  975. deviceMode (mode)
  976. {
  977. }
  978. ~WASAPIAudioIODevice() override
  979. {
  980. cancelPendingUpdate();
  981. close();
  982. }
  983. bool initialise()
  984. {
  985. latencyIn = latencyOut = 0;
  986. Array<double> ratesIn, ratesOut;
  987. if (createDevices())
  988. {
  989. jassert (inputDevice != nullptr || outputDevice != nullptr);
  990. sampleRates.clear();
  991. if (inputDevice != nullptr && outputDevice != nullptr)
  992. {
  993. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  994. minBufferSize = jmax (inputDevice->minBufferSize, outputDevice->minBufferSize);
  995. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  996. if (isLowLatencyMode (deviceMode))
  997. {
  998. lowLatencyMaxBufferSize = jmin (inputDevice->lowLatencyMaxBufferSize, outputDevice->lowLatencyMaxBufferSize);
  999. lowLatencyBufferSizeMultiple = jmax (inputDevice->lowLatencyBufferSizeMultiple, outputDevice->lowLatencyBufferSizeMultiple);
  1000. }
  1001. sampleRates.addArray (inputDevice->rates);
  1002. if (supportsSampleRateConversion (deviceMode))
  1003. {
  1004. for (auto r : outputDevice->rates)
  1005. if (! sampleRates.contains (r))
  1006. sampleRates.addUsingDefaultSort (r);
  1007. }
  1008. else
  1009. {
  1010. sampleRates.removeValuesNotIn (outputDevice->rates);
  1011. }
  1012. }
  1013. else
  1014. {
  1015. auto* d = inputDevice != nullptr ? static_cast<WASAPIDeviceBase*> (inputDevice.get())
  1016. : static_cast<WASAPIDeviceBase*> (outputDevice.get());
  1017. defaultSampleRate = d->defaultSampleRate;
  1018. minBufferSize = d->minBufferSize;
  1019. defaultBufferSize = d->defaultBufferSize;
  1020. if (isLowLatencyMode (deviceMode))
  1021. {
  1022. lowLatencyMaxBufferSize = d->lowLatencyMaxBufferSize;
  1023. lowLatencyBufferSizeMultiple = d->lowLatencyBufferSizeMultiple;
  1024. }
  1025. sampleRates = d->rates;
  1026. }
  1027. bufferSizes.clear();
  1028. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  1029. if (minBufferSize != defaultBufferSize)
  1030. bufferSizes.addUsingDefaultSort (minBufferSize);
  1031. if (isLowLatencyMode (deviceMode))
  1032. {
  1033. auto size = minBufferSize;
  1034. while (size < lowLatencyMaxBufferSize)
  1035. {
  1036. size += lowLatencyBufferSizeMultiple;
  1037. if (! bufferSizes.contains (size))
  1038. bufferSizes.addUsingDefaultSort (size);
  1039. }
  1040. }
  1041. else
  1042. {
  1043. int n = 64;
  1044. for (int i = 0; i < 40; ++i)
  1045. {
  1046. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  1047. bufferSizes.addUsingDefaultSort (n);
  1048. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  1049. }
  1050. }
  1051. return true;
  1052. }
  1053. return false;
  1054. }
  1055. StringArray getOutputChannelNames() override
  1056. {
  1057. StringArray outChannels;
  1058. if (outputDevice != nullptr)
  1059. for (int i = 1; i <= outputDevice->maxNumChannels; ++i)
  1060. outChannels.add ("Output channel " + String (i));
  1061. return outChannels;
  1062. }
  1063. StringArray getInputChannelNames() override
  1064. {
  1065. StringArray inChannels;
  1066. if (inputDevice != nullptr)
  1067. for (int i = 1; i <= inputDevice->maxNumChannels; ++i)
  1068. inChannels.add ("Input channel " + String (i));
  1069. return inChannels;
  1070. }
  1071. Array<double> getAvailableSampleRates() override { return sampleRates; }
  1072. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  1073. int getDefaultBufferSize() override { return defaultBufferSize; }
  1074. int getCurrentBufferSizeSamples() override { return currentBufferSizeSamples; }
  1075. double getCurrentSampleRate() override { return currentSampleRate; }
  1076. int getCurrentBitDepth() override { return 32; }
  1077. int getOutputLatencyInSamples() override { return latencyOut; }
  1078. int getInputLatencyInSamples() override { return latencyIn; }
  1079. BigInteger getActiveOutputChannels() const override { return outputDevice != nullptr ? outputDevice->channels : BigInteger(); }
  1080. BigInteger getActiveInputChannels() const override { return inputDevice != nullptr ? inputDevice->channels : BigInteger(); }
  1081. String getLastError() override { return lastError; }
  1082. int getXRunCount() const noexcept override { return inputDevice != nullptr ? inputDevice->xruns : -1; }
  1083. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  1084. double sampleRate, int bufferSizeSamples) override
  1085. {
  1086. close();
  1087. lastError.clear();
  1088. if (sampleRates.size() == 0 && inputDevice != nullptr && outputDevice != nullptr)
  1089. {
  1090. lastError = TRANS("The input and output devices don't share a common sample rate!");
  1091. return lastError;
  1092. }
  1093. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  1094. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  1095. lastKnownInputChannels = inputChannels;
  1096. lastKnownOutputChannels = outputChannels;
  1097. if (inputDevice != nullptr && ! inputDevice->open (currentSampleRate, inputChannels, bufferSizeSamples))
  1098. {
  1099. lastError = TRANS("Couldn't open the input device!");
  1100. return lastError;
  1101. }
  1102. if (outputDevice != nullptr && ! outputDevice->open (currentSampleRate, outputChannels, bufferSizeSamples))
  1103. {
  1104. close();
  1105. lastError = TRANS("Couldn't open the output device!");
  1106. return lastError;
  1107. }
  1108. if (isExclusiveMode (deviceMode))
  1109. {
  1110. // This is to make sure that the callback uses actualBufferSize in case of exclusive mode
  1111. if (inputDevice != nullptr && outputDevice != nullptr && inputDevice->actualBufferSize != outputDevice->actualBufferSize)
  1112. {
  1113. close();
  1114. lastError = TRANS("Couldn't open the output device (buffer size mismatch)");
  1115. return lastError;
  1116. }
  1117. currentBufferSizeSamples = (int) (outputDevice != nullptr ? outputDevice->actualBufferSize
  1118. : inputDevice->actualBufferSize);
  1119. }
  1120. if (inputDevice != nullptr) ResetEvent (inputDevice->clientEvent);
  1121. if (outputDevice != nullptr) ResetEvent (outputDevice->clientEvent);
  1122. shouldShutdown = false;
  1123. deviceSampleRateChanged = false;
  1124. startThread (Priority::high);
  1125. Thread::sleep (5);
  1126. if (inputDevice != nullptr && inputDevice->client != nullptr)
  1127. {
  1128. latencyIn = (int) (inputDevice->latencySamples + currentBufferSizeSamples);
  1129. if (! inputDevice->start (currentBufferSizeSamples))
  1130. {
  1131. close();
  1132. lastError = TRANS("Couldn't start the input device!");
  1133. return lastError;
  1134. }
  1135. }
  1136. if (outputDevice != nullptr && outputDevice->client != nullptr)
  1137. {
  1138. latencyOut = (int) (outputDevice->latencySamples + currentBufferSizeSamples);
  1139. if (! outputDevice->start())
  1140. {
  1141. close();
  1142. lastError = TRANS("Couldn't start the output device!");
  1143. return lastError;
  1144. }
  1145. }
  1146. isOpen_ = true;
  1147. return lastError;
  1148. }
  1149. void close() override
  1150. {
  1151. stop();
  1152. signalThreadShouldExit();
  1153. if (inputDevice != nullptr) SetEvent (inputDevice->clientEvent);
  1154. if (outputDevice != nullptr) SetEvent (outputDevice->clientEvent);
  1155. stopThread (5000);
  1156. if (inputDevice != nullptr) inputDevice->close();
  1157. if (outputDevice != nullptr) outputDevice->close();
  1158. isOpen_ = false;
  1159. }
  1160. bool isOpen() override { return isOpen_ && isThreadRunning(); }
  1161. bool isPlaying() override { return isStarted && isOpen_ && isThreadRunning(); }
  1162. void start (AudioIODeviceCallback* call) override
  1163. {
  1164. if (isOpen_ && call != nullptr && ! isStarted)
  1165. {
  1166. if (! isThreadRunning())
  1167. {
  1168. // something's gone wrong and the thread's stopped..
  1169. isOpen_ = false;
  1170. return;
  1171. }
  1172. call->audioDeviceAboutToStart (this);
  1173. const ScopedLock sl (startStopLock);
  1174. callback = call;
  1175. isStarted = true;
  1176. }
  1177. }
  1178. void stop() override
  1179. {
  1180. if (isStarted)
  1181. {
  1182. auto* callbackLocal = callback;
  1183. {
  1184. const ScopedLock sl (startStopLock);
  1185. isStarted = false;
  1186. }
  1187. if (callbackLocal != nullptr)
  1188. callbackLocal->audioDeviceStopped();
  1189. }
  1190. }
  1191. void setMMThreadPriority()
  1192. {
  1193. DynamicLibrary dll ("avrt.dll");
  1194. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, (LPCWSTR, LPDWORD))
  1195. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, (HANDLE, AVRT_PRIORITY))
  1196. if (avSetMmThreadCharacteristics != nullptr && avSetMmThreadPriority != nullptr)
  1197. {
  1198. DWORD dummy = 0;
  1199. if (auto h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy))
  1200. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  1201. }
  1202. }
  1203. void run() override
  1204. {
  1205. setMMThreadPriority();
  1206. auto bufferSize = currentBufferSizeSamples;
  1207. auto numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  1208. auto numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  1209. AudioBuffer<float> ins (jmax (1, numInputBuffers), bufferSize + 32);
  1210. AudioBuffer<float> outs (jmax (1, numOutputBuffers), bufferSize + 32);
  1211. auto inputBuffers = ins.getArrayOfWritePointers();
  1212. auto outputBuffers = outs.getArrayOfWritePointers();
  1213. ins.clear();
  1214. outs.clear();
  1215. while (! threadShouldExit())
  1216. {
  1217. if ((outputDevice != nullptr && outputDevice->shouldShutdown)
  1218. || (inputDevice != nullptr && inputDevice->shouldShutdown))
  1219. {
  1220. shouldShutdown = true;
  1221. triggerAsyncUpdate();
  1222. break;
  1223. }
  1224. auto inputDeviceActive = (inputDevice != nullptr && inputDevice->isActive);
  1225. auto outputDeviceActive = (outputDevice != nullptr && outputDevice->isActive);
  1226. if (! inputDeviceActive && ! outputDeviceActive)
  1227. continue;
  1228. if (inputDeviceActive)
  1229. {
  1230. if (outputDevice == nullptr)
  1231. {
  1232. if (WaitForSingleObject (inputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  1233. break;
  1234. inputDevice->handleDeviceBuffer();
  1235. if (inputDevice->getNumSamplesInReservoir() < bufferSize)
  1236. continue;
  1237. }
  1238. else
  1239. {
  1240. if (isExclusiveMode (deviceMode) && WaitForSingleObject (inputDevice->clientEvent, 0) == WAIT_OBJECT_0)
  1241. inputDevice->handleDeviceBuffer();
  1242. }
  1243. inputDevice->copyBuffersFromReservoir (inputBuffers, numInputBuffers, bufferSize);
  1244. if (inputDevice->sampleRateHasChanged)
  1245. {
  1246. deviceSampleRateChanged = true;
  1247. triggerAsyncUpdate();
  1248. break;
  1249. }
  1250. }
  1251. {
  1252. const ScopedTryLock sl (startStopLock);
  1253. if (sl.isLocked() && isStarted)
  1254. callback->audioDeviceIOCallbackWithContext (inputBuffers,
  1255. numInputBuffers,
  1256. outputBuffers,
  1257. numOutputBuffers,
  1258. bufferSize,
  1259. {});
  1260. else
  1261. outs.clear();
  1262. }
  1263. if (outputDeviceActive)
  1264. {
  1265. // Note that this function is handed the input device so it can check for the event and make sure
  1266. // the input reservoir is filled up correctly even when bufferSize > device actualBufferSize
  1267. outputDevice->copyBuffers (outputBuffers, numOutputBuffers, bufferSize, inputDevice.get(), *this);
  1268. if (outputDevice->sampleRateHasChanged)
  1269. {
  1270. deviceSampleRateChanged = true;
  1271. triggerAsyncUpdate();
  1272. break;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. //==============================================================================
  1278. String outputDeviceId, inputDeviceId;
  1279. String lastError;
  1280. private:
  1281. // Device stats...
  1282. std::unique_ptr<WASAPIInputDevice> inputDevice;
  1283. std::unique_ptr<WASAPIOutputDevice> outputDevice;
  1284. WASAPIDeviceMode deviceMode;
  1285. double defaultSampleRate = 0;
  1286. int minBufferSize = 0, defaultBufferSize = 0;
  1287. int lowLatencyMaxBufferSize = 0, lowLatencyBufferSizeMultiple = 0;
  1288. int latencyIn = 0, latencyOut = 0;
  1289. Array<double> sampleRates;
  1290. Array<int> bufferSizes;
  1291. // Active state...
  1292. bool isOpen_ = false, isStarted = false;
  1293. int currentBufferSizeSamples = 0;
  1294. double currentSampleRate = 0;
  1295. AudioIODeviceCallback* callback = {};
  1296. CriticalSection startStopLock;
  1297. std::atomic<bool> shouldShutdown { false }, deviceSampleRateChanged { false };
  1298. BigInteger lastKnownInputChannels, lastKnownOutputChannels;
  1299. //==============================================================================
  1300. bool createDevices()
  1301. {
  1302. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1303. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1304. return false;
  1305. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  1306. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  1307. return false;
  1308. UINT32 numDevices = 0;
  1309. if (! check (deviceCollection->GetCount (&numDevices)))
  1310. return false;
  1311. for (UINT32 i = 0; i < numDevices; ++i)
  1312. {
  1313. ComSmartPtr<IMMDevice> device;
  1314. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1315. continue;
  1316. auto deviceId = getDeviceID (device);
  1317. if (deviceId.isEmpty())
  1318. continue;
  1319. auto flow = getDataFlow (device);
  1320. if (deviceId == inputDeviceId && flow == eCapture)
  1321. inputDevice.reset (new WASAPIInputDevice (device, deviceMode));
  1322. else if (deviceId == outputDeviceId && flow == eRender)
  1323. outputDevice.reset (new WASAPIOutputDevice (device, deviceMode));
  1324. }
  1325. return (outputDeviceId.isEmpty() || (outputDevice != nullptr && outputDevice->isOk()))
  1326. && (inputDeviceId.isEmpty() || (inputDevice != nullptr && inputDevice->isOk()));
  1327. }
  1328. //==============================================================================
  1329. void handleAsyncUpdate() override
  1330. {
  1331. auto closeDevices = [this]
  1332. {
  1333. close();
  1334. outputDevice = nullptr;
  1335. inputDevice = nullptr;
  1336. };
  1337. if (shouldShutdown)
  1338. {
  1339. closeDevices();
  1340. }
  1341. else if (deviceSampleRateChanged)
  1342. {
  1343. auto sampleRateChangedByInput = (inputDevice != nullptr && inputDevice->sampleRateHasChanged);
  1344. closeDevices();
  1345. initialise();
  1346. auto changedSampleRate = [this, sampleRateChangedByInput]()
  1347. {
  1348. if (inputDevice != nullptr && sampleRateChangedByInput)
  1349. return inputDevice->defaultSampleRate;
  1350. if (outputDevice != nullptr && ! sampleRateChangedByInput)
  1351. return outputDevice->defaultSampleRate;
  1352. return 0.0;
  1353. }();
  1354. open (lastKnownInputChannels, lastKnownOutputChannels,
  1355. changedSampleRate, currentBufferSizeSamples);
  1356. start (callback);
  1357. }
  1358. }
  1359. //==============================================================================
  1360. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice)
  1361. };
  1362. //==============================================================================
  1363. class WASAPIAudioIODeviceType : public AudioIODeviceType,
  1364. private DeviceChangeDetector
  1365. {
  1366. public:
  1367. WASAPIAudioIODeviceType (WASAPIDeviceMode mode)
  1368. : AudioIODeviceType (getDeviceTypename (mode)),
  1369. DeviceChangeDetector (L"Windows Audio"),
  1370. deviceMode (mode)
  1371. {
  1372. }
  1373. ~WASAPIAudioIODeviceType() override
  1374. {
  1375. if (notifyClient != nullptr)
  1376. enumerator->UnregisterEndpointNotificationCallback (notifyClient);
  1377. }
  1378. //==============================================================================
  1379. void scanForDevices() override
  1380. {
  1381. hasScanned = true;
  1382. outputDeviceNames.clear();
  1383. inputDeviceNames.clear();
  1384. outputDeviceIds.clear();
  1385. inputDeviceIds.clear();
  1386. scan (outputDeviceNames, inputDeviceNames,
  1387. outputDeviceIds, inputDeviceIds);
  1388. }
  1389. StringArray getDeviceNames (bool wantInputNames) const override
  1390. {
  1391. jassert (hasScanned); // need to call scanForDevices() before doing this
  1392. return wantInputNames ? inputDeviceNames
  1393. : outputDeviceNames;
  1394. }
  1395. int getDefaultDeviceIndex (bool /*forInput*/) const override
  1396. {
  1397. jassert (hasScanned); // need to call scanForDevices() before doing this
  1398. return 0;
  1399. }
  1400. int getIndexOfDevice (AudioIODevice* device, bool asInput) const override
  1401. {
  1402. jassert (hasScanned); // need to call scanForDevices() before doing this
  1403. if (auto d = dynamic_cast<WASAPIAudioIODevice*> (device))
  1404. return asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  1405. : outputDeviceIds.indexOf (d->outputDeviceId);
  1406. return -1;
  1407. }
  1408. bool hasSeparateInputsAndOutputs() const override { return true; }
  1409. AudioIODevice* createDevice (const String& outputDeviceName,
  1410. const String& inputDeviceName) override
  1411. {
  1412. jassert (hasScanned); // need to call scanForDevices() before doing this
  1413. std::unique_ptr<WASAPIAudioIODevice> device;
  1414. auto outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  1415. auto inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  1416. if (outputIndex >= 0 || inputIndex >= 0)
  1417. {
  1418. device.reset (new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1419. : inputDeviceName,
  1420. getTypeName(),
  1421. outputDeviceIds [outputIndex],
  1422. inputDeviceIds [inputIndex],
  1423. deviceMode));
  1424. if (! device->initialise())
  1425. device = nullptr;
  1426. }
  1427. return device.release();
  1428. }
  1429. //==============================================================================
  1430. StringArray outputDeviceNames, outputDeviceIds;
  1431. StringArray inputDeviceNames, inputDeviceIds;
  1432. private:
  1433. WASAPIDeviceMode deviceMode;
  1434. bool hasScanned = false;
  1435. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1436. //==============================================================================
  1437. class ChangeNotificationClient : public ComBaseClassHelper<IMMNotificationClient>
  1438. {
  1439. public:
  1440. ChangeNotificationClient (WASAPIAudioIODeviceType* d)
  1441. : ComBaseClassHelper (0), device (d) {}
  1442. JUCE_COMRESULT OnDeviceAdded (LPCWSTR) { return notify(); }
  1443. JUCE_COMRESULT OnDeviceRemoved (LPCWSTR) { return notify(); }
  1444. JUCE_COMRESULT OnDeviceStateChanged(LPCWSTR, DWORD) { return notify(); }
  1445. JUCE_COMRESULT OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) { return notify(); }
  1446. JUCE_COMRESULT OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) { return notify(); }
  1447. private:
  1448. WeakReference<WASAPIAudioIODeviceType> device;
  1449. HRESULT notify()
  1450. {
  1451. if (device != nullptr)
  1452. device->triggerAsyncDeviceChangeCallback();
  1453. return S_OK;
  1454. }
  1455. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeNotificationClient)
  1456. };
  1457. ComSmartPtr<ChangeNotificationClient> notifyClient;
  1458. //==============================================================================
  1459. static String getDefaultEndpoint (IMMDeviceEnumerator* enumerator, bool forCapture)
  1460. {
  1461. String s;
  1462. IMMDevice* dev = nullptr;
  1463. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  1464. eMultimedia, &dev)))
  1465. {
  1466. WCHAR* deviceId = nullptr;
  1467. if (check (dev->GetId (&deviceId)))
  1468. {
  1469. s = deviceId;
  1470. CoTaskMemFree (deviceId);
  1471. }
  1472. dev->Release();
  1473. }
  1474. return s;
  1475. }
  1476. //==============================================================================
  1477. void scan (StringArray& outDeviceNames,
  1478. StringArray& inDeviceNames,
  1479. StringArray& outDeviceIds,
  1480. StringArray& inDeviceIds)
  1481. {
  1482. if (enumerator == nullptr)
  1483. {
  1484. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1485. return;
  1486. notifyClient = new ChangeNotificationClient (this);
  1487. enumerator->RegisterEndpointNotificationCallback (notifyClient);
  1488. }
  1489. auto defaultRenderer = getDefaultEndpoint (enumerator, false);
  1490. auto defaultCapture = getDefaultEndpoint (enumerator, true);
  1491. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  1492. UINT32 numDevices = 0;
  1493. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  1494. && check (deviceCollection->GetCount (&numDevices))))
  1495. return;
  1496. for (UINT32 i = 0; i < numDevices; ++i)
  1497. {
  1498. ComSmartPtr<IMMDevice> device;
  1499. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1500. continue;
  1501. DWORD state = 0;
  1502. if (! (check (device->GetState (&state)) && state == DEVICE_STATE_ACTIVE))
  1503. continue;
  1504. auto deviceId = getDeviceID (device);
  1505. String name;
  1506. {
  1507. ComSmartPtr<IPropertyStore> properties;
  1508. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  1509. continue;
  1510. PROPVARIANT value;
  1511. zerostruct (value);
  1512. const PROPERTYKEY PKEY_Device_FriendlyName
  1513. = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 };
  1514. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  1515. name = value.pwszVal;
  1516. PropVariantClear (&value);
  1517. }
  1518. auto flow = getDataFlow (device);
  1519. if (flow == eRender)
  1520. {
  1521. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  1522. outDeviceIds.insert (index, deviceId);
  1523. outDeviceNames.insert (index, name);
  1524. }
  1525. else if (flow == eCapture)
  1526. {
  1527. const int index = (deviceId == defaultCapture) ? 0 : -1;
  1528. inDeviceIds.insert (index, deviceId);
  1529. inDeviceNames.insert (index, name);
  1530. }
  1531. }
  1532. inDeviceNames.appendNumbersToDuplicates (false, false);
  1533. outDeviceNames.appendNumbersToDuplicates (false, false);
  1534. }
  1535. //==============================================================================
  1536. void systemDeviceChanged() override
  1537. {
  1538. StringArray newOutNames, newInNames, newOutIds, newInIds;
  1539. scan (newOutNames, newInNames, newOutIds, newInIds);
  1540. if (newOutNames != outputDeviceNames
  1541. || newInNames != inputDeviceNames
  1542. || newOutIds != outputDeviceIds
  1543. || newInIds != inputDeviceIds)
  1544. {
  1545. hasScanned = true;
  1546. outputDeviceNames = newOutNames;
  1547. inputDeviceNames = newInNames;
  1548. outputDeviceIds = newOutIds;
  1549. inputDeviceIds = newInIds;
  1550. }
  1551. callDeviceChangeListeners();
  1552. }
  1553. //==============================================================================
  1554. static String getDeviceTypename (WASAPIDeviceMode mode)
  1555. {
  1556. if (mode == WASAPIDeviceMode::shared) return "Windows Audio";
  1557. if (mode == WASAPIDeviceMode::sharedLowLatency) return "Windows Audio (Low Latency Mode)";
  1558. if (mode == WASAPIDeviceMode::exclusive) return "Windows Audio (Exclusive Mode)";
  1559. jassertfalse;
  1560. return {};
  1561. }
  1562. //==============================================================================
  1563. JUCE_DECLARE_WEAK_REFERENCEABLE (WASAPIAudioIODeviceType)
  1564. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType)
  1565. };
  1566. //==============================================================================
  1567. struct MMDeviceMasterVolume
  1568. {
  1569. MMDeviceMasterVolume()
  1570. {
  1571. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1572. if (check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1573. {
  1574. ComSmartPtr<IMMDevice> device;
  1575. if (check (enumerator->GetDefaultAudioEndpoint (eRender, eConsole, device.resetAndGetPointerAddress())))
  1576. check (device->Activate (__uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr,
  1577. (void**) endpointVolume.resetAndGetPointerAddress()));
  1578. }
  1579. }
  1580. float getGain() const
  1581. {
  1582. float vol = 0.0f;
  1583. if (endpointVolume != nullptr)
  1584. check (endpointVolume->GetMasterVolumeLevelScalar (&vol));
  1585. return vol;
  1586. }
  1587. bool setGain (float newGain) const
  1588. {
  1589. return endpointVolume != nullptr
  1590. && check (endpointVolume->SetMasterVolumeLevelScalar (jlimit (0.0f, 1.0f, newGain), nullptr));
  1591. }
  1592. bool isMuted() const
  1593. {
  1594. BOOL mute = 0;
  1595. return endpointVolume != nullptr
  1596. && check (endpointVolume->GetMute (&mute)) && mute != 0;
  1597. }
  1598. bool setMuted (bool shouldMute) const
  1599. {
  1600. return endpointVolume != nullptr
  1601. && check (endpointVolume->SetMute (shouldMute, nullptr));
  1602. }
  1603. ComSmartPtr<IAudioEndpointVolume> endpointVolume;
  1604. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MMDeviceMasterVolume)
  1605. };
  1606. }
  1607. //==============================================================================
  1608. #define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
  1609. float JUCE_CALLTYPE SystemAudioVolume::getGain() { return WasapiClasses::MMDeviceMasterVolume().getGain(); }
  1610. bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return WasapiClasses::MMDeviceMasterVolume().setGain (gain); }
  1611. bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return WasapiClasses::MMDeviceMasterVolume().isMuted(); }
  1612. bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return WasapiClasses::MMDeviceMasterVolume().setMuted (mute); }
  1613. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1614. } // namespace juce