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.

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