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