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 54KB

10 years ago
10 years ago
10 years ago
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 != (HRESULT) 0x800401f0); // If you hit this, it means you're trying to call from
  27. // a thread which hasn't been initialised with CoInitialize().
  28. #if JUCE_WASAPI_LOGGING
  29. if (FAILED (hr))
  30. {
  31. const char* m = nullptr;
  32. switch (hr)
  33. {
  34. case E_POINTER: m = "E_POINTER"; break;
  35. case E_INVALIDARG: m = "E_INVALIDARG"; break;
  36. #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. ComSmartPtr<IAudioClient> createClient()
  436. {
  437. ComSmartPtr<IAudioClient> client;
  438. if (device != nullptr)
  439. logFailure (device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER,
  440. nullptr, (void**) client.resetAndGetPointerAddress()));
  441. return client;
  442. }
  443. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  444. {
  445. WAVEFORMATEXTENSIBLE format;
  446. zerostruct (format);
  447. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  448. {
  449. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  450. }
  451. else
  452. {
  453. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  454. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  455. }
  456. format.Format.nSamplesPerSec = (DWORD) sampleRate;
  457. format.Format.nChannels = (WORD) numChannels;
  458. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  459. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  460. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  461. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  462. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  463. format.dwChannelMask = mixFormatChannelMask;
  464. WAVEFORMATEXTENSIBLE* nearestFormat = nullptr;
  465. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE
  466. : AUDCLNT_SHAREMODE_SHARED,
  467. (WAVEFORMATEX*) &format,
  468. useExclusiveMode ? nullptr : (WAVEFORMATEX**) &nearestFormat);
  469. logFailure (hr);
  470. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  471. {
  472. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  473. hr = S_OK;
  474. }
  475. CoTaskMemFree (nearestFormat);
  476. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  477. if (useExclusiveMode)
  478. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  479. GUID session;
  480. if (hr == S_OK
  481. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  482. 0x40000 /*AUDCLNT_STREAMFLAGS_EVENTCALLBACK*/,
  483. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  484. {
  485. actualNumChannels = format.Format.nChannels;
  486. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  487. bytesPerSample = format.Format.wBitsPerSample / 8;
  488. updateFormat (isFloat);
  489. return true;
  490. }
  491. return false;
  492. }
  493. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase)
  494. };
  495. //==============================================================================
  496. class WASAPIInputDevice : public WASAPIDeviceBase
  497. {
  498. public:
  499. WASAPIInputDevice (const ComSmartPtr<IMMDevice>& d, const bool exclusiveMode)
  500. : WASAPIDeviceBase (d, exclusiveMode),
  501. reservoir (1, 1)
  502. {
  503. }
  504. ~WASAPIInputDevice()
  505. {
  506. close();
  507. }
  508. bool open (const double newSampleRate, const BigInteger& newChannels)
  509. {
  510. reservoirSize = 0;
  511. reservoirCapacity = 16384;
  512. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  513. return openClient (newSampleRate, newChannels)
  514. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  515. (void**) captureClient.resetAndGetPointerAddress())));
  516. }
  517. void close()
  518. {
  519. closeClient();
  520. captureClient = nullptr;
  521. reservoir.reset();
  522. }
  523. template<class SourceType>
  524. void updateFormatWithType (SourceType*)
  525. {
  526. typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  527. converter = new AudioData::ConverterInstance<AudioData::Pointer<SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  528. }
  529. void updateFormat (bool isFloat)
  530. {
  531. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  532. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  533. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  534. else updateFormatWithType ((AudioData::Int16*) 0);
  535. }
  536. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  537. {
  538. if (numChannels <= 0)
  539. return;
  540. int offset = 0;
  541. while (bufferSize > 0)
  542. {
  543. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  544. {
  545. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  546. for (int i = 0; i < numDestBuffers; ++i)
  547. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  548. bufferSize -= samplesToDo;
  549. offset += samplesToDo;
  550. reservoirSize = 0;
  551. }
  552. else
  553. {
  554. UINT32 packetLength = 0;
  555. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  556. break;
  557. if (packetLength == 0)
  558. {
  559. if (thread.threadShouldExit()
  560. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  561. break;
  562. continue;
  563. }
  564. uint8* inputData;
  565. UINT32 numSamplesAvailable;
  566. DWORD flags;
  567. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  568. {
  569. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  570. for (int i = 0; i < numDestBuffers; ++i)
  571. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  572. bufferSize -= samplesToDo;
  573. offset += samplesToDo;
  574. if (samplesToDo < (int) numSamplesAvailable)
  575. {
  576. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  577. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  578. (size_t) (bytesPerSample * actualNumChannels * reservoirSize));
  579. }
  580. captureClient->ReleaseBuffer (numSamplesAvailable);
  581. }
  582. }
  583. }
  584. }
  585. ComSmartPtr<IAudioCaptureClient> captureClient;
  586. MemoryBlock reservoir;
  587. int reservoirSize, reservoirCapacity;
  588. ScopedPointer<AudioData::Converter> converter;
  589. private:
  590. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice)
  591. };
  592. //==============================================================================
  593. class WASAPIOutputDevice : public WASAPIDeviceBase
  594. {
  595. public:
  596. WASAPIOutputDevice (const ComSmartPtr<IMMDevice>& d, const bool exclusiveMode)
  597. : WASAPIDeviceBase (d, exclusiveMode)
  598. {
  599. }
  600. ~WASAPIOutputDevice()
  601. {
  602. close();
  603. }
  604. bool open (const double newSampleRate, const BigInteger& newChannels)
  605. {
  606. return openClient (newSampleRate, newChannels)
  607. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  608. }
  609. void close()
  610. {
  611. closeClient();
  612. renderClient = nullptr;
  613. }
  614. template<class DestType>
  615. void updateFormatWithType (DestType*)
  616. {
  617. typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  618. converter = new AudioData::ConverterInstance<NativeType, AudioData::Pointer<DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  619. }
  620. void updateFormat (bool isFloat)
  621. {
  622. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  623. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  624. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  625. else updateFormatWithType ((AudioData::Int16*) 0);
  626. }
  627. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  628. {
  629. if (numChannels <= 0)
  630. return;
  631. int offset = 0;
  632. while (bufferSize > 0)
  633. {
  634. UINT32 padding = 0;
  635. if (! check (client->GetCurrentPadding (&padding)))
  636. return;
  637. int samplesToDo = useExclusiveMode ? bufferSize
  638. : jmin ((int) (actualBufferSize - padding), bufferSize);
  639. if (samplesToDo <= 0)
  640. {
  641. if (thread.threadShouldExit()
  642. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  643. break;
  644. continue;
  645. }
  646. uint8* outputData = nullptr;
  647. if (check (renderClient->GetBuffer ((UINT32) samplesToDo, &outputData)))
  648. {
  649. for (int i = 0; i < numSrcBuffers; ++i)
  650. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  651. renderClient->ReleaseBuffer ((UINT32) samplesToDo, 0);
  652. offset += samplesToDo;
  653. bufferSize -= samplesToDo;
  654. }
  655. }
  656. }
  657. ComSmartPtr<IAudioRenderClient> renderClient;
  658. ScopedPointer<AudioData::Converter> converter;
  659. private:
  660. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice)
  661. };
  662. //==============================================================================
  663. class WASAPIAudioIODevice : public AudioIODevice,
  664. public Thread,
  665. private AsyncUpdater
  666. {
  667. public:
  668. WASAPIAudioIODevice (const String& deviceName,
  669. const String& outputDeviceId_,
  670. const String& inputDeviceId_,
  671. const bool exclusiveMode)
  672. : AudioIODevice (deviceName, "Windows Audio"),
  673. Thread ("Juce WASAPI"),
  674. outputDeviceId (outputDeviceId_),
  675. inputDeviceId (inputDeviceId_),
  676. useExclusiveMode (exclusiveMode),
  677. isOpen_ (false),
  678. isStarted (false),
  679. currentBufferSizeSamples (0),
  680. currentSampleRate (0),
  681. callback (nullptr)
  682. {
  683. }
  684. ~WASAPIAudioIODevice()
  685. {
  686. close();
  687. }
  688. bool initialise()
  689. {
  690. latencyIn = latencyOut = 0;
  691. Array<double> ratesIn, ratesOut;
  692. if (createDevices())
  693. {
  694. jassert (inputDevice != nullptr || outputDevice != nullptr);
  695. if (inputDevice != nullptr && outputDevice != nullptr)
  696. {
  697. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  698. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  699. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  700. sampleRates = inputDevice->rates;
  701. sampleRates.removeValuesNotIn (outputDevice->rates);
  702. }
  703. else
  704. {
  705. WASAPIDeviceBase* d = inputDevice != nullptr ? static_cast<WASAPIDeviceBase*> (inputDevice)
  706. : static_cast<WASAPIDeviceBase*> (outputDevice);
  707. defaultSampleRate = d->defaultSampleRate;
  708. minBufferSize = d->minBufferSize;
  709. defaultBufferSize = d->defaultBufferSize;
  710. sampleRates = d->rates;
  711. }
  712. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  713. if (minBufferSize != defaultBufferSize)
  714. bufferSizes.addUsingDefaultSort (minBufferSize);
  715. int n = 64;
  716. for (int i = 0; i < 40; ++i)
  717. {
  718. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  719. bufferSizes.addUsingDefaultSort (n);
  720. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  721. }
  722. return true;
  723. }
  724. return false;
  725. }
  726. StringArray getOutputChannelNames() override
  727. {
  728. StringArray outChannels;
  729. if (outputDevice != nullptr)
  730. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  731. outChannels.add ("Output channel " + String (i));
  732. return outChannels;
  733. }
  734. StringArray getInputChannelNames() override
  735. {
  736. StringArray inChannels;
  737. if (inputDevice != nullptr)
  738. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  739. inChannels.add ("Input channel " + String (i));
  740. return inChannels;
  741. }
  742. Array<double> getAvailableSampleRates() override { return sampleRates; }
  743. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  744. int getDefaultBufferSize() override { return defaultBufferSize; }
  745. int getCurrentBufferSizeSamples() override { return currentBufferSizeSamples; }
  746. double getCurrentSampleRate() override { return currentSampleRate; }
  747. int getCurrentBitDepth() override { return 32; }
  748. int getOutputLatencyInSamples() override { return latencyOut; }
  749. int getInputLatencyInSamples() override { return latencyIn; }
  750. BigInteger getActiveOutputChannels() const override { return outputDevice != nullptr ? outputDevice->channels : BigInteger(); }
  751. BigInteger getActiveInputChannels() const override { return inputDevice != nullptr ? inputDevice->channels : BigInteger(); }
  752. String getLastError() override { return lastError; }
  753. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  754. double sampleRate, int bufferSizeSamples) override
  755. {
  756. close();
  757. lastError.clear();
  758. if (sampleRates.size() == 0 && inputDevice != nullptr && outputDevice != nullptr)
  759. {
  760. lastError = TRANS("The input and output devices don't share a common sample rate!");
  761. return lastError;
  762. }
  763. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  764. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  765. lastKnownInputChannels = inputChannels;
  766. lastKnownOutputChannels = outputChannels;
  767. if (inputDevice != nullptr && ! inputDevice->open (currentSampleRate, inputChannels))
  768. {
  769. lastError = TRANS("Couldn't open the input device!");
  770. return lastError;
  771. }
  772. if (outputDevice != nullptr && ! outputDevice->open (currentSampleRate, outputChannels))
  773. {
  774. close();
  775. lastError = TRANS("Couldn't open the output device!");
  776. return lastError;
  777. }
  778. if (inputDevice != nullptr) ResetEvent (inputDevice->clientEvent);
  779. if (outputDevice != nullptr) ResetEvent (outputDevice->clientEvent);
  780. startThread (8);
  781. Thread::sleep (5);
  782. if (inputDevice != nullptr && inputDevice->client != nullptr)
  783. {
  784. latencyIn = (int) (inputDevice->latencySamples + currentBufferSizeSamples);
  785. if (! check (inputDevice->client->Start()))
  786. {
  787. close();
  788. lastError = TRANS("Couldn't start the input device!");
  789. return lastError;
  790. }
  791. }
  792. if (outputDevice != nullptr && outputDevice->client != nullptr)
  793. {
  794. latencyOut = (int) (outputDevice->latencySamples + currentBufferSizeSamples);
  795. if (! check (outputDevice->client->Start()))
  796. {
  797. close();
  798. lastError = TRANS("Couldn't start the output device!");
  799. return lastError;
  800. }
  801. }
  802. isOpen_ = true;
  803. return lastError;
  804. }
  805. void close() override
  806. {
  807. stop();
  808. signalThreadShouldExit();
  809. if (inputDevice != nullptr) SetEvent (inputDevice->clientEvent);
  810. if (outputDevice != nullptr) SetEvent (outputDevice->clientEvent);
  811. stopThread (5000);
  812. if (inputDevice != nullptr) inputDevice->close();
  813. if (outputDevice != nullptr) outputDevice->close();
  814. isOpen_ = false;
  815. }
  816. bool isOpen() override { return isOpen_ && isThreadRunning(); }
  817. bool isPlaying() override { return isStarted && isOpen_ && isThreadRunning(); }
  818. void start (AudioIODeviceCallback* call) override
  819. {
  820. if (isOpen_ && call != nullptr && ! isStarted)
  821. {
  822. if (! isThreadRunning())
  823. {
  824. // something's gone wrong and the thread's stopped..
  825. isOpen_ = false;
  826. return;
  827. }
  828. call->audioDeviceAboutToStart (this);
  829. const ScopedLock sl (startStopLock);
  830. callback = call;
  831. isStarted = true;
  832. }
  833. }
  834. void stop() override
  835. {
  836. if (isStarted)
  837. {
  838. AudioIODeviceCallback* const callbackLocal = callback;
  839. {
  840. const ScopedLock sl (startStopLock);
  841. isStarted = false;
  842. }
  843. if (callbackLocal != nullptr)
  844. callbackLocal->audioDeviceStopped();
  845. }
  846. }
  847. void setMMThreadPriority()
  848. {
  849. DynamicLibrary dll ("avrt.dll");
  850. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, (LPCWSTR, LPDWORD))
  851. JUCE_LOAD_WINAPI_FUNCTION (dll, AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, (HANDLE, AVRT_PRIORITY))
  852. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  853. {
  854. DWORD dummy = 0;
  855. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  856. if (h != 0)
  857. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  858. }
  859. }
  860. void run() override
  861. {
  862. setMMThreadPriority();
  863. const int bufferSize = currentBufferSizeSamples;
  864. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  865. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  866. bool sampleRateChanged = false;
  867. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  868. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  869. float** const inputBuffers = ins.getArrayOfWritePointers();
  870. float** const outputBuffers = outs.getArrayOfWritePointers();
  871. ins.clear();
  872. while (! threadShouldExit())
  873. {
  874. if (inputDevice != nullptr)
  875. {
  876. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  877. if (threadShouldExit())
  878. break;
  879. if (inputDevice->sampleRateHasChanged)
  880. {
  881. sampleRateChanged = true;
  882. sampleRateChangedByOutput = false;
  883. }
  884. }
  885. {
  886. const ScopedLock sl (startStopLock);
  887. if (isStarted)
  888. callback->audioDeviceIOCallback (const_cast<const float**> (inputBuffers), numInputBuffers,
  889. outputBuffers, numOutputBuffers, bufferSize);
  890. else
  891. outs.clear();
  892. }
  893. if (outputDevice != nullptr)
  894. {
  895. outputDevice->copyBuffers (const_cast<const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  896. if (outputDevice->sampleRateHasChanged)
  897. {
  898. sampleRateChanged = true;
  899. sampleRateChangedByOutput = true;
  900. }
  901. }
  902. if (sampleRateChanged)
  903. {
  904. triggerAsyncUpdate();
  905. break; // Quit the thread... will restart it later!
  906. }
  907. }
  908. }
  909. //==============================================================================
  910. String outputDeviceId, inputDeviceId;
  911. String lastError;
  912. private:
  913. // Device stats...
  914. ScopedPointer<WASAPIInputDevice> inputDevice;
  915. ScopedPointer<WASAPIOutputDevice> outputDevice;
  916. const bool useExclusiveMode;
  917. double defaultSampleRate;
  918. int minBufferSize, defaultBufferSize;
  919. int latencyIn, latencyOut;
  920. Array<double> sampleRates;
  921. Array<int> bufferSizes;
  922. // Active state...
  923. bool isOpen_, isStarted;
  924. int currentBufferSizeSamples;
  925. double currentSampleRate;
  926. bool sampleRateChangedByOutput;
  927. AudioIODeviceCallback* callback;
  928. CriticalSection startStopLock;
  929. BigInteger lastKnownInputChannels, lastKnownOutputChannels;
  930. //==============================================================================
  931. bool createDevices()
  932. {
  933. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  934. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  935. return false;
  936. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  937. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  938. return false;
  939. UINT32 numDevices = 0;
  940. if (! check (deviceCollection->GetCount (&numDevices)))
  941. return false;
  942. for (UINT32 i = 0; i < numDevices; ++i)
  943. {
  944. ComSmartPtr<IMMDevice> device;
  945. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  946. continue;
  947. const String deviceId (getDeviceID (device));
  948. if (deviceId.isEmpty())
  949. continue;
  950. const EDataFlow flow = getDataFlow (device);
  951. if (deviceId == inputDeviceId && flow == eCapture)
  952. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  953. else if (deviceId == outputDeviceId && flow == eRender)
  954. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  955. }
  956. return (outputDeviceId.isEmpty() || (outputDevice != nullptr && outputDevice->isOk()))
  957. && (inputDeviceId.isEmpty() || (inputDevice != nullptr && inputDevice->isOk()));
  958. }
  959. //==============================================================================
  960. void handleAsyncUpdate() override
  961. {
  962. stop();
  963. outputDevice = nullptr;
  964. inputDevice = nullptr;
  965. initialise();
  966. open (lastKnownInputChannels, lastKnownOutputChannels,
  967. getChangedSampleRate(), currentBufferSizeSamples);
  968. start (callback);
  969. }
  970. double getChangedSampleRate() const
  971. {
  972. if (outputDevice != nullptr && sampleRateChangedByOutput)
  973. return outputDevice->defaultSampleRate;
  974. if (inputDevice != nullptr && ! sampleRateChangedByOutput)
  975. return inputDevice->defaultSampleRate;
  976. return 0.0;
  977. }
  978. //==============================================================================
  979. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice)
  980. };
  981. //==============================================================================
  982. class WASAPIAudioIODeviceType : public AudioIODeviceType,
  983. private DeviceChangeDetector
  984. {
  985. public:
  986. WASAPIAudioIODeviceType()
  987. : AudioIODeviceType ("Windows Audio"),
  988. DeviceChangeDetector (L"Windows Audio"),
  989. hasScanned (false)
  990. {
  991. }
  992. ~WASAPIAudioIODeviceType()
  993. {
  994. if (notifyClient != nullptr)
  995. enumerator->UnregisterEndpointNotificationCallback (notifyClient);
  996. }
  997. //==============================================================================
  998. void scanForDevices()
  999. {
  1000. hasScanned = true;
  1001. outputDeviceNames.clear();
  1002. inputDeviceNames.clear();
  1003. outputDeviceIds.clear();
  1004. inputDeviceIds.clear();
  1005. scan (outputDeviceNames, inputDeviceNames,
  1006. outputDeviceIds, inputDeviceIds);
  1007. }
  1008. StringArray getDeviceNames (bool wantInputNames) const
  1009. {
  1010. jassert (hasScanned); // need to call scanForDevices() before doing this
  1011. return wantInputNames ? inputDeviceNames
  1012. : outputDeviceNames;
  1013. }
  1014. int getDefaultDeviceIndex (bool /*forInput*/) const
  1015. {
  1016. jassert (hasScanned); // need to call scanForDevices() before doing this
  1017. return 0;
  1018. }
  1019. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  1020. {
  1021. jassert (hasScanned); // need to call scanForDevices() before doing this
  1022. if (WASAPIAudioIODevice* const d = dynamic_cast<WASAPIAudioIODevice*> (device))
  1023. return asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  1024. : outputDeviceIds.indexOf (d->outputDeviceId);
  1025. return -1;
  1026. }
  1027. bool hasSeparateInputsAndOutputs() const { return true; }
  1028. AudioIODevice* createDevice (const String& outputDeviceName,
  1029. const String& inputDeviceName)
  1030. {
  1031. jassert (hasScanned); // need to call scanForDevices() before doing this
  1032. const bool useExclusiveMode = false;
  1033. ScopedPointer<WASAPIAudioIODevice> device;
  1034. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  1035. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  1036. if (outputIndex >= 0 || inputIndex >= 0)
  1037. {
  1038. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  1039. : inputDeviceName,
  1040. outputDeviceIds [outputIndex],
  1041. inputDeviceIds [inputIndex],
  1042. useExclusiveMode);
  1043. if (! device->initialise())
  1044. device = nullptr;
  1045. }
  1046. return device.release();
  1047. }
  1048. //==============================================================================
  1049. StringArray outputDeviceNames, outputDeviceIds;
  1050. StringArray inputDeviceNames, inputDeviceIds;
  1051. private:
  1052. bool hasScanned;
  1053. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1054. //==============================================================================
  1055. class ChangeNotificationClient : public ComBaseClassHelper<IMMNotificationClient>
  1056. {
  1057. public:
  1058. ChangeNotificationClient (WASAPIAudioIODeviceType& d)
  1059. : ComBaseClassHelper<IMMNotificationClient> (0), device (d) {}
  1060. HRESULT STDMETHODCALLTYPE OnDeviceAdded (LPCWSTR) { return notify(); }
  1061. HRESULT STDMETHODCALLTYPE OnDeviceRemoved (LPCWSTR) { return notify(); }
  1062. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged (LPCWSTR, DWORD) { return notify(); }
  1063. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged (EDataFlow, ERole, LPCWSTR) { return notify(); }
  1064. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged (LPCWSTR, const PROPERTYKEY) { return notify(); }
  1065. private:
  1066. WASAPIAudioIODeviceType& device;
  1067. HRESULT notify() { device.triggerAsyncDeviceChangeCallback(); return S_OK; }
  1068. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeNotificationClient)
  1069. };
  1070. ComSmartPtr<ChangeNotificationClient> notifyClient;
  1071. //==============================================================================
  1072. static String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  1073. {
  1074. String s;
  1075. IMMDevice* dev = nullptr;
  1076. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  1077. eMultimedia, &dev)))
  1078. {
  1079. WCHAR* deviceId = nullptr;
  1080. if (check (dev->GetId (&deviceId)))
  1081. {
  1082. s = deviceId;
  1083. CoTaskMemFree (deviceId);
  1084. }
  1085. dev->Release();
  1086. }
  1087. return s;
  1088. }
  1089. //==============================================================================
  1090. void scan (StringArray& outputDeviceNames,
  1091. StringArray& inputDeviceNames,
  1092. StringArray& outputDeviceIds,
  1093. StringArray& inputDeviceIds)
  1094. {
  1095. if (enumerator == nullptr)
  1096. {
  1097. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1098. return;
  1099. notifyClient = new ChangeNotificationClient (*this);
  1100. enumerator->RegisterEndpointNotificationCallback (notifyClient);
  1101. }
  1102. const String defaultRenderer (getDefaultEndpoint (enumerator, false));
  1103. const String defaultCapture (getDefaultEndpoint (enumerator, true));
  1104. ComSmartPtr<IMMDeviceCollection> deviceCollection;
  1105. UINT32 numDevices = 0;
  1106. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  1107. && check (deviceCollection->GetCount (&numDevices))))
  1108. return;
  1109. for (UINT32 i = 0; i < numDevices; ++i)
  1110. {
  1111. ComSmartPtr<IMMDevice> device;
  1112. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  1113. continue;
  1114. DWORD state = 0;
  1115. if (! (check (device->GetState (&state)) && state == DEVICE_STATE_ACTIVE))
  1116. continue;
  1117. const String deviceId (getDeviceID (device));
  1118. String name;
  1119. {
  1120. ComSmartPtr<IPropertyStore> properties;
  1121. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  1122. continue;
  1123. PROPVARIANT value;
  1124. zerostruct (value);
  1125. const PROPERTYKEY PKEY_Device_FriendlyName
  1126. = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 };
  1127. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  1128. name = value.pwszVal;
  1129. PropVariantClear (&value);
  1130. }
  1131. const EDataFlow flow = getDataFlow (device);
  1132. if (flow == eRender)
  1133. {
  1134. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  1135. outputDeviceIds.insert (index, deviceId);
  1136. outputDeviceNames.insert (index, name);
  1137. }
  1138. else if (flow == eCapture)
  1139. {
  1140. const int index = (deviceId == defaultCapture) ? 0 : -1;
  1141. inputDeviceIds.insert (index, deviceId);
  1142. inputDeviceNames.insert (index, name);
  1143. }
  1144. }
  1145. inputDeviceNames.appendNumbersToDuplicates (false, false);
  1146. outputDeviceNames.appendNumbersToDuplicates (false, false);
  1147. }
  1148. //==============================================================================
  1149. void systemDeviceChanged()
  1150. {
  1151. StringArray newOutNames, newInNames, newOutIds, newInIds;
  1152. scan (newOutNames, newInNames, newOutIds, newInIds);
  1153. if (newOutNames != outputDeviceNames
  1154. || newInNames != inputDeviceNames
  1155. || newOutIds != outputDeviceIds
  1156. || newInIds != inputDeviceIds)
  1157. {
  1158. hasScanned = true;
  1159. outputDeviceNames = newOutNames;
  1160. inputDeviceNames = newInNames;
  1161. outputDeviceIds = newOutIds;
  1162. inputDeviceIds = newInIds;
  1163. }
  1164. callDeviceChangeListeners();
  1165. }
  1166. //==============================================================================
  1167. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType)
  1168. };
  1169. //==============================================================================
  1170. struct MMDeviceMasterVolume
  1171. {
  1172. MMDeviceMasterVolume()
  1173. {
  1174. ComSmartPtr<IMMDeviceEnumerator> enumerator;
  1175. if (check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  1176. {
  1177. ComSmartPtr<IMMDevice> device;
  1178. if (check (enumerator->GetDefaultAudioEndpoint (eRender, eConsole, device.resetAndGetPointerAddress())))
  1179. check (device->Activate (__uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, nullptr,
  1180. (void**) endpointVolume.resetAndGetPointerAddress()));
  1181. }
  1182. }
  1183. float getGain() const
  1184. {
  1185. float vol = 0.0f;
  1186. if (endpointVolume != nullptr)
  1187. check (endpointVolume->GetMasterVolumeLevelScalar (&vol));
  1188. return vol;
  1189. }
  1190. bool setGain (float newGain) const
  1191. {
  1192. return endpointVolume != nullptr
  1193. && check (endpointVolume->SetMasterVolumeLevelScalar (jlimit (0.0f, 1.0f, newGain), nullptr));
  1194. }
  1195. bool isMuted() const
  1196. {
  1197. BOOL mute = 0;
  1198. return endpointVolume != nullptr
  1199. && check (endpointVolume->GetMute (&mute)) && mute != 0;
  1200. }
  1201. bool setMuted (bool shouldMute) const
  1202. {
  1203. return endpointVolume != nullptr
  1204. && check (endpointVolume->SetMute (shouldMute, nullptr));
  1205. }
  1206. ComSmartPtr<IAudioEndpointVolume> endpointVolume;
  1207. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MMDeviceMasterVolume)
  1208. };
  1209. }
  1210. //==============================================================================
  1211. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI()
  1212. {
  1213. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1214. return new WasapiClasses::WASAPIAudioIODeviceType();
  1215. return nullptr;
  1216. }
  1217. //==============================================================================
  1218. #define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
  1219. float JUCE_CALLTYPE SystemAudioVolume::getGain() { return WasapiClasses::MMDeviceMasterVolume().getGain(); }
  1220. bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return WasapiClasses::MMDeviceMasterVolume().setGain (gain); }
  1221. bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return WasapiClasses::MMDeviceMasterVolume().isMuted(); }
  1222. bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return WasapiClasses::MMDeviceMasterVolume().setMuted (mute); }