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.

1706 lines
62KB

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