Audio plugin host https://kx.studio/carla
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.

1730 lines
63KB

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