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.

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