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.

1976 lines
71KB

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