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.

1694 lines
62KB

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