Added fields from NetBSD struct sigcontext on i386.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21 /*
22  * Most thread locking is complete. There may be a few race
23  * conditions still lurking.
24  *
25  * Tested with a Soundblaster clone, a Gravis UltraSound Classic,
26  * and a Turtle Beach Tropez+.
27  *
28  * TODO:
29  *      Implement SetCooperativeLevel properly (need to address focus issues)
30  *      Implement DirectSound3DBuffers (stubs in place)
31  *      Use hardware 3D support if available
32  *      Add critical section locking inside Release and AddRef methods
33  *      Handle static buffers - put those in hardware, non-static not in hardware
34  *      Hardware DuplicateSoundBuffer
35  *      Proper volume calculation, and setting volume in HEL primary buffer
36  *      Optimize WINMM and negotiate fragment size, decrease DS_HEL_MARGIN
37  */
38
39 #include "config.h"
40 #include "wine/port.h"
41
42 #include <assert.h>
43 #include <stdio.h>
44 #include <sys/types.h>
45 #include <sys/fcntl.h>
46 #ifdef HAVE_UNISTD_H
47 # include <unistd.h>
48 #endif
49 #include <stdlib.h>
50 #include <string.h>
51 #include <math.h>       /* Insomnia - pow() function */
52
53 #include "windef.h"
54 #include "winbase.h"
55 #include "winreg.h"
56 #include "winuser.h"
57 #include "wingdi.h"
58 #include "winuser.h"
59 #include "winerror.h"
60 #include "mmsystem.h"
61 #include "winternl.h"
62 #include "mmddk.h"
63 #include "wine/windef16.h"
64 #include "wine/winbase16.h"
65 #include "wine/debug.h"
66 #include "dsound.h"
67 #include "dsdriver.h"
68 #include "dsound_private.h"
69
70 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
71
72 /* these are eligible for tuning... they must be high on slow machines... */
73 /* some stuff may get more responsive with lower values though... */
74 #define DS_EMULDRIVER 0 /* some games (Quake 2, UT) refuse to accept
75                                 emulated dsound devices. set to 0 ! */
76 #define DS_HEL_MARGIN 5 /* HEL only: number of waveOut fragments ahead to mix in new buffers
77                          * (keep this close or equal to DS_HEL_QUEUE for best results) */
78 #define DS_HEL_QUEUE  5 /* HEL only: number of waveOut fragments ahead to queue to driver
79                          * (this will affect HEL sound reliability and latency) */
80
81 #define DS_SND_QUEUE_MAX 28 /* max number of fragments to prebuffer */
82 #define DS_SND_QUEUE_MIN 12 /* min number of fragments to prebuffer */
83
84 IDirectSoundImpl*       dsound = NULL;
85
86 HRESULT mmErr(UINT err)
87 {
88         switch(err) {
89         case MMSYSERR_NOERROR:
90                 return DS_OK;
91         case MMSYSERR_ALLOCATED:
92                 return DSERR_ALLOCATED;
93         case MMSYSERR_ERROR:
94         case MMSYSERR_INVALHANDLE:
95         case WAVERR_STILLPLAYING:
96                 return DSERR_GENERIC; /* FIXME */
97         case MMSYSERR_NODRIVER:
98                 return DSERR_NODRIVER;
99         case MMSYSERR_NOMEM:
100                 return DSERR_OUTOFMEMORY;
101         case MMSYSERR_INVALPARAM:
102         case WAVERR_BADFORMAT:
103         case WAVERR_UNPREPARED:
104                 return DSERR_INVALIDPARAM;
105         case MMSYSERR_NOTSUPPORTED:
106                 return DSERR_UNSUPPORTED;
107         default:
108                 FIXME("Unknown MMSYS error %d\n",err);
109                 return DSERR_GENERIC;
110         }
111 }
112
113 int ds_emuldriver = DS_EMULDRIVER;
114 int ds_hel_margin = DS_HEL_MARGIN;
115 int ds_hel_queue = DS_HEL_QUEUE;
116 int ds_snd_queue_max = DS_SND_QUEUE_MAX;
117 int ds_snd_queue_min = DS_SND_QUEUE_MIN;
118 int ds_hw_accel = DS_HW_ACCEL_FULL;
119 int ds_default_playback = 0;
120 int ds_default_capture = 0;
121
122 /*
123  * Get a config key from either the app-specific or the default config
124  */
125
126 inline static DWORD get_config_key( HKEY defkey, HKEY appkey, const char *name,
127                                     char *buffer, DWORD size )
128 {
129     if (appkey && !RegQueryValueExA( appkey, name, 0, NULL, buffer, &size )) return 0;
130     return RegQueryValueExA( defkey, name, 0, NULL, buffer, &size );
131 }
132
133
134 /*
135  * Setup the dsound options.
136  */
137
138 void setup_dsound_options(void)
139 {
140     char buffer[MAX_PATH+1];
141     HKEY hkey, appkey = 0;
142
143     buffer[MAX_PATH]='\0';
144
145     if (RegCreateKeyExA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\dsound", 0, NULL,
146                          REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, NULL ))
147     {
148         ERR("Cannot create config registry key\n" );
149         ExitProcess(1);
150     }
151
152     if (GetModuleFileNameA( 0, buffer, MAX_PATH ))
153     {
154         HKEY tmpkey;
155
156         if (!RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\AppDefaults", &tmpkey ))
157         {
158            char appname[MAX_PATH+16];
159            char *p = strrchr( buffer, '\\' );
160            if (p!=NULL) {
161                    appname[MAX_PATH]='\0';
162                    strncpy(appname,p+1,MAX_PATH);
163                    strcat(appname,"\\dsound");
164                    TRACE("appname = [%s] \n",appname);
165                    if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
166                        RegCloseKey( tmpkey );
167            }
168         }
169     }
170
171     /* get options */
172
173     if (!get_config_key( hkey, appkey, "EmulDriver", buffer, MAX_PATH ))
174         ds_emuldriver = strcmp(buffer, "N");
175
176     if (!get_config_key( hkey, appkey, "HELmargin", buffer, MAX_PATH ))
177         ds_hel_margin = atoi(buffer);
178
179     if (!get_config_key( hkey, appkey, "HELqueue", buffer, MAX_PATH ))
180         ds_hel_queue = atoi(buffer);
181
182     if (!get_config_key( hkey, appkey, "SndQueueMax", buffer, MAX_PATH ))
183         ds_snd_queue_max = atoi(buffer);
184
185     if (!get_config_key( hkey, appkey, "SndQueueMin", buffer, MAX_PATH ))
186         ds_snd_queue_min = atoi(buffer);
187
188     if (!get_config_key( hkey, appkey, "HardwareAcceleration", buffer, MAX_PATH )) {
189         if (strcmp(buffer, "Full") == 0)
190             ds_hw_accel = DS_HW_ACCEL_FULL;
191         else if (strcmp(buffer, "Standard") == 0)
192             ds_hw_accel = DS_HW_ACCEL_STANDARD;
193         else if (strcmp(buffer, "Basic") == 0)
194             ds_hw_accel = DS_HW_ACCEL_BASIC;
195         else if (strcmp(buffer, "Emulation") == 0)
196             ds_hw_accel = DS_HW_ACCEL_EMULATION;
197     }
198
199     if (!get_config_key( hkey, appkey, "DefaultPlayback", buffer, MAX_PATH ))
200             ds_default_playback = atoi(buffer);
201
202     if (!get_config_key( hkey, appkey, "DefaultCapture", buffer, MAX_PATH ))
203             ds_default_capture = atoi(buffer);
204
205     if (appkey) RegCloseKey( appkey );
206     RegCloseKey( hkey );
207
208     if (ds_emuldriver != DS_EMULDRIVER )
209        WARN("ds_emuldriver = %d (default=%d)\n",ds_emuldriver, DS_EMULDRIVER);
210     if (ds_hel_margin != DS_HEL_MARGIN )
211        WARN("ds_hel_margin = %d (default=%d)\n",ds_hel_margin, DS_HEL_MARGIN );
212     if (ds_hel_queue != DS_HEL_QUEUE )
213        WARN("ds_hel_queue = %d (default=%d)\n",ds_hel_queue, DS_HEL_QUEUE );
214     if (ds_snd_queue_max != DS_SND_QUEUE_MAX)
215        WARN("ds_snd_queue_max = %d (default=%d)\n",ds_snd_queue_max ,DS_SND_QUEUE_MAX);
216     if (ds_snd_queue_min != DS_SND_QUEUE_MIN)
217        WARN("ds_snd_queue_min = %d (default=%d)\n",ds_snd_queue_min ,DS_SND_QUEUE_MIN);
218     if (ds_hw_accel != DS_HW_ACCEL_FULL)
219         WARN("ds_hw_accel = %s (default=Full)\n", 
220             ds_hw_accel==DS_HW_ACCEL_FULL ? "Full" :
221             ds_hw_accel==DS_HW_ACCEL_STANDARD ? "Standard" :
222             ds_hw_accel==DS_HW_ACCEL_BASIC ? "Basic" :
223             ds_hw_accel==DS_HW_ACCEL_EMULATION ? "Emulation" :
224             "Unknown");
225     if (ds_default_playback != 0)
226         WARN("ds_default_playback = %d (default=0)\n",ds_default_playback);
227     if (ds_default_capture != 0)
228         WARN("ds_default_capture = %d (default=0)\n",ds_default_playback);
229 }
230
231
232
233 /***************************************************************************
234  * GetDeviceId  [DSOUND.2]
235  *
236  * Retrieves unique identifier of default device specified
237  *
238  * RETURNS
239  *    Success: DS_OK
240  *    Failure: DSERR_INVALIDPARAM
241  */
242 HRESULT WINAPI GetDeviceID(LPCGUID pGuidSrc, LPGUID pGuidDest)
243 {
244     if ( ( pGuidSrc == NULL) || (pGuidDest == NULL) ) {
245         WARN("invalid parameter\n");
246         return DSERR_INVALIDPARAM;
247     }
248
249     if ( IsEqualGUID( &DSDEVID_DefaultPlayback, pGuidSrc ) ||
250         IsEqualGUID( &DSDEVID_DefaultVoicePlayback, pGuidSrc ) ) {
251         GUID guid;
252         int err = mmErr(waveOutMessage((HWAVEOUT)ds_default_playback,DRV_QUERYDSOUNDGUID,(DWORD)&guid,0));
253         if (err == DS_OK) {
254             memcpy(pGuidDest, &guid, sizeof(GUID));
255             return DS_OK;
256         }
257     }
258
259     if ( IsEqualGUID( &DSDEVID_DefaultCapture, pGuidSrc ) ||
260         IsEqualGUID( &DSDEVID_DefaultVoiceCapture, pGuidSrc ) ) {
261         GUID guid;
262         int err = mmErr(waveInMessage((HWAVEIN)ds_default_capture,DRV_QUERYDSOUNDGUID,(DWORD)&guid,0));
263         if (err == DS_OK) {
264             memcpy(pGuidDest, &guid, sizeof(GUID));
265             return DS_OK;
266         }
267     }
268
269     memcpy(pGuidDest, pGuidSrc, sizeof(GUID));
270
271     return DS_OK;
272 }
273
274
275 /***************************************************************************
276  * DirectSoundEnumerateA [DSOUND.2]
277  *
278  * Enumerate all DirectSound drivers installed in the system
279  *
280  * RETURNS
281  *    Success: DS_OK
282  *    Failure: DSERR_INVALIDPARAM
283  */
284 HRESULT WINAPI DirectSoundEnumerateA(
285     LPDSENUMCALLBACKA lpDSEnumCallback,
286     LPVOID lpContext)
287 {
288     unsigned devs, wod;
289     DSDRIVERDESC desc;
290     GUID guid;
291     int err;
292
293     TRACE("lpDSEnumCallback = %p, lpContext = %p\n",
294         lpDSEnumCallback, lpContext);
295
296     if (lpDSEnumCallback == NULL) {
297         WARN("invalid parameter\n");
298         return DSERR_INVALIDPARAM;
299     }
300
301     devs = waveOutGetNumDevs();
302     if (devs > 0) {
303         if (GetDeviceID(&DSDEVID_DefaultPlayback, &guid) == DS_OK) {
304             GUID temp;
305             for (wod = 0; wod < devs; ++wod) {
306                 err = mmErr(waveOutMessage((HWAVEOUT)wod,DRV_QUERYDSOUNDGUID,(DWORD)&temp,0));
307                 if (err == DS_OK) {
308                     if (IsEqualGUID( &guid, &temp ) ) {
309                         err = mmErr(waveOutMessage((HWAVEOUT)wod,DRV_QUERYDSOUNDDESC,(DWORD)&desc,0));
310                         if (err == DS_OK) {
311                             TRACE("calling lpDSEnumCallback(%s,\"%s\",\"%s\",%p)\n",
312                                 debugstr_guid(&DSDEVID_DefaultPlayback),"Primary Sound Driver",desc.szDrvName,lpContext);
313                             if (lpDSEnumCallback((LPGUID)&DSDEVID_DefaultPlayback, "Primary Sound Driver", desc.szDrvName, lpContext) == FALSE)
314                                 return DS_OK;
315                         }
316                     }
317                 }
318             }
319         }
320     }
321
322     for (wod = 0; wod < devs; ++wod) {
323         err = mmErr(waveOutMessage((HWAVEOUT)wod,DRV_QUERYDSOUNDDESC,(DWORD)&desc,0));
324         if (err == DS_OK) {
325             err = mmErr(waveOutMessage((HWAVEOUT)wod,DRV_QUERYDSOUNDGUID,(DWORD)&guid,0));
326             if (err == DS_OK) {
327                 TRACE("calling lpDSEnumCallback(%s,\"%s\",\"%s\",%p)\n",
328                     debugstr_guid(&guid),desc.szDesc,desc.szDrvName,lpContext);
329                 if (lpDSEnumCallback(&guid, desc.szDesc, desc.szDrvName, lpContext) == FALSE)
330                     return DS_OK;
331             }
332         }
333     }
334     return DS_OK;
335 }
336
337 /***************************************************************************
338  * DirectSoundEnumerateW [DSOUND.3]
339  *
340  * Enumerate all DirectSound drivers installed in the system
341  *
342  * RETURNS
343  *    Success: DS_OK
344  *    Failure: DSERR_INVALIDPARAM
345  */
346 HRESULT WINAPI DirectSoundEnumerateW(
347         LPDSENUMCALLBACKW lpDSEnumCallback,
348         LPVOID lpContext )
349 {
350         FIXME("lpDSEnumCallback = %p, lpContext = %p: stub\n",
351                 lpDSEnumCallback, lpContext);
352
353         return DS_OK;
354 }
355
356
357 static void _dump_DSBCAPS(DWORD xmask) {
358         struct {
359                 DWORD   mask;
360                 char    *name;
361         } flags[] = {
362 #define FE(x) { x, #x },
363                 FE(DSBCAPS_PRIMARYBUFFER)
364                 FE(DSBCAPS_STATIC)
365                 FE(DSBCAPS_LOCHARDWARE)
366                 FE(DSBCAPS_LOCSOFTWARE)
367                 FE(DSBCAPS_CTRL3D)
368                 FE(DSBCAPS_CTRLFREQUENCY)
369                 FE(DSBCAPS_CTRLPAN)
370                 FE(DSBCAPS_CTRLVOLUME)
371                 FE(DSBCAPS_CTRLPOSITIONNOTIFY)
372                 FE(DSBCAPS_CTRLDEFAULT)
373                 FE(DSBCAPS_CTRLALL)
374                 FE(DSBCAPS_STICKYFOCUS)
375                 FE(DSBCAPS_GLOBALFOCUS)
376                 FE(DSBCAPS_GETCURRENTPOSITION2)
377                 FE(DSBCAPS_MUTE3DATMAXDISTANCE)
378 #undef FE
379         };
380         int     i;
381
382         for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
383                 if ((flags[i].mask & xmask) == flags[i].mask)
384                         DPRINTF("%s ",flags[i].name);
385 }
386
387 /*******************************************************************************
388  *              IDirectSound
389  */
390
391 static HRESULT WINAPI IDirectSoundImpl_SetCooperativeLevel(
392         LPDIRECTSOUND8 iface,HWND hwnd,DWORD level
393 ) {
394         ICOM_THIS(IDirectSoundImpl,iface);
395
396         FIXME("(%p,%08lx,%ld):stub\n",This,(DWORD)hwnd,level);
397
398         This->priolevel = level;
399
400         return DS_OK;
401 }
402
403 static HRESULT WINAPI IDirectSoundImpl_CreateSoundBuffer(
404         LPDIRECTSOUND8 iface,LPDSBUFFERDESC dsbd,LPLPDIRECTSOUNDBUFFER8 ppdsb,LPUNKNOWN lpunk
405 ) {
406         ICOM_THIS(IDirectSoundImpl,iface);
407         LPWAVEFORMATEX  wfex;
408
409         TRACE("(%p,%p,%p,%p)\n",This,dsbd,ppdsb,lpunk);
410
411         if ((This == NULL) || (dsbd == NULL) || (ppdsb == NULL))
412                 return DSERR_INVALIDPARAM;
413
414         if (TRACE_ON(dsound)) {
415                 TRACE("(structsize=%ld)\n",dsbd->dwSize);
416                 TRACE("(flags=0x%08lx:\n",dsbd->dwFlags);
417                 _dump_DSBCAPS(dsbd->dwFlags);
418                 DPRINTF(")\n");
419                 TRACE("(bufferbytes=%ld)\n",dsbd->dwBufferBytes);
420                 TRACE("(lpwfxFormat=%p)\n",dsbd->lpwfxFormat);
421         }
422
423         wfex = dsbd->lpwfxFormat;
424
425         if (wfex)
426                 TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
427                    "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
428                    wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
429                    wfex->nAvgBytesPerSec, wfex->nBlockAlign,
430                    wfex->wBitsPerSample, wfex->cbSize);
431
432         if (dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)
433                 return PrimaryBuffer_Create(This, (PrimaryBufferImpl**)ppdsb, dsbd);
434         else
435                 return SecondaryBuffer_Create(This, (IDirectSoundBufferImpl**)ppdsb, dsbd);
436 }
437
438 static HRESULT WINAPI IDirectSoundImpl_DuplicateSoundBuffer(
439         LPDIRECTSOUND8 iface,LPDIRECTSOUNDBUFFER8 pdsb,LPLPDIRECTSOUNDBUFFER8 ppdsb
440 ) {
441         ICOM_THIS(IDirectSoundImpl,iface);
442         IDirectSoundBufferImpl* ipdsb=(IDirectSoundBufferImpl*)pdsb;
443         IDirectSoundBufferImpl** ippdsb=(IDirectSoundBufferImpl**)ppdsb;
444         TRACE("(%p,%p,%p)\n",This,ipdsb,ippdsb);
445
446         if (ipdsb->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) {
447                 ERR("trying to duplicate primary buffer\n");
448                 return DSERR_INVALIDCALL;
449         }
450
451         if (ipdsb->hwbuf) {
452                 FIXME("need to duplicate hardware buffer\n");
453         }
454
455         if (ipdsb->dsbd.dwFlags & DSBCAPS_CTRL3D) {
456                 FIXME("need to duplicate 3D buffer\n");
457         }
458
459         *ippdsb = (IDirectSoundBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundBufferImpl));
460
461         IDirectSoundBuffer8_AddRef(pdsb);
462         memcpy(*ippdsb, ipdsb, sizeof(IDirectSoundBufferImpl));
463         (*ippdsb)->ref = 1;
464         (*ippdsb)->state = STATE_STOPPED;
465         (*ippdsb)->playpos = 0;
466         (*ippdsb)->buf_mixpos = 0;
467         (*ippdsb)->dsound = This;
468         (*ippdsb)->parent = ipdsb;
469         (*ippdsb)->hwbuf = NULL;
470         (*ippdsb)->ds3db = NULL; /* FIXME? */
471         (*ippdsb)->iks = NULL; /* FIXME? */
472         memcpy(&((*ippdsb)->wfx), &(ipdsb->wfx), sizeof((*ippdsb)->wfx));
473         InitializeCriticalSection(&(*ippdsb)->lock);
474         /* register buffer */
475         RtlAcquireResourceExclusive(&(This->lock), TRUE);
476         {
477                 IDirectSoundBufferImpl **newbuffers = (IDirectSoundBufferImpl**)HeapReAlloc(GetProcessHeap(),0,This->buffers,sizeof(IDirectSoundBufferImpl**)*(This->nrofbuffers+1));
478                 if (newbuffers) {
479                         This->buffers = newbuffers;
480                         This->buffers[This->nrofbuffers] = *ippdsb;
481                         This->nrofbuffers++;
482                         TRACE("buffer count is now %d\n", This->nrofbuffers);
483                 } else {
484                         ERR("out of memory for buffer list! Current buffer count is %d\n", This->nrofbuffers);
485                         /* FIXME: release buffer */
486                 }
487         }
488         RtlReleaseResource(&(This->lock));
489         IDirectSound_AddRef(iface);
490         return DS_OK;
491 }
492
493
494 static HRESULT WINAPI IDirectSoundImpl_GetCaps(LPDIRECTSOUND8 iface,LPDSCAPS caps) {
495         ICOM_THIS(IDirectSoundImpl,iface);
496         TRACE("(%p,%p)\n",This,caps);
497
498         if (caps == NULL || caps->dwSize!=sizeof(*caps))
499                 return DSERR_INVALIDPARAM;
500
501         caps->dwFlags = This->drvcaps.dwFlags;
502         TRACE("(flags=0x%08lx)\n",caps->dwFlags);
503
504         /* FIXME: copy caps from This->drvcaps */
505         caps->dwMinSecondarySampleRate          = DSBFREQUENCY_MIN;
506         caps->dwMaxSecondarySampleRate          = DSBFREQUENCY_MAX;
507
508         caps->dwPrimaryBuffers                  = 1;
509
510         caps->dwMaxHwMixingAllBuffers           = 0;
511         caps->dwMaxHwMixingStaticBuffers        = 0;
512         caps->dwMaxHwMixingStreamingBuffers     = 0;
513
514         caps->dwFreeHwMixingAllBuffers          = 0;
515         caps->dwFreeHwMixingStaticBuffers       = 0;
516         caps->dwFreeHwMixingStreamingBuffers    = 0;
517
518         caps->dwMaxHw3DAllBuffers               = 0;
519         caps->dwMaxHw3DStaticBuffers            = 0;
520         caps->dwMaxHw3DStreamingBuffers         = 0;
521
522         caps->dwFreeHw3DAllBuffers              = 0;
523         caps->dwFreeHw3DStaticBuffers           = 0;
524         caps->dwFreeHw3DStreamingBuffers        = 0;
525
526         caps->dwTotalHwMemBytes                 = 0;
527
528         caps->dwFreeHwMemBytes                  = 0;
529
530         caps->dwMaxContigFreeHwMemBytes         = 0;
531
532         caps->dwUnlockTransferRateHwBuffers     = 4096; /* But we have none... */
533
534         caps->dwPlayCpuOverheadSwBuffers        = 1;    /* 1% */
535
536         return DS_OK;
537 }
538
539 static ULONG WINAPI IDirectSoundImpl_AddRef(LPDIRECTSOUND8 iface) {
540         ICOM_THIS(IDirectSoundImpl,iface);
541         return ++(This->ref);
542 }
543
544 static ULONG WINAPI IDirectSoundImpl_Release(LPDIRECTSOUND8 iface) {
545         ICOM_THIS(IDirectSoundImpl,iface);
546         TRACE("(%p), ref was %ld\n",This,This->ref);
547         if (!--(This->ref)) {
548                 UINT i;
549
550                 timeKillEvent(This->timerID);
551                 timeEndPeriod(DS_TIME_RES);
552
553                 if (This->buffers) {
554                         for( i=0;i<This->nrofbuffers;i++)
555                                 IDirectSoundBuffer8_Release((LPDIRECTSOUNDBUFFER8)This->buffers[i]);
556                 }
557
558                 DSOUND_PrimaryDestroy(This);
559
560                 RtlDeleteResource(&This->lock);
561                 DeleteCriticalSection(&This->mixlock);
562                 if (This->driver) {
563                         IDsDriver_Close(This->driver);
564                 }
565                 if (This->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN) {
566                         waveOutClose(This->hwo);
567                 }
568                 if (This->driver)
569                         IDsDriver_Release(This->driver);
570
571                 HeapFree(GetProcessHeap(),0,This);
572                 dsound = NULL;
573                 return 0;
574         }
575         return This->ref;
576 }
577
578 static HRESULT WINAPI IDirectSoundImpl_SetSpeakerConfig(
579         LPDIRECTSOUND8 iface,DWORD config
580 ) {
581         ICOM_THIS(IDirectSoundImpl,iface);
582         FIXME("(%p,0x%08lx):stub\n",This,config);
583         return DS_OK;
584 }
585
586 static HRESULT WINAPI IDirectSoundImpl_QueryInterface(
587         LPDIRECTSOUND8 iface,REFIID riid,LPVOID *ppobj
588 ) {
589         ICOM_THIS(IDirectSoundImpl,iface);
590
591         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
592                 ERR("app requested IDirectSound3DListener on dsound object\n");
593                 *ppobj = NULL;
594                 return E_FAIL;
595         }
596
597         FIXME("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
598         return E_NOINTERFACE;
599 }
600
601 static HRESULT WINAPI IDirectSoundImpl_Compact(
602         LPDIRECTSOUND8 iface)
603 {
604         ICOM_THIS(IDirectSoundImpl,iface);
605         TRACE("(%p)\n", This);
606         return DS_OK;
607 }
608
609 static HRESULT WINAPI IDirectSoundImpl_GetSpeakerConfig(
610         LPDIRECTSOUND8 iface,
611         LPDWORD lpdwSpeakerConfig)
612 {
613         ICOM_THIS(IDirectSoundImpl,iface);
614         TRACE("(%p, %p)\n", This, lpdwSpeakerConfig);
615         *lpdwSpeakerConfig = DSSPEAKER_STEREO | (DSSPEAKER_GEOMETRY_NARROW << 16);
616         return DS_OK;
617 }
618
619 static HRESULT WINAPI IDirectSoundImpl_Initialize(
620         LPDIRECTSOUND8 iface,
621         LPCGUID lpcGuid)
622 {
623         ICOM_THIS(IDirectSoundImpl,iface);
624         TRACE("(%p, %p)\n", This, lpcGuid);
625         return DS_OK;
626 }
627
628 static HRESULT WINAPI IDirectSoundImpl_VerifyCertification(
629         LPDIRECTSOUND8 iface,
630         LPDWORD pdwCertified)
631 {
632         ICOM_THIS(IDirectSoundImpl,iface);
633         TRACE("(%p, %p)\n", This, pdwCertified);
634         *pdwCertified = DS_CERTIFIED;
635         return DS_OK;
636 }
637
638 static ICOM_VTABLE(IDirectSound8) dsvt =
639 {
640         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
641         IDirectSoundImpl_QueryInterface,
642         IDirectSoundImpl_AddRef,
643         IDirectSoundImpl_Release,
644         IDirectSoundImpl_CreateSoundBuffer,
645         IDirectSoundImpl_GetCaps,
646         IDirectSoundImpl_DuplicateSoundBuffer,
647         IDirectSoundImpl_SetCooperativeLevel,
648         IDirectSoundImpl_Compact,
649         IDirectSoundImpl_GetSpeakerConfig,
650         IDirectSoundImpl_SetSpeakerConfig,
651         IDirectSoundImpl_Initialize,
652         IDirectSoundImpl_VerifyCertification
653 };
654
655
656 /*******************************************************************************
657  *              DirectSoundCreate (DSOUND.1)
658  */
659 HRESULT WINAPI DirectSoundCreate8(LPCGUID lpcGUID,LPDIRECTSOUND8 *ppDS,IUnknown *pUnkOuter )
660 {
661         IDirectSoundImpl** ippDS=(IDirectSoundImpl**)ppDS;
662         PIDSDRIVER drv = NULL;
663         unsigned wod, wodn;
664         HRESULT err = DSERR_INVALIDPARAM;
665         GUID devGuid;
666         TRACE("(%p,%p,%p)\n",lpcGUID,ippDS,pUnkOuter);
667
668         if (ippDS == NULL)
669                 return DSERR_INVALIDPARAM;
670
671         /* Get dsound configuration */
672         setup_dsound_options();
673
674         /* Default device? */
675         if ( !lpcGUID || IsEqualGUID(lpcGUID, &GUID_NULL) )
676                 lpcGUID = &DSDEVID_DefaultPlayback;
677
678         if (GetDeviceID(lpcGUID, &devGuid) != DS_OK) {
679                 WARN("invalid parameter\n");
680                 return DSERR_INVALIDPARAM;
681         }
682
683         if (dsound && IsEqualGUID(&devGuid, &dsound->guid) ) {
684                 ERR("dsound already opened\n");
685                 if (IsEqualGUID(&devGuid, &dsound->guid) ) {
686                         IDirectSound_AddRef((LPDIRECTSOUND)dsound);
687                         *ippDS = dsound;
688                         return DS_OK;
689                 } else {
690                         ERR("different dsound already opened\n");
691                 }
692         }
693
694         /* Enumerate WINMM audio devices and find the one we want */
695         wodn = waveOutGetNumDevs();
696         if (!wodn) return DSERR_NODRIVER;
697
698         for (wod=0; wod<wodn; wod++) {
699                 GUID guid;
700                 err = mmErr(waveOutMessage((HWAVEOUT)wod,DRV_QUERYDSOUNDGUID,(DWORD)(&guid),0));
701                 if (err != DS_OK) {
702                         WARN("waveOutMessage failed; err=%lx\n",err);
703                         return err;
704                 }
705                 if (IsEqualGUID( &devGuid, &guid) ) {
706                         err = DS_OK;
707                         break;
708                 }
709         }
710
711         if (err != DS_OK) {
712                 WARN("invalid parameter\n");
713                 return DSERR_INVALIDPARAM;
714         }
715
716         /* DRV_QUERYDSOUNDIFACE is a "Wine extension" to get the DSound interface */
717         waveOutMessage((HWAVEOUT)wod, DRV_QUERYDSOUNDIFACE, (DWORD)&drv, 0);
718
719         /* Disable the direct sound driver to force emulation if requested. */
720         if (ds_hw_accel == DS_HW_ACCEL_EMULATION)
721             drv = NULL;
722         
723         /* Allocate memory */
724         *ippDS = (IDirectSoundImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundImpl));
725         if (*ippDS == NULL)
726                 return DSERR_OUTOFMEMORY;
727
728         ICOM_VTBL(*ippDS)       = &dsvt;
729         (*ippDS)->ref           = 1;
730
731         (*ippDS)->driver        = drv;
732         (*ippDS)->priolevel     = DSSCL_NORMAL;
733         (*ippDS)->fraglen       = 0;
734         (*ippDS)->hwbuf         = NULL;
735         (*ippDS)->buffer        = NULL;
736         (*ippDS)->buflen        = 0;
737         (*ippDS)->writelead     = 0;
738         (*ippDS)->state         = STATE_STOPPED;
739         (*ippDS)->nrofbuffers   = 0;
740         (*ippDS)->buffers       = NULL;
741 /*      (*ippDS)->primary       = NULL; */
742         (*ippDS)->listener      = NULL;
743
744         (*ippDS)->prebuf        = ds_snd_queue_max;
745         (*ippDS)->guid          = devGuid;
746
747         /* Get driver description */
748         if (drv) {
749                 IDsDriver_GetDriverDesc(drv,&((*ippDS)->drvdesc));
750         } else {
751                 /* if no DirectSound interface available, use WINMM API instead */
752                 (*ippDS)->drvdesc.dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT;
753                 (*ippDS)->drvdesc.dnDevNode = wod; /* FIXME? */
754         }
755
756         /* Set default wave format (may need it for waveOutOpen) */
757         (*ippDS)->wfx.wFormatTag        = WAVE_FORMAT_PCM;
758         /* We rely on the sound driver to return the actual sound format of 
759          * the device if it does not support 22050x8x2 and is given the 
760          * WAVE_DIRECTSOUND flag.
761          */
762         (*ippDS)->wfx.nSamplesPerSec = 22050;
763         (*ippDS)->wfx.wBitsPerSample = 8;
764         (*ippDS)->wfx.nChannels = 2;
765         (*ippDS)->wfx.nBlockAlign = (*ippDS)->wfx.wBitsPerSample * (*ippDS)->wfx.nChannels / 8;
766         (*ippDS)->wfx.nAvgBytesPerSec = (*ippDS)->wfx.nSamplesPerSec * (*ippDS)->wfx.nBlockAlign;
767         (*ippDS)->wfx.cbSize = 0;
768
769         /* If the driver requests being opened through MMSYSTEM
770          * (which is recommended by the DDK), it is supposed to happen
771          * before the DirectSound interface is opened */
772         if ((*ippDS)->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN)
773         {
774                 DWORD flags = CALLBACK_FUNCTION;
775
776                 /* disable direct sound if requested */
777                 if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
778                     flags |= WAVE_DIRECTSOUND;
779
780                 /* FIXME: is this right? */
781                 (*ippDS)->drvdesc.dnDevNode = 0;
782                 err = DSERR_ALLOCATED;
783
784                 /* if this device is busy try the next one */
785                 while((err == DSERR_ALLOCATED) &&
786                         ((*ippDS)->drvdesc.dnDevNode < wodn))
787                 {
788                   err = mmErr(waveOutOpen(&((*ippDS)->hwo),
789                                           (*ippDS)->drvdesc.dnDevNode, &((*ippDS)->wfx),
790                                           (DWORD)DSOUND_callback, (DWORD)(*ippDS),
791                                           flags));
792                   (*ippDS)->drvdesc.dnDevNode++; /* next wave device */
793                 }
794
795                 (*ippDS)->drvdesc.dnDevNode--; /* take away last increment */
796         }
797
798         if (drv && (err == DS_OK))
799                 err = IDsDriver_Open(drv);
800
801         /* FIXME: do we want to handle a temporarily busy device? */
802         if (err != DS_OK) {
803                 HeapFree(GetProcessHeap(),0,*ippDS);
804                 *ippDS = NULL;
805                 return err;
806         }
807
808         /* the driver is now open, so it's now allowed to call GetCaps */
809         if (drv) {
810                 IDsDriver_GetCaps(drv,&((*ippDS)->drvcaps));
811         } else {
812                 /* FIXME: We should check the device capabilities */
813                 (*ippDS)->drvcaps.dwFlags =
814                         DSCAPS_PRIMARY16BIT | DSCAPS_PRIMARYSTEREO;
815                 if (ds_emuldriver)
816                     (*ippDS)->drvcaps.dwFlags |= DSCAPS_EMULDRIVER;
817         }
818
819         DSOUND_RecalcVolPan(&((*ippDS)->volpan));
820
821         InitializeCriticalSection(&((*ippDS)->mixlock));
822         RtlInitializeResource(&((*ippDS)->lock));
823
824         if (!dsound) {
825                 dsound = (*ippDS);
826                 DSOUND_PrimaryCreate(dsound);
827                 timeBeginPeriod(DS_TIME_RES);
828                 dsound->timerID = timeSetEvent(DS_TIME_DEL, DS_TIME_RES, DSOUND_timer,
829                                                (DWORD)dsound, TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
830         }
831         return DS_OK;
832 }
833
834
835 /*******************************************************************************
836  * DirectSound ClassFactory
837  */
838 typedef struct
839 {
840     /* IUnknown fields */
841     ICOM_VFIELD(IClassFactory);
842     DWORD                       ref;
843 } IClassFactoryImpl;
844
845 static HRESULT WINAPI
846 DSCF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
847         ICOM_THIS(IClassFactoryImpl,iface);
848
849         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
850         return E_NOINTERFACE;
851 }
852
853 static ULONG WINAPI
854 DSCF_AddRef(LPCLASSFACTORY iface) {
855         ICOM_THIS(IClassFactoryImpl,iface);
856         return ++(This->ref);
857 }
858
859 static ULONG WINAPI DSCF_Release(LPCLASSFACTORY iface) {
860         ICOM_THIS(IClassFactoryImpl,iface);
861         /* static class, won't be  freed */
862         return --(This->ref);
863 }
864
865 static HRESULT WINAPI DSCF_CreateInstance(
866         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
867 ) {
868         ICOM_THIS(IClassFactoryImpl,iface);
869
870         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
871         if ( IsEqualGUID( &IID_IDirectSound, riid ) ||
872              IsEqualGUID( &IID_IDirectSound8, riid ) ) {
873                 /* FIXME: reuse already created dsound if present? */
874                 return DirectSoundCreate8(riid,(LPDIRECTSOUND8*)ppobj,pOuter);
875         }
876         return E_NOINTERFACE;
877 }
878
879 static HRESULT WINAPI DSCF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
880         ICOM_THIS(IClassFactoryImpl,iface);
881         FIXME("(%p)->(%d),stub!\n",This,dolock);
882         return S_OK;
883 }
884
885 static ICOM_VTABLE(IClassFactory) DSCF_Vtbl = {
886         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
887         DSCF_QueryInterface,
888         DSCF_AddRef,
889         DSCF_Release,
890         DSCF_CreateInstance,
891         DSCF_LockServer
892 };
893 static IClassFactoryImpl DSOUND_CF = {&DSCF_Vtbl, 1 };
894
895 /*******************************************************************************
896  * DllGetClassObject [DSOUND.5]
897  * Retrieves class object from a DLL object
898  *
899  * NOTES
900  *    Docs say returns STDAPI
901  *
902  * PARAMS
903  *    rclsid [I] CLSID for the class object
904  *    riid   [I] Reference to identifier of interface for class object
905  *    ppv    [O] Address of variable to receive interface pointer for riid
906  *
907  * RETURNS
908  *    Success: S_OK
909  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
910  *             E_UNEXPECTED
911  */
912 DWORD WINAPI DSOUND_DllGetClassObject(REFCLSID rclsid,REFIID riid,LPVOID *ppv)
913 {
914     TRACE("(%p,%p,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
915     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
916         *ppv = (LPVOID)&DSOUND_CF;
917         IClassFactory_AddRef((IClassFactory*)*ppv);
918     return S_OK;
919     }
920
921     FIXME("(%p,%p,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
922     return CLASS_E_CLASSNOTAVAILABLE;
923 }
924
925
926 /*******************************************************************************
927  * DllCanUnloadNow [DSOUND.4]  Determines whether the DLL is in use.
928  *
929  * RETURNS
930  *    Success: S_OK
931  *    Failure: S_FALSE
932  */
933 DWORD WINAPI DSOUND_DllCanUnloadNow(void)
934 {
935     FIXME("(void): stub\n");
936     return S_FALSE;
937 }