Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1984 lines
72KB

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