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.

juce_win32_WASAPI.cpp 55KB

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