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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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() override
  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() override
  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. Array<double> getAvailableSampleRates() override { return sampleRates; }
  746. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  747. int getDefaultBufferSize() override { return defaultBufferSize; }
  748. int getCurrentBufferSizeSamples() override { return currentBufferSizeSamples; }
  749. double getCurrentSampleRate() override { return currentSampleRate; }
  750. int getCurrentBitDepth() override { return 32; }
  751. int getOutputLatencyInSamples() override { return latencyOut; }
  752. int getInputLatencyInSamples() override { return latencyIn; }
  753. BigInteger getActiveOutputChannels() const override { return outputDevice != nullptr ? outputDevice->channels : BigInteger(); }
  754. BigInteger getActiveInputChannels() const override { return inputDevice != nullptr ? inputDevice->channels : BigInteger(); }
  755. String getLastError() override { return lastError; }
  756. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  757. double sampleRate, int bufferSizeSamples) override
  758. {
  759. close();
  760. lastError.clear();
  761. if (sampleRates.size() == 0 && inputDevice != nullptr && outputDevice != nullptr)
  762. {
  763. lastError = TRANS("The input and output devices don't share a common sample rate!");
  764. return lastError;
  765. }
  766. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  767. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  768. lastKnownInputChannels = inputChannels;
  769. lastKnownOutputChannels = outputChannels;
  770. if (inputDevice != nullptr && ! inputDevice->open (currentSampleRate, inputChannels))
  771. {
  772. lastError = TRANS("Couldn't open the input device!");
  773. return lastError;
  774. }
  775. if (outputDevice != nullptr && ! outputDevice->open (currentSampleRate, outputChannels))
  776. {
  777. close();
  778. lastError = TRANS("Couldn't open the output device!");
  779. return lastError;
  780. }
  781. if (inputDevice != nullptr) ResetEvent (inputDevice->clientEvent);
  782. if (outputDevice != nullptr) ResetEvent (outputDevice->clientEvent);
  783. startThread (8);
  784. Thread::sleep (5);
  785. if (inputDevice != nullptr && inputDevice->client != nullptr)
  786. {
  787. latencyIn = (int) (inputDevice->latencySamples + currentBufferSizeSamples);
  788. if (! check (inputDevice->client->Start()))
  789. {
  790. close();
  791. lastError = TRANS("Couldn't start the input device!");
  792. return lastError;
  793. }
  794. }
  795. if (outputDevice != nullptr && outputDevice->client != nullptr)
  796. {
  797. latencyOut = (int) (outputDevice->latencySamples + currentBufferSizeSamples);
  798. if (! check (outputDevice->client->Start()))
  799. {
  800. close();
  801. lastError = TRANS("Couldn't start the output device!");
  802. return lastError;
  803. }
  804. }
  805. isOpen_ = true;
  806. return lastError;
  807. }
  808. void close() override
  809. {
  810. stop();
  811. signalThreadShouldExit();
  812. if (inputDevice != nullptr) SetEvent (inputDevice->clientEvent);
  813. if (outputDevice != nullptr) SetEvent (outputDevice->clientEvent);
  814. stopThread (5000);
  815. if (inputDevice != nullptr) inputDevice->close();
  816. if (outputDevice != nullptr) outputDevice->close();
  817. isOpen_ = false;
  818. }
  819. bool isOpen() override { return isOpen_ && isThreadRunning(); }
  820. bool isPlaying() override { return isStarted && isOpen_ && isThreadRunning(); }
  821. void start (AudioIODeviceCallback* call) override
  822. {
  823. if (isOpen_ && call != nullptr && ! isStarted)
  824. {
  825. if (! isThreadRunning())
  826. {
  827. // something's gone wrong and the thread's stopped..
  828. isOpen_ = false;
  829. return;
  830. }
  831. call->audioDeviceAboutToStart (this);
  832. const ScopedLock sl (startStopLock);
  833. callback = call;
  834. isStarted = true;
  835. }
  836. }
  837. void stop() override
  838. {
  839. if (isStarted)
  840. {
  841. AudioIODeviceCallback* const callbackLocal = callback;
  842. {
  843. const ScopedLock sl (startStopLock);
  844. isStarted = false;
  845. }
  846. if (callbackLocal != nullptr)
  847. callbackLocal->audioDeviceStopped();
  848. }
  849. }
  850. void setMMThreadPriority()
  851. {
  852. DynamicLibrary dll ("avrt.dll");
  853. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, (LPCWSTR, LPDWORD))
  854. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, (HANDLE, AVRT_PRIORITY))
  855. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  856. {
  857. DWORD dummy = 0;
  858. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  859. if (h != 0)
  860. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  861. }
  862. }
  863. void run() override
  864. {
  865. setMMThreadPriority();
  866. const int bufferSize = currentBufferSizeSamples;
  867. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  868. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  869. bool sampleRateChanged = false;
  870. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  871. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  872. float** const inputBuffers = ins.getArrayOfChannels();
  873. float** const outputBuffers = outs.getArrayOfChannels();
  874. ins.clear();
  875. while (! threadShouldExit())
  876. {
  877. if (inputDevice != nullptr)
  878. {
  879. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  880. if (threadShouldExit())
  881. break;
  882. if (inputDevice->sampleRateHasChanged)
  883. {
  884. sampleRateChanged = true;
  885. sampleRateChangedByOutput = false;
  886. }
  887. }
  888. {
  889. const ScopedLock sl (startStopLock);
  890. if (isStarted)
  891. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  892. outputBuffers, numOutputBuffers, bufferSize);
  893. else
  894. outs.clear();
  895. }
  896. if (outputDevice != nullptr)
  897. {
  898. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  899. if (outputDevice->sampleRateHasChanged)
  900. {
  901. sampleRateChanged = true;
  902. sampleRateChangedByOutput = true;
  903. }
  904. }
  905. if (sampleRateChanged)
  906. {
  907. triggerAsyncUpdate();
  908. break; // Quit the thread... will restart it later!
  909. }
  910. }
  911. }
  912. //==============================================================================
  913. String outputDeviceId, inputDeviceId;
  914. String lastError;
  915. private:
  916. // Device stats...
  917. ScopedPointer<WASAPIInputDevice> inputDevice;
  918. ScopedPointer<WASAPIOutputDevice> outputDevice;
  919. const bool useExclusiveMode;
  920. double defaultSampleRate;
  921. int minBufferSize, defaultBufferSize;
  922. int latencyIn, latencyOut;
  923. Array <double> sampleRates;
  924. Array <int> bufferSizes;
  925. // Active state...
  926. bool isOpen_, isStarted;
  927. int currentBufferSizeSamples;
  928. double currentSampleRate;
  929. bool sampleRateChangedByOutput;
  930. AudioIODeviceCallback* callback;
  931. CriticalSection startStopLock;
  932. BigInteger lastKnownInputChannels, lastKnownOutputChannels;
  933. //==============================================================================
  934. bool createDevices()
  935. {
  936. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  937. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  938. return false;
  939. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  940. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  941. return false;
  942. UINT32 numDevices = 0;
  943. if (! check (deviceCollection->GetCount (&numDevices)))
  944. return false;
  945. for (UINT32 i = 0; i < numDevices; ++i)
  946. {
  947. ComSmartPtr <IMMDevice> device;
  948. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  949. continue;
  950. const String deviceId (getDeviceID (device));
  951. if (deviceId.isEmpty())
  952. continue;
  953. const EDataFlow flow = getDataFlow (device);
  954. if (deviceId == inputDeviceId && flow == eCapture)
  955. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  956. else if (deviceId == outputDeviceId && flow == eRender)
  957. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  958. }
  959. return (outputDeviceId.isEmpty() || (outputDevice != nullptr && outputDevice->isOk()))
  960. && (inputDeviceId.isEmpty() || (inputDevice != nullptr && inputDevice->isOk()));
  961. }
  962. //==============================================================================
  963. void handleAsyncUpdate() override
  964. {
  965. stop();
  966. outputDevice = nullptr;
  967. inputDevice = nullptr;
  968. initialise();
  969. open (lastKnownInputChannels, lastKnownOutputChannels,
  970. getChangedSampleRate(), currentBufferSizeSamples);
  971. start (callback);
  972. }
  973. double getChangedSampleRate() const
  974. {
  975. if (outputDevice != nullptr && sampleRateChangedByOutput)
  976. return outputDevice->defaultSampleRate;
  977. if (inputDevice != nullptr && ! sampleRateChangedByOutput)
  978. return inputDevice->defaultSampleRate;
  979. return 0.0;
  980. }
  981. //==============================================================================
  982. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice)
  983. };
  984. //==============================================================================
  985. class WASAPIAudioIODeviceType : public AudioIODeviceType,
  986. private DeviceChangeDetector
  987. {
  988. public:
  989. WASAPIAudioIODeviceType()
  990. : AudioIODeviceType ("Windows Audio"),
  991. DeviceChangeDetector (L"Windows Audio"),
  992. hasScanned (false)
  993. {
  994. }
  995. ~WASAPIAudioIODeviceType()
  996. {
  997. if (notifyClient != nullptr)
  998. enumerator->UnregisterEndpointNotificationCallback (notifyClient);
  999. }
  1000. //==============================================================================
  1001. void scanForDevices()
  1002. {
  1003. hasScanned = true;
  1004. outputDeviceNames.clear();
  1005. inputDeviceNames.clear();
  1006. outputDeviceIds.clear();
  1007. inputDeviceIds.clear();
  1008. scan (outputDeviceNames, inputDeviceNames,
  1009. outputDeviceIds, inputDeviceIds);
  1010. }
  1011. StringArray getDeviceNames (bool wantInputNames) const
  1012. {
  1013. jassert (hasScanned); // need to call scanForDevices() before doing this
  1014. return wantInputNames ? inputDeviceNames
  1015. : outputDeviceNames;
  1016. }
  1017. int getDefaultDeviceIndex (bool /*forInput*/) const
  1018. {
  1019. jassert (hasScanned); // need to call scanForDevices() before doing this
  1020. return 0;
  1021. }
  1022. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  1023. {
  1024. jassert (hasScanned); // need to call scanForDevices() before doing this
  1025. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  1026. return d == nullptr ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  1027. : outputDeviceIds.indexOf (d->outputDeviceId));
  1028. }
  1029. bool hasSeparateInputsAndOutputs() const { return true; }
  1030. AudioIODevice* createDevice (const String& outputDeviceName,
  1031. const String& inputDeviceName)
  1032. {
  1033. jassert (hasScanned); // need to call scanForDevices() before doing this
  1034. const bool useExclusiveMode = false;
  1035. ScopedPointer<WASAPIAudioIODevice> device;
  1036. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  1037. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  1038. if (outputIndex >= 0 || inputIndex >= 0)
  1039. {
  1040. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1041. : inputDeviceName,
  1042. outputDeviceIds [outputIndex],
  1043. inputDeviceIds [inputIndex],
  1044. useExclusiveMode);
  1045. if (! device->initialise())
  1046. device = nullptr;
  1047. }
  1048. return device.release();
  1049. }
  1050. //==============================================================================
  1051. StringArray outputDeviceNames, outputDeviceIds;
  1052. StringArray inputDeviceNames, inputDeviceIds;
  1053. private:
  1054. bool hasScanned;
  1055. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1056. //==============================================================================
  1057. class ChangeNotificationClient : public ComBaseClassHelper<IMMNotificationClient>
  1058. {
  1059. public:
  1060. ChangeNotificationClient (WASAPIAudioIODeviceType& d)
  1061. : ComBaseClassHelper <IMMNotificationClient> (0), device (d) {}
  1062. HRESULT STDMETHODCALLTYPE OnDeviceAdded (LPCWSTR) { return notify(); }
  1063. HRESULT STDMETHODCALLTYPE OnDeviceRemoved (LPCWSTR) { return notify(); }
  1064. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged (LPCWSTR, DWORD) { return notify(); }
  1065. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) { return notify(); }
  1066. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) { return notify(); }
  1067. private:
  1068. WASAPIAudioIODeviceType& device;
  1069. HRESULT notify() { device.triggerAsyncDeviceChangeCallback(); return S_OK; }
  1070. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeNotificationClient)
  1071. };
  1072. ComSmartPtr<ChangeNotificationClient> notifyClient;
  1073. //==============================================================================
  1074. static String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  1075. {
  1076. String s;
  1077. IMMDevice* dev = nullptr;
  1078. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  1079. eMultimedia, &dev)))
  1080. {
  1081. WCHAR* deviceId = nullptr;
  1082. if (check (dev->GetId (&deviceId)))
  1083. {
  1084. s = deviceId;
  1085. CoTaskMemFree (deviceId);
  1086. }
  1087. dev->Release();
  1088. }
  1089. return s;
  1090. }
  1091. //==============================================================================
  1092. void scan (StringArray& outputDeviceNames,
  1093. StringArray& inputDeviceNames,
  1094. StringArray& outputDeviceIds,
  1095. StringArray& inputDeviceIds)
  1096. {
  1097. if (enumerator == nullptr)
  1098. {
  1099. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1100. return;
  1101. notifyClient = new ChangeNotificationClient (*this);
  1102. enumerator->RegisterEndpointNotificationCallback (notifyClient);
  1103. }
  1104. const String defaultRenderer (getDefaultEndpoint (enumerator, false));
  1105. const String defaultCapture (getDefaultEndpoint (enumerator, true));
  1106. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  1107. UINT32 numDevices = 0;
  1108. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  1109. && check (deviceCollection->GetCount (&numDevices))))
  1110. return;
  1111. for (UINT32 i = 0; i < numDevices; ++i)
  1112. {
  1113. ComSmartPtr <IMMDevice> device;
  1114. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1115. continue;
  1116. DWORD state = 0;
  1117. if (! (check (device->GetState (&state)) && state == DEVICE_STATE_ACTIVE))
  1118. continue;
  1119. const String deviceId (getDeviceID (device));
  1120. String name;
  1121. {
  1122. ComSmartPtr <IPropertyStore> properties;
  1123. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  1124. continue;
  1125. PROPVARIANT value;
  1126. zerostruct (value);
  1127. const PROPERTYKEY PKEY_Device_FriendlyName
  1128. = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 };
  1129. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  1130. name = value.pwszVal;
  1131. PropVariantClear (&value);
  1132. }
  1133. const EDataFlow flow = getDataFlow (device);
  1134. if (flow == eRender)
  1135. {
  1136. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  1137. outputDeviceIds.insert (index, deviceId);
  1138. outputDeviceNames.insert (index, name);
  1139. }
  1140. else if (flow == eCapture)
  1141. {
  1142. const int index = (deviceId == defaultCapture) ? 0 : -1;
  1143. inputDeviceIds.insert (index, deviceId);
  1144. inputDeviceNames.insert (index, name);
  1145. }
  1146. }
  1147. inputDeviceNames.appendNumbersToDuplicates (false, false);
  1148. outputDeviceNames.appendNumbersToDuplicates (false, false);
  1149. }
  1150. //==============================================================================
  1151. void systemDeviceChanged()
  1152. {
  1153. StringArray newOutNames, newInNames, newOutIds, newInIds;
  1154. scan (newOutNames, newInNames, newOutIds, newInIds);
  1155. if (newOutNames != outputDeviceNames
  1156. || newInNames != inputDeviceNames
  1157. || newOutIds != outputDeviceIds
  1158. || newInIds != inputDeviceIds)
  1159. {
  1160. hasScanned = true;
  1161. outputDeviceNames = newOutNames;
  1162. inputDeviceNames = newInNames;
  1163. outputDeviceIds = newOutIds;
  1164. inputDeviceIds = newInIds;
  1165. }
  1166. callDeviceChangeListeners();
  1167. }
  1168. //==============================================================================
  1169. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType)
  1170. };
  1171. //==============================================================================
  1172. struct MMDeviceMasterVolume
  1173. {
  1174. MMDeviceMasterVolume()
  1175. {
  1176. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1177. if (check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1178. {
  1179. ComSmartPtr<IMMDevice> device;
  1180. if (check (enumerator->GetDefaultAudioEndpoint (eRender, eConsole, device.resetAndGetPointerAddress())))
  1181. check (device->Activate (__uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr,
  1182. (void**) endpointVolume.resetAndGetPointerAddress()));
  1183. }
  1184. }
  1185. float getGain() const
  1186. {
  1187. float vol = 0.0f;
  1188. if (endpointVolume != nullptr)
  1189. check (endpointVolume->GetMasterVolumeLevelScalar (&vol));
  1190. return vol;
  1191. }
  1192. bool setGain (float newGain) const
  1193. {
  1194. return endpointVolume != nullptr
  1195. && check (endpointVolume->SetMasterVolumeLevelScalar (jlimit (0.0f, 1.0f, newGain), nullptr));
  1196. }
  1197. bool isMuted() const
  1198. {
  1199. BOOL mute = 0;
  1200. return endpointVolume != nullptr
  1201. && check (endpointVolume->GetMute (&mute)) && mute != 0;
  1202. }
  1203. bool setMuted (bool shouldMute) const
  1204. {
  1205. return endpointVolume != nullptr
  1206. && check (endpointVolume->SetMute (shouldMute, nullptr));
  1207. }
  1208. ComSmartPtr<IAudioEndpointVolume> endpointVolume;
  1209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MMDeviceMasterVolume)
  1210. };
  1211. }
  1212. //==============================================================================
  1213. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI()
  1214. {
  1215. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1216. return new WasapiClasses::WASAPIAudioIODeviceType();
  1217. return nullptr;
  1218. }
  1219. //==============================================================================
  1220. #define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
  1221. float JUCE_CALLTYPE SystemAudioVolume::getGain() { return WasapiClasses::MMDeviceMasterVolume().getGain(); }
  1222. bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return WasapiClasses::MMDeviceMasterVolume().setGain (gain); }
  1223. bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return WasapiClasses::MMDeviceMasterVolume().isMuted(); }
  1224. bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return WasapiClasses::MMDeviceMasterVolume().setMuted (mute); }