kernel32/tests: Better check the NT path returned by QueryFullProcessImageName().
[wine] / dlls / dsound / dsound_main.c
1 /*                      DirectSound
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2002 TransGaming Technologies, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  * Most thread locking is complete. There may be a few race
22  * conditions still lurking.
23  *
24  * TODO:
25  *      Implement SetCooperativeLevel properly (need to address focus issues)
26  *      Implement DirectSound3DBuffers (stubs in place)
27  *      Use hardware 3D support if available
28  *      Add critical section locking inside Release and AddRef methods
29  *      Handle static buffers - put those in hardware, non-static not in hardware
30  *      Hardware DuplicateSoundBuffer
31  *      Proper volume calculation for 3d buffers
32  *      Remove DS_HEL_FRAGS and use mixer fragment length for it
33  */
34
35 #include <stdarg.h>
36
37 #define COBJMACROS
38 #define NONAMELESSSTRUCT
39 #define NONAMELESSUNION
40 #include "windef.h"
41 #include "winbase.h"
42 #include "winuser.h"
43 #include "winnls.h"
44 #include "winreg.h"
45 #include "mmsystem.h"
46 #include "winternl.h"
47 #include "mmddk.h"
48 #include "wine/debug.h"
49 #include "dsound.h"
50 #include "dsconf.h"
51 #include "ks.h"
52 #include "rpcproxy.h"
53 #include "rpc.h"
54 #include "rpcndr.h"
55 #include "unknwn.h"
56 #include "oleidl.h"
57 #include "shobjidl.h"
58
59 #include "initguid.h"
60 #include "ksmedia.h"
61 #include "propkey.h"
62 #include "devpkey.h"
63
64 #include "dsound_private.h"
65
66 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
67
68 struct list DSOUND_renderers = LIST_INIT(DSOUND_renderers);
69 CRITICAL_SECTION DSOUND_renderers_lock;
70
71 struct list DSOUND_capturers = LIST_INIT(DSOUND_capturers);
72 CRITICAL_SECTION DSOUND_capturers_lock;
73
74 GUID                    DSOUND_renderer_guids[MAXWAVEDRIVERS];
75 GUID                    DSOUND_capture_guids[MAXWAVEDRIVERS];
76
77 static IMMDeviceEnumerator *g_devenum;
78 static CRITICAL_SECTION g_devenum_lock;
79 static HANDLE g_devenum_thread;
80
81 WCHAR wine_vxd_drv[] = { 'w','i','n','e','m','m','.','v','x','d', 0 };
82
83 HRESULT mmErr(UINT err)
84 {
85         switch(err) {
86         case MMSYSERR_NOERROR:
87                 return DS_OK;
88         case MMSYSERR_ALLOCATED:
89                 return DSERR_ALLOCATED;
90         case MMSYSERR_ERROR:
91         case MMSYSERR_INVALHANDLE:
92         case WAVERR_STILLPLAYING:
93                 return DSERR_GENERIC; /* FIXME */
94         case MMSYSERR_NODRIVER:
95                 return DSERR_NODRIVER;
96         case MMSYSERR_NOMEM:
97                 return DSERR_OUTOFMEMORY;
98         case MMSYSERR_INVALPARAM:
99         case WAVERR_BADFORMAT:
100         case WAVERR_UNPREPARED:
101                 return DSERR_INVALIDPARAM;
102         case MMSYSERR_NOTSUPPORTED:
103                 return DSERR_UNSUPPORTED;
104         default:
105                 FIXME("Unknown MMSYS error %d\n",err);
106                 return DSERR_GENERIC;
107         }
108 }
109
110 /* All default settings, you most likely don't want to touch these, see wiki on UsefulRegistryKeys */
111 int ds_emuldriver = 0;
112 int ds_hel_buflen = 32768 * 2;
113 int ds_snd_queue_max = 10;
114 int ds_snd_shadow_maxsize = 2;
115 int ds_default_sample_rate = 44100;
116 int ds_default_bits_per_sample = 16;
117 static int ds_default_playback;
118 static int ds_default_capture;
119 static HINSTANCE instance;
120
121 /*
122  * Get a config key from either the app-specific or the default config
123  */
124
125 static inline DWORD get_config_key( HKEY defkey, HKEY appkey, const char *name,
126                                     char *buffer, DWORD size )
127 {
128     if (appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE)buffer, &size )) return 0;
129     if (defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE)buffer, &size )) return 0;
130     return ERROR_FILE_NOT_FOUND;
131 }
132
133
134 /*
135  * Setup the dsound options.
136  */
137
138 void setup_dsound_options(void)
139 {
140     char buffer[MAX_PATH+16];
141     HKEY hkey, appkey = 0;
142     DWORD len;
143
144     buffer[MAX_PATH]='\0';
145
146     /* @@ Wine registry key: HKCU\Software\Wine\DirectSound */
147     if (RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\DirectSound", &hkey )) hkey = 0;
148
149     len = GetModuleFileNameA( 0, buffer, MAX_PATH );
150     if (len && len < MAX_PATH)
151     {
152         HKEY tmpkey;
153         /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\DirectSound */
154         if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
155         {
156             char *p, *appname = buffer;
157             if ((p = strrchr( appname, '/' ))) appname = p + 1;
158             if ((p = strrchr( appname, '\\' ))) appname = p + 1;
159             strcat( appname, "\\DirectSound" );
160             TRACE("appname = [%s]\n", appname);
161             if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
162             RegCloseKey( tmpkey );
163         }
164     }
165
166     /* get options */
167
168     if (!get_config_key( hkey, appkey, "EmulDriver", buffer, MAX_PATH ))
169         ds_emuldriver = strcmp(buffer, "N");
170
171     if (!get_config_key( hkey, appkey, "HelBuflen", buffer, MAX_PATH ))
172         ds_hel_buflen = atoi(buffer);
173
174     if (!get_config_key( hkey, appkey, "SndQueueMax", buffer, MAX_PATH ))
175         ds_snd_queue_max = atoi(buffer);
176
177     if (!get_config_key( hkey, appkey, "DefaultPlayback", buffer, MAX_PATH ))
178         ds_default_playback = atoi(buffer);
179
180     if (!get_config_key( hkey, appkey, "MaxShadowSize", buffer, MAX_PATH ))
181         ds_snd_shadow_maxsize = atoi(buffer);
182
183     if (!get_config_key( hkey, appkey, "DefaultCapture", buffer, MAX_PATH ))
184         ds_default_capture = atoi(buffer);
185
186     if (!get_config_key( hkey, appkey, "DefaultSampleRate", buffer, MAX_PATH ))
187         ds_default_sample_rate = atoi(buffer);
188
189     if (!get_config_key( hkey, appkey, "DefaultBitsPerSample", buffer, MAX_PATH ))
190         ds_default_bits_per_sample = atoi(buffer);
191
192     if (appkey) RegCloseKey( appkey );
193     if (hkey) RegCloseKey( hkey );
194
195     TRACE("ds_emuldriver = %d\n", ds_emuldriver);
196     TRACE("ds_hel_buflen = %d\n", ds_hel_buflen);
197     TRACE("ds_snd_queue_max = %d\n", ds_snd_queue_max);
198     TRACE("ds_default_playback = %d\n", ds_default_playback);
199     TRACE("ds_default_capture = %d\n", ds_default_capture);
200     TRACE("ds_default_sample_rate = %d\n", ds_default_sample_rate);
201     TRACE("ds_default_bits_per_sample = %d\n", ds_default_bits_per_sample);
202     TRACE("ds_snd_shadow_maxsize = %d\n", ds_snd_shadow_maxsize);
203 }
204
205 static const char * get_device_id(LPCGUID pGuid)
206 {
207     if (IsEqualGUID(&DSDEVID_DefaultPlayback, pGuid))
208         return "DSDEVID_DefaultPlayback";
209     else if (IsEqualGUID(&DSDEVID_DefaultVoicePlayback, pGuid))
210         return "DSDEVID_DefaultVoicePlayback";
211     else if (IsEqualGUID(&DSDEVID_DefaultCapture, pGuid))
212         return "DSDEVID_DefaultCapture";
213     else if (IsEqualGUID(&DSDEVID_DefaultVoiceCapture, pGuid))
214         return "DSDEVID_DefaultVoiceCapture";
215     return debugstr_guid(pGuid);
216 }
217
218 /* The MMDeviceEnumerator object has to be created & destroyed
219  * from the same thread. */
220 static DWORD WINAPI devenum_thread_proc(void *arg)
221 {
222     HANDLE evt = arg;
223     HRESULT hr;
224     MSG msg;
225
226     hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
227     if(FAILED(hr)){
228          ERR("CoInitializeEx failed: %08x\n", hr);
229          return 1;
230     }
231
232     hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL,
233             CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, (void**)&g_devenum);
234     if(FAILED(hr)){
235         ERR("CoCreateInstance failed: %08x\n", hr);
236         CoUninitialize();
237         return 1;
238     }
239
240     SetEvent(evt);
241
242     PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
243
244     while(GetMessageW(&msg, NULL, 0, 0)){
245         if(msg.hwnd)
246             DispatchMessageW(&msg);
247         else
248             ERR("Unknown message: %04x\n", msg.message);
249     }
250
251     IMMDeviceEnumerator_Release(g_devenum);
252     g_devenum = NULL;
253     CoUninitialize();
254
255     return 0;
256 }
257
258 static IMMDeviceEnumerator *get_mmdevenum(void)
259 {
260     HANDLE events[2];
261     DWORD wait;
262
263     EnterCriticalSection(&g_devenum_lock);
264
265     if(g_devenum){
266         LeaveCriticalSection(&g_devenum_lock);
267         return g_devenum;
268     }
269
270     events[0] = CreateEventW(NULL, FALSE, FALSE, NULL);
271
272     g_devenum_thread = CreateThread(NULL, 0, devenum_thread_proc,
273             events[0], 0, NULL);
274     if(!g_devenum_thread){
275         LeaveCriticalSection(&g_devenum_lock);
276         CloseHandle(events[0]);
277         return NULL;
278     }
279
280     events[1] = g_devenum_thread;
281     wait = WaitForMultipleObjects(2, events, FALSE, INFINITE);
282     CloseHandle(events[0]);
283     if(wait != WAIT_OBJECT_0){
284         if(wait == 1 + WAIT_OBJECT_0){
285             CloseHandle(g_devenum_thread);
286             g_devenum_thread = NULL;
287         }
288         LeaveCriticalSection(&g_devenum_lock);
289         return NULL;
290     }
291
292     LeaveCriticalSection(&g_devenum_lock);
293
294     return g_devenum;
295 }
296
297 static HRESULT get_mmdevice_guid(IMMDevice *device, IPropertyStore *ps,
298         GUID *guid)
299 {
300     PROPVARIANT pv;
301     HRESULT hr;
302
303     if(!ps){
304         hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
305         if(FAILED(hr)){
306             WARN("OpenPropertyStore failed: %08x\n", hr);
307             return hr;
308         }
309     }else
310         IPropertyStore_AddRef(ps);
311
312     PropVariantInit(&pv);
313
314     hr = IPropertyStore_GetValue(ps, &PKEY_AudioEndpoint_GUID, &pv);
315     if(FAILED(hr)){
316         IPropertyStore_Release(ps);
317         WARN("GetValue(GUID) failed: %08x\n", hr);
318         return hr;
319     }
320
321     CLSIDFromString(pv.u.pwszVal, guid);
322
323     PropVariantClear(&pv);
324     IPropertyStore_Release(ps);
325
326     return S_OK;
327 }
328
329 /***************************************************************************
330  * GetDeviceID  [DSOUND.9]
331  *
332  * Retrieves unique identifier of default device specified
333  *
334  * PARAMS
335  *    pGuidSrc  [I] Address of device GUID.
336  *    pGuidDest [O] Address to receive unique device GUID.
337  *
338  * RETURNS
339  *    Success: DS_OK
340  *    Failure: DSERR_INVALIDPARAM
341  *
342  * NOTES
343  *    pGuidSrc is a valid device GUID or DSDEVID_DefaultPlayback,
344  *    DSDEVID_DefaultCapture, DSDEVID_DefaultVoicePlayback, or
345  *    DSDEVID_DefaultVoiceCapture.
346  *    Returns pGuidSrc if pGuidSrc is a valid device or the device
347  *    GUID for the specified constants.
348  */
349 HRESULT WINAPI GetDeviceID(LPCGUID pGuidSrc, LPGUID pGuidDest)
350 {
351     IMMDeviceEnumerator *devenum;
352     EDataFlow flow = (EDataFlow)-1;
353     ERole role = (ERole)-1;
354     HRESULT hr;
355
356     TRACE("(%s,%p)\n", get_device_id(pGuidSrc),pGuidDest);
357
358     if(!pGuidSrc || !pGuidDest)
359         return DSERR_INVALIDPARAM;
360
361     devenum = get_mmdevenum();
362     if(!devenum)
363         return DSERR_GENERIC;
364
365     if(IsEqualGUID(&DSDEVID_DefaultPlayback, pGuidSrc)){
366         role = eMultimedia;
367         flow = eRender;
368     }else if(IsEqualGUID(&DSDEVID_DefaultVoicePlayback, pGuidSrc)){
369         role = eCommunications;
370         flow = eRender;
371     }else if(IsEqualGUID(&DSDEVID_DefaultCapture, pGuidSrc)){
372         role = eMultimedia;
373         flow = eCapture;
374     }else if(IsEqualGUID(&DSDEVID_DefaultVoiceCapture, pGuidSrc)){
375         role = eCommunications;
376         flow = eCapture;
377     }
378
379     if(role != (ERole)-1 && flow != (EDataFlow)-1){
380         IMMDevice *device;
381
382         hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(devenum,
383                 flow, role, &device);
384         if(FAILED(hr)){
385             WARN("GetDefaultAudioEndpoint failed: %08x\n", hr);
386             return DSERR_NODRIVER;
387         }
388
389         hr = get_mmdevice_guid(device, NULL, pGuidDest);
390         IMMDevice_Release(device);
391
392         return (hr == S_OK) ? DS_OK : hr;
393     }
394
395     *pGuidDest = *pGuidSrc;
396
397     return DS_OK;
398 }
399
400 struct morecontext
401 {
402     LPDSENUMCALLBACKA callA;
403     LPVOID data;
404 };
405
406 static BOOL CALLBACK a_to_w_callback(LPGUID guid, LPCWSTR descW, LPCWSTR modW, LPVOID data)
407 {
408     struct morecontext *context = data;
409     char descA[MAXPNAMELEN], modA[MAXPNAMELEN];
410
411     WideCharToMultiByte(CP_ACP, 0, descW, -1, descA, sizeof(descA), NULL, NULL);
412     WideCharToMultiByte(CP_ACP, 0, modW, -1, modA, sizeof(modA), NULL, NULL);
413
414     return context->callA(guid, descA, modA, context->data);
415 }
416
417 /***************************************************************************
418  * DirectSoundEnumerateA [DSOUND.2]
419  *
420  * Enumerate all DirectSound drivers installed in the system
421  *
422  * PARAMS
423  *    lpDSEnumCallback  [I] Address of callback function.
424  *    lpContext         [I] Address of user defined context passed to callback function.
425  *
426  * RETURNS
427  *    Success: DS_OK
428  *    Failure: DSERR_INVALIDPARAM
429  */
430 HRESULT WINAPI DirectSoundEnumerateA(
431     LPDSENUMCALLBACKA lpDSEnumCallback,
432     LPVOID lpContext)
433 {
434     struct morecontext context;
435
436     if (lpDSEnumCallback == NULL) {
437         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
438         return DSERR_INVALIDPARAM;
439     }
440
441     context.callA = lpDSEnumCallback;
442     context.data = lpContext;
443
444     return DirectSoundEnumerateW(a_to_w_callback, &context);
445 }
446
447 HRESULT get_mmdevice(EDataFlow flow, const GUID *tgt, IMMDevice **device)
448 {
449     IMMDeviceEnumerator *devenum;
450     IMMDeviceCollection *coll;
451     UINT count, i;
452     HRESULT hr;
453
454     devenum = get_mmdevenum();
455     if(!devenum)
456         return DSERR_GENERIC;
457
458     hr = IMMDeviceEnumerator_EnumAudioEndpoints(devenum, flow,
459             DEVICE_STATE_ACTIVE, &coll);
460     if(FAILED(hr)){
461         WARN("EnumAudioEndpoints failed: %08x\n", hr);
462         return hr;
463     }
464
465     hr = IMMDeviceCollection_GetCount(coll, &count);
466     if(FAILED(hr)){
467         IMMDeviceCollection_Release(coll);
468         WARN("GetCount failed: %08x\n", hr);
469         return hr;
470     }
471
472     for(i = 0; i < count; ++i){
473         GUID guid;
474
475         hr = IMMDeviceCollection_Item(coll, i, device);
476         if(FAILED(hr))
477             continue;
478
479         hr = get_mmdevice_guid(*device, NULL, &guid);
480         if(FAILED(hr)){
481             IMMDevice_Release(*device);
482             continue;
483         }
484
485         if(IsEqualGUID(&guid, tgt))
486             return DS_OK;
487
488         IMMDevice_Release(*device);
489     }
490
491     WARN("No device with GUID %s found!\n", wine_dbgstr_guid(tgt));
492
493     return DSERR_INVALIDPARAM;
494 }
495
496 /* S_FALSE means the callback returned FALSE at some point
497  * S_OK means the callback always returned TRUE */
498 HRESULT enumerate_mmdevices(EDataFlow flow, GUID *guids,
499         LPDSENUMCALLBACKW cb, void *user)
500 {
501     IMMDeviceEnumerator *devenum;
502     IMMDeviceCollection *coll;
503     UINT count, i;
504     BOOL keep_going;
505     HRESULT hr;
506
507     static const WCHAR primary_desc[] = {'P','r','i','m','a','r','y',' ',
508         'S','o','u','n','d',' ','D','r','i','v','e','r',0};
509     static const WCHAR empty_drv[] = {0};
510
511     devenum = get_mmdevenum();
512     if(!devenum)
513         return DS_OK;
514
515     hr = IMMDeviceEnumerator_EnumAudioEndpoints(g_devenum, flow,
516             DEVICE_STATE_ACTIVE, &coll);
517     if(FAILED(hr)){
518         WARN("EnumAudioEndpoints failed: %08x\n", hr);
519         return DS_OK;
520     }
521
522     hr = IMMDeviceCollection_GetCount(coll, &count);
523     if(FAILED(hr)){
524         IMMDeviceCollection_Release(coll);
525         WARN("GetCount failed: %08x\n", hr);
526         return DS_OK;
527     }
528
529     if(count == 0)
530         return DS_OK;
531
532     keep_going = cb(NULL, primary_desc, empty_drv, user);
533
534     for(i = 0; keep_going && i < count; ++i){
535         IMMDevice *device;
536         IPropertyStore *ps;
537         PROPVARIANT pv;
538
539         PropVariantInit(&pv);
540
541         hr = IMMDeviceCollection_Item(coll, i, &device);
542         if(FAILED(hr)){
543             WARN("Item failed: %08x\n", hr);
544             continue;
545         }
546
547         hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
548         if(FAILED(hr)){
549             IMMDevice_Release(device);
550             WARN("OpenPropertyStore failed: %08x\n", hr);
551             continue;
552         }
553
554         hr = get_mmdevice_guid(device, ps, &guids[i]);
555         if(FAILED(hr)){
556             IPropertyStore_Release(ps);
557             IMMDevice_Release(device);
558             continue;
559         }
560
561         hr = IPropertyStore_GetValue(ps,
562                 (const PROPERTYKEY *)&DEVPKEY_Device_FriendlyName, &pv);
563         if(FAILED(hr)){
564             IPropertyStore_Release(ps);
565             IMMDevice_Release(device);
566             WARN("GetValue(FriendlyName) failed: %08x\n", hr);
567             continue;
568         }
569
570         keep_going = cb(&guids[i], pv.u.pwszVal, wine_vxd_drv, user);
571
572         PropVariantClear(&pv);
573         IPropertyStore_Release(ps);
574         IMMDevice_Release(device);
575     }
576
577     IMMDeviceCollection_Release(coll);
578
579     return (keep_going == TRUE) ? S_OK : S_FALSE;
580 }
581
582 /***************************************************************************
583  * DirectSoundEnumerateW [DSOUND.3]
584  *
585  * Enumerate all DirectSound drivers installed in the system
586  *
587  * PARAMS
588  *    lpDSEnumCallback  [I] Address of callback function.
589  *    lpContext         [I] Address of user defined context passed to callback function.
590  *
591  * RETURNS
592  *    Success: DS_OK
593  *    Failure: DSERR_INVALIDPARAM
594  */
595 HRESULT WINAPI DirectSoundEnumerateW(
596         LPDSENUMCALLBACKW lpDSEnumCallback,
597         LPVOID lpContext )
598 {
599     HRESULT hr;
600
601     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext);
602
603     if (lpDSEnumCallback == NULL) {
604         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
605         return DSERR_INVALIDPARAM;
606     }
607
608     setup_dsound_options();
609
610     hr = enumerate_mmdevices(eRender, DSOUND_renderer_guids,
611             lpDSEnumCallback, lpContext);
612     return SUCCEEDED(hr) ? DS_OK : hr;
613 }
614
615 /***************************************************************************
616  * DirectSoundCaptureEnumerateA [DSOUND.7]
617  *
618  * Enumerate all DirectSound drivers installed in the system.
619  *
620  * PARAMS
621  *    lpDSEnumCallback  [I] Address of callback function.
622  *    lpContext         [I] Address of user defined context passed to callback function.
623  *
624  * RETURNS
625  *    Success: DS_OK
626  *    Failure: DSERR_INVALIDPARAM
627  */
628 HRESULT WINAPI DirectSoundCaptureEnumerateA(
629     LPDSENUMCALLBACKA lpDSEnumCallback,
630     LPVOID lpContext)
631 {
632     struct morecontext context;
633
634     if (lpDSEnumCallback == NULL) {
635         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
636         return DSERR_INVALIDPARAM;
637     }
638
639     context.callA = lpDSEnumCallback;
640     context.data = lpContext;
641
642     return DirectSoundCaptureEnumerateW(a_to_w_callback, &context);
643 }
644
645 /***************************************************************************
646  * DirectSoundCaptureEnumerateW [DSOUND.8]
647  *
648  * Enumerate all DirectSound drivers installed in the system.
649  *
650  * PARAMS
651  *    lpDSEnumCallback  [I] Address of callback function.
652  *    lpContext         [I] Address of user defined context passed to callback function.
653  *
654  * RETURNS
655  *    Success: DS_OK
656  *    Failure: DSERR_INVALIDPARAM
657  */
658 HRESULT WINAPI
659 DirectSoundCaptureEnumerateW(
660     LPDSENUMCALLBACKW lpDSEnumCallback,
661     LPVOID lpContext)
662 {
663     HRESULT hr;
664
665     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext );
666
667     if (lpDSEnumCallback == NULL) {
668         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
669         return DSERR_INVALIDPARAM;
670     }
671
672     setup_dsound_options();
673
674     hr = enumerate_mmdevices(eCapture, DSOUND_capture_guids,
675             lpDSEnumCallback, lpContext);
676     return SUCCEEDED(hr) ? DS_OK : hr;
677 }
678
679 /*******************************************************************************
680  * DirectSound ClassFactory
681  */
682
683 typedef  HRESULT (*FnCreateInstance)(REFIID riid, LPVOID *ppobj);
684  
685 typedef struct {
686     IClassFactory IClassFactory_iface;
687     REFCLSID rclsid;
688     FnCreateInstance pfnCreateInstance;
689 } IClassFactoryImpl;
690
691 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
692 {
693     return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
694 }
695
696 static HRESULT WINAPI
697 DSCF_QueryInterface(LPCLASSFACTORY iface, REFIID riid, LPVOID *ppobj)
698 {
699     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
700     TRACE("(%p, %s, %p)\n", This, debugstr_guid(riid), ppobj);
701     if (ppobj == NULL)
702         return E_POINTER;
703     if (IsEqualIID(riid, &IID_IUnknown) ||
704         IsEqualIID(riid, &IID_IClassFactory))
705     {
706         *ppobj = iface;
707         IUnknown_AddRef(iface);
708         return S_OK;
709     }
710     *ppobj = NULL;
711     return E_NOINTERFACE;
712 }
713
714 static ULONG WINAPI DSCF_AddRef(LPCLASSFACTORY iface)
715 {
716     return 2;
717 }
718
719 static ULONG WINAPI DSCF_Release(LPCLASSFACTORY iface)
720 {
721     /* static class, won't be freed */
722     return 1;
723 }
724
725 static HRESULT WINAPI DSCF_CreateInstance(
726     LPCLASSFACTORY iface,
727     LPUNKNOWN pOuter,
728     REFIID riid,
729     LPVOID *ppobj)
730 {
731     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
732     TRACE("(%p, %p, %s, %p)\n", This, pOuter, debugstr_guid(riid), ppobj);
733
734     if (pOuter)
735         return CLASS_E_NOAGGREGATION;
736
737     if (ppobj == NULL) {
738         WARN("invalid parameter\n");
739         return DSERR_INVALIDPARAM;
740     }
741     *ppobj = NULL;
742     return This->pfnCreateInstance(riid, ppobj);
743 }
744  
745 static HRESULT WINAPI DSCF_LockServer(LPCLASSFACTORY iface, BOOL dolock)
746 {
747     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
748     FIXME("(%p, %d) stub!\n", This, dolock);
749     return S_OK;
750 }
751
752 static const IClassFactoryVtbl DSCF_Vtbl = {
753     DSCF_QueryInterface,
754     DSCF_AddRef,
755     DSCF_Release,
756     DSCF_CreateInstance,
757     DSCF_LockServer
758 };
759
760 static IClassFactoryImpl DSOUND_CF[] = {
761     { { &DSCF_Vtbl }, &CLSID_DirectSound, (FnCreateInstance)DSOUND_Create },
762     { { &DSCF_Vtbl }, &CLSID_DirectSound8, (FnCreateInstance)DSOUND_Create8 },
763     { { &DSCF_Vtbl }, &CLSID_DirectSoundCapture, (FnCreateInstance)DSOUND_CaptureCreate },
764     { { &DSCF_Vtbl }, &CLSID_DirectSoundCapture8, (FnCreateInstance)DSOUND_CaptureCreate8 },
765     { { &DSCF_Vtbl }, &CLSID_DirectSoundFullDuplex, (FnCreateInstance)DSOUND_FullDuplexCreate },
766     { { &DSCF_Vtbl }, &CLSID_DirectSoundPrivate, (FnCreateInstance)IKsPrivatePropertySetImpl_Create },
767     { { NULL }, NULL, NULL }
768 };
769
770 /*******************************************************************************
771  * DllGetClassObject [DSOUND.@]
772  * Retrieves class object from a DLL object
773  *
774  * NOTES
775  *    Docs say returns STDAPI
776  *
777  * PARAMS
778  *    rclsid [I] CLSID for the class object
779  *    riid   [I] Reference to identifier of interface for class object
780  *    ppv    [O] Address of variable to receive interface pointer for riid
781  *
782  * RETURNS
783  *    Success: S_OK
784  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
785  *             E_UNEXPECTED
786  */
787 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
788 {
789     int i = 0;
790     TRACE("(%s, %s, %p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
791
792     if (ppv == NULL) {
793         WARN("invalid parameter\n");
794         return E_INVALIDARG;
795     }
796
797     *ppv = NULL;
798
799     if (!IsEqualIID(riid, &IID_IClassFactory) &&
800         !IsEqualIID(riid, &IID_IUnknown)) {
801         WARN("no interface for %s\n", debugstr_guid(riid));
802         return E_NOINTERFACE;
803     }
804
805     while (NULL != DSOUND_CF[i].rclsid) {
806         if (IsEqualGUID(rclsid, DSOUND_CF[i].rclsid)) {
807             DSCF_AddRef(&DSOUND_CF[i].IClassFactory_iface);
808             *ppv = &DSOUND_CF[i];
809             return S_OK;
810         }
811         i++;
812     }
813
814     WARN("(%s, %s, %p): no class found.\n", debugstr_guid(rclsid),
815          debugstr_guid(riid), ppv);
816     return CLASS_E_CLASSNOTAVAILABLE;
817 }
818
819
820 /*******************************************************************************
821  * DllCanUnloadNow [DSOUND.4]
822  * Determines whether the DLL is in use.
823  *
824  * RETURNS
825  *    Can unload now: S_OK
826  *    Cannot unload now (the DLL is still active): S_FALSE
827  */
828 HRESULT WINAPI DllCanUnloadNow(void)
829 {
830     return S_FALSE;
831 }
832
833 #define INIT_GUID(guid, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8)      \
834         guid.Data1 = l; guid.Data2 = w1; guid.Data3 = w2;               \
835         guid.Data4[0] = b1; guid.Data4[1] = b2; guid.Data4[2] = b3;     \
836         guid.Data4[3] = b4; guid.Data4[4] = b5; guid.Data4[5] = b6;     \
837         guid.Data4[6] = b7; guid.Data4[7] = b8;
838
839 /***********************************************************************
840  *           DllMain (DSOUND.init)
841  */
842 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpvReserved)
843 {
844     TRACE("(%p %d %p)\n", hInstDLL, fdwReason, lpvReserved);
845
846     switch (fdwReason) {
847     case DLL_PROCESS_ATTACH:
848         TRACE("DLL_PROCESS_ATTACH\n");
849         instance = hInstDLL;
850         DisableThreadLibraryCalls(hInstDLL);
851         /* Increase refcount on dsound by 1 */
852         GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)hInstDLL, &hInstDLL);
853         InitializeCriticalSection(&DSOUND_renderers_lock);
854         InitializeCriticalSection(&DSOUND_capturers_lock);
855         InitializeCriticalSection(&g_devenum_lock);
856         break;
857     case DLL_PROCESS_DETACH:
858         TRACE("DLL_PROCESS_DETACH\n");
859         break;
860     default:
861         TRACE("UNKNOWN REASON\n");
862         break;
863     }
864     return TRUE;
865 }
866
867 /***********************************************************************
868  *              DllRegisterServer (DSOUND.@)
869  */
870 HRESULT WINAPI DllRegisterServer(void)
871 {
872     return __wine_register_resources( instance );
873 }
874
875 /***********************************************************************
876  *              DllUnregisterServer (DSOUND.@)
877  */
878 HRESULT WINAPI DllUnregisterServer(void)
879 {
880     return __wine_unregister_resources( instance );
881 }