hlink: Return S_FALSE in GetTargetFrameName when returning NULL.
[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_hel_buflen = 32768 * 2;
112 int ds_snd_queue_max = 10;
113 int ds_snd_shadow_maxsize = 2;
114 int ds_default_sample_rate = 44100;
115 int ds_default_bits_per_sample = 16;
116 static HINSTANCE instance;
117
118 /*
119  * Get a config key from either the app-specific or the default config
120  */
121
122 static inline DWORD get_config_key( HKEY defkey, HKEY appkey, const char *name,
123                                     char *buffer, DWORD size )
124 {
125     if (appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE)buffer, &size )) return 0;
126     if (defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE)buffer, &size )) return 0;
127     return ERROR_FILE_NOT_FOUND;
128 }
129
130
131 /*
132  * Setup the dsound options.
133  */
134
135 void setup_dsound_options(void)
136 {
137     char buffer[MAX_PATH+16];
138     HKEY hkey, appkey = 0;
139     DWORD len;
140
141     buffer[MAX_PATH]='\0';
142
143     /* @@ Wine registry key: HKCU\Software\Wine\DirectSound */
144     if (RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\DirectSound", &hkey )) hkey = 0;
145
146     len = GetModuleFileNameA( 0, buffer, MAX_PATH );
147     if (len && len < MAX_PATH)
148     {
149         HKEY tmpkey;
150         /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\DirectSound */
151         if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
152         {
153             char *p, *appname = buffer;
154             if ((p = strrchr( appname, '/' ))) appname = p + 1;
155             if ((p = strrchr( appname, '\\' ))) appname = p + 1;
156             strcat( appname, "\\DirectSound" );
157             TRACE("appname = [%s]\n", appname);
158             if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
159             RegCloseKey( tmpkey );
160         }
161     }
162
163     /* get options */
164
165     if (!get_config_key( hkey, appkey, "HelBuflen", buffer, MAX_PATH ))
166         ds_hel_buflen = atoi(buffer);
167
168     if (!get_config_key( hkey, appkey, "SndQueueMax", buffer, MAX_PATH ))
169         ds_snd_queue_max = atoi(buffer);
170
171     if (!get_config_key( hkey, appkey, "MaxShadowSize", buffer, MAX_PATH ))
172         ds_snd_shadow_maxsize = atoi(buffer);
173
174     if (!get_config_key( hkey, appkey, "DefaultSampleRate", buffer, MAX_PATH ))
175         ds_default_sample_rate = atoi(buffer);
176
177     if (!get_config_key( hkey, appkey, "DefaultBitsPerSample", buffer, MAX_PATH ))
178         ds_default_bits_per_sample = atoi(buffer);
179
180     if (appkey) RegCloseKey( appkey );
181     if (hkey) RegCloseKey( hkey );
182
183     TRACE("ds_hel_buflen = %d\n", ds_hel_buflen);
184     TRACE("ds_snd_queue_max = %d\n", ds_snd_queue_max);
185     TRACE("ds_default_sample_rate = %d\n", ds_default_sample_rate);
186     TRACE("ds_default_bits_per_sample = %d\n", ds_default_bits_per_sample);
187     TRACE("ds_snd_shadow_maxsize = %d\n", ds_snd_shadow_maxsize);
188 }
189
190 static const char * get_device_id(LPCGUID pGuid)
191 {
192     if (IsEqualGUID(&DSDEVID_DefaultPlayback, pGuid))
193         return "DSDEVID_DefaultPlayback";
194     else if (IsEqualGUID(&DSDEVID_DefaultVoicePlayback, pGuid))
195         return "DSDEVID_DefaultVoicePlayback";
196     else if (IsEqualGUID(&DSDEVID_DefaultCapture, pGuid))
197         return "DSDEVID_DefaultCapture";
198     else if (IsEqualGUID(&DSDEVID_DefaultVoiceCapture, pGuid))
199         return "DSDEVID_DefaultVoiceCapture";
200     return debugstr_guid(pGuid);
201 }
202
203 /* The MMDeviceEnumerator object has to be created & destroyed
204  * from the same thread. */
205 static DWORD WINAPI devenum_thread_proc(void *arg)
206 {
207     HANDLE evt = arg;
208     HRESULT hr;
209     MSG msg;
210
211     hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
212     if(FAILED(hr)){
213          ERR("CoInitializeEx failed: %08x\n", hr);
214          return 1;
215     }
216
217     hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL,
218             CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, (void**)&g_devenum);
219     if(FAILED(hr)){
220         ERR("CoCreateInstance failed: %08x\n", hr);
221         CoUninitialize();
222         return 1;
223     }
224
225     SetEvent(evt);
226
227     PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
228
229     while(GetMessageW(&msg, NULL, 0, 0)){
230         if(msg.hwnd)
231             DispatchMessageW(&msg);
232         else
233             ERR("Unknown message: %04x\n", msg.message);
234     }
235
236     IMMDeviceEnumerator_Release(g_devenum);
237     g_devenum = NULL;
238     CoUninitialize();
239
240     return 0;
241 }
242
243 static IMMDeviceEnumerator *get_mmdevenum(void)
244 {
245     HANDLE events[2];
246     DWORD wait;
247
248     EnterCriticalSection(&g_devenum_lock);
249
250     if(g_devenum){
251         LeaveCriticalSection(&g_devenum_lock);
252         return g_devenum;
253     }
254
255     events[0] = CreateEventW(NULL, FALSE, FALSE, NULL);
256
257     g_devenum_thread = CreateThread(NULL, 0, devenum_thread_proc,
258             events[0], 0, NULL);
259     if(!g_devenum_thread){
260         LeaveCriticalSection(&g_devenum_lock);
261         CloseHandle(events[0]);
262         return NULL;
263     }
264
265     events[1] = g_devenum_thread;
266     wait = WaitForMultipleObjects(2, events, FALSE, INFINITE);
267     CloseHandle(events[0]);
268     if(wait != WAIT_OBJECT_0){
269         if(wait == 1 + WAIT_OBJECT_0){
270             CloseHandle(g_devenum_thread);
271             g_devenum_thread = NULL;
272         }
273         LeaveCriticalSection(&g_devenum_lock);
274         return NULL;
275     }
276
277     LeaveCriticalSection(&g_devenum_lock);
278
279     return g_devenum;
280 }
281
282 static HRESULT get_mmdevice_guid(IMMDevice *device, IPropertyStore *ps,
283         GUID *guid)
284 {
285     PROPVARIANT pv;
286     HRESULT hr;
287
288     if(!ps){
289         hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
290         if(FAILED(hr)){
291             WARN("OpenPropertyStore failed: %08x\n", hr);
292             return hr;
293         }
294     }else
295         IPropertyStore_AddRef(ps);
296
297     PropVariantInit(&pv);
298
299     hr = IPropertyStore_GetValue(ps, &PKEY_AudioEndpoint_GUID, &pv);
300     if(FAILED(hr)){
301         IPropertyStore_Release(ps);
302         WARN("GetValue(GUID) failed: %08x\n", hr);
303         return hr;
304     }
305
306     CLSIDFromString(pv.u.pwszVal, guid);
307
308     PropVariantClear(&pv);
309     IPropertyStore_Release(ps);
310
311     return S_OK;
312 }
313
314 /***************************************************************************
315  * GetDeviceID  [DSOUND.9]
316  *
317  * Retrieves unique identifier of default device specified
318  *
319  * PARAMS
320  *    pGuidSrc  [I] Address of device GUID.
321  *    pGuidDest [O] Address to receive unique device GUID.
322  *
323  * RETURNS
324  *    Success: DS_OK
325  *    Failure: DSERR_INVALIDPARAM
326  *
327  * NOTES
328  *    pGuidSrc is a valid device GUID or DSDEVID_DefaultPlayback,
329  *    DSDEVID_DefaultCapture, DSDEVID_DefaultVoicePlayback, or
330  *    DSDEVID_DefaultVoiceCapture.
331  *    Returns pGuidSrc if pGuidSrc is a valid device or the device
332  *    GUID for the specified constants.
333  */
334 HRESULT WINAPI GetDeviceID(LPCGUID pGuidSrc, LPGUID pGuidDest)
335 {
336     IMMDeviceEnumerator *devenum;
337     EDataFlow flow = (EDataFlow)-1;
338     ERole role = (ERole)-1;
339     HRESULT hr;
340
341     TRACE("(%s,%p)\n", get_device_id(pGuidSrc),pGuidDest);
342
343     if(!pGuidSrc || !pGuidDest)
344         return DSERR_INVALIDPARAM;
345
346     devenum = get_mmdevenum();
347     if(!devenum)
348         return DSERR_GENERIC;
349
350     if(IsEqualGUID(&DSDEVID_DefaultPlayback, pGuidSrc)){
351         role = eMultimedia;
352         flow = eRender;
353     }else if(IsEqualGUID(&DSDEVID_DefaultVoicePlayback, pGuidSrc)){
354         role = eCommunications;
355         flow = eRender;
356     }else if(IsEqualGUID(&DSDEVID_DefaultCapture, pGuidSrc)){
357         role = eMultimedia;
358         flow = eCapture;
359     }else if(IsEqualGUID(&DSDEVID_DefaultVoiceCapture, pGuidSrc)){
360         role = eCommunications;
361         flow = eCapture;
362     }
363
364     if(role != (ERole)-1 && flow != (EDataFlow)-1){
365         IMMDevice *device;
366
367         hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(devenum,
368                 flow, role, &device);
369         if(FAILED(hr)){
370             WARN("GetDefaultAudioEndpoint failed: %08x\n", hr);
371             return DSERR_NODRIVER;
372         }
373
374         hr = get_mmdevice_guid(device, NULL, pGuidDest);
375         IMMDevice_Release(device);
376
377         return (hr == S_OK) ? DS_OK : hr;
378     }
379
380     *pGuidDest = *pGuidSrc;
381
382     return DS_OK;
383 }
384
385 struct morecontext
386 {
387     LPDSENUMCALLBACKA callA;
388     LPVOID data;
389 };
390
391 static BOOL CALLBACK a_to_w_callback(LPGUID guid, LPCWSTR descW, LPCWSTR modW, LPVOID data)
392 {
393     struct morecontext *context = data;
394     char descA[MAXPNAMELEN], modA[MAXPNAMELEN];
395
396     WideCharToMultiByte(CP_ACP, 0, descW, -1, descA, sizeof(descA), NULL, NULL);
397     WideCharToMultiByte(CP_ACP, 0, modW, -1, modA, sizeof(modA), NULL, NULL);
398
399     return context->callA(guid, descA, modA, context->data);
400 }
401
402 /***************************************************************************
403  * DirectSoundEnumerateA [DSOUND.2]
404  *
405  * Enumerate all DirectSound drivers installed in the system
406  *
407  * PARAMS
408  *    lpDSEnumCallback  [I] Address of callback function.
409  *    lpContext         [I] Address of user defined context passed to callback function.
410  *
411  * RETURNS
412  *    Success: DS_OK
413  *    Failure: DSERR_INVALIDPARAM
414  */
415 HRESULT WINAPI DirectSoundEnumerateA(
416     LPDSENUMCALLBACKA lpDSEnumCallback,
417     LPVOID lpContext)
418 {
419     struct morecontext context;
420
421     if (lpDSEnumCallback == NULL) {
422         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
423         return DSERR_INVALIDPARAM;
424     }
425
426     context.callA = lpDSEnumCallback;
427     context.data = lpContext;
428
429     return DirectSoundEnumerateW(a_to_w_callback, &context);
430 }
431
432 HRESULT get_mmdevice(EDataFlow flow, const GUID *tgt, IMMDevice **device)
433 {
434     IMMDeviceEnumerator *devenum;
435     IMMDeviceCollection *coll;
436     UINT count, i;
437     HRESULT hr;
438
439     devenum = get_mmdevenum();
440     if(!devenum)
441         return DSERR_GENERIC;
442
443     hr = IMMDeviceEnumerator_EnumAudioEndpoints(devenum, flow,
444             DEVICE_STATE_ACTIVE, &coll);
445     if(FAILED(hr)){
446         WARN("EnumAudioEndpoints failed: %08x\n", hr);
447         return hr;
448     }
449
450     hr = IMMDeviceCollection_GetCount(coll, &count);
451     if(FAILED(hr)){
452         IMMDeviceCollection_Release(coll);
453         WARN("GetCount failed: %08x\n", hr);
454         return hr;
455     }
456
457     for(i = 0; i < count; ++i){
458         GUID guid;
459
460         hr = IMMDeviceCollection_Item(coll, i, device);
461         if(FAILED(hr))
462             continue;
463
464         hr = get_mmdevice_guid(*device, NULL, &guid);
465         if(FAILED(hr)){
466             IMMDevice_Release(*device);
467             continue;
468         }
469
470         if(IsEqualGUID(&guid, tgt))
471             return DS_OK;
472
473         IMMDevice_Release(*device);
474     }
475
476     WARN("No device with GUID %s found!\n", wine_dbgstr_guid(tgt));
477
478     return DSERR_INVALIDPARAM;
479 }
480
481 static BOOL send_device(IMMDevice *device, GUID *guid,
482         LPDSENUMCALLBACKW cb, void *user)
483 {
484     IPropertyStore *ps;
485     PROPVARIANT pv;
486     BOOL keep_going;
487     HRESULT hr;
488
489     PropVariantInit(&pv);
490
491     hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
492     if(FAILED(hr)){
493         WARN("OpenPropertyStore failed: %08x\n", hr);
494         return TRUE;
495     }
496
497     hr = get_mmdevice_guid(device, ps, guid);
498     if(FAILED(hr)){
499         IPropertyStore_Release(ps);
500         return TRUE;
501     }
502
503     hr = IPropertyStore_GetValue(ps,
504             (const PROPERTYKEY *)&DEVPKEY_Device_FriendlyName, &pv);
505     if(FAILED(hr)){
506         IPropertyStore_Release(ps);
507         WARN("GetValue(FriendlyName) failed: %08x\n", hr);
508         return TRUE;
509     }
510
511     TRACE("Calling back with %s (%s)\n", wine_dbgstr_guid(guid),
512             wine_dbgstr_w(pv.u.pwszVal));
513
514     keep_going = cb(guid, pv.u.pwszVal, wine_vxd_drv, user);
515
516     PropVariantClear(&pv);
517     IPropertyStore_Release(ps);
518
519     return keep_going;
520 }
521
522 /* S_FALSE means the callback returned FALSE at some point
523  * S_OK means the callback always returned TRUE */
524 HRESULT enumerate_mmdevices(EDataFlow flow, GUID *guids,
525         LPDSENUMCALLBACKW cb, void *user)
526 {
527     IMMDeviceEnumerator *devenum;
528     IMMDeviceCollection *coll;
529     IMMDevice *defdev = NULL;
530     UINT count, i, n;
531     BOOL keep_going;
532     HRESULT hr;
533
534     static const WCHAR primary_desc[] = {'P','r','i','m','a','r','y',' ',
535         'S','o','u','n','d',' ','D','r','i','v','e','r',0};
536     static const WCHAR empty_drv[] = {0};
537
538     devenum = get_mmdevenum();
539     if(!devenum)
540         return DS_OK;
541
542     hr = IMMDeviceEnumerator_EnumAudioEndpoints(g_devenum, flow,
543             DEVICE_STATE_ACTIVE, &coll);
544     if(FAILED(hr)){
545         WARN("EnumAudioEndpoints failed: %08x\n", hr);
546         return DS_OK;
547     }
548
549     hr = IMMDeviceCollection_GetCount(coll, &count);
550     if(FAILED(hr)){
551         IMMDeviceCollection_Release(coll);
552         WARN("GetCount failed: %08x\n", hr);
553         return DS_OK;
554     }
555
556     if(count == 0)
557         return DS_OK;
558
559     TRACE("Calling back with NULL (%s)\n", wine_dbgstr_w(primary_desc));
560     keep_going = cb(NULL, primary_desc, empty_drv, user);
561
562     /* always send the default device first */
563     if(keep_going){
564         hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(devenum, flow,
565                 eMultimedia, &defdev);
566         if(FAILED(hr)){
567             defdev = NULL;
568             n = 0;
569         }else{
570             keep_going = send_device(defdev, &guids[0], cb, user);
571             n = 1;
572         }
573     }
574
575     for(i = 0; keep_going && i < count; ++i){
576         IMMDevice *device;
577
578         hr = IMMDeviceCollection_Item(coll, i, &device);
579         if(FAILED(hr)){
580             WARN("Item failed: %08x\n", hr);
581             continue;
582         }
583
584         if(device != defdev){
585             send_device(device, &guids[n], cb, user);
586             ++n;
587         }
588
589         IMMDevice_Release(device);
590     }
591
592     if(defdev)
593         IMMDevice_Release(defdev);
594     IMMDeviceCollection_Release(coll);
595
596     return (keep_going == TRUE) ? S_OK : S_FALSE;
597 }
598
599 /***************************************************************************
600  * DirectSoundEnumerateW [DSOUND.3]
601  *
602  * Enumerate all DirectSound drivers installed in the system
603  *
604  * PARAMS
605  *    lpDSEnumCallback  [I] Address of callback function.
606  *    lpContext         [I] Address of user defined context passed to callback function.
607  *
608  * RETURNS
609  *    Success: DS_OK
610  *    Failure: DSERR_INVALIDPARAM
611  */
612 HRESULT WINAPI DirectSoundEnumerateW(
613         LPDSENUMCALLBACKW lpDSEnumCallback,
614         LPVOID lpContext )
615 {
616     HRESULT hr;
617
618     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext);
619
620     if (lpDSEnumCallback == NULL) {
621         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
622         return DSERR_INVALIDPARAM;
623     }
624
625     setup_dsound_options();
626
627     hr = enumerate_mmdevices(eRender, DSOUND_renderer_guids,
628             lpDSEnumCallback, lpContext);
629     return SUCCEEDED(hr) ? DS_OK : hr;
630 }
631
632 /***************************************************************************
633  * DirectSoundCaptureEnumerateA [DSOUND.7]
634  *
635  * Enumerate all DirectSound drivers installed in the system.
636  *
637  * PARAMS
638  *    lpDSEnumCallback  [I] Address of callback function.
639  *    lpContext         [I] Address of user defined context passed to callback function.
640  *
641  * RETURNS
642  *    Success: DS_OK
643  *    Failure: DSERR_INVALIDPARAM
644  */
645 HRESULT WINAPI DirectSoundCaptureEnumerateA(
646     LPDSENUMCALLBACKA lpDSEnumCallback,
647     LPVOID lpContext)
648 {
649     struct morecontext context;
650
651     if (lpDSEnumCallback == NULL) {
652         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
653         return DSERR_INVALIDPARAM;
654     }
655
656     context.callA = lpDSEnumCallback;
657     context.data = lpContext;
658
659     return DirectSoundCaptureEnumerateW(a_to_w_callback, &context);
660 }
661
662 /***************************************************************************
663  * DirectSoundCaptureEnumerateW [DSOUND.8]
664  *
665  * Enumerate all DirectSound drivers installed in the system.
666  *
667  * PARAMS
668  *    lpDSEnumCallback  [I] Address of callback function.
669  *    lpContext         [I] Address of user defined context passed to callback function.
670  *
671  * RETURNS
672  *    Success: DS_OK
673  *    Failure: DSERR_INVALIDPARAM
674  */
675 HRESULT WINAPI
676 DirectSoundCaptureEnumerateW(
677     LPDSENUMCALLBACKW lpDSEnumCallback,
678     LPVOID lpContext)
679 {
680     HRESULT hr;
681
682     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext );
683
684     if (lpDSEnumCallback == NULL) {
685         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
686         return DSERR_INVALIDPARAM;
687     }
688
689     setup_dsound_options();
690
691     hr = enumerate_mmdevices(eCapture, DSOUND_capture_guids,
692             lpDSEnumCallback, lpContext);
693     return SUCCEEDED(hr) ? DS_OK : hr;
694 }
695
696 /*******************************************************************************
697  * DirectSound ClassFactory
698  */
699
700 typedef  HRESULT (*FnCreateInstance)(REFIID riid, LPVOID *ppobj);
701  
702 typedef struct {
703     IClassFactory IClassFactory_iface;
704     REFCLSID rclsid;
705     FnCreateInstance pfnCreateInstance;
706 } IClassFactoryImpl;
707
708 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
709 {
710     return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
711 }
712
713 static HRESULT WINAPI
714 DSCF_QueryInterface(LPCLASSFACTORY iface, REFIID riid, LPVOID *ppobj)
715 {
716     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
717     TRACE("(%p, %s, %p)\n", This, debugstr_guid(riid), ppobj);
718     if (ppobj == NULL)
719         return E_POINTER;
720     if (IsEqualIID(riid, &IID_IUnknown) ||
721         IsEqualIID(riid, &IID_IClassFactory))
722     {
723         *ppobj = iface;
724         IUnknown_AddRef(iface);
725         return S_OK;
726     }
727     *ppobj = NULL;
728     return E_NOINTERFACE;
729 }
730
731 static ULONG WINAPI DSCF_AddRef(LPCLASSFACTORY iface)
732 {
733     return 2;
734 }
735
736 static ULONG WINAPI DSCF_Release(LPCLASSFACTORY iface)
737 {
738     /* static class, won't be freed */
739     return 1;
740 }
741
742 static HRESULT WINAPI DSCF_CreateInstance(
743     LPCLASSFACTORY iface,
744     LPUNKNOWN pOuter,
745     REFIID riid,
746     LPVOID *ppobj)
747 {
748     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
749     TRACE("(%p, %p, %s, %p)\n", This, pOuter, debugstr_guid(riid), ppobj);
750
751     if (pOuter)
752         return CLASS_E_NOAGGREGATION;
753
754     if (ppobj == NULL) {
755         WARN("invalid parameter\n");
756         return DSERR_INVALIDPARAM;
757     }
758     *ppobj = NULL;
759     return This->pfnCreateInstance(riid, ppobj);
760 }
761  
762 static HRESULT WINAPI DSCF_LockServer(LPCLASSFACTORY iface, BOOL dolock)
763 {
764     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
765     FIXME("(%p, %d) stub!\n", This, dolock);
766     return S_OK;
767 }
768
769 static const IClassFactoryVtbl DSCF_Vtbl = {
770     DSCF_QueryInterface,
771     DSCF_AddRef,
772     DSCF_Release,
773     DSCF_CreateInstance,
774     DSCF_LockServer
775 };
776
777 static IClassFactoryImpl DSOUND_CF[] = {
778     { { &DSCF_Vtbl }, &CLSID_DirectSound, (FnCreateInstance)DSOUND_Create },
779     { { &DSCF_Vtbl }, &CLSID_DirectSound8, (FnCreateInstance)DSOUND_Create8 },
780     { { &DSCF_Vtbl }, &CLSID_DirectSoundCapture, (FnCreateInstance)DSOUND_CaptureCreate },
781     { { &DSCF_Vtbl }, &CLSID_DirectSoundCapture8, (FnCreateInstance)DSOUND_CaptureCreate8 },
782     { { &DSCF_Vtbl }, &CLSID_DirectSoundFullDuplex, (FnCreateInstance)DSOUND_FullDuplexCreate },
783     { { &DSCF_Vtbl }, &CLSID_DirectSoundPrivate, (FnCreateInstance)IKsPrivatePropertySetImpl_Create },
784     { { NULL }, NULL, NULL }
785 };
786
787 /*******************************************************************************
788  * DllGetClassObject [DSOUND.@]
789  * Retrieves class object from a DLL object
790  *
791  * NOTES
792  *    Docs say returns STDAPI
793  *
794  * PARAMS
795  *    rclsid [I] CLSID for the class object
796  *    riid   [I] Reference to identifier of interface for class object
797  *    ppv    [O] Address of variable to receive interface pointer for riid
798  *
799  * RETURNS
800  *    Success: S_OK
801  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
802  *             E_UNEXPECTED
803  */
804 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
805 {
806     int i = 0;
807     TRACE("(%s, %s, %p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
808
809     if (ppv == NULL) {
810         WARN("invalid parameter\n");
811         return E_INVALIDARG;
812     }
813
814     *ppv = NULL;
815
816     if (!IsEqualIID(riid, &IID_IClassFactory) &&
817         !IsEqualIID(riid, &IID_IUnknown)) {
818         WARN("no interface for %s\n", debugstr_guid(riid));
819         return E_NOINTERFACE;
820     }
821
822     while (NULL != DSOUND_CF[i].rclsid) {
823         if (IsEqualGUID(rclsid, DSOUND_CF[i].rclsid)) {
824             DSCF_AddRef(&DSOUND_CF[i].IClassFactory_iface);
825             *ppv = &DSOUND_CF[i];
826             return S_OK;
827         }
828         i++;
829     }
830
831     WARN("(%s, %s, %p): no class found.\n", debugstr_guid(rclsid),
832          debugstr_guid(riid), ppv);
833     return CLASS_E_CLASSNOTAVAILABLE;
834 }
835
836
837 /*******************************************************************************
838  * DllCanUnloadNow [DSOUND.4]
839  * Determines whether the DLL is in use.
840  *
841  * RETURNS
842  *    Can unload now: S_OK
843  *    Cannot unload now (the DLL is still active): S_FALSE
844  */
845 HRESULT WINAPI DllCanUnloadNow(void)
846 {
847     return S_FALSE;
848 }
849
850 #define INIT_GUID(guid, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8)      \
851         guid.Data1 = l; guid.Data2 = w1; guid.Data3 = w2;               \
852         guid.Data4[0] = b1; guid.Data4[1] = b2; guid.Data4[2] = b3;     \
853         guid.Data4[3] = b4; guid.Data4[4] = b5; guid.Data4[5] = b6;     \
854         guid.Data4[6] = b7; guid.Data4[7] = b8;
855
856 /***********************************************************************
857  *           DllMain (DSOUND.init)
858  */
859 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpvReserved)
860 {
861     TRACE("(%p %d %p)\n", hInstDLL, fdwReason, lpvReserved);
862
863     switch (fdwReason) {
864     case DLL_PROCESS_ATTACH:
865         TRACE("DLL_PROCESS_ATTACH\n");
866         instance = hInstDLL;
867         DisableThreadLibraryCalls(hInstDLL);
868         /* Increase refcount on dsound by 1 */
869         GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)hInstDLL, &hInstDLL);
870         InitializeCriticalSection(&DSOUND_renderers_lock);
871         InitializeCriticalSection(&DSOUND_capturers_lock);
872         InitializeCriticalSection(&g_devenum_lock);
873         break;
874     case DLL_PROCESS_DETACH:
875         TRACE("DLL_PROCESS_DETACH\n");
876         break;
877     default:
878         TRACE("UNKNOWN REASON\n");
879         break;
880     }
881     return TRUE;
882 }
883
884 /***********************************************************************
885  *              DllRegisterServer (DSOUND.@)
886  */
887 HRESULT WINAPI DllRegisterServer(void)
888 {
889     return __wine_register_resources( instance );
890 }
891
892 /***********************************************************************
893  *              DllUnregisterServer (DSOUND.@)
894  */
895 HRESULT WINAPI DllUnregisterServer(void)
896 {
897     return __wine_unregister_resources( instance );
898 }