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.

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