mmdevapi.c 56 KB

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