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.

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