dsound: Added missing LeaveCriticalSection (Coverity).
[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 /* S_FALSE means the callback returned FALSE at some point
482  * S_OK means the callback always returned TRUE */
483 HRESULT enumerate_mmdevices(EDataFlow flow, GUID *guids,
484         LPDSENUMCALLBACKW cb, void *user)
485 {
486     IMMDeviceEnumerator *devenum;
487     IMMDeviceCollection *coll;
488     UINT count, i;
489     BOOL keep_going;
490     HRESULT hr;
491
492     static const WCHAR primary_desc[] = {'P','r','i','m','a','r','y',' ',
493         'S','o','u','n','d',' ','D','r','i','v','e','r',0};
494     static const WCHAR empty_drv[] = {0};
495
496     devenum = get_mmdevenum();
497     if(!devenum)
498         return DS_OK;
499
500     hr = IMMDeviceEnumerator_EnumAudioEndpoints(g_devenum, flow,
501             DEVICE_STATE_ACTIVE, &coll);
502     if(FAILED(hr)){
503         WARN("EnumAudioEndpoints failed: %08x\n", hr);
504         return DS_OK;
505     }
506
507     hr = IMMDeviceCollection_GetCount(coll, &count);
508     if(FAILED(hr)){
509         IMMDeviceCollection_Release(coll);
510         WARN("GetCount failed: %08x\n", hr);
511         return DS_OK;
512     }
513
514     if(count == 0)
515         return DS_OK;
516
517     keep_going = cb(NULL, primary_desc, empty_drv, user);
518
519     for(i = 0; keep_going && i < count; ++i){
520         IMMDevice *device;
521         IPropertyStore *ps;
522         PROPVARIANT pv;
523
524         PropVariantInit(&pv);
525
526         hr = IMMDeviceCollection_Item(coll, i, &device);
527         if(FAILED(hr)){
528             WARN("Item failed: %08x\n", hr);
529             continue;
530         }
531
532         hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
533         if(FAILED(hr)){
534             IMMDevice_Release(device);
535             WARN("OpenPropertyStore failed: %08x\n", hr);
536             continue;
537         }
538
539         hr = get_mmdevice_guid(device, ps, &guids[i]);
540         if(FAILED(hr)){
541             IPropertyStore_Release(ps);
542             IMMDevice_Release(device);
543             continue;
544         }
545
546         hr = IPropertyStore_GetValue(ps,
547                 (const PROPERTYKEY *)&DEVPKEY_Device_FriendlyName, &pv);
548         if(FAILED(hr)){
549             IPropertyStore_Release(ps);
550             IMMDevice_Release(device);
551             WARN("GetValue(FriendlyName) failed: %08x\n", hr);
552             continue;
553         }
554
555         keep_going = cb(&guids[i], pv.u.pwszVal, wine_vxd_drv, user);
556
557         PropVariantClear(&pv);
558         IPropertyStore_Release(ps);
559         IMMDevice_Release(device);
560     }
561
562     IMMDeviceCollection_Release(coll);
563
564     return (keep_going == TRUE) ? S_OK : S_FALSE;
565 }
566
567 /***************************************************************************
568  * DirectSoundEnumerateW [DSOUND.3]
569  *
570  * Enumerate all DirectSound drivers installed in the system
571  *
572  * PARAMS
573  *    lpDSEnumCallback  [I] Address of callback function.
574  *    lpContext         [I] Address of user defined context passed to callback function.
575  *
576  * RETURNS
577  *    Success: DS_OK
578  *    Failure: DSERR_INVALIDPARAM
579  */
580 HRESULT WINAPI DirectSoundEnumerateW(
581         LPDSENUMCALLBACKW lpDSEnumCallback,
582         LPVOID lpContext )
583 {
584     HRESULT hr;
585
586     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext);
587
588     if (lpDSEnumCallback == NULL) {
589         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
590         return DSERR_INVALIDPARAM;
591     }
592
593     setup_dsound_options();
594
595     hr = enumerate_mmdevices(eRender, DSOUND_renderer_guids,
596             lpDSEnumCallback, lpContext);
597     return SUCCEEDED(hr) ? DS_OK : hr;
598 }
599
600 /***************************************************************************
601  * DirectSoundCaptureEnumerateA [DSOUND.7]
602  *
603  * Enumerate all DirectSound drivers installed in the system.
604  *
605  * PARAMS
606  *    lpDSEnumCallback  [I] Address of callback function.
607  *    lpContext         [I] Address of user defined context passed to callback function.
608  *
609  * RETURNS
610  *    Success: DS_OK
611  *    Failure: DSERR_INVALIDPARAM
612  */
613 HRESULT WINAPI DirectSoundCaptureEnumerateA(
614     LPDSENUMCALLBACKA lpDSEnumCallback,
615     LPVOID lpContext)
616 {
617     struct morecontext context;
618
619     if (lpDSEnumCallback == NULL) {
620         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
621         return DSERR_INVALIDPARAM;
622     }
623
624     context.callA = lpDSEnumCallback;
625     context.data = lpContext;
626
627     return DirectSoundCaptureEnumerateW(a_to_w_callback, &context);
628 }
629
630 /***************************************************************************
631  * DirectSoundCaptureEnumerateW [DSOUND.8]
632  *
633  * Enumerate all DirectSound drivers installed in the system.
634  *
635  * PARAMS
636  *    lpDSEnumCallback  [I] Address of callback function.
637  *    lpContext         [I] Address of user defined context passed to callback function.
638  *
639  * RETURNS
640  *    Success: DS_OK
641  *    Failure: DSERR_INVALIDPARAM
642  */
643 HRESULT WINAPI
644 DirectSoundCaptureEnumerateW(
645     LPDSENUMCALLBACKW lpDSEnumCallback,
646     LPVOID lpContext)
647 {
648     HRESULT hr;
649
650     TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext );
651
652     if (lpDSEnumCallback == NULL) {
653         WARN("invalid parameter: lpDSEnumCallback == NULL\n");
654         return DSERR_INVALIDPARAM;
655     }
656
657     setup_dsound_options();
658
659     hr = enumerate_mmdevices(eCapture, DSOUND_capture_guids,
660             lpDSEnumCallback, lpContext);
661     return SUCCEEDED(hr) ? DS_OK : hr;
662 }
663
664 /*******************************************************************************
665  * DirectSound ClassFactory
666  */
667
668 typedef  HRESULT (*FnCreateInstance)(REFIID riid, LPVOID *ppobj);
669  
670 typedef struct {
671     IClassFactory IClassFactory_iface;
672     REFCLSID rclsid;
673     FnCreateInstance pfnCreateInstance;
674 } IClassFactoryImpl;
675
676 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
677 {
678     return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
679 }
680
681 static HRESULT WINAPI
682 DSCF_QueryInterface(LPCLASSFACTORY iface, REFIID riid, LPVOID *ppobj)
683 {
684     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
685     TRACE("(%p, %s, %p)\n", This, debugstr_guid(riid), ppobj);
686     if (ppobj == NULL)
687         return E_POINTER;
688     if (IsEqualIID(riid, &IID_IUnknown) ||
689         IsEqualIID(riid, &IID_IClassFactory))
690     {
691         *ppobj = iface;
692         IUnknown_AddRef(iface);
693         return S_OK;
694     }
695     *ppobj = NULL;
696     return E_NOINTERFACE;
697 }
698
699 static ULONG WINAPI DSCF_AddRef(LPCLASSFACTORY iface)
700 {
701     return 2;
702 }
703
704 static ULONG WINAPI DSCF_Release(LPCLASSFACTORY iface)
705 {
706     /* static class, won't be freed */
707     return 1;
708 }
709
710 static HRESULT WINAPI DSCF_CreateInstance(
711     LPCLASSFACTORY iface,
712     LPUNKNOWN pOuter,
713     REFIID riid,
714     LPVOID *ppobj)
715 {
716     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
717     TRACE("(%p, %p, %s, %p)\n", This, pOuter, debugstr_guid(riid), ppobj);
718
719     if (pOuter)
720         return CLASS_E_NOAGGREGATION;
721
722     if (ppobj == NULL) {
723         WARN("invalid parameter\n");
724         return DSERR_INVALIDPARAM;
725     }
726     *ppobj = NULL;
727     return This->pfnCreateInstance(riid, ppobj);
728 }
729  
730 static HRESULT WINAPI DSCF_LockServer(LPCLASSFACTORY iface, BOOL dolock)
731 {
732     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
733     FIXME("(%p, %d) stub!\n", This, dolock);
734     return S_OK;
735 }
736
737 static const IClassFactoryVtbl DSCF_Vtbl = {
738     DSCF_QueryInterface,
739     DSCF_AddRef,
740     DSCF_Release,
741     DSCF_CreateInstance,
742     DSCF_LockServer
743 };
744
745 static IClassFactoryImpl DSOUND_CF[] = {
746     { { &DSCF_Vtbl }, &CLSID_DirectSound, (FnCreateInstance)DSOUND_Create },
747     { { &DSCF_Vtbl }, &CLSID_DirectSound8, (FnCreateInstance)DSOUND_Create8 },
748     { { &DSCF_Vtbl }, &CLSID_DirectSoundCapture, (FnCreateInstance)DSOUND_CaptureCreate },
749     { { &DSCF_Vtbl }, &CLSID_DirectSoundCapture8, (FnCreateInstance)DSOUND_CaptureCreate8 },
750     { { &DSCF_Vtbl }, &CLSID_DirectSoundFullDuplex, (FnCreateInstance)DSOUND_FullDuplexCreate },
751     { { &DSCF_Vtbl }, &CLSID_DirectSoundPrivate, (FnCreateInstance)IKsPrivatePropertySetImpl_Create },
752     { { NULL }, NULL, NULL }
753 };
754
755 /*******************************************************************************
756  * DllGetClassObject [DSOUND.@]
757  * Retrieves class object from a DLL object
758  *
759  * NOTES
760  *    Docs say returns STDAPI
761  *
762  * PARAMS
763  *    rclsid [I] CLSID for the class object
764  *    riid   [I] Reference to identifier of interface for class object
765  *    ppv    [O] Address of variable to receive interface pointer for riid
766  *
767  * RETURNS
768  *    Success: S_OK
769  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
770  *             E_UNEXPECTED
771  */
772 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
773 {
774     int i = 0;
775     TRACE("(%s, %s, %p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
776
777     if (ppv == NULL) {
778         WARN("invalid parameter\n");
779         return E_INVALIDARG;
780     }
781
782     *ppv = NULL;
783
784     if (!IsEqualIID(riid, &IID_IClassFactory) &&
785         !IsEqualIID(riid, &IID_IUnknown)) {
786         WARN("no interface for %s\n", debugstr_guid(riid));
787         return E_NOINTERFACE;
788     }
789
790     while (NULL != DSOUND_CF[i].rclsid) {
791         if (IsEqualGUID(rclsid, DSOUND_CF[i].rclsid)) {
792             DSCF_AddRef(&DSOUND_CF[i].IClassFactory_iface);
793             *ppv = &DSOUND_CF[i];
794             return S_OK;
795         }
796         i++;
797     }
798
799     WARN("(%s, %s, %p): no class found.\n", debugstr_guid(rclsid),
800          debugstr_guid(riid), ppv);
801     return CLASS_E_CLASSNOTAVAILABLE;
802 }
803
804
805 /*******************************************************************************
806  * DllCanUnloadNow [DSOUND.4]
807  * Determines whether the DLL is in use.
808  *
809  * RETURNS
810  *    Can unload now: S_OK
811  *    Cannot unload now (the DLL is still active): S_FALSE
812  */
813 HRESULT WINAPI DllCanUnloadNow(void)
814 {
815     return S_FALSE;
816 }
817
818 #define INIT_GUID(guid, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8)      \
819         guid.Data1 = l; guid.Data2 = w1; guid.Data3 = w2;               \
820         guid.Data4[0] = b1; guid.Data4[1] = b2; guid.Data4[2] = b3;     \
821         guid.Data4[3] = b4; guid.Data4[4] = b5; guid.Data4[5] = b6;     \
822         guid.Data4[6] = b7; guid.Data4[7] = b8;
823
824 /***********************************************************************
825  *           DllMain (DSOUND.init)
826  */
827 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpvReserved)
828 {
829     TRACE("(%p %d %p)\n", hInstDLL, fdwReason, lpvReserved);
830
831     switch (fdwReason) {
832     case DLL_PROCESS_ATTACH:
833         TRACE("DLL_PROCESS_ATTACH\n");
834         instance = hInstDLL;
835         DisableThreadLibraryCalls(hInstDLL);
836         /* Increase refcount on dsound by 1 */
837         GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)hInstDLL, &hInstDLL);
838         InitializeCriticalSection(&DSOUND_renderers_lock);
839         InitializeCriticalSection(&DSOUND_capturers_lock);
840         InitializeCriticalSection(&g_devenum_lock);
841         break;
842     case DLL_PROCESS_DETACH:
843         TRACE("DLL_PROCESS_DETACH\n");
844         break;
845     default:
846         TRACE("UNKNOWN REASON\n");
847         break;
848     }
849     return TRUE;
850 }
851
852 /***********************************************************************
853  *              DllRegisterServer (DSOUND.@)
854  */
855 HRESULT WINAPI DllRegisterServer(void)
856 {
857     return __wine_register_resources( instance );
858 }
859
860 /***********************************************************************
861  *              DllUnregisterServer (DSOUND.@)
862  */
863 HRESULT WINAPI DllUnregisterServer(void)
864 {
865     return __wine_unregister_resources( instance );
866 }