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