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.

1780 lines
63KB

  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. JUCE_IUNKNOWNCLASS (IAudioClient, "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")
  175. {
  176. JUCE_COMCALL Initialize (AUDCLNT_SHAREMODE, DWORD, REFERENCE_TIME, REFERENCE_TIME, const WAVEFORMATEX*, LPCGUID) = 0;
  177. JUCE_COMCALL GetBufferSize (UINT32*) = 0;
  178. JUCE_COMCALL GetStreamLatency (REFERENCE_TIME*) = 0;
  179. JUCE_COMCALL GetCurrentPadding (UINT32*) = 0;
  180. JUCE_COMCALL IsFormatSupported (AUDCLNT_SHAREMODE, const WAVEFORMATEX*, WAVEFORMATEX**) = 0;
  181. JUCE_COMCALL GetMixFormat (WAVEFORMATEX**) = 0;
  182. JUCE_COMCALL GetDevicePeriod (REFERENCE_TIME*, REFERENCE_TIME*) = 0;
  183. JUCE_COMCALL Start() = 0;
  184. JUCE_COMCALL Stop() = 0;
  185. JUCE_COMCALL Reset() = 0;
  186. JUCE_COMCALL SetEventHandle (HANDLE) = 0;
  187. JUCE_COMCALL GetService (REFIID, void**) = 0;
  188. };
  189. JUCE_IUNKNOWNCLASS (IAudioCaptureClient, "C8ADBD64-E71E-48a0-A4DE-185C395CD317")
  190. {
  191. JUCE_COMCALL GetBuffer (BYTE**, UINT32*, DWORD*, UINT64*, UINT64*) = 0;
  192. JUCE_COMCALL ReleaseBuffer (UINT32) = 0;
  193. JUCE_COMCALL GetNextPacketSize (UINT32*) = 0;
  194. };
  195. JUCE_IUNKNOWNCLASS (IAudioRenderClient, "F294ACFC-3146-4483-A7BF-ADDCA7C260E2")
  196. {
  197. JUCE_COMCALL GetBuffer (UINT32, BYTE**) = 0;
  198. JUCE_COMCALL ReleaseBuffer (UINT32, DWORD) = 0;
  199. };
  200. JUCE_IUNKNOWNCLASS (IAudioEndpointVolume, "5CDF2C82-841E-4546-9722-0CF74078229A")
  201. {
  202. JUCE_COMCALL RegisterControlChangeNotify (void*) = 0;
  203. JUCE_COMCALL UnregisterControlChangeNotify (void*) = 0;
  204. JUCE_COMCALL GetChannelCount (UINT*) = 0;
  205. JUCE_COMCALL SetMasterVolumeLevel (float, LPCGUID) = 0;
  206. JUCE_COMCALL SetMasterVolumeLevelScalar (float, LPCGUID) = 0;
  207. JUCE_COMCALL GetMasterVolumeLevel (float*) = 0;
  208. JUCE_COMCALL GetMasterVolumeLevelScalar (float*) = 0;
  209. JUCE_COMCALL SetChannelVolumeLevel (UINT, float, LPCGUID) = 0;
  210. JUCE_COMCALL SetChannelVolumeLevelScalar (UINT, float, LPCGUID) = 0;
  211. JUCE_COMCALL GetChannelVolumeLevel (UINT, float*) = 0;
  212. JUCE_COMCALL GetChannelVolumeLevelScalar (UINT, float*) = 0;
  213. JUCE_COMCALL SetMute (BOOL, LPCGUID) = 0;
  214. JUCE_COMCALL GetMute (BOOL*) = 0;
  215. JUCE_COMCALL GetVolumeStepInfo (UINT*, UINT*) = 0;
  216. JUCE_COMCALL VolumeStepUp (LPCGUID) = 0;
  217. JUCE_COMCALL VolumeStepDown (LPCGUID) = 0;
  218. JUCE_COMCALL QueryHardwareSupport (DWORD*) = 0;
  219. JUCE_COMCALL GetVolumeRange (float*, float*, float*) = 0;
  220. };
  221. enum AudioSessionDisconnectReason
  222. {
  223. DisconnectReasonDeviceRemoval = 0,
  224. DisconnectReasonServerShutdown = 1,
  225. DisconnectReasonFormatChanged = 2,
  226. DisconnectReasonSessionLogoff = 3,
  227. DisconnectReasonSessionDisconnected = 4,
  228. DisconnectReasonExclusiveModeOverride = 5
  229. };
  230. enum AudioSessionState
  231. {
  232. AudioSessionStateInactive = 0,
  233. AudioSessionStateActive = 1,
  234. AudioSessionStateExpired = 2
  235. };
  236. JUCE_IUNKNOWNCLASS (IAudioSessionEvents, "24918ACC-64B3-37C1-8CA9-74A66E9957A8")
  237. {
  238. JUCE_COMCALL OnDisplayNameChanged (LPCWSTR, LPCGUID) = 0;
  239. JUCE_COMCALL OnIconPathChanged (LPCWSTR, LPCGUID) = 0;
  240. JUCE_COMCALL OnSimpleVolumeChanged (float, BOOL, LPCGUID) = 0;
  241. JUCE_COMCALL OnChannelVolumeChanged (DWORD, float*, DWORD, LPCGUID) = 0;
  242. JUCE_COMCALL OnGroupingParamChanged (LPCGUID, LPCGUID) = 0;
  243. JUCE_COMCALL OnStateChanged (AudioSessionState) = 0;
  244. JUCE_COMCALL OnSessionDisconnected (AudioSessionDisconnectReason) = 0;
  245. };
  246. JUCE_IUNKNOWNCLASS (IAudioSessionControl, "F4B1A599-7266-4319-A8CA-E70ACB11E8CD")
  247. {
  248. JUCE_COMCALL GetState (AudioSessionState*) = 0;
  249. JUCE_COMCALL GetDisplayName (LPWSTR*) = 0;
  250. JUCE_COMCALL SetDisplayName (LPCWSTR, LPCGUID) = 0;
  251. JUCE_COMCALL GetIconPath (LPWSTR*) = 0;
  252. JUCE_COMCALL SetIconPath (LPCWSTR, LPCGUID) = 0;
  253. JUCE_COMCALL GetGroupingParam (GUID*) = 0;
  254. JUCE_COMCALL SetGroupingParam (LPCGUID, LPCGUID) = 0;
  255. JUCE_COMCALL RegisterAudioSessionNotification (IAudioSessionEvents*) = 0;
  256. JUCE_COMCALL UnregisterAudioSessionNotification (IAudioSessionEvents*) = 0;
  257. };
  258. #undef JUCE_COMCALL
  259. #undef JUCE_COMCLASS
  260. #undef JUCE_IUNKNOWNCLASS
  261. //==============================================================================
  262. namespace WasapiClasses
  263. {
  264. String getDeviceID (IMMDevice* device)
  265. {
  266. String s;
  267. WCHAR* deviceId = nullptr;
  268. if (check (device->GetId (&deviceId)))
  269. {
  270. s = String (deviceId);
  271. CoTaskMemFree (deviceId);
  272. }
  273. return s;
  274. }
  275. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  276. {
  277. EDataFlow flow = eRender;
  278. ComSmartPtr<IMMEndpoint> endPoint;
  279. if (check (device.QueryInterface (endPoint)))
  280. (void) check (endPoint->GetDataFlow (&flow));
  281. return flow;
  282. }
  283. int refTimeToSamples (const REFERENCE_TIME& t, double sampleRate) noexcept
  284. {
  285. return roundToInt (sampleRate * ((double) t) * 0.0000001);
  286. }
  287. REFERENCE_TIME samplesToRefTime (int numSamples, double sampleRate) noexcept
  288. {
  289. return (REFERENCE_TIME) ((numSamples * 10000.0 * 1000.0 / sampleRate) + 0.5);
  290. }
  291. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* src) noexcept
  292. {
  293. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  294. : sizeof (WAVEFORMATEX));
  295. }
  296. //==============================================================================
  297. class WASAPIDeviceBase
  298. {
  299. public:
  300. WASAPIDeviceBase (const ComSmartPtr<IMMDevice>& d, bool exclusiveMode)
  301. : device (d), useExclusiveMode (exclusiveMode)
  302. {
  303. clientEvent = CreateEvent (nullptr, false, false, nullptr);
  304. ComSmartPtr<IAudioClient> tempClient (createClient());
  305. if (tempClient == nullptr)
  306. return;
  307. REFERENCE_TIME defaultPeriod, minPeriod;
  308. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  309. return;
  310. WAVEFORMATEX* mixFormat = nullptr;
  311. if (! check (tempClient->GetMixFormat (&mixFormat)))
  312. return;
  313. WAVEFORMATEXTENSIBLE format;
  314. copyWavFormat (format, mixFormat);
  315. CoTaskMemFree (mixFormat);
  316. actualNumChannels = numChannels = format.Format.nChannels;
  317. defaultSampleRate = format.Format.nSamplesPerSec;
  318. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  319. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  320. mixFormatChannelMask = format.dwChannelMask;
  321. rates.addUsingDefaultSort (defaultSampleRate);
  322. if (useExclusiveMode
  323. && findSupportedFormat (tempClient, defaultSampleRate, format.dwChannelMask, format))
  324. {
  325. // Got a format that is supported by the device so we can ask what sample rates are supported (in whatever format)
  326. }
  327. for (auto rate : { 8000, 11025, 16000, 22050, 32000,
  328. 44100, 48000, 88200, 96000, 176400,
  329. 192000, 352800, 384000, 705600, 768000 })
  330. {
  331. if (rates.contains (rate))
  332. continue;
  333. format.Format.nSamplesPerSec = (DWORD) rate;
  334. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nChannels * format.Format.wBitsPerSample / 8);
  335. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE
  336. : AUDCLNT_SHAREMODE_SHARED,
  337. (WAVEFORMATEX*) &format, 0)))
  338. if (! rates.contains (rate))
  339. rates.addUsingDefaultSort (rate);
  340. }
  341. }
  342. virtual ~WASAPIDeviceBase()
  343. {
  344. device = nullptr;
  345. CloseHandle (clientEvent);
  346. }
  347. bool isOk() const noexcept { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  348. bool openClient (const double newSampleRate, const BigInteger& newChannels, const int bufferSizeSamples)
  349. {
  350. sampleRate = newSampleRate;
  351. channels = newChannels;
  352. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  353. numChannels = channels.getHighestBit() + 1;
  354. if (numChannels == 0)
  355. return true;
  356. client = createClient();
  357. if (client != nullptr
  358. && tryInitialisingWithBufferSize (bufferSizeSamples))
  359. {
  360. sampleRateHasChanged = false;
  361. shouldShutdown = false;
  362. channelMaps.clear();
  363. for (int i = 0; i <= channels.getHighestBit(); ++i)
  364. if (channels[i])
  365. channelMaps.add (i);
  366. REFERENCE_TIME latency;
  367. if (check (client->GetStreamLatency (&latency)))
  368. latencySamples = refTimeToSamples (latency, sampleRate);
  369. (void) check (client->GetBufferSize (&actualBufferSize));
  370. createSessionEventCallback();
  371. return check (client->SetEventHandle (clientEvent));
  372. }
  373. return false;
  374. }
  375. void closeClient()
  376. {
  377. if (client != nullptr)
  378. client->Stop();
  379. // N.B. this is needed to prevent a double-deletion of the IAudioSessionEvents object
  380. // on older versions of Windows
  381. Thread::sleep (5);
  382. deleteSessionEventCallback();
  383. client = nullptr;
  384. ResetEvent (clientEvent);
  385. }
  386. void deviceSampleRateChanged()
  387. {
  388. sampleRateHasChanged = true;
  389. }
  390. void deviceSessionBecameInactive()
  391. {
  392. isActive = false;
  393. }
  394. void deviceSessionExpired()
  395. {
  396. shouldShutdown = true;
  397. }
  398. void deviceSessionBecameActive()
  399. {
  400. isActive = true;
  401. }
  402. //==============================================================================
  403. ComSmartPtr<IMMDevice> device;
  404. ComSmartPtr<IAudioClient> client;
  405. double sampleRate = 0, defaultSampleRate = 0;
  406. int numChannels = 0, actualNumChannels = 0;
  407. int minBufferSize = 0, defaultBufferSize = 0, latencySamples = 0;
  408. DWORD mixFormatChannelMask = 0;
  409. const bool useExclusiveMode;
  410. Array<double> rates;
  411. HANDLE clientEvent = {};
  412. BigInteger channels;
  413. Array<int> channelMaps;
  414. UINT32 actualBufferSize = 0;
  415. int bytesPerSample = 0, bytesPerFrame = 0;
  416. std::atomic<bool> sampleRateHasChanged { false }, shouldShutdown { false }, isActive { true };
  417. virtual void updateFormat (bool isFloat) = 0;
  418. private:
  419. //==============================================================================
  420. struct SessionEventCallback : public ComBaseClassHelper<IAudioSessionEvents>
  421. {
  422. SessionEventCallback (WASAPIDeviceBase& d) : owner (d) {}
  423. JUCE_COMRESULT OnDisplayNameChanged (LPCWSTR, LPCGUID) { return S_OK; }
  424. JUCE_COMRESULT OnIconPathChanged (LPCWSTR, LPCGUID) { return S_OK; }
  425. JUCE_COMRESULT OnSimpleVolumeChanged (float, BOOL, LPCGUID) { return S_OK; }
  426. JUCE_COMRESULT OnChannelVolumeChanged (DWORD, float*, DWORD, LPCGUID) { return S_OK; }
  427. JUCE_COMRESULT OnGroupingParamChanged (LPCGUID, LPCGUID) { return S_OK; }
  428. JUCE_COMRESULT OnStateChanged (AudioSessionState state)
  429. {
  430. switch (state)
  431. {
  432. case AudioSessionStateInactive:
  433. owner.deviceSessionBecameInactive();
  434. break;
  435. case AudioSessionStateExpired:
  436. owner.deviceSessionExpired();
  437. break;
  438. case AudioSessionStateActive:
  439. owner.deviceSessionBecameActive();
  440. break;
  441. }
  442. return S_OK;
  443. }
  444. JUCE_COMRESULT OnSessionDisconnected (AudioSessionDisconnectReason reason)
  445. {
  446. if (reason == DisconnectReasonFormatChanged)
  447. owner.deviceSampleRateChanged();
  448. return S_OK;
  449. }
  450. WASAPIDeviceBase& owner;
  451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionEventCallback)
  452. };
  453. ComSmartPtr<IAudioSessionControl> audioSessionControl;
  454. ComSmartPtr<SessionEventCallback> sessionEventCallback;
  455. void createSessionEventCallback()
  456. {
  457. deleteSessionEventCallback();
  458. client->GetService (__uuidof (IAudioSessionControl),
  459. (void**) audioSessionControl.resetAndGetPointerAddress());
  460. if (audioSessionControl != nullptr)
  461. {
  462. sessionEventCallback = new SessionEventCallback (*this);
  463. audioSessionControl->RegisterAudioSessionNotification (sessionEventCallback);
  464. sessionEventCallback->Release(); // (required because ComBaseClassHelper objects are constructed with a ref count of 1)
  465. }
  466. }
  467. void deleteSessionEventCallback()
  468. {
  469. if (audioSessionControl != nullptr && sessionEventCallback != nullptr)
  470. audioSessionControl->UnregisterAudioSessionNotification (sessionEventCallback);
  471. audioSessionControl = nullptr;
  472. sessionEventCallback = nullptr;
  473. }
  474. //==============================================================================
  475. ComSmartPtr<IAudioClient> createClient()
  476. {
  477. ComSmartPtr<IAudioClient> newClient;
  478. if (device != nullptr)
  479. logFailure (device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER,
  480. nullptr, (void**) newClient.resetAndGetPointerAddress()));
  481. return newClient;
  482. }
  483. struct AudioSampleFormat
  484. {
  485. bool useFloat;
  486. int bitsPerSampleToTry;
  487. int bytesPerSampleContainer;
  488. };
  489. bool tryFormat (const AudioSampleFormat sampleFormat, IAudioClient* clientToUse, double newSampleRate,
  490. DWORD newMixFormatChannelMask, WAVEFORMATEXTENSIBLE& format) const
  491. {
  492. zerostruct (format);
  493. if (numChannels <= 2 && sampleFormat.bitsPerSampleToTry <= 16)
  494. {
  495. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  496. }
  497. else
  498. {
  499. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  500. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  501. }
  502. format.Format.nSamplesPerSec = (DWORD) newSampleRate;
  503. format.Format.nChannels = (WORD) numChannels;
  504. format.Format.wBitsPerSample = (WORD) (8 * sampleFormat.bytesPerSampleContainer);
  505. format.Samples.wValidBitsPerSample = (WORD) (sampleFormat.bitsPerSampleToTry);
  506. format.Format.nBlockAlign = (WORD) (format.Format.nChannels * format.Format.wBitsPerSample / 8);
  507. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * format.Format.nBlockAlign);
  508. format.SubFormat = sampleFormat.useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  509. format.dwChannelMask = newMixFormatChannelMask;
  510. WAVEFORMATEXTENSIBLE* nearestFormat = nullptr;
  511. HRESULT hr = clientToUse->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE
  512. : AUDCLNT_SHAREMODE_SHARED,
  513. (WAVEFORMATEX*) &format,
  514. useExclusiveMode ? nullptr : (WAVEFORMATEX**) &nearestFormat);
  515. logFailure (hr);
  516. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  517. {
  518. copyWavFormat (format, (const WAVEFORMATEX*) nearestFormat);
  519. hr = S_OK;
  520. }
  521. CoTaskMemFree (nearestFormat);
  522. return check (hr);
  523. }
  524. bool findSupportedFormat (IAudioClient* clientToUse, double newSampleRate,
  525. DWORD newMixFormatChannelMask, WAVEFORMATEXTENSIBLE& format) const
  526. {
  527. static const AudioSampleFormat formats[] =
  528. {
  529. { true, 32, 4 },
  530. { false, 32, 4 },
  531. { false, 24, 4 },
  532. { false, 24, 3 },
  533. { false, 20, 4 },
  534. { false, 20, 3 },
  535. { false, 16, 2 }
  536. };
  537. for (int i = 0; i < numElementsInArray (formats); ++i)
  538. if (tryFormat (formats[i], clientToUse, newSampleRate, newMixFormatChannelMask, format))
  539. return true;
  540. return false;
  541. }
  542. bool tryInitialisingWithBufferSize (int bufferSizeSamples)
  543. {
  544. WAVEFORMATEXTENSIBLE format;
  545. if (findSupportedFormat (client, sampleRate, mixFormatChannelMask, format))
  546. {
  547. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  548. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  549. if (useExclusiveMode && bufferSizeSamples > 0)
  550. defaultPeriod = jmax (minPeriod, samplesToRefTime (bufferSizeSamples, format.Format.nSamplesPerSec));
  551. for (;;)
  552. {
  553. GUID session;
  554. HRESULT hr = client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  555. 0x40000 /*AUDCLNT_STREAMFLAGS_EVENTCALLBACK*/,
  556. defaultPeriod, useExclusiveMode ? defaultPeriod : 0, (WAVEFORMATEX*) &format, &session);
  557. if (check (hr))
  558. {
  559. actualNumChannels = format.Format.nChannels;
  560. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  561. bytesPerSample = format.Format.wBitsPerSample / 8;
  562. bytesPerFrame = format.Format.nBlockAlign;
  563. updateFormat (isFloat);
  564. return true;
  565. }
  566. // Handle the "alignment dance" : http://msdn.microsoft.com/en-us/library/windows/desktop/dd370875(v=vs.85).aspx (see Remarks)
  567. if (hr != MAKE_HRESULT (1, 0x889, 0x19)) // AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
  568. break;
  569. UINT32 numFrames = 0;
  570. if (! check (client->GetBufferSize (&numFrames)))
  571. break;
  572. // Recreate client
  573. client = nullptr;
  574. client = createClient();
  575. defaultPeriod = samplesToRefTime (numFrames, format.Format.nSamplesPerSec);
  576. }
  577. }
  578. return false;
  579. }
  580. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase)
  581. };
  582. //==============================================================================
  583. class WASAPIInputDevice : public WASAPIDeviceBase
  584. {
  585. public:
  586. WASAPIInputDevice (const ComSmartPtr<IMMDevice>& d, bool exclusiveMode)
  587. : WASAPIDeviceBase (d, exclusiveMode)
  588. {
  589. }
  590. ~WASAPIInputDevice()
  591. {
  592. close();
  593. }
  594. bool open (double newSampleRate, const BigInteger& newChannels, int bufferSizeSamples)
  595. {
  596. return openClient (newSampleRate, newChannels, bufferSizeSamples)
  597. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  598. (void**) captureClient.resetAndGetPointerAddress())));
  599. }
  600. void close()
  601. {
  602. closeClient();
  603. captureClient = nullptr;
  604. reservoir.reset();
  605. reservoirReadPos = 0;
  606. reservoirWritePos = 0;
  607. }
  608. template<class SourceType>
  609. void updateFormatWithType (SourceType*) noexcept
  610. {
  611. using NativeType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  612. converter.reset (new AudioData::ConverterInstance<AudioData::Pointer<SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1));
  613. }
  614. void updateFormat (bool isFloat) override
  615. {
  616. if (isFloat) updateFormatWithType ((AudioData::Float32*) nullptr);
  617. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) nullptr);
  618. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) nullptr);
  619. else updateFormatWithType ((AudioData::Int16*) nullptr);
  620. }
  621. bool start (int userBufferSize)
  622. {
  623. reservoirSize = actualBufferSize + userBufferSize;
  624. reservoirMask = nextPowerOfTwo (reservoirSize) - 1;
  625. reservoir.setSize ((reservoirMask + 1) * bytesPerFrame, true);
  626. reservoirReadPos = 0;
  627. reservoirWritePos = 0;
  628. xruns = 0;
  629. if (! check (client->Start()))
  630. return false;
  631. purgeInputBuffers();
  632. isActive = true;
  633. return true;
  634. }
  635. void purgeInputBuffers()
  636. {
  637. uint8* inputData;
  638. UINT32 numSamplesAvailable;
  639. DWORD flags;
  640. while (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, nullptr, nullptr)
  641. != MAKE_HRESULT (0, 0x889, 0x1) /* AUDCLNT_S_BUFFER_EMPTY */)
  642. captureClient->ReleaseBuffer (numSamplesAvailable);
  643. }
  644. int getNumSamplesInReservoir() const noexcept { return reservoirWritePos.load() - reservoirReadPos.load(); }
  645. void handleDeviceBuffer()
  646. {
  647. if (numChannels <= 0)
  648. return;
  649. uint8* inputData;
  650. UINT32 numSamplesAvailable;
  651. DWORD flags;
  652. while (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, nullptr, nullptr)) && numSamplesAvailable > 0)
  653. {
  654. if ((flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0)
  655. xruns++;
  656. int samplesLeft = (int) numSamplesAvailable;
  657. while (samplesLeft > 0)
  658. {
  659. auto localWrite = reservoirWritePos.load() & reservoirMask;
  660. auto samplesToDo = jmin (samplesLeft, reservoirMask + 1 - localWrite);
  661. auto samplesToDoBytes = samplesToDo * bytesPerFrame;
  662. void* reservoirPtr = addBytesToPointer (reservoir.getData(), localWrite * bytesPerFrame);
  663. if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0)
  664. zeromem (reservoirPtr, samplesToDoBytes);
  665. else
  666. memcpy (reservoirPtr, inputData, samplesToDoBytes);
  667. reservoirWritePos += samplesToDo;
  668. inputData += samplesToDoBytes;
  669. samplesLeft -= samplesToDo;
  670. }
  671. if (getNumSamplesInReservoir() > reservoirSize)
  672. reservoirReadPos = reservoirWritePos.load() - reservoirSize;
  673. captureClient->ReleaseBuffer (numSamplesAvailable);
  674. }
  675. }
  676. void copyBuffersFromReservoir (float** destBuffers, int numDestBuffers, int bufferSize)
  677. {
  678. if ((numChannels <= 0 && bufferSize == 0) || reservoir.getSize() == 0)
  679. return;
  680. int offset = jmax (0, bufferSize - getNumSamplesInReservoir());
  681. if (offset > 0)
  682. {
  683. for (int i = 0; i < numDestBuffers; ++i)
  684. zeromem (destBuffers[i], offset * sizeof (float));
  685. bufferSize -= offset;
  686. reservoirReadPos -= offset / 2;
  687. }
  688. while (bufferSize > 0)
  689. {
  690. auto localRead = reservoirReadPos.load() & reservoirMask;
  691. auto samplesToDo = jmin (bufferSize, getNumSamplesInReservoir(), reservoirMask + 1 - localRead);
  692. if (samplesToDo <= 0)
  693. break;
  694. auto reservoirOffset = localRead * bytesPerFrame;
  695. for (int i = 0; i < numDestBuffers; ++i)
  696. converter->convertSamples (destBuffers[i] + offset, 0, addBytesToPointer (reservoir.getData(), reservoirOffset), channelMaps.getUnchecked(i), samplesToDo);
  697. bufferSize -= samplesToDo;
  698. offset += samplesToDo;
  699. reservoirReadPos += samplesToDo;
  700. }
  701. }
  702. ComSmartPtr<IAudioCaptureClient> captureClient;
  703. MemoryBlock reservoir;
  704. int reservoirSize, reservoirMask, xruns;
  705. std::atomic<int> reservoirReadPos, reservoirWritePos;
  706. std::unique_ptr<AudioData::Converter> converter;
  707. private:
  708. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice)
  709. };
  710. //==============================================================================
  711. class WASAPIOutputDevice : public WASAPIDeviceBase
  712. {
  713. public:
  714. WASAPIOutputDevice (const ComSmartPtr<IMMDevice>& d, bool exclusiveMode)
  715. : WASAPIDeviceBase (d, exclusiveMode)
  716. {
  717. }
  718. ~WASAPIOutputDevice()
  719. {
  720. close();
  721. }
  722. bool open (double newSampleRate, const BigInteger& newChannels, int bufferSizeSamples)
  723. {
  724. return openClient (newSampleRate, newChannels, bufferSizeSamples)
  725. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient),
  726. (void**) renderClient.resetAndGetPointerAddress())));
  727. }
  728. void close()
  729. {
  730. closeClient();
  731. renderClient = nullptr;
  732. }
  733. template<class DestType>
  734. void updateFormatWithType (DestType*)
  735. {
  736. using NativeType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  737. converter.reset (new AudioData::ConverterInstance<NativeType, AudioData::Pointer<DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst>> (1, actualNumChannels));
  738. }
  739. void updateFormat (bool isFloat) override
  740. {
  741. if (isFloat) updateFormatWithType ((AudioData::Float32*) nullptr);
  742. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) nullptr);
  743. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) nullptr);
  744. else updateFormatWithType ((AudioData::Int16*) nullptr);
  745. }
  746. bool start()
  747. {
  748. auto samplesToDo = getNumSamplesAvailableToCopy();
  749. uint8* outputData;
  750. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  751. renderClient->ReleaseBuffer (samplesToDo, AUDCLNT_BUFFERFLAGS_SILENT);
  752. if (! check (client->Start()))
  753. return false;
  754. isActive = true;
  755. return true;
  756. }
  757. int getNumSamplesAvailableToCopy() const
  758. {
  759. if (numChannels <= 0)
  760. return 0;
  761. if (! useExclusiveMode)
  762. {
  763. UINT32 padding = 0;
  764. if (check (client->GetCurrentPadding (&padding)))
  765. return actualBufferSize - (int) padding;
  766. }
  767. return actualBufferSize;
  768. }
  769. void copyBuffers (const float** srcBuffers, int numSrcBuffers, int bufferSize,
  770. WASAPIInputDevice* inputDevice, Thread& thread)
  771. {
  772. if (numChannels <= 0)
  773. return;
  774. int offset = 0;
  775. while (bufferSize > 0)
  776. {
  777. // This is needed in order not to drop any input data if the output device endpoint buffer was full
  778. if ((! useExclusiveMode) && inputDevice != nullptr
  779. && WaitForSingleObject (inputDevice->clientEvent, 0) == WAIT_OBJECT_0)
  780. inputDevice->handleDeviceBuffer();
  781. int samplesToDo = jmin (getNumSamplesAvailableToCopy(), bufferSize);
  782. if (samplesToDo == 0)
  783. {
  784. // This can ONLY occur in non-exclusive mode
  785. if (! thread.threadShouldExit() && WaitForSingleObject (clientEvent, 1000) == WAIT_OBJECT_0)
  786. continue;
  787. break;
  788. }
  789. if (useExclusiveMode && WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  790. break;
  791. uint8* outputData = nullptr;
  792. if (check (renderClient->GetBuffer ((UINT32) samplesToDo, &outputData)))
  793. {
  794. for (int i = 0; i < numSrcBuffers; ++i)
  795. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  796. renderClient->ReleaseBuffer ((UINT32) samplesToDo, 0);
  797. }
  798. bufferSize -= samplesToDo;
  799. offset += samplesToDo;
  800. }
  801. }
  802. ComSmartPtr<IAudioRenderClient> renderClient;
  803. std::unique_ptr<AudioData::Converter> converter;
  804. private:
  805. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice)
  806. };
  807. //==============================================================================
  808. class WASAPIAudioIODevice : public AudioIODevice,
  809. public Thread,
  810. private AsyncUpdater
  811. {
  812. public:
  813. WASAPIAudioIODevice (const String& deviceName,
  814. const String& typeName,
  815. const String& outputDeviceID,
  816. const String& inputDeviceID,
  817. bool exclusiveMode)
  818. : AudioIODevice (deviceName, typeName),
  819. Thread ("JUCE WASAPI"),
  820. outputDeviceId (outputDeviceID),
  821. inputDeviceId (inputDeviceID),
  822. useExclusiveMode (exclusiveMode)
  823. {
  824. }
  825. ~WASAPIAudioIODevice()
  826. {
  827. cancelPendingUpdate();
  828. close();
  829. }
  830. bool initialise()
  831. {
  832. latencyIn = latencyOut = 0;
  833. Array<double> ratesIn, ratesOut;
  834. if (createDevices())
  835. {
  836. jassert (inputDevice != nullptr || outputDevice != nullptr);
  837. if (inputDevice != nullptr && outputDevice != nullptr)
  838. {
  839. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  840. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  841. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  842. sampleRates = inputDevice->rates;
  843. sampleRates.removeValuesNotIn (outputDevice->rates);
  844. }
  845. else
  846. {
  847. WASAPIDeviceBase* d = inputDevice != nullptr ? static_cast<WASAPIDeviceBase*> (inputDevice.get())
  848. : static_cast<WASAPIDeviceBase*> (outputDevice.get());
  849. defaultSampleRate = d->defaultSampleRate;
  850. minBufferSize = d->minBufferSize;
  851. defaultBufferSize = d->defaultBufferSize;
  852. sampleRates = d->rates;
  853. }
  854. bufferSizes.clear();
  855. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  856. if (minBufferSize != defaultBufferSize)
  857. bufferSizes.addUsingDefaultSort (minBufferSize);
  858. int n = 64;
  859. for (int i = 0; i < 40; ++i)
  860. {
  861. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  862. bufferSizes.addUsingDefaultSort (n);
  863. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  864. }
  865. return true;
  866. }
  867. return false;
  868. }
  869. StringArray getOutputChannelNames() override
  870. {
  871. StringArray outChannels;
  872. if (outputDevice != nullptr)
  873. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  874. outChannels.add ("Output channel " + String (i));
  875. return outChannels;
  876. }
  877. StringArray getInputChannelNames() override
  878. {
  879. StringArray inChannels;
  880. if (inputDevice != nullptr)
  881. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  882. inChannels.add ("Input channel " + String (i));
  883. return inChannels;
  884. }
  885. Array<double> getAvailableSampleRates() override { return sampleRates; }
  886. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  887. int getDefaultBufferSize() override { return defaultBufferSize; }
  888. int getCurrentBufferSizeSamples() override { return currentBufferSizeSamples; }
  889. double getCurrentSampleRate() override { return currentSampleRate; }
  890. int getCurrentBitDepth() override { return 32; }
  891. int getOutputLatencyInSamples() override { return latencyOut; }
  892. int getInputLatencyInSamples() override { return latencyIn; }
  893. BigInteger getActiveOutputChannels() const override { return outputDevice != nullptr ? outputDevice->channels : BigInteger(); }
  894. BigInteger getActiveInputChannels() const override { return inputDevice != nullptr ? inputDevice->channels : BigInteger(); }
  895. String getLastError() override { return lastError; }
  896. int getXRunCount() const noexcept override { return inputDevice != nullptr ? inputDevice->xruns : -1; }
  897. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  898. double sampleRate, int bufferSizeSamples) override
  899. {
  900. close();
  901. lastError.clear();
  902. if (sampleRates.size() == 0 && inputDevice != nullptr && outputDevice != nullptr)
  903. {
  904. lastError = TRANS("The input and output devices don't share a common sample rate!");
  905. return lastError;
  906. }
  907. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  908. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  909. lastKnownInputChannels = inputChannels;
  910. lastKnownOutputChannels = outputChannels;
  911. if (inputDevice != nullptr && ! inputDevice->open (currentSampleRate, inputChannels, bufferSizeSamples))
  912. {
  913. lastError = TRANS("Couldn't open the input device!");
  914. return lastError;
  915. }
  916. if (outputDevice != nullptr && ! outputDevice->open (currentSampleRate, outputChannels, bufferSizeSamples))
  917. {
  918. close();
  919. lastError = TRANS("Couldn't open the output device!");
  920. return lastError;
  921. }
  922. if (useExclusiveMode)
  923. {
  924. // This is to make sure that the callback uses actualBufferSize in case of exclusive mode
  925. if (inputDevice != nullptr && outputDevice != nullptr && inputDevice->actualBufferSize != outputDevice->actualBufferSize)
  926. {
  927. close();
  928. lastError = TRANS("Couldn't open the output device (buffer size mismatch)");
  929. return lastError;
  930. }
  931. currentBufferSizeSamples = outputDevice != nullptr ? outputDevice->actualBufferSize
  932. : inputDevice->actualBufferSize;
  933. }
  934. if (inputDevice != nullptr) ResetEvent (inputDevice->clientEvent);
  935. if (outputDevice != nullptr) ResetEvent (outputDevice->clientEvent);
  936. shouldShutdown = false;
  937. deviceSampleRateChanged = false;
  938. startThread (8);
  939. Thread::sleep (5);
  940. if (inputDevice != nullptr && inputDevice->client != nullptr)
  941. {
  942. latencyIn = (int) (inputDevice->latencySamples + currentBufferSizeSamples);
  943. if (! inputDevice->start (currentBufferSizeSamples))
  944. {
  945. close();
  946. lastError = TRANS("Couldn't start the input device!");
  947. return lastError;
  948. }
  949. }
  950. if (outputDevice != nullptr && outputDevice->client != nullptr)
  951. {
  952. latencyOut = (int) (outputDevice->latencySamples + currentBufferSizeSamples);
  953. if (! outputDevice->start())
  954. {
  955. close();
  956. lastError = TRANS("Couldn't start the output device!");
  957. return lastError;
  958. }
  959. }
  960. isOpen_ = true;
  961. return lastError;
  962. }
  963. void close() override
  964. {
  965. stop();
  966. signalThreadShouldExit();
  967. if (inputDevice != nullptr) SetEvent (inputDevice->clientEvent);
  968. if (outputDevice != nullptr) SetEvent (outputDevice->clientEvent);
  969. stopThread (5000);
  970. if (inputDevice != nullptr) inputDevice->close();
  971. if (outputDevice != nullptr) outputDevice->close();
  972. isOpen_ = false;
  973. }
  974. bool isOpen() override { return isOpen_ && isThreadRunning(); }
  975. bool isPlaying() override { return isStarted && isOpen_ && isThreadRunning(); }
  976. void start (AudioIODeviceCallback* call) override
  977. {
  978. if (isOpen_ && call != nullptr && ! isStarted)
  979. {
  980. if (! isThreadRunning())
  981. {
  982. // something's gone wrong and the thread's stopped..
  983. isOpen_ = false;
  984. return;
  985. }
  986. call->audioDeviceAboutToStart (this);
  987. const ScopedLock sl (startStopLock);
  988. callback = call;
  989. isStarted = true;
  990. }
  991. }
  992. void stop() override
  993. {
  994. if (isStarted)
  995. {
  996. auto* callbackLocal = callback;
  997. {
  998. const ScopedLock sl (startStopLock);
  999. isStarted = false;
  1000. }
  1001. if (callbackLocal != nullptr)
  1002. callbackLocal->audioDeviceStopped();
  1003. }
  1004. }
  1005. void setMMThreadPriority()
  1006. {
  1007. DynamicLibrary dll ("avrt.dll");
  1008. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, (LPCWSTR, LPDWORD))
  1009. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, (HANDLE, AVRT_PRIORITY))
  1010. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  1011. {
  1012. DWORD dummy = 0;
  1013. if (auto h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy))
  1014. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  1015. }
  1016. }
  1017. void run() override
  1018. {
  1019. setMMThreadPriority();
  1020. auto bufferSize = currentBufferSizeSamples;
  1021. auto numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  1022. auto numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  1023. AudioBuffer<float> ins (jmax (1, numInputBuffers), bufferSize + 32);
  1024. AudioBuffer<float> outs (jmax (1, numOutputBuffers), bufferSize + 32);
  1025. auto inputBuffers = ins.getArrayOfWritePointers();
  1026. auto outputBuffers = outs.getArrayOfWritePointers();
  1027. ins.clear();
  1028. outs.clear();
  1029. while (! threadShouldExit())
  1030. {
  1031. if ((outputDevice != nullptr && outputDevice->shouldShutdown)
  1032. || (inputDevice != nullptr && inputDevice->shouldShutdown))
  1033. {
  1034. shouldShutdown = true;
  1035. triggerAsyncUpdate();
  1036. break;
  1037. }
  1038. auto inputDeviceActive = (inputDevice != nullptr && inputDevice->isActive);
  1039. auto outputDeviceActive = (outputDevice != nullptr && outputDevice->isActive);
  1040. if (! inputDeviceActive && ! outputDeviceActive)
  1041. continue;
  1042. if (inputDeviceActive)
  1043. {
  1044. if (outputDevice == nullptr)
  1045. {
  1046. if (WaitForSingleObject (inputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  1047. break;
  1048. inputDevice->handleDeviceBuffer();
  1049. if (inputDevice->getNumSamplesInReservoir() < bufferSize)
  1050. continue;
  1051. }
  1052. else
  1053. {
  1054. if (useExclusiveMode && WaitForSingleObject (inputDevice->clientEvent, 0) == WAIT_OBJECT_0)
  1055. inputDevice->handleDeviceBuffer();
  1056. }
  1057. inputDevice->copyBuffersFromReservoir (inputBuffers, numInputBuffers, bufferSize);
  1058. if (inputDevice->sampleRateHasChanged)
  1059. {
  1060. deviceSampleRateChanged = true;
  1061. triggerAsyncUpdate();
  1062. break;
  1063. }
  1064. }
  1065. {
  1066. const ScopedTryLock sl (startStopLock);
  1067. if (sl.isLocked() && isStarted)
  1068. callback->audioDeviceIOCallback (const_cast<const float**> (inputBuffers), numInputBuffers,
  1069. outputBuffers, numOutputBuffers, bufferSize);
  1070. else
  1071. outs.clear();
  1072. }
  1073. if (outputDeviceActive)
  1074. {
  1075. // Note that this function is handed the input device so it can check for the event and make sure
  1076. // the input reservoir is filled up correctly even when bufferSize > device actualBufferSize
  1077. outputDevice->copyBuffers (const_cast<const float**> (outputBuffers), numOutputBuffers, bufferSize, inputDevice.get(), *this);
  1078. if (outputDevice->sampleRateHasChanged)
  1079. {
  1080. deviceSampleRateChanged = true;
  1081. triggerAsyncUpdate();
  1082. break;
  1083. }
  1084. }
  1085. }
  1086. }
  1087. //==============================================================================
  1088. String outputDeviceId, inputDeviceId;
  1089. String lastError;
  1090. private:
  1091. // Device stats...
  1092. std::unique_ptr<WASAPIInputDevice> inputDevice;
  1093. std::unique_ptr<WASAPIOutputDevice> outputDevice;
  1094. const bool useExclusiveMode;
  1095. double defaultSampleRate = 0;
  1096. int minBufferSize = 0, defaultBufferSize = 0;
  1097. int latencyIn = 0, latencyOut = 0;
  1098. Array<double> sampleRates;
  1099. Array<int> bufferSizes;
  1100. // Active state...
  1101. bool isOpen_ = false, isStarted = false;
  1102. int currentBufferSizeSamples = 0;
  1103. double currentSampleRate = 0;
  1104. AudioIODeviceCallback* callback = {};
  1105. CriticalSection startStopLock;
  1106. std::atomic<bool> shouldShutdown { false }, deviceSampleRateChanged { false };
  1107. BigInteger lastKnownInputChannels, lastKnownOutputChannels;
  1108. //==============================================================================
  1109. bool createDevices()
  1110. {
  1111. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1112. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1113. return false;
  1114. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  1115. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  1116. return false;
  1117. UINT32 numDevices = 0;
  1118. if (! check (deviceCollection->GetCount (&numDevices)))
  1119. return false;
  1120. for (UINT32 i = 0; i < numDevices; ++i)
  1121. {
  1122. ComSmartPtr<IMMDevice> device;
  1123. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1124. continue;
  1125. auto deviceId = getDeviceID (device);
  1126. if (deviceId.isEmpty())
  1127. continue;
  1128. auto flow = getDataFlow (device);
  1129. if (deviceId == inputDeviceId && flow == eCapture)
  1130. inputDevice.reset (new WASAPIInputDevice (device, useExclusiveMode));
  1131. else if (deviceId == outputDeviceId && flow == eRender)
  1132. outputDevice.reset (new WASAPIOutputDevice (device, useExclusiveMode));
  1133. }
  1134. return (outputDeviceId.isEmpty() || (outputDevice != nullptr && outputDevice->isOk()))
  1135. && (inputDeviceId.isEmpty() || (inputDevice != nullptr && inputDevice->isOk()));
  1136. }
  1137. //==============================================================================
  1138. void handleAsyncUpdate() override
  1139. {
  1140. auto closeDevices = [this]
  1141. {
  1142. close();
  1143. outputDevice = nullptr;
  1144. inputDevice = nullptr;
  1145. };
  1146. if (shouldShutdown)
  1147. {
  1148. closeDevices();
  1149. }
  1150. else if (deviceSampleRateChanged)
  1151. {
  1152. auto sampleRateChangedByInput = (inputDevice != nullptr && inputDevice->sampleRateHasChanged);
  1153. closeDevices();
  1154. initialise();
  1155. auto changedSampleRate = [this, sampleRateChangedByInput]()
  1156. {
  1157. if (inputDevice != nullptr && sampleRateChangedByInput)
  1158. return inputDevice->defaultSampleRate;
  1159. if (outputDevice != nullptr && ! sampleRateChangedByInput)
  1160. return outputDevice->defaultSampleRate;
  1161. return 0.0;
  1162. }();
  1163. open (lastKnownInputChannels, lastKnownOutputChannels,
  1164. changedSampleRate, currentBufferSizeSamples);
  1165. start (callback);
  1166. }
  1167. }
  1168. //==============================================================================
  1169. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice)
  1170. };
  1171. //==============================================================================
  1172. class WASAPIAudioIODeviceType : public AudioIODeviceType,
  1173. private DeviceChangeDetector
  1174. {
  1175. public:
  1176. WASAPIAudioIODeviceType (bool exclusive)
  1177. : AudioIODeviceType (exclusive ? "Windows Audio (Exclusive Mode)" : "Windows Audio"),
  1178. DeviceChangeDetector (L"Windows Audio"),
  1179. exclusiveMode (exclusive)
  1180. {
  1181. }
  1182. ~WASAPIAudioIODeviceType()
  1183. {
  1184. if (notifyClient != nullptr)
  1185. enumerator->UnregisterEndpointNotificationCallback (notifyClient);
  1186. }
  1187. //==============================================================================
  1188. void scanForDevices() override
  1189. {
  1190. hasScanned = true;
  1191. outputDeviceNames.clear();
  1192. inputDeviceNames.clear();
  1193. outputDeviceIds.clear();
  1194. inputDeviceIds.clear();
  1195. scan (outputDeviceNames, inputDeviceNames,
  1196. outputDeviceIds, inputDeviceIds);
  1197. }
  1198. StringArray getDeviceNames (bool wantInputNames) const override
  1199. {
  1200. jassert (hasScanned); // need to call scanForDevices() before doing this
  1201. return wantInputNames ? inputDeviceNames
  1202. : outputDeviceNames;
  1203. }
  1204. int getDefaultDeviceIndex (bool /*forInput*/) const override
  1205. {
  1206. jassert (hasScanned); // need to call scanForDevices() before doing this
  1207. return 0;
  1208. }
  1209. int getIndexOfDevice (AudioIODevice* device, bool asInput) const override
  1210. {
  1211. jassert (hasScanned); // need to call scanForDevices() before doing this
  1212. if (auto d = dynamic_cast<WASAPIAudioIODevice*> (device))
  1213. return asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  1214. : outputDeviceIds.indexOf (d->outputDeviceId);
  1215. return -1;
  1216. }
  1217. bool hasSeparateInputsAndOutputs() const override { return true; }
  1218. AudioIODevice* createDevice (const String& outputDeviceName,
  1219. const String& inputDeviceName) override
  1220. {
  1221. jassert (hasScanned); // need to call scanForDevices() before doing this
  1222. std::unique_ptr<WASAPIAudioIODevice> device;
  1223. auto outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  1224. auto inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  1225. if (outputIndex >= 0 || inputIndex >= 0)
  1226. {
  1227. device.reset (new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1228. : inputDeviceName,
  1229. getTypeName(),
  1230. outputDeviceIds [outputIndex],
  1231. inputDeviceIds [inputIndex],
  1232. exclusiveMode));
  1233. if (! device->initialise())
  1234. device = nullptr;
  1235. }
  1236. return device.release();
  1237. }
  1238. //==============================================================================
  1239. StringArray outputDeviceNames, outputDeviceIds;
  1240. StringArray inputDeviceNames, inputDeviceIds;
  1241. private:
  1242. const bool exclusiveMode;
  1243. bool hasScanned = false;
  1244. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1245. //==============================================================================
  1246. class ChangeNotificationClient : public ComBaseClassHelper<IMMNotificationClient>
  1247. {
  1248. public:
  1249. ChangeNotificationClient (WASAPIAudioIODeviceType* d)
  1250. : ComBaseClassHelper<IMMNotificationClient> (0), device (d) {}
  1251. HRESULT STDMETHODCALLTYPE OnDeviceAdded (LPCWSTR) { return notify(); }
  1252. HRESULT STDMETHODCALLTYPE OnDeviceRemoved (LPCWSTR) { return notify(); }
  1253. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR, DWORD) { return notify(); }
  1254. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) { return notify(); }
  1255. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) { return notify(); }
  1256. private:
  1257. WeakReference<WASAPIAudioIODeviceType> device;
  1258. HRESULT notify()
  1259. {
  1260. if (device != nullptr)
  1261. device->triggerAsyncDeviceChangeCallback();
  1262. return S_OK;
  1263. }
  1264. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeNotificationClient)
  1265. };
  1266. ComSmartPtr<ChangeNotificationClient> notifyClient;
  1267. //==============================================================================
  1268. static String getDefaultEndpoint (IMMDeviceEnumerator* enumerator, bool forCapture)
  1269. {
  1270. String s;
  1271. IMMDevice* dev = nullptr;
  1272. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  1273. eMultimedia, &dev)))
  1274. {
  1275. WCHAR* deviceId = nullptr;
  1276. if (check (dev->GetId (&deviceId)))
  1277. {
  1278. s = deviceId;
  1279. CoTaskMemFree (deviceId);
  1280. }
  1281. dev->Release();
  1282. }
  1283. return s;
  1284. }
  1285. //==============================================================================
  1286. void scan (StringArray& outDeviceNames,
  1287. StringArray& inDeviceNames,
  1288. StringArray& outDeviceIds,
  1289. StringArray& inDeviceIds)
  1290. {
  1291. if (enumerator == nullptr)
  1292. {
  1293. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1294. return;
  1295. notifyClient = new ChangeNotificationClient (this);
  1296. enumerator->RegisterEndpointNotificationCallback (notifyClient);
  1297. }
  1298. auto defaultRenderer = getDefaultEndpoint (enumerator, false);
  1299. auto defaultCapture = getDefaultEndpoint (enumerator, true);
  1300. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  1301. UINT32 numDevices = 0;
  1302. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  1303. && check (deviceCollection->GetCount (&numDevices))))
  1304. return;
  1305. for (UINT32 i = 0; i < numDevices; ++i)
  1306. {
  1307. ComSmartPtr<IMMDevice> device;
  1308. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1309. continue;
  1310. DWORD state = 0;
  1311. if (! (check (device->GetState (&state)) && state == DEVICE_STATE_ACTIVE))
  1312. continue;
  1313. auto deviceId = getDeviceID (device);
  1314. String name;
  1315. {
  1316. ComSmartPtr<IPropertyStore> properties;
  1317. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  1318. continue;
  1319. PROPVARIANT value;
  1320. zerostruct (value);
  1321. const PROPERTYKEY PKEY_Device_FriendlyName
  1322. = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 };
  1323. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  1324. name = value.pwszVal;
  1325. PropVariantClear (&value);
  1326. }
  1327. auto flow = getDataFlow (device);
  1328. if (flow == eRender)
  1329. {
  1330. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  1331. outDeviceIds.insert (index, deviceId);
  1332. outDeviceNames.insert (index, name);
  1333. }
  1334. else if (flow == eCapture)
  1335. {
  1336. const int index = (deviceId == defaultCapture) ? 0 : -1;
  1337. inDeviceIds.insert (index, deviceId);
  1338. inDeviceNames.insert (index, name);
  1339. }
  1340. }
  1341. inDeviceNames.appendNumbersToDuplicates (false, false);
  1342. outDeviceNames.appendNumbersToDuplicates (false, false);
  1343. }
  1344. //==============================================================================
  1345. void systemDeviceChanged() override
  1346. {
  1347. StringArray newOutNames, newInNames, newOutIds, newInIds;
  1348. scan (newOutNames, newInNames, newOutIds, newInIds);
  1349. if (newOutNames != outputDeviceNames
  1350. || newInNames != inputDeviceNames
  1351. || newOutIds != outputDeviceIds
  1352. || newInIds != inputDeviceIds)
  1353. {
  1354. hasScanned = true;
  1355. outputDeviceNames = newOutNames;
  1356. inputDeviceNames = newInNames;
  1357. outputDeviceIds = newOutIds;
  1358. inputDeviceIds = newInIds;
  1359. }
  1360. callDeviceChangeListeners();
  1361. }
  1362. //==============================================================================
  1363. JUCE_DECLARE_WEAK_REFERENCEABLE (WASAPIAudioIODeviceType)
  1364. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType)
  1365. };
  1366. //==============================================================================
  1367. struct MMDeviceMasterVolume
  1368. {
  1369. MMDeviceMasterVolume()
  1370. {
  1371. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1372. if (check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1373. {
  1374. ComSmartPtr<IMMDevice> device;
  1375. if (check (enumerator->GetDefaultAudioEndpoint (eRender, eConsole, device.resetAndGetPointerAddress())))
  1376. check (device->Activate (__uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr,
  1377. (void**) endpointVolume.resetAndGetPointerAddress()));
  1378. }
  1379. }
  1380. float getGain() const
  1381. {
  1382. float vol = 0.0f;
  1383. if (endpointVolume != nullptr)
  1384. check (endpointVolume->GetMasterVolumeLevelScalar (&vol));
  1385. return vol;
  1386. }
  1387. bool setGain (float newGain) const
  1388. {
  1389. return endpointVolume != nullptr
  1390. && check (endpointVolume->SetMasterVolumeLevelScalar (jlimit (0.0f, 1.0f, newGain), nullptr));
  1391. }
  1392. bool isMuted() const
  1393. {
  1394. BOOL mute = 0;
  1395. return endpointVolume != nullptr
  1396. && check (endpointVolume->GetMute (&mute)) && mute != 0;
  1397. }
  1398. bool setMuted (bool shouldMute) const
  1399. {
  1400. return endpointVolume != nullptr
  1401. && check (endpointVolume->SetMute (shouldMute, nullptr));
  1402. }
  1403. ComSmartPtr<IAudioEndpointVolume> endpointVolume;
  1404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MMDeviceMasterVolume)
  1405. };
  1406. }
  1407. //==============================================================================
  1408. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI (bool exclusiveMode)
  1409. {
  1410. #if ! JUCE_WASAPI_EXCLUSIVE
  1411. if (exclusiveMode)
  1412. return nullptr;
  1413. #endif
  1414. return SystemStats::getOperatingSystemType() >= SystemStats::WinVista
  1415. ? new WasapiClasses::WASAPIAudioIODeviceType (exclusiveMode)
  1416. : nullptr;
  1417. }
  1418. //==============================================================================
  1419. #define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
  1420. float JUCE_CALLTYPE SystemAudioVolume::getGain() { return WasapiClasses::MMDeviceMasterVolume().getGain(); }
  1421. bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return WasapiClasses::MMDeviceMasterVolume().setGain (gain); }
  1422. bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return WasapiClasses::MMDeviceMasterVolume().isMuted(); }
  1423. bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return WasapiClasses::MMDeviceMasterVolume().setMuted (mute); }
  1424. } // namespace juce