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

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