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.

1723 lines
62KB

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