wasapi.cpp 96 KB

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