wasapi.cpp 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 2011 by authors.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include "wasapi.h"
  22. #define WIN32_LEAN_AND_MEAN
  23. #include <windows.h>
  24. #include <cstdio>
  25. #include <cstdlib>
  26. #include <memory.h>
  27. #include <avrt.h>
  28. #include <wtypes.h>
  29. #include <mmdeviceapi.h>
  30. #include <audiosessiontypes.h>
  31. #include <audioclient.h>
  32. #include <spatialaudioclient.h>
  33. #include <cguid.h>
  34. #include <devpropdef.h>
  35. #include <mmreg.h>
  36. #include <propsys.h>
  37. #include <propkey.h>
  38. #include <devpkey.h>
  39. #ifndef _WAVEFORMATEXTENSIBLE_
  40. #include <ks.h>
  41. #include <ksmedia.h>
  42. #endif
  43. #include <algorithm>
  44. #include <atomic>
  45. #include <chrono>
  46. #include <condition_variable>
  47. #include <cstring>
  48. #include <functional>
  49. #include <future>
  50. #include <mutex>
  51. #include <string>
  52. #include <string_view>
  53. #include <thread>
  54. #include <vector>
  55. #include "albit.h"
  56. #include "alc/alconfig.h"
  57. #include "alnumeric.h"
  58. #include "alspan.h"
  59. #include "alstring.h"
  60. #include "althrd_setname.h"
  61. #include "comptr.h"
  62. #include "core/converter.h"
  63. #include "core/device.h"
  64. #include "core/logging.h"
  65. #include "fmt/core.h"
  66. #include "fmt/chrono.h"
  67. #include "ringbuffer.h"
  68. #include "strutils.h"
  69. #if ALSOFT_UWP
  70. #include <winrt/Windows.Media.Core.h> // !!This is important!!
  71. #include <winrt/Windows.Foundation.Collections.h>
  72. #include <winrt/Windows.Devices.h>
  73. #include <winrt/Windows.Foundation.h>
  74. #include <winrt/Windows.Devices.Enumeration.h>
  75. #include <winrt/Windows.Media.Devices.h>
  76. #include "alstring.h"
  77. #endif
  78. /* Some headers seem to define these as macros for __uuidof, which is annoying
  79. * since some headers don't declare them at all. Hopefully the ifdef is enough
  80. * to tell if they need to be declared.
  81. */
  82. #ifndef KSDATAFORMAT_SUBTYPE_PCM
  83. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
  84. #endif
  85. #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
  86. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
  87. #endif
  88. #if !ALSOFT_UWP
  89. DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
  90. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
  91. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
  92. #endif
  93. namespace {
  94. #if ALSOFT_UWP
  95. using namespace winrt;
  96. using namespace Windows::Foundation;
  97. using namespace Windows::Media::Devices;
  98. using namespace Windows::Devices::Enumeration;
  99. using namespace Windows::Media::Devices;
  100. #endif
  101. #ifndef E_NOTFOUND
  102. #define E_NOTFOUND E_NOINTERFACE
  103. #endif
  104. using namespace std::string_view_literals;
  105. using std::chrono::nanoseconds;
  106. using std::chrono::milliseconds;
  107. using std::chrono::seconds;
  108. using ReferenceTime = std::chrono::duration<REFERENCE_TIME,std::ratio<1,10'000'000>>;
  109. #define MONO SPEAKER_FRONT_CENTER
  110. #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
  111. #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
  112. #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  113. #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
  114. #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  115. #define X7DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  116. #define X7DOT1DOT4 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT|SPEAKER_TOP_FRONT_LEFT|SPEAKER_TOP_FRONT_RIGHT|SPEAKER_TOP_BACK_LEFT|SPEAKER_TOP_BACK_RIGHT)
  117. constexpr auto MaskFromTopBits(DWORD b) noexcept -> DWORD
  118. {
  119. b |= b>>1;
  120. b |= b>>2;
  121. b |= b>>4;
  122. b |= b>>8;
  123. b |= b>>16;
  124. return b;
  125. }
  126. constexpr DWORD MonoMask{MaskFromTopBits(MONO)};
  127. constexpr DWORD StereoMask{MaskFromTopBits(STEREO)};
  128. constexpr DWORD QuadMask{MaskFromTopBits(QUAD)};
  129. constexpr DWORD X51Mask{MaskFromTopBits(X5DOT1)};
  130. constexpr DWORD X51RearMask{MaskFromTopBits(X5DOT1REAR)};
  131. constexpr DWORD X61Mask{MaskFromTopBits(X6DOT1)};
  132. constexpr DWORD X71Mask{MaskFromTopBits(X7DOT1)};
  133. constexpr DWORD X714Mask{MaskFromTopBits(X7DOT1DOT4)};
  134. #ifndef _MSC_VER
  135. constexpr AudioObjectType operator|(AudioObjectType lhs, AudioObjectType rhs) noexcept
  136. { return static_cast<AudioObjectType>(lhs | al::to_underlying(rhs)); }
  137. #endif
  138. constexpr AudioObjectType ChannelMask_Mono{AudioObjectType_FrontCenter};
  139. constexpr AudioObjectType ChannelMask_Stereo{AudioObjectType_FrontLeft
  140. | AudioObjectType_FrontRight};
  141. constexpr AudioObjectType ChannelMask_Quad{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
  142. | AudioObjectType_BackLeft | AudioObjectType_BackRight};
  143. constexpr AudioObjectType ChannelMask_X51{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
  144. | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
  145. | AudioObjectType_SideRight};
  146. constexpr AudioObjectType ChannelMask_X61{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
  147. | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
  148. | AudioObjectType_SideRight | AudioObjectType_BackCenter};
  149. constexpr AudioObjectType ChannelMask_X71{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
  150. | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
  151. | AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight};
  152. constexpr AudioObjectType ChannelMask_X714{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
  153. | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
  154. | AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight
  155. | AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft
  156. | AudioObjectType_TopBackRight};
  157. constexpr AudioObjectType ChannelMask_X7144{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
  158. | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
  159. | AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight
  160. | AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft
  161. | AudioObjectType_TopBackRight | AudioObjectType_BottomFrontLeft
  162. | AudioObjectType_BottomFrontRight | AudioObjectType_BottomBackLeft
  163. | AudioObjectType_BottomBackRight};
  164. template<typename... Ts>
  165. struct overloaded : Ts... { using Ts::operator()...; };
  166. template<typename... Ts>
  167. overloaded(Ts...) -> overloaded<Ts...>;
  168. template<typename T>
  169. struct CoTaskMemDeleter {
  170. void operator()(T *ptr) const { CoTaskMemFree(ptr); }
  171. };
  172. template<typename T>
  173. using unique_coptr = std::unique_ptr<T,CoTaskMemDeleter<T>>;
  174. /* Scales the given reftime value, rounding the result. */
  175. constexpr auto RefTime2Samples(const ReferenceTime &val, DWORD srate) noexcept -> uint
  176. {
  177. const auto retval = (val*srate + ReferenceTime{seconds{1}}/2) / seconds{1};
  178. return static_cast<uint>(std::min<decltype(retval)>(retval, std::numeric_limits<uint>::max()));
  179. }
  180. class GuidPrinter {
  181. std::string mMsg;
  182. public:
  183. explicit GuidPrinter(const GUID &guid)
  184. : mMsg{fmt::format(
  185. "{{{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}}}",
  186. guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2],
  187. guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7])}
  188. { }
  189. [[nodiscard]] auto str() const noexcept -> const std::string& { return mMsg; }
  190. };
  191. struct PropVariant {
  192. PROPVARIANT mProp{};
  193. public:
  194. PropVariant() { PropVariantInit(&mProp); }
  195. PropVariant(const PropVariant &rhs) : PropVariant{} { PropVariantCopy(&mProp, &rhs.mProp); }
  196. ~PropVariant() { clear(); }
  197. auto operator=(const PropVariant &rhs) -> PropVariant&
  198. {
  199. if(this != &rhs)
  200. PropVariantCopy(&mProp, &rhs.mProp);
  201. return *this;
  202. }
  203. void clear() { PropVariantClear(&mProp); }
  204. PROPVARIANT* get() noexcept { return &mProp; }
  205. /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
  206. [[nodiscard]]
  207. auto type() const noexcept -> VARTYPE { return mProp.vt; }
  208. template<typename T> [[nodiscard]]
  209. auto value() const -> T
  210. {
  211. if constexpr(std::is_same_v<T,uint>)
  212. {
  213. alassert(mProp.vt == VT_UI4 || mProp.vt == VT_UINT);
  214. return mProp.uintVal;
  215. }
  216. else if constexpr(std::is_same_v<T,std::wstring_view> || std::is_same_v<T,std::wstring>
  217. || std::is_same_v<T,LPWSTR> || std::is_same_v<T,LPCWSTR>)
  218. {
  219. alassert(mProp.vt == VT_LPWSTR);
  220. return mProp.pwszVal;
  221. }
  222. }
  223. void setBlob(const al::span<BYTE> data)
  224. {
  225. if constexpr(sizeof(size_t) > sizeof(ULONG))
  226. alassert(data.size() <= std::numeric_limits<ULONG>::max());
  227. mProp.vt = VT_BLOB;
  228. mProp.blob.cbSize = static_cast<ULONG>(data.size());
  229. mProp.blob.pBlobData = data.data();
  230. }
  231. /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
  232. };
  233. struct DevMap {
  234. std::string name;
  235. std::string endpoint_guid; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
  236. std::wstring devid;
  237. template<typename T0, typename T1, typename T2>
  238. DevMap(T0&& name_, T1&& guid_, T2&& devid_)
  239. : name{std::forward<T0>(name_)}
  240. , endpoint_guid{std::forward<T1>(guid_)}
  241. , devid{std::forward<T2>(devid_)}
  242. { }
  243. /* To prevent GCC from complaining it doesn't want to inline this. */
  244. ~DevMap();
  245. };
  246. DevMap::~DevMap() = default;
  247. bool checkName(const al::span<DevMap> list, const std::string_view name)
  248. {
  249. auto match_name = [name](const DevMap &entry) -> bool { return entry.name == name; };
  250. return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
  251. }
  252. struct DeviceList {
  253. auto lock() noexcept(noexcept(mMutex.lock())) { return mMutex.lock(); }
  254. auto unlock() noexcept(noexcept(mMutex.unlock())) { return mMutex.unlock(); }
  255. private:
  256. std::mutex mMutex;
  257. std::vector<DevMap> mPlayback;
  258. std::vector<DevMap> mCapture;
  259. std::wstring mPlaybackDefaultId;
  260. std::wstring mCaptureDefaultId;
  261. friend struct DeviceListLock;
  262. };
  263. struct DeviceListLock : public std::unique_lock<DeviceList> {
  264. using std::unique_lock<DeviceList>::unique_lock;
  265. [[nodiscard]] auto& getPlaybackList() const noexcept { return mutex()->mPlayback; }
  266. [[nodiscard]] auto& getCaptureList() const noexcept { return mutex()->mCapture; }
  267. void setPlaybackDefaultId(std::wstring_view devid) const { mutex()->mPlaybackDefaultId = devid; }
  268. [[nodiscard]] auto getPlaybackDefaultId() const noexcept -> std::wstring_view { return mutex()->mPlaybackDefaultId; }
  269. void setCaptureDefaultId(std::wstring_view devid) const { mutex()->mCaptureDefaultId = devid; }
  270. [[nodiscard]] auto getCaptureDefaultId() const noexcept -> std::wstring_view { return mutex()->mCaptureDefaultId; }
  271. };
  272. DeviceList gDeviceList;
  273. std::condition_variable_any gInitCV;
  274. std::atomic<bool> gInitDone{false};
  275. #ifdef AVRTAPI
  276. struct AvrtHandleCloser {
  277. void operator()(HANDLE handle) { AvRevertMmThreadCharacteristics(handle); }
  278. };
  279. using AvrtHandlePtr = std::unique_ptr<std::remove_pointer_t<HANDLE>,AvrtHandleCloser>;
  280. #endif
  281. #if ALSOFT_UWP
  282. enum EDataFlow {
  283. eRender = 0,
  284. eCapture = (eRender + 1),
  285. eAll = (eCapture + 1),
  286. EDataFlow_enum_count = (eAll + 1)
  287. };
  288. #endif
  289. #if ALSOFT_UWP
  290. using DeviceHandle = Windows::Devices::Enumeration::DeviceInformation;
  291. using EventRegistrationToken = winrt::event_token;
  292. #else
  293. using DeviceHandle = ComPtr<IMMDevice>;
  294. #endif
  295. struct NameGUIDPair { std::string mName; std::string mGuid; };
  296. auto GetDeviceNameAndGuid(const DeviceHandle &device) -> NameGUIDPair
  297. {
  298. constexpr auto UnknownName = "Unknown Device Name"sv;
  299. constexpr auto UnknownGuid = "Unknown Device GUID"sv;
  300. #if !ALSOFT_UWP
  301. auto ps = ComPtr<IPropertyStore>{};
  302. auto hr = device->OpenPropertyStore(STGM_READ, al::out_ptr(ps));
  303. if(FAILED(hr))
  304. {
  305. WARN("OpenPropertyStore failed: {:#x}", as_unsigned(hr));
  306. return NameGUIDPair{std::string{UnknownName}, std::string{UnknownGuid}};
  307. }
  308. auto ret = NameGUIDPair{};
  309. auto pvprop = PropVariant{};
  310. hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(DEVPKEY_Device_FriendlyName), pvprop.get());
  311. if(FAILED(hr))
  312. WARN("GetValue Device_FriendlyName failed: {:#x}", as_unsigned(hr));
  313. else if(pvprop.type() == VT_LPWSTR)
  314. ret.mName = wstr_to_utf8(pvprop.value<std::wstring_view>());
  315. else
  316. WARN("Unexpected Device_FriendlyName PROPVARIANT type: {:#04x}", pvprop.type());
  317. pvprop.clear();
  318. hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(PKEY_AudioEndpoint_GUID), pvprop.get());
  319. if(FAILED(hr))
  320. WARN("GetValue AudioEndpoint_GUID failed: {:#x}", as_unsigned(hr));
  321. else if(pvprop.type() == VT_LPWSTR)
  322. ret.mGuid = wstr_to_utf8(pvprop.value<std::wstring_view>());
  323. else
  324. WARN("Unexpected AudioEndpoint_GUID PROPVARIANT type: {:#04x}", pvprop.type());
  325. #else
  326. auto ret = NameGUIDPair{wstr_to_utf8(device.Name()), {}};
  327. // device->Id is DeviceInterfacePath: \\?\SWD#MMDEVAPI#{0.0.0.00000000}.{a21c17a0-fc1d-405e-ab5a-b513422b57d1}#{e6327cad-dcec-4949-ae8a-991e976a79d2}
  328. auto devIfPath = device.Id();
  329. if(auto devIdStart = wcsstr(devIfPath.data(), L"}."))
  330. {
  331. devIdStart += 2; // L"}."
  332. if(auto devIdStartEnd = wcschr(devIdStart, L'#'))
  333. {
  334. ret.mGuid = wstr_to_utf8(std::wstring_view{devIdStart,
  335. static_cast<size_t>(devIdStartEnd - devIdStart)});
  336. std::transform(ret.mGuid.begin(), ret.mGuid.end(), ret.mGuid.begin(),
  337. [](char ch) { return static_cast<char>(std::toupper(ch)); });
  338. }
  339. }
  340. #endif
  341. if(ret.mName.empty()) ret.mName = UnknownName;
  342. if(ret.mGuid.empty()) ret.mGuid = UnknownGuid;
  343. return ret;
  344. }
  345. #if !ALSOFT_UWP
  346. EndpointFormFactor GetDeviceFormfactor(IMMDevice *device)
  347. {
  348. ComPtr<IPropertyStore> ps;
  349. HRESULT hr{device->OpenPropertyStore(STGM_READ, al::out_ptr(ps))};
  350. if(FAILED(hr))
  351. {
  352. WARN("OpenPropertyStore failed: {:#x}", as_unsigned(hr));
  353. return UnknownFormFactor;
  354. }
  355. EndpointFormFactor formfactor{UnknownFormFactor};
  356. PropVariant pvform;
  357. hr = ps->GetValue(PKEY_AudioEndpoint_FormFactor, pvform.get());
  358. if(FAILED(hr))
  359. WARN("GetValue AudioEndpoint_FormFactor failed: {:#x}", as_unsigned(hr));
  360. else if(pvform.type() == VT_UI4)
  361. formfactor = static_cast<EndpointFormFactor>(pvform.value<uint>());
  362. else if(pvform.type() != VT_EMPTY)
  363. WARN("Unexpected PROPVARIANT type: {:#04x}", pvform.type());
  364. return formfactor;
  365. }
  366. #endif
  367. #if ALSOFT_UWP
  368. struct DeviceEnumHelper final : public IActivateAudioInterfaceCompletionHandler {
  369. DeviceEnumHelper()
  370. {
  371. /* TODO: UWP also needs to watch for device added/removed events and
  372. * dynamically add/remove devices from the lists.
  373. */
  374. mActiveClientEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
  375. static constexpr auto playback_cb = [](const IInspectable &sender [[maybe_unused]],
  376. const DefaultAudioRenderDeviceChangedEventArgs &args)
  377. {
  378. if(args.Role() == AudioDeviceRole::Default)
  379. {
  380. const auto msg = std::string{"Default playback device changed: " +
  381. wstr_to_utf8(args.Id())};
  382. alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
  383. }
  384. };
  385. mRenderDeviceChangedToken = MediaDevice::DefaultAudioRenderDeviceChanged(playback_cb);
  386. static constexpr auto capture_cb = [](const IInspectable &sender [[maybe_unused]],
  387. const DefaultAudioCaptureDeviceChangedEventArgs &args)
  388. {
  389. if(args.Role() == AudioDeviceRole::Default)
  390. {
  391. const auto msg = std::string{"Default capture device changed: " +
  392. wstr_to_utf8(args.Id())};
  393. alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
  394. }
  395. };
  396. mCaptureDeviceChangedToken = MediaDevice::DefaultAudioCaptureDeviceChanged(capture_cb);
  397. }
  398. ~DeviceEnumHelper()
  399. {
  400. MediaDevice::DefaultAudioRenderDeviceChanged(mRenderDeviceChangedToken);
  401. MediaDevice::DefaultAudioCaptureDeviceChanged(mCaptureDeviceChangedToken);
  402. if(mActiveClientEvent != nullptr)
  403. CloseHandle(mActiveClientEvent);
  404. mActiveClientEvent = nullptr;
  405. }
  406. #else
  407. struct DeviceEnumHelper final : private IMMNotificationClient {
  408. DeviceEnumHelper() = default;
  409. ~DeviceEnumHelper()
  410. {
  411. if(mEnumerator)
  412. mEnumerator->UnregisterEndpointNotificationCallback(this);
  413. mEnumerator = nullptr;
  414. }
  415. #endif
  416. template<typename T>
  417. auto as() noexcept -> T { return T{this}; }
  418. /** -------------------------- IUnknown ----------------------------- */
  419. std::atomic<ULONG> mRefCount{1};
  420. STDMETHODIMP_(ULONG) AddRef() noexcept override { return mRefCount.fetch_add(1u) + 1u; }
  421. STDMETHODIMP_(ULONG) Release() noexcept override { return mRefCount.fetch_sub(1u) - 1u; }
  422. STDMETHODIMP QueryInterface(const IID& IId, void **UnknownPtrPtr) noexcept override
  423. {
  424. // Three rules of QueryInterface:
  425. // https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface
  426. // 1. Objects must have identity.
  427. // 2. The set of interfaces on an object instance must be static.
  428. // 3. It must be possible to query successfully for any interface on an object from any other interface.
  429. // If ppvObject(the address) is nullptr, then this method returns E_POINTER.
  430. if(!UnknownPtrPtr)
  431. return E_POINTER;
  432. // https://docs.microsoft.com/en-us/windows/win32/com/implementing-reference-counting
  433. // Whenever a client calls a method(or API function), such as QueryInterface, that returns a new interface
  434. // pointer, the method being called is responsible for incrementing the reference count through the returned
  435. // pointer. For example, when a client first creates an object, it receives an interface pointer to an object
  436. // that, from the client's point of view, has a reference count of one. If the client then calls AddRef on the
  437. // interface pointer, the reference count becomes two. The client must call Release twice on the interface
  438. // pointer to drop all of its references to the object.
  439. #if ALSOFT_UWP
  440. if(IId == __uuidof(IActivateAudioInterfaceCompletionHandler))
  441. {
  442. *UnknownPtrPtr = as<IActivateAudioInterfaceCompletionHandler*>();
  443. AddRef();
  444. return S_OK;
  445. }
  446. #else
  447. if(IId == __uuidof(IMMNotificationClient))
  448. {
  449. *UnknownPtrPtr = as<IMMNotificationClient*>();
  450. AddRef();
  451. return S_OK;
  452. }
  453. #endif
  454. else if(IId == __uuidof(IAgileObject) || IId == __uuidof(IUnknown))
  455. {
  456. *UnknownPtrPtr = as<IUnknown*>();
  457. AddRef();
  458. return S_OK;
  459. }
  460. // This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise.
  461. *UnknownPtrPtr = nullptr;
  462. return E_NOINTERFACE;
  463. }
  464. #if ALSOFT_UWP
  465. /** ----------------------- IActivateAudioInterfaceCompletionHandler ------------ */
  466. HRESULT ActivateCompleted(IActivateAudioInterfaceAsyncOperation*) override
  467. {
  468. SetEvent(mActiveClientEvent);
  469. // Need to return S_OK
  470. return S_OK;
  471. }
  472. #else
  473. /** ----------------------- IMMNotificationClient ------------ */
  474. STDMETHODIMP OnDeviceStateChanged(LPCWSTR deviceId, DWORD newState) noexcept override
  475. {
  476. TRACE("OnDeviceStateChanged({}, {:#x})", deviceId ? wstr_to_utf8(deviceId)
  477. : std::string{"<null>"}, newState);
  478. if(!(newState&DEVICE_STATE_ACTIVE))
  479. return DeviceRemoved(deviceId);
  480. return DeviceAdded(deviceId);
  481. }
  482. STDMETHODIMP OnDeviceAdded(LPCWSTR deviceId) noexcept override
  483. {
  484. TRACE("OnDeviceAdded({})", deviceId ? wstr_to_utf8(deviceId) : std::string{"<null>"});
  485. return DeviceAdded(deviceId);
  486. }
  487. STDMETHODIMP OnDeviceRemoved(LPCWSTR deviceId) noexcept override
  488. {
  489. TRACE("OnDeviceRemoved({})", deviceId ? wstr_to_utf8(deviceId) : std::string{"<null>"});
  490. return DeviceRemoved(deviceId);
  491. }
  492. /* NOLINTNEXTLINE(clazy-function-args-by-ref) */
  493. STDMETHODIMP OnPropertyValueChanged(LPCWSTR /*pwstrDeviceId*/, const PROPERTYKEY /*key*/) noexcept override { return S_OK; }
  494. STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR defaultDeviceId) noexcept override
  495. {
  496. TRACE("OnDefaultDeviceChanged({}, {}, {})", al::to_underlying(flow),
  497. al::to_underlying(role), defaultDeviceId ? wstr_to_utf8(defaultDeviceId)
  498. : std::string{"<null>"});
  499. if(role != eMultimedia)
  500. return S_OK;
  501. const auto devid = defaultDeviceId ? std::wstring_view{defaultDeviceId}
  502. : std::wstring_view{};
  503. if(flow == eRender)
  504. {
  505. DeviceListLock{gDeviceList}.setPlaybackDefaultId(devid);
  506. const std::string msg{"Default playback device changed: " + wstr_to_utf8(devid)};
  507. alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
  508. }
  509. else if(flow == eCapture)
  510. {
  511. DeviceListLock{gDeviceList}.setCaptureDefaultId(devid);
  512. const std::string msg{"Default capture device changed: " + wstr_to_utf8(devid)};
  513. alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
  514. }
  515. return S_OK;
  516. }
  517. #endif
  518. /** ------------------------ DeviceEnumHelper -------------------------- */
  519. HRESULT init()
  520. {
  521. #if !ALSOFT_UWP
  522. HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
  523. __uuidof(IMMDeviceEnumerator), al::out_ptr(mEnumerator))};
  524. if(SUCCEEDED(hr))
  525. mEnumerator->RegisterEndpointNotificationCallback(this);
  526. else
  527. WARN("Failed to create IMMDeviceEnumerator instance: {:#x}", as_unsigned(hr));
  528. return hr;
  529. #else
  530. return S_OK;
  531. #endif
  532. }
  533. std::wstring probeDevices(EDataFlow flowdir, std::vector<DevMap> &list)
  534. {
  535. std::wstring defaultId;
  536. std::vector<DevMap>{}.swap(list);
  537. #if !ALSOFT_UWP
  538. ComPtr<IMMDeviceCollection> coll;
  539. HRESULT hr{mEnumerator->EnumAudioEndpoints(flowdir, DEVICE_STATE_ACTIVE,
  540. al::out_ptr(coll))};
  541. if(FAILED(hr))
  542. {
  543. ERR("Failed to enumerate audio endpoints: {:#x}", as_unsigned(hr));
  544. return defaultId;
  545. }
  546. UINT count{0};
  547. hr = coll->GetCount(&count);
  548. if(SUCCEEDED(hr) && count > 0)
  549. list.reserve(count);
  550. ComPtr<IMMDevice> device;
  551. hr = mEnumerator->GetDefaultAudioEndpoint(flowdir, eMultimedia, al::out_ptr(device));
  552. if(SUCCEEDED(hr))
  553. {
  554. auto devid = unique_coptr<WCHAR>{};
  555. if(auto hr2 = device->GetId(al::out_ptr(devid)); SUCCEEDED(hr2))
  556. defaultId = devid.get();
  557. else
  558. ERR("Failed to get device id: {:#x}", as_unsigned(hr));
  559. device = nullptr;
  560. }
  561. for(UINT i{0};i < count;++i)
  562. {
  563. hr = coll->Item(i, al::out_ptr(device));
  564. if(FAILED(hr))
  565. continue;
  566. auto devid = unique_coptr<WCHAR>{};
  567. if(auto hr2 = device->GetId(al::out_ptr(devid)); SUCCEEDED(hr2))
  568. std::ignore = AddDevice(device, devid.get(), list);
  569. else
  570. ERR("Failed to get device id: {:#x}", as_unsigned(hr));
  571. device = nullptr;
  572. }
  573. #else
  574. const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
  575. auto DefaultAudioId = flowdir == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole)
  576. : MediaDevice::GetDefaultAudioCaptureId(deviceRole);
  577. if(!DefaultAudioId.empty())
  578. {
  579. auto deviceInfo = DeviceInformation::CreateFromIdAsync(DefaultAudioId, nullptr,
  580. DeviceInformationKind::DeviceInterface).get();
  581. if(deviceInfo)
  582. defaultId = deviceInfo.Id().data();
  583. }
  584. // Get the string identifier of the audio renderer
  585. auto AudioSelector = flowdir == eRender ? MediaDevice::GetAudioRenderSelector() : MediaDevice::GetAudioCaptureSelector();
  586. // Setup the asynchronous callback
  587. auto&& DeviceInfoCollection = DeviceInformation::FindAllAsync(AudioSelector, /*PropertyList*/nullptr, DeviceInformationKind::DeviceInterface).get();
  588. if(DeviceInfoCollection)
  589. {
  590. try {
  591. auto deviceCount = DeviceInfoCollection.Size();
  592. for(unsigned int i{0};i < deviceCount;++i)
  593. {
  594. auto deviceInfo = DeviceInfoCollection.GetAt(i);
  595. if(deviceInfo)
  596. std::ignore = AddDevice(deviceInfo, deviceInfo.Id().data(), list);
  597. }
  598. }
  599. catch (const winrt::hresult_error& /*ex*/) {
  600. }
  601. }
  602. #endif
  603. return defaultId;
  604. }
  605. private:
  606. static bool AddDevice(const DeviceHandle &device, const WCHAR *devid, std::vector<DevMap> &list)
  607. {
  608. for(auto &entry : list)
  609. {
  610. if(entry.devid == devid)
  611. return false;
  612. }
  613. auto [name, guid] = GetDeviceNameAndGuid(device);
  614. auto count = 1;
  615. auto newname = name;
  616. while(checkName(list, newname))
  617. newname = fmt::format("{} #{}", name, ++count);
  618. const auto &newentry = list.emplace_back(std::move(newname), std::move(guid), devid);
  619. TRACE("Got device \"{}\", \"{}\", \"{}\"", newentry.name, newentry.endpoint_guid,
  620. wstr_to_utf8(newentry.devid));
  621. return true;
  622. }
  623. #if !ALSOFT_UWP
  624. STDMETHODIMP DeviceAdded(LPCWSTR deviceId) noexcept
  625. {
  626. auto device = ComPtr<IMMDevice>{};
  627. auto hr = mEnumerator->GetDevice(deviceId, al::out_ptr(device));
  628. if(FAILED(hr))
  629. {
  630. ERR("Failed to get device: {:#x}", as_unsigned(hr));
  631. return S_OK;
  632. }
  633. auto state = DWORD{};
  634. hr = device->GetState(&state);
  635. if(FAILED(hr))
  636. {
  637. ERR("Failed to get device state: {:#x}", as_unsigned(hr));
  638. return S_OK;
  639. }
  640. if(!(state&DEVICE_STATE_ACTIVE))
  641. return S_OK;
  642. auto endpoint = ComPtr<IMMEndpoint>{};
  643. hr = device->QueryInterface(__uuidof(IMMEndpoint), al::out_ptr(endpoint));
  644. if(FAILED(hr))
  645. {
  646. ERR("Failed to get device endpoint: {:#x}", as_unsigned(hr));
  647. return S_OK;
  648. }
  649. auto flowdir = EDataFlow{};
  650. hr = endpoint->GetDataFlow(&flowdir);
  651. if(FAILED(hr))
  652. {
  653. ERR("Failed to get endpoint data flow: {:#x}", as_unsigned(hr));
  654. return S_OK;
  655. }
  656. auto devlock = DeviceListLock{gDeviceList};
  657. auto &list = (flowdir == eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
  658. if(AddDevice(device, deviceId, list))
  659. {
  660. const auto devtype = (flowdir == eRender) ? alc::DeviceType::Playback
  661. : alc::DeviceType::Capture;
  662. const auto msg = "Device added: "+list.back().name;
  663. alc::Event(alc::EventType::DeviceAdded, devtype, msg);
  664. }
  665. return S_OK;
  666. }
  667. STDMETHODIMP DeviceRemoved(LPCWSTR deviceId) noexcept
  668. {
  669. auto devlock = DeviceListLock{gDeviceList};
  670. for(auto flowdir : std::array{eRender, eCapture})
  671. {
  672. auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
  673. auto devtype = (flowdir==eRender)?alc::DeviceType::Playback : alc::DeviceType::Capture;
  674. /* Find the ID in the list to remove. */
  675. auto iter = std::find_if(list.begin(), list.end(),
  676. [deviceId](const DevMap &entry) noexcept { return deviceId == entry.devid; });
  677. if(iter == list.end()) continue;
  678. TRACE("Removing device \"{}\", \"{}\", \"{}\"", iter->name, iter->endpoint_guid,
  679. wstr_to_utf8(iter->devid));
  680. std::string msg{"Device removed: "+std::move(iter->name)};
  681. list.erase(iter);
  682. alc::Event(alc::EventType::DeviceRemoved, devtype, msg);
  683. }
  684. return S_OK;
  685. }
  686. ComPtr<IMMDeviceEnumerator> mEnumerator{nullptr};
  687. #else
  688. HANDLE mActiveClientEvent{nullptr};
  689. EventRegistrationToken mRenderDeviceChangedToken;
  690. EventRegistrationToken mCaptureDeviceChangedToken;
  691. #endif
  692. static inline std::mutex mMsgLock;
  693. static inline std::condition_variable mMsgCond;
  694. static inline bool mQuit{false};
  695. [[nodiscard]]
  696. static bool quit()
  697. {
  698. auto lock = std::unique_lock{mMsgLock};
  699. mMsgCond.wait(lock, []{return mQuit;});
  700. return mQuit;
  701. }
  702. public:
  703. static void messageHandler(std::promise<HRESULT> *promise);
  704. };
  705. /* Manages a DeviceEnumHelper on its own thread, to track available devices. */
  706. void DeviceEnumHelper::messageHandler(std::promise<HRESULT> *promise)
  707. {
  708. TRACE("Starting watcher thread");
  709. ComWrapper com{COINIT_MULTITHREADED};
  710. if(!com)
  711. {
  712. WARN("Failed to initialize COM: {:#x}", as_unsigned(com.status()));
  713. promise->set_value(com.status());
  714. return;
  715. }
  716. auto helper = std::optional<DeviceEnumHelper>{};
  717. try {
  718. auto devlock = DeviceListLock{gDeviceList};
  719. auto hr = helper.emplace().init();
  720. promise->set_value(hr);
  721. promise = nullptr;
  722. if(FAILED(hr))
  723. return;
  724. auto defaultId = helper->probeDevices(eRender, devlock.getPlaybackList());
  725. if(!defaultId.empty()) devlock.setPlaybackDefaultId(defaultId);
  726. defaultId = helper->probeDevices(eCapture, devlock.getCaptureList());
  727. if(!defaultId.empty()) devlock.setCaptureDefaultId(defaultId);
  728. gInitDone.store(true, std::memory_order_relaxed);
  729. }
  730. catch(std::exception &e) {
  731. ERR("Exception probing devices: {}", e.what());
  732. if(promise)
  733. promise->set_value(E_FAIL);
  734. return;
  735. }
  736. TRACE("Watcher thread started");
  737. gInitCV.notify_all();
  738. while(!quit()) {
  739. /* Do nothing. */
  740. }
  741. }
  742. #if ALSOFT_UWP
  743. struct DeviceHelper final : public IActivateAudioInterfaceCompletionHandler {
  744. DeviceHelper()
  745. {
  746. mActiveClientEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
  747. }
  748. ~DeviceHelper()
  749. {
  750. if(mActiveClientEvent != nullptr)
  751. CloseHandle(mActiveClientEvent);
  752. mActiveClientEvent = nullptr;
  753. }
  754. template<typename T>
  755. auto as() noexcept -> T { return T{this}; }
  756. /** -------------------------- IUnknown ----------------------------- */
  757. std::atomic<ULONG> mRefCount{1};
  758. STDMETHODIMP_(ULONG) AddRef() noexcept override { return mRefCount.fetch_add(1u) + 1u; }
  759. STDMETHODIMP_(ULONG) Release() noexcept override { return mRefCount.fetch_sub(1u) - 1u; }
  760. STDMETHODIMP QueryInterface(const IID& IId, void **UnknownPtrPtr) noexcept override
  761. {
  762. // Three rules of QueryInterface:
  763. // https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface
  764. // 1. Objects must have identity.
  765. // 2. The set of interfaces on an object instance must be static.
  766. // 3. It must be possible to query successfully for any interface on an object from any other interface.
  767. // If ppvObject(the address) is nullptr, then this method returns E_POINTER.
  768. if(!UnknownPtrPtr)
  769. return E_POINTER;
  770. if(IId == __uuidof(IActivateAudioInterfaceCompletionHandler))
  771. {
  772. *UnknownPtrPtr = as<IActivateAudioInterfaceCompletionHandler*>();
  773. AddRef();
  774. return S_OK;
  775. }
  776. else if(IId == __uuidof(IAgileObject) || IId == __uuidof(IUnknown))
  777. {
  778. *UnknownPtrPtr = as<IUnknown*>();
  779. AddRef();
  780. return S_OK;
  781. }
  782. // This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise.
  783. *UnknownPtrPtr = nullptr;
  784. return E_NOINTERFACE;
  785. }
  786. /** ----------------------- IActivateAudioInterfaceCompletionHandler ------------ */
  787. HRESULT ActivateCompleted(IActivateAudioInterfaceAsyncOperation*) override
  788. {
  789. SetEvent(mActiveClientEvent);
  790. // Need to return S_OK
  791. return S_OK;
  792. }
  793. /** -------------------------- DeviceHelper ----------------------------- */
  794. [[nodiscard]] constexpr
  795. auto init() -> HRESULT { return S_OK; }
  796. [[nodiscard]]
  797. auto openDevice(const std::wstring &devid, EDataFlow flow, DeviceHandle &device) -> HRESULT
  798. {
  799. const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
  800. auto devIfPath =
  801. devid.empty() ? (flow == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole)
  802. : MediaDevice::GetDefaultAudioCaptureId(deviceRole))
  803. : winrt::hstring(devid.c_str());
  804. if (devIfPath.empty())
  805. return E_POINTER;
  806. auto&& deviceInfo = DeviceInformation::CreateFromIdAsync(devIfPath, nullptr,
  807. DeviceInformationKind::DeviceInterface).get();
  808. if(!deviceInfo)
  809. return E_NOINTERFACE;
  810. device = deviceInfo;
  811. return S_OK;
  812. }
  813. [[nodiscard]]
  814. auto activateAudioClient(_In_ DeviceHandle &device, _In_ REFIID iid, void **ppv) -> HRESULT
  815. {
  816. ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
  817. HRESULT hr{ActivateAudioInterfaceAsync(device.Id().data(), iid, nullptr, this,
  818. al::out_ptr(asyncOp))};
  819. if(FAILED(hr))
  820. return hr;
  821. /* I don't like waiting for INFINITE time, but the activate operation
  822. * can take an indefinite amount of time since it can require user
  823. * input.
  824. */
  825. DWORD res{WaitForSingleObjectEx(mActiveClientEvent, INFINITE, FALSE)};
  826. if(res != WAIT_OBJECT_0)
  827. {
  828. ERR("WaitForSingleObjectEx error: {:#x}", res);
  829. return E_FAIL;
  830. }
  831. HRESULT hrActivateRes{E_FAIL};
  832. ComPtr<IUnknown> punkAudioIface;
  833. hr = asyncOp->GetActivateResult(&hrActivateRes, al::out_ptr(punkAudioIface));
  834. if(SUCCEEDED(hr)) hr = hrActivateRes;
  835. if(FAILED(hr)) return hr;
  836. return punkAudioIface->QueryInterface(iid, ppv);
  837. }
  838. HANDLE mActiveClientEvent{nullptr};
  839. };
  840. #else
  841. struct DeviceHelper {
  842. DeviceHelper() = default;
  843. ~DeviceHelper() = default;
  844. [[nodiscard]]
  845. auto init() -> HRESULT
  846. {
  847. HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
  848. __uuidof(IMMDeviceEnumerator), al::out_ptr(mEnumerator))};
  849. if(FAILED(hr))
  850. WARN("Failed to create IMMDeviceEnumerator instance: {:#x}", as_unsigned(hr));
  851. return hr;
  852. }
  853. [[nodiscard]]
  854. auto openDevice(const std::wstring &devid, EDataFlow flow, DeviceHandle &device) const
  855. -> HRESULT
  856. {
  857. HRESULT hr{E_FAIL};
  858. if(mEnumerator)
  859. {
  860. if(devid.empty())
  861. hr = mEnumerator->GetDefaultAudioEndpoint(flow, eMultimedia, al::out_ptr(device));
  862. else
  863. hr = mEnumerator->GetDevice(devid.c_str(), al::out_ptr(device));
  864. }
  865. return hr;
  866. }
  867. [[nodiscard]]
  868. static auto activateAudioClient(_In_ DeviceHandle &device, REFIID iid, void **ppv) -> HRESULT
  869. {
  870. if(iid == __uuidof(IAudioClient))
  871. {
  872. /* Always (try) to activate an IAudioClient3, even if giving back
  873. * an IAudioClient iface. This may(?) offer more features even if
  874. * not using its new methods.
  875. */
  876. auto ac3 = ComPtr<IAudioClient3>{};
  877. const auto hr = device->Activate(__uuidof(IAudioClient3), CLSCTX_INPROC_SERVER,
  878. nullptr, al::out_ptr(ac3));
  879. if(SUCCEEDED(hr))
  880. return ac3->QueryInterface(iid, ppv);
  881. }
  882. return device->Activate(iid, CLSCTX_INPROC_SERVER, nullptr, ppv);
  883. }
  884. ComPtr<IMMDeviceEnumerator> mEnumerator{nullptr};
  885. };
  886. #endif
  887. bool MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in)
  888. {
  889. *out = WAVEFORMATEXTENSIBLE{};
  890. if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
  891. {
  892. *out = *CONTAINING_RECORD(in, const WAVEFORMATEXTENSIBLE, Format);
  893. out->Format.cbSize = sizeof(*out) - sizeof(out->Format);
  894. }
  895. else if(in->wFormatTag == WAVE_FORMAT_PCM)
  896. {
  897. out->Format = *in;
  898. out->Format.cbSize = 0;
  899. /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
  900. out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
  901. if(out->Format.nChannels == 1)
  902. out->dwChannelMask = MONO;
  903. else if(out->Format.nChannels == 2)
  904. out->dwChannelMask = STEREO;
  905. else
  906. ERR("Unhandled PCM channel count: {}", out->Format.nChannels);
  907. out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  908. }
  909. else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
  910. {
  911. out->Format = *in;
  912. out->Format.cbSize = 0;
  913. /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
  914. out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
  915. if(out->Format.nChannels == 1)
  916. out->dwChannelMask = MONO;
  917. else if(out->Format.nChannels == 2)
  918. out->dwChannelMask = STEREO;
  919. else
  920. ERR("Unhandled IEEE float channel count: {}", out->Format.nChannels);
  921. out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  922. }
  923. else
  924. {
  925. ERR("Unhandled format tag: {:#06x}", in->wFormatTag);
  926. return false;
  927. }
  928. return true;
  929. }
  930. void TraceFormat(const std::string_view msg, const WAVEFORMATEX *format)
  931. {
  932. constexpr size_t fmtex_extra_size{sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)};
  933. if(format->wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->cbSize >= fmtex_extra_size)
  934. {
  935. const auto *fmtex = CONTAINING_RECORD(format, const WAVEFORMATEXTENSIBLE, Format);
  936. /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
  937. TRACE("{}:\n"
  938. " FormatTag = {:#06x}\n"
  939. " Channels = {}\n"
  940. " SamplesPerSec = {}\n"
  941. " AvgBytesPerSec = {}\n"
  942. " BlockAlign = {}\n"
  943. " BitsPerSample = {}\n"
  944. " Size = {}\n"
  945. " Samples = {}\n"
  946. " ChannelMask = {:#x}\n"
  947. " SubFormat = {}",
  948. msg, fmtex->Format.wFormatTag, fmtex->Format.nChannels, fmtex->Format.nSamplesPerSec,
  949. fmtex->Format.nAvgBytesPerSec, fmtex->Format.nBlockAlign, fmtex->Format.wBitsPerSample,
  950. fmtex->Format.cbSize, fmtex->Samples.wReserved, fmtex->dwChannelMask,
  951. GuidPrinter{fmtex->SubFormat}.str());
  952. /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
  953. }
  954. else
  955. TRACE("{}:\n"
  956. " FormatTag = {:#06x}\n"
  957. " Channels = {}\n"
  958. " SamplesPerSec = {}\n"
  959. " AvgBytesPerSec = {}\n"
  960. " BlockAlign = {}\n"
  961. " BitsPerSample = {}\n"
  962. " Size = {}",
  963. msg, format->wFormatTag, format->nChannels, format->nSamplesPerSec,
  964. format->nAvgBytesPerSec, format->nBlockAlign, format->wBitsPerSample, format->cbSize);
  965. }
  966. /* Duplicates the first sample of each sample frame to the second sample, at
  967. * half volume. Essentially converting mono to stereo.
  968. */
  969. template<typename T>
  970. void DuplicateSamples(al::span<BYTE> insamples, size_t step)
  971. {
  972. auto samples = al::span{reinterpret_cast<T*>(insamples.data()), insamples.size()/sizeof(T)};
  973. if constexpr(std::is_floating_point_v<T>)
  974. {
  975. for(size_t i{0};i < samples.size();i+=step)
  976. {
  977. const auto s = samples[i] * T{0.5};
  978. samples[i+1] = samples[i] = s;
  979. }
  980. }
  981. else if constexpr(std::is_signed_v<T>)
  982. {
  983. for(size_t i{0};i < samples.size();i+=step)
  984. {
  985. const auto s = samples[i] / 2;
  986. samples[i+1] = samples[i] = T(s);
  987. }
  988. }
  989. else
  990. {
  991. using ST = std::make_signed_t<T>;
  992. static constexpr auto SignBit = T{1u << (sizeof(T)*8 - 1)};
  993. for(size_t i{0};i < samples.size();i+=step)
  994. {
  995. const auto s = static_cast<ST>(samples[i]^SignBit) / 2;
  996. samples[i+1] = samples[i] = T(s)^SignBit;
  997. }
  998. }
  999. }
  1000. void DuplicateSamples(al::span<BYTE> insamples, DevFmtType sampletype, size_t step)
  1001. {
  1002. switch(sampletype)
  1003. {
  1004. case DevFmtByte: return DuplicateSamples<char>(insamples, step);
  1005. case DevFmtUByte: return DuplicateSamples<unsigned char>(insamples, step);
  1006. case DevFmtShort: return DuplicateSamples<short>(insamples, step);
  1007. case DevFmtUShort: return DuplicateSamples<unsigned short>(insamples, step);
  1008. case DevFmtInt: return DuplicateSamples<int>(insamples, step);
  1009. case DevFmtUInt: return DuplicateSamples<unsigned int>(insamples, step);
  1010. case DevFmtFloat: return DuplicateSamples<float>(insamples, step);
  1011. }
  1012. }
  1013. struct WasapiPlayback final : public BackendBase {
  1014. explicit WasapiPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
  1015. ~WasapiPlayback() override;
  1016. struct PlainDevice {
  1017. ComPtr<IAudioClient> mClient{nullptr};
  1018. ComPtr<IAudioRenderClient> mRender{nullptr};
  1019. };
  1020. struct SpatialDevice {
  1021. ComPtr<ISpatialAudioClient> mClient{nullptr};
  1022. ComPtr<ISpatialAudioObjectRenderStream> mRender{nullptr};
  1023. AudioObjectType mStaticMask{};
  1024. };
  1025. void mixerProc(PlainDevice &audio);
  1026. void mixerProc(SpatialDevice &audio);
  1027. auto openProxy(const std::string_view name, DeviceHelper &helper, DeviceHandle &mmdev)
  1028. -> HRESULT;
  1029. void finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType);
  1030. auto initSpatial(DeviceHelper &helper, DeviceHandle &mmdev, SpatialDevice &audio) -> bool;
  1031. auto resetProxy(DeviceHelper &helper, DeviceHandle &mmdev,
  1032. std::variant<PlainDevice,SpatialDevice> &audiodev) -> HRESULT;
  1033. void proc_thread(std::string&& name);
  1034. void open(std::string_view name) override;
  1035. bool reset() override;
  1036. void start() override;
  1037. void stop() override;
  1038. ClockLatency getClockLatency() override;
  1039. std::thread mProcThread;
  1040. std::mutex mProcMutex;
  1041. std::condition_variable mProcCond;
  1042. HRESULT mProcResult{E_FAIL};
  1043. enum class ThreadState : uint8_t {
  1044. Initializing,
  1045. Waiting,
  1046. Playing,
  1047. Done
  1048. };
  1049. ThreadState mState{ThreadState::Initializing};
  1050. enum class ThreadAction : uint8_t {
  1051. Nothing,
  1052. Configure,
  1053. Play,
  1054. Quit
  1055. };
  1056. ThreadAction mAction{ThreadAction::Nothing};
  1057. static inline DWORD sAvIndex{};
  1058. HANDLE mNotifyEvent{nullptr};
  1059. UINT32 mOutBufferSize{}, mOutUpdateSize{};
  1060. std::vector<char> mResampleBuffer;
  1061. uint mBufferFilled{0};
  1062. SampleConverterPtr mResampler;
  1063. bool mMonoUpsample{false};
  1064. bool mExclusiveMode{false};
  1065. WAVEFORMATEXTENSIBLE mFormat{};
  1066. std::atomic<UINT32> mPadding{0u};
  1067. std::mutex mMutex;
  1068. std::atomic<bool> mKillNow{true};
  1069. };
  1070. WasapiPlayback::~WasapiPlayback()
  1071. {
  1072. if(mProcThread.joinable())
  1073. {
  1074. {
  1075. auto plock = std::lock_guard{mProcMutex};
  1076. mKillNow = true;
  1077. mAction = ThreadAction::Quit;
  1078. }
  1079. mProcCond.notify_all();
  1080. mProcThread.join();
  1081. }
  1082. if(mNotifyEvent != nullptr)
  1083. CloseHandle(mNotifyEvent);
  1084. mNotifyEvent = nullptr;
  1085. }
  1086. FORCE_ALIGN void WasapiPlayback::mixerProc(PlainDevice &audio)
  1087. {
  1088. class PriorityControl {
  1089. const int mOldPriority;
  1090. public:
  1091. PriorityControl() : mOldPriority{GetThreadPriority(GetCurrentThread())}
  1092. {
  1093. if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
  1094. ERR("Failed to set priority level for thread");
  1095. }
  1096. ~PriorityControl()
  1097. { SetThreadPriority(GetCurrentThread(), mOldPriority); }
  1098. };
  1099. auto prioctrl = PriorityControl{};
  1100. const uint frame_size{mFormat.Format.nChannels * mFormat.Format.wBitsPerSample / 8u};
  1101. const UINT32 buffer_len{mOutBufferSize};
  1102. const void *resbufferptr{};
  1103. assert(buffer_len > 0);
  1104. #ifdef AVRTAPI
  1105. /* TODO: "Audio" or "Pro Audio"? The suggestion is to use "Pro Audio" for
  1106. * device periods less than 10ms, and "Audio" for greater than or equal to
  1107. * 10ms.
  1108. */
  1109. auto taskname = (mOutUpdateSize < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
  1110. auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
  1111. #endif
  1112. auto prefilling = true;
  1113. mBufferFilled = 0;
  1114. while(!mKillNow.load(std::memory_order_relaxed))
  1115. {
  1116. /* For exclusive mode, assume buffer_len sample frames are writable.
  1117. * The first pass will be a prefill of the buffer, while subsequent
  1118. * passes will only occur after notify events.
  1119. * IAudioClient::GetCurrentPadding shouldn't be used with exclusive
  1120. * streams that use event notifications, according to the docs, we
  1121. * should just assume a buffer length is writable after notification.
  1122. */
  1123. auto written = UINT32{};
  1124. if(!mExclusiveMode)
  1125. {
  1126. if(auto hr = audio.mClient->GetCurrentPadding(&written); FAILED(hr))
  1127. {
  1128. ERR("Failed to get padding: {:#x}", as_unsigned(hr));
  1129. mDevice->handleDisconnect("Failed to retrieve buffer padding: {:#x}",
  1130. as_unsigned(hr));
  1131. break;
  1132. }
  1133. mPadding.store(written, std::memory_order_relaxed);
  1134. }
  1135. if(const auto len = uint{buffer_len - written})
  1136. {
  1137. auto buffer = LPBYTE{};
  1138. auto hr = audio.mRender->GetBuffer(len, &buffer);
  1139. if(SUCCEEDED(hr))
  1140. {
  1141. if(mResampler)
  1142. {
  1143. auto dlock = std::lock_guard{mMutex};
  1144. auto dst = al::span{buffer, size_t{len}*frame_size};
  1145. for(UINT32 done{0};done < len;)
  1146. {
  1147. if(mBufferFilled == 0)
  1148. {
  1149. mDevice->renderSamples(mResampleBuffer.data(), mDevice->mUpdateSize,
  1150. mFormat.Format.nChannels);
  1151. resbufferptr = mResampleBuffer.data();
  1152. mBufferFilled = mDevice->mUpdateSize;
  1153. }
  1154. const auto got = mResampler->convert(&resbufferptr, &mBufferFilled,
  1155. dst.data(), len-done);
  1156. dst = dst.subspan(size_t{got}*frame_size);
  1157. done += got;
  1158. }
  1159. mPadding.store(written + len, std::memory_order_relaxed);
  1160. }
  1161. else
  1162. {
  1163. auto dlock = std::lock_guard{mMutex};
  1164. mDevice->renderSamples(buffer, len, mFormat.Format.nChannels);
  1165. mPadding.store(written + len, std::memory_order_relaxed);
  1166. }
  1167. if(mMonoUpsample)
  1168. {
  1169. DuplicateSamples(al::span{buffer, size_t{len}*frame_size}, mDevice->FmtType,
  1170. mFormat.Format.nChannels);
  1171. }
  1172. hr = audio.mRender->ReleaseBuffer(len, 0);
  1173. }
  1174. if(FAILED(hr))
  1175. {
  1176. ERR("Failed to buffer data: {:#x}", as_unsigned(hr));
  1177. mDevice->handleDisconnect("Failed to send playback samples: {:#x}",
  1178. as_unsigned(hr));
  1179. break;
  1180. }
  1181. }
  1182. if(prefilling)
  1183. {
  1184. prefilling = false;
  1185. ResetEvent(mNotifyEvent);
  1186. if(auto hr = audio.mClient->Start(); FAILED(hr))
  1187. {
  1188. ERR("Failed to start audio client: {:#x}", as_unsigned(hr));
  1189. mDevice->handleDisconnect("Failed to start audio client: {:#x}",
  1190. as_unsigned(hr));
  1191. break;
  1192. }
  1193. }
  1194. if(DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)}; res != WAIT_OBJECT_0)
  1195. ERR("WaitForSingleObjectEx error: {:#x}", res);
  1196. }
  1197. mPadding.store(0u, std::memory_order_release);
  1198. audio.mClient->Stop();
  1199. }
  1200. FORCE_ALIGN void WasapiPlayback::mixerProc(SpatialDevice &audio)
  1201. {
  1202. class PriorityControl {
  1203. int mOldPriority;
  1204. public:
  1205. PriorityControl() : mOldPriority{GetThreadPriority(GetCurrentThread())}
  1206. {
  1207. if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
  1208. ERR("Failed to set priority level for thread");
  1209. }
  1210. ~PriorityControl()
  1211. { SetThreadPriority(GetCurrentThread(), mOldPriority); }
  1212. };
  1213. auto prioctrl = PriorityControl{};
  1214. #ifdef AVRTAPI
  1215. auto taskname = (mOutUpdateSize < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
  1216. auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
  1217. #endif
  1218. std::vector<ComPtr<ISpatialAudioObject>> channels;
  1219. std::vector<void*> buffers;
  1220. std::vector<void*> resbuffers;
  1221. std::vector<const void*> tmpbuffers;
  1222. /* TODO: Set mPadding appropriately. There doesn't seem to be a way to
  1223. * update it dynamically based on the stream, so a fixed size may be the
  1224. * best we can do.
  1225. */
  1226. mPadding.store(mOutBufferSize-mOutUpdateSize, std::memory_order_release);
  1227. mBufferFilled = 0;
  1228. auto firstupdate = true;
  1229. while(!mKillNow.load(std::memory_order_relaxed))
  1230. {
  1231. UINT32 dynamicCount{}, framesToDo{};
  1232. HRESULT hr{audio.mRender->BeginUpdatingAudioObjects(&dynamicCount, &framesToDo)};
  1233. if(SUCCEEDED(hr))
  1234. {
  1235. if(channels.empty()) UNLIKELY
  1236. {
  1237. auto flags = as_unsigned(al::to_underlying(audio.mStaticMask));
  1238. channels.reserve(as_unsigned(al::popcount(flags)));
  1239. while(flags)
  1240. {
  1241. auto id = decltype(flags){1} << al::countr_zero(flags);
  1242. flags &= ~id;
  1243. audio.mRender->ActivateSpatialAudioObject(static_cast<AudioObjectType>(id),
  1244. al::out_ptr(channels.emplace_back()));
  1245. }
  1246. buffers.resize(channels.size());
  1247. if(mResampler)
  1248. {
  1249. tmpbuffers.resize(buffers.size());
  1250. resbuffers.resize(buffers.size());
  1251. auto bufptr = mResampleBuffer.begin();
  1252. for(size_t i{0};i < tmpbuffers.size();++i)
  1253. {
  1254. resbuffers[i] = al::to_address(bufptr);
  1255. bufptr += ptrdiff_t(mDevice->mUpdateSize*sizeof(float));
  1256. }
  1257. }
  1258. }
  1259. /* We have to call to get each channel's buffer individually every
  1260. * update, unfortunately.
  1261. */
  1262. std::transform(channels.cbegin(), channels.cend(), buffers.begin(),
  1263. [](const ComPtr<ISpatialAudioObject> &obj) -> void*
  1264. {
  1265. auto buffer = LPBYTE{};
  1266. auto size = UINT32{};
  1267. obj->GetBuffer(&buffer, &size);
  1268. return buffer;
  1269. });
  1270. if(!mResampler)
  1271. mDevice->renderSamples(buffers, framesToDo);
  1272. else
  1273. {
  1274. std::lock_guard<std::mutex> dlock{mMutex};
  1275. for(UINT32 pos{0};pos < framesToDo;)
  1276. {
  1277. if(mBufferFilled == 0)
  1278. {
  1279. mDevice->renderSamples(resbuffers, mDevice->mUpdateSize);
  1280. std::copy(resbuffers.cbegin(), resbuffers.cend(), tmpbuffers.begin());
  1281. mBufferFilled = mDevice->mUpdateSize;
  1282. }
  1283. const uint got{mResampler->convertPlanar(tmpbuffers.data(), &mBufferFilled,
  1284. buffers.data(), framesToDo-pos)};
  1285. for(auto &buf : buffers)
  1286. buf = static_cast<float*>(buf) + got; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
  1287. pos += got;
  1288. }
  1289. }
  1290. hr = audio.mRender->EndUpdatingAudioObjects();
  1291. }
  1292. if(firstupdate)
  1293. {
  1294. firstupdate = false;
  1295. ResetEvent(mNotifyEvent);
  1296. hr = audio.mRender->Start();
  1297. if(FAILED(hr))
  1298. {
  1299. ERR("Failed to start spatial audio stream: {:#x}", as_unsigned(hr));
  1300. mDevice->handleDisconnect("Failed to start spatial audio stream: {:#x}",
  1301. as_unsigned(hr));
  1302. return;
  1303. }
  1304. }
  1305. if(DWORD res{WaitForSingleObjectEx(mNotifyEvent, 1000, FALSE)}; res != WAIT_OBJECT_0)
  1306. {
  1307. ERR("WaitForSingleObjectEx error: {:#x}", res);
  1308. hr = audio.mRender->Reset();
  1309. if(FAILED(hr))
  1310. {
  1311. ERR("ISpatialAudioObjectRenderStream::Reset failed: {:#x}", as_unsigned(hr));
  1312. mDevice->handleDisconnect("Device lost: {:#x}", as_unsigned(hr));
  1313. break;
  1314. }
  1315. firstupdate = true;
  1316. }
  1317. if(FAILED(hr))
  1318. ERR("Failed to update playback objects: {:#x}", as_unsigned(hr));
  1319. }
  1320. mPadding.store(0u, std::memory_order_release);
  1321. audio.mRender->Stop();
  1322. audio.mRender->Reset();
  1323. }
  1324. void WasapiPlayback::proc_thread(std::string&& name)
  1325. try {
  1326. auto com = ComWrapper{COINIT_MULTITHREADED};
  1327. if(!com)
  1328. {
  1329. const auto hr = as_unsigned(com.status());
  1330. ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: {:#x}", hr);
  1331. mDevice->handleDisconnect("COM init failed: {:#x}", hr);
  1332. auto plock = std::lock_guard{mProcMutex};
  1333. mProcResult = com.status();
  1334. mState = ThreadState::Done;
  1335. mProcCond.notify_all();
  1336. return;
  1337. }
  1338. if(!gInitDone.load(std::memory_order_relaxed))
  1339. {
  1340. auto devlock = DeviceListLock{gDeviceList};
  1341. gInitCV.wait(devlock, []() -> bool { return gInitDone; });
  1342. }
  1343. auto helper = DeviceHelper{};
  1344. if(HRESULT hr{helper.init()}; FAILED(hr))
  1345. {
  1346. mDevice->handleDisconnect("Helper init failed: {:#x}", as_unsigned(hr));
  1347. auto plock = std::lock_guard{mProcMutex};
  1348. mProcResult = hr;
  1349. mState = ThreadState::Done;
  1350. mProcCond.notify_all();
  1351. return;
  1352. }
  1353. althrd_setname(GetMixerThreadName());
  1354. auto mmdev = DeviceHandle{nullptr};
  1355. if(auto hr = openProxy(name, helper, mmdev); FAILED(hr))
  1356. {
  1357. auto plock = std::lock_guard{mProcMutex};
  1358. mProcResult = hr;
  1359. mState = ThreadState::Done;
  1360. mProcCond.notify_all();
  1361. return;
  1362. }
  1363. auto audiodev = std::variant<PlainDevice,SpatialDevice>{};
  1364. auto plock = std::unique_lock{mProcMutex};
  1365. mProcResult = S_OK;
  1366. while(mState != ThreadState::Done)
  1367. {
  1368. mAction = ThreadAction::Nothing;
  1369. mState = ThreadState::Waiting;
  1370. mProcCond.notify_all();
  1371. mProcCond.wait(plock, [this]() noexcept { return mAction != ThreadAction::Nothing; });
  1372. switch(mAction)
  1373. {
  1374. case ThreadAction::Nothing:
  1375. break;
  1376. case ThreadAction::Configure:
  1377. {
  1378. plock.unlock();
  1379. const auto hr = resetProxy(helper, mmdev, audiodev);
  1380. plock.lock();
  1381. mProcResult = hr;
  1382. }
  1383. break;
  1384. case ThreadAction::Play:
  1385. mKillNow.store(false, std::memory_order_release);
  1386. mAction = ThreadAction::Nothing;
  1387. mState = ThreadState::Playing;
  1388. mProcResult = S_OK;
  1389. plock.unlock();
  1390. mProcCond.notify_all();
  1391. std::visit([this](auto &audio) -> void { mixerProc(audio); }, audiodev);
  1392. plock.lock();
  1393. break;
  1394. case ThreadAction::Quit:
  1395. mAction = ThreadAction::Nothing;
  1396. mState = ThreadState::Done;
  1397. mProcCond.notify_all();
  1398. break;
  1399. }
  1400. }
  1401. }
  1402. catch(...) {
  1403. auto plock = std::lock_guard{mProcMutex};
  1404. mProcResult = E_FAIL;
  1405. mAction = ThreadAction::Nothing;
  1406. mState = ThreadState::Done;
  1407. mProcCond.notify_all();
  1408. }
  1409. void WasapiPlayback::open(std::string_view name)
  1410. {
  1411. mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
  1412. if(mNotifyEvent == nullptr)
  1413. {
  1414. ERR("Failed to create notify events: {}", GetLastError());
  1415. throw al::backend_exception{al::backend_error::DeviceError,
  1416. "Failed to create notify events"};
  1417. }
  1418. mProcThread = std::thread{&WasapiPlayback::proc_thread, this, std::string{name}};
  1419. auto plock = std::unique_lock{mProcMutex};
  1420. mProcCond.wait(plock, [this]() noexcept { return mState != ThreadState::Initializing; });
  1421. if(mProcResult == E_NOTFOUND)
  1422. throw al::backend_exception{al::backend_error::NoDevice, "Device \"{}\" not found", name};
  1423. if(FAILED(mProcResult) || mState == ThreadState::Done)
  1424. throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: {:#x}",
  1425. as_unsigned(mProcResult)};
  1426. }
  1427. auto WasapiPlayback::openProxy(const std::string_view name, DeviceHelper &helper,
  1428. DeviceHandle &mmdev) -> HRESULT
  1429. {
  1430. auto devname = std::string{};
  1431. auto devid = std::wstring{};
  1432. if(!name.empty())
  1433. {
  1434. auto devlock = DeviceListLock{gDeviceList};
  1435. auto list = al::span{devlock.getPlaybackList()};
  1436. auto iter = std::find_if(list.cbegin(), list.cend(),
  1437. [name](const DevMap &entry) -> bool
  1438. { return entry.name == name || al::case_compare(entry.endpoint_guid, name) == 0; });
  1439. if(iter == list.cend())
  1440. {
  1441. const std::wstring wname{utf8_to_wstr(name)};
  1442. iter = std::find_if(list.cbegin(), list.cend(),
  1443. [&wname](const DevMap &entry) -> bool
  1444. { return al::case_compare(entry.devid, wname) == 0; });
  1445. }
  1446. if(iter == list.cend())
  1447. {
  1448. WARN("Failed to find device name matching \"{}\"", name);
  1449. return E_NOTFOUND;
  1450. }
  1451. devname = iter->name;
  1452. devid = iter->devid;
  1453. }
  1454. if(HRESULT hr{helper.openDevice(devid, eRender, mmdev)}; FAILED(hr))
  1455. {
  1456. WARN("Failed to open device \"{}\": {:#x}", devname.empty()
  1457. ? "(default)"sv : std::string_view{devname}, as_unsigned(hr));
  1458. return hr;
  1459. }
  1460. if(!devname.empty())
  1461. mDeviceName = std::move(devname);
  1462. else
  1463. mDeviceName = GetDeviceNameAndGuid(mmdev).mName;
  1464. return S_OK;
  1465. }
  1466. void WasapiPlayback::finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType)
  1467. {
  1468. if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
  1469. mDevice->mSampleRate = uint(OutputType.Format.nSamplesPerSec);
  1470. else
  1471. mDevice->mSampleRate = std::min(mDevice->mSampleRate,
  1472. uint(OutputType.Format.nSamplesPerSec));
  1473. const uint32_t chancount{OutputType.Format.nChannels};
  1474. const DWORD chanmask{OutputType.dwChannelMask};
  1475. /* Don't update the channel format if the requested format fits what's
  1476. * supported.
  1477. */
  1478. bool chansok{false};
  1479. if(mDevice->Flags.test(ChannelsRequest))
  1480. {
  1481. /* When requesting a channel configuration, make sure it fits the
  1482. * mask's lsb (to ensure no gaps in the output channels). If there's no
  1483. * mask, assume the request fits with enough channels.
  1484. */
  1485. switch(mDevice->FmtChans)
  1486. {
  1487. case DevFmtMono:
  1488. chansok = (chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask));
  1489. if(!chansok && chancount >= 2 && (chanmask&StereoMask) == STEREO)
  1490. {
  1491. /* Mono rendering with stereo+ output is handled specially. */
  1492. chansok = true;
  1493. mMonoUpsample = true;
  1494. }
  1495. break;
  1496. case DevFmtStereo:
  1497. chansok = (chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask));
  1498. break;
  1499. case DevFmtQuad:
  1500. chansok = (chancount >= 4 && ((chanmask&QuadMask) == QUAD || !chanmask));
  1501. break;
  1502. case DevFmtX51:
  1503. chansok = (chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
  1504. || (chanmask&X51RearMask) == X5DOT1REAR || !chanmask));
  1505. break;
  1506. case DevFmtX61:
  1507. chansok = (chancount >= 7 && ((chanmask&X61Mask) == X6DOT1 || !chanmask));
  1508. break;
  1509. case DevFmtX71:
  1510. case DevFmtX3D71:
  1511. chansok = (chancount >= 8 && ((chanmask&X71Mask) == X7DOT1 || !chanmask));
  1512. break;
  1513. case DevFmtX714:
  1514. chansok = (chancount >= 12 && ((chanmask&X714Mask) == X7DOT1DOT4 || !chanmask));
  1515. case DevFmtX7144:
  1516. case DevFmtAmbi3D:
  1517. break;
  1518. }
  1519. }
  1520. if(!chansok)
  1521. {
  1522. if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
  1523. mDevice->FmtChans = DevFmtX714;
  1524. else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
  1525. mDevice->FmtChans = DevFmtX71;
  1526. else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
  1527. mDevice->FmtChans = DevFmtX61;
  1528. else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
  1529. || (chanmask&X51RearMask) == X5DOT1REAR))
  1530. mDevice->FmtChans = DevFmtX51;
  1531. else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
  1532. mDevice->FmtChans = DevFmtQuad;
  1533. else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
  1534. mDevice->FmtChans = DevFmtStereo;
  1535. else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
  1536. mDevice->FmtChans = DevFmtMono;
  1537. else
  1538. {
  1539. ERR("Unhandled extensible channels: {} -- {:#08x}", OutputType.Format.nChannels,
  1540. OutputType.dwChannelMask);
  1541. mDevice->FmtChans = DevFmtStereo;
  1542. OutputType.Format.nChannels = 2;
  1543. OutputType.dwChannelMask = STEREO;
  1544. }
  1545. }
  1546. if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
  1547. {
  1548. if(OutputType.Format.wBitsPerSample == 8)
  1549. mDevice->FmtType = DevFmtUByte;
  1550. else if(OutputType.Format.wBitsPerSample == 16)
  1551. mDevice->FmtType = DevFmtShort;
  1552. else if(OutputType.Format.wBitsPerSample == 32)
  1553. mDevice->FmtType = DevFmtInt;
  1554. else
  1555. {
  1556. mDevice->FmtType = DevFmtShort;
  1557. OutputType.Format.wBitsPerSample = 16;
  1558. }
  1559. }
  1560. else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
  1561. {
  1562. mDevice->FmtType = DevFmtFloat;
  1563. OutputType.Format.wBitsPerSample = 32;
  1564. }
  1565. else
  1566. {
  1567. ERR("Unhandled format sub-type: {}", GuidPrinter{OutputType.SubFormat}.str());
  1568. mDevice->FmtType = DevFmtShort;
  1569. if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
  1570. OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
  1571. OutputType.Format.wBitsPerSample = 16;
  1572. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1573. }
  1574. /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
  1575. OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
  1576. }
  1577. auto WasapiPlayback::initSpatial(DeviceHelper &helper, DeviceHandle &mmdev, SpatialDevice &audio)
  1578. -> bool
  1579. {
  1580. HRESULT hr{helper.activateAudioClient(mmdev, __uuidof(ISpatialAudioClient),
  1581. al::out_ptr(audio.mClient))};
  1582. if(FAILED(hr))
  1583. {
  1584. ERR("Failed to activate spatial audio client: {:#x}", as_unsigned(hr));
  1585. return false;
  1586. }
  1587. ComPtr<IAudioFormatEnumerator> fmtenum;
  1588. hr = audio.mClient->GetSupportedAudioObjectFormatEnumerator(al::out_ptr(fmtenum));
  1589. if(FAILED(hr))
  1590. {
  1591. ERR("Failed to get format enumerator: {:#x}", as_unsigned(hr));
  1592. return false;
  1593. }
  1594. UINT32 fmtcount{};
  1595. hr = fmtenum->GetCount(&fmtcount);
  1596. if(FAILED(hr) || fmtcount == 0)
  1597. {
  1598. ERR("Failed to get format count: {:#08x}", as_unsigned(hr));
  1599. return false;
  1600. }
  1601. WAVEFORMATEX *preferredFormat{};
  1602. hr = fmtenum->GetFormat(0, &preferredFormat);
  1603. if(FAILED(hr))
  1604. {
  1605. ERR("Failed to get preferred format: {:#x}", as_unsigned(hr));
  1606. return false;
  1607. }
  1608. TraceFormat("Preferred mix format", preferredFormat);
  1609. UINT32 maxFrames{};
  1610. hr = audio.mClient->GetMaxFrameCount(preferredFormat, &maxFrames);
  1611. if(FAILED(hr))
  1612. ERR("Failed to get max frames: {:#x}", as_unsigned(hr));
  1613. else
  1614. TRACE("Max sample frames: {}", maxFrames);
  1615. for(UINT32 i{1};i < fmtcount;++i)
  1616. {
  1617. WAVEFORMATEX *otherFormat{};
  1618. hr = fmtenum->GetFormat(i, &otherFormat);
  1619. if(FAILED(hr))
  1620. ERR("Failed to get format {}: {:#x}", i+1, as_unsigned(hr));
  1621. else
  1622. {
  1623. TraceFormat("Other mix format", otherFormat);
  1624. UINT32 otherMaxFrames{};
  1625. hr = audio.mClient->GetMaxFrameCount(otherFormat, &otherMaxFrames);
  1626. if(FAILED(hr))
  1627. ERR("Failed to get max frames: {:#x}", as_unsigned(hr));
  1628. else
  1629. TRACE("Max sample frames: {}", otherMaxFrames);
  1630. }
  1631. }
  1632. WAVEFORMATEXTENSIBLE OutputType;
  1633. if(!MakeExtensible(&OutputType, preferredFormat))
  1634. return false;
  1635. /* This seems to be the format of each "object", which should be mono. */
  1636. if(!(OutputType.Format.nChannels == 1
  1637. && (OutputType.dwChannelMask == MONO || !OutputType.dwChannelMask)))
  1638. ERR("Unhandled channel config: {} -- {:#08x}", OutputType.Format.nChannels,
  1639. OutputType.dwChannelMask);
  1640. /* Force 32-bit float. This is currently required for planar output. */
  1641. if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE
  1642. && OutputType.Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT)
  1643. {
  1644. OutputType.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
  1645. OutputType.Format.cbSize = 0;
  1646. }
  1647. if(OutputType.Format.wBitsPerSample != 32)
  1648. {
  1649. OutputType.Format.nAvgBytesPerSec = OutputType.Format.nAvgBytesPerSec * 32u
  1650. / OutputType.Format.wBitsPerSample;
  1651. OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nBlockAlign * 32
  1652. / OutputType.Format.wBitsPerSample);
  1653. OutputType.Format.wBitsPerSample = 32;
  1654. }
  1655. /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
  1656. OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
  1657. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  1658. /* Match the output rate if not requesting anything specific. */
  1659. if(!mDevice->Flags.test(FrequencyRequest))
  1660. mDevice->mSampleRate = OutputType.Format.nSamplesPerSec;
  1661. auto getTypeMask = [](DevFmtChannels chans) noexcept
  1662. {
  1663. switch(chans)
  1664. {
  1665. case DevFmtMono: return ChannelMask_Mono;
  1666. case DevFmtStereo: return ChannelMask_Stereo;
  1667. case DevFmtQuad: return ChannelMask_Quad;
  1668. case DevFmtX51: return ChannelMask_X51;
  1669. case DevFmtX61: return ChannelMask_X61;
  1670. case DevFmtX3D71: [[fallthrough]];
  1671. case DevFmtX71: return ChannelMask_X71;
  1672. case DevFmtX714: return ChannelMask_X714;
  1673. case DevFmtX7144: return ChannelMask_X7144;
  1674. case DevFmtAmbi3D:
  1675. break;
  1676. }
  1677. return ChannelMask_Stereo;
  1678. };
  1679. SpatialAudioObjectRenderStreamActivationParams streamParams{};
  1680. streamParams.ObjectFormat = &OutputType.Format;
  1681. streamParams.StaticObjectTypeMask = getTypeMask(mDevice->FmtChans);
  1682. streamParams.Category = AudioCategory_Media;
  1683. streamParams.EventHandle = mNotifyEvent;
  1684. PropVariant paramProp{};
  1685. paramProp.setBlob({reinterpret_cast<BYTE*>(&streamParams), sizeof(streamParams)});
  1686. hr = audio.mClient->ActivateSpatialAudioStream(paramProp.get(),
  1687. __uuidof(ISpatialAudioObjectRenderStream), al::out_ptr(audio.mRender));
  1688. if(FAILED(hr))
  1689. {
  1690. ERR("Failed to activate spatial audio stream: {:#x}", as_unsigned(hr));
  1691. return false;
  1692. }
  1693. audio.mStaticMask = streamParams.StaticObjectTypeMask;
  1694. mFormat = OutputType;
  1695. mDevice->FmtType = DevFmtFloat;
  1696. mDevice->Flags.reset(DirectEar).set(Virtualization);
  1697. if(streamParams.StaticObjectTypeMask == ChannelMask_Stereo)
  1698. mDevice->FmtChans = DevFmtStereo;
  1699. if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
  1700. mDevice->mSampleRate = uint(OutputType.Format.nSamplesPerSec);
  1701. else
  1702. mDevice->mSampleRate = std::min(mDevice->mSampleRate,
  1703. uint(OutputType.Format.nSamplesPerSec));
  1704. setDefaultWFXChannelOrder();
  1705. /* TODO: ISpatialAudioClient::GetMaxFrameCount returns the maximum number
  1706. * of frames per processing pass, which is ostensibly the period size. This
  1707. * should be checked on a real Windows system.
  1708. *
  1709. * In either case, this won't get the buffer size of the
  1710. * ISpatialAudioObjectRenderStream, so we only assume there's two periods.
  1711. */
  1712. mOutUpdateSize = maxFrames;
  1713. mOutBufferSize = mOutUpdateSize*2;
  1714. mDevice->mUpdateSize = static_cast<uint>((uint64_t{mOutUpdateSize}*mDevice->mSampleRate
  1715. + (mFormat.Format.nSamplesPerSec-1)) / mFormat.Format.nSamplesPerSec);
  1716. mDevice->mBufferSize = mDevice->mUpdateSize*2;
  1717. mResampler = nullptr;
  1718. mResampleBuffer.clear();
  1719. mResampleBuffer.shrink_to_fit();
  1720. mBufferFilled = 0;
  1721. if(mDevice->mSampleRate != mFormat.Format.nSamplesPerSec)
  1722. {
  1723. const auto flags = as_unsigned(al::to_underlying(streamParams.StaticObjectTypeMask));
  1724. const auto channelCount = as_unsigned(al::popcount(flags));
  1725. mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType, channelCount,
  1726. mDevice->mSampleRate, mFormat.Format.nSamplesPerSec, Resampler::FastBSinc24);
  1727. mResampleBuffer.resize(size_t{mDevice->mUpdateSize} * channelCount *
  1728. mFormat.Format.wBitsPerSample / 8);
  1729. TRACE("Created converter for {}/{} format, dst: {}hz ({}), src: {}hz ({})",
  1730. DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
  1731. mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->mSampleRate,
  1732. mDevice->mUpdateSize);
  1733. }
  1734. return true;
  1735. }
  1736. bool WasapiPlayback::reset()
  1737. {
  1738. auto plock = std::unique_lock{mProcMutex};
  1739. if(mState != ThreadState::Waiting)
  1740. throw al::backend_exception{al::backend_error::DeviceError, "Invalid state: {}",
  1741. unsigned{al::to_underlying(mState)}};
  1742. mAction = ThreadAction::Configure;
  1743. mProcCond.notify_all();
  1744. mProcCond.wait(plock, [this]() noexcept { return mAction != ThreadAction::Configure; });
  1745. if(FAILED(mProcResult) || mState != ThreadState::Waiting)
  1746. throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: {:#x}",
  1747. as_unsigned(mProcResult)};
  1748. return true;
  1749. }
  1750. auto WasapiPlayback::resetProxy(DeviceHelper &helper, DeviceHandle &mmdev,
  1751. std::variant<PlainDevice,SpatialDevice> &audiodev) -> HRESULT
  1752. {
  1753. if(GetConfigValueBool(mDevice->mDeviceName, "wasapi", "spatial-api", false))
  1754. {
  1755. if(initSpatial(helper, mmdev, audiodev.emplace<SpatialDevice>()))
  1756. return S_OK;
  1757. }
  1758. mDevice->Flags.reset(Virtualization);
  1759. mMonoUpsample = false;
  1760. mExclusiveMode = false;
  1761. auto &audio = audiodev.emplace<PlainDevice>();
  1762. auto hr = helper.activateAudioClient(mmdev, __uuidof(IAudioClient),
  1763. al::out_ptr(audio.mClient));
  1764. if(FAILED(hr))
  1765. {
  1766. ERR("Failed to reactivate audio client: {:#x}", as_unsigned(hr));
  1767. return hr;
  1768. }
  1769. auto wfx = unique_coptr<WAVEFORMATEX>{};
  1770. hr = audio.mClient->GetMixFormat(al::out_ptr(wfx));
  1771. if(FAILED(hr))
  1772. {
  1773. ERR("Failed to get mix format: {:#x}", as_unsigned(hr));
  1774. return hr;
  1775. }
  1776. TraceFormat("Device mix format", wfx.get());
  1777. auto OutputType = WAVEFORMATEXTENSIBLE{};
  1778. if(!MakeExtensible(&OutputType, wfx.get()))
  1779. return E_FAIL;
  1780. wfx = nullptr;
  1781. /* Get the buffer and update sizes as a ReferenceTime before potentially
  1782. * altering the sample rate.
  1783. */
  1784. const auto buf_time = ReferenceTime{seconds{mDevice->mBufferSize}} / mDevice->mSampleRate;
  1785. const auto per_time = ReferenceTime{seconds{mDevice->mUpdateSize}} / mDevice->mSampleRate;
  1786. /* Update the mDevice format for non-requested properties. */
  1787. bool isRear51{false};
  1788. if(!mDevice->Flags.test(FrequencyRequest))
  1789. mDevice->mSampleRate = OutputType.Format.nSamplesPerSec;
  1790. if(!mDevice->Flags.test(ChannelsRequest))
  1791. {
  1792. /* If not requesting a channel configuration, auto-select given what
  1793. * fits the mask's lsb (to ensure no gaps in the output channels). If
  1794. * there's no mask, we can only assume mono or stereo.
  1795. */
  1796. const uint32_t chancount{OutputType.Format.nChannels};
  1797. const DWORD chanmask{OutputType.dwChannelMask};
  1798. if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
  1799. mDevice->FmtChans = DevFmtX714;
  1800. else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
  1801. mDevice->FmtChans = DevFmtX71;
  1802. else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
  1803. mDevice->FmtChans = DevFmtX61;
  1804. else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1)
  1805. mDevice->FmtChans = DevFmtX51;
  1806. else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR)
  1807. {
  1808. mDevice->FmtChans = DevFmtX51;
  1809. isRear51 = true;
  1810. }
  1811. else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
  1812. mDevice->FmtChans = DevFmtQuad;
  1813. else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
  1814. mDevice->FmtChans = DevFmtStereo;
  1815. else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
  1816. mDevice->FmtChans = DevFmtMono;
  1817. else
  1818. ERR("Unhandled channel config: {} -- {:#08x}", chancount, chanmask);
  1819. }
  1820. else
  1821. {
  1822. const uint32_t chancount{OutputType.Format.nChannels};
  1823. const DWORD chanmask{OutputType.dwChannelMask};
  1824. isRear51 = (chancount == 6 && (chanmask&X51RearMask) == X5DOT1REAR);
  1825. }
  1826. /* Request a format matching the mDevice. */
  1827. OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  1828. switch(mDevice->FmtChans)
  1829. {
  1830. case DevFmtMono:
  1831. OutputType.Format.nChannels = 1;
  1832. OutputType.dwChannelMask = MONO;
  1833. break;
  1834. case DevFmtAmbi3D:
  1835. mDevice->FmtChans = DevFmtStereo;
  1836. [[fallthrough]];
  1837. case DevFmtStereo:
  1838. OutputType.Format.nChannels = 2;
  1839. OutputType.dwChannelMask = STEREO;
  1840. break;
  1841. case DevFmtQuad:
  1842. OutputType.Format.nChannels = 4;
  1843. OutputType.dwChannelMask = QUAD;
  1844. break;
  1845. case DevFmtX51:
  1846. OutputType.Format.nChannels = 6;
  1847. OutputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
  1848. break;
  1849. case DevFmtX61:
  1850. OutputType.Format.nChannels = 7;
  1851. OutputType.dwChannelMask = X6DOT1;
  1852. break;
  1853. case DevFmtX71:
  1854. case DevFmtX3D71:
  1855. OutputType.Format.nChannels = 8;
  1856. OutputType.dwChannelMask = X7DOT1;
  1857. break;
  1858. case DevFmtX7144:
  1859. mDevice->FmtChans = DevFmtX714;
  1860. [[fallthrough]];
  1861. case DevFmtX714:
  1862. OutputType.Format.nChannels = 12;
  1863. OutputType.dwChannelMask = X7DOT1DOT4;
  1864. break;
  1865. }
  1866. switch(mDevice->FmtType)
  1867. {
  1868. case DevFmtByte:
  1869. mDevice->FmtType = DevFmtUByte;
  1870. [[fallthrough]];
  1871. case DevFmtUByte:
  1872. OutputType.Format.wBitsPerSample = 8;
  1873. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1874. break;
  1875. case DevFmtUShort:
  1876. mDevice->FmtType = DevFmtShort;
  1877. [[fallthrough]];
  1878. case DevFmtShort:
  1879. OutputType.Format.wBitsPerSample = 16;
  1880. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1881. break;
  1882. case DevFmtUInt:
  1883. mDevice->FmtType = DevFmtInt;
  1884. [[fallthrough]];
  1885. case DevFmtInt:
  1886. OutputType.Format.wBitsPerSample = 32;
  1887. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1888. break;
  1889. case DevFmtFloat:
  1890. OutputType.Format.wBitsPerSample = 32;
  1891. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  1892. break;
  1893. }
  1894. /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
  1895. OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
  1896. OutputType.Format.nSamplesPerSec = mDevice->mSampleRate;
  1897. OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels
  1898. * OutputType.Format.wBitsPerSample / 8);
  1899. OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec
  1900. * OutputType.Format.nBlockAlign;
  1901. const auto sharemode =
  1902. GetConfigValueBool(mDevice->mDeviceName, "wasapi", "exclusive-mode", false)
  1903. ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED;
  1904. mExclusiveMode = (sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE);
  1905. TraceFormat("Requesting playback format", &OutputType.Format);
  1906. hr = audio.mClient->IsFormatSupported(sharemode, &OutputType.Format, al::out_ptr(wfx));
  1907. if(FAILED(hr))
  1908. {
  1909. if(sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE)
  1910. {
  1911. /* For exclusive mode, IAudioClient::IsFormatSupported won't give
  1912. * back a supported format. However, a common failure is an
  1913. * unsupported sample type, so try a fallback to 16-bit int.
  1914. */
  1915. if(hr == AUDCLNT_E_UNSUPPORTED_FORMAT && mDevice->FmtType != DevFmtShort)
  1916. {
  1917. mDevice->FmtType = DevFmtShort;
  1918. OutputType.Format.wBitsPerSample = 16;
  1919. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1920. /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
  1921. OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
  1922. OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels
  1923. * OutputType.Format.wBitsPerSample / 8);
  1924. OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec
  1925. * OutputType.Format.nBlockAlign;
  1926. hr = audio.mClient->IsFormatSupported(sharemode, &OutputType.Format,
  1927. al::out_ptr(wfx));
  1928. }
  1929. }
  1930. else
  1931. {
  1932. WARN("Failed to check format support: {:#x}", as_unsigned(hr));
  1933. hr = audio.mClient->GetMixFormat(al::out_ptr(wfx));
  1934. }
  1935. }
  1936. if(FAILED(hr))
  1937. {
  1938. ERR("Failed to find a supported format: {:#x}", as_unsigned(hr));
  1939. return hr;
  1940. }
  1941. if(wfx)
  1942. {
  1943. TraceFormat("Got playback format", wfx.get());
  1944. if(!MakeExtensible(&OutputType, wfx.get()))
  1945. return E_FAIL;
  1946. wfx = nullptr;
  1947. finalizeFormat(OutputType);
  1948. }
  1949. mFormat = OutputType;
  1950. #if !ALSOFT_UWP
  1951. const EndpointFormFactor formfactor{GetDeviceFormfactor(mmdev.get())};
  1952. mDevice->Flags.set(DirectEar, (formfactor == Headphones || formfactor == Headset));
  1953. #else
  1954. mDevice->Flags.set(DirectEar, false);
  1955. #endif
  1956. setDefaultWFXChannelOrder();
  1957. if(sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE)
  1958. {
  1959. auto period_time = per_time;
  1960. auto min_period = ReferenceTime{};
  1961. hr = audio.mClient->GetDevicePeriod(nullptr,
  1962. &reinterpret_cast<REFERENCE_TIME&>(min_period));
  1963. if(FAILED(hr))
  1964. ERR("Failed to get minimum period time: {:#x}", as_unsigned(hr));
  1965. else if(min_period > period_time)
  1966. {
  1967. period_time = min_period;
  1968. WARN("Clamping to minimum period time, {}", nanoseconds{min_period});
  1969. }
  1970. hr = audio.mClient->Initialize(sharemode, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  1971. period_time.count(), period_time.count(), &OutputType.Format, nullptr);
  1972. if(hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
  1973. {
  1974. auto newsize = UINT32{};
  1975. hr = audio.mClient->GetBufferSize(&newsize);
  1976. if(SUCCEEDED(hr))
  1977. {
  1978. period_time = ReferenceTime{seconds{newsize}}
  1979. / OutputType.Format.nSamplesPerSec;
  1980. WARN("Adjusting to supported period time, {}", nanoseconds{period_time});
  1981. audio.mClient = nullptr;
  1982. hr = helper.activateAudioClient(mmdev, __uuidof(IAudioClient),
  1983. al::out_ptr(audio.mClient));
  1984. if(FAILED(hr))
  1985. {
  1986. ERR("Failed to reactivate audio client: {:#x}", as_unsigned(hr));
  1987. return hr;
  1988. }
  1989. hr = audio.mClient->Initialize(sharemode, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  1990. period_time.count(), period_time.count(), &OutputType.Format, nullptr);
  1991. }
  1992. }
  1993. }
  1994. else
  1995. hr = audio.mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  1996. buf_time.count(), 0, &OutputType.Format, nullptr);
  1997. if(FAILED(hr))
  1998. {
  1999. ERR("Failed to initialize audio client: {:#x}", as_unsigned(hr));
  2000. return hr;
  2001. }
  2002. auto buffer_len = UINT32{};
  2003. auto period_time = ReferenceTime{};
  2004. hr = audio.mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(period_time), nullptr);
  2005. if(SUCCEEDED(hr))
  2006. hr = audio.mClient->GetBufferSize(&buffer_len);
  2007. if(FAILED(hr))
  2008. {
  2009. ERR("Failed to get audio buffer info: {:#x}", as_unsigned(hr));
  2010. return hr;
  2011. }
  2012. hr = audio.mClient->SetEventHandle(mNotifyEvent);
  2013. if(FAILED(hr))
  2014. {
  2015. ERR("Failed to set event handle: {:#x}", as_unsigned(hr));
  2016. return hr;
  2017. }
  2018. hr = audio.mClient->GetService(__uuidof(IAudioRenderClient), al::out_ptr(audio.mRender));
  2019. if(FAILED(hr))
  2020. {
  2021. ERR("Failed to get IAudioRenderClient: {:#x}", as_unsigned(hr));
  2022. return hr;
  2023. }
  2024. mOutBufferSize = buffer_len;
  2025. if(sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE)
  2026. {
  2027. /* For exclusive mode, the buffer size is the update size, and there's
  2028. * implicitly two update periods on the device.
  2029. */
  2030. mOutUpdateSize = buffer_len;
  2031. mDevice->mUpdateSize = static_cast<uint>(uint64_t{buffer_len} * mDevice->mSampleRate /
  2032. mFormat.Format.nSamplesPerSec);
  2033. mDevice->mBufferSize = mDevice->mUpdateSize * 2;
  2034. }
  2035. else
  2036. {
  2037. mOutUpdateSize = RefTime2Samples(period_time, mFormat.Format.nSamplesPerSec);
  2038. mDevice->mBufferSize = static_cast<uint>(uint64_t{buffer_len} * mDevice->mSampleRate /
  2039. mFormat.Format.nSamplesPerSec);
  2040. mDevice->mUpdateSize = std::min(RefTime2Samples(period_time, mDevice->mSampleRate),
  2041. mDevice->mBufferSize/2u);
  2042. }
  2043. mResampler = nullptr;
  2044. mResampleBuffer.clear();
  2045. mResampleBuffer.shrink_to_fit();
  2046. mBufferFilled = 0;
  2047. if(mDevice->mSampleRate != mFormat.Format.nSamplesPerSec)
  2048. {
  2049. mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType,
  2050. mFormat.Format.nChannels, mDevice->mSampleRate, mFormat.Format.nSamplesPerSec,
  2051. Resampler::FastBSinc24);
  2052. mResampleBuffer.resize(size_t{mDevice->mUpdateSize} * mFormat.Format.nChannels *
  2053. mFormat.Format.wBitsPerSample / 8);
  2054. TRACE("Created converter for {}/{} format, dst: {}hz ({}), src: {}hz ({})",
  2055. DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
  2056. mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->mSampleRate,
  2057. mDevice->mUpdateSize);
  2058. }
  2059. return hr;
  2060. }
  2061. void WasapiPlayback::start()
  2062. {
  2063. auto plock = std::unique_lock{mProcMutex};
  2064. if(mState != ThreadState::Waiting)
  2065. throw al::backend_exception{al::backend_error::DeviceError, "Invalid state: {}",
  2066. unsigned{al::to_underlying(mState)}};
  2067. mAction = ThreadAction::Play;
  2068. mProcCond.notify_all();
  2069. mProcCond.wait(plock, [this]() noexcept { return mAction != ThreadAction::Play; });
  2070. if(FAILED(mProcResult) || mState != ThreadState::Playing)
  2071. throw al::backend_exception{al::backend_error::DeviceError, "Device playback failed: {:#x}",
  2072. as_unsigned(mProcResult)};
  2073. }
  2074. void WasapiPlayback::stop()
  2075. {
  2076. auto plock = std::unique_lock{mProcMutex};
  2077. if(mState == ThreadState::Playing)
  2078. {
  2079. mKillNow = true;
  2080. mProcCond.wait(plock, [this]() noexcept { return mState != ThreadState::Playing; });
  2081. }
  2082. }
  2083. ClockLatency WasapiPlayback::getClockLatency()
  2084. {
  2085. std::lock_guard<std::mutex> dlock{mMutex};
  2086. ClockLatency ret{};
  2087. ret.ClockTime = mDevice->getClockTime();
  2088. ret.Latency = seconds{mPadding.load(std::memory_order_relaxed)};
  2089. ret.Latency /= mFormat.Format.nSamplesPerSec;
  2090. if(mResampler)
  2091. {
  2092. auto extra = mResampler->currentInputDelay();
  2093. ret.Latency += std::chrono::duration_cast<nanoseconds>(extra) / mDevice->mSampleRate;
  2094. ret.Latency += nanoseconds{seconds{mBufferFilled}} / mDevice->mSampleRate;
  2095. }
  2096. return ret;
  2097. }
  2098. struct WasapiCapture final : public BackendBase {
  2099. explicit WasapiCapture(DeviceBase *device) noexcept : BackendBase{device} { }
  2100. ~WasapiCapture() override;
  2101. void recordProc(IAudioClient *client, IAudioCaptureClient *capture);
  2102. void proc_thread(std::string&& name);
  2103. auto openProxy(const std::string_view name, DeviceHelper &helper, DeviceHandle &mmdev)
  2104. -> HRESULT;
  2105. auto resetProxy(DeviceHelper &helper, DeviceHandle &mmdev, ComPtr<IAudioClient> &client,
  2106. ComPtr<IAudioCaptureClient> &capture) -> HRESULT;
  2107. void open(std::string_view name) override;
  2108. void start() override;
  2109. void stop() override;
  2110. void captureSamples(std::byte *buffer, uint samples) override;
  2111. uint availableSamples() override;
  2112. std::thread mProcThread;
  2113. std::mutex mProcMutex;
  2114. std::condition_variable mProcCond;
  2115. HRESULT mProcResult{E_FAIL};
  2116. enum class ThreadState : uint8_t {
  2117. Initializing,
  2118. Waiting,
  2119. Recording,
  2120. Done
  2121. };
  2122. ThreadState mState{ThreadState::Initializing};
  2123. enum class ThreadAction : uint8_t {
  2124. Nothing,
  2125. Record,
  2126. Quit
  2127. };
  2128. ThreadAction mAction{ThreadAction::Nothing};
  2129. HANDLE mNotifyEvent{nullptr};
  2130. ChannelConverter mChannelConv{};
  2131. SampleConverterPtr mSampleConv;
  2132. RingBufferPtr mRing;
  2133. std::atomic<bool> mKillNow{true};
  2134. std::thread mThread;
  2135. };
  2136. WasapiCapture::~WasapiCapture()
  2137. {
  2138. if(mProcThread.joinable())
  2139. {
  2140. {
  2141. auto plock = std::lock_guard{mProcMutex};
  2142. mKillNow = true;
  2143. mAction = ThreadAction::Quit;
  2144. }
  2145. mProcCond.notify_all();
  2146. mProcThread.join();
  2147. }
  2148. if(mNotifyEvent != nullptr)
  2149. CloseHandle(mNotifyEvent);
  2150. mNotifyEvent = nullptr;
  2151. }
  2152. FORCE_ALIGN void WasapiCapture::recordProc(IAudioClient *client, IAudioCaptureClient *capture)
  2153. {
  2154. ResetEvent(mNotifyEvent);
  2155. if(HRESULT hr{client->Start()}; FAILED(hr))
  2156. {
  2157. ERR("Failed to start audio client: {:#x}", as_unsigned(hr));
  2158. mDevice->handleDisconnect("Failed to start audio client: {:#x}", as_unsigned(hr));
  2159. return;
  2160. }
  2161. std::vector<float> samples;
  2162. while(!mKillNow.load(std::memory_order_relaxed))
  2163. {
  2164. auto avail = UINT32{};
  2165. auto hr = capture->GetNextPacketSize(&avail);
  2166. if(FAILED(hr))
  2167. ERR("Failed to get next packet size: {:#x}", as_unsigned(hr));
  2168. else if(avail > 0)
  2169. {
  2170. auto numsamples = UINT32{};
  2171. auto flags = DWORD{};
  2172. BYTE *rdata{};
  2173. hr = capture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
  2174. if(FAILED(hr))
  2175. ERR("Failed to get capture buffer: {:#x}", as_unsigned(hr));
  2176. else
  2177. {
  2178. if(mChannelConv.is_active())
  2179. {
  2180. samples.resize(numsamples*2_uz);
  2181. mChannelConv.convert(rdata, samples.data(), numsamples);
  2182. rdata = reinterpret_cast<BYTE*>(samples.data());
  2183. }
  2184. auto data = mRing->getWriteVector();
  2185. size_t dstframes;
  2186. if(mSampleConv)
  2187. {
  2188. static constexpr auto lenlimit = size_t{std::numeric_limits<int>::max()};
  2189. const void *srcdata{rdata};
  2190. uint srcframes{numsamples};
  2191. dstframes = mSampleConv->convert(&srcdata, &srcframes, data[0].buf,
  2192. static_cast<uint>(std::min(data[0].len, lenlimit)));
  2193. if(srcframes > 0 && dstframes == data[0].len && data[1].len > 0)
  2194. {
  2195. /* If some source samples remain, all of the first dest
  2196. * block was filled, and there's space in the second
  2197. * dest block, do another run for the second block.
  2198. */
  2199. dstframes += mSampleConv->convert(&srcdata, &srcframes, data[1].buf,
  2200. static_cast<uint>(std::min(data[1].len, lenlimit)));
  2201. }
  2202. }
  2203. else
  2204. {
  2205. const uint framesize{mDevice->frameSizeFromFmt()};
  2206. auto dst = al::span{rdata, size_t{numsamples}*framesize};
  2207. size_t len1{std::min(data[0].len, size_t{numsamples})};
  2208. size_t len2{std::min(data[1].len, numsamples-len1)};
  2209. memcpy(data[0].buf, dst.data(), len1*framesize);
  2210. if(len2 > 0)
  2211. {
  2212. dst = dst.subspan(len1*framesize);
  2213. memcpy(data[1].buf, dst.data(), len2*framesize);
  2214. }
  2215. dstframes = len1 + len2;
  2216. }
  2217. mRing->writeAdvance(dstframes);
  2218. hr = capture->ReleaseBuffer(numsamples);
  2219. if(FAILED(hr)) ERR("Failed to release capture buffer: {:#x}", as_unsigned(hr));
  2220. }
  2221. }
  2222. if(FAILED(hr))
  2223. {
  2224. mDevice->handleDisconnect("Failed to capture samples: {:#x}", as_unsigned(hr));
  2225. break;
  2226. }
  2227. if(DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)}; res != WAIT_OBJECT_0)
  2228. ERR("WaitForSingleObjectEx error: {:#x}", res);
  2229. }
  2230. client->Stop();
  2231. client->Reset();
  2232. }
  2233. void WasapiCapture::proc_thread(std::string&& name)
  2234. try {
  2235. auto com = ComWrapper{COINIT_MULTITHREADED};
  2236. if(!com)
  2237. {
  2238. const auto hr = as_unsigned(com.status());
  2239. ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: {:#x}", hr);
  2240. mDevice->handleDisconnect("COM init failed: {:#x}", hr);
  2241. auto plock = std::lock_guard{mProcMutex};
  2242. mProcResult = com.status();
  2243. mState = ThreadState::Done;
  2244. mProcCond.notify_all();
  2245. return;
  2246. }
  2247. if(!gInitDone.load(std::memory_order_relaxed))
  2248. {
  2249. auto devlock = DeviceListLock{gDeviceList};
  2250. gInitCV.wait(devlock, []() -> bool { return gInitDone; });
  2251. }
  2252. auto helper = DeviceHelper{};
  2253. if(HRESULT hr{helper.init()}; FAILED(hr))
  2254. {
  2255. mDevice->handleDisconnect("Helper init failed: {:#x}", as_unsigned(hr));
  2256. auto plock = std::lock_guard{mProcMutex};
  2257. mProcResult = hr;
  2258. mState = ThreadState::Done;
  2259. mProcCond.notify_all();
  2260. return;
  2261. }
  2262. althrd_setname(GetRecordThreadName());
  2263. auto mmdev = DeviceHandle{nullptr};
  2264. if(auto hr = openProxy(name, helper, mmdev); FAILED(hr))
  2265. {
  2266. auto plock = std::lock_guard{mProcMutex};
  2267. mProcResult = hr;
  2268. mState = ThreadState::Done;
  2269. mProcCond.notify_all();
  2270. return;
  2271. }
  2272. auto client = ComPtr<IAudioClient>{};
  2273. auto capture = ComPtr<IAudioCaptureClient>{};
  2274. if(auto hr = resetProxy(helper, mmdev, client, capture); FAILED(hr))
  2275. {
  2276. auto plock = std::lock_guard{mProcMutex};
  2277. mProcResult = hr;
  2278. mState = ThreadState::Done;
  2279. mProcCond.notify_all();
  2280. return;
  2281. }
  2282. auto plock = std::unique_lock{mProcMutex};
  2283. mProcResult = S_OK;
  2284. while(mState != ThreadState::Done)
  2285. {
  2286. mAction = ThreadAction::Nothing;
  2287. mState = ThreadState::Waiting;
  2288. mProcCond.notify_all();
  2289. mProcCond.wait(plock, [this]() noexcept { return mAction != ThreadAction::Nothing; });
  2290. switch(mAction)
  2291. {
  2292. case ThreadAction::Nothing:
  2293. break;
  2294. case ThreadAction::Record:
  2295. mKillNow.store(false, std::memory_order_release);
  2296. mAction = ThreadAction::Nothing;
  2297. mState = ThreadState::Recording;
  2298. mProcResult = S_OK;
  2299. plock.unlock();
  2300. mProcCond.notify_all();
  2301. recordProc(client.get(), capture.get());
  2302. plock.lock();
  2303. break;
  2304. case ThreadAction::Quit:
  2305. mAction = ThreadAction::Nothing;
  2306. mState = ThreadState::Done;
  2307. mProcCond.notify_all();
  2308. break;
  2309. }
  2310. }
  2311. }
  2312. catch(...) {
  2313. auto plock = std::lock_guard{mProcMutex};
  2314. mProcResult = E_FAIL;
  2315. mAction = ThreadAction::Nothing;
  2316. mState = ThreadState::Done;
  2317. mProcCond.notify_all();
  2318. }
  2319. void WasapiCapture::open(std::string_view name)
  2320. {
  2321. mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
  2322. if(mNotifyEvent == nullptr)
  2323. {
  2324. ERR("Failed to create notify events: {}", GetLastError());
  2325. throw al::backend_exception{al::backend_error::DeviceError,
  2326. "Failed to create notify events"};
  2327. }
  2328. mProcThread = std::thread{&WasapiCapture::proc_thread, this, std::string{name}};
  2329. auto plock = std::unique_lock{mProcMutex};
  2330. mProcCond.wait(plock, [this]() noexcept { return mState != ThreadState::Initializing; });
  2331. if(mProcResult == E_NOTFOUND)
  2332. throw al::backend_exception{al::backend_error::NoDevice, "Device \"{}\" not found", name};
  2333. if(mProcResult == E_OUTOFMEMORY)
  2334. throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"};
  2335. if(FAILED(mProcResult) || mState == ThreadState::Done)
  2336. throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: {:#x}",
  2337. as_unsigned(mProcResult)};
  2338. }
  2339. auto WasapiCapture::openProxy(const std::string_view name, DeviceHelper &helper,
  2340. DeviceHandle &mmdev) -> HRESULT
  2341. {
  2342. auto devname = std::string{};
  2343. auto devid = std::wstring{};
  2344. if(!name.empty())
  2345. {
  2346. auto devlock = DeviceListLock{gDeviceList};
  2347. auto devlist = al::span{devlock.getCaptureList()};
  2348. auto iter = std::find_if(devlist.cbegin(), devlist.cend(),
  2349. [name](const DevMap &entry) -> bool
  2350. { return entry.name == name || al::case_compare(entry.endpoint_guid, name) == 0; });
  2351. if(iter == devlist.cend())
  2352. {
  2353. const std::wstring wname{utf8_to_wstr(name)};
  2354. iter = std::find_if(devlist.cbegin(), devlist.cend(),
  2355. [&wname](const DevMap &entry) -> bool
  2356. { return al::case_compare(entry.devid, wname) == 0; });
  2357. }
  2358. if(iter == devlist.cend())
  2359. {
  2360. WARN("Failed to find device name matching \"{}\"", name);
  2361. return E_NOTFOUND;
  2362. }
  2363. devname = iter->name;
  2364. devid = iter->devid;
  2365. }
  2366. auto hr = helper.openDevice(devid, eCapture, mmdev);
  2367. if(FAILED(hr))
  2368. {
  2369. WARN("Failed to open device \"{}\": {:#x}", devname.empty()
  2370. ? "(default)"sv : std::string_view{devname}, as_unsigned(hr));
  2371. return hr;
  2372. }
  2373. if(!devname.empty())
  2374. mDeviceName = std::move(devname);
  2375. else
  2376. mDeviceName = GetDeviceNameAndGuid(mmdev).mName;
  2377. return S_OK;
  2378. }
  2379. auto WasapiCapture::resetProxy(DeviceHelper &helper, DeviceHandle &mmdev,
  2380. ComPtr<IAudioClient> &client, ComPtr<IAudioCaptureClient> &capture) -> HRESULT
  2381. {
  2382. capture = nullptr;
  2383. client = nullptr;
  2384. auto hr = helper.activateAudioClient(mmdev, __uuidof(IAudioClient), al::out_ptr(client));
  2385. if(FAILED(hr))
  2386. {
  2387. ERR("Failed to reactivate audio client: {:#x}", as_unsigned(hr));
  2388. return hr;
  2389. }
  2390. auto wfx = unique_coptr<WAVEFORMATEX>{};
  2391. hr = client->GetMixFormat(al::out_ptr(wfx));
  2392. if(FAILED(hr))
  2393. {
  2394. ERR("Failed to get capture format: {:#x}", as_unsigned(hr));
  2395. return hr;
  2396. }
  2397. TraceFormat("Device capture format", wfx.get());
  2398. auto InputType = WAVEFORMATEXTENSIBLE{};
  2399. if(!MakeExtensible(&InputType, wfx.get()))
  2400. return E_FAIL;
  2401. wfx = nullptr;
  2402. const bool isRear51{InputType.Format.nChannels == 6
  2403. && (InputType.dwChannelMask&X51RearMask) == X5DOT1REAR};
  2404. // Make sure buffer is at least 100ms in size
  2405. ReferenceTime buf_time{ReferenceTime{seconds{mDevice->mBufferSize}} / mDevice->mSampleRate};
  2406. buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}});
  2407. InputType = {};
  2408. InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  2409. switch(mDevice->FmtChans)
  2410. {
  2411. case DevFmtMono:
  2412. InputType.Format.nChannels = 1;
  2413. InputType.dwChannelMask = MONO;
  2414. break;
  2415. case DevFmtStereo:
  2416. InputType.Format.nChannels = 2;
  2417. InputType.dwChannelMask = STEREO;
  2418. break;
  2419. case DevFmtQuad:
  2420. InputType.Format.nChannels = 4;
  2421. InputType.dwChannelMask = QUAD;
  2422. break;
  2423. case DevFmtX51:
  2424. InputType.Format.nChannels = 6;
  2425. InputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
  2426. break;
  2427. case DevFmtX61:
  2428. InputType.Format.nChannels = 7;
  2429. InputType.dwChannelMask = X6DOT1;
  2430. break;
  2431. case DevFmtX71:
  2432. InputType.Format.nChannels = 8;
  2433. InputType.dwChannelMask = X7DOT1;
  2434. break;
  2435. case DevFmtX714:
  2436. InputType.Format.nChannels = 12;
  2437. InputType.dwChannelMask = X7DOT1DOT4;
  2438. break;
  2439. case DevFmtX7144:
  2440. case DevFmtX3D71:
  2441. case DevFmtAmbi3D:
  2442. return E_FAIL;
  2443. }
  2444. switch(mDevice->FmtType)
  2445. {
  2446. /* NOTE: Signedness doesn't matter, the converter will handle it. */
  2447. case DevFmtByte:
  2448. case DevFmtUByte:
  2449. InputType.Format.wBitsPerSample = 8;
  2450. InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  2451. break;
  2452. case DevFmtShort:
  2453. case DevFmtUShort:
  2454. InputType.Format.wBitsPerSample = 16;
  2455. InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  2456. break;
  2457. case DevFmtInt:
  2458. case DevFmtUInt:
  2459. InputType.Format.wBitsPerSample = 32;
  2460. InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  2461. break;
  2462. case DevFmtFloat:
  2463. InputType.Format.wBitsPerSample = 32;
  2464. InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  2465. break;
  2466. }
  2467. /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
  2468. InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
  2469. InputType.Format.nSamplesPerSec = mDevice->mSampleRate;
  2470. InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
  2471. InputType.Format.wBitsPerSample / 8);
  2472. InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
  2473. InputType.Format.nBlockAlign;
  2474. InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format);
  2475. TraceFormat("Requesting capture format", &InputType.Format);
  2476. hr = client->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, al::out_ptr(wfx));
  2477. if(FAILED(hr))
  2478. {
  2479. WARN("Failed to check capture format support: {:#x}", as_unsigned(hr));
  2480. hr = client->GetMixFormat(al::out_ptr(wfx));
  2481. }
  2482. if(FAILED(hr))
  2483. {
  2484. ERR("Failed to find a supported capture format: {:#x}", as_unsigned(hr));
  2485. return hr;
  2486. }
  2487. mSampleConv = nullptr;
  2488. mChannelConv = {};
  2489. if(wfx != nullptr)
  2490. {
  2491. TraceFormat("Got capture format", wfx.get());
  2492. if(!MakeExtensible(&InputType, wfx.get()))
  2493. return E_FAIL;
  2494. wfx = nullptr;
  2495. auto validate_fmt = [](DeviceBase *device, uint32_t chancount, DWORD chanmask) noexcept
  2496. -> bool
  2497. {
  2498. switch(device->FmtChans)
  2499. {
  2500. /* If the device wants mono, we can handle any input. */
  2501. case DevFmtMono:
  2502. return true;
  2503. /* If the device wants stereo, we can handle mono or stereo input. */
  2504. case DevFmtStereo:
  2505. return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO))
  2506. || (chancount == 1 && (chanmask&MonoMask) == MONO);
  2507. /* Otherwise, the device must match the input type. */
  2508. case DevFmtQuad:
  2509. return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD));
  2510. /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
  2511. case DevFmtX51:
  2512. return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1
  2513. || (chanmask&X51RearMask) == X5DOT1REAR));
  2514. case DevFmtX61:
  2515. return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1));
  2516. case DevFmtX71:
  2517. case DevFmtX3D71:
  2518. return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1));
  2519. case DevFmtX714:
  2520. return (chancount == 12 && (chanmask == 0 || (chanmask&X714Mask) == X7DOT1DOT4));
  2521. case DevFmtX7144:
  2522. return (chancount == 16 && chanmask == 0);
  2523. case DevFmtAmbi3D:
  2524. return (chanmask == 0 && chancount == device->channelsFromFmt());
  2525. }
  2526. return false;
  2527. };
  2528. if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask))
  2529. {
  2530. ERR("Failed to match format, wanted: {} {} {}hz, got: {:#08x} mask {} channel{} {}-bit {}hz",
  2531. DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
  2532. mDevice->mSampleRate, InputType.dwChannelMask, InputType.Format.nChannels,
  2533. (InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample,
  2534. InputType.Format.nSamplesPerSec);
  2535. return E_FAIL;
  2536. }
  2537. }
  2538. DevFmtType srcType{};
  2539. if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
  2540. {
  2541. if(InputType.Format.wBitsPerSample == 8)
  2542. srcType = DevFmtUByte;
  2543. else if(InputType.Format.wBitsPerSample == 16)
  2544. srcType = DevFmtShort;
  2545. else if(InputType.Format.wBitsPerSample == 32)
  2546. srcType = DevFmtInt;
  2547. else
  2548. {
  2549. ERR("Unhandled integer bit depth: {}", InputType.Format.wBitsPerSample);
  2550. return E_FAIL;
  2551. }
  2552. }
  2553. else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
  2554. {
  2555. if(InputType.Format.wBitsPerSample == 32)
  2556. srcType = DevFmtFloat;
  2557. else
  2558. {
  2559. ERR("Unhandled float bit depth: {}", InputType.Format.wBitsPerSample);
  2560. return E_FAIL;
  2561. }
  2562. }
  2563. else
  2564. {
  2565. ERR("Unhandled format sub-type: {}", GuidPrinter{InputType.SubFormat}.str());
  2566. return E_FAIL;
  2567. }
  2568. if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1)
  2569. {
  2570. uint chanmask{(1u<<InputType.Format.nChannels) - 1u};
  2571. /* Exclude LFE from the downmix. */
  2572. if((InputType.dwChannelMask&SPEAKER_LOW_FREQUENCY))
  2573. {
  2574. constexpr auto lfemask = MaskFromTopBits(SPEAKER_LOW_FREQUENCY);
  2575. const int lfeidx{al::popcount(InputType.dwChannelMask&lfemask) - 1};
  2576. chanmask &= ~(1u << lfeidx);
  2577. }
  2578. mChannelConv = ChannelConverter{srcType, InputType.Format.nChannels, chanmask,
  2579. mDevice->FmtChans};
  2580. TRACE("Created {} multichannel-to-mono converter", DevFmtTypeString(srcType));
  2581. /* The channel converter always outputs float, so change the input type
  2582. * for the resampler/type-converter.
  2583. */
  2584. srcType = DevFmtFloat;
  2585. }
  2586. else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1)
  2587. {
  2588. mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans};
  2589. TRACE("Created {} mono-to-stereo converter", DevFmtTypeString(srcType));
  2590. srcType = DevFmtFloat;
  2591. }
  2592. if(mDevice->mSampleRate != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType)
  2593. {
  2594. mSampleConv = SampleConverter::Create(srcType, mDevice->FmtType,
  2595. mDevice->channelsFromFmt(), InputType.Format.nSamplesPerSec, mDevice->mSampleRate,
  2596. Resampler::FastBSinc24);
  2597. if(!mSampleConv)
  2598. {
  2599. ERR("Failed to create converter for {} format, dst: {} {}hz, src: {} {}hz",
  2600. DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
  2601. mDevice->mSampleRate, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
  2602. return E_FAIL;
  2603. }
  2604. TRACE("Created converter for {} format, dst: {} {}hz, src: {} {}hz",
  2605. DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
  2606. mDevice->mSampleRate, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
  2607. }
  2608. hr = client->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  2609. buf_time.count(), 0, &InputType.Format, nullptr);
  2610. if(FAILED(hr))
  2611. {
  2612. ERR("Failed to initialize audio client: {:#x}", as_unsigned(hr));
  2613. return hr;
  2614. }
  2615. hr = client->GetService(__uuidof(IAudioCaptureClient), al::out_ptr(capture));
  2616. if(FAILED(hr))
  2617. {
  2618. ERR("Failed to get IAudioCaptureClient: {:#x}", as_unsigned(hr));
  2619. return hr;
  2620. }
  2621. UINT32 buffer_len{};
  2622. ReferenceTime min_per{};
  2623. hr = client->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
  2624. if(SUCCEEDED(hr))
  2625. hr = client->GetBufferSize(&buffer_len);
  2626. if(FAILED(hr))
  2627. {
  2628. ERR("Failed to get buffer size: {:#x}", as_unsigned(hr));
  2629. return hr;
  2630. }
  2631. mDevice->mUpdateSize = RefTime2Samples(min_per, mDevice->mSampleRate);
  2632. mDevice->mBufferSize = buffer_len;
  2633. mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false);
  2634. hr = client->SetEventHandle(mNotifyEvent);
  2635. if(FAILED(hr))
  2636. {
  2637. ERR("Failed to set event handle: {:#x}", as_unsigned(hr));
  2638. return hr;
  2639. }
  2640. return hr;
  2641. }
  2642. void WasapiCapture::start()
  2643. {
  2644. auto plock = std::unique_lock{mProcMutex};
  2645. if(mState != ThreadState::Waiting)
  2646. throw al::backend_exception{al::backend_error::DeviceError, "Invalid state: {}",
  2647. unsigned{al::to_underlying(mState)}};
  2648. mAction = ThreadAction::Record;
  2649. mProcCond.notify_all();
  2650. mProcCond.wait(plock, [this]() noexcept { return mAction != ThreadAction::Record; });
  2651. if(FAILED(mProcResult) || mState != ThreadState::Recording)
  2652. throw al::backend_exception{al::backend_error::DeviceError, "Device capture failed: {:#x}",
  2653. as_unsigned(mProcResult)};
  2654. }
  2655. void WasapiCapture::stop()
  2656. {
  2657. auto plock = std::unique_lock{mProcMutex};
  2658. if(mState == ThreadState::Recording)
  2659. {
  2660. mKillNow = true;
  2661. mProcCond.wait(plock, [this]() noexcept { return mState != ThreadState::Recording; });
  2662. }
  2663. }
  2664. void WasapiCapture::captureSamples(std::byte *buffer, uint samples)
  2665. { std::ignore = mRing->read(buffer, samples); }
  2666. uint WasapiCapture::availableSamples()
  2667. { return static_cast<uint>(mRing->readSpace()); }
  2668. } // namespace
  2669. bool WasapiBackendFactory::init()
  2670. {
  2671. static HRESULT InitResult{E_FAIL};
  2672. if(FAILED(InitResult)) try
  2673. {
  2674. std::promise<HRESULT> promise;
  2675. auto future = promise.get_future();
  2676. std::thread{&DeviceEnumHelper::messageHandler, &promise}.detach();
  2677. InitResult = future.get();
  2678. }
  2679. catch(...) {
  2680. }
  2681. return SUCCEEDED(InitResult);
  2682. }
  2683. bool WasapiBackendFactory::querySupport(BackendType type)
  2684. { return type == BackendType::Playback || type == BackendType::Capture; }
  2685. auto WasapiBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
  2686. {
  2687. std::vector<std::string> outnames;
  2688. auto devlock = DeviceListLock{gDeviceList};
  2689. switch(type)
  2690. {
  2691. case BackendType::Playback:
  2692. {
  2693. auto defaultId = devlock.getPlaybackDefaultId();
  2694. auto &devlist = devlock.getPlaybackList();
  2695. outnames.reserve(devlist.size());
  2696. std::transform(devlist.cbegin(), devlist.cend(), std::back_inserter(outnames),
  2697. std::mem_fn(&DevMap::name));
  2698. /* Default device goes first. */
  2699. const auto defiter = std::find_if(devlist.cbegin(), devlist.cend(),
  2700. [defaultId](const DevMap &entry) -> bool { return entry.devid == defaultId; });
  2701. if(defiter != devlist.cend())
  2702. {
  2703. const auto defname = outnames.begin() + std::distance(devlist.cbegin(), defiter);
  2704. std::rotate(outnames.begin(), defname, defname+1);
  2705. }
  2706. }
  2707. break;
  2708. case BackendType::Capture:
  2709. {
  2710. auto defaultId = devlock.getCaptureDefaultId();
  2711. auto &devlist = devlock.getCaptureList();
  2712. outnames.reserve(devlist.size());
  2713. std::transform(devlist.cbegin(), devlist.cend(), std::back_inserter(outnames),
  2714. std::mem_fn(&DevMap::name));
  2715. /* Default device goes first. */
  2716. const auto defiter = std::find_if(devlist.cbegin(), devlist.cend(),
  2717. [defaultId](const DevMap &entry) -> bool { return entry.devid == defaultId; });
  2718. if(defiter != devlist.cend())
  2719. {
  2720. const auto defname = outnames.begin() + std::distance(devlist.cbegin(), defiter);
  2721. std::rotate(outnames.begin(), defname, defname+1);
  2722. }
  2723. }
  2724. break;
  2725. }
  2726. return outnames;
  2727. }
  2728. BackendPtr WasapiBackendFactory::createBackend(DeviceBase *device, BackendType type)
  2729. {
  2730. if(type == BackendType::Playback)
  2731. return BackendPtr{new WasapiPlayback{device}};
  2732. if(type == BackendType::Capture)
  2733. return BackendPtr{new WasapiCapture{device}};
  2734. return nullptr;
  2735. }
  2736. BackendFactory &WasapiBackendFactory::getFactory()
  2737. {
  2738. static WasapiBackendFactory factory{};
  2739. return factory;
  2740. }
  2741. alc::EventSupport WasapiBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
  2742. {
  2743. switch(eventType)
  2744. {
  2745. case alc::EventType::DefaultDeviceChanged:
  2746. return alc::EventSupport::FullSupport;
  2747. case alc::EventType::DeviceAdded:
  2748. case alc::EventType::DeviceRemoved:
  2749. #if !ALSOFT_UWP
  2750. return alc::EventSupport::FullSupport;
  2751. #endif
  2752. case alc::EventType::Count:
  2753. break;
  2754. }
  2755. return alc::EventSupport::NoSupport;
  2756. }