mmdevapi.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060
  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. #define COBJMACROS
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <memory.h>
  25. #include <wtypes.h>
  26. #include <mmdeviceapi.h>
  27. #include <audioclient.h>
  28. #include <cguid.h>
  29. #include <devpropdef.h>
  30. #include <mmreg.h>
  31. #include <propsys.h>
  32. #include <propkey.h>
  33. #include <devpkey.h>
  34. #ifndef _WAVEFORMATEXTENSIBLE_
  35. #include <ks.h>
  36. #include <ksmedia.h>
  37. #endif
  38. #include "alMain.h"
  39. #include "alu.h"
  40. #include "threads.h"
  41. #include "compat.h"
  42. #include "alstring.h"
  43. #include "converter.h"
  44. #include "backends/base.h"
  45. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
  46. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
  47. DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
  48. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
  49. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
  50. #define MONO SPEAKER_FRONT_CENTER
  51. #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
  52. #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
  53. #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  54. #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
  55. #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  56. #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)
  57. #define X7DOT1_WIDE (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_FRONT_LEFT_OF_CENTER|SPEAKER_FRONT_RIGHT_OF_CENTER)
  58. #define REFTIME_PER_SEC ((REFERENCE_TIME)10000000)
  59. #define DEVNAME_HEAD "OpenAL Soft on "
  60. typedef struct {
  61. al_string name;
  62. al_string endpoint_guid; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
  63. WCHAR *devid;
  64. } DevMap;
  65. TYPEDEF_VECTOR(DevMap, vector_DevMap)
  66. static void clear_devlist(vector_DevMap *list)
  67. {
  68. #define CLEAR_DEVMAP(i) do { \
  69. AL_STRING_DEINIT((i)->name); \
  70. AL_STRING_DEINIT((i)->endpoint_guid); \
  71. free((i)->devid); \
  72. (i)->devid = NULL; \
  73. } while(0)
  74. VECTOR_FOR_EACH(DevMap, *list, CLEAR_DEVMAP);
  75. VECTOR_RESIZE(*list, 0, 0);
  76. #undef CLEAR_DEVMAP
  77. }
  78. static vector_DevMap PlaybackDevices;
  79. static vector_DevMap CaptureDevices;
  80. static HANDLE ThreadHdl;
  81. static DWORD ThreadID;
  82. typedef struct {
  83. HANDLE FinishedEvt;
  84. HRESULT result;
  85. } ThreadRequest;
  86. #define WM_USER_First (WM_USER+0)
  87. #define WM_USER_OpenDevice (WM_USER+0)
  88. #define WM_USER_ResetDevice (WM_USER+1)
  89. #define WM_USER_StartDevice (WM_USER+2)
  90. #define WM_USER_StopDevice (WM_USER+3)
  91. #define WM_USER_CloseDevice (WM_USER+4)
  92. #define WM_USER_Enumerate (WM_USER+5)
  93. #define WM_USER_Last (WM_USER+5)
  94. static const char MessageStr[WM_USER_Last+1-WM_USER][20] = {
  95. "Open Device",
  96. "Reset Device",
  97. "Start Device",
  98. "Stop Device",
  99. "Close Device",
  100. "Enumerate Devices",
  101. };
  102. static inline void ReturnMsgResponse(ThreadRequest *req, HRESULT res)
  103. {
  104. req->result = res;
  105. SetEvent(req->FinishedEvt);
  106. }
  107. static HRESULT WaitForResponse(ThreadRequest *req)
  108. {
  109. if(WaitForSingleObject(req->FinishedEvt, INFINITE) == WAIT_OBJECT_0)
  110. return req->result;
  111. ERR("Message response error: %lu\n", GetLastError());
  112. return E_FAIL;
  113. }
  114. static void get_device_name_and_guid(IMMDevice *device, al_string *name, al_string *guid)
  115. {
  116. IPropertyStore *ps;
  117. PROPVARIANT pvname;
  118. PROPVARIANT pvguid;
  119. HRESULT hr;
  120. alstr_copy_cstr(name, DEVNAME_HEAD);
  121. hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
  122. if(FAILED(hr))
  123. {
  124. WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
  125. alstr_append_cstr(name, "Unknown Device Name");
  126. if(guid!=NULL)alstr_copy_cstr(guid, "Unknown Device GUID");
  127. return;
  128. }
  129. PropVariantInit(&pvname);
  130. hr = IPropertyStore_GetValue(ps, (const PROPERTYKEY*)&DEVPKEY_Device_FriendlyName, &pvname);
  131. if(FAILED(hr))
  132. {
  133. WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr);
  134. alstr_append_cstr(name, "Unknown Device Name");
  135. }
  136. else if(pvname.vt == VT_LPWSTR)
  137. alstr_append_wcstr(name, pvname.pwszVal);
  138. else
  139. {
  140. WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvname.vt);
  141. alstr_append_cstr(name, "Unknown Device Name");
  142. }
  143. PropVariantClear(&pvname);
  144. if(guid!=NULL){
  145. PropVariantInit(&pvguid);
  146. hr = IPropertyStore_GetValue(ps, (const PROPERTYKEY*)&PKEY_AudioEndpoint_GUID, &pvguid);
  147. if(FAILED(hr))
  148. {
  149. WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr);
  150. alstr_copy_cstr(guid, "Unknown Device GUID");
  151. }
  152. else if(pvguid.vt == VT_LPWSTR)
  153. alstr_copy_wcstr(guid, pvguid.pwszVal);
  154. else
  155. {
  156. WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvguid.vt);
  157. alstr_copy_cstr(guid, "Unknown Device GUID");
  158. }
  159. PropVariantClear(&pvguid);
  160. }
  161. IPropertyStore_Release(ps);
  162. }
  163. static void get_device_formfactor(IMMDevice *device, EndpointFormFactor *formfactor)
  164. {
  165. IPropertyStore *ps;
  166. PROPVARIANT pvform;
  167. HRESULT hr;
  168. hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
  169. if(FAILED(hr))
  170. {
  171. WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
  172. return;
  173. }
  174. PropVariantInit(&pvform);
  175. hr = IPropertyStore_GetValue(ps, &PKEY_AudioEndpoint_FormFactor, &pvform);
  176. if(FAILED(hr))
  177. WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr);
  178. else if(pvform.vt == VT_UI4)
  179. *formfactor = pvform.ulVal;
  180. else if(pvform.vt == VT_EMPTY)
  181. *formfactor = UnknownFormFactor;
  182. else
  183. WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform.vt);
  184. PropVariantClear(&pvform);
  185. IPropertyStore_Release(ps);
  186. }
  187. static void add_device(IMMDevice *device, const WCHAR *devid, vector_DevMap *list)
  188. {
  189. int count = 0;
  190. al_string tmpname;
  191. DevMap entry;
  192. AL_STRING_INIT(tmpname);
  193. AL_STRING_INIT(entry.name);
  194. AL_STRING_INIT(entry.endpoint_guid);
  195. entry.devid = strdupW(devid);
  196. get_device_name_and_guid(device, &tmpname, &entry.endpoint_guid);
  197. while(1)
  198. {
  199. const DevMap *iter;
  200. alstr_copy(&entry.name, tmpname);
  201. if(count != 0)
  202. {
  203. char str[64];
  204. snprintf(str, sizeof(str), " #%d", count+1);
  205. alstr_append_cstr(&entry.name, str);
  206. }
  207. #define MATCH_ENTRY(i) (alstr_cmp(entry.name, (i)->name) == 0)
  208. VECTOR_FIND_IF(iter, const DevMap, *list, MATCH_ENTRY);
  209. if(iter == VECTOR_END(*list)) break;
  210. #undef MATCH_ENTRY
  211. count++;
  212. }
  213. TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", alstr_get_cstr(entry.name), alstr_get_cstr(entry.endpoint_guid), entry.devid);
  214. VECTOR_PUSH_BACK(*list, entry);
  215. AL_STRING_DEINIT(tmpname);
  216. }
  217. static WCHAR *get_device_id(IMMDevice *device)
  218. {
  219. WCHAR *devid;
  220. HRESULT hr;
  221. hr = IMMDevice_GetId(device, &devid);
  222. if(FAILED(hr))
  223. {
  224. ERR("Failed to get device id: %lx\n", hr);
  225. return NULL;
  226. }
  227. return devid;
  228. }
  229. static HRESULT probe_devices(IMMDeviceEnumerator *devenum, EDataFlow flowdir, vector_DevMap *list)
  230. {
  231. IMMDeviceCollection *coll;
  232. IMMDevice *defdev = NULL;
  233. WCHAR *defdevid = NULL;
  234. HRESULT hr;
  235. UINT count;
  236. UINT i;
  237. hr = IMMDeviceEnumerator_EnumAudioEndpoints(devenum, flowdir, DEVICE_STATE_ACTIVE, &coll);
  238. if(FAILED(hr))
  239. {
  240. ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr);
  241. return hr;
  242. }
  243. count = 0;
  244. hr = IMMDeviceCollection_GetCount(coll, &count);
  245. if(SUCCEEDED(hr) && count > 0)
  246. {
  247. clear_devlist(list);
  248. VECTOR_RESIZE(*list, 0, count);
  249. hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(devenum, flowdir,
  250. eMultimedia, &defdev);
  251. }
  252. if(SUCCEEDED(hr) && defdev != NULL)
  253. {
  254. defdevid = get_device_id(defdev);
  255. if(defdevid)
  256. add_device(defdev, defdevid, list);
  257. }
  258. for(i = 0;i < count;++i)
  259. {
  260. IMMDevice *device;
  261. WCHAR *devid;
  262. hr = IMMDeviceCollection_Item(coll, i, &device);
  263. if(FAILED(hr)) continue;
  264. devid = get_device_id(device);
  265. if(devid)
  266. {
  267. if(wcscmp(devid, defdevid) != 0)
  268. add_device(device, devid, list);
  269. CoTaskMemFree(devid);
  270. }
  271. IMMDevice_Release(device);
  272. }
  273. if(defdev) IMMDevice_Release(defdev);
  274. if(defdevid) CoTaskMemFree(defdevid);
  275. IMMDeviceCollection_Release(coll);
  276. return S_OK;
  277. }
  278. /* Proxy interface used by the message handler. */
  279. struct ALCmmdevProxyVtable;
  280. typedef struct ALCmmdevProxy {
  281. const struct ALCmmdevProxyVtable *vtbl;
  282. } ALCmmdevProxy;
  283. struct ALCmmdevProxyVtable {
  284. HRESULT (*const openProxy)(ALCmmdevProxy*);
  285. void (*const closeProxy)(ALCmmdevProxy*);
  286. HRESULT (*const resetProxy)(ALCmmdevProxy*);
  287. HRESULT (*const startProxy)(ALCmmdevProxy*);
  288. void (*const stopProxy)(ALCmmdevProxy*);
  289. };
  290. #define DEFINE_ALCMMDEVPROXY_VTABLE(T) \
  291. DECLARE_THUNK(T, ALCmmdevProxy, HRESULT, openProxy) \
  292. DECLARE_THUNK(T, ALCmmdevProxy, void, closeProxy) \
  293. DECLARE_THUNK(T, ALCmmdevProxy, HRESULT, resetProxy) \
  294. DECLARE_THUNK(T, ALCmmdevProxy, HRESULT, startProxy) \
  295. DECLARE_THUNK(T, ALCmmdevProxy, void, stopProxy) \
  296. \
  297. static const struct ALCmmdevProxyVtable T##_ALCmmdevProxy_vtable = { \
  298. T##_ALCmmdevProxy_openProxy, \
  299. T##_ALCmmdevProxy_closeProxy, \
  300. T##_ALCmmdevProxy_resetProxy, \
  301. T##_ALCmmdevProxy_startProxy, \
  302. T##_ALCmmdevProxy_stopProxy, \
  303. }
  304. static void ALCmmdevProxy_Construct(ALCmmdevProxy* UNUSED(self)) { }
  305. static void ALCmmdevProxy_Destruct(ALCmmdevProxy* UNUSED(self)) { }
  306. static DWORD CALLBACK ALCmmdevProxy_messageHandler(void *ptr)
  307. {
  308. ThreadRequest *req = ptr;
  309. IMMDeviceEnumerator *Enumerator;
  310. ALuint deviceCount = 0;
  311. ALCmmdevProxy *proxy;
  312. HRESULT hr, cohr;
  313. MSG msg;
  314. TRACE("Starting message thread\n");
  315. cohr = CoInitialize(NULL);
  316. if(FAILED(cohr))
  317. {
  318. WARN("Failed to initialize COM: 0x%08lx\n", cohr);
  319. ReturnMsgResponse(req, cohr);
  320. return 0;
  321. }
  322. hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &ptr);
  323. if(FAILED(hr))
  324. {
  325. WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
  326. CoUninitialize();
  327. ReturnMsgResponse(req, hr);
  328. return 0;
  329. }
  330. Enumerator = ptr;
  331. IMMDeviceEnumerator_Release(Enumerator);
  332. Enumerator = NULL;
  333. CoUninitialize();
  334. /* HACK: Force Windows to create a message queue for this thread before
  335. * returning success, otherwise PostThreadMessage may fail if it gets
  336. * called before GetMessage.
  337. */
  338. PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
  339. TRACE("Message thread initialization complete\n");
  340. ReturnMsgResponse(req, S_OK);
  341. TRACE("Starting message loop\n");
  342. while(GetMessage(&msg, NULL, WM_USER_First, WM_USER_Last))
  343. {
  344. TRACE("Got message \"%s\" (0x%04x, lparam=%p, wparam=%p)\n",
  345. (msg.message >= WM_USER && msg.message <= WM_USER_Last) ?
  346. MessageStr[msg.message-WM_USER] : "Unknown",
  347. msg.message, (void*)msg.lParam, (void*)msg.wParam
  348. );
  349. switch(msg.message)
  350. {
  351. case WM_USER_OpenDevice:
  352. req = (ThreadRequest*)msg.wParam;
  353. proxy = (ALCmmdevProxy*)msg.lParam;
  354. hr = cohr = S_OK;
  355. if(++deviceCount == 1)
  356. hr = cohr = CoInitialize(NULL);
  357. if(SUCCEEDED(hr))
  358. hr = V0(proxy,openProxy)();
  359. if(FAILED(hr))
  360. {
  361. if(--deviceCount == 0 && SUCCEEDED(cohr))
  362. CoUninitialize();
  363. }
  364. ReturnMsgResponse(req, hr);
  365. continue;
  366. case WM_USER_ResetDevice:
  367. req = (ThreadRequest*)msg.wParam;
  368. proxy = (ALCmmdevProxy*)msg.lParam;
  369. hr = V0(proxy,resetProxy)();
  370. ReturnMsgResponse(req, hr);
  371. continue;
  372. case WM_USER_StartDevice:
  373. req = (ThreadRequest*)msg.wParam;
  374. proxy = (ALCmmdevProxy*)msg.lParam;
  375. hr = V0(proxy,startProxy)();
  376. ReturnMsgResponse(req, hr);
  377. continue;
  378. case WM_USER_StopDevice:
  379. req = (ThreadRequest*)msg.wParam;
  380. proxy = (ALCmmdevProxy*)msg.lParam;
  381. V0(proxy,stopProxy)();
  382. ReturnMsgResponse(req, S_OK);
  383. continue;
  384. case WM_USER_CloseDevice:
  385. req = (ThreadRequest*)msg.wParam;
  386. proxy = (ALCmmdevProxy*)msg.lParam;
  387. V0(proxy,closeProxy)();
  388. if(--deviceCount == 0)
  389. CoUninitialize();
  390. ReturnMsgResponse(req, S_OK);
  391. continue;
  392. case WM_USER_Enumerate:
  393. req = (ThreadRequest*)msg.wParam;
  394. hr = cohr = S_OK;
  395. if(++deviceCount == 1)
  396. hr = cohr = CoInitialize(NULL);
  397. if(SUCCEEDED(hr))
  398. hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &ptr);
  399. if(SUCCEEDED(hr))
  400. {
  401. Enumerator = ptr;
  402. if(msg.lParam == ALL_DEVICE_PROBE)
  403. hr = probe_devices(Enumerator, eRender, &PlaybackDevices);
  404. else if(msg.lParam == CAPTURE_DEVICE_PROBE)
  405. hr = probe_devices(Enumerator, eCapture, &CaptureDevices);
  406. IMMDeviceEnumerator_Release(Enumerator);
  407. Enumerator = NULL;
  408. }
  409. if(--deviceCount == 0 && SUCCEEDED(cohr))
  410. CoUninitialize();
  411. ReturnMsgResponse(req, hr);
  412. continue;
  413. default:
  414. ERR("Unexpected message: %u\n", msg.message);
  415. continue;
  416. }
  417. }
  418. TRACE("Message loop finished\n");
  419. return 0;
  420. }
  421. typedef struct ALCmmdevPlayback {
  422. DERIVE_FROM_TYPE(ALCbackend);
  423. DERIVE_FROM_TYPE(ALCmmdevProxy);
  424. WCHAR *devid;
  425. IMMDevice *mmdev;
  426. IAudioClient *client;
  427. IAudioRenderClient *render;
  428. HANDLE NotifyEvent;
  429. HANDLE MsgEvent;
  430. volatile UINT32 Padding;
  431. volatile int killNow;
  432. althrd_t thread;
  433. } ALCmmdevPlayback;
  434. static int ALCmmdevPlayback_mixerProc(void *arg);
  435. static void ALCmmdevPlayback_Construct(ALCmmdevPlayback *self, ALCdevice *device);
  436. static void ALCmmdevPlayback_Destruct(ALCmmdevPlayback *self);
  437. static ALCenum ALCmmdevPlayback_open(ALCmmdevPlayback *self, const ALCchar *name);
  438. static HRESULT ALCmmdevPlayback_openProxy(ALCmmdevPlayback *self);
  439. static void ALCmmdevPlayback_close(ALCmmdevPlayback *self);
  440. static void ALCmmdevPlayback_closeProxy(ALCmmdevPlayback *self);
  441. static ALCboolean ALCmmdevPlayback_reset(ALCmmdevPlayback *self);
  442. static HRESULT ALCmmdevPlayback_resetProxy(ALCmmdevPlayback *self);
  443. static ALCboolean ALCmmdevPlayback_start(ALCmmdevPlayback *self);
  444. static HRESULT ALCmmdevPlayback_startProxy(ALCmmdevPlayback *self);
  445. static void ALCmmdevPlayback_stop(ALCmmdevPlayback *self);
  446. static void ALCmmdevPlayback_stopProxy(ALCmmdevPlayback *self);
  447. static DECLARE_FORWARD2(ALCmmdevPlayback, ALCbackend, ALCenum, captureSamples, ALCvoid*, ALCuint)
  448. static DECLARE_FORWARD(ALCmmdevPlayback, ALCbackend, ALCuint, availableSamples)
  449. static ClockLatency ALCmmdevPlayback_getClockLatency(ALCmmdevPlayback *self);
  450. static DECLARE_FORWARD(ALCmmdevPlayback, ALCbackend, void, lock)
  451. static DECLARE_FORWARD(ALCmmdevPlayback, ALCbackend, void, unlock)
  452. DECLARE_DEFAULT_ALLOCATORS(ALCmmdevPlayback)
  453. DEFINE_ALCMMDEVPROXY_VTABLE(ALCmmdevPlayback);
  454. DEFINE_ALCBACKEND_VTABLE(ALCmmdevPlayback);
  455. static void ALCmmdevPlayback_Construct(ALCmmdevPlayback *self, ALCdevice *device)
  456. {
  457. SET_VTABLE2(ALCmmdevPlayback, ALCbackend, self);
  458. SET_VTABLE2(ALCmmdevPlayback, ALCmmdevProxy, self);
  459. ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
  460. ALCmmdevProxy_Construct(STATIC_CAST(ALCmmdevProxy, self));
  461. self->devid = NULL;
  462. self->mmdev = NULL;
  463. self->client = NULL;
  464. self->render = NULL;
  465. self->NotifyEvent = NULL;
  466. self->MsgEvent = NULL;
  467. self->Padding = 0;
  468. self->killNow = 0;
  469. }
  470. static void ALCmmdevPlayback_Destruct(ALCmmdevPlayback *self)
  471. {
  472. if(self->NotifyEvent != NULL)
  473. CloseHandle(self->NotifyEvent);
  474. self->NotifyEvent = NULL;
  475. if(self->MsgEvent != NULL)
  476. CloseHandle(self->MsgEvent);
  477. self->MsgEvent = NULL;
  478. free(self->devid);
  479. self->devid = NULL;
  480. ALCmmdevProxy_Destruct(STATIC_CAST(ALCmmdevProxy, self));
  481. ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
  482. }
  483. FORCE_ALIGN static int ALCmmdevPlayback_mixerProc(void *arg)
  484. {
  485. ALCmmdevPlayback *self = arg;
  486. ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
  487. UINT32 buffer_len, written;
  488. ALuint update_size, len;
  489. BYTE *buffer;
  490. HRESULT hr;
  491. hr = CoInitialize(NULL);
  492. if(FAILED(hr))
  493. {
  494. ERR("CoInitialize(NULL) failed: 0x%08lx\n", hr);
  495. V0(device->Backend,lock)();
  496. aluHandleDisconnect(device);
  497. V0(device->Backend,unlock)();
  498. return 1;
  499. }
  500. SetRTPriority();
  501. althrd_setname(althrd_current(), MIXER_THREAD_NAME);
  502. update_size = device->UpdateSize;
  503. buffer_len = update_size * device->NumUpdates;
  504. while(!self->killNow)
  505. {
  506. hr = IAudioClient_GetCurrentPadding(self->client, &written);
  507. if(FAILED(hr))
  508. {
  509. ERR("Failed to get padding: 0x%08lx\n", hr);
  510. V0(device->Backend,lock)();
  511. aluHandleDisconnect(device);
  512. V0(device->Backend,unlock)();
  513. break;
  514. }
  515. self->Padding = written;
  516. len = buffer_len - written;
  517. if(len < update_size)
  518. {
  519. DWORD res;
  520. res = WaitForSingleObjectEx(self->NotifyEvent, 2000, FALSE);
  521. if(res != WAIT_OBJECT_0)
  522. ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
  523. continue;
  524. }
  525. len -= len%update_size;
  526. hr = IAudioRenderClient_GetBuffer(self->render, len, &buffer);
  527. if(SUCCEEDED(hr))
  528. {
  529. ALCmmdevPlayback_lock(self);
  530. aluMixData(device, buffer, len);
  531. self->Padding = written + len;
  532. ALCmmdevPlayback_unlock(self);
  533. hr = IAudioRenderClient_ReleaseBuffer(self->render, len, 0);
  534. }
  535. if(FAILED(hr))
  536. {
  537. ERR("Failed to buffer data: 0x%08lx\n", hr);
  538. V0(device->Backend,lock)();
  539. aluHandleDisconnect(device);
  540. V0(device->Backend,unlock)();
  541. break;
  542. }
  543. }
  544. self->Padding = 0;
  545. CoUninitialize();
  546. return 0;
  547. }
  548. static ALCboolean MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in)
  549. {
  550. memset(out, 0, sizeof(*out));
  551. if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
  552. *out = *(const WAVEFORMATEXTENSIBLE*)in;
  553. else if(in->wFormatTag == WAVE_FORMAT_PCM)
  554. {
  555. out->Format = *in;
  556. out->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  557. out->Format.cbSize = sizeof(*out) - sizeof(*in);
  558. if(out->Format.nChannels == 1)
  559. out->dwChannelMask = MONO;
  560. else if(out->Format.nChannels == 2)
  561. out->dwChannelMask = STEREO;
  562. else
  563. ERR("Unhandled PCM channel count: %d\n", out->Format.nChannels);
  564. out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  565. }
  566. else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
  567. {
  568. out->Format = *in;
  569. out->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  570. out->Format.cbSize = sizeof(*out) - sizeof(*in);
  571. if(out->Format.nChannels == 1)
  572. out->dwChannelMask = MONO;
  573. else if(out->Format.nChannels == 2)
  574. out->dwChannelMask = STEREO;
  575. else
  576. ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels);
  577. out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  578. }
  579. else
  580. {
  581. ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag);
  582. return ALC_FALSE;
  583. }
  584. return ALC_TRUE;
  585. }
  586. static ALCenum ALCmmdevPlayback_open(ALCmmdevPlayback *self, const ALCchar *deviceName)
  587. {
  588. HRESULT hr = S_OK;
  589. self->NotifyEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
  590. self->MsgEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
  591. if(self->NotifyEvent == NULL || self->MsgEvent == NULL)
  592. {
  593. ERR("Failed to create message events: %lu\n", GetLastError());
  594. hr = E_FAIL;
  595. }
  596. if(SUCCEEDED(hr))
  597. {
  598. if(deviceName)
  599. {
  600. const DevMap *iter;
  601. if(VECTOR_SIZE(PlaybackDevices) == 0)
  602. {
  603. ThreadRequest req = { self->MsgEvent, 0 };
  604. if(PostThreadMessage(ThreadID, WM_USER_Enumerate, (WPARAM)&req, ALL_DEVICE_PROBE))
  605. (void)WaitForResponse(&req);
  606. }
  607. hr = E_FAIL;
  608. #define MATCH_NAME(i) (alstr_cmp_cstr((i)->name, deviceName) == 0 || \
  609. alstr_cmp_cstr((i)->endpoint_guid, deviceName) == 0)
  610. VECTOR_FIND_IF(iter, const DevMap, PlaybackDevices, MATCH_NAME);
  611. #undef MATCH_NAME
  612. if(iter == VECTOR_END(PlaybackDevices))
  613. {
  614. int len;
  615. if((len=MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, NULL, 0)) > 0)
  616. {
  617. WCHAR *wname = calloc(sizeof(WCHAR), len);
  618. MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, wname, len);
  619. #define MATCH_NAME(i) (wcscmp((i)->devid, wname) == 0)
  620. VECTOR_FIND_IF(iter, const DevMap, PlaybackDevices, MATCH_NAME);
  621. #undef MATCH_NAME
  622. free(wname);
  623. }
  624. }
  625. if(iter == VECTOR_END(PlaybackDevices))
  626. WARN("Failed to find device name matching \"%s\"\n", deviceName);
  627. else
  628. {
  629. ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
  630. self->devid = strdupW(iter->devid);
  631. alstr_copy(&device->DeviceName, iter->name);
  632. hr = S_OK;
  633. }
  634. }
  635. }
  636. if(SUCCEEDED(hr))
  637. {
  638. ThreadRequest req = { self->MsgEvent, 0 };
  639. hr = E_FAIL;
  640. if(PostThreadMessage(ThreadID, WM_USER_OpenDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  641. hr = WaitForResponse(&req);
  642. else
  643. ERR("Failed to post thread message: %lu\n", GetLastError());
  644. }
  645. if(FAILED(hr))
  646. {
  647. if(self->NotifyEvent != NULL)
  648. CloseHandle(self->NotifyEvent);
  649. self->NotifyEvent = NULL;
  650. if(self->MsgEvent != NULL)
  651. CloseHandle(self->MsgEvent);
  652. self->MsgEvent = NULL;
  653. free(self->devid);
  654. self->devid = NULL;
  655. ERR("Device init failed: 0x%08lx\n", hr);
  656. return ALC_INVALID_VALUE;
  657. }
  658. return ALC_NO_ERROR;
  659. }
  660. static HRESULT ALCmmdevPlayback_openProxy(ALCmmdevPlayback *self)
  661. {
  662. ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
  663. void *ptr;
  664. HRESULT hr;
  665. hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &ptr);
  666. if(SUCCEEDED(hr))
  667. {
  668. IMMDeviceEnumerator *Enumerator = ptr;
  669. if(!self->devid)
  670. hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(Enumerator, eRender, eMultimedia, &self->mmdev);
  671. else
  672. hr = IMMDeviceEnumerator_GetDevice(Enumerator, self->devid, &self->mmdev);
  673. IMMDeviceEnumerator_Release(Enumerator);
  674. Enumerator = NULL;
  675. }
  676. if(SUCCEEDED(hr))
  677. hr = IMMDevice_Activate(self->mmdev, &IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, &ptr);
  678. if(SUCCEEDED(hr))
  679. {
  680. self->client = ptr;
  681. if(alstr_empty(device->DeviceName))
  682. get_device_name_and_guid(self->mmdev, &device->DeviceName, NULL);
  683. }
  684. if(FAILED(hr))
  685. {
  686. if(self->mmdev)
  687. IMMDevice_Release(self->mmdev);
  688. self->mmdev = NULL;
  689. }
  690. return hr;
  691. }
  692. static void ALCmmdevPlayback_close(ALCmmdevPlayback *self)
  693. {
  694. ThreadRequest req = { self->MsgEvent, 0 };
  695. if(PostThreadMessage(ThreadID, WM_USER_CloseDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  696. (void)WaitForResponse(&req);
  697. CloseHandle(self->MsgEvent);
  698. self->MsgEvent = NULL;
  699. CloseHandle(self->NotifyEvent);
  700. self->NotifyEvent = NULL;
  701. free(self->devid);
  702. self->devid = NULL;
  703. }
  704. static void ALCmmdevPlayback_closeProxy(ALCmmdevPlayback *self)
  705. {
  706. if(self->client)
  707. IAudioClient_Release(self->client);
  708. self->client = NULL;
  709. if(self->mmdev)
  710. IMMDevice_Release(self->mmdev);
  711. self->mmdev = NULL;
  712. }
  713. static ALCboolean ALCmmdevPlayback_reset(ALCmmdevPlayback *self)
  714. {
  715. ThreadRequest req = { self->MsgEvent, 0 };
  716. HRESULT hr = E_FAIL;
  717. if(PostThreadMessage(ThreadID, WM_USER_ResetDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  718. hr = WaitForResponse(&req);
  719. return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE;
  720. }
  721. static HRESULT ALCmmdevPlayback_resetProxy(ALCmmdevPlayback *self)
  722. {
  723. ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
  724. EndpointFormFactor formfactor = UnknownFormFactor;
  725. WAVEFORMATEXTENSIBLE OutputType;
  726. WAVEFORMATEX *wfx = NULL;
  727. REFERENCE_TIME min_per, buf_time;
  728. UINT32 buffer_len, min_len;
  729. void *ptr = NULL;
  730. HRESULT hr;
  731. if(self->client)
  732. IAudioClient_Release(self->client);
  733. self->client = NULL;
  734. hr = IMMDevice_Activate(self->mmdev, &IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, &ptr);
  735. if(FAILED(hr))
  736. {
  737. ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
  738. return hr;
  739. }
  740. self->client = ptr;
  741. hr = IAudioClient_GetMixFormat(self->client, &wfx);
  742. if(FAILED(hr))
  743. {
  744. ERR("Failed to get mix format: 0x%08lx\n", hr);
  745. return hr;
  746. }
  747. if(!MakeExtensible(&OutputType, wfx))
  748. {
  749. CoTaskMemFree(wfx);
  750. return E_FAIL;
  751. }
  752. CoTaskMemFree(wfx);
  753. wfx = NULL;
  754. buf_time = ScaleCeil(device->UpdateSize*device->NumUpdates, REFTIME_PER_SEC,
  755. device->Frequency);
  756. if(!(device->Flags&DEVICE_FREQUENCY_REQUEST))
  757. device->Frequency = OutputType.Format.nSamplesPerSec;
  758. if(!(device->Flags&DEVICE_CHANNELS_REQUEST))
  759. {
  760. if(OutputType.Format.nChannels == 1 && OutputType.dwChannelMask == MONO)
  761. device->FmtChans = DevFmtMono;
  762. else if(OutputType.Format.nChannels == 2 && OutputType.dwChannelMask == STEREO)
  763. device->FmtChans = DevFmtStereo;
  764. else if(OutputType.Format.nChannels == 4 && OutputType.dwChannelMask == QUAD)
  765. device->FmtChans = DevFmtQuad;
  766. else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1)
  767. device->FmtChans = DevFmtX51;
  768. else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1REAR)
  769. device->FmtChans = DevFmtX51Rear;
  770. else if(OutputType.Format.nChannels == 7 && OutputType.dwChannelMask == X6DOT1)
  771. device->FmtChans = DevFmtX61;
  772. else if(OutputType.Format.nChannels == 8 && (OutputType.dwChannelMask == X7DOT1 || OutputType.dwChannelMask == X7DOT1_WIDE))
  773. device->FmtChans = DevFmtX71;
  774. else
  775. ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType.Format.nChannels, OutputType.dwChannelMask);
  776. }
  777. switch(device->FmtChans)
  778. {
  779. case DevFmtMono:
  780. OutputType.Format.nChannels = 1;
  781. OutputType.dwChannelMask = MONO;
  782. break;
  783. case DevFmtAmbi3D:
  784. device->FmtChans = DevFmtStereo;
  785. /*fall-through*/
  786. case DevFmtStereo:
  787. OutputType.Format.nChannels = 2;
  788. OutputType.dwChannelMask = STEREO;
  789. break;
  790. case DevFmtQuad:
  791. OutputType.Format.nChannels = 4;
  792. OutputType.dwChannelMask = QUAD;
  793. break;
  794. case DevFmtX51:
  795. OutputType.Format.nChannels = 6;
  796. OutputType.dwChannelMask = X5DOT1;
  797. break;
  798. case DevFmtX51Rear:
  799. OutputType.Format.nChannels = 6;
  800. OutputType.dwChannelMask = X5DOT1REAR;
  801. break;
  802. case DevFmtX61:
  803. OutputType.Format.nChannels = 7;
  804. OutputType.dwChannelMask = X6DOT1;
  805. break;
  806. case DevFmtX71:
  807. OutputType.Format.nChannels = 8;
  808. OutputType.dwChannelMask = X7DOT1;
  809. break;
  810. }
  811. switch(device->FmtType)
  812. {
  813. case DevFmtByte:
  814. device->FmtType = DevFmtUByte;
  815. /* fall-through */
  816. case DevFmtUByte:
  817. OutputType.Format.wBitsPerSample = 8;
  818. OutputType.Samples.wValidBitsPerSample = 8;
  819. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  820. break;
  821. case DevFmtUShort:
  822. device->FmtType = DevFmtShort;
  823. /* fall-through */
  824. case DevFmtShort:
  825. OutputType.Format.wBitsPerSample = 16;
  826. OutputType.Samples.wValidBitsPerSample = 16;
  827. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  828. break;
  829. case DevFmtUInt:
  830. device->FmtType = DevFmtInt;
  831. /* fall-through */
  832. case DevFmtInt:
  833. OutputType.Format.wBitsPerSample = 32;
  834. OutputType.Samples.wValidBitsPerSample = 32;
  835. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  836. break;
  837. case DevFmtFloat:
  838. OutputType.Format.wBitsPerSample = 32;
  839. OutputType.Samples.wValidBitsPerSample = 32;
  840. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  841. break;
  842. }
  843. OutputType.Format.nSamplesPerSec = device->Frequency;
  844. OutputType.Format.nBlockAlign = OutputType.Format.nChannels *
  845. OutputType.Format.wBitsPerSample / 8;
  846. OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
  847. OutputType.Format.nBlockAlign;
  848. hr = IAudioClient_IsFormatSupported(self->client, AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
  849. if(FAILED(hr))
  850. {
  851. ERR("Failed to check format support: 0x%08lx\n", hr);
  852. hr = IAudioClient_GetMixFormat(self->client, &wfx);
  853. }
  854. if(FAILED(hr))
  855. {
  856. ERR("Failed to find a supported format: 0x%08lx\n", hr);
  857. return hr;
  858. }
  859. if(wfx != NULL)
  860. {
  861. if(!MakeExtensible(&OutputType, wfx))
  862. {
  863. CoTaskMemFree(wfx);
  864. return E_FAIL;
  865. }
  866. CoTaskMemFree(wfx);
  867. wfx = NULL;
  868. device->Frequency = OutputType.Format.nSamplesPerSec;
  869. if(OutputType.Format.nChannels == 1 && OutputType.dwChannelMask == MONO)
  870. device->FmtChans = DevFmtMono;
  871. else if(OutputType.Format.nChannels == 2 && OutputType.dwChannelMask == STEREO)
  872. device->FmtChans = DevFmtStereo;
  873. else if(OutputType.Format.nChannels == 4 && OutputType.dwChannelMask == QUAD)
  874. device->FmtChans = DevFmtQuad;
  875. else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1)
  876. device->FmtChans = DevFmtX51;
  877. else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1REAR)
  878. device->FmtChans = DevFmtX51Rear;
  879. else if(OutputType.Format.nChannels == 7 && OutputType.dwChannelMask == X6DOT1)
  880. device->FmtChans = DevFmtX61;
  881. else if(OutputType.Format.nChannels == 8 && (OutputType.dwChannelMask == X7DOT1 || OutputType.dwChannelMask == X7DOT1_WIDE))
  882. device->FmtChans = DevFmtX71;
  883. else
  884. {
  885. ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels, OutputType.dwChannelMask);
  886. device->FmtChans = DevFmtStereo;
  887. OutputType.Format.nChannels = 2;
  888. OutputType.dwChannelMask = STEREO;
  889. }
  890. if(IsEqualGUID(&OutputType.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))
  891. {
  892. if(OutputType.Format.wBitsPerSample == 8)
  893. device->FmtType = DevFmtUByte;
  894. else if(OutputType.Format.wBitsPerSample == 16)
  895. device->FmtType = DevFmtShort;
  896. else if(OutputType.Format.wBitsPerSample == 32)
  897. device->FmtType = DevFmtInt;
  898. else
  899. {
  900. device->FmtType = DevFmtShort;
  901. OutputType.Format.wBitsPerSample = 16;
  902. }
  903. }
  904. else if(IsEqualGUID(&OutputType.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
  905. {
  906. device->FmtType = DevFmtFloat;
  907. OutputType.Format.wBitsPerSample = 32;
  908. }
  909. else
  910. {
  911. ERR("Unhandled format sub-type\n");
  912. device->FmtType = DevFmtShort;
  913. OutputType.Format.wBitsPerSample = 16;
  914. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  915. }
  916. OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
  917. }
  918. get_device_formfactor(self->mmdev, &formfactor);
  919. device->IsHeadphones = (device->FmtChans == DevFmtStereo &&
  920. (formfactor == Headphones || formfactor == Headset)
  921. );
  922. SetDefaultWFXChannelOrder(device);
  923. hr = IAudioClient_Initialize(self->client, AUDCLNT_SHAREMODE_SHARED,
  924. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  925. buf_time, 0, &OutputType.Format, NULL);
  926. if(FAILED(hr))
  927. {
  928. ERR("Failed to initialize audio client: 0x%08lx\n", hr);
  929. return hr;
  930. }
  931. hr = IAudioClient_GetDevicePeriod(self->client, &min_per, NULL);
  932. if(SUCCEEDED(hr))
  933. {
  934. min_len = (UINT32)ScaleCeil(min_per, device->Frequency, REFTIME_PER_SEC);
  935. /* Find the nearest multiple of the period size to the update size */
  936. if(min_len < device->UpdateSize)
  937. min_len *= (device->UpdateSize + min_len/2)/min_len;
  938. hr = IAudioClient_GetBufferSize(self->client, &buffer_len);
  939. }
  940. if(FAILED(hr))
  941. {
  942. ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
  943. return hr;
  944. }
  945. device->UpdateSize = min_len;
  946. device->NumUpdates = buffer_len / device->UpdateSize;
  947. if(device->NumUpdates <= 1)
  948. {
  949. ERR("Audio client returned buffer_len < period*2; expect break up\n");
  950. device->NumUpdates = 2;
  951. device->UpdateSize = buffer_len / device->NumUpdates;
  952. }
  953. hr = IAudioClient_SetEventHandle(self->client, self->NotifyEvent);
  954. if(FAILED(hr))
  955. {
  956. ERR("Failed to set event handle: 0x%08lx\n", hr);
  957. return hr;
  958. }
  959. return hr;
  960. }
  961. static ALCboolean ALCmmdevPlayback_start(ALCmmdevPlayback *self)
  962. {
  963. ThreadRequest req = { self->MsgEvent, 0 };
  964. HRESULT hr = E_FAIL;
  965. if(PostThreadMessage(ThreadID, WM_USER_StartDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  966. hr = WaitForResponse(&req);
  967. return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE;
  968. }
  969. static HRESULT ALCmmdevPlayback_startProxy(ALCmmdevPlayback *self)
  970. {
  971. HRESULT hr;
  972. void *ptr;
  973. ResetEvent(self->NotifyEvent);
  974. hr = IAudioClient_Start(self->client);
  975. if(FAILED(hr))
  976. ERR("Failed to start audio client: 0x%08lx\n", hr);
  977. if(SUCCEEDED(hr))
  978. hr = IAudioClient_GetService(self->client, &IID_IAudioRenderClient, &ptr);
  979. if(SUCCEEDED(hr))
  980. {
  981. self->render = ptr;
  982. self->killNow = 0;
  983. if(althrd_create(&self->thread, ALCmmdevPlayback_mixerProc, self) != althrd_success)
  984. {
  985. if(self->render)
  986. IAudioRenderClient_Release(self->render);
  987. self->render = NULL;
  988. IAudioClient_Stop(self->client);
  989. ERR("Failed to start thread\n");
  990. hr = E_FAIL;
  991. }
  992. }
  993. return hr;
  994. }
  995. static void ALCmmdevPlayback_stop(ALCmmdevPlayback *self)
  996. {
  997. ThreadRequest req = { self->MsgEvent, 0 };
  998. if(PostThreadMessage(ThreadID, WM_USER_StopDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  999. (void)WaitForResponse(&req);
  1000. }
  1001. static void ALCmmdevPlayback_stopProxy(ALCmmdevPlayback *self)
  1002. {
  1003. int res;
  1004. if(!self->render)
  1005. return;
  1006. self->killNow = 1;
  1007. althrd_join(self->thread, &res);
  1008. IAudioRenderClient_Release(self->render);
  1009. self->render = NULL;
  1010. IAudioClient_Stop(self->client);
  1011. }
  1012. static ClockLatency ALCmmdevPlayback_getClockLatency(ALCmmdevPlayback *self)
  1013. {
  1014. ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
  1015. ClockLatency ret;
  1016. ALCmmdevPlayback_lock(self);
  1017. ret.ClockTime = GetDeviceClockTime(device);
  1018. ret.Latency = self->Padding * DEVICE_CLOCK_RES / device->Frequency;
  1019. ALCmmdevPlayback_unlock(self);
  1020. return ret;
  1021. }
  1022. typedef struct ALCmmdevCapture {
  1023. DERIVE_FROM_TYPE(ALCbackend);
  1024. DERIVE_FROM_TYPE(ALCmmdevProxy);
  1025. WCHAR *devid;
  1026. IMMDevice *mmdev;
  1027. IAudioClient *client;
  1028. IAudioCaptureClient *capture;
  1029. HANDLE NotifyEvent;
  1030. HANDLE MsgEvent;
  1031. ChannelConverter *ChannelConv;
  1032. SampleConverter *SampleConv;
  1033. ll_ringbuffer_t *Ring;
  1034. volatile int killNow;
  1035. althrd_t thread;
  1036. } ALCmmdevCapture;
  1037. static int ALCmmdevCapture_recordProc(void *arg);
  1038. static void ALCmmdevCapture_Construct(ALCmmdevCapture *self, ALCdevice *device);
  1039. static void ALCmmdevCapture_Destruct(ALCmmdevCapture *self);
  1040. static ALCenum ALCmmdevCapture_open(ALCmmdevCapture *self, const ALCchar *name);
  1041. static HRESULT ALCmmdevCapture_openProxy(ALCmmdevCapture *self);
  1042. static void ALCmmdevCapture_close(ALCmmdevCapture *self);
  1043. static void ALCmmdevCapture_closeProxy(ALCmmdevCapture *self);
  1044. static DECLARE_FORWARD(ALCmmdevCapture, ALCbackend, ALCboolean, reset)
  1045. static HRESULT ALCmmdevCapture_resetProxy(ALCmmdevCapture *self);
  1046. static ALCboolean ALCmmdevCapture_start(ALCmmdevCapture *self);
  1047. static HRESULT ALCmmdevCapture_startProxy(ALCmmdevCapture *self);
  1048. static void ALCmmdevCapture_stop(ALCmmdevCapture *self);
  1049. static void ALCmmdevCapture_stopProxy(ALCmmdevCapture *self);
  1050. static ALCenum ALCmmdevCapture_captureSamples(ALCmmdevCapture *self, ALCvoid *buffer, ALCuint samples);
  1051. static ALuint ALCmmdevCapture_availableSamples(ALCmmdevCapture *self);
  1052. static DECLARE_FORWARD(ALCmmdevCapture, ALCbackend, ClockLatency, getClockLatency)
  1053. static DECLARE_FORWARD(ALCmmdevCapture, ALCbackend, void, lock)
  1054. static DECLARE_FORWARD(ALCmmdevCapture, ALCbackend, void, unlock)
  1055. DECLARE_DEFAULT_ALLOCATORS(ALCmmdevCapture)
  1056. DEFINE_ALCMMDEVPROXY_VTABLE(ALCmmdevCapture);
  1057. DEFINE_ALCBACKEND_VTABLE(ALCmmdevCapture);
  1058. static void ALCmmdevCapture_Construct(ALCmmdevCapture *self, ALCdevice *device)
  1059. {
  1060. SET_VTABLE2(ALCmmdevCapture, ALCbackend, self);
  1061. SET_VTABLE2(ALCmmdevCapture, ALCmmdevProxy, self);
  1062. ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
  1063. ALCmmdevProxy_Construct(STATIC_CAST(ALCmmdevProxy, self));
  1064. self->devid = NULL;
  1065. self->mmdev = NULL;
  1066. self->client = NULL;
  1067. self->capture = NULL;
  1068. self->NotifyEvent = NULL;
  1069. self->MsgEvent = NULL;
  1070. self->ChannelConv = NULL;
  1071. self->SampleConv = NULL;
  1072. self->Ring = NULL;
  1073. self->killNow = 0;
  1074. }
  1075. static void ALCmmdevCapture_Destruct(ALCmmdevCapture *self)
  1076. {
  1077. ll_ringbuffer_free(self->Ring);
  1078. self->Ring = NULL;
  1079. DestroySampleConverter(&self->SampleConv);
  1080. DestroyChannelConverter(&self->ChannelConv);
  1081. if(self->NotifyEvent != NULL)
  1082. CloseHandle(self->NotifyEvent);
  1083. self->NotifyEvent = NULL;
  1084. if(self->MsgEvent != NULL)
  1085. CloseHandle(self->MsgEvent);
  1086. self->MsgEvent = NULL;
  1087. free(self->devid);
  1088. self->devid = NULL;
  1089. ALCmmdevProxy_Destruct(STATIC_CAST(ALCmmdevProxy, self));
  1090. ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
  1091. }
  1092. FORCE_ALIGN int ALCmmdevCapture_recordProc(void *arg)
  1093. {
  1094. ALCmmdevCapture *self = arg;
  1095. ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
  1096. ALfloat *samples = NULL;
  1097. size_t samplesmax = 0;
  1098. HRESULT hr;
  1099. hr = CoInitialize(NULL);
  1100. if(FAILED(hr))
  1101. {
  1102. ERR("CoInitialize(NULL) failed: 0x%08lx\n", hr);
  1103. V0(device->Backend,lock)();
  1104. aluHandleDisconnect(device);
  1105. V0(device->Backend,unlock)();
  1106. return 1;
  1107. }
  1108. althrd_setname(althrd_current(), RECORD_THREAD_NAME);
  1109. while(!self->killNow)
  1110. {
  1111. UINT32 avail;
  1112. DWORD res;
  1113. hr = IAudioCaptureClient_GetNextPacketSize(self->capture, &avail);
  1114. if(FAILED(hr))
  1115. ERR("Failed to get next packet size: 0x%08lx\n", hr);
  1116. else if(avail > 0)
  1117. {
  1118. UINT32 numsamples;
  1119. DWORD flags;
  1120. BYTE *rdata;
  1121. hr = IAudioCaptureClient_GetBuffer(self->capture,
  1122. &rdata, &numsamples, &flags, NULL, NULL
  1123. );
  1124. if(FAILED(hr))
  1125. ERR("Failed to get capture buffer: 0x%08lx\n", hr);
  1126. else
  1127. {
  1128. ll_ringbuffer_data_t data[2];
  1129. size_t dstframes = 0;
  1130. if(self->ChannelConv)
  1131. {
  1132. if(samplesmax < numsamples)
  1133. {
  1134. size_t newmax = RoundUp(numsamples, 4096);
  1135. ALfloat *tmp = al_calloc(DEF_ALIGN, newmax*2*sizeof(ALfloat));
  1136. al_free(samples);
  1137. samples = tmp;
  1138. samplesmax = newmax;
  1139. }
  1140. ChannelConverterInput(self->ChannelConv, rdata, samples, numsamples);
  1141. rdata = (BYTE*)samples;
  1142. }
  1143. ll_ringbuffer_get_write_vector(self->Ring, data);
  1144. if(self->SampleConv)
  1145. {
  1146. const ALvoid *srcdata = rdata;
  1147. ALsizei srcframes = numsamples;
  1148. dstframes = SampleConverterInput(self->SampleConv,
  1149. &srcdata, &srcframes, data[0].buf, data[0].len
  1150. );
  1151. if(srcframes > 0 && dstframes == data[0].len && data[1].len > 0)
  1152. {
  1153. /* If some source samples remain, all of the first dest
  1154. * block was filled, and there's space in the second
  1155. * dest block, do another run for the second block.
  1156. */
  1157. dstframes += SampleConverterInput(self->SampleConv,
  1158. &srcdata, &srcframes, data[1].buf, data[1].len
  1159. );
  1160. }
  1161. }
  1162. else
  1163. {
  1164. size_t framesize = FrameSizeFromDevFmt(device->FmtChans, device->FmtType,
  1165. device->AmbiOrder);
  1166. ALuint len1 = minu(data[0].len, numsamples);
  1167. ALuint len2 = minu(data[1].len, numsamples-len1);
  1168. memcpy(data[0].buf, rdata, len1*framesize);
  1169. if(len2 > 0)
  1170. memcpy(data[1].buf, rdata+len1*framesize, len2*framesize);
  1171. dstframes = len1 + len2;
  1172. }
  1173. ll_ringbuffer_write_advance(self->Ring, dstframes);
  1174. hr = IAudioCaptureClient_ReleaseBuffer(self->capture, numsamples);
  1175. if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
  1176. }
  1177. }
  1178. if(FAILED(hr))
  1179. {
  1180. V0(device->Backend,lock)();
  1181. aluHandleDisconnect(device);
  1182. V0(device->Backend,unlock)();
  1183. break;
  1184. }
  1185. res = WaitForSingleObjectEx(self->NotifyEvent, 2000, FALSE);
  1186. if(res != WAIT_OBJECT_0)
  1187. ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
  1188. }
  1189. al_free(samples);
  1190. samples = NULL;
  1191. samplesmax = 0;
  1192. CoUninitialize();
  1193. return 0;
  1194. }
  1195. static ALCenum ALCmmdevCapture_open(ALCmmdevCapture *self, const ALCchar *deviceName)
  1196. {
  1197. HRESULT hr = S_OK;
  1198. self->NotifyEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
  1199. self->MsgEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
  1200. if(self->NotifyEvent == NULL || self->MsgEvent == NULL)
  1201. {
  1202. ERR("Failed to create message events: %lu\n", GetLastError());
  1203. hr = E_FAIL;
  1204. }
  1205. if(SUCCEEDED(hr))
  1206. {
  1207. if(deviceName)
  1208. {
  1209. const DevMap *iter;
  1210. if(VECTOR_SIZE(CaptureDevices) == 0)
  1211. {
  1212. ThreadRequest req = { self->MsgEvent, 0 };
  1213. if(PostThreadMessage(ThreadID, WM_USER_Enumerate, (WPARAM)&req, CAPTURE_DEVICE_PROBE))
  1214. (void)WaitForResponse(&req);
  1215. }
  1216. hr = E_FAIL;
  1217. #define MATCH_NAME(i) (alstr_cmp_cstr((i)->name, deviceName) == 0 || \
  1218. alstr_cmp_cstr((i)->endpoint_guid, deviceName) == 0)
  1219. VECTOR_FIND_IF(iter, const DevMap, CaptureDevices, MATCH_NAME);
  1220. #undef MATCH_NAME
  1221. if(iter == VECTOR_END(CaptureDevices))
  1222. {
  1223. int len;
  1224. if((len=MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, NULL, 0)) > 0)
  1225. {
  1226. WCHAR *wname = calloc(sizeof(WCHAR), len);
  1227. MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, wname, len);
  1228. #define MATCH_NAME(i) (wcscmp((i)->devid, wname) == 0)
  1229. VECTOR_FIND_IF(iter, const DevMap, CaptureDevices, MATCH_NAME);
  1230. #undef MATCH_NAME
  1231. free(wname);
  1232. }
  1233. }
  1234. if(iter == VECTOR_END(CaptureDevices))
  1235. WARN("Failed to find device name matching \"%s\"\n", deviceName);
  1236. else
  1237. {
  1238. ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
  1239. self->devid = strdupW(iter->devid);
  1240. alstr_copy(&device->DeviceName, iter->name);
  1241. hr = S_OK;
  1242. }
  1243. }
  1244. }
  1245. if(SUCCEEDED(hr))
  1246. {
  1247. ThreadRequest req = { self->MsgEvent, 0 };
  1248. hr = E_FAIL;
  1249. if(PostThreadMessage(ThreadID, WM_USER_OpenDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  1250. hr = WaitForResponse(&req);
  1251. else
  1252. ERR("Failed to post thread message: %lu\n", GetLastError());
  1253. }
  1254. if(FAILED(hr))
  1255. {
  1256. if(self->NotifyEvent != NULL)
  1257. CloseHandle(self->NotifyEvent);
  1258. self->NotifyEvent = NULL;
  1259. if(self->MsgEvent != NULL)
  1260. CloseHandle(self->MsgEvent);
  1261. self->MsgEvent = NULL;
  1262. free(self->devid);
  1263. self->devid = NULL;
  1264. ERR("Device init failed: 0x%08lx\n", hr);
  1265. return ALC_INVALID_VALUE;
  1266. }
  1267. else
  1268. {
  1269. ThreadRequest req = { self->MsgEvent, 0 };
  1270. hr = E_FAIL;
  1271. if(PostThreadMessage(ThreadID, WM_USER_ResetDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  1272. hr = WaitForResponse(&req);
  1273. else
  1274. ERR("Failed to post thread message: %lu\n", GetLastError());
  1275. if(FAILED(hr))
  1276. {
  1277. ALCmmdevCapture_close(self);
  1278. if(hr == E_OUTOFMEMORY)
  1279. return ALC_OUT_OF_MEMORY;
  1280. return ALC_INVALID_VALUE;
  1281. }
  1282. }
  1283. return ALC_NO_ERROR;
  1284. }
  1285. static HRESULT ALCmmdevCapture_openProxy(ALCmmdevCapture *self)
  1286. {
  1287. ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
  1288. void *ptr;
  1289. HRESULT hr;
  1290. hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &ptr);
  1291. if(SUCCEEDED(hr))
  1292. {
  1293. IMMDeviceEnumerator *Enumerator = ptr;
  1294. if(!self->devid)
  1295. hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(Enumerator, eCapture, eMultimedia, &self->mmdev);
  1296. else
  1297. hr = IMMDeviceEnumerator_GetDevice(Enumerator, self->devid, &self->mmdev);
  1298. IMMDeviceEnumerator_Release(Enumerator);
  1299. Enumerator = NULL;
  1300. }
  1301. if(SUCCEEDED(hr))
  1302. hr = IMMDevice_Activate(self->mmdev, &IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, &ptr);
  1303. if(SUCCEEDED(hr))
  1304. {
  1305. self->client = ptr;
  1306. if(alstr_empty(device->DeviceName))
  1307. get_device_name_and_guid(self->mmdev, &device->DeviceName, NULL);
  1308. }
  1309. if(FAILED(hr))
  1310. {
  1311. if(self->mmdev)
  1312. IMMDevice_Release(self->mmdev);
  1313. self->mmdev = NULL;
  1314. }
  1315. return hr;
  1316. }
  1317. static void ALCmmdevCapture_close(ALCmmdevCapture *self)
  1318. {
  1319. ThreadRequest req = { self->MsgEvent, 0 };
  1320. if(PostThreadMessage(ThreadID, WM_USER_CloseDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  1321. (void)WaitForResponse(&req);
  1322. ll_ringbuffer_free(self->Ring);
  1323. self->Ring = NULL;
  1324. CloseHandle(self->MsgEvent);
  1325. self->MsgEvent = NULL;
  1326. CloseHandle(self->NotifyEvent);
  1327. self->NotifyEvent = NULL;
  1328. free(self->devid);
  1329. self->devid = NULL;
  1330. }
  1331. static void ALCmmdevCapture_closeProxy(ALCmmdevCapture *self)
  1332. {
  1333. if(self->client)
  1334. IAudioClient_Release(self->client);
  1335. self->client = NULL;
  1336. if(self->mmdev)
  1337. IMMDevice_Release(self->mmdev);
  1338. self->mmdev = NULL;
  1339. }
  1340. static HRESULT ALCmmdevCapture_resetProxy(ALCmmdevCapture *self)
  1341. {
  1342. ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
  1343. WAVEFORMATEXTENSIBLE OutputType;
  1344. WAVEFORMATEX *wfx = NULL;
  1345. enum DevFmtType srcType;
  1346. REFERENCE_TIME buf_time;
  1347. UINT32 buffer_len;
  1348. void *ptr = NULL;
  1349. HRESULT hr;
  1350. if(self->client)
  1351. IAudioClient_Release(self->client);
  1352. self->client = NULL;
  1353. hr = IMMDevice_Activate(self->mmdev, &IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, &ptr);
  1354. if(FAILED(hr))
  1355. {
  1356. ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
  1357. return hr;
  1358. }
  1359. self->client = ptr;
  1360. buf_time = ScaleCeil(device->UpdateSize*device->NumUpdates, REFTIME_PER_SEC,
  1361. device->Frequency);
  1362. // Make sure buffer is at least 100ms in size
  1363. buf_time = maxu64(buf_time, REFTIME_PER_SEC/10);
  1364. device->UpdateSize = (ALuint)ScaleCeil(buf_time, device->Frequency, REFTIME_PER_SEC) /
  1365. device->NumUpdates;
  1366. OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  1367. switch(device->FmtChans)
  1368. {
  1369. case DevFmtMono:
  1370. OutputType.Format.nChannels = 1;
  1371. OutputType.dwChannelMask = MONO;
  1372. break;
  1373. case DevFmtStereo:
  1374. OutputType.Format.nChannels = 2;
  1375. OutputType.dwChannelMask = STEREO;
  1376. break;
  1377. case DevFmtQuad:
  1378. OutputType.Format.nChannels = 4;
  1379. OutputType.dwChannelMask = QUAD;
  1380. break;
  1381. case DevFmtX51:
  1382. OutputType.Format.nChannels = 6;
  1383. OutputType.dwChannelMask = X5DOT1;
  1384. break;
  1385. case DevFmtX51Rear:
  1386. OutputType.Format.nChannels = 6;
  1387. OutputType.dwChannelMask = X5DOT1REAR;
  1388. break;
  1389. case DevFmtX61:
  1390. OutputType.Format.nChannels = 7;
  1391. OutputType.dwChannelMask = X6DOT1;
  1392. break;
  1393. case DevFmtX71:
  1394. OutputType.Format.nChannels = 8;
  1395. OutputType.dwChannelMask = X7DOT1;
  1396. break;
  1397. case DevFmtAmbi3D:
  1398. return E_FAIL;
  1399. }
  1400. switch(device->FmtType)
  1401. {
  1402. /* NOTE: Signedness doesn't matter, the converter will handle it. */
  1403. case DevFmtByte:
  1404. case DevFmtUByte:
  1405. OutputType.Format.wBitsPerSample = 8;
  1406. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1407. break;
  1408. case DevFmtShort:
  1409. case DevFmtUShort:
  1410. OutputType.Format.wBitsPerSample = 16;
  1411. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1412. break;
  1413. case DevFmtInt:
  1414. case DevFmtUInt:
  1415. OutputType.Format.wBitsPerSample = 32;
  1416. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  1417. break;
  1418. case DevFmtFloat:
  1419. OutputType.Format.wBitsPerSample = 32;
  1420. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  1421. break;
  1422. }
  1423. OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
  1424. OutputType.Format.nSamplesPerSec = device->Frequency;
  1425. OutputType.Format.nBlockAlign = OutputType.Format.nChannels *
  1426. OutputType.Format.wBitsPerSample / 8;
  1427. OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
  1428. OutputType.Format.nBlockAlign;
  1429. OutputType.Format.cbSize = sizeof(OutputType) - sizeof(OutputType.Format);
  1430. hr = IAudioClient_IsFormatSupported(self->client,
  1431. AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx
  1432. );
  1433. if(FAILED(hr))
  1434. {
  1435. ERR("Failed to check format support: 0x%08lx\n", hr);
  1436. return hr;
  1437. }
  1438. DestroySampleConverter(&self->SampleConv);
  1439. DestroyChannelConverter(&self->ChannelConv);
  1440. if(wfx != NULL)
  1441. {
  1442. if(!(wfx->nChannels == OutputType.Format.nChannels ||
  1443. (wfx->nChannels == 1 && OutputType.Format.nChannels == 2) ||
  1444. (wfx->nChannels == 2 && OutputType.Format.nChannels == 1)))
  1445. {
  1446. ERR("Failed to get matching format, wanted: %s %s %uhz, got: %d channel%s %d-bit %luhz\n",
  1447. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  1448. device->Frequency, wfx->nChannels, (wfx->nChannels==1)?"":"s", wfx->wBitsPerSample,
  1449. wfx->nSamplesPerSec);
  1450. CoTaskMemFree(wfx);
  1451. return E_FAIL;
  1452. }
  1453. if(!MakeExtensible(&OutputType, wfx))
  1454. {
  1455. CoTaskMemFree(wfx);
  1456. return E_FAIL;
  1457. }
  1458. CoTaskMemFree(wfx);
  1459. wfx = NULL;
  1460. }
  1461. if(IsEqualGUID(&OutputType.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))
  1462. {
  1463. if(OutputType.Format.wBitsPerSample == 8)
  1464. srcType = DevFmtUByte;
  1465. else if(OutputType.Format.wBitsPerSample == 16)
  1466. srcType = DevFmtShort;
  1467. else if(OutputType.Format.wBitsPerSample == 32)
  1468. srcType = DevFmtInt;
  1469. else
  1470. {
  1471. ERR("Unhandled integer bit depth: %d\n", OutputType.Format.wBitsPerSample);
  1472. return E_FAIL;
  1473. }
  1474. }
  1475. else if(IsEqualGUID(&OutputType.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
  1476. {
  1477. if(OutputType.Format.wBitsPerSample == 32)
  1478. srcType = DevFmtFloat;
  1479. else
  1480. {
  1481. ERR("Unhandled float bit depth: %d\n", OutputType.Format.wBitsPerSample);
  1482. return E_FAIL;
  1483. }
  1484. }
  1485. else
  1486. {
  1487. ERR("Unhandled format sub-type\n");
  1488. return E_FAIL;
  1489. }
  1490. if(device->FmtChans == DevFmtMono && OutputType.Format.nChannels == 2)
  1491. {
  1492. self->ChannelConv = CreateChannelConverter(srcType, DevFmtStereo,
  1493. device->FmtChans);
  1494. if(!self->ChannelConv)
  1495. {
  1496. ERR("Failed to create %s stereo-to-mono converter\n", DevFmtTypeString(srcType));
  1497. return E_FAIL;
  1498. }
  1499. TRACE("Created %s stereo-to-mono converter\n", DevFmtTypeString(srcType));
  1500. /* The channel converter always outputs float, so change the input type
  1501. * for the resampler/type-converter.
  1502. */
  1503. srcType = DevFmtFloat;
  1504. }
  1505. else if(device->FmtChans == DevFmtStereo && OutputType.Format.nChannels == 1)
  1506. {
  1507. self->ChannelConv = CreateChannelConverter(srcType, DevFmtMono,
  1508. device->FmtChans);
  1509. if(!self->ChannelConv)
  1510. {
  1511. ERR("Failed to create %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
  1512. return E_FAIL;
  1513. }
  1514. TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
  1515. srcType = DevFmtFloat;
  1516. }
  1517. if(device->Frequency != OutputType.Format.nSamplesPerSec || device->FmtType != srcType)
  1518. {
  1519. self->SampleConv = CreateSampleConverter(
  1520. srcType, device->FmtType, ChannelsFromDevFmt(device->FmtChans, device->AmbiOrder),
  1521. OutputType.Format.nSamplesPerSec, device->Frequency
  1522. );
  1523. if(!self->SampleConv)
  1524. {
  1525. ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
  1526. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  1527. device->Frequency, DevFmtTypeString(srcType), OutputType.Format.nSamplesPerSec);
  1528. return E_FAIL;
  1529. }
  1530. TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
  1531. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  1532. device->Frequency, DevFmtTypeString(srcType), OutputType.Format.nSamplesPerSec);
  1533. }
  1534. hr = IAudioClient_Initialize(self->client,
  1535. AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  1536. buf_time, 0, &OutputType.Format, NULL
  1537. );
  1538. if(FAILED(hr))
  1539. {
  1540. ERR("Failed to initialize audio client: 0x%08lx\n", hr);
  1541. return hr;
  1542. }
  1543. hr = IAudioClient_GetBufferSize(self->client, &buffer_len);
  1544. if(FAILED(hr))
  1545. {
  1546. ERR("Failed to get buffer size: 0x%08lx\n", hr);
  1547. return hr;
  1548. }
  1549. buffer_len = maxu(device->UpdateSize*device->NumUpdates + 1, buffer_len);
  1550. ll_ringbuffer_free(self->Ring);
  1551. self->Ring = ll_ringbuffer_create(buffer_len,
  1552. FrameSizeFromDevFmt(device->FmtChans, device->FmtType, device->AmbiOrder)
  1553. );
  1554. if(!self->Ring)
  1555. {
  1556. ERR("Failed to allocate capture ring buffer\n");
  1557. return E_OUTOFMEMORY;
  1558. }
  1559. hr = IAudioClient_SetEventHandle(self->client, self->NotifyEvent);
  1560. if(FAILED(hr))
  1561. {
  1562. ERR("Failed to set event handle: 0x%08lx\n", hr);
  1563. return hr;
  1564. }
  1565. return hr;
  1566. }
  1567. static ALCboolean ALCmmdevCapture_start(ALCmmdevCapture *self)
  1568. {
  1569. ThreadRequest req = { self->MsgEvent, 0 };
  1570. HRESULT hr = E_FAIL;
  1571. if(PostThreadMessage(ThreadID, WM_USER_StartDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  1572. hr = WaitForResponse(&req);
  1573. return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE;
  1574. }
  1575. static HRESULT ALCmmdevCapture_startProxy(ALCmmdevCapture *self)
  1576. {
  1577. HRESULT hr;
  1578. void *ptr;
  1579. ResetEvent(self->NotifyEvent);
  1580. hr = IAudioClient_Start(self->client);
  1581. if(FAILED(hr))
  1582. {
  1583. ERR("Failed to start audio client: 0x%08lx\n", hr);
  1584. return hr;
  1585. }
  1586. hr = IAudioClient_GetService(self->client, &IID_IAudioCaptureClient, &ptr);
  1587. if(SUCCEEDED(hr))
  1588. {
  1589. self->capture = ptr;
  1590. self->killNow = 0;
  1591. if(althrd_create(&self->thread, ALCmmdevCapture_recordProc, self) != althrd_success)
  1592. {
  1593. ERR("Failed to start thread\n");
  1594. IAudioCaptureClient_Release(self->capture);
  1595. self->capture = NULL;
  1596. hr = E_FAIL;
  1597. }
  1598. }
  1599. if(FAILED(hr))
  1600. {
  1601. IAudioClient_Stop(self->client);
  1602. IAudioClient_Reset(self->client);
  1603. }
  1604. return hr;
  1605. }
  1606. static void ALCmmdevCapture_stop(ALCmmdevCapture *self)
  1607. {
  1608. ThreadRequest req = { self->MsgEvent, 0 };
  1609. if(PostThreadMessage(ThreadID, WM_USER_StopDevice, (WPARAM)&req, (LPARAM)STATIC_CAST(ALCmmdevProxy, self)))
  1610. (void)WaitForResponse(&req);
  1611. }
  1612. static void ALCmmdevCapture_stopProxy(ALCmmdevCapture *self)
  1613. {
  1614. int res;
  1615. if(!self->capture)
  1616. return;
  1617. self->killNow = 1;
  1618. althrd_join(self->thread, &res);
  1619. IAudioCaptureClient_Release(self->capture);
  1620. self->capture = NULL;
  1621. IAudioClient_Stop(self->client);
  1622. IAudioClient_Reset(self->client);
  1623. }
  1624. ALuint ALCmmdevCapture_availableSamples(ALCmmdevCapture *self)
  1625. {
  1626. return (ALuint)ll_ringbuffer_read_space(self->Ring);
  1627. }
  1628. ALCenum ALCmmdevCapture_captureSamples(ALCmmdevCapture *self, ALCvoid *buffer, ALCuint samples)
  1629. {
  1630. if(ALCmmdevCapture_availableSamples(self) < samples)
  1631. return ALC_INVALID_VALUE;
  1632. ll_ringbuffer_read(self->Ring, buffer, samples);
  1633. return ALC_NO_ERROR;
  1634. }
  1635. static inline void AppendAllDevicesList2(const DevMap *entry)
  1636. { AppendAllDevicesList(alstr_get_cstr(entry->name)); }
  1637. static inline void AppendCaptureDeviceList2(const DevMap *entry)
  1638. { AppendCaptureDeviceList(alstr_get_cstr(entry->name)); }
  1639. typedef struct ALCmmdevBackendFactory {
  1640. DERIVE_FROM_TYPE(ALCbackendFactory);
  1641. } ALCmmdevBackendFactory;
  1642. #define ALCMMDEVBACKENDFACTORY_INITIALIZER { { GET_VTABLE2(ALCmmdevBackendFactory, ALCbackendFactory) } }
  1643. static ALCboolean ALCmmdevBackendFactory_init(ALCmmdevBackendFactory *self);
  1644. static void ALCmmdevBackendFactory_deinit(ALCmmdevBackendFactory *self);
  1645. static ALCboolean ALCmmdevBackendFactory_querySupport(ALCmmdevBackendFactory *self, ALCbackend_Type type);
  1646. static void ALCmmdevBackendFactory_probe(ALCmmdevBackendFactory *self, enum DevProbe type);
  1647. static ALCbackend* ALCmmdevBackendFactory_createBackend(ALCmmdevBackendFactory *self, ALCdevice *device, ALCbackend_Type type);
  1648. DEFINE_ALCBACKENDFACTORY_VTABLE(ALCmmdevBackendFactory);
  1649. static BOOL MMDevApiLoad(void)
  1650. {
  1651. static HRESULT InitResult;
  1652. if(!ThreadHdl)
  1653. {
  1654. ThreadRequest req;
  1655. InitResult = E_FAIL;
  1656. req.FinishedEvt = CreateEventW(NULL, FALSE, FALSE, NULL);
  1657. if(req.FinishedEvt == NULL)
  1658. ERR("Failed to create event: %lu\n", GetLastError());
  1659. else
  1660. {
  1661. ThreadHdl = CreateThread(NULL, 0, ALCmmdevProxy_messageHandler, &req, 0, &ThreadID);
  1662. if(ThreadHdl != NULL)
  1663. InitResult = WaitForResponse(&req);
  1664. CloseHandle(req.FinishedEvt);
  1665. }
  1666. }
  1667. return SUCCEEDED(InitResult);
  1668. }
  1669. static ALCboolean ALCmmdevBackendFactory_init(ALCmmdevBackendFactory* UNUSED(self))
  1670. {
  1671. VECTOR_INIT(PlaybackDevices);
  1672. VECTOR_INIT(CaptureDevices);
  1673. if(!MMDevApiLoad())
  1674. return ALC_FALSE;
  1675. return ALC_TRUE;
  1676. }
  1677. static void ALCmmdevBackendFactory_deinit(ALCmmdevBackendFactory* UNUSED(self))
  1678. {
  1679. clear_devlist(&PlaybackDevices);
  1680. VECTOR_DEINIT(PlaybackDevices);
  1681. clear_devlist(&CaptureDevices);
  1682. VECTOR_DEINIT(CaptureDevices);
  1683. if(ThreadHdl)
  1684. {
  1685. TRACE("Sending WM_QUIT to Thread %04lx\n", ThreadID);
  1686. PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
  1687. CloseHandle(ThreadHdl);
  1688. ThreadHdl = NULL;
  1689. }
  1690. }
  1691. static ALCboolean ALCmmdevBackendFactory_querySupport(ALCmmdevBackendFactory* UNUSED(self), ALCbackend_Type type)
  1692. {
  1693. /* TODO: Disable capture with mmdevapi for now, since it doesn't do any
  1694. * rechanneling or resampling; if the device is configured for 48000hz
  1695. * stereo input, for example, and the app asks for 22050hz mono,
  1696. * initialization will fail.
  1697. */
  1698. if(type == ALCbackend_Playback || type == ALCbackend_Capture)
  1699. return ALC_TRUE;
  1700. return ALC_FALSE;
  1701. }
  1702. static void ALCmmdevBackendFactory_probe(ALCmmdevBackendFactory* UNUSED(self), enum DevProbe type)
  1703. {
  1704. ThreadRequest req = { NULL, 0 };
  1705. req.FinishedEvt = CreateEventW(NULL, FALSE, FALSE, NULL);
  1706. if(req.FinishedEvt == NULL)
  1707. ERR("Failed to create event: %lu\n", GetLastError());
  1708. else
  1709. {
  1710. HRESULT hr = E_FAIL;
  1711. if(PostThreadMessage(ThreadID, WM_USER_Enumerate, (WPARAM)&req, type))
  1712. hr = WaitForResponse(&req);
  1713. if(SUCCEEDED(hr)) switch(type)
  1714. {
  1715. case ALL_DEVICE_PROBE:
  1716. VECTOR_FOR_EACH(const DevMap, PlaybackDevices, AppendAllDevicesList2);
  1717. break;
  1718. case CAPTURE_DEVICE_PROBE:
  1719. VECTOR_FOR_EACH(const DevMap, CaptureDevices, AppendCaptureDeviceList2);
  1720. break;
  1721. }
  1722. CloseHandle(req.FinishedEvt);
  1723. req.FinishedEvt = NULL;
  1724. }
  1725. }
  1726. static ALCbackend* ALCmmdevBackendFactory_createBackend(ALCmmdevBackendFactory* UNUSED(self), ALCdevice *device, ALCbackend_Type type)
  1727. {
  1728. if(type == ALCbackend_Playback)
  1729. {
  1730. ALCmmdevPlayback *backend;
  1731. NEW_OBJ(backend, ALCmmdevPlayback)(device);
  1732. if(!backend) return NULL;
  1733. return STATIC_CAST(ALCbackend, backend);
  1734. }
  1735. if(type == ALCbackend_Capture)
  1736. {
  1737. ALCmmdevCapture *backend;
  1738. NEW_OBJ(backend, ALCmmdevCapture)(device);
  1739. if(!backend) return NULL;
  1740. return STATIC_CAST(ALCbackend, backend);
  1741. }
  1742. return NULL;
  1743. }
  1744. ALCbackendFactory *ALCmmdevBackendFactory_getFactory(void)
  1745. {
  1746. static ALCmmdevBackendFactory factory = ALCMMDEVBACKENDFACTORY_INITIALIZER;
  1747. return STATIC_CAST(ALCbackendFactory, &factory);
  1748. }