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