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.

1690 lines
61KB

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