The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1724 lines
62KB

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