Made the buffer list in the directsound object thread-safe.
[wine] / dlls / dsound / dsound_main.c
1 /*                      DirectSound
2  * 
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  */
6 /*
7  * Note: This file requires multithread ability. It is not possible to
8  * implement the stuff in a single thread anyway. And most DirectX apps
9  * require threading themselves.
10  *
11  * Most thread locking is complete. There may be a few race
12  * conditions still lurking.
13  *
14  * Tested with a Soundblaster clone, a Gravis UltraSound Classic,
15  * and a Turtle Beach Tropez+.
16  *
17  * TODO:
18  *      Implement DirectSoundCapture API
19  *      Implement SetCooperativeLevel properly (need to address focus issues)
20  *      Use wavetable synth for static buffers if available
21  *      Implement DirectSound3DBuffers (stubs in place)
22  *      Use hardware 3D support if available (OSS support may be needed first)
23  *      Add support for APIs other than OSS: ALSA (http://alsa.jcu.cz/)
24  *      and esound (http://www.gnome.org), for instance
25  *
26  * FIXME: Status needs updating.
27  *
28  * Status:
29  * - Wing Commander 4/W95:
30  *   The intromovie plays without problems. Nearly lipsynchron.
31  * - DiscWorld 2
32  *   The sound works, but noticeable chunks are left out (from the sound and
33  *   the animation). Don't know why yet.
34  * - Diablo:
35  *   Sound works, but slows down the movieplayer.
36  * - XvT: 
37  *   Doesn't sound yet.
38  * - Monkey Island 3:
39  *   The background sound of the startscreen works ;)
40  * - WingCommander Prophecy Demo:
41  *   Sound works for the intromovie.
42  * - Total Annihilation (1998/12/04):
43  *   Sound plays perfectly in the game, but the Smacker movies
44  *   (http://www.smacker.com/) play silently.
45  * - A-10 Cuba! Demo (1998/12/04):
46  *   Sound works properly (for some people).
47  * - dsstream.exe, from DirectX 5.2 SDK (1998/12/04):
48  *   Works properly, but requires "-dll -winmm".
49  * - dsshow.exe, from DirectX 5.2 SDK (1998/12/04):
50  *   Initializes the DLL properly with CoCreateInstance(), but the
51  *   FileOpen dialog box is broken - could not test properly
52  */
53
54 #include "config.h"
55 #include <assert.h>
56 #include <errno.h>
57 #include <stdio.h>
58 #include <sys/types.h>
59 #include <sys/time.h>
60 #include <sys/fcntl.h>
61 #include <unistd.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <math.h>       /* Insomnia - pow() function */
65 #include "dsound.h"
66 #include "windef.h"
67 #include "wingdi.h"
68 #include "winuser.h"
69 #include "winerror.h"
70 #include "wine/obj_base.h"
71 #include "thread.h"
72 #include "debugtools.h"
73
74 DEFAULT_DEBUG_CHANNEL(dsound);
75
76
77 /*****************************************************************************
78  * Predeclare the interface implementation structures
79  */
80 typedef struct IDirectSoundImpl IDirectSoundImpl;
81 typedef struct IDirectSoundBufferImpl IDirectSoundBufferImpl;
82 typedef struct IDirectSoundNotifyImpl IDirectSoundNotifyImpl;
83 typedef struct IDirectSound3DListenerImpl IDirectSound3DListenerImpl;
84 typedef struct IDirectSound3DBufferImpl IDirectSound3DBufferImpl;
85
86 /*****************************************************************************
87  * IDirectSound implementation structure
88  */
89 struct IDirectSoundImpl
90 {
91     /* IUnknown fields */
92     ICOM_VFIELD(IDirectSound);
93     DWORD                      ref;
94     /* IDirectSoundImpl fields */
95     DWORD                       priolevel;
96     int                         nrofbuffers;
97     IDirectSoundBufferImpl**    buffers;
98     IDirectSoundBufferImpl*     primary;
99     IDirectSound3DListenerImpl* listener;
100     WAVEFORMATEX                wfx; /* current main waveformat */
101     CRITICAL_SECTION            lock;
102 };
103
104 /*****************************************************************************
105  * IDirectSoundBuffer implementation structure
106  */
107 struct IDirectSoundBufferImpl
108 {
109     /* IUnknown fields */
110     ICOM_VFIELD(IDirectSoundBuffer);
111     DWORD                            ref;
112     /* IDirectSoundBufferImpl fields */
113     WAVEFORMATEX              wfx;
114     LPBYTE                    buffer;
115     IDirectSound3DBufferImpl* ds3db;
116     DWORD                     playflags,playing;
117     DWORD                     playpos,writepos,buflen;
118     DWORD                     nAvgBytesPerSec;
119     DWORD                     freq;
120     ULONG                     freqAdjust;
121     LONG                      volume,pan;
122     LONG                      lVolAdjust,rVolAdjust;
123     IDirectSoundBufferImpl*   parent;         /* for duplicates */
124     IDirectSoundImpl*         dsound;
125     DSBUFFERDESC              dsbd;
126     LPDSBPOSITIONNOTIFY       notifies;
127     int                       nrofnotifies;
128     CRITICAL_SECTION          lock;
129 };
130
131 /*****************************************************************************
132  * IDirectSoundNotify implementation structure
133  */
134 struct IDirectSoundNotifyImpl
135 {
136     /* IUnknown fields */
137     ICOM_VFIELD(IDirectSoundNotify);
138     DWORD                            ref;
139     /* IDirectSoundNotifyImpl fields */
140     IDirectSoundBufferImpl* dsb;
141 };
142
143 /*****************************************************************************
144  *  IDirectSound3DListener implementation structure
145  */
146 struct IDirectSound3DListenerImpl
147 {
148     /* IUnknown fields */
149     ICOM_VFIELD(IDirectSound3DListener);
150     DWORD                                ref;
151     /* IDirectSound3DListenerImpl fields */
152     IDirectSoundBufferImpl* dsb;
153     DS3DLISTENER            ds3dl;
154     CRITICAL_SECTION        lock;   
155 };
156
157 /*****************************************************************************
158  * IDirectSound3DBuffer implementation structure
159  */
160 struct IDirectSound3DBufferImpl
161 {
162     /* IUnknown fields */
163     ICOM_VFIELD(IDirectSound3DBuffer);
164     DWORD                              ref;
165     /* IDirectSound3DBufferImpl fields */
166     IDirectSoundBufferImpl* dsb;
167     DS3DBUFFER              ds3db;
168     LPBYTE                  buffer;
169     DWORD                   buflen;
170     CRITICAL_SECTION        lock;
171 };
172
173
174 #ifdef HAVE_OSS
175 # include <sys/ioctl.h>
176 # ifdef HAVE_MACHINE_SOUNDCARD_H
177 #  include <machine/soundcard.h>
178 # endif
179 # ifdef HAVE_SYS_SOUNDCARD_H
180 #  include <sys/soundcard.h>
181 # endif
182 # ifdef HAVE_SOUNDCARD_H
183 #  include <soundcard.h>
184 # endif
185
186 /* #define USE_DSOUND3D 1 */
187
188 #define DSOUND_FRAGLEN (primarybuf->wfx.nAvgBytesPerSec >> 4)
189 #define DSOUND_FREQSHIFT (14)
190
191 static int audiofd = -1;
192 static int audioOK = 0;
193
194 static IDirectSoundImpl*        dsound = NULL;
195
196 static IDirectSoundBufferImpl*  primarybuf = NULL;
197
198 static int DSOUND_setformat(LPWAVEFORMATEX wfex);
199 static void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len);
200 static void DSOUND_CloseAudio(void);
201
202 #endif
203
204
205 HRESULT WINAPI DirectSoundEnumerateA(
206         LPDSENUMCALLBACKA enumcb,
207         LPVOID context)
208 {
209         TRACE("enumcb = %p, context = %p\n", enumcb, context);
210
211 #ifdef HAVE_OSS
212         if (enumcb != NULL)
213                 enumcb(NULL,"WINE DirectSound using Open Sound System",
214                     "sound",context);
215 #endif
216
217         return DS_OK;
218 }
219
220 #ifdef HAVE_OSS
221 static void _dump_DSBCAPS(DWORD xmask) {
222         struct {
223                 DWORD   mask;
224                 char    *name;
225         } flags[] = {
226 #define FE(x) { x, #x },
227                 FE(DSBCAPS_PRIMARYBUFFER)
228                 FE(DSBCAPS_STATIC)
229                 FE(DSBCAPS_LOCHARDWARE)
230                 FE(DSBCAPS_LOCSOFTWARE)
231                 FE(DSBCAPS_CTRLFREQUENCY)
232                 FE(DSBCAPS_CTRLPAN)
233                 FE(DSBCAPS_CTRLVOLUME)
234                 FE(DSBCAPS_CTRLDEFAULT)
235                 FE(DSBCAPS_CTRLALL)
236                 FE(DSBCAPS_STICKYFOCUS)
237                 FE(DSBCAPS_GETCURRENTPOSITION2)
238         };
239         int     i;
240
241         for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
242                 if (flags[i].mask & xmask)
243                         DPRINTF("%s ",flags[i].name);
244 }
245
246 /*******************************************************************************
247  *              IDirectSound3DBuffer
248  */
249
250 /* IUnknown methods */
251 static HRESULT WINAPI IDirectSound3DBufferImpl_QueryInterface(
252         LPDIRECTSOUND3DBUFFER iface, REFIID riid, LPVOID *ppobj)
253 {
254         ICOM_THIS(IDirectSound3DBufferImpl,iface);
255
256         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
257         return E_FAIL;
258 }
259         
260 static ULONG WINAPI IDirectSound3DBufferImpl_AddRef(LPDIRECTSOUND3DBUFFER iface)
261 {
262         ICOM_THIS(IDirectSound3DBufferImpl,iface);
263         This->ref++;
264         return This->ref;
265 }
266
267 static ULONG WINAPI IDirectSound3DBufferImpl_Release(LPDIRECTSOUND3DBUFFER iface)
268 {
269         ICOM_THIS(IDirectSound3DBufferImpl,iface);
270         if(--This->ref)
271                 return This->ref;
272
273         HeapFree(GetProcessHeap(),0,This->buffer);
274         HeapFree(GetProcessHeap(),0,This);
275
276         return S_OK;
277 }
278
279 /* IDirectSound3DBuffer methods */
280 static HRESULT WINAPI IDirectSound3DBufferImpl_GetAllParameters(
281         LPDIRECTSOUND3DBUFFER iface,
282         LPDS3DBUFFER lpDs3dBuffer)
283 {
284         FIXME("stub\n");
285         return DS_OK;
286 }
287
288 static HRESULT WINAPI IDirectSound3DBufferImpl_GetConeAngles(
289         LPDIRECTSOUND3DBUFFER iface,
290         LPDWORD lpdwInsideConeAngle,
291         LPDWORD lpdwOutsideConeAngle)
292 {
293         FIXME("stub\n");
294         return DS_OK;
295 }
296
297 static HRESULT WINAPI IDirectSound3DBufferImpl_GetConeOrientation(
298         LPDIRECTSOUND3DBUFFER iface,
299         LPD3DVECTOR lpvConeOrientation)
300 {
301         FIXME("stub\n");
302         return DS_OK;
303 }
304
305 static HRESULT WINAPI IDirectSound3DBufferImpl_GetConeOutsideVolume(
306         LPDIRECTSOUND3DBUFFER iface,
307         LPLONG lplConeOutsideVolume)
308 {
309         FIXME("stub\n");
310         return DS_OK;
311 }
312
313 static HRESULT WINAPI IDirectSound3DBufferImpl_GetMaxDistance(
314         LPDIRECTSOUND3DBUFFER iface,
315         LPD3DVALUE lpfMaxDistance)
316 {
317         FIXME("stub\n");
318         return DS_OK;
319 }
320
321 static HRESULT WINAPI IDirectSound3DBufferImpl_GetMinDistance(
322         LPDIRECTSOUND3DBUFFER iface,
323         LPD3DVALUE lpfMinDistance)
324 {
325         FIXME("stub\n");
326         return DS_OK;
327 }
328
329 static HRESULT WINAPI IDirectSound3DBufferImpl_GetMode(
330         LPDIRECTSOUND3DBUFFER iface,
331         LPDWORD lpdwMode)
332 {
333         FIXME("stub\n");
334         return DS_OK;
335 }
336
337 static HRESULT WINAPI IDirectSound3DBufferImpl_GetPosition(
338         LPDIRECTSOUND3DBUFFER iface,
339         LPD3DVECTOR lpvPosition)
340 {
341         FIXME("stub\n");
342         return DS_OK;
343 }
344
345 static HRESULT WINAPI IDirectSound3DBufferImpl_GetVelocity(
346         LPDIRECTSOUND3DBUFFER iface,
347         LPD3DVECTOR lpvVelocity)
348 {
349         FIXME("stub\n");
350         return DS_OK;
351 }
352
353 static HRESULT WINAPI IDirectSound3DBufferImpl_SetAllParameters(
354         LPDIRECTSOUND3DBUFFER iface,
355         LPCDS3DBUFFER lpcDs3dBuffer,
356         DWORD dwApply)
357 {
358         FIXME("stub\n");
359         return DS_OK;
360 }
361
362 static HRESULT WINAPI IDirectSound3DBufferImpl_SetConeAngles(
363         LPDIRECTSOUND3DBUFFER iface,
364         DWORD dwInsideConeAngle,
365         DWORD dwOutsideConeAngle,
366         DWORD dwApply)
367 {
368         FIXME("stub\n");
369         return DS_OK;
370 }
371
372 static HRESULT WINAPI IDirectSound3DBufferImpl_SetConeOrientation(
373         LPDIRECTSOUND3DBUFFER iface,
374         D3DVALUE x, D3DVALUE y, D3DVALUE z,
375         DWORD dwApply)
376 {
377         FIXME("stub\n");
378         return DS_OK;
379 }
380
381 static HRESULT WINAPI IDirectSound3DBufferImpl_SetConeOutsideVolume(
382         LPDIRECTSOUND3DBUFFER iface,
383         LONG lConeOutsideVolume,
384         DWORD dwApply)
385 {
386         FIXME("stub\n");
387         return DS_OK;
388 }
389
390 static HRESULT WINAPI IDirectSound3DBufferImpl_SetMaxDistance(
391         LPDIRECTSOUND3DBUFFER iface,
392         D3DVALUE fMaxDistance,
393         DWORD dwApply)
394 {
395         FIXME("stub\n");
396         return DS_OK;
397 }
398
399 static HRESULT WINAPI IDirectSound3DBufferImpl_SetMinDistance(
400         LPDIRECTSOUND3DBUFFER iface,
401         D3DVALUE fMinDistance,
402         DWORD dwApply)
403 {
404         FIXME("stub\n");
405         return DS_OK;
406 }
407
408 static HRESULT WINAPI IDirectSound3DBufferImpl_SetMode(
409         LPDIRECTSOUND3DBUFFER iface,
410         DWORD dwMode,
411         DWORD dwApply)
412 {
413         ICOM_THIS(IDirectSound3DBufferImpl,iface);
414         TRACE("mode = %lx\n", dwMode);
415         This->ds3db.dwMode = dwMode;
416         return DS_OK;
417 }
418
419 static HRESULT WINAPI IDirectSound3DBufferImpl_SetPosition(
420         LPDIRECTSOUND3DBUFFER iface,
421         D3DVALUE x, D3DVALUE y, D3DVALUE z,
422         DWORD dwApply)
423 {
424         FIXME("stub\n");
425         return DS_OK;
426 }
427
428 static HRESULT WINAPI IDirectSound3DBufferImpl_SetVelocity(
429         LPDIRECTSOUND3DBUFFER iface,
430         D3DVALUE x, D3DVALUE y, D3DVALUE z,
431         DWORD dwApply)
432 {
433         FIXME("stub\n");
434         return DS_OK;
435 }
436
437 ICOM_VTABLE(IDirectSound3DBuffer) ds3dbvt = 
438 {
439         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
440         /* IUnknown methods */
441         IDirectSound3DBufferImpl_QueryInterface,
442         IDirectSound3DBufferImpl_AddRef,
443         IDirectSound3DBufferImpl_Release,
444         /* IDirectSound3DBuffer methods */
445         IDirectSound3DBufferImpl_GetAllParameters,
446         IDirectSound3DBufferImpl_GetConeAngles,
447         IDirectSound3DBufferImpl_GetConeOrientation,
448         IDirectSound3DBufferImpl_GetConeOutsideVolume,
449         IDirectSound3DBufferImpl_GetMaxDistance,
450         IDirectSound3DBufferImpl_GetMinDistance,
451         IDirectSound3DBufferImpl_GetMode,
452         IDirectSound3DBufferImpl_GetPosition,
453         IDirectSound3DBufferImpl_GetVelocity,
454         IDirectSound3DBufferImpl_SetAllParameters,
455         IDirectSound3DBufferImpl_SetConeAngles,
456         IDirectSound3DBufferImpl_SetConeOrientation,
457         IDirectSound3DBufferImpl_SetConeOutsideVolume,
458         IDirectSound3DBufferImpl_SetMaxDistance,
459         IDirectSound3DBufferImpl_SetMinDistance,
460         IDirectSound3DBufferImpl_SetMode,
461         IDirectSound3DBufferImpl_SetPosition,
462         IDirectSound3DBufferImpl_SetVelocity,
463 };
464
465 #ifdef USE_DSOUND3D
466 static int DSOUND_Create3DBuffer(IDirectSoundBufferImpl* dsb)
467 {
468         DWORD   i, temp, iSize, oSize, offset;
469         LPBYTE  bIbuf, bObuf, bTbuf = NULL;
470         LPWORD  wIbuf, wObuf, wTbuf = NULL;
471
472         /* Inside DirectX says it's stupid but allowed */
473         if (dsb->wfx.nChannels == 2) {
474                 /* Convert to mono */
475                 if (dsb->wfx.wBitsPerSample == 16) {
476                         iSize = dsb->buflen / 4;
477                         wTbuf = malloc(dsb->buflen / 2);
478                         if (wTbuf == NULL)
479                                 return DSERR_OUTOFMEMORY;
480                         for (i = 0; i < iSize; i++)
481                                 wTbuf[i] = (dsb->buffer[i] + dsb->buffer[(i * 2) + 1]) / 2;
482                         wIbuf = wTbuf;
483                 } else {
484                         iSize = dsb->buflen / 2;
485                         bTbuf = malloc(dsb->buflen / 2);
486                         if (bTbuf == NULL)
487                                 return DSERR_OUTOFMEMORY;
488                         for (i = 0; i < iSize; i++)
489                                 bTbuf[i] = (dsb->buffer[i] + dsb->buffer[(i * 2) + 1]) / 2;
490                         bIbuf = bTbuf;
491                 }
492         } else {
493                 if (dsb->wfx.wBitsPerSample == 16) {
494                         iSize = dsb->buflen / 2;
495                         wIbuf = (LPWORD) dsb->buffer;
496                 } else {
497                         bIbuf = (LPBYTE) dsb->buffer;
498                         iSize = dsb->buflen;
499                 }
500         }
501
502         if (primarybuf->wfx.wBitsPerSample == 16) {
503                 wObuf = (LPWORD) dsb->ds3db->buffer;
504                 oSize = dsb->ds3db->buflen / 2;
505         } else {
506                 bObuf = (LPBYTE) dsb->ds3db->buffer;
507                 oSize = dsb->ds3db->buflen;
508         }
509
510         offset = primarybuf->wfx.nSamplesPerSec / 100;          /* 10ms */
511         if (primarybuf->wfx.wBitsPerSample == 16 && dsb->wfx.wBitsPerSample == 16)
512                 for (i = 0; i < iSize; i++) {
513                         temp = wIbuf[i];
514                         if (i >= offset)
515                                 temp += wIbuf[i - offset] >> 9;
516                         else
517                                 temp += wIbuf[i + iSize - offset] >> 9;
518                         wObuf[i * 2] = temp;
519                         wObuf[(i * 2) + 1] = temp;
520                 }
521         else if (primarybuf->wfx.wBitsPerSample == 8 && dsb->wfx.wBitsPerSample == 8)
522                 for (i = 0; i < iSize; i++) {
523                         temp = bIbuf[i];
524                         if (i >= offset)
525                                 temp += bIbuf[i - offset] >> 5;
526                         else
527                                 temp += bIbuf[i + iSize - offset] >> 5;
528                         bObuf[i * 2] = temp;
529                         bObuf[(i * 2) + 1] = temp;
530                 }
531         
532         if (wTbuf)
533                 free(wTbuf);
534         if (bTbuf)
535                 free(bTbuf);
536
537         return DS_OK;
538 }
539 #endif
540 /*******************************************************************************
541  *              IDirectSound3DListener
542  */
543
544 /* IUnknown methods */
545 static HRESULT WINAPI IDirectSound3DListenerImpl_QueryInterface(
546         LPDIRECTSOUND3DLISTENER iface, REFIID riid, LPVOID *ppobj)
547 {
548         ICOM_THIS(IDirectSound3DListenerImpl,iface);
549
550         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
551         return E_FAIL;
552 }
553         
554 static ULONG WINAPI IDirectSound3DListenerImpl_AddRef(LPDIRECTSOUND3DLISTENER iface)
555 {
556         ICOM_THIS(IDirectSound3DListenerImpl,iface);
557         This->ref++;
558         return This->ref;
559 }
560
561 static ULONG WINAPI IDirectSound3DListenerImpl_Release(LPDIRECTSOUND3DLISTENER iface)
562 {
563         ICOM_THIS(IDirectSound3DListenerImpl,iface);
564         This->ref--;
565         return This->ref;
566 }
567
568 /* IDirectSound3DListener methods */
569 static HRESULT WINAPI IDirectSound3DListenerImpl_GetAllParameter(
570         LPDIRECTSOUND3DLISTENER iface,
571         LPDS3DLISTENER lpDS3DL)
572 {
573         FIXME("stub\n");
574         return DS_OK;
575 }
576
577 static HRESULT WINAPI IDirectSound3DListenerImpl_GetDistanceFactor(
578         LPDIRECTSOUND3DLISTENER iface,
579         LPD3DVALUE lpfDistanceFactor)
580 {
581         FIXME("stub\n");
582         return DS_OK;
583 }
584
585 static HRESULT WINAPI IDirectSound3DListenerImpl_GetDopplerFactor(
586         LPDIRECTSOUND3DLISTENER iface,
587         LPD3DVALUE lpfDopplerFactor)
588 {
589         FIXME("stub\n");
590         return DS_OK;
591 }
592
593 static HRESULT WINAPI IDirectSound3DListenerImpl_GetOrientation(
594         LPDIRECTSOUND3DLISTENER iface,
595         LPD3DVECTOR lpvOrientFront,
596         LPD3DVECTOR lpvOrientTop)
597 {
598         FIXME("stub\n");
599         return DS_OK;
600 }
601
602 static HRESULT WINAPI IDirectSound3DListenerImpl_GetPosition(
603         LPDIRECTSOUND3DLISTENER iface,
604         LPD3DVECTOR lpvPosition)
605 {
606         FIXME("stub\n");
607         return DS_OK;
608 }
609
610 static HRESULT WINAPI IDirectSound3DListenerImpl_GetRolloffFactor(
611         LPDIRECTSOUND3DLISTENER iface,
612         LPD3DVALUE lpfRolloffFactor)
613 {
614         FIXME("stub\n");
615         return DS_OK;
616 }
617
618 static HRESULT WINAPI IDirectSound3DListenerImpl_GetVelocity(
619         LPDIRECTSOUND3DLISTENER iface,
620         LPD3DVECTOR lpvVelocity)
621 {
622         FIXME("stub\n");
623         return DS_OK;
624 }
625
626 static HRESULT WINAPI IDirectSound3DListenerImpl_SetAllParameters(
627         LPDIRECTSOUND3DLISTENER iface,
628         LPCDS3DLISTENER lpcDS3DL,
629         DWORD dwApply)
630 {
631         FIXME("stub\n");
632         return DS_OK;
633 }
634
635 static HRESULT WINAPI IDirectSound3DListenerImpl_SetDistanceFactor(
636         LPDIRECTSOUND3DLISTENER iface,
637         D3DVALUE fDistanceFactor,
638         DWORD dwApply)
639 {
640         FIXME("stub\n");
641         return DS_OK;
642 }
643
644 static HRESULT WINAPI IDirectSound3DListenerImpl_SetDopplerFactor(
645         LPDIRECTSOUND3DLISTENER iface,
646         D3DVALUE fDopplerFactor,
647         DWORD dwApply)
648 {
649         FIXME("stub\n");
650         return DS_OK;
651 }
652
653 static HRESULT WINAPI IDirectSound3DListenerImpl_SetOrientation(
654         LPDIRECTSOUND3DLISTENER iface,
655         D3DVALUE xFront, D3DVALUE yFront, D3DVALUE zFront,
656         D3DVALUE xTop, D3DVALUE yTop, D3DVALUE zTop,
657         DWORD dwApply)
658 {
659         FIXME("stub\n");
660         return DS_OK;
661 }
662
663 static HRESULT WINAPI IDirectSound3DListenerImpl_SetPosition(
664         LPDIRECTSOUND3DLISTENER iface,
665         D3DVALUE x, D3DVALUE y, D3DVALUE z,
666         DWORD dwApply)
667 {
668         FIXME("stub\n");
669         return DS_OK;
670 }
671
672 static HRESULT WINAPI IDirectSound3DListenerImpl_SetRolloffFactor(
673         LPDIRECTSOUND3DLISTENER iface,
674         D3DVALUE fRolloffFactor,
675         DWORD dwApply)
676 {
677         FIXME("stub\n");
678         return DS_OK;
679 }
680
681 static HRESULT WINAPI IDirectSound3DListenerImpl_SetVelocity(
682         LPDIRECTSOUND3DLISTENER iface,
683         D3DVALUE x, D3DVALUE y, D3DVALUE z,
684         DWORD dwApply)
685 {
686         FIXME("stub\n");
687         return DS_OK;
688 }
689
690 static HRESULT WINAPI IDirectSound3DListenerImpl_CommitDeferredSettings(
691         LPDIRECTSOUND3DLISTENER iface)
692
693 {
694         FIXME("stub\n");
695         return DS_OK;
696 }
697
698 ICOM_VTABLE(IDirectSound3DListener) ds3dlvt = 
699 {
700         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
701         /* IUnknown methods */
702         IDirectSound3DListenerImpl_QueryInterface,
703         IDirectSound3DListenerImpl_AddRef,
704         IDirectSound3DListenerImpl_Release,
705         /* IDirectSound3DListener methods */
706         IDirectSound3DListenerImpl_GetAllParameter,
707         IDirectSound3DListenerImpl_GetDistanceFactor,
708         IDirectSound3DListenerImpl_GetDopplerFactor,
709         IDirectSound3DListenerImpl_GetOrientation,
710         IDirectSound3DListenerImpl_GetPosition,
711         IDirectSound3DListenerImpl_GetRolloffFactor,
712         IDirectSound3DListenerImpl_GetVelocity,
713         IDirectSound3DListenerImpl_SetAllParameters,
714         IDirectSound3DListenerImpl_SetDistanceFactor,
715         IDirectSound3DListenerImpl_SetDopplerFactor,
716         IDirectSound3DListenerImpl_SetOrientation,
717         IDirectSound3DListenerImpl_SetPosition,
718         IDirectSound3DListenerImpl_SetRolloffFactor,
719         IDirectSound3DListenerImpl_SetVelocity,
720         IDirectSound3DListenerImpl_CommitDeferredSettings,
721 };
722
723 /*******************************************************************************
724  *              IDirectSoundNotify
725  */
726 static HRESULT WINAPI IDirectSoundNotifyImpl_QueryInterface(
727         LPDIRECTSOUNDNOTIFY iface,REFIID riid,LPVOID *ppobj
728 ) {
729         ICOM_THIS(IDirectSoundNotifyImpl,iface);
730
731         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
732         return E_FAIL;
733 }
734
735 static ULONG WINAPI IDirectSoundNotifyImpl_AddRef(LPDIRECTSOUNDNOTIFY iface) {
736         ICOM_THIS(IDirectSoundNotifyImpl,iface);
737         return ++(This->ref);
738 }
739
740 static ULONG WINAPI IDirectSoundNotifyImpl_Release(LPDIRECTSOUNDNOTIFY iface) {
741         ICOM_THIS(IDirectSoundNotifyImpl,iface);
742         This->ref--;
743         if (!This->ref) {
744                 IDirectSoundNotify_Release((LPDIRECTSOUNDBUFFER)This->dsb);
745                 HeapFree(GetProcessHeap(),0,This);
746                 return S_OK;
747         }
748         return This->ref;
749 }
750
751 static HRESULT WINAPI IDirectSoundNotifyImpl_SetNotificationPositions(
752         LPDIRECTSOUNDNOTIFY iface,DWORD howmuch,LPCDSBPOSITIONNOTIFY notify
753 ) {
754         ICOM_THIS(IDirectSoundNotifyImpl,iface);
755         int     i;
756
757         if (TRACE_ON(dsound)) {
758             TRACE("(%p,0x%08lx,%p)\n",This,howmuch,notify);
759             for (i=0;i<howmuch;i++)
760                     TRACE("notify at %ld to 0x%08lx\n",
761                             notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
762         }
763         This->dsb->notifies = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,This->dsb->notifies,(This->dsb->nrofnotifies+howmuch)*sizeof(DSBPOSITIONNOTIFY));
764         memcpy( This->dsb->notifies+This->dsb->nrofnotifies,
765                 notify,
766                 howmuch*sizeof(DSBPOSITIONNOTIFY)
767         );
768         This->dsb->nrofnotifies+=howmuch;
769
770         return S_OK;
771 }
772
773 ICOM_VTABLE(IDirectSoundNotify) dsnvt = 
774 {
775         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
776         IDirectSoundNotifyImpl_QueryInterface,
777         IDirectSoundNotifyImpl_AddRef,
778         IDirectSoundNotifyImpl_Release,
779         IDirectSoundNotifyImpl_SetNotificationPositions,
780 };
781
782 /*******************************************************************************
783  *              IDirectSoundBuffer
784  */
785
786 /* This sets this format for the <em>Primary Buffer Only</em> */
787 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
788 static HRESULT WINAPI IDirectSoundBufferImpl_SetFormat(
789         LPDIRECTSOUNDBUFFER iface,LPWAVEFORMATEX wfex
790 ) {
791         ICOM_THIS(IDirectSoundBufferImpl,iface);
792         IDirectSoundBufferImpl** dsb;
793         int                     i;
794
795         /* Let's be pedantic! */
796         if ((wfex == NULL) ||
797             (wfex->wFormatTag != WAVE_FORMAT_PCM) ||
798             (wfex->nChannels < 1) || (wfex->nChannels > 2) ||
799             (wfex->nSamplesPerSec < 1) ||
800             (wfex->nBlockAlign < 1) || (wfex->nChannels > 4) ||
801             ((wfex->wBitsPerSample != 8) && (wfex->wBitsPerSample != 16))) {
802                 TRACE("failed pedantic check!\n");
803                 return DSERR_INVALIDPARAM;
804         }
805
806         /* **** */
807         EnterCriticalSection(&(This->dsound->lock));
808
809         if (primarybuf->wfx.nSamplesPerSec != wfex->nSamplesPerSec) {
810                 dsb = dsound->buffers;
811                 for (i = 0; i < dsound->nrofbuffers; i++, dsb++) {
812                         /* **** */
813                         EnterCriticalSection(&((*dsb)->lock));
814
815                         (*dsb)->freqAdjust = ((*dsb)->freq << DSOUND_FREQSHIFT) /
816                                 wfex->nSamplesPerSec;
817
818                         LeaveCriticalSection(&((*dsb)->lock));
819                         /* **** */
820                 }
821         }
822
823         memcpy(&(primarybuf->wfx), wfex, sizeof(primarybuf->wfx));
824
825         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld"
826                    "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
827                    wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
828                    wfex->nAvgBytesPerSec, wfex->nBlockAlign, 
829                    wfex->wBitsPerSample, wfex->cbSize);
830
831         primarybuf->wfx.nAvgBytesPerSec =
832                 This->wfx.nSamplesPerSec * This->wfx.nBlockAlign;
833         DSOUND_CloseAudio();
834
835         LeaveCriticalSection(&(This->dsound->lock));
836         /* **** */
837
838         return DS_OK;
839 }
840
841 static HRESULT WINAPI IDirectSoundBufferImpl_SetVolume(
842         LPDIRECTSOUNDBUFFER iface,LONG vol
843 ) {
844         ICOM_THIS(IDirectSoundBufferImpl,iface);
845         double  temp;
846
847         TRACE("(%p,%ld)\n",This,vol);
848
849         /* I'm not sure if we need this for primary buffer */
850         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
851                 return DSERR_CONTROLUNAVAIL;
852
853         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN))
854                 return DSERR_INVALIDPARAM;
855
856         /* This needs to adjust the soundcard volume when */
857         /* called for the primary buffer */
858         if (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) {
859                 FIXME("Volume control of primary unimplemented.\n");
860                 This->volume = vol;
861                 return DS_OK;
862         }
863
864         /* **** */
865         EnterCriticalSection(&(This->lock));
866
867         This->volume = vol;
868
869         temp = (double) (This->volume - (This->pan > 0 ? This->pan : 0));
870         This->lVolAdjust = (ULONG) (pow(2.0, temp / 600.0) * 32768.0);
871         temp = (double) (This->volume + (This->pan < 0 ? This->pan : 0));
872         This->rVolAdjust = (ULONG) (pow(2.0, temp / 600.0) * 32768.0);
873
874         LeaveCriticalSection(&(This->lock));
875         /* **** */
876
877         TRACE("left = %lx, right = %lx\n", This->lVolAdjust, This->rVolAdjust);
878
879         return DS_OK;
880 }
881
882 static HRESULT WINAPI IDirectSoundBufferImpl_GetVolume(
883         LPDIRECTSOUNDBUFFER iface,LPLONG vol
884 ) {
885         ICOM_THIS(IDirectSoundBufferImpl,iface);
886         TRACE("(%p,%p)\n",This,vol);
887
888         if (vol == NULL)
889                 return DSERR_INVALIDPARAM;
890
891         *vol = This->volume;
892         return DS_OK;
893 }
894
895 static HRESULT WINAPI IDirectSoundBufferImpl_SetFrequency(
896         LPDIRECTSOUNDBUFFER iface,DWORD freq
897 ) {
898         ICOM_THIS(IDirectSoundBufferImpl,iface);
899         TRACE("(%p,%ld)\n",This,freq);
900
901         /* You cannot set the frequency of the primary buffer */
902         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY) ||
903             (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER))
904                 return DSERR_CONTROLUNAVAIL;
905
906         if ((freq < DSBFREQUENCY_MIN) || (freq > DSBFREQUENCY_MAX))
907                 return DSERR_INVALIDPARAM;
908
909         /* **** */
910         EnterCriticalSection(&(This->lock));
911
912         This->freq = freq;
913         This->freqAdjust = (freq << DSOUND_FREQSHIFT) / primarybuf->wfx.nSamplesPerSec;
914         This->nAvgBytesPerSec = freq * This->wfx.nBlockAlign;
915
916         LeaveCriticalSection(&(This->lock));
917         /* **** */
918
919         return DS_OK;
920 }
921
922 static HRESULT WINAPI IDirectSoundBufferImpl_Play(
923         LPDIRECTSOUNDBUFFER iface,DWORD reserved1,DWORD reserved2,DWORD flags
924 ) {
925         ICOM_THIS(IDirectSoundBufferImpl,iface);
926         TRACE("(%p,%08lx,%08lx,%08lx)\n",
927                 This,reserved1,reserved2,flags
928         );
929         This->playflags = flags;
930         This->playing = 1;
931         return DS_OK;
932 }
933
934 static HRESULT WINAPI IDirectSoundBufferImpl_Stop(LPDIRECTSOUNDBUFFER iface)
935 {
936         ICOM_THIS(IDirectSoundBufferImpl,iface);
937         TRACE("(%p)\n",This);
938
939         /* **** */
940         EnterCriticalSection(&(This->lock));
941
942         This->playing = 0;
943         DSOUND_CheckEvent(This, 0);
944
945         LeaveCriticalSection(&(This->lock));
946         /* **** */
947
948         return DS_OK;
949 }
950
951 static DWORD WINAPI IDirectSoundBufferImpl_AddRef(LPDIRECTSOUNDBUFFER iface) {
952         ICOM_THIS(IDirectSoundBufferImpl,iface);
953 /*      TRACE(dsound,"(%p) ref was %ld\n",This, This->ref); */
954
955         return ++(This->ref);
956 }
957 static DWORD WINAPI IDirectSoundBufferImpl_Release(LPDIRECTSOUNDBUFFER iface) {
958         ICOM_THIS(IDirectSoundBufferImpl,iface);
959         int     i;
960
961 /*      TRACE(dsound,"(%p) ref was %ld\n",This, This->ref); */
962
963         if (--This->ref)
964                 return This->ref;
965
966         EnterCriticalSection(&(This->dsound->lock));
967         for (i=0;i<This->dsound->nrofbuffers;i++)
968                 if (This->dsound->buffers[i] == This)
969                         break;
970         if (i < This->dsound->nrofbuffers) {
971                 /* Put the last buffer of the list in the (now empty) position */
972                 This->dsound->buffers[i] = This->dsound->buffers[This->dsound->nrofbuffers - 1];
973                 This->dsound->buffers = HeapReAlloc(GetProcessHeap(),0,This->dsound->buffers,sizeof(LPDIRECTSOUNDBUFFER)*This->dsound->nrofbuffers);
974                 This->dsound->nrofbuffers--;
975                 IDirectSound_Release((LPDIRECTSOUND)This->dsound);
976         }
977         LeaveCriticalSection(&(This->dsound->lock));
978
979         DeleteCriticalSection(&(This->lock));
980         if (This->ds3db && ICOM_VTBL(This->ds3db))
981                 IDirectSound3DBuffer_Release((LPDIRECTSOUND3DBUFFER)This->ds3db);
982         if (This->parent)
983                 /* this is a duplicate buffer */
984                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->parent);
985         else
986                 /* this is a toplevel buffer */
987                 HeapFree(GetProcessHeap(),0,This->buffer);
988
989         HeapFree(GetProcessHeap(),0,This);
990         
991         if (This == primarybuf)
992                 primarybuf = NULL;
993
994         return DS_OK;
995 }
996
997 static HRESULT WINAPI IDirectSoundBufferImpl_GetCurrentPosition(
998         LPDIRECTSOUNDBUFFER iface,LPDWORD playpos,LPDWORD writepos
999 ) {
1000         ICOM_THIS(IDirectSoundBufferImpl,iface);
1001         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
1002         if (playpos) *playpos = This->playpos;
1003         if (writepos) *writepos = This->writepos;
1004         TRACE("playpos = %ld, writepos = %ld\n", playpos?*playpos:0, writepos?*writepos:0);
1005         return DS_OK;
1006 }
1007
1008 static HRESULT WINAPI IDirectSoundBufferImpl_GetStatus(
1009         LPDIRECTSOUNDBUFFER iface,LPDWORD status
1010 ) {
1011         ICOM_THIS(IDirectSoundBufferImpl,iface);
1012         TRACE("(%p,%p)\n",This,status);
1013
1014         if (status == NULL)
1015                 return DSERR_INVALIDPARAM;
1016
1017         *status = 0;
1018         if (This->playing)
1019                 *status |= DSBSTATUS_PLAYING;
1020         if (This->playflags & DSBPLAY_LOOPING)
1021                 *status |= DSBSTATUS_LOOPING;
1022
1023         return DS_OK;
1024 }
1025
1026
1027 static HRESULT WINAPI IDirectSoundBufferImpl_GetFormat(
1028         LPDIRECTSOUNDBUFFER iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten
1029 ) {
1030         ICOM_THIS(IDirectSoundBufferImpl,iface);
1031         TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
1032
1033         if (wfsize>sizeof(This->wfx))
1034                 wfsize = sizeof(This->wfx);
1035         if (lpwf) {     /* NULL is valid */
1036                 memcpy(lpwf,&(This->wfx),wfsize);
1037                 if (wfwritten)
1038                         *wfwritten = wfsize;
1039         } else
1040                 if (wfwritten)
1041                         *wfwritten = sizeof(This->wfx);
1042                 else
1043                         return DSERR_INVALIDPARAM;
1044
1045         return DS_OK;
1046 }
1047
1048 static HRESULT WINAPI IDirectSoundBufferImpl_Lock(
1049         LPDIRECTSOUNDBUFFER iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
1050 ) {
1051         ICOM_THIS(IDirectSoundBufferImpl,iface);
1052
1053         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx)\n",
1054                 This,
1055                 writecursor,
1056                 writebytes,
1057                 lplpaudioptr1,
1058                 audiobytes1,
1059                 lplpaudioptr2,
1060                 audiobytes2,
1061                 flags
1062         );
1063         if (flags & DSBLOCK_FROMWRITECURSOR)
1064                 writecursor += This->writepos;
1065         if (flags & DSBLOCK_ENTIREBUFFER)
1066                 writebytes = This->buflen;
1067         if (writebytes > This->buflen)
1068                 writebytes = This->buflen;
1069
1070         assert(audiobytes1!=audiobytes2);
1071         assert(lplpaudioptr1!=lplpaudioptr2);
1072         if (writecursor+writebytes <= This->buflen) {
1073                 *(LPBYTE*)lplpaudioptr1 = This->buffer+writecursor;
1074                 *audiobytes1 = writebytes;
1075                 if (lplpaudioptr2)
1076                         *(LPBYTE*)lplpaudioptr2 = NULL;
1077                 if (audiobytes2)
1078                         *audiobytes2 = 0;
1079                 TRACE("->%ld.0\n",writebytes);
1080         } else {
1081                 *(LPBYTE*)lplpaudioptr1 = This->buffer+writecursor;
1082                 *audiobytes1 = This->buflen-writecursor;
1083                 if (lplpaudioptr2)
1084                         *(LPBYTE*)lplpaudioptr2 = This->buffer;
1085                 if (audiobytes2)
1086                         *audiobytes2 = writebytes-(This->buflen-writecursor);
1087                 TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
1088         }
1089         /* No. See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 21 */
1090         /* This->writepos=(writecursor+writebytes)%This->buflen; */
1091         return DS_OK;
1092 }
1093
1094 static HRESULT WINAPI IDirectSoundBufferImpl_SetCurrentPosition(
1095         LPDIRECTSOUNDBUFFER iface,DWORD newpos
1096 ) {
1097         ICOM_THIS(IDirectSoundBufferImpl,iface);
1098         TRACE("(%p,%ld)\n",This,newpos);
1099
1100         /* **** */
1101         EnterCriticalSection(&(This->lock));
1102
1103         This->playpos = newpos;
1104
1105         LeaveCriticalSection(&(This->lock));
1106         /* **** */
1107
1108         return DS_OK;
1109 }
1110
1111 static HRESULT WINAPI IDirectSoundBufferImpl_SetPan(
1112         LPDIRECTSOUNDBUFFER iface,LONG pan
1113 ) {
1114         ICOM_THIS(IDirectSoundBufferImpl,iface);
1115         double  temp;
1116
1117         TRACE("(%p,%ld)\n",This,pan);
1118
1119         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT))
1120                 return DSERR_INVALIDPARAM;
1121
1122         /* You cannot set the pan of the primary buffer */
1123         /* and you cannot use both pan and 3D controls */
1124         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
1125             (This->dsbd.dwFlags & DSBCAPS_CTRL3D) ||
1126             (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER))
1127                 return DSERR_CONTROLUNAVAIL;
1128
1129         /* **** */
1130         EnterCriticalSection(&(This->lock));
1131
1132         This->pan = pan;
1133         
1134         temp = (double) (This->volume - (This->pan > 0 ? This->pan : 0));
1135         This->lVolAdjust = (ULONG) (pow(2.0, temp / 600.0) * 32768.0);
1136         temp = (double) (This->volume + (This->pan < 0 ? This->pan : 0));
1137         This->rVolAdjust = (ULONG) (pow(2.0, temp / 600.0) * 32768.0);
1138
1139         LeaveCriticalSection(&(This->lock));
1140         /* **** */
1141
1142         return DS_OK;
1143 }
1144
1145 static HRESULT WINAPI IDirectSoundBufferImpl_GetPan(
1146         LPDIRECTSOUNDBUFFER iface,LPLONG pan
1147 ) {
1148         ICOM_THIS(IDirectSoundBufferImpl,iface);
1149         TRACE("(%p,%p)\n",This,pan);
1150
1151         if (pan == NULL)
1152                 return DSERR_INVALIDPARAM;
1153
1154         *pan = This->pan;
1155
1156         return DS_OK;
1157 }
1158
1159 static HRESULT WINAPI IDirectSoundBufferImpl_Unlock(
1160         LPDIRECTSOUNDBUFFER iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
1161 ) {
1162         ICOM_THIS(IDirectSoundBufferImpl,iface);
1163         TRACE("(%p,%p,%ld,%p,%ld):stub\n", This,p1,x1,p2,x2);
1164
1165         /* There is really nothing to do here. Should someone */
1166         /* choose to implement static buffers in hardware (by */
1167         /* using a wave table synth, for example) this is where */
1168         /* you'd want to do the loading. For software buffers, */
1169         /* which is what we currently use, we need do nothing. */
1170
1171 #if 0
1172         /* It's also the place to pre-process 3D buffers... */
1173         
1174         /* This is highly experimental and liable to break things */
1175         if (This->dsbd.dwFlags & DSBCAPS_CTRL3D)
1176                 DSOUND_Create3DBuffer(This);
1177 #endif
1178
1179         return DS_OK;
1180 }
1181
1182 static HRESULT WINAPI IDirectSoundBufferImpl_GetFrequency(
1183         LPDIRECTSOUNDBUFFER iface,LPDWORD freq
1184 ) {
1185         ICOM_THIS(IDirectSoundBufferImpl,iface);
1186         TRACE("(%p,%p)\n",This,freq);
1187
1188         if (freq == NULL)
1189                 return DSERR_INVALIDPARAM;
1190
1191         *freq = This->freq;
1192
1193         return DS_OK;
1194 }
1195
1196 static HRESULT WINAPI IDirectSoundBufferImpl_Initialize(
1197         LPDIRECTSOUNDBUFFER iface,LPDIRECTSOUND dsound,LPDSBUFFERDESC dbsd
1198 ) {
1199         ICOM_THIS(IDirectSoundBufferImpl,iface);
1200         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
1201         DPRINTF("Re-Init!!!\n");
1202         return DSERR_ALREADYINITIALIZED;
1203 }
1204
1205 static HRESULT WINAPI IDirectSoundBufferImpl_GetCaps(
1206         LPDIRECTSOUNDBUFFER iface,LPDSBCAPS caps
1207 ) {
1208         ICOM_THIS(IDirectSoundBufferImpl,iface);
1209         TRACE("(%p)->(%p)\n",This,caps);
1210   
1211         if (caps == NULL)
1212                 return DSERR_INVALIDPARAM;
1213
1214         /* I think we should check this value, not set it. See */
1215         /* Inside DirectX, p215. That should apply here, too. */
1216         caps->dwSize = sizeof(*caps);
1217
1218         caps->dwFlags = This->dsbd.dwFlags | DSBCAPS_LOCSOFTWARE;
1219         caps->dwBufferBytes = This->dsbd.dwBufferBytes;
1220         /* This value represents the speed of the "unlock" command.
1221            As unlock is quite fast (it does not do anything), I put
1222            4096 ko/s = 4 Mo / s */
1223         caps->dwUnlockTransferRate = 4096;
1224         caps->dwPlayCpuOverhead = 0;
1225         
1226         return DS_OK;
1227 }
1228
1229 static HRESULT WINAPI IDirectSoundBufferImpl_QueryInterface(
1230         LPDIRECTSOUNDBUFFER iface,REFIID riid,LPVOID *ppobj
1231 ) {
1232         ICOM_THIS(IDirectSoundBufferImpl,iface);
1233
1234         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
1235
1236         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
1237                 IDirectSoundNotifyImpl  *dsn;
1238
1239                 dsn = (IDirectSoundNotifyImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(*dsn));
1240                 dsn->ref = 1;
1241                 dsn->dsb = This;
1242                 IDirectSoundBuffer_AddRef(iface);
1243                 ICOM_VTBL(dsn) = &dsnvt;
1244                 *ppobj = (LPVOID)dsn;
1245                 return S_OK;
1246         }
1247
1248         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1249                 *ppobj = This->ds3db;
1250                 if (*ppobj)
1251                         return DS_OK;
1252         }
1253
1254         return E_FAIL;
1255 }
1256
1257 static ICOM_VTABLE(IDirectSoundBuffer) dsbvt = 
1258 {
1259         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1260         IDirectSoundBufferImpl_QueryInterface,
1261         IDirectSoundBufferImpl_AddRef,
1262         IDirectSoundBufferImpl_Release,
1263         IDirectSoundBufferImpl_GetCaps,
1264         IDirectSoundBufferImpl_GetCurrentPosition,
1265         IDirectSoundBufferImpl_GetFormat,
1266         IDirectSoundBufferImpl_GetVolume,
1267         IDirectSoundBufferImpl_GetPan,
1268         IDirectSoundBufferImpl_GetFrequency,
1269         IDirectSoundBufferImpl_GetStatus,
1270         IDirectSoundBufferImpl_Initialize,
1271         IDirectSoundBufferImpl_Lock,
1272         IDirectSoundBufferImpl_Play,
1273         IDirectSoundBufferImpl_SetCurrentPosition,
1274         IDirectSoundBufferImpl_SetFormat,
1275         IDirectSoundBufferImpl_SetVolume,
1276         IDirectSoundBufferImpl_SetPan,
1277         IDirectSoundBufferImpl_SetFrequency,
1278         IDirectSoundBufferImpl_Stop,
1279         IDirectSoundBufferImpl_Unlock
1280 };
1281
1282 /*******************************************************************************
1283  *              IDirectSound
1284  */
1285
1286 static HRESULT WINAPI IDirectSoundImpl_SetCooperativeLevel(
1287         LPDIRECTSOUND iface,HWND hwnd,DWORD level
1288 ) {
1289         ICOM_THIS(IDirectSoundImpl,iface);
1290         FIXME("(%p,%08lx,%ld):stub\n",This,(DWORD)hwnd,level);
1291         return DS_OK;
1292 }
1293
1294 static HRESULT WINAPI IDirectSoundImpl_CreateSoundBuffer(
1295         LPDIRECTSOUND iface,LPDSBUFFERDESC dsbd,LPLPDIRECTSOUNDBUFFER ppdsb,LPUNKNOWN lpunk
1296 ) {
1297         ICOM_THIS(IDirectSoundImpl,iface);
1298         IDirectSoundBufferImpl** ippdsb=(IDirectSoundBufferImpl**)ppdsb;
1299         LPWAVEFORMATEX  wfex;
1300
1301         TRACE("(%p,%p,%p,%p)\n",This,dsbd,ippdsb,lpunk);
1302         
1303         if ((This == NULL) || (dsbd == NULL) || (ippdsb == NULL))
1304                 return DSERR_INVALIDPARAM;
1305         
1306         if (TRACE_ON(dsound)) {
1307                 TRACE("(size=%ld)\n",dsbd->dwSize);
1308                 TRACE("(flags=0x%08lx\n",dsbd->dwFlags);
1309                 _dump_DSBCAPS(dsbd->dwFlags);
1310                 TRACE("(bufferbytes=%ld)\n",dsbd->dwBufferBytes);
1311                 TRACE("(lpwfxFormat=%p)\n",dsbd->lpwfxFormat);
1312         }
1313
1314         wfex = dsbd->lpwfxFormat;
1315
1316         if (wfex)
1317                 TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld"
1318                    "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1319                    wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
1320                    wfex->nAvgBytesPerSec, wfex->nBlockAlign, 
1321                    wfex->wBitsPerSample, wfex->cbSize);
1322
1323         if (dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER) {
1324                 if (primarybuf) {
1325                         IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)primarybuf);
1326                         *ippdsb = primarybuf;
1327                         primarybuf->dsbd.dwFlags = dsbd->dwFlags;
1328                         return DS_OK;
1329                 } /* Else create primarybuf */
1330         }
1331
1332         *ippdsb = (IDirectSoundBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundBufferImpl));
1333         if (*ippdsb == NULL)
1334                 return DSERR_OUTOFMEMORY;
1335         (*ippdsb)->ref = 1;
1336
1337         TRACE("Created buffer at %p\n", *ippdsb);
1338
1339         if (dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER) {
1340                 (*ippdsb)->buflen = dsound->wfx.nAvgBytesPerSec;
1341                 (*ippdsb)->freq = dsound->wfx.nSamplesPerSec;
1342         } else {
1343                 (*ippdsb)->buflen = dsbd->dwBufferBytes;
1344                 (*ippdsb)->freq = dsbd->lpwfxFormat->nSamplesPerSec;
1345         }
1346         (*ippdsb)->buffer = (LPBYTE)HeapAlloc(GetProcessHeap(),0,(*ippdsb)->buflen);
1347         if ((*ippdsb)->buffer == NULL) {
1348                 HeapFree(GetProcessHeap(),0,(*ippdsb));
1349                 *ippdsb = NULL;
1350                 return DSERR_OUTOFMEMORY;
1351         }
1352         /* It's not necessary to initialize values to zero since */
1353         /* we allocated this structure with HEAP_ZERO_MEMORY... */
1354         (*ippdsb)->playpos = 0;
1355         (*ippdsb)->writepos = 0;
1356         (*ippdsb)->parent = NULL;
1357         ICOM_VTBL(*ippdsb) = &dsbvt;
1358         (*ippdsb)->dsound = This;
1359         (*ippdsb)->playing = 0;
1360         (*ippdsb)->lVolAdjust = (1 << 15);
1361         (*ippdsb)->rVolAdjust = (1 << 15);
1362
1363         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
1364                 (*ippdsb)->freqAdjust = ((*ippdsb)->freq << DSOUND_FREQSHIFT) /
1365                         primarybuf->wfx.nSamplesPerSec;
1366                 (*ippdsb)->nAvgBytesPerSec = (*ippdsb)->freq *
1367                         dsbd->lpwfxFormat->nBlockAlign;
1368         }
1369
1370         memcpy(&((*ippdsb)->dsbd),dsbd,sizeof(*dsbd));
1371
1372         EnterCriticalSection(&(This->lock));
1373         /* register buffer */
1374         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
1375                 This->buffers = (IDirectSoundBufferImpl**)HeapReAlloc(GetProcessHeap(),0,This->buffers,sizeof(IDirectSoundBufferImpl*)*(This->nrofbuffers+1));
1376                 This->buffers[This->nrofbuffers] = *ippdsb;
1377                 This->nrofbuffers++;
1378         }
1379         LeaveCriticalSection(&(This->lock));
1380
1381         IDirectSound_AddRef(iface);
1382
1383         if (dsbd->lpwfxFormat)
1384                 memcpy(&((*ippdsb)->wfx), dsbd->lpwfxFormat, sizeof((*ippdsb)->wfx));
1385
1386         InitializeCriticalSection(&((*ippdsb)->lock));
1387         
1388 #if USE_DSOUND3D
1389         if (dsbd->dwFlags & DSBCAPS_CTRL3D) {
1390                 IDirectSound3DBufferImpl        *ds3db;
1391
1392                 ds3db = (IDirectSound3DBufferImpl*)HeapAlloc(GetProcessHeap(),
1393                         0,sizeof(*ds3db));
1394                 ds3db->ref = 1;
1395                 ds3db->dsb = (*ippdsb);
1396                 ICOM_VTBL(ds3db) = &ds3dbvt;
1397                 (*ippdsb)->ds3db = ds3db;
1398                 ds3db->ds3db.dwSize = sizeof(DS3DBUFFER);
1399                 ds3db->ds3db.vPosition.x.x = 0.0;
1400                 ds3db->ds3db.vPosition.y.y = 0.0;
1401                 ds3db->ds3db.vPosition.z.z = 0.0;
1402                 ds3db->ds3db.vVelocity.x.x = 0.0;
1403                 ds3db->ds3db.vVelocity.y.y = 0.0;
1404                 ds3db->ds3db.vVelocity.z.z = 0.0;
1405                 ds3db->ds3db.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
1406                 ds3db->ds3db.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
1407                 ds3db->ds3db.vConeOrientation.x.x = 0.0;
1408                 ds3db->ds3db.vConeOrientation.y.y = 0.0;
1409                 ds3db->ds3db.vConeOrientation.z.z = 0.0;
1410                 ds3db->ds3db.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;
1411                 ds3db->ds3db.flMinDistance = DS3D_DEFAULTMINDISTANCE;
1412                 ds3db->ds3db.flMaxDistance = DS3D_DEFAULTMAXDISTANCE;
1413                 ds3db->ds3db.dwMode = DS3DMODE_NORMAL;
1414                 ds3db->buflen = ((*ippdsb)->buflen * primarybuf->wfx.nBlockAlign) /
1415                         (*ippdsb)->wfx.nBlockAlign;
1416                 ds3db->buffer = HeapAlloc(GetProcessHeap(), 0, ds3db->buflen);
1417                 if (ds3db->buffer == NULL) {
1418                         ds3db->buflen = 0;
1419                         ds3db->ds3db.dwMode = DS3DMODE_DISABLE;
1420                 }
1421         }
1422 #endif
1423         return DS_OK;
1424 }
1425
1426 static HRESULT WINAPI IDirectSoundImpl_DuplicateSoundBuffer(
1427         LPDIRECTSOUND iface,LPDIRECTSOUNDBUFFER pdsb,LPLPDIRECTSOUNDBUFFER ppdsb
1428 ) {
1429         ICOM_THIS(IDirectSoundImpl,iface);
1430         IDirectSoundBufferImpl* ipdsb=(IDirectSoundBufferImpl*)pdsb;
1431         IDirectSoundBufferImpl** ippdsb=(IDirectSoundBufferImpl**)ppdsb;
1432         TRACE("(%p,%p,%p)\n",This,ipdsb,ippdsb);
1433
1434         *ippdsb = (IDirectSoundBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundBufferImpl));
1435
1436         IDirectSoundBuffer_AddRef(pdsb);
1437         memcpy(*ippdsb, ipdsb, sizeof(IDirectSoundBufferImpl));
1438         (*ippdsb)->ref = 1;
1439         (*ippdsb)->playpos = 0;
1440         (*ippdsb)->writepos = 0;
1441         (*ippdsb)->dsound = This;
1442         (*ippdsb)->parent = ipdsb;
1443         memcpy(&((*ippdsb)->wfx), &(ipdsb->wfx), sizeof((*ippdsb)->wfx));
1444         /* register buffer */
1445         EnterCriticalSection(&(This->lock));
1446         This->buffers = (IDirectSoundBufferImpl**)HeapReAlloc(GetProcessHeap(),0,This->buffers,sizeof(IDirectSoundBufferImpl**)*(This->nrofbuffers+1));
1447         This->buffers[This->nrofbuffers] = *ippdsb;
1448         This->nrofbuffers++;
1449         IDirectSound_AddRef(iface);
1450         LeaveCriticalSection(&(This->lock));
1451         return DS_OK;
1452 }
1453
1454
1455 static HRESULT WINAPI IDirectSoundImpl_GetCaps(LPDIRECTSOUND iface,LPDSCAPS caps) {
1456         ICOM_THIS(IDirectSoundImpl,iface);
1457         TRACE("(%p,%p)\n",This,caps);
1458         TRACE("(flags=0x%08lx)\n",caps->dwFlags);
1459
1460         if (caps == NULL)
1461                 return DSERR_INVALIDPARAM;
1462
1463         /* We should check this value, not set it. See Inside DirectX, p215. */
1464         caps->dwSize = sizeof(*caps);
1465
1466         caps->dwFlags =
1467                 DSCAPS_PRIMARYSTEREO |
1468                 DSCAPS_PRIMARY16BIT |
1469                 DSCAPS_SECONDARYSTEREO |
1470                 DSCAPS_SECONDARY16BIT |
1471                 DSCAPS_CONTINUOUSRATE;
1472         /* FIXME: query OSS */
1473         caps->dwMinSecondarySampleRate          = DSBFREQUENCY_MIN;
1474         caps->dwMaxSecondarySampleRate          = DSBFREQUENCY_MAX;
1475
1476         caps->dwPrimaryBuffers                  = 1;
1477
1478         caps->dwMaxHwMixingAllBuffers           = 0;
1479         caps->dwMaxHwMixingStaticBuffers        = 0;
1480         caps->dwMaxHwMixingStreamingBuffers     = 0;
1481
1482         caps->dwFreeHwMixingAllBuffers          = 0;
1483         caps->dwFreeHwMixingStaticBuffers       = 0;
1484         caps->dwFreeHwMixingStreamingBuffers    = 0;
1485
1486         caps->dwMaxHw3DAllBuffers               = 0;
1487         caps->dwMaxHw3DStaticBuffers            = 0;
1488         caps->dwMaxHw3DStreamingBuffers         = 0;
1489
1490         caps->dwFreeHw3DAllBuffers              = 0;
1491         caps->dwFreeHw3DStaticBuffers           = 0;
1492         caps->dwFreeHw3DStreamingBuffers        = 0;
1493
1494         caps->dwTotalHwMemBytes                 = 0;
1495
1496         caps->dwFreeHwMemBytes                  = 0;
1497
1498         caps->dwMaxContigFreeHwMemBytes         = 0;
1499
1500         caps->dwUnlockTransferRateHwBuffers     = 4096; /* But we have none... */
1501
1502         caps->dwPlayCpuOverheadSwBuffers        = 1;    /* 1% */
1503
1504         return DS_OK;
1505 }
1506
1507 static ULONG WINAPI IDirectSoundImpl_AddRef(LPDIRECTSOUND iface) {
1508         ICOM_THIS(IDirectSoundImpl,iface);
1509         return ++(This->ref);
1510 }
1511
1512 static ULONG WINAPI IDirectSoundImpl_Release(LPDIRECTSOUND iface) {
1513         ICOM_THIS(IDirectSoundImpl,iface);
1514         TRACE("(%p), ref was %ld\n",This,This->ref);
1515         if (!--(This->ref)) {
1516                 DSOUND_CloseAudio();
1517                 while(IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)primarybuf)); /* Deallocate */
1518                 FIXME("need to release all buffers!\n");
1519                 HeapFree(GetProcessHeap(),0,This);
1520                 dsound = NULL;
1521                 return S_OK;
1522         }
1523         return This->ref;
1524 }
1525
1526 static HRESULT WINAPI IDirectSoundImpl_SetSpeakerConfig(
1527         LPDIRECTSOUND iface,DWORD config
1528 ) {
1529         ICOM_THIS(IDirectSoundImpl,iface);
1530         FIXME("(%p,0x%08lx):stub\n",This,config);
1531         return DS_OK;
1532 }
1533
1534 static HRESULT WINAPI IDirectSoundImpl_QueryInterface(
1535         LPDIRECTSOUND iface,REFIID riid,LPVOID *ppobj
1536 ) {
1537         ICOM_THIS(IDirectSoundImpl,iface);
1538
1539         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1540
1541                 if (This->listener) {
1542                         *ppobj = This->listener;
1543                         return DS_OK;
1544                 }
1545                 This->listener = (IDirectSound3DListenerImpl*)HeapAlloc(
1546                         GetProcessHeap(), 0, sizeof(*(This->listener)));
1547                 This->listener->ref = 1;
1548                 ICOM_VTBL(This->listener) = &ds3dlvt;
1549                 IDirectSound_AddRef(iface);
1550                 This->listener->ds3dl.dwSize = sizeof(DS3DLISTENER);
1551                 This->listener->ds3dl.vPosition.x.x = 0.0;
1552                 This->listener->ds3dl.vPosition.y.y = 0.0;
1553                 This->listener->ds3dl.vPosition.z.z = 0.0;
1554                 This->listener->ds3dl.vVelocity.x.x = 0.0;
1555                 This->listener->ds3dl.vVelocity.y.y = 0.0;
1556                 This->listener->ds3dl.vVelocity.z.z = 0.0;
1557                 This->listener->ds3dl.vOrientFront.x.x = 0.0;
1558                 This->listener->ds3dl.vOrientFront.y.y = 0.0;
1559                 This->listener->ds3dl.vOrientFront.z.z = 1.0;
1560                 This->listener->ds3dl.vOrientTop.x.x = 0.0;
1561                 This->listener->ds3dl.vOrientTop.y.y = 1.0;
1562                 This->listener->ds3dl.vOrientTop.z.z = 0.0;
1563                 This->listener->ds3dl.flDistanceFactor = DS3D_DEFAULTDISTANCEFACTOR;
1564                 This->listener->ds3dl.flRolloffFactor = DS3D_DEFAULTROLLOFFFACTOR;
1565                 This->listener->ds3dl.flDopplerFactor = DS3D_DEFAULTDOPPLERFACTOR;
1566                 *ppobj = (LPVOID)This->listener;
1567                 return DS_OK;
1568         }
1569
1570         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
1571         return E_FAIL;
1572 }
1573
1574 static HRESULT WINAPI IDirectSoundImpl_Compact(
1575         LPDIRECTSOUND iface)
1576 {
1577         ICOM_THIS(IDirectSoundImpl,iface);
1578         TRACE("(%p)\n", This);
1579         return DS_OK;
1580 }
1581
1582 static HRESULT WINAPI IDirectSoundImpl_GetSpeakerConfig(
1583         LPDIRECTSOUND iface,
1584         LPDWORD lpdwSpeakerConfig)
1585 {
1586         ICOM_THIS(IDirectSoundImpl,iface);
1587         TRACE("(%p, %p)\n", This, lpdwSpeakerConfig);
1588         *lpdwSpeakerConfig = DSSPEAKER_STEREO | (DSSPEAKER_GEOMETRY_NARROW << 16);
1589         return DS_OK;
1590 }
1591
1592 static HRESULT WINAPI IDirectSoundImpl_Initialize(
1593         LPDIRECTSOUND iface,
1594         LPGUID lpGuid)
1595 {
1596         ICOM_THIS(IDirectSoundImpl,iface);
1597         TRACE("(%p, %p)\n", This, lpGuid);
1598         return DS_OK;
1599 }
1600
1601 static ICOM_VTABLE(IDirectSound) dsvt = 
1602 {
1603         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1604         IDirectSoundImpl_QueryInterface,
1605         IDirectSoundImpl_AddRef,
1606         IDirectSoundImpl_Release,
1607         IDirectSoundImpl_CreateSoundBuffer,
1608         IDirectSoundImpl_GetCaps,
1609         IDirectSoundImpl_DuplicateSoundBuffer,
1610         IDirectSoundImpl_SetCooperativeLevel,
1611         IDirectSoundImpl_Compact,
1612         IDirectSoundImpl_GetSpeakerConfig,
1613         IDirectSoundImpl_SetSpeakerConfig,
1614         IDirectSoundImpl_Initialize
1615 };
1616
1617
1618 /* See http://www.opensound.com/pguide/audio.html for more details */
1619
1620 static int
1621 DSOUND_setformat(LPWAVEFORMATEX wfex) {
1622         int     xx,channels,speed,format,nformat;
1623
1624         if (!audioOK) {
1625                 TRACE("(%p) deferred\n", wfex);
1626                 return 0;
1627         }
1628         switch (wfex->wFormatTag) {
1629         default:
1630                 WARN("unknown WAVE_FORMAT tag %d\n",wfex->wFormatTag);
1631                 return DSERR_BADFORMAT;
1632         case WAVE_FORMAT_PCM:
1633                 break;
1634         }
1635         if (wfex->wBitsPerSample==8)
1636                 format = AFMT_U8;
1637         else
1638                 format = AFMT_S16_LE;
1639
1640         if (-1==ioctl(audiofd,SNDCTL_DSP_GETFMTS,&xx)) {
1641                 perror("ioctl SNDCTL_DSP_GETFMTS");
1642                 return -1;
1643         }
1644         if ((xx&format)!=format) {/* format unsupported */
1645                 FIXME("SNDCTL_DSP_GETFMTS: format not supported\n"); 
1646                 return -1;
1647         }
1648         nformat = format;
1649         if (-1==ioctl(audiofd,SNDCTL_DSP_SETFMT,&nformat)) {
1650                 perror("ioctl SNDCTL_DSP_SETFMT");
1651                 return -1;
1652         }
1653         if (nformat!=format) {/* didn't work */
1654                 FIXME("SNDCTL_DSP_GETFMTS: format not set\n"); 
1655                 return -1;
1656         }
1657
1658         channels = wfex->nChannels-1;
1659         if (-1==ioctl(audiofd,SNDCTL_DSP_STEREO,&channels)) {
1660                 perror("ioctl SNDCTL_DSP_STEREO");
1661                 return -1;
1662         }
1663         speed = wfex->nSamplesPerSec;
1664         if (-1==ioctl(audiofd,SNDCTL_DSP_SPEED,&speed)) {
1665                 perror("ioctl SNDCTL_DSP_SPEED");
1666                 return -1;
1667         }
1668         TRACE("(freq=%ld,channels=%d,bits=%d)\n",
1669                 wfex->nSamplesPerSec,wfex->nChannels,wfex->wBitsPerSample
1670         );
1671         return 0;
1672 }
1673
1674 static void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
1675 {
1676         int                     i;
1677         DWORD                   offset;
1678         LPDSBPOSITIONNOTIFY     event;
1679
1680         if (dsb->nrofnotifies == 0)
1681                 return;
1682
1683         TRACE("(%p) buflen = %ld, playpos = %ld, len = %d\n",
1684                 dsb, dsb->buflen, dsb->playpos, len);
1685         for (i = 0; i < dsb->nrofnotifies ; i++) {
1686                 event = dsb->notifies + i;
1687                 offset = event->dwOffset;
1688                 TRACE("checking %d, position %ld, event = %d\n",
1689                         i, offset, event->hEventNotify);
1690                 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
1691                 /* OK. [Inside DirectX, p274] */
1692                 /*  */
1693                 /* This also means we can't sort the entries by offset, */
1694                 /* because DSBPN_OFFSETSTOP == -1 */
1695                 if (offset == DSBPN_OFFSETSTOP) {
1696                         if (dsb->playing == 0) {
1697                                 SetEvent(event->hEventNotify);
1698                                 TRACE("signalled event %d (%d)\n", event->hEventNotify, i);
1699                                 return;
1700                         } else
1701                                 return;
1702                 }
1703                 if ((dsb->playpos + len) >= dsb->buflen) {
1704                         if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
1705                             (offset >= dsb->playpos)) {
1706                                 TRACE("signalled event %d (%d)\n", event->hEventNotify, i);
1707                                 SetEvent(event->hEventNotify);
1708                         }
1709                 } else {
1710                         if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
1711                                 TRACE("signalled event %d (%d)\n", event->hEventNotify, i);
1712                                 SetEvent(event->hEventNotify);
1713                         }
1714                 }
1715         }
1716 }
1717
1718 /* WAV format info can be found at: */
1719 /* */
1720 /*      http://www.cwi.nl/ftp/audio/AudioFormats.part2 */
1721 /*      ftp://ftp.cwi.nl/pub/audio/RIFF-format */
1722 /* */
1723 /* Import points to remember: */
1724 /* */
1725 /*      8-bit WAV is unsigned */
1726 /*      16-bit WAV is signed */
1727
1728 static inline INT16 cvtU8toS16(BYTE byte)
1729 {
1730         INT16   s = (byte - 128) << 8;
1731
1732         return s;
1733 }
1734
1735 static inline BYTE cvtS16toU8(INT16 word)
1736 {
1737         BYTE    b = (word + 32768) >> 8;
1738         
1739         return b;
1740 }
1741
1742
1743 /* We should be able to optimize these two inline functions */
1744 /* so that we aren't doing 8->16->8 conversions when it is */
1745 /* not necessary. But this is still a WIP. Optimize later. */
1746 static inline void get_fields(const IDirectSoundBufferImpl *dsb, BYTE *buf, INT *fl, INT *fr)
1747 {
1748         INT16   *bufs = (INT16 *) buf;
1749
1750         /* TRACE(dsound, "(%p)", buf); */
1751         if ((dsb->wfx.wBitsPerSample == 8) && dsb->wfx.nChannels == 2) {
1752                 *fl = cvtU8toS16(*buf);
1753                 *fr = cvtU8toS16(*(buf + 1));
1754                 return;
1755         }
1756
1757         if ((dsb->wfx.wBitsPerSample == 16) && dsb->wfx.nChannels == 2) {
1758                 *fl = *bufs;
1759                 *fr = *(bufs + 1);
1760                 return;
1761         }
1762
1763         if ((dsb->wfx.wBitsPerSample == 8) && dsb->wfx.nChannels == 1) {
1764                 *fl = cvtU8toS16(*buf);
1765                 *fr = *fl;
1766                 return;
1767         }
1768
1769         if ((dsb->wfx.wBitsPerSample == 16) && dsb->wfx.nChannels == 1) {
1770                 *fl = *bufs;
1771                 *fr = *bufs;
1772                 return;
1773         }
1774
1775         FIXME("get_fields found an unsupported configuration\n");
1776         return;
1777 }
1778
1779 static inline void set_fields(BYTE *buf, INT fl, INT fr)
1780 {
1781         INT16 *bufs = (INT16 *) buf;
1782
1783         if ((primarybuf->wfx.wBitsPerSample == 8) && (primarybuf->wfx.nChannels == 2)) {
1784                 *buf = cvtS16toU8(fl);
1785                 *(buf + 1) = cvtS16toU8(fr);
1786                 return;
1787         }
1788
1789         if ((primarybuf->wfx.wBitsPerSample == 16) && (primarybuf->wfx.nChannels == 2)) {
1790                 *bufs = fl;
1791                 *(bufs + 1) = fr;
1792                 return;
1793         }
1794
1795         if ((primarybuf->wfx.wBitsPerSample == 8) && (primarybuf->wfx.nChannels == 1)) {
1796                 *buf = cvtS16toU8((fl + fr) >> 1);
1797                 return;
1798         }
1799
1800         if ((primarybuf->wfx.wBitsPerSample == 16) && (primarybuf->wfx.nChannels == 1)) {
1801                 *bufs = (fl + fr) >> 1;
1802                 return;
1803         }
1804         FIXME("set_fields found an unsupported configuration\n");
1805         return;
1806 }
1807
1808 /* Now with PerfectPitch (tm) technology */
1809 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
1810 {
1811         INT     i, size, ipos, ilen, fieldL, fieldR;
1812         BYTE    *ibp, *obp;
1813         INT     iAdvance = dsb->wfx.nBlockAlign;
1814         INT     oAdvance = primarybuf->wfx.nBlockAlign;
1815
1816         ibp = dsb->buffer + dsb->playpos;
1817         obp = buf;
1818
1819         TRACE("(%p, %p, %p), playpos=%8.8lx\n", dsb, ibp, obp, dsb->playpos);
1820         /* Check for the best case */
1821         if ((dsb->freq == primarybuf->wfx.nSamplesPerSec) &&
1822             (dsb->wfx.wBitsPerSample == primarybuf->wfx.wBitsPerSample) &&
1823             (dsb->wfx.nChannels == primarybuf->wfx.nChannels)) {
1824                 TRACE("(%p) Best case\n", dsb);
1825                 if ((ibp + len) < (BYTE *)(dsb->buffer + dsb->buflen))
1826                         memcpy(obp, ibp, len);
1827                 else { /* wrap */
1828                         memcpy(obp, ibp, dsb->buflen - dsb->playpos);
1829                         memcpy(obp + (dsb->buflen - dsb->playpos),
1830                             dsb->buffer,
1831                             len - (dsb->buflen - dsb->playpos));
1832                 }
1833                 return len;
1834         }
1835         
1836         /* Check for same sample rate */
1837         if (dsb->freq == primarybuf->wfx.nSamplesPerSec) {
1838                 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
1839                         dsb->freq, primarybuf->wfx.nSamplesPerSec);
1840                 ilen = 0;
1841                 for (i = 0; i < len; i += oAdvance) {
1842                         get_fields(dsb, ibp, &fieldL, &fieldR);
1843                         ibp += iAdvance;
1844                         ilen += iAdvance;
1845                         set_fields(obp, fieldL, fieldR);
1846                         obp += oAdvance;
1847                         if (ibp >= (BYTE *)(dsb->buffer + dsb->buflen))
1848                                 ibp = dsb->buffer;      /* wrap */
1849                 }
1850                 return (ilen);  
1851         }
1852
1853         /* Mix in different sample rates */
1854         /* */
1855         /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
1856         /* Patent Pending :-] */
1857
1858         TRACE("(%p) Adjusting frequency: %ld -> %ld\n",
1859                 dsb, dsb->freq, primarybuf->wfx.nSamplesPerSec);
1860
1861         size = len / oAdvance;
1862         ilen = ((size * dsb->freqAdjust) >> DSOUND_FREQSHIFT) * iAdvance;
1863         for (i = 0; i < size; i++) {
1864
1865                 ipos = (((i * dsb->freqAdjust) >> DSOUND_FREQSHIFT) * iAdvance) + dsb->playpos;
1866
1867                 if (ipos >= dsb->buflen)
1868                         ipos %= dsb->buflen;    /* wrap */
1869
1870                 get_fields(dsb, (dsb->buffer + ipos), &fieldL, &fieldR);
1871                 set_fields(obp, fieldL, fieldR);
1872                 obp += oAdvance;
1873         }
1874         return ilen;
1875 }
1876
1877 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
1878 {
1879         INT     i, inc = primarybuf->wfx.wBitsPerSample >> 3;
1880         BYTE    *bpc = buf;
1881         INT16   *bps = (INT16 *) buf;
1882         
1883         TRACE("(%p) left = %lx, right = %lx\n", dsb,
1884                 dsb->lVolAdjust, dsb->rVolAdjust);
1885         if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->pan == 0)) &&
1886             (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volume == 0)) &&
1887             !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
1888                 return;         /* Nothing to do */
1889
1890         /* If we end up with some bozo coder using panning or 3D sound */
1891         /* with a mono primary buffer, it could sound very weird using */
1892         /* this method. Oh well, tough patooties. */
1893
1894         for (i = 0; i < len; i += inc) {
1895                 INT     val;
1896
1897                 switch (inc) {
1898
1899                 case 1:
1900                         /* 8-bit WAV is unsigned, but we need to operate */
1901                         /* on signed data for this to work properly */
1902                         val = *bpc - 128;
1903                         val = ((val * (i & inc ? dsb->rVolAdjust : dsb->lVolAdjust)) >> 15);
1904                         *bpc = val + 128;
1905                         bpc++;
1906                         break;
1907                 case 2:
1908                         /* 16-bit WAV is signed -- much better */
1909                         val = *bps;
1910                         val = ((val * ((i & inc) ? dsb->rVolAdjust : dsb->lVolAdjust)) >> 15);
1911                         *bps = val;
1912                         bps++;
1913                         break;
1914                 default:
1915                         /* Very ugly! */
1916                         FIXME("MixerVol had a nasty error\n");
1917                 }
1918         }               
1919 }
1920
1921 #ifdef USE_DSOUND3D
1922 static void DSOUND_Mixer3D(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
1923 {
1924         BYTE    *ibp, *obp;
1925         DWORD   buflen, playpos;
1926
1927         buflen = dsb->ds3db->buflen;
1928         playpos = (dsb->playpos * primarybuf->wfx.nBlockAlign) / dsb->wfx.nBlockAlign;
1929         ibp = dsb->ds3db->buffer + playpos;
1930         obp = buf;
1931
1932         if (playpos > buflen) {
1933                 FIXME("Major breakage");
1934                 return;
1935         }
1936
1937         if (len <= (playpos + buflen))
1938                 memcpy(obp, ibp, len);
1939         else { /* wrap */
1940                 memcpy(obp, ibp, buflen - playpos);
1941                 memcpy(obp + (buflen - playpos),
1942                     dsb->buffer,
1943                     len - (buflen - playpos));
1944         }
1945         return;
1946 }
1947 #endif
1948
1949 static void *tmp_buffer;
1950 static size_t tmp_buffer_len = 0;
1951
1952 static void *DSOUND_tmpbuffer(size_t len)
1953 {
1954   if (len>tmp_buffer_len) {
1955     void *new_buffer = realloc(tmp_buffer, len);
1956     if (new_buffer) {
1957       tmp_buffer = new_buffer;
1958       tmp_buffer_len = len;
1959     }
1960     return new_buffer;
1961   }
1962   return tmp_buffer;
1963 }
1964
1965 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb)
1966 {
1967         INT     i, len, ilen, temp, field;
1968         INT     advance = primarybuf->wfx.wBitsPerSample >> 3;
1969         BYTE    *buf, *ibuf, *obuf;
1970         INT16   *ibufs, *obufs;
1971
1972         len = DSOUND_FRAGLEN;                   /* The most we will use */
1973         if (!(dsb->playflags & DSBPLAY_LOOPING)) {
1974                 temp = MulDiv(primarybuf->wfx.nAvgBytesPerSec, dsb->buflen,
1975                         dsb->nAvgBytesPerSec) -
1976                        MulDiv(primarybuf->wfx.nAvgBytesPerSec, dsb->playpos,
1977                         dsb->nAvgBytesPerSec);
1978                 len = (len > temp) ? temp : len;
1979         }
1980         len &= ~3;                              /* 4 byte alignment */
1981
1982         if (len == 0) {
1983                 /* This should only happen if we aren't looping and temp < 4 */
1984
1985                 /* We skip the remainder, so check for possible events */
1986                 DSOUND_CheckEvent(dsb, dsb->buflen - dsb->playpos);
1987                 /* Stop */
1988                 dsb->playing = 0;
1989                 dsb->writepos = 0;
1990                 dsb->playpos = 0;
1991                 /* Check for DSBPN_OFFSETSTOP */
1992                 DSOUND_CheckEvent(dsb, 0);
1993                 return 0;
1994         }
1995
1996         /* Been seeing segfaults in malloc() for some reason... */
1997         TRACE("allocating buffer (size = %d)\n", len);
1998         if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
1999                 return 0;
2000
2001         TRACE("MixInBuffer (%p) len = %d\n", dsb, len);
2002
2003         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
2004         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
2005             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
2006                 DSOUND_MixerVol(dsb, ibuf, len);
2007
2008         obuf = primarybuf->buffer + primarybuf->playpos;
2009         for (i = 0; i < len; i += advance) {
2010                 obufs = (INT16 *) obuf;
2011                 ibufs = (INT16 *) ibuf;
2012                 if (primarybuf->wfx.wBitsPerSample == 8) {
2013                         /* 8-bit WAV is unsigned */
2014                         field = (*ibuf - 128);
2015                         field += (*obuf - 128);
2016                         field = field > 127 ? 127 : field;
2017                         field = field < -128 ? -128 : field;
2018                         *obuf = field + 128;
2019                 } else {
2020                         /* 16-bit WAV is signed */
2021                         field = *ibufs;
2022                         field += *obufs;
2023                         field = field > 32767 ? 32767 : field;
2024                         field = field < -32768 ? -32768 : field;
2025                         *obufs = field;
2026                 }
2027                 ibuf += advance;
2028                 obuf += advance;
2029                 if (obuf >= (BYTE *)(primarybuf->buffer + primarybuf->buflen))
2030                         obuf = primarybuf->buffer;
2031         }
2032         /* free(buf); */
2033
2034         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY)
2035                 DSOUND_CheckEvent(dsb, ilen);
2036
2037         dsb->playpos += ilen;
2038         dsb->writepos = dsb->playpos + ilen;
2039         
2040         if (dsb->playpos >= dsb->buflen) {
2041                 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
2042                         dsb->playing = 0;
2043                         dsb->writepos = 0;
2044                         dsb->playpos = 0;
2045                         DSOUND_CheckEvent(dsb, 0);              /* For DSBPN_OFFSETSTOP */
2046                 } else
2047                         dsb->playpos %= dsb->buflen;            /* wrap */
2048         }
2049         
2050         if (dsb->writepos >= dsb->buflen)
2051                 dsb->writepos %= dsb->buflen;
2052
2053         return len;
2054 }
2055
2056 static DWORD WINAPI DSOUND_MixPrimary(void)
2057 {
2058         INT                     i, len, maxlen = 0;
2059         IDirectSoundBufferImpl  *dsb;
2060
2061         for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
2062                 dsb = dsound->buffers[i];
2063
2064                 if (!dsb || !(ICOM_VTBL(dsb)))
2065                         continue;
2066                 IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)dsb);
2067                 if (dsb->buflen && dsb->playing) {
2068                         EnterCriticalSection(&(dsb->lock));
2069                         len = DSOUND_MixInBuffer(dsb);
2070                         maxlen = len > maxlen ? len : maxlen;
2071                         LeaveCriticalSection(&(dsb->lock));
2072                 }
2073                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)dsb);
2074         }
2075         
2076         return maxlen;
2077 }
2078
2079 static int DSOUND_OpenAudio(void)
2080 {
2081         int     audioFragment;
2082
2083         if (primarybuf == NULL)
2084                 return DSERR_OUTOFMEMORY;
2085
2086         while (audiofd >= 0)
2087
2088                 sleep(5);
2089         /* we will most likely not get one, avoid excessive opens ... */
2090         if (audiofd == -ENODEV)
2091                 return -1;
2092         audiofd = open("/dev/audio",O_WRONLY);
2093         if (audiofd==-1) {
2094                 /* Don't worry if sound is busy at the moment */
2095                 if ((errno != EBUSY) && (errno != ENODEV))
2096                         perror("open /dev/audio");
2097                 audiofd = -errno;
2098                 return -1; /* -1 */
2099         }
2100
2101         /* We should probably do something here if SETFRAGMENT fails... */
2102         audioFragment=0x0002000c;
2103         if (-1==ioctl(audiofd,SNDCTL_DSP_SETFRAGMENT,&audioFragment))
2104                 perror("ioctl SETFRAGMENT");
2105
2106         audioOK = 1;
2107         DSOUND_setformat(&(primarybuf->wfx));
2108
2109         return 0;
2110 }
2111
2112 static void DSOUND_CloseAudio(void)
2113 {
2114         int     neutral;
2115         
2116         neutral = primarybuf->wfx.wBitsPerSample == 8 ? 128 : 0;
2117         audioOK = 0;    /* race condition */
2118         Sleep(5);
2119         /* It's possible we've been called with audio closed */
2120         /* from SetFormat()... this is just to force a call */
2121         /* to OpenAudio() to reset the hardware properly */
2122         if (audiofd >= 0)
2123                 close(audiofd);
2124         primarybuf->playpos = 0;
2125         primarybuf->writepos = DSOUND_FRAGLEN;
2126         memset(primarybuf->buffer, neutral, primarybuf->buflen);
2127         audiofd = -1;
2128         TRACE("Audio stopped\n");
2129 }
2130         
2131 static int DSOUND_WriteAudio(char *buf, int len)
2132 {
2133         int     result, left = 0;
2134
2135         while (left < len) {
2136                 result = write(audiofd, buf + left, len - left);
2137                 if (result == -1) {
2138                         if (errno == EINTR)
2139                                 continue;
2140                         else
2141                                 return result;
2142                 }
2143                 left += result;
2144         }
2145         return 0;
2146 }
2147
2148 static void DSOUND_OutputPrimary(int len)
2149 {
2150         int     neutral, flen1, flen2;
2151         char    *frag1, *frag2;
2152         
2153         /* This is a bad place for this. We need to clear the */
2154         /* buffer with a neutral value, for unsigned 8-bit WAVE */
2155         /* that's 128, for signed 16-bit it's 0 */
2156         neutral = primarybuf->wfx.wBitsPerSample == 8 ? 128 : 0;
2157         
2158         /* **** */
2159         EnterCriticalSection(&(primarybuf->lock));
2160
2161         /* Write out the  */
2162         if ((audioOK == 1) || (DSOUND_OpenAudio() == 0)) {
2163                 if (primarybuf->playpos + len >= primarybuf->buflen) {
2164                         frag1 = primarybuf->buffer + primarybuf->playpos;
2165                         flen1 = primarybuf->buflen - primarybuf->playpos;
2166                         frag2 = primarybuf->buffer;
2167                         flen2 = len - (primarybuf->buflen - primarybuf->playpos);
2168                         if (DSOUND_WriteAudio(frag1, flen1) != 0) {
2169                                 perror("DSOUND_WriteAudio");
2170                                 LeaveCriticalSection(&(primarybuf->lock));
2171                                 ExitThread(0);
2172                         }
2173                         memset(frag1, neutral, flen1);
2174                         if (DSOUND_WriteAudio(frag2, flen2) != 0) {
2175                                 perror("DSOUND_WriteAudio");
2176                                 LeaveCriticalSection(&(primarybuf->lock));
2177                                 ExitThread(0);
2178                         }
2179                         memset(frag2, neutral, flen2);
2180                 } else {
2181                         frag1 = primarybuf->buffer + primarybuf->playpos;
2182                         flen1 = len;
2183                         if (DSOUND_WriteAudio(frag1, flen1) != 0) {
2184                                 perror("DSOUND_WriteAudio");
2185                                 LeaveCriticalSection(&(primarybuf->lock));
2186                                 ExitThread(0);
2187                         }
2188                         memset(frag1, neutral, flen1);
2189                 }
2190         } else {
2191                 /* Can't play audio at the moment -- we need to sleep */
2192                 /* to make up for the time we'd be blocked in write() */
2193                 /* to /dev/audio */
2194                 Sleep(60);
2195         }
2196         primarybuf->playpos += len;
2197         if (primarybuf->playpos >= primarybuf->buflen)
2198                 primarybuf->playpos %= primarybuf->buflen;
2199         primarybuf->writepos = primarybuf->playpos + DSOUND_FRAGLEN;
2200         if (primarybuf->writepos >= primarybuf->buflen)
2201                 primarybuf->writepos %= primarybuf->buflen;
2202
2203         LeaveCriticalSection(&(primarybuf->lock));
2204         /* **** */
2205 }
2206
2207 static DWORD WINAPI DSOUND_thread(LPVOID arg)
2208 {
2209         int     len;
2210
2211         TRACE("dsound is at pid %d\n",getpid());
2212         while (1) {
2213                 if (!dsound) {
2214                         WARN("DSOUND thread giving up.\n");
2215                         ExitThread(0);
2216                 }
2217 #if 0
2218                 /* EP: since the thread creating this thread can
2219                  * die before the end of the DSOUND one, this
2220                  * test is of no use
2221                  * What shall be tested is whether the DSOUND thread 
2222                  * is the last one in the process
2223                  */
2224                 if (getppid()==1) {
2225                         WARN("DSOUND father died? Giving up.\n");
2226                         ExitThread(0);
2227                 }
2228 #endif
2229                 /* RACE: dsound could be deleted */
2230                 EnterCriticalSection(&(dsound->lock));
2231                 if (primarybuf == NULL) {
2232                         /* Should never happen */
2233                         WARN("Lost the primary buffer!\n");
2234                         IDirectSound_Release((LPDIRECTSOUND)dsound);
2235                         ExitThread(0);
2236                 }
2237
2238                 EnterCriticalSection(&(primarybuf->lock));
2239
2240                 len = DSOUND_MixPrimary();
2241
2242                 LeaveCriticalSection(&(primarybuf->lock));
2243                 LeaveCriticalSection(&(dsound->lock));
2244
2245                 if (primarybuf->playing)
2246                         len = DSOUND_FRAGLEN > len ? DSOUND_FRAGLEN : len;
2247                 if (len) {
2248                         /* This does all the work */
2249                         DSOUND_OutputPrimary(len);
2250                 } else {
2251                         /* no buffers playing -- close and wait */
2252                         if (audioOK)
2253                                 DSOUND_CloseAudio();
2254                         Sleep(100);
2255                 }
2256         }
2257         ExitThread(0);
2258 }
2259
2260 #endif /* HAVE_OSS */
2261
2262 HRESULT WINAPI DirectSoundCreate(REFGUID lpGUID,LPDIRECTSOUND *ppDS,IUnknown *pUnkOuter )
2263 {
2264         IDirectSoundImpl** ippDS=(IDirectSoundImpl**)ppDS;
2265         if (lpGUID)
2266                 TRACE("(%p,%p,%p)\n",lpGUID,ippDS,pUnkOuter);
2267         else
2268                 TRACE("DirectSoundCreate (%p)\n", ippDS);
2269
2270 #ifdef HAVE_OSS
2271
2272         if (ippDS == NULL)
2273                 return DSERR_INVALIDPARAM;
2274
2275         if (primarybuf) {
2276                 IDirectSound_AddRef((LPDIRECTSOUND)dsound);
2277                 *ippDS = dsound;
2278                 return DS_OK;
2279         }
2280
2281         /* Check that we actually have audio capabilities */
2282         /* If we do, whether it's busy or not, we continue */
2283         /* otherwise we return with DSERR_NODRIVER */
2284
2285         audiofd = open("/dev/audio",O_WRONLY);
2286         if (audiofd == -1) {
2287                 audiofd = -errno;
2288                 if (errno == ENODEV) {
2289                         MESSAGE("No sound hardware found, but continuing anyway.\n");
2290                 } else if (errno == EBUSY) {
2291                         MESSAGE("Sound device busy, will keep trying.\n");
2292                 } else {
2293                         MESSAGE("Unexpected error (%d) while checking for sound support.\n",errno);
2294                         return DSERR_GENERIC;
2295                 }
2296         } else {
2297                 close(audiofd);
2298                 audiofd = -1;
2299         }
2300
2301         *ippDS = (IDirectSoundImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDirectSoundImpl));
2302         if (*ippDS == NULL)
2303                 return DSERR_OUTOFMEMORY;
2304
2305         (*ippDS)->ref           = 1;
2306         ICOM_VTBL(*ippDS)       = &dsvt;
2307         (*ippDS)->buffers       = NULL;
2308         (*ippDS)->nrofbuffers   = 0;
2309
2310         (*ippDS)->wfx.wFormatTag                = 1;
2311         (*ippDS)->wfx.nChannels         = 2;
2312         (*ippDS)->wfx.nSamplesPerSec    = 22050;
2313         (*ippDS)->wfx.nAvgBytesPerSec   = 44100;
2314         (*ippDS)->wfx.nBlockAlign       = 2;
2315         (*ippDS)->wfx.wBitsPerSample    = 8;
2316
2317         InitializeCriticalSection(&((*ippDS)->lock));
2318
2319         if (!dsound) {
2320                 HANDLE  hnd;
2321                 DWORD           xid;
2322
2323                 dsound = (*ippDS);
2324                 if (primarybuf == NULL) {
2325                         DSBUFFERDESC    dsbd;
2326                         HRESULT         hr;
2327
2328                         dsbd.dwSize = sizeof(DSBUFFERDESC);
2329                         dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
2330                         dsbd.dwBufferBytes = 0;
2331                         dsbd.lpwfxFormat = &(dsound->wfx);
2332                         hr = IDirectSound_CreateSoundBuffer(*ppDS, &dsbd, (LPDIRECTSOUNDBUFFER*)&primarybuf, NULL);
2333                         if (hr != DS_OK)
2334                                 return hr;
2335                         dsound->primary = primarybuf;
2336                 }
2337                 memset(primarybuf->buffer, 128, primarybuf->buflen);
2338                 hnd = CreateThread(NULL,0,DSOUND_thread,0,0,&xid);
2339         }
2340         return DS_OK;
2341 #else
2342         MessageBoxA(0,"DirectSound needs the Open Sound System Driver, which has not been found by ./configure.","WINE DirectSound",MB_OK|MB_ICONSTOP);
2343         return DSERR_NODRIVER;
2344 #endif
2345 }
2346
2347 /*******************************************************************************
2348  * DirectSound ClassFactory
2349  */
2350 typedef struct
2351 {
2352     /* IUnknown fields */
2353     ICOM_VFIELD(IClassFactory);
2354     DWORD                       ref;
2355 } IClassFactoryImpl;
2356
2357 static HRESULT WINAPI 
2358 DSCF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
2359         ICOM_THIS(IClassFactoryImpl,iface);
2360
2361         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
2362         return E_NOINTERFACE;
2363 }
2364
2365 static ULONG WINAPI
2366 DSCF_AddRef(LPCLASSFACTORY iface) {
2367         ICOM_THIS(IClassFactoryImpl,iface);
2368         return ++(This->ref);
2369 }
2370
2371 static ULONG WINAPI DSCF_Release(LPCLASSFACTORY iface) {
2372         ICOM_THIS(IClassFactoryImpl,iface);
2373         /* static class, won't be  freed */
2374         return --(This->ref);
2375 }
2376
2377 static HRESULT WINAPI DSCF_CreateInstance(
2378         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
2379 ) {
2380         ICOM_THIS(IClassFactoryImpl,iface);
2381
2382         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
2383         if ( IsEqualGUID( &IID_IDirectSound, riid ) ) {
2384                 /* FIXME: reuse already created dsound if present? */
2385                 return DirectSoundCreate(riid,(LPDIRECTSOUND*)ppobj,pOuter);
2386         }
2387         return E_NOINTERFACE;
2388 }
2389
2390 static HRESULT WINAPI DSCF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
2391         ICOM_THIS(IClassFactoryImpl,iface);
2392         FIXME("(%p)->(%d),stub!\n",This,dolock);
2393         return S_OK;
2394 }
2395
2396 static ICOM_VTABLE(IClassFactory) DSCF_Vtbl = {
2397         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2398         DSCF_QueryInterface,
2399         DSCF_AddRef,
2400         DSCF_Release,
2401         DSCF_CreateInstance,
2402         DSCF_LockServer
2403 };
2404 static IClassFactoryImpl DSOUND_CF = {&DSCF_Vtbl, 1 };
2405
2406 /*******************************************************************************
2407  * DllGetClassObject [DSOUND.4]
2408  * Retrieves class object from a DLL object
2409  *
2410  * NOTES
2411  *    Docs say returns STDAPI
2412  *
2413  * PARAMS
2414  *    rclsid [I] CLSID for the class object
2415  *    riid   [I] Reference to identifier of interface for class object
2416  *    ppv    [O] Address of variable to receive interface pointer for riid
2417  *
2418  * RETURNS
2419  *    Success: S_OK
2420  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
2421  *             E_UNEXPECTED
2422  */
2423 DWORD WINAPI DSOUND_DllGetClassObject(REFCLSID rclsid,REFIID riid,LPVOID *ppv)
2424 {
2425     TRACE("(%p,%p,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
2426     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
2427         *ppv = (LPVOID)&DSOUND_CF;
2428         IClassFactory_AddRef((IClassFactory*)*ppv);
2429     return S_OK;
2430     }
2431
2432     FIXME("(%p,%p,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
2433     return CLASS_E_CLASSNOTAVAILABLE;
2434 }
2435
2436
2437 /*******************************************************************************
2438  * DllCanUnloadNow [DSOUND.3]  Determines whether the DLL is in use.
2439  *
2440  * RETURNS
2441  *    Success: S_OK
2442  *    Failure: S_FALSE
2443  */
2444 DWORD WINAPI DSOUND_DllCanUnloadNow(void)
2445 {
2446     FIXME("(void): stub\n");
2447     return S_FALSE;
2448 }