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.

1513 lines
55KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef JUCE_WASAPI_LOGGING
  19. #define JUCE_WASAPI_LOGGING 0
  20. #endif
  21. //==============================================================================
  22. namespace WasapiClasses
  23. {
  24. void logFailure (HRESULT hr)
  25. {
  26. (void) hr;
  27. jassert (hr != 0x800401f0); // If you hit this, it means you're trying to call from
  28. // a thread which hasn't been initialised with CoInitialize().
  29. #if JUCE_WASAPI_LOGGING
  30. if (FAILED (hr))
  31. {
  32. const char* m = nullptr;
  33. switch (hr)
  34. {
  35. case E_POINTER: m = "E_POINTER"; break;
  36. case E_INVALIDARG: m = "E_INVALIDARG"; break;
  37. #define JUCE_WASAPI_ERR(desc, n) \
  38. case MAKE_HRESULT(1, 0x889, n): m = #desc; break;
  39. JUCE_WASAPI_ERR (AUDCLNT_E_NOT_INITIALIZED, 0x001)
  40. JUCE_WASAPI_ERR (AUDCLNT_E_ALREADY_INITIALIZED, 0x002)
  41. JUCE_WASAPI_ERR (AUDCLNT_E_WRONG_ENDPOINT_TYPE, 0x003)
  42. JUCE_WASAPI_ERR (AUDCLNT_E_DEVICE_INVALIDATED, 0x004)
  43. JUCE_WASAPI_ERR (AUDCLNT_E_NOT_STOPPED, 0x005)
  44. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_TOO_LARGE, 0x006)
  45. JUCE_WASAPI_ERR (AUDCLNT_E_OUT_OF_ORDER, 0x007)
  46. JUCE_WASAPI_ERR (AUDCLNT_E_UNSUPPORTED_FORMAT, 0x008)
  47. JUCE_WASAPI_ERR (AUDCLNT_E_INVALID_SIZE, 0x009)
  48. JUCE_WASAPI_ERR (AUDCLNT_E_DEVICE_IN_USE, 0x00a)
  49. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_OPERATION_PENDING, 0x00b)
  50. JUCE_WASAPI_ERR (AUDCLNT_E_THREAD_NOT_REGISTERED, 0x00c)
  51. JUCE_WASAPI_ERR (AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED, 0x00e)
  52. JUCE_WASAPI_ERR (AUDCLNT_E_ENDPOINT_CREATE_FAILED, 0x00f)
  53. JUCE_WASAPI_ERR (AUDCLNT_E_SERVICE_NOT_RUNNING, 0x010)
  54. JUCE_WASAPI_ERR (AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED, 0x011)
  55. JUCE_WASAPI_ERR (AUDCLNT_E_EXCLUSIVE_MODE_ONLY, 0x012)
  56. JUCE_WASAPI_ERR (AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL, 0x013)
  57. JUCE_WASAPI_ERR (AUDCLNT_E_EVENTHANDLE_NOT_SET, 0x014)
  58. JUCE_WASAPI_ERR (AUDCLNT_E_INCORRECT_BUFFER_SIZE, 0x015)
  59. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_SIZE_ERROR, 0x016)
  60. JUCE_WASAPI_ERR (AUDCLNT_E_CPUUSAGE_EXCEEDED, 0x017)
  61. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_ERROR, 0x018)
  62. JUCE_WASAPI_ERR (AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED, 0x019)
  63. JUCE_WASAPI_ERR (AUDCLNT_E_INVALID_DEVICE_PERIOD, 0x020)
  64. default: break;
  65. }
  66. Logger::writeToLog ("WASAPI error: " + (m != nullptr ? String (m)
  67. : String::toHexString ((int) hr)));
  68. }
  69. #endif
  70. }
  71. #undef check
  72. bool check (HRESULT hr)
  73. {
  74. logFailure (hr);
  75. return SUCCEEDED (hr);
  76. }
  77. //==============================================================================
  78. }
  79. #if JUCE_MINGW
  80. #define JUCE_COMCLASS(name, guid) \
  81. struct name; \
  82. template<> struct UUIDGetter<name> { static CLSID get() { return uuidFromString (guid); } }; \
  83. struct name
  84. struct PROPERTYKEY
  85. {
  86. GUID fmtid;
  87. DWORD pid;
  88. };
  89. WINOLEAPI PropVariantClear (PROPVARIANT*);
  90. #else
  91. #define JUCE_COMCLASS(name, guid) struct __declspec (uuid (guid)) name
  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 { DEVICE_STATE_ACTIVE = 1 };
  106. JUCE_IUNKNOWNCLASS (IPropertyStore, "886d8eeb-8cf2-4446-8d02-cdba1dbdcf99")
  107. {
  108. JUCE_COMCALL GetCount (DWORD*) = 0;
  109. JUCE_COMCALL GetAt (DWORD, PROPERTYKEY*) = 0;
  110. JUCE_COMCALL GetValue (const PROPERTYKEY&, PROPVARIANT*) = 0;
  111. JUCE_COMCALL SetValue (const PROPERTYKEY&, const PROPVARIANT&) = 0;
  112. JUCE_COMCALL Commit() = 0;
  113. };
  114. JUCE_IUNKNOWNCLASS (IMMDevice, "D666063F-1587-4E43-81F1-B948E807363F")
  115. {
  116. JUCE_COMCALL Activate (REFIID, DWORD, PROPVARIANT*, void**) = 0;
  117. JUCE_COMCALL OpenPropertyStore (DWORD, IPropertyStore**) = 0;
  118. JUCE_COMCALL GetId (LPWSTR*) = 0;
  119. JUCE_COMCALL GetState (DWORD*) = 0;
  120. };
  121. JUCE_IUNKNOWNCLASS (IMMEndpoint, "1BE09788-6894-4089-8586-9A2A6C265AC5")
  122. {
  123. JUCE_COMCALL GetDataFlow (EDataFlow*) = 0;
  124. };
  125. struct IMMDeviceCollection : public IUnknown
  126. {
  127. JUCE_COMCALL GetCount (UINT*) = 0;
  128. JUCE_COMCALL Item (UINT, IMMDevice**) = 0;
  129. };
  130. enum ERole
  131. {
  132. eConsole = 0,
  133. eMultimedia = (eConsole + 1),
  134. eCommunications = (eMultimedia + 1)
  135. };
  136. JUCE_IUNKNOWNCLASS (IMMNotificationClient, "7991EEC9-7E89-4D85-8390-6C703CEC60C0")
  137. {
  138. JUCE_COMCALL OnDeviceStateChanged (LPCWSTR, DWORD) = 0;
  139. JUCE_COMCALL OnDeviceAdded (LPCWSTR) = 0;
  140. JUCE_COMCALL OnDeviceRemoved (LPCWSTR) = 0;
  141. JUCE_COMCALL OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) = 0;
  142. JUCE_COMCALL OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) = 0;
  143. };
  144. JUCE_IUNKNOWNCLASS (IMMDeviceEnumerator, "A95664D2-9614-4F35-A746-DE8DB63617E6")
  145. {
  146. JUCE_COMCALL EnumAudioEndpoints (EDataFlow, DWORD, IMMDeviceCollection**) = 0;
  147. JUCE_COMCALL GetDefaultAudioEndpoint (EDataFlow, ERole, IMMDevice**) = 0;
  148. JUCE_COMCALL GetDevice (LPCWSTR, IMMDevice**) = 0;
  149. JUCE_COMCALL RegisterEndpointNotificationCallback (IMMNotificationClient*) = 0;
  150. JUCE_COMCALL UnregisterEndpointNotificationCallback (IMMNotificationClient*) = 0;
  151. };
  152. JUCE_COMCLASS (MMDeviceEnumerator, "BCDE0395-E52F-467C-8E3D-C4579291692E");
  153. typedef LONGLONG REFERENCE_TIME;
  154. enum AVRT_PRIORITY
  155. {
  156. AVRT_PRIORITY_LOW = -1,
  157. AVRT_PRIORITY_NORMAL,
  158. AVRT_PRIORITY_HIGH,
  159. AVRT_PRIORITY_CRITICAL
  160. };
  161. enum AUDCLNT_SHAREMODE
  162. {
  163. AUDCLNT_SHAREMODE_SHARED,
  164. AUDCLNT_SHAREMODE_EXCLUSIVE
  165. };
  166. JUCE_IUNKNOWNCLASS (IAudioClient, "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")
  167. {
  168. JUCE_COMCALL Initialize (AUDCLNT_SHAREMODE, DWORD, REFERENCE_TIME, REFERENCE_TIME, const WAVEFORMATEX*, LPCGUID) = 0;
  169. JUCE_COMCALL GetBufferSize (UINT32*) = 0;
  170. JUCE_COMCALL GetStreamLatency (REFERENCE_TIME*) = 0;
  171. JUCE_COMCALL GetCurrentPadding (UINT32*) = 0;
  172. JUCE_COMCALL IsFormatSupported (AUDCLNT_SHAREMODE, const WAVEFORMATEX*, WAVEFORMATEX**) = 0;
  173. JUCE_COMCALL GetMixFormat (WAVEFORMATEX**) = 0;
  174. JUCE_COMCALL GetDevicePeriod (REFERENCE_TIME*, REFERENCE_TIME*) = 0;
  175. JUCE_COMCALL Start() = 0;
  176. JUCE_COMCALL Stop() = 0;
  177. JUCE_COMCALL Reset() = 0;
  178. JUCE_COMCALL SetEventHandle (HANDLE) = 0;
  179. JUCE_COMCALL GetService (REFIID, void**) = 0;
  180. };
  181. JUCE_IUNKNOWNCLASS (IAudioCaptureClient, "C8ADBD64-E71E-48a0-A4DE-185C395CD317")
  182. {
  183. JUCE_COMCALL GetBuffer (BYTE**, UINT32*, DWORD*, UINT64*, UINT64*) = 0;
  184. JUCE_COMCALL ReleaseBuffer (UINT32) = 0;
  185. JUCE_COMCALL GetNextPacketSize (UINT32*) = 0;
  186. };
  187. JUCE_IUNKNOWNCLASS (IAudioRenderClient, "F294ACFC-3146-4483-A7BF-ADDCA7C260E2")
  188. {
  189. JUCE_COMCALL GetBuffer (UINT32, BYTE**) = 0;
  190. JUCE_COMCALL ReleaseBuffer (UINT32, DWORD) = 0;
  191. };
  192. JUCE_IUNKNOWNCLASS (IAudioEndpointVolume, "5CDF2C82-841E-4546-9722-0CF74078229A")
  193. {
  194. JUCE_COMCALL RegisterControlChangeNotify (void*) = 0;
  195. JUCE_COMCALL UnregisterControlChangeNotify (void*) = 0;
  196. JUCE_COMCALL GetChannelCount (UINT*) = 0;
  197. JUCE_COMCALL SetMasterVolumeLevel (float, LPCGUID) = 0;
  198. JUCE_COMCALL SetMasterVolumeLevelScalar (float, LPCGUID) = 0;
  199. JUCE_COMCALL GetMasterVolumeLevel (float*) = 0;
  200. JUCE_COMCALL GetMasterVolumeLevelScalar (float*) = 0;
  201. JUCE_COMCALL SetChannelVolumeLevel (UINT, float, LPCGUID) = 0;
  202. JUCE_COMCALL SetChannelVolumeLevelScalar (UINT, float, LPCGUID) = 0;
  203. JUCE_COMCALL GetChannelVolumeLevel (UINT, float*) = 0;
  204. JUCE_COMCALL GetChannelVolumeLevelScalar (UINT, float*) = 0;
  205. JUCE_COMCALL SetMute (BOOL, LPCGUID) = 0;
  206. JUCE_COMCALL GetMute (BOOL*) = 0;
  207. JUCE_COMCALL GetVolumeStepInfo (UINT*, UINT*) = 0;
  208. JUCE_COMCALL VolumeStepUp (LPCGUID) = 0;
  209. JUCE_COMCALL VolumeStepDown (LPCGUID) = 0;
  210. JUCE_COMCALL QueryHardwareSupport (DWORD*) = 0;
  211. JUCE_COMCALL GetVolumeRange (float*, float*, float*) = 0;
  212. };
  213. enum AudioSessionDisconnectReason
  214. {
  215. DisconnectReasonDeviceRemoval = 0,
  216. DisconnectReasonServerShutdown = 1,
  217. DisconnectReasonFormatChanged = 2,
  218. DisconnectReasonSessionLogoff = 3,
  219. DisconnectReasonSessionDisconnected = 4,
  220. DisconnectReasonExclusiveModeOverride = 5
  221. };
  222. enum AudioSessionState
  223. {
  224. AudioSessionStateInactive = 0,
  225. AudioSessionStateActive = 1,
  226. AudioSessionStateExpired = 2
  227. };
  228. JUCE_IUNKNOWNCLASS (IAudioSessionEvents, "24918ACC-64B3-37C1-8CA9-74A66E9957A8")
  229. {
  230. JUCE_COMCALL OnDisplayNameChanged (LPCWSTR, LPCGUID) = 0;
  231. JUCE_COMCALL OnIconPathChanged (LPCWSTR, LPCGUID) = 0;
  232. JUCE_COMCALL OnSimpleVolumeChanged (float, BOOL, LPCGUID) = 0;
  233. JUCE_COMCALL OnChannelVolumeChanged (DWORD, float*, DWORD, LPCGUID) = 0;
  234. JUCE_COMCALL OnGroupingParamChanged (LPCGUID, LPCGUID) = 0;
  235. JUCE_COMCALL OnStateChanged (AudioSessionState) = 0;
  236. JUCE_COMCALL OnSessionDisconnected (AudioSessionDisconnectReason) = 0;
  237. };
  238. JUCE_IUNKNOWNCLASS (IAudioSessionControl, "F4B1A599-7266-4319-A8CA-E70ACB11E8CD")
  239. {
  240. JUCE_COMCALL GetState (AudioSessionState*) = 0;
  241. JUCE_COMCALL GetDisplayName (LPWSTR*) = 0;
  242. JUCE_COMCALL SetDisplayName (LPCWSTR, LPCGUID) = 0;
  243. JUCE_COMCALL GetIconPath (LPWSTR*) = 0;
  244. JUCE_COMCALL SetIconPath (LPCWSTR, LPCGUID) = 0;
  245. JUCE_COMCALL GetGroupingParam (GUID*) = 0;
  246. JUCE_COMCALL SetGroupingParam (LPCGUID, LPCGUID) = 0;
  247. JUCE_COMCALL RegisterAudioSessionNotification (IAudioSessionEvents*) = 0;
  248. JUCE_COMCALL UnregisterAudioSessionNotification (IAudioSessionEvents*) = 0;
  249. };
  250. #undef JUCE_COMCALL
  251. #undef JUCE_COMCLASS
  252. #undef JUCE_IUNKNOWNCLASS
  253. //==============================================================================
  254. namespace WasapiClasses
  255. {
  256. String getDeviceID (IMMDevice* const device)
  257. {
  258. String s;
  259. WCHAR* deviceId = nullptr;
  260. if (check (device->GetId (&deviceId)))
  261. {
  262. s = String (deviceId);
  263. CoTaskMemFree (deviceId);
  264. }
  265. return s;
  266. }
  267. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  268. {
  269. EDataFlow flow = eRender;
  270. ComSmartPtr <IMMEndpoint> endPoint;
  271. if (check (device.QueryInterface (endPoint)))
  272. (void) check (endPoint->GetDataFlow (&flow));
  273. return flow;
  274. }
  275. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) noexcept
  276. {
  277. return roundToInt (sampleRate * ((double) t) * 0.0000001);
  278. }
  279. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) noexcept
  280. {
  281. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  282. : sizeof (WAVEFORMATEX));
  283. }
  284. //==============================================================================
  285. class WASAPIDeviceBase
  286. {
  287. public:
  288. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& d, const bool exclusiveMode)
  289. : device (d),
  290. sampleRate (0),
  291. defaultSampleRate (0),
  292. numChannels (0),
  293. actualNumChannels (0),
  294. minBufferSize (0),
  295. defaultBufferSize (0),
  296. latencySamples (0),
  297. useExclusiveMode (exclusiveMode),
  298. sampleRateHasChanged (false)
  299. {
  300. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  301. ComSmartPtr <IAudioClient> tempClient (createClient());
  302. if (tempClient == nullptr)
  303. return;
  304. REFERENCE_TIME defaultPeriod, minPeriod;
  305. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  306. return;
  307. WAVEFORMATEX* mixFormat = nullptr;
  308. if (! check (tempClient->GetMixFormat (&mixFormat)))
  309. return;
  310. WAVEFORMATEXTENSIBLE format;
  311. copyWavFormat (format, mixFormat);
  312. CoTaskMemFree (mixFormat);
  313. actualNumChannels = numChannels = format.Format.nChannels;
  314. defaultSampleRate = format.Format.nSamplesPerSec;
  315. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  316. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  317. mixFormatChannelMask = format.dwChannelMask;
  318. rates.addUsingDefaultSort (defaultSampleRate);
  319. static const int ratesToTest[] = { 44100, 48000, 88200, 96000, 176400, 192000 };
  320. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  321. {
  322. if (ratesToTest[i] == defaultSampleRate)
  323. continue;
  324. format.Format.nSamplesPerSec = (DWORD) ratesToTest[i];
  325. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  326. (WAVEFORMATEX*) &format, 0)))
  327. if (! rates.contains (ratesToTest[i]))
  328. rates.addUsingDefaultSort (ratesToTest[i]);
  329. }
  330. }
  331. virtual ~WASAPIDeviceBase()
  332. {
  333. device = nullptr;
  334. CloseHandle (clientEvent);
  335. }
  336. bool isOk() const noexcept { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  337. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  338. {
  339. sampleRate = newSampleRate;
  340. channels = newChannels;
  341. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  342. numChannels = channels.getHighestBit() + 1;
  343. if (numChannels == 0)
  344. return true;
  345. client = createClient();
  346. if (client != nullptr
  347. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  348. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  349. {
  350. sampleRateHasChanged = false;
  351. channelMaps.clear();
  352. for (int i = 0; i <= channels.getHighestBit(); ++i)
  353. if (channels[i])
  354. channelMaps.add (i);
  355. REFERENCE_TIME latency;
  356. if (check (client->GetStreamLatency (&latency)))
  357. latencySamples = refTimeToSamples (latency, sampleRate);
  358. (void) check (client->GetBufferSize (&actualBufferSize));
  359. createSessionEventCallback();
  360. return check (client->SetEventHandle (clientEvent));
  361. }
  362. return false;
  363. }
  364. void closeClient()
  365. {
  366. if (client != nullptr)
  367. client->Stop();
  368. deleteSessionEventCallback();
  369. client = nullptr;
  370. ResetEvent (clientEvent);
  371. }
  372. void deviceSampleRateChanged()
  373. {
  374. sampleRateHasChanged = true;
  375. }
  376. //==============================================================================
  377. ComSmartPtr <IMMDevice> device;
  378. ComSmartPtr <IAudioClient> client;
  379. double sampleRate, defaultSampleRate;
  380. int numChannels, actualNumChannels;
  381. int minBufferSize, defaultBufferSize, latencySamples;
  382. DWORD mixFormatChannelMask;
  383. const bool useExclusiveMode;
  384. Array <double> rates;
  385. HANDLE clientEvent;
  386. BigInteger channels;
  387. Array <int> channelMaps;
  388. UINT32 actualBufferSize;
  389. int bytesPerSample;
  390. bool sampleRateHasChanged;
  391. virtual void updateFormat (bool isFloat) = 0;
  392. private:
  393. //==============================================================================
  394. class SessionEventCallback : public ComBaseClassHelper <IAudioSessionEvents>
  395. {
  396. public:
  397. SessionEventCallback (WASAPIDeviceBase& d) : owner (d) {}
  398. JUCE_COMRESULT OnDisplayNameChanged (LPCWSTR, LPCGUID) { return S_OK; }
  399. JUCE_COMRESULT OnIconPathChanged (LPCWSTR, LPCGUID) { return S_OK; }
  400. JUCE_COMRESULT OnSimpleVolumeChanged (float, BOOL, LPCGUID) { return S_OK; }
  401. JUCE_COMRESULT OnChannelVolumeChanged (DWORD, float*, DWORD, LPCGUID) { return S_OK; }
  402. JUCE_COMRESULT OnGroupingParamChanged (LPCGUID, LPCGUID) { return S_OK; }
  403. JUCE_COMRESULT OnStateChanged (AudioSessionState) { return S_OK; }
  404. JUCE_COMRESULT OnSessionDisconnected (AudioSessionDisconnectReason reason)
  405. {
  406. if (reason == DisconnectReasonFormatChanged)
  407. owner.deviceSampleRateChanged();
  408. return S_OK;
  409. }
  410. private:
  411. WASAPIDeviceBase& owner;
  412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionEventCallback)
  413. };
  414. ComSmartPtr <IAudioSessionControl> audioSessionControl;
  415. ComSmartPtr <SessionEventCallback> sessionEventCallback;
  416. void createSessionEventCallback()
  417. {
  418. deleteSessionEventCallback();
  419. client->GetService (__uuidof (IAudioSessionControl),
  420. (void**) audioSessionControl.resetAndGetPointerAddress());
  421. if (audioSessionControl != nullptr)
  422. {
  423. sessionEventCallback = new SessionEventCallback (*this);
  424. audioSessionControl->RegisterAudioSessionNotification (sessionEventCallback);
  425. sessionEventCallback->Release(); // (required because ComBaseClassHelper objects are constructed with a ref count of 1)
  426. }
  427. }
  428. void deleteSessionEventCallback()
  429. {
  430. if (audioSessionControl != nullptr && sessionEventCallback != nullptr)
  431. audioSessionControl->UnregisterAudioSessionNotification (sessionEventCallback);
  432. audioSessionControl = nullptr;
  433. sessionEventCallback = nullptr;
  434. }
  435. //==============================================================================
  436. const ComSmartPtr <IAudioClient> createClient()
  437. {
  438. ComSmartPtr <IAudioClient> client;
  439. if (device != nullptr)
  440. {
  441. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER,
  442. nullptr, (void**) client.resetAndGetPointerAddress());
  443. logFailure (hr);
  444. }
  445. return client;
  446. }
  447. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  448. {
  449. WAVEFORMATEXTENSIBLE format;
  450. zerostruct (format);
  451. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  452. {
  453. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  454. }
  455. else
  456. {
  457. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  458. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  459. }
  460. format.Format.nSamplesPerSec = (DWORD) sampleRate;
  461. format.Format.nChannels = (WORD) numChannels;
  462. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  463. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  464. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  465. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  466. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  467. format.dwChannelMask = mixFormatChannelMask;
  468. WAVEFORMATEXTENSIBLE* nearestFormat = nullptr;
  469. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE
  470. : AUDCLNT_SHAREMODE_SHARED,
  471. (WAVEFORMATEX*) &format,
  472. useExclusiveMode ? nullptr : (WAVEFORMATEX**) &nearestFormat);
  473. logFailure (hr);
  474. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  475. {
  476. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  477. hr = S_OK;
  478. }
  479. CoTaskMemFree (nearestFormat);
  480. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  481. if (useExclusiveMode)
  482. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  483. GUID session;
  484. if (hr == S_OK
  485. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  486. 0x40000 /*AUDCLNT_STREAMFLAGS_EVENTCALLBACK*/,
  487. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  488. {
  489. actualNumChannels = format.Format.nChannels;
  490. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  491. bytesPerSample = format.Format.wBitsPerSample / 8;
  492. updateFormat (isFloat);
  493. return true;
  494. }
  495. return false;
  496. }
  497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase)
  498. };
  499. //==============================================================================
  500. class WASAPIInputDevice : public WASAPIDeviceBase
  501. {
  502. public:
  503. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& d, const bool exclusiveMode)
  504. : WASAPIDeviceBase (d, exclusiveMode),
  505. reservoir (1, 1)
  506. {
  507. }
  508. ~WASAPIInputDevice()
  509. {
  510. close();
  511. }
  512. bool open (const double newSampleRate, const BigInteger& newChannels)
  513. {
  514. reservoirSize = 0;
  515. reservoirCapacity = 16384;
  516. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  517. return openClient (newSampleRate, newChannels)
  518. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  519. (void**) captureClient.resetAndGetPointerAddress())));
  520. }
  521. void close()
  522. {
  523. closeClient();
  524. captureClient = nullptr;
  525. reservoir.setSize (0);
  526. }
  527. template <class SourceType>
  528. void updateFormatWithType (SourceType*)
  529. {
  530. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  531. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  532. }
  533. void updateFormat (bool isFloat)
  534. {
  535. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  536. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  537. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  538. else updateFormatWithType ((AudioData::Int16*) 0);
  539. }
  540. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  541. {
  542. if (numChannels <= 0)
  543. return;
  544. int offset = 0;
  545. while (bufferSize > 0)
  546. {
  547. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  548. {
  549. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  550. for (int i = 0; i < numDestBuffers; ++i)
  551. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  552. bufferSize -= samplesToDo;
  553. offset += samplesToDo;
  554. reservoirSize = 0;
  555. }
  556. else
  557. {
  558. UINT32 packetLength = 0;
  559. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  560. break;
  561. if (packetLength == 0)
  562. {
  563. if (thread.threadShouldExit()
  564. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  565. break;
  566. continue;
  567. }
  568. uint8* inputData;
  569. UINT32 numSamplesAvailable;
  570. DWORD flags;
  571. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  572. {
  573. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  574. for (int i = 0; i < numDestBuffers; ++i)
  575. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  576. bufferSize -= samplesToDo;
  577. offset += samplesToDo;
  578. if (samplesToDo < (int) numSamplesAvailable)
  579. {
  580. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  581. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  582. (size_t) (bytesPerSample * actualNumChannels * reservoirSize));
  583. }
  584. captureClient->ReleaseBuffer (numSamplesAvailable);
  585. }
  586. }
  587. }
  588. }
  589. ComSmartPtr <IAudioCaptureClient> captureClient;
  590. MemoryBlock reservoir;
  591. int reservoirSize, reservoirCapacity;
  592. ScopedPointer <AudioData::Converter> converter;
  593. private:
  594. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice)
  595. };
  596. //==============================================================================
  597. class WASAPIOutputDevice : public WASAPIDeviceBase
  598. {
  599. public:
  600. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& d, const bool exclusiveMode)
  601. : WASAPIDeviceBase (d, exclusiveMode)
  602. {
  603. }
  604. ~WASAPIOutputDevice()
  605. {
  606. close();
  607. }
  608. bool open (const double newSampleRate, const BigInteger& newChannels)
  609. {
  610. return openClient (newSampleRate, newChannels)
  611. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  612. }
  613. void close()
  614. {
  615. closeClient();
  616. renderClient = nullptr;
  617. }
  618. template <class DestType>
  619. void updateFormatWithType (DestType*)
  620. {
  621. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  622. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  623. }
  624. void updateFormat (bool isFloat)
  625. {
  626. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  627. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  628. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  629. else updateFormatWithType ((AudioData::Int16*) 0);
  630. }
  631. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  632. {
  633. if (numChannels <= 0)
  634. return;
  635. int offset = 0;
  636. while (bufferSize > 0)
  637. {
  638. UINT32 padding = 0;
  639. if (! check (client->GetCurrentPadding (&padding)))
  640. return;
  641. int samplesToDo = useExclusiveMode ? bufferSize
  642. : jmin ((int) (actualBufferSize - padding), bufferSize);
  643. if (samplesToDo <= 0)
  644. {
  645. if (thread.threadShouldExit()
  646. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  647. break;
  648. continue;
  649. }
  650. uint8* outputData = nullptr;
  651. if (check (renderClient->GetBuffer ((UINT32) samplesToDo, &outputData)))
  652. {
  653. for (int i = 0; i < numSrcBuffers; ++i)
  654. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  655. renderClient->ReleaseBuffer ((UINT32) samplesToDo, 0);
  656. offset += samplesToDo;
  657. bufferSize -= samplesToDo;
  658. }
  659. }
  660. }
  661. ComSmartPtr <IAudioRenderClient> renderClient;
  662. ScopedPointer <AudioData::Converter> converter;
  663. private:
  664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice)
  665. };
  666. //==============================================================================
  667. class WASAPIAudioIODevice : public AudioIODevice,
  668. public Thread,
  669. private AsyncUpdater
  670. {
  671. public:
  672. WASAPIAudioIODevice (const String& deviceName,
  673. const String& outputDeviceId_,
  674. const String& inputDeviceId_,
  675. const bool exclusiveMode)
  676. : AudioIODevice (deviceName, "Windows Audio"),
  677. Thread ("Juce WASAPI"),
  678. outputDeviceId (outputDeviceId_),
  679. inputDeviceId (inputDeviceId_),
  680. useExclusiveMode (exclusiveMode),
  681. isOpen_ (false),
  682. isStarted (false),
  683. currentBufferSizeSamples (0),
  684. currentSampleRate (0),
  685. callback (nullptr)
  686. {
  687. }
  688. ~WASAPIAudioIODevice()
  689. {
  690. close();
  691. }
  692. bool initialise()
  693. {
  694. latencyIn = latencyOut = 0;
  695. Array <double> ratesIn, ratesOut;
  696. if (createDevices())
  697. {
  698. jassert (inputDevice != nullptr || outputDevice != nullptr);
  699. if (inputDevice != nullptr && outputDevice != nullptr)
  700. {
  701. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  702. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  703. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  704. sampleRates = inputDevice->rates;
  705. sampleRates.removeValuesNotIn (outputDevice->rates);
  706. }
  707. else
  708. {
  709. WASAPIDeviceBase* d = inputDevice != nullptr ? static_cast<WASAPIDeviceBase*> (inputDevice)
  710. : static_cast<WASAPIDeviceBase*> (outputDevice);
  711. defaultSampleRate = d->defaultSampleRate;
  712. minBufferSize = d->minBufferSize;
  713. defaultBufferSize = d->defaultBufferSize;
  714. sampleRates = d->rates;
  715. }
  716. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  717. if (minBufferSize != defaultBufferSize)
  718. bufferSizes.addUsingDefaultSort (minBufferSize);
  719. int n = 64;
  720. for (int i = 0; i < 40; ++i)
  721. {
  722. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  723. bufferSizes.addUsingDefaultSort (n);
  724. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  725. }
  726. return true;
  727. }
  728. return false;
  729. }
  730. StringArray getOutputChannelNames()
  731. {
  732. StringArray outChannels;
  733. if (outputDevice != nullptr)
  734. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  735. outChannels.add ("Output channel " + String (i));
  736. return outChannels;
  737. }
  738. StringArray getInputChannelNames()
  739. {
  740. StringArray inChannels;
  741. if (inputDevice != nullptr)
  742. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  743. inChannels.add ("Input channel " + String (i));
  744. return inChannels;
  745. }
  746. int getNumSampleRates() { return sampleRates.size(); }
  747. double getSampleRate (int index) { return sampleRates [index]; }
  748. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  749. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  750. int getDefaultBufferSize() { return defaultBufferSize; }
  751. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  752. double getCurrentSampleRate() { return currentSampleRate; }
  753. int getCurrentBitDepth() { return 32; }
  754. int getOutputLatencyInSamples() { return latencyOut; }
  755. int getInputLatencyInSamples() { return latencyIn; }
  756. BigInteger getActiveOutputChannels() const { return outputDevice != nullptr ? outputDevice->channels : BigInteger(); }
  757. BigInteger getActiveInputChannels() const { return inputDevice != nullptr ? inputDevice->channels : BigInteger(); }
  758. String getLastError() { return lastError; }
  759. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  760. double sampleRate, int bufferSizeSamples)
  761. {
  762. close();
  763. lastError = String::empty;
  764. if (sampleRates.size() == 0 && inputDevice != nullptr && outputDevice != nullptr)
  765. {
  766. lastError = "The input and output devices don't share a common sample rate!";
  767. return lastError;
  768. }
  769. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  770. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  771. lastKnownInputChannels = inputChannels;
  772. lastKnownOutputChannels = outputChannels;
  773. if (inputDevice != nullptr && ! inputDevice->open (currentSampleRate, inputChannels))
  774. {
  775. lastError = "Couldn't open the input device!";
  776. return lastError;
  777. }
  778. if (outputDevice != nullptr && ! outputDevice->open (currentSampleRate, outputChannels))
  779. {
  780. close();
  781. lastError = "Couldn't open the output device!";
  782. return lastError;
  783. }
  784. if (inputDevice != nullptr) ResetEvent (inputDevice->clientEvent);
  785. if (outputDevice != nullptr) ResetEvent (outputDevice->clientEvent);
  786. startThread (8);
  787. Thread::sleep (5);
  788. if (inputDevice != nullptr && inputDevice->client != nullptr)
  789. {
  790. latencyIn = (int) (inputDevice->latencySamples + currentBufferSizeSamples);
  791. if (! check (inputDevice->client->Start()))
  792. {
  793. close();
  794. lastError = "Couldn't start the input device!";
  795. return lastError;
  796. }
  797. }
  798. if (outputDevice != nullptr && outputDevice->client != nullptr)
  799. {
  800. latencyOut = (int) (outputDevice->latencySamples + currentBufferSizeSamples);
  801. if (! check (outputDevice->client->Start()))
  802. {
  803. close();
  804. lastError = "Couldn't start the output device!";
  805. return lastError;
  806. }
  807. }
  808. isOpen_ = true;
  809. return lastError;
  810. }
  811. void close()
  812. {
  813. stop();
  814. signalThreadShouldExit();
  815. if (inputDevice != nullptr) SetEvent (inputDevice->clientEvent);
  816. if (outputDevice != nullptr) SetEvent (outputDevice->clientEvent);
  817. stopThread (5000);
  818. if (inputDevice != nullptr) inputDevice->close();
  819. if (outputDevice != nullptr) outputDevice->close();
  820. isOpen_ = false;
  821. }
  822. bool isOpen() { return isOpen_ && isThreadRunning(); }
  823. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  824. void start (AudioIODeviceCallback* call)
  825. {
  826. if (isOpen_ && call != nullptr && ! isStarted)
  827. {
  828. if (! isThreadRunning())
  829. {
  830. // something's gone wrong and the thread's stopped..
  831. isOpen_ = false;
  832. return;
  833. }
  834. call->audioDeviceAboutToStart (this);
  835. const ScopedLock sl (startStopLock);
  836. callback = call;
  837. isStarted = true;
  838. }
  839. }
  840. void stop()
  841. {
  842. if (isStarted)
  843. {
  844. AudioIODeviceCallback* const callbackLocal = callback;
  845. {
  846. const ScopedLock sl (startStopLock);
  847. isStarted = false;
  848. }
  849. if (callbackLocal != nullptr)
  850. callbackLocal->audioDeviceStopped();
  851. }
  852. }
  853. void setMMThreadPriority()
  854. {
  855. DynamicLibrary dll ("avrt.dll");
  856. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, (LPCWSTR, LPDWORD))
  857. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, (HANDLE, AVRT_PRIORITY))
  858. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  859. {
  860. DWORD dummy = 0;
  861. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  862. if (h != 0)
  863. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  864. }
  865. }
  866. void run()
  867. {
  868. setMMThreadPriority();
  869. const int bufferSize = currentBufferSizeSamples;
  870. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  871. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  872. bool sampleRateChanged = false;
  873. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  874. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  875. float** const inputBuffers = ins.getArrayOfChannels();
  876. float** const outputBuffers = outs.getArrayOfChannels();
  877. ins.clear();
  878. while (! threadShouldExit())
  879. {
  880. if (inputDevice != nullptr)
  881. {
  882. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  883. if (threadShouldExit())
  884. break;
  885. if (inputDevice->sampleRateHasChanged)
  886. {
  887. sampleRateChanged = true;
  888. sampleRateChangedByOutput = false;
  889. }
  890. }
  891. {
  892. const ScopedLock sl (startStopLock);
  893. if (isStarted)
  894. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  895. outputBuffers, numOutputBuffers, bufferSize);
  896. else
  897. outs.clear();
  898. }
  899. if (outputDevice != nullptr)
  900. {
  901. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  902. if (outputDevice->sampleRateHasChanged)
  903. {
  904. sampleRateChanged = true;
  905. sampleRateChangedByOutput = true;
  906. }
  907. }
  908. if (sampleRateChanged)
  909. {
  910. triggerAsyncUpdate();
  911. break; // Quit the thread... will restart it later!
  912. }
  913. }
  914. }
  915. //==============================================================================
  916. String outputDeviceId, inputDeviceId;
  917. String lastError;
  918. private:
  919. // Device stats...
  920. ScopedPointer<WASAPIInputDevice> inputDevice;
  921. ScopedPointer<WASAPIOutputDevice> outputDevice;
  922. const bool useExclusiveMode;
  923. double defaultSampleRate;
  924. int minBufferSize, defaultBufferSize;
  925. int latencyIn, latencyOut;
  926. Array <double> sampleRates;
  927. Array <int> bufferSizes;
  928. // Active state...
  929. bool isOpen_, isStarted;
  930. int currentBufferSizeSamples;
  931. double currentSampleRate;
  932. bool sampleRateChangedByOutput;
  933. AudioIODeviceCallback* callback;
  934. CriticalSection startStopLock;
  935. BigInteger lastKnownInputChannels, lastKnownOutputChannels;
  936. //==============================================================================
  937. bool createDevices()
  938. {
  939. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  940. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  941. return false;
  942. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  943. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  944. return false;
  945. UINT32 numDevices = 0;
  946. if (! check (deviceCollection->GetCount (&numDevices)))
  947. return false;
  948. for (UINT32 i = 0; i < numDevices; ++i)
  949. {
  950. ComSmartPtr <IMMDevice> device;
  951. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  952. continue;
  953. const String deviceId (getDeviceID (device));
  954. if (deviceId.isEmpty())
  955. continue;
  956. const EDataFlow flow = getDataFlow (device);
  957. if (deviceId == inputDeviceId && flow == eCapture)
  958. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  959. else if (deviceId == outputDeviceId && flow == eRender)
  960. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  961. }
  962. return (outputDeviceId.isEmpty() || (outputDevice != nullptr && outputDevice->isOk()))
  963. && (inputDeviceId.isEmpty() || (inputDevice != nullptr && inputDevice->isOk()));
  964. }
  965. //==============================================================================
  966. void handleAsyncUpdate()
  967. {
  968. stop();
  969. outputDevice = nullptr;
  970. inputDevice = nullptr;
  971. initialise();
  972. open (lastKnownInputChannels, lastKnownOutputChannels,
  973. getChangedSampleRate(), currentBufferSizeSamples);
  974. start (callback);
  975. }
  976. double getChangedSampleRate() const
  977. {
  978. if (outputDevice != nullptr && sampleRateChangedByOutput)
  979. return outputDevice->defaultSampleRate;
  980. if (inputDevice != nullptr && ! sampleRateChangedByOutput)
  981. return inputDevice->defaultSampleRate;
  982. return 0.0;
  983. }
  984. //==============================================================================
  985. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice)
  986. };
  987. //==============================================================================
  988. class WASAPIAudioIODeviceType : public AudioIODeviceType,
  989. private DeviceChangeDetector
  990. {
  991. public:
  992. WASAPIAudioIODeviceType()
  993. : AudioIODeviceType ("Windows Audio"),
  994. DeviceChangeDetector (L"Windows Audio"),
  995. hasScanned (false)
  996. {
  997. }
  998. ~WASAPIAudioIODeviceType()
  999. {
  1000. if (notifyClient != nullptr)
  1001. enumerator->UnregisterEndpointNotificationCallback (notifyClient);
  1002. }
  1003. //==============================================================================
  1004. void scanForDevices()
  1005. {
  1006. hasScanned = true;
  1007. outputDeviceNames.clear();
  1008. inputDeviceNames.clear();
  1009. outputDeviceIds.clear();
  1010. inputDeviceIds.clear();
  1011. scan (outputDeviceNames, inputDeviceNames,
  1012. outputDeviceIds, inputDeviceIds);
  1013. }
  1014. StringArray getDeviceNames (bool wantInputNames) const
  1015. {
  1016. jassert (hasScanned); // need to call scanForDevices() before doing this
  1017. return wantInputNames ? inputDeviceNames
  1018. : outputDeviceNames;
  1019. }
  1020. int getDefaultDeviceIndex (bool /*forInput*/) const
  1021. {
  1022. jassert (hasScanned); // need to call scanForDevices() before doing this
  1023. return 0;
  1024. }
  1025. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  1026. {
  1027. jassert (hasScanned); // need to call scanForDevices() before doing this
  1028. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  1029. return d == nullptr ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  1030. : outputDeviceIds.indexOf (d->outputDeviceId));
  1031. }
  1032. bool hasSeparateInputsAndOutputs() const { return true; }
  1033. AudioIODevice* createDevice (const String& outputDeviceName,
  1034. const String& inputDeviceName)
  1035. {
  1036. jassert (hasScanned); // need to call scanForDevices() before doing this
  1037. const bool useExclusiveMode = false;
  1038. ScopedPointer<WASAPIAudioIODevice> device;
  1039. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  1040. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  1041. if (outputIndex >= 0 || inputIndex >= 0)
  1042. {
  1043. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1044. : inputDeviceName,
  1045. outputDeviceIds [outputIndex],
  1046. inputDeviceIds [inputIndex],
  1047. useExclusiveMode);
  1048. if (! device->initialise())
  1049. device = nullptr;
  1050. }
  1051. return device.release();
  1052. }
  1053. //==============================================================================
  1054. StringArray outputDeviceNames, outputDeviceIds;
  1055. StringArray inputDeviceNames, inputDeviceIds;
  1056. private:
  1057. bool hasScanned;
  1058. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1059. //==============================================================================
  1060. class ChangeNotificationClient : public ComBaseClassHelper<IMMNotificationClient>
  1061. {
  1062. public:
  1063. ChangeNotificationClient (WASAPIAudioIODeviceType& d)
  1064. : ComBaseClassHelper <IMMNotificationClient> (0), device (d) {}
  1065. HRESULT STDMETHODCALLTYPE OnDeviceAdded (LPCWSTR) { return notify(); }
  1066. HRESULT STDMETHODCALLTYPE OnDeviceRemoved (LPCWSTR) { return notify(); }
  1067. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged (LPCWSTR, DWORD) { return notify(); }
  1068. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) { return notify(); }
  1069. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) { return notify(); }
  1070. private:
  1071. WASAPIAudioIODeviceType& device;
  1072. HRESULT notify() { device.triggerAsyncDeviceChangeCallback(); return S_OK; }
  1073. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeNotificationClient)
  1074. };
  1075. ComSmartPtr<ChangeNotificationClient> notifyClient;
  1076. //==============================================================================
  1077. static String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  1078. {
  1079. String s;
  1080. IMMDevice* dev = nullptr;
  1081. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  1082. eMultimedia, &dev)))
  1083. {
  1084. WCHAR* deviceId = nullptr;
  1085. if (check (dev->GetId (&deviceId)))
  1086. {
  1087. s = deviceId;
  1088. CoTaskMemFree (deviceId);
  1089. }
  1090. dev->Release();
  1091. }
  1092. return s;
  1093. }
  1094. //==============================================================================
  1095. void scan (StringArray& outputDeviceNames,
  1096. StringArray& inputDeviceNames,
  1097. StringArray& outputDeviceIds,
  1098. StringArray& inputDeviceIds)
  1099. {
  1100. if (enumerator == nullptr)
  1101. {
  1102. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1103. return;
  1104. notifyClient = new ChangeNotificationClient (*this);
  1105. enumerator->RegisterEndpointNotificationCallback (notifyClient);
  1106. }
  1107. const String defaultRenderer (getDefaultEndpoint (enumerator, false));
  1108. const String defaultCapture (getDefaultEndpoint (enumerator, true));
  1109. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  1110. UINT32 numDevices = 0;
  1111. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  1112. && check (deviceCollection->GetCount (&numDevices))))
  1113. return;
  1114. for (UINT32 i = 0; i < numDevices; ++i)
  1115. {
  1116. ComSmartPtr <IMMDevice> device;
  1117. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1118. continue;
  1119. DWORD state = 0;
  1120. if (! (check (device->GetState (&state)) && state == DEVICE_STATE_ACTIVE))
  1121. continue;
  1122. const String deviceId (getDeviceID (device));
  1123. String name;
  1124. {
  1125. ComSmartPtr <IPropertyStore> properties;
  1126. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  1127. continue;
  1128. PROPVARIANT value;
  1129. zerostruct (value);
  1130. const PROPERTYKEY PKEY_Device_FriendlyName
  1131. = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 };
  1132. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  1133. name = value.pwszVal;
  1134. PropVariantClear (&value);
  1135. }
  1136. const EDataFlow flow = getDataFlow (device);
  1137. if (flow == eRender)
  1138. {
  1139. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  1140. outputDeviceIds.insert (index, deviceId);
  1141. outputDeviceNames.insert (index, name);
  1142. }
  1143. else if (flow == eCapture)
  1144. {
  1145. const int index = (deviceId == defaultCapture) ? 0 : -1;
  1146. inputDeviceIds.insert (index, deviceId);
  1147. inputDeviceNames.insert (index, name);
  1148. }
  1149. }
  1150. inputDeviceNames.appendNumbersToDuplicates (false, false);
  1151. outputDeviceNames.appendNumbersToDuplicates (false, false);
  1152. }
  1153. //==============================================================================
  1154. void systemDeviceChanged()
  1155. {
  1156. StringArray newOutNames, newInNames, newOutIds, newInIds;
  1157. scan (newOutNames, newInNames, newOutIds, newInIds);
  1158. if (newOutNames != outputDeviceNames
  1159. || newInNames != inputDeviceNames
  1160. || newOutIds != outputDeviceIds
  1161. || newInIds != inputDeviceIds)
  1162. {
  1163. hasScanned = true;
  1164. outputDeviceNames = newOutNames;
  1165. inputDeviceNames = newInNames;
  1166. outputDeviceIds = newOutIds;
  1167. inputDeviceIds = newInIds;
  1168. }
  1169. callDeviceChangeListeners();
  1170. }
  1171. //==============================================================================
  1172. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType)
  1173. };
  1174. //==============================================================================
  1175. struct MMDeviceMasterVolume
  1176. {
  1177. MMDeviceMasterVolume()
  1178. {
  1179. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1180. if (check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1181. {
  1182. ComSmartPtr<IMMDevice> device;
  1183. if (check (enumerator->GetDefaultAudioEndpoint (eRender, eConsole, device.resetAndGetPointerAddress())))
  1184. check (device->Activate (__uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr,
  1185. (void**) endpointVolume.resetAndGetPointerAddress()));
  1186. }
  1187. }
  1188. float getGain() const
  1189. {
  1190. float vol = 0.0f;
  1191. if (endpointVolume != nullptr)
  1192. check (endpointVolume->GetMasterVolumeLevelScalar (&vol));
  1193. return vol;
  1194. }
  1195. bool setGain (float newGain) const
  1196. {
  1197. return endpointVolume != nullptr
  1198. && check (endpointVolume->SetMasterVolumeLevelScalar (jlimit (0.0f, 1.0f, newGain), nullptr));
  1199. }
  1200. bool isMuted() const
  1201. {
  1202. BOOL mute = 0;
  1203. return endpointVolume != nullptr
  1204. && check (endpointVolume->GetMute (&mute)) && mute != 0;
  1205. }
  1206. bool setMuted (bool shouldMute) const
  1207. {
  1208. return endpointVolume != nullptr
  1209. && check (endpointVolume->SetMute (shouldMute, nullptr));
  1210. }
  1211. ComSmartPtr<IAudioEndpointVolume> endpointVolume;
  1212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MMDeviceMasterVolume)
  1213. };
  1214. }
  1215. //==============================================================================
  1216. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI()
  1217. {
  1218. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1219. return new WasapiClasses::WASAPIAudioIODeviceType();
  1220. return nullptr;
  1221. }
  1222. //==============================================================================
  1223. #define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
  1224. float JUCE_CALLTYPE SystemAudioVolume::getGain() { return WasapiClasses::MMDeviceMasterVolume().getGain(); }
  1225. bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return WasapiClasses::MMDeviceMasterVolume().setGain (gain); }
  1226. bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return WasapiClasses::MMDeviceMasterVolume().isMuted(); }
  1227. bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return WasapiClasses::MMDeviceMasterVolume().setMuted (mute); }