Fix to old DCB format parsing.
[wine] / dlls / dsound / dsound_main.c
1 /*                      DirectSound
2  * 
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2001 TransGaming Technologies, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21 /*
22  * Most thread locking is complete. There may be a few race
23  * conditions still lurking.
24  *
25  * Tested with a Soundblaster clone, a Gravis UltraSound Classic,
26  * and a Turtle Beach Tropez+.
27  *
28  * TODO:
29  *      Implement DirectSoundCapture API
30  *      Implement SetCooperativeLevel properly (need to address focus issues)
31  *      Implement DirectSound3DBuffers (stubs in place)
32  *      Use hardware 3D support if available
33  *      Add critical section locking inside Release and AddRef methods
34  *      Handle static buffers - put those in hardware, non-static not in hardware
35  *      Hardware DuplicateSoundBuffer
36  *      Proper volume calculation, and setting volume in HEL primary buffer
37  *      Optimize WINMM and negotiate fragment size, decrease DS_HEL_MARGIN
38  */
39
40 #include "config.h"
41 #include <assert.h>
42 #include <stdio.h>
43 #include <sys/types.h>
44 #include <sys/fcntl.h>
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <math.h>       /* Insomnia - pow() function */
49
50 #include "windef.h"
51 #include "winbase.h"
52 #include "wingdi.h"
53 #include "winuser.h"
54 #include "winerror.h"
55 #include "mmsystem.h"
56 #include "mmddk.h"
57 #include "wine/windef16.h"
58 #include "wine/debug.h"
59 #include "dsound.h"
60 #include "dsdriver.h"
61
62 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
63
64 /* these are eligible for tuning... they must be high on slow machines... */
65 /* some stuff may get more responsive with lower values though... */
66 #define DS_EMULDRIVER 1 /* some games (Quake 2, UT) refuse to accept
67                                 emulated dsound devices. set to 0 ! */ 
68 #define DS_HEL_FRAGS 48 /* HEL only: number of waveOut fragments in primary buffer
69                          * (changing this won't help you) */
70 #define DS_HEL_MARGIN 5 /* HEL only: number of waveOut fragments ahead to mix in new buffers
71                          * (keep this close or equal to DS_HEL_QUEUE for best results) */
72 #define DS_HEL_QUEUE  5 /* HEL only: number of waveOut fragments ahead to queue to driver
73                          * (this will affect HEL sound reliability and latency) */
74
75 #define DS_SND_QUEUE_MAX 28 /* max number of fragments to prebuffer */
76 #define DS_SND_QUEUE_MIN 12 /* min number of fragments to prebuffer */
77
78 /* Linux does not support better timing than 10ms */
79 #define DS_TIME_RES 10  /* Resolution of multimedia timer */
80 #define DS_TIME_DEL 10  /* Delay of multimedia timer callback, and duration of HEL fragment */
81
82 /*****************************************************************************
83  * Predeclare the interface implementation structures
84  */
85 typedef struct IDirectSoundImpl IDirectSoundImpl;
86 typedef struct IDirectSoundBufferImpl IDirectSoundBufferImpl;
87 typedef struct IDirectSoundNotifyImpl IDirectSoundNotifyImpl;
88 typedef struct IDirectSound3DListenerImpl IDirectSound3DListenerImpl;
89 typedef struct IDirectSound3DBufferImpl IDirectSound3DBufferImpl;
90 typedef struct IDirectSoundCaptureImpl IDirectSoundCaptureImpl;
91 typedef struct IDirectSoundCaptureBufferImpl IDirectSoundCaptureBufferImpl;
92 typedef struct IKsPropertySetImpl IKsPropertySetImpl;
93
94 /*****************************************************************************
95  * IDirectSound implementation structure
96  */
97 struct IDirectSoundImpl
98 {
99     /* IUnknown fields */
100     ICOM_VFIELD(IDirectSound);
101     DWORD                      ref;
102     /* IDirectSoundImpl fields */
103     PIDSDRIVER                  driver;
104     DSDRIVERDESC                drvdesc;
105     DSDRIVERCAPS                drvcaps;
106     HWAVEOUT                    hwo;
107     LPWAVEHDR                   pwave[DS_HEL_FRAGS];
108     UINT                        timerID, pwplay, pwwrite, pwqueue, prebuf;
109     DWORD                       fraglen;
110     DWORD                       priolevel;
111     int                         nrofbuffers;
112     IDirectSoundBufferImpl**    buffers;
113     IDirectSoundBufferImpl*     primary;
114     IDirectSound3DListenerImpl* listener;
115     WAVEFORMATEX                wfx; /* current main waveformat */
116     CRITICAL_SECTION            lock;
117 };
118
119 /*****************************************************************************
120  * IDirectSoundBuffer implementation structure
121  */
122 struct IDirectSoundBufferImpl
123 {
124     /* FIXME: document */
125     /* IUnknown fields */
126     ICOM_VFIELD(IDirectSoundBuffer);
127     DWORD                            ref;
128     /* IDirectSoundBufferImpl fields */
129     PIDSDRIVERBUFFER          hwbuf;
130     WAVEFORMATEX              wfx;
131     LPBYTE                    buffer;
132     IDirectSound3DBufferImpl* ds3db;
133     DWORD                     playflags,state,leadin;
134     DWORD                     playpos,startpos,writelead,buflen;
135     DWORD                     nAvgBytesPerSec;
136     DWORD                     freq;
137     DSVOLUMEPAN               volpan;
138     IDirectSoundBufferImpl*   parent;         /* for duplicates */
139     IDirectSoundImpl*         dsound;
140     DSBUFFERDESC              dsbd;
141     LPDSBPOSITIONNOTIFY       notifies;
142     int                       nrofnotifies;
143     CRITICAL_SECTION          lock;
144     /* used for frequency conversion (PerfectPitch) */
145     ULONG                     freqAdjust, freqAcc;
146     /* used for intelligent (well, sort of) prebuffering */
147     DWORD                     probably_valid_to;
148     DWORD                     primary_mixpos, buf_mixpos;
149     BOOL                      need_remix;
150 };
151
152 #define STATE_STOPPED  0
153 #define STATE_STARTING 1
154 #define STATE_PLAYING  2
155 #define STATE_STOPPING 3
156
157 /*****************************************************************************
158  * IDirectSoundNotify implementation structure
159  */
160 struct IDirectSoundNotifyImpl
161 {
162     /* IUnknown fields */
163     ICOM_VFIELD(IDirectSoundNotify);
164     DWORD                            ref;
165     /* IDirectSoundNotifyImpl fields */
166     IDirectSoundBufferImpl* dsb;
167 };
168
169 /*****************************************************************************
170  *  IDirectSound3DListener implementation structure
171  */
172 struct IDirectSound3DListenerImpl
173 {
174     /* IUnknown fields */
175     ICOM_VFIELD(IDirectSound3DListener);
176     DWORD                                ref;
177     /* IDirectSound3DListenerImpl fields */
178     IDirectSoundBufferImpl* dsb;
179     DS3DLISTENER            ds3dl;
180     CRITICAL_SECTION        lock;   
181 };
182
183 struct IKsPropertySetImpl 
184 {
185     /* IUnknown fields */
186     ICOM_VFIELD(IKsPropertySet);
187     DWORD                       ref;
188     /* IKsPropertySetImpl fields */
189     IDirectSound3DBufferImpl    *ds3db; /* backptr, no ref */
190 };
191
192 /*****************************************************************************
193  * IDirectSound3DBuffer implementation structure
194  */
195 struct IDirectSound3DBufferImpl
196 {
197     /* IUnknown fields */
198     ICOM_VFIELD(IDirectSound3DBuffer);
199     DWORD                              ref;
200     /* IDirectSound3DBufferImpl fields */
201     IDirectSoundBufferImpl* dsb;
202     DS3DBUFFER              ds3db;
203     LPBYTE                  buffer;
204     DWORD                   buflen;
205     CRITICAL_SECTION        lock;
206     IKsPropertySetImpl*     iks;
207 };
208
209
210 /*****************************************************************************
211  * IDirectSoundCapture implementation structure
212  */
213 struct IDirectSoundCaptureImpl
214 {
215     /* IUnknown fields */
216     ICOM_VFIELD(IDirectSoundCapture);
217     DWORD                              ref;
218
219     /* IDirectSoundCaptureImpl fields */
220     CRITICAL_SECTION        lock;
221 };
222
223 /*****************************************************************************
224  * IDirectSoundCapture implementation structure
225  */
226 struct IDirectSoundCaptureBufferImpl
227 {
228     /* IUnknown fields */
229     ICOM_VFIELD(IDirectSoundCaptureBuffer);
230     DWORD                              ref;
231
232     /* IDirectSoundCaptureBufferImpl fields */
233     CRITICAL_SECTION        lock;
234 };
235
236
237 /* #define USE_DSOUND3D 1 */
238
239 #define DSOUND_FREQSHIFT (14)
240
241 static IDirectSoundImpl*        dsound = NULL;
242
243 static IDirectSoundBufferImpl*  primarybuf = NULL;
244
245 static void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len);
246 static void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos);
247
248 static void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq);
249 static void DSOUND_PerformMix(void);
250 static void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2);
251
252 static HRESULT DSOUND_CreateDirectSoundCapture( LPVOID* ppobj );
253 static HRESULT DSOUND_CreateDirectSoundCaptureBuffer( LPCDSCBUFFERDESC lpcDSCBufferDesc, LPVOID* ppobj );
254
255 static ICOM_VTABLE(IDirectSoundCapture) dscvt;
256 static ICOM_VTABLE(IDirectSoundCaptureBuffer) dscbvt;
257
258 static HRESULT mmErr(UINT err)
259 {
260         switch(err) {
261         case MMSYSERR_NOERROR:
262                 return DS_OK;
263         case MMSYSERR_ALLOCATED:
264                 return DSERR_ALLOCATED;
265         case MMSYSERR_INVALHANDLE:
266                 return DSERR_GENERIC; /* FIXME */
267         case MMSYSERR_NODRIVER:
268                 return DSERR_NODRIVER;
269         case MMSYSERR_NOMEM:
270                 return DSERR_OUTOFMEMORY;
271         case MMSYSERR_INVALPARAM:
272                 return DSERR_INVALIDPARAM;
273         default:
274                 FIXME("Unknown MMSYS error %d\n",err);
275                 return DSERR_GENERIC;
276         }
277 }
278
279 /***************************************************************************
280  * DirectSoundEnumerateA [DSOUND.2]  
281  *
282  * Enumerate all DirectSound drivers installed in the system
283  *
284  * RETURNS
285  *    Success: DS_OK
286  *    Failure: DSERR_INVALIDPARAM
287  */
288 HRESULT WINAPI DirectSoundEnumerateA(
289         LPDSENUMCALLBACKA lpDSEnumCallback,
290         LPVOID lpContext)
291 {
292         TRACE("lpDSEnumCallback = %p, lpContext = %p\n", 
293                 lpDSEnumCallback, lpContext);
294
295 #ifdef HAVE_OSS
296         if (lpDSEnumCallback != NULL)
297                 lpDSEnumCallback(NULL,"WINE DirectSound",
298                     "sound",lpContext);
299 #endif
300
301         return DS_OK;
302 }
303
304 /***************************************************************************
305  * DirectSoundEnumerateW [DSOUND.3]  
306  *
307  * Enumerate all DirectSound drivers installed in the system
308  *
309  * RETURNS
310  *    Success: DS_OK
311  *    Failure: DSERR_INVALIDPARAM
312  */
313 HRESULT WINAPI DirectSoundEnumerateW(
314         LPDSENUMCALLBACKW lpDSEnumCallback, 
315         LPVOID lpContext )
316 {
317         FIXME("lpDSEnumCallback = %p, lpContext = %p: stub\n", 
318                 lpDSEnumCallback, lpContext);
319
320         return DS_OK;
321 }
322
323
324 static void _dump_DSBCAPS(DWORD xmask) {
325         struct {
326                 DWORD   mask;
327                 char    *name;
328         } flags[] = {
329 #define FE(x) { x, #x },
330                 FE(DSBCAPS_PRIMARYBUFFER)
331                 FE(DSBCAPS_STATIC)
332                 FE(DSBCAPS_LOCHARDWARE)
333                 FE(DSBCAPS_LOCSOFTWARE)
334                 FE(DSBCAPS_CTRL3D)
335                 FE(DSBCAPS_CTRLFREQUENCY)
336                 FE(DSBCAPS_CTRLPAN)
337                 FE(DSBCAPS_CTRLVOLUME)
338                 FE(DSBCAPS_CTRLPOSITIONNOTIFY)
339                 FE(DSBCAPS_CTRLDEFAULT)
340                 FE(DSBCAPS_CTRLALL)
341                 FE(DSBCAPS_STICKYFOCUS)
342                 FE(DSBCAPS_GLOBALFOCUS)
343                 FE(DSBCAPS_GETCURRENTPOSITION2)
344                 FE(DSBCAPS_MUTE3DATMAXDISTANCE)
345 #undef FE
346         };
347         int     i;
348
349         for (i=0;i<sizeof(flags)/sizeof(flags[0]);i++)
350                 if ((flags[i].mask & xmask) == flags[i].mask)
351                         DPRINTF("%s ",flags[i].name);
352 }
353
354 /*******************************************************************************
355  *              IKsPropertySet
356  */
357
358 /* IUnknown methods */
359 #ifdef USE_DSOUND3D
360 static HRESULT WINAPI IKsPropertySetImpl_QueryInterface(
361         LPKSPROPERTYSET iface, REFIID riid, LPVOID *ppobj
362 ) {
363         ICOM_THIS(IKsPropertySetImpl,iface);
364
365         FIXME("(%p,%s,%p), stub!\n",This,debugstr_guid(riid),ppobj);
366         return E_FAIL;
367 }
368 #endif
369
370 #ifdef USE_DSOUND3D
371 static ULONG WINAPI IKsPropertySetImpl_AddRef(LPKSPROPERTYSET iface) {
372         ICOM_THIS(IKsPropertySetImpl,iface);
373
374         This->ref++;
375         return This->ref;
376 }
377 #endif
378
379 #ifdef USE_DSOUND3D
380 static ULONG WINAPI IKsPropertySetImpl_Release(LPKSPROPERTYSET iface) {
381         ICOM_THIS(IKsPropertySetImpl,iface);
382
383         This->ref--;
384         return This->ref;
385 }
386 #endif
387
388 #ifdef USE_DSOUND3D
389 static HRESULT WINAPI IKsPropertySetImpl_Get(LPKSPROPERTYSET iface,
390         REFGUID guidPropSet, ULONG dwPropID,
391         LPVOID pInstanceData, ULONG cbInstanceData,
392         LPVOID pPropData, ULONG cbPropData,
393         PULONG pcbReturned
394 ) {
395         ICOM_THIS(IKsPropertySetImpl,iface);
396
397         FIXME("(%p,%s,%ld,%p,%ld,%p,%ld,%p), stub!\n",This,debugstr_guid(guidPropSet),dwPropID,pInstanceData,cbInstanceData,pPropData,cbPropData,pcbReturned);
398         return E_PROP_ID_UNSUPPORTED;
399 }
400 #endif
401
402 #ifdef USE_DSOUND3D
403 static HRESULT WINAPI IKsPropertySetImpl_Set(LPKSPROPERTYSET iface,
404         REFGUID guidPropSet, ULONG dwPropID,
405         LPVOID pInstanceData, ULONG cbInstanceData,
406         LPVOID pPropData, ULONG cbPropData
407 ) {
408         ICOM_THIS(IKsPropertySetImpl,iface);
409
410         FIXME("(%p,%s,%ld,%p,%ld,%p,%ld), stub!\n",This,debugstr_guid(guidPropSet),dwPropID,pInstanceData,cbInstanceData,pPropData,cbPropData);
411         return E_PROP_ID_UNSUPPORTED;
412 }
413 #endif
414
415 #ifdef USE_DSOUND3D
416 static HRESULT WINAPI IKsPropertySetImpl_QuerySupport(LPKSPROPERTYSET iface,
417         REFGUID guidPropSet, ULONG dwPropID, PULONG pTypeSupport
418 ) {
419         ICOM_THIS(IKsPropertySetImpl,iface);
420
421         FIXME("(%p,%s,%ld,%p), stub!\n",This,debugstr_guid(guidPropSet),dwPropID,pTypeSupport);
422         return E_PROP_ID_UNSUPPORTED;
423 }
424 #endif
425
426 #ifdef USE_DSOUND3D
427 static ICOM_VTABLE(IKsPropertySet) iksvt = {
428         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
429         IKsPropertySetImpl_QueryInterface,
430         IKsPropertySetImpl_AddRef,
431         IKsPropertySetImpl_Release,
432         IKsPropertySetImpl_Get,
433         IKsPropertySetImpl_Set,
434         IKsPropertySetImpl_QuerySupport
435 };
436 #endif
437
438 /*******************************************************************************
439  *              IDirectSound3DBuffer
440  */
441
442 /* IUnknown methods */
443 #ifdef USE_DSOUND3D
444 static HRESULT WINAPI IDirectSound3DBufferImpl_QueryInterface(
445         LPDIRECTSOUND3DBUFFER iface, REFIID riid, LPVOID *ppobj)
446 {
447         ICOM_THIS(IDirectSound3DBufferImpl,iface);
448
449         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
450             IDirectSound3DBuffer_AddRef(iface);
451             *ppobj = This->iks;
452             return S_OK;
453         }
454
455         FIXME("(%p,%s,%p), no such interface.\n",This,debugstr_guid(riid),ppobj);
456         return E_FAIL;
457 }
458 #endif
459
460 #ifdef USE_DSOUND3D
461 static ULONG WINAPI IDirectSound3DBufferImpl_AddRef(LPDIRECTSOUND3DBUFFER iface)
462 {
463         ICOM_THIS(IDirectSound3DBufferImpl,iface);
464         This->ref++;
465         return This->ref;
466 }
467 #endif
468
469 #ifdef USE_DSOUND3D
470 static ULONG WINAPI IDirectSound3DBufferImpl_Release(LPDIRECTSOUND3DBUFFER iface)
471 {
472         ICOM_THIS(IDirectSound3DBufferImpl,iface);
473
474         TRACE("(%p) ref was %ld\n", This, This->ref);
475
476         if(--This->ref)
477                 return This->ref;
478
479         if (This->dsb)
480                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->dsb);
481
482         DeleteCriticalSection(&This->lock);
483
484         HeapFree(GetProcessHeap(),0,This->buffer);
485         HeapFree(GetProcessHeap(),0,This);
486
487         return 0;
488 }
489 #endif
490
491 /* IDirectSound3DBuffer methods */
492 #ifdef USE_DSOUND3D
493 static HRESULT WINAPI IDirectSound3DBufferImpl_GetAllParameters(
494         LPDIRECTSOUND3DBUFFER iface,
495         LPDS3DBUFFER lpDs3dBuffer)
496 {
497         FIXME("stub\n");
498         return DS_OK;
499 }
500 #endif
501
502 #ifdef USE_DSOUND3D
503 static HRESULT WINAPI IDirectSound3DBufferImpl_GetConeAngles(
504         LPDIRECTSOUND3DBUFFER iface,
505         LPDWORD lpdwInsideConeAngle,
506         LPDWORD lpdwOutsideConeAngle)
507 {
508         FIXME("stub\n");
509         return DS_OK;
510 }
511 #endif
512
513 #ifdef USE_DSOUND3D
514 static HRESULT WINAPI IDirectSound3DBufferImpl_GetConeOrientation(
515         LPDIRECTSOUND3DBUFFER iface,
516         LPD3DVECTOR lpvConeOrientation)
517 {
518         FIXME("stub\n");
519         return DS_OK;
520 }
521 #endif
522
523 #ifdef USE_DSOUND3D
524 static HRESULT WINAPI IDirectSound3DBufferImpl_GetConeOutsideVolume(
525         LPDIRECTSOUND3DBUFFER iface,
526         LPLONG lplConeOutsideVolume)
527 {
528         FIXME("stub\n");
529         return DS_OK;
530 }
531 #endif
532
533 #ifdef USE_DSOUND3D
534 static HRESULT WINAPI IDirectSound3DBufferImpl_GetMaxDistance(
535         LPDIRECTSOUND3DBUFFER iface,
536         LPD3DVALUE lpfMaxDistance)
537 {
538         FIXME("stub\n");
539         return DS_OK;
540 }
541 #endif
542
543 #ifdef USE_DSOUND3D
544 static HRESULT WINAPI IDirectSound3DBufferImpl_GetMinDistance(
545         LPDIRECTSOUND3DBUFFER iface,
546         LPD3DVALUE lpfMinDistance)
547 {
548         FIXME("stub\n");
549         return DS_OK;
550 }
551 #endif
552
553 #ifdef USE_DSOUND3D
554 static HRESULT WINAPI IDirectSound3DBufferImpl_GetMode(
555         LPDIRECTSOUND3DBUFFER iface,
556         LPDWORD lpdwMode)
557 {
558         FIXME("stub\n");
559         return DS_OK;
560 }
561 #endif
562
563 #ifdef USE_DSOUND3D
564 static HRESULT WINAPI IDirectSound3DBufferImpl_GetPosition(
565         LPDIRECTSOUND3DBUFFER iface,
566         LPD3DVECTOR lpvPosition)
567 {
568         FIXME("stub\n");
569         return DS_OK;
570 }
571 #endif
572
573 #ifdef USE_DSOUND3D
574 static HRESULT WINAPI IDirectSound3DBufferImpl_GetVelocity(
575         LPDIRECTSOUND3DBUFFER iface,
576         LPD3DVECTOR lpvVelocity)
577 {
578         FIXME("stub\n");
579         return DS_OK;
580 }
581 #endif
582
583 #ifdef USE_DSOUND3D
584 static HRESULT WINAPI IDirectSound3DBufferImpl_SetAllParameters(
585         LPDIRECTSOUND3DBUFFER iface,
586         LPCDS3DBUFFER lpcDs3dBuffer,
587         DWORD dwApply)
588 {
589         FIXME("stub\n");
590         return DS_OK;
591 }
592 #endif
593
594 #ifdef USE_DSOUND3D
595 static HRESULT WINAPI IDirectSound3DBufferImpl_SetConeAngles(
596         LPDIRECTSOUND3DBUFFER iface,
597         DWORD dwInsideConeAngle,
598         DWORD dwOutsideConeAngle,
599         DWORD dwApply)
600 {
601         FIXME("stub\n");
602         return DS_OK;
603 }
604 #endif
605
606 #ifdef USE_DSOUND3D
607 static HRESULT WINAPI IDirectSound3DBufferImpl_SetConeOrientation(
608         LPDIRECTSOUND3DBUFFER iface,
609         D3DVALUE x, D3DVALUE y, D3DVALUE z,
610         DWORD dwApply)
611 {
612         FIXME("stub\n");
613         return DS_OK;
614 }
615 #endif
616
617 #ifdef USE_DSOUND3D
618 static HRESULT WINAPI IDirectSound3DBufferImpl_SetConeOutsideVolume(
619         LPDIRECTSOUND3DBUFFER iface,
620         LONG lConeOutsideVolume,
621         DWORD dwApply)
622 {
623         FIXME("stub\n");
624         return DS_OK;
625 }
626 #endif
627
628 #ifdef USE_DSOUND3D
629 static HRESULT WINAPI IDirectSound3DBufferImpl_SetMaxDistance(
630         LPDIRECTSOUND3DBUFFER iface,
631         D3DVALUE fMaxDistance,
632         DWORD dwApply)
633 {
634         FIXME("stub\n");
635         return DS_OK;
636 }
637 #endif
638
639 #ifdef USE_DSOUND3D
640 static HRESULT WINAPI IDirectSound3DBufferImpl_SetMinDistance(
641         LPDIRECTSOUND3DBUFFER iface,
642         D3DVALUE fMinDistance,
643         DWORD dwApply)
644 {
645         FIXME("stub\n");
646         return DS_OK;
647 }
648 #endif
649
650 #ifdef USE_DSOUND3D
651 static HRESULT WINAPI IDirectSound3DBufferImpl_SetMode(
652         LPDIRECTSOUND3DBUFFER iface,
653         DWORD dwMode,
654         DWORD dwApply)
655 {
656         ICOM_THIS(IDirectSound3DBufferImpl,iface);
657         TRACE("mode = %lx\n", dwMode);
658         This->ds3db.dwMode = dwMode;
659         return DS_OK;
660 }
661 #endif
662
663 #ifdef USE_DSOUND3D
664 static HRESULT WINAPI IDirectSound3DBufferImpl_SetPosition(
665         LPDIRECTSOUND3DBUFFER iface,
666         D3DVALUE x, D3DVALUE y, D3DVALUE z,
667         DWORD dwApply)
668 {
669         FIXME("stub\n");
670         return DS_OK;
671 }
672 #endif
673
674 #ifdef USE_DSOUND3D
675 static HRESULT WINAPI IDirectSound3DBufferImpl_SetVelocity(
676         LPDIRECTSOUND3DBUFFER iface,
677         D3DVALUE x, D3DVALUE y, D3DVALUE z,
678         DWORD dwApply)
679 {
680         FIXME("stub\n");
681         return DS_OK;
682 }
683 #endif
684
685 #ifdef USE_DSOUND3D
686 static ICOM_VTABLE(IDirectSound3DBuffer) ds3dbvt = 
687 {
688         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
689         /* IUnknown methods */
690         IDirectSound3DBufferImpl_QueryInterface,
691         IDirectSound3DBufferImpl_AddRef,
692         IDirectSound3DBufferImpl_Release,
693         /* IDirectSound3DBuffer methods */
694         IDirectSound3DBufferImpl_GetAllParameters,
695         IDirectSound3DBufferImpl_GetConeAngles,
696         IDirectSound3DBufferImpl_GetConeOrientation,
697         IDirectSound3DBufferImpl_GetConeOutsideVolume,
698         IDirectSound3DBufferImpl_GetMaxDistance,
699         IDirectSound3DBufferImpl_GetMinDistance,
700         IDirectSound3DBufferImpl_GetMode,
701         IDirectSound3DBufferImpl_GetPosition,
702         IDirectSound3DBufferImpl_GetVelocity,
703         IDirectSound3DBufferImpl_SetAllParameters,
704         IDirectSound3DBufferImpl_SetConeAngles,
705         IDirectSound3DBufferImpl_SetConeOrientation,
706         IDirectSound3DBufferImpl_SetConeOutsideVolume,
707         IDirectSound3DBufferImpl_SetMaxDistance,
708         IDirectSound3DBufferImpl_SetMinDistance,
709         IDirectSound3DBufferImpl_SetMode,
710         IDirectSound3DBufferImpl_SetPosition,
711         IDirectSound3DBufferImpl_SetVelocity,
712 };
713 #endif
714
715 #ifdef USE_DSOUND3D
716 static int DSOUND_Create3DBuffer(IDirectSoundBufferImpl* dsb)
717 {
718         DWORD   i, temp, iSize, oSize, offset;
719         LPBYTE  bIbuf, bObuf, bTbuf = NULL;
720         LPWORD  wIbuf, wObuf, wTbuf = NULL;
721
722         /* Inside DirectX says it's stupid but allowed */
723         if (dsb->wfx.nChannels == 2) {
724                 /* Convert to mono */
725                 if (dsb->wfx.wBitsPerSample == 16) {
726                         iSize = dsb->buflen / 4;
727                         wTbuf = malloc(dsb->buflen / 2);
728                         if (wTbuf == NULL)
729                                 return DSERR_OUTOFMEMORY;
730                         for (i = 0; i < iSize; i++)
731                                 wTbuf[i] = (dsb->buffer[i * 2] + dsb->buffer[(i * 2) + 1]) / 2;
732                         wIbuf = wTbuf;
733                 } else {
734                         iSize = dsb->buflen / 2;
735                         bTbuf = malloc(dsb->buflen / 2);
736                         if (bTbuf == NULL)
737                                 return DSERR_OUTOFMEMORY;
738                         for (i = 0; i < iSize; i++)
739                                 bTbuf[i] = (dsb->buffer[i * 2] + dsb->buffer[(i * 2) + 1]) / 2;
740                         bIbuf = bTbuf;
741                 }
742         } else {
743                 if (dsb->wfx.wBitsPerSample == 16) {
744                         iSize = dsb->buflen / 2;
745                         wIbuf = (LPWORD) dsb->buffer;
746                 } else {
747                         bIbuf = (LPBYTE) dsb->buffer;
748                         iSize = dsb->buflen;
749                 }
750         }
751
752         if (primarybuf->wfx.wBitsPerSample == 16) {
753                 wObuf = (LPWORD) dsb->ds3db->buffer;
754                 oSize = dsb->ds3db->buflen / 2;
755         } else {
756                 bObuf = (LPBYTE) dsb->ds3db->buffer;
757                 oSize = dsb->ds3db->buflen;
758         }
759
760         offset = primarybuf->wfx.nSamplesPerSec / 100;          /* 10ms */
761         if (primarybuf->wfx.wBitsPerSample == 16 && dsb->wfx.wBitsPerSample == 16)
762                 for (i = 0; i < iSize; i++) {
763                         temp = wIbuf[i];
764                         if (i >= offset)
765                                 temp += wIbuf[i - offset] >> 9;
766                         else
767                                 temp += wIbuf[i + iSize - offset] >> 9;
768                         wObuf[i * 2] = temp;
769                         wObuf[(i * 2) + 1] = temp;
770                 }
771         else if (primarybuf->wfx.wBitsPerSample == 8 && dsb->wfx.wBitsPerSample == 8)
772                 for (i = 0; i < iSize; i++) {
773                         temp = bIbuf[i];
774                         if (i >= offset)
775                                 temp += bIbuf[i - offset] >> 5;
776                         else
777                                 temp += bIbuf[i + iSize - offset] >> 5;
778                         bObuf[i * 2] = temp;
779                         bObuf[(i * 2) + 1] = temp;
780                 }
781         
782         if (wTbuf)
783                 free(wTbuf);
784         if (bTbuf)
785                 free(bTbuf);
786
787         return DS_OK;
788 }
789 #endif
790 /*******************************************************************************
791  *              IDirectSound3DListener
792  */
793
794 /* IUnknown methods */
795 static HRESULT WINAPI IDirectSound3DListenerImpl_QueryInterface(
796         LPDIRECTSOUND3DLISTENER iface, REFIID riid, LPVOID *ppobj)
797 {
798         ICOM_THIS(IDirectSound3DListenerImpl,iface);
799
800         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
801         return E_FAIL;
802 }
803         
804 static ULONG WINAPI IDirectSound3DListenerImpl_AddRef(LPDIRECTSOUND3DLISTENER iface)
805 {
806         ICOM_THIS(IDirectSound3DListenerImpl,iface);
807         This->ref++;
808         return This->ref;
809 }
810
811 static ULONG WINAPI IDirectSound3DListenerImpl_Release(LPDIRECTSOUND3DLISTENER iface)
812 {
813         ULONG ulReturn;
814         ICOM_THIS(IDirectSound3DListenerImpl,iface);
815
816         TRACE("(%p) ref was %ld\n", This, This->ref);
817
818         ulReturn = --This->ref;
819
820         /* Free all resources */
821         if( ulReturn == 0 ) {
822                 if(This->dsb)
823                         IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->dsb);
824                 DeleteCriticalSection(&This->lock);
825                 HeapFree(GetProcessHeap(),0,This);
826         }
827
828         return ulReturn;
829 }
830
831 /* IDirectSound3DListener methods */
832 static HRESULT WINAPI IDirectSound3DListenerImpl_GetAllParameter(
833         LPDIRECTSOUND3DLISTENER iface,
834         LPDS3DLISTENER lpDS3DL)
835 {
836         FIXME("stub\n");
837         return DS_OK;
838 }
839
840 static HRESULT WINAPI IDirectSound3DListenerImpl_GetDistanceFactor(
841         LPDIRECTSOUND3DLISTENER iface,
842         LPD3DVALUE lpfDistanceFactor)
843 {
844         FIXME("stub\n");
845         return DS_OK;
846 }
847
848 static HRESULT WINAPI IDirectSound3DListenerImpl_GetDopplerFactor(
849         LPDIRECTSOUND3DLISTENER iface,
850         LPD3DVALUE lpfDopplerFactor)
851 {
852         FIXME("stub\n");
853         return DS_OK;
854 }
855
856 static HRESULT WINAPI IDirectSound3DListenerImpl_GetOrientation(
857         LPDIRECTSOUND3DLISTENER iface,
858         LPD3DVECTOR lpvOrientFront,
859         LPD3DVECTOR lpvOrientTop)
860 {
861         FIXME("stub\n");
862         return DS_OK;
863 }
864
865 static HRESULT WINAPI IDirectSound3DListenerImpl_GetPosition(
866         LPDIRECTSOUND3DLISTENER iface,
867         LPD3DVECTOR lpvPosition)
868 {
869         FIXME("stub\n");
870         return DS_OK;
871 }
872
873 static HRESULT WINAPI IDirectSound3DListenerImpl_GetRolloffFactor(
874         LPDIRECTSOUND3DLISTENER iface,
875         LPD3DVALUE lpfRolloffFactor)
876 {
877         FIXME("stub\n");
878         return DS_OK;
879 }
880
881 static HRESULT WINAPI IDirectSound3DListenerImpl_GetVelocity(
882         LPDIRECTSOUND3DLISTENER iface,
883         LPD3DVECTOR lpvVelocity)
884 {
885         FIXME("stub\n");
886         return DS_OK;
887 }
888
889 static HRESULT WINAPI IDirectSound3DListenerImpl_SetAllParameters(
890         LPDIRECTSOUND3DLISTENER iface,
891         LPCDS3DLISTENER lpcDS3DL,
892         DWORD dwApply)
893 {
894         FIXME("stub\n");
895         return DS_OK;
896 }
897
898 static HRESULT WINAPI IDirectSound3DListenerImpl_SetDistanceFactor(
899         LPDIRECTSOUND3DLISTENER iface,
900         D3DVALUE fDistanceFactor,
901         DWORD dwApply)
902 {
903         FIXME("stub\n");
904         return DS_OK;
905 }
906
907 static HRESULT WINAPI IDirectSound3DListenerImpl_SetDopplerFactor(
908         LPDIRECTSOUND3DLISTENER iface,
909         D3DVALUE fDopplerFactor,
910         DWORD dwApply)
911 {
912         FIXME("stub\n");
913         return DS_OK;
914 }
915
916 static HRESULT WINAPI IDirectSound3DListenerImpl_SetOrientation(
917         LPDIRECTSOUND3DLISTENER iface,
918         D3DVALUE xFront, D3DVALUE yFront, D3DVALUE zFront,
919         D3DVALUE xTop, D3DVALUE yTop, D3DVALUE zTop,
920         DWORD dwApply)
921 {
922         FIXME("stub\n");
923         return DS_OK;
924 }
925
926 static HRESULT WINAPI IDirectSound3DListenerImpl_SetPosition(
927         LPDIRECTSOUND3DLISTENER iface,
928         D3DVALUE x, D3DVALUE y, D3DVALUE z,
929         DWORD dwApply)
930 {
931         FIXME("stub\n");
932         return DS_OK;
933 }
934
935 static HRESULT WINAPI IDirectSound3DListenerImpl_SetRolloffFactor(
936         LPDIRECTSOUND3DLISTENER iface,
937         D3DVALUE fRolloffFactor,
938         DWORD dwApply)
939 {
940         FIXME("stub\n");
941         return DS_OK;
942 }
943
944 static HRESULT WINAPI IDirectSound3DListenerImpl_SetVelocity(
945         LPDIRECTSOUND3DLISTENER iface,
946         D3DVALUE x, D3DVALUE y, D3DVALUE z,
947         DWORD dwApply)
948 {
949         FIXME("stub\n");
950         return DS_OK;
951 }
952
953 static HRESULT WINAPI IDirectSound3DListenerImpl_CommitDeferredSettings(
954         LPDIRECTSOUND3DLISTENER iface)
955
956 {
957         FIXME("stub\n");
958         return DS_OK;
959 }
960
961 static ICOM_VTABLE(IDirectSound3DListener) ds3dlvt = 
962 {
963         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
964         /* IUnknown methods */
965         IDirectSound3DListenerImpl_QueryInterface,
966         IDirectSound3DListenerImpl_AddRef,
967         IDirectSound3DListenerImpl_Release,
968         /* IDirectSound3DListener methods */
969         IDirectSound3DListenerImpl_GetAllParameter,
970         IDirectSound3DListenerImpl_GetDistanceFactor,
971         IDirectSound3DListenerImpl_GetDopplerFactor,
972         IDirectSound3DListenerImpl_GetOrientation,
973         IDirectSound3DListenerImpl_GetPosition,
974         IDirectSound3DListenerImpl_GetRolloffFactor,
975         IDirectSound3DListenerImpl_GetVelocity,
976         IDirectSound3DListenerImpl_SetAllParameters,
977         IDirectSound3DListenerImpl_SetDistanceFactor,
978         IDirectSound3DListenerImpl_SetDopplerFactor,
979         IDirectSound3DListenerImpl_SetOrientation,
980         IDirectSound3DListenerImpl_SetPosition,
981         IDirectSound3DListenerImpl_SetRolloffFactor,
982         IDirectSound3DListenerImpl_SetVelocity,
983         IDirectSound3DListenerImpl_CommitDeferredSettings,
984 };
985
986 /*******************************************************************************
987  *              IDirectSoundNotify
988  */
989 static HRESULT WINAPI IDirectSoundNotifyImpl_QueryInterface(
990         LPDIRECTSOUNDNOTIFY iface,REFIID riid,LPVOID *ppobj
991 ) {
992         ICOM_THIS(IDirectSoundNotifyImpl,iface);
993
994         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
995         return E_FAIL;
996 }
997
998 static ULONG WINAPI IDirectSoundNotifyImpl_AddRef(LPDIRECTSOUNDNOTIFY iface) {
999         ICOM_THIS(IDirectSoundNotifyImpl,iface);
1000         return ++(This->ref);
1001 }
1002
1003 static ULONG WINAPI IDirectSoundNotifyImpl_Release(LPDIRECTSOUNDNOTIFY iface) {
1004         ICOM_THIS(IDirectSoundNotifyImpl,iface);
1005
1006         TRACE("(%p) ref was %ld\n", This, This->ref);
1007
1008         This->ref--;
1009         if (!This->ref) {
1010                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->dsb);
1011                 HeapFree(GetProcessHeap(),0,This);
1012                 return 0;
1013         }
1014         return This->ref;
1015 }
1016
1017 static HRESULT WINAPI IDirectSoundNotifyImpl_SetNotificationPositions(
1018         LPDIRECTSOUNDNOTIFY iface,DWORD howmuch,LPCDSBPOSITIONNOTIFY notify
1019 ) {
1020         ICOM_THIS(IDirectSoundNotifyImpl,iface);
1021         int     i;
1022
1023         if (TRACE_ON(dsound)) {
1024             TRACE("(%p,0x%08lx,%p)\n",This,howmuch,notify);
1025             for (i=0;i<howmuch;i++)
1026                     TRACE("notify at %ld to 0x%08lx\n",
1027                             notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
1028         }
1029         This->dsb->notifies = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,This->dsb->notifies,(This->dsb->nrofnotifies+howmuch)*sizeof(DSBPOSITIONNOTIFY));
1030         memcpy( This->dsb->notifies+This->dsb->nrofnotifies,
1031                 notify,
1032                 howmuch*sizeof(DSBPOSITIONNOTIFY)
1033         );
1034         This->dsb->nrofnotifies+=howmuch;
1035
1036         return S_OK;
1037 }
1038
1039 static ICOM_VTABLE(IDirectSoundNotify) dsnvt = 
1040 {
1041         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1042         IDirectSoundNotifyImpl_QueryInterface,
1043         IDirectSoundNotifyImpl_AddRef,
1044         IDirectSoundNotifyImpl_Release,
1045         IDirectSoundNotifyImpl_SetNotificationPositions,
1046 };
1047
1048 /*******************************************************************************
1049  *              IDirectSoundBuffer
1050  */
1051
1052 static void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
1053 {
1054         double temp;
1055
1056         /* the AmpFactors are expressed in 16.16 fixed point */
1057         volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 65536);
1058         /* FIXME: dwPan{Left|Right}AmpFactor */
1059
1060         /* FIXME: use calculated vol and pan ampfactors */
1061         temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
1062         volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 65536);
1063         temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
1064         volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 65536);
1065
1066         TRACE("left = %lx, right = %lx\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
1067 }
1068
1069 static void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
1070 {
1071         DWORD sw;
1072
1073         sw = dsb->wfx.nChannels * (dsb->wfx.wBitsPerSample / 8);
1074         if ((dsb->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) && dsb->hwbuf) {
1075                 DWORD fraglen;
1076                 /* let fragment size approximate the timer delay */
1077                 fraglen = (dsb->freq * DS_TIME_DEL / 1000) * sw;
1078                 /* reduce fragment size until an integer number of them fits in the buffer */
1079                 /* (FIXME: this may or may not be a good idea) */
1080                 while (dsb->buflen % fraglen) fraglen -= sw;
1081                 dsb->dsound->fraglen = fraglen;
1082                 TRACE("fraglen=%ld\n", dsb->dsound->fraglen);
1083         }
1084         /* calculate the 10ms write lead */
1085         dsb->writelead = (dsb->freq / 100) * sw;
1086 }
1087
1088 static HRESULT DSOUND_PrimaryOpen(IDirectSoundBufferImpl *dsb)
1089 {
1090         HRESULT err = DS_OK;
1091
1092         /* are we using waveOut stuff? */
1093         if (!dsb->hwbuf) {
1094                 LPBYTE newbuf;
1095                 DWORD buflen;
1096                 HRESULT merr = DS_OK;
1097                 /* Start in pause mode, to allow buffers to get filled */
1098                 waveOutPause(dsb->dsound->hwo);
1099                 if (dsb->state == STATE_PLAYING) dsb->state = STATE_STARTING;
1100                 else if (dsb->state == STATE_STOPPING) dsb->state = STATE_STOPPED;
1101                 /* use fragments of 10ms (1/100s) each (which should get us within
1102                  * the documented write cursor lead of 10-15ms) */
1103                 buflen = ((dsb->wfx.nAvgBytesPerSec / 100) & ~3) * DS_HEL_FRAGS;
1104                 TRACE("desired buflen=%ld, old buffer=%p\n", buflen, dsb->buffer);
1105                 /* reallocate emulated primary buffer */
1106                 newbuf = (LPBYTE)HeapReAlloc(GetProcessHeap(),0,dsb->buffer,buflen);
1107                 if (newbuf == NULL) {
1108                         ERR("failed to allocate primary buffer\n");
1109                         merr = DSERR_OUTOFMEMORY;
1110                         /* but the old buffer might still exists and must be re-prepared */
1111                 } else {
1112                         dsb->buffer = newbuf;
1113                         dsb->buflen = buflen;
1114                 }
1115                 if (dsb->buffer) {
1116                         unsigned c;
1117                         IDirectSoundImpl *ds = dsb->dsound;
1118
1119                         ds->fraglen = dsb->buflen / DS_HEL_FRAGS;
1120
1121                         /* prepare fragment headers */
1122                         for (c=0; c<DS_HEL_FRAGS; c++) {
1123                                 ds->pwave[c]->lpData = dsb->buffer + c*ds->fraglen;
1124                                 ds->pwave[c]->dwBufferLength = ds->fraglen;
1125                                 ds->pwave[c]->dwUser = (DWORD)dsb;
1126                                 ds->pwave[c]->dwFlags = 0;
1127                                 ds->pwave[c]->dwLoops = 0;
1128                                 err = mmErr(waveOutPrepareHeader(ds->hwo,ds->pwave[c],sizeof(WAVEHDR)));
1129                                 if (err != DS_OK) {
1130                                         while (c--)
1131                                                 waveOutUnprepareHeader(ds->hwo,ds->pwave[c],sizeof(WAVEHDR));
1132                                         break;
1133                                 }
1134                         }
1135
1136                         ds->pwplay = 0;
1137                         ds->pwwrite = 0;
1138                         ds->pwqueue = 0;
1139                         memset(dsb->buffer, (dsb->wfx.wBitsPerSample == 16) ? 0 : 128, dsb->buflen);
1140                         TRACE("fraglen=%ld\n", ds->fraglen);
1141                         DSOUND_WaveQueue(dsb->dsound, (DWORD)-1);
1142                 }
1143                 if ((err == DS_OK) && (merr != DS_OK))
1144                         err = merr;
1145         }
1146         return err;
1147 }
1148
1149
1150 static void DSOUND_PrimaryClose(IDirectSoundBufferImpl *dsb)
1151 {
1152         /* are we using waveOut stuff? */
1153         if (!dsb->hwbuf) {
1154                 unsigned c;
1155                 IDirectSoundImpl *ds = dsb->dsound;
1156
1157                 ds->pwqueue = (DWORD)-1; /* resetting queues */
1158                 waveOutReset(ds->hwo);
1159                 for (c=0; c<DS_HEL_FRAGS; c++)
1160                         waveOutUnprepareHeader(ds->hwo, ds->pwave[c], sizeof(WAVEHDR));
1161                 ds->pwqueue = 0;
1162         }
1163 }
1164
1165 static HRESULT DSOUND_PrimaryPlay(IDirectSoundBufferImpl *dsb)
1166 {
1167         HRESULT err = DS_OK;
1168         if (dsb->hwbuf)
1169                 err = IDsDriverBuffer_Play(dsb->hwbuf, 0, 0, DSBPLAY_LOOPING);
1170         else
1171                 err = mmErr(waveOutRestart(dsb->dsound->hwo));
1172         return err;
1173 }
1174
1175 static HRESULT DSOUND_PrimaryStop(IDirectSoundBufferImpl *dsb)
1176 {
1177         HRESULT err = DS_OK;
1178
1179         TRACE("\n");
1180
1181         if (dsb->hwbuf) {
1182                 err = IDsDriverBuffer_Stop(dsb->hwbuf);
1183                 if (err == DSERR_BUFFERLOST) {
1184                         /* Wine-only: the driver wants us to reopen the device */
1185                         /* FIXME: check for errors */
1186                         IDsDriverBuffer_Release(primarybuf->hwbuf);
1187                         waveOutClose(dsb->dsound->hwo);
1188                         dsb->dsound->hwo = 0;
1189                         err = mmErr(waveOutOpen(&(dsb->dsound->hwo), dsb->dsound->drvdesc.dnDevNode,
1190                                                 &(primarybuf->wfx), (DWORD)DSOUND_callback, (DWORD)dsb->dsound,
1191                                                 CALLBACK_FUNCTION | WAVE_DIRECTSOUND));
1192                         if (err == DS_OK)
1193                             err = IDsDriver_CreateSoundBuffer(dsb->dsound->driver,&(dsb->wfx),dsb->dsbd.dwFlags,0,
1194                                                               &(dsb->buflen),&(dsb->buffer),
1195                                                               (LPVOID)&(dsb->hwbuf));
1196                 }
1197         }
1198         else
1199                 err = mmErr(waveOutPause(dsb->dsound->hwo));
1200         return err;
1201 }
1202
1203 /* This sets this format for the <em>Primary Buffer Only</em> */
1204 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
1205 static HRESULT WINAPI IDirectSoundBufferImpl_SetFormat(
1206         LPDIRECTSOUNDBUFFER iface,LPWAVEFORMATEX wfex
1207 ) {
1208         ICOM_THIS(IDirectSoundBufferImpl,iface);
1209         IDirectSoundBufferImpl** dsb;
1210         HRESULT err = DS_OK;
1211         int                     i;
1212
1213         /* Let's be pedantic! */
1214         if ((wfex == NULL) ||
1215             (wfex->wFormatTag != WAVE_FORMAT_PCM) ||
1216             (wfex->nChannels < 1) || (wfex->nChannels > 2) ||
1217             (wfex->nSamplesPerSec < 1) ||
1218             (wfex->nBlockAlign < 1) || (wfex->nChannels > 4) ||
1219             ((wfex->wBitsPerSample != 8) && (wfex->wBitsPerSample != 16))) {
1220                 TRACE("failed pedantic check!\n");
1221                 return DSERR_INVALIDPARAM;
1222         }
1223
1224         /* **** */
1225         EnterCriticalSection(&(This->dsound->lock));
1226
1227         if (primarybuf->wfx.nSamplesPerSec != wfex->nSamplesPerSec) {
1228                 dsb = dsound->buffers;
1229                 for (i = 0; i < dsound->nrofbuffers; i++, dsb++) {
1230                         /* **** */
1231                         EnterCriticalSection(&((*dsb)->lock));
1232
1233                         (*dsb)->freqAdjust = ((*dsb)->freq << DSOUND_FREQSHIFT) /
1234                                 wfex->nSamplesPerSec;
1235
1236                         LeaveCriticalSection(&((*dsb)->lock));
1237                         /* **** */
1238                 }
1239         }
1240
1241         memcpy(&(primarybuf->wfx), wfex, sizeof(primarybuf->wfx));
1242
1243         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
1244                    "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1245                    wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
1246                    wfex->nAvgBytesPerSec, wfex->nBlockAlign, 
1247                    wfex->wBitsPerSample, wfex->cbSize);
1248
1249         primarybuf->wfx.nAvgBytesPerSec =
1250                 This->wfx.nSamplesPerSec * This->wfx.nBlockAlign;
1251
1252         if (primarybuf->dsound->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMSETFORMAT) {
1253                 /* FIXME: check for errors */
1254                 DSOUND_PrimaryClose(primarybuf);
1255                 waveOutClose(This->dsound->hwo);
1256                 This->dsound->hwo = 0;
1257                 err = mmErr(waveOutOpen(&(This->dsound->hwo), This->dsound->drvdesc.dnDevNode,
1258                                         &(primarybuf->wfx), (DWORD)DSOUND_callback, (DWORD)This->dsound,
1259                                         CALLBACK_FUNCTION | WAVE_DIRECTSOUND));
1260                 if (err == DS_OK)
1261                     DSOUND_PrimaryOpen(primarybuf);
1262         }
1263         if (primarybuf->hwbuf) {
1264                 err = IDsDriverBuffer_SetFormat(primarybuf->hwbuf, &(primarybuf->wfx));
1265                 if (err == DSERR_BUFFERLOST) {
1266                         /* Wine-only: the driver wants us to recreate the HW buffer */
1267                         IDsDriverBuffer_Release(primarybuf->hwbuf);
1268                         err = IDsDriver_CreateSoundBuffer(primarybuf->dsound->driver,&(primarybuf->wfx),primarybuf->dsbd.dwFlags,0,
1269                                                           &(primarybuf->buflen),&(primarybuf->buffer),
1270                                                           (LPVOID)&(primarybuf->hwbuf));
1271                         if (primarybuf->state == STATE_PLAYING) primarybuf->state = STATE_STARTING;
1272                         else if (primarybuf->state == STATE_STOPPING) primarybuf->state = STATE_STOPPED;
1273                 }
1274                 /* FIXME: should we set err back to DS_OK in all cases ? */
1275         }
1276         DSOUND_RecalcFormat(primarybuf);
1277
1278         LeaveCriticalSection(&(This->dsound->lock));
1279         /* **** */
1280
1281         return err;
1282 }
1283
1284 static HRESULT WINAPI IDirectSoundBufferImpl_SetVolume(
1285         LPDIRECTSOUNDBUFFER iface,LONG vol
1286 ) {
1287         ICOM_THIS(IDirectSoundBufferImpl,iface);
1288
1289         TRACE("(%p,%ld)\n",This,vol);
1290
1291         /* I'm not sure if we need this for primary buffer */
1292         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
1293                 return DSERR_CONTROLUNAVAIL;
1294
1295         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN))
1296                 return DSERR_INVALIDPARAM;
1297
1298         /* **** */
1299         EnterCriticalSection(&(This->lock));
1300
1301         This->volpan.lVolume = vol;
1302
1303         DSOUND_RecalcVolPan(&(This->volpan));
1304
1305         if (This->hwbuf) {
1306                 IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
1307         }
1308         else if (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) {
1309 #if 0 /* should we really do this? */
1310                 /* the DS volume ranges from 0 (max, 0dB attenuation) to -10000 (min, 100dB attenuation) */
1311                 /* the MM volume ranges from 0 to 0xffff in an unspecified logarithmic scale */
1312                 WORD cvol = 0xffff + vol*6 + vol/2;
1313                 DWORD vol = cvol | ((DWORD)cvol << 16)
1314                 waveOutSetVolume(This->dsound->hwo, vol);
1315 #endif
1316         }
1317
1318         LeaveCriticalSection(&(This->lock));
1319         /* **** */
1320
1321         return DS_OK;
1322 }
1323
1324 static HRESULT WINAPI IDirectSoundBufferImpl_GetVolume(
1325         LPDIRECTSOUNDBUFFER iface,LPLONG vol
1326 ) {
1327         ICOM_THIS(IDirectSoundBufferImpl,iface);
1328         TRACE("(%p,%p)\n",This,vol);
1329
1330         if (vol == NULL)
1331                 return DSERR_INVALIDPARAM;
1332
1333         *vol = This->volpan.lVolume;
1334         return DS_OK;
1335 }
1336
1337 static HRESULT WINAPI IDirectSoundBufferImpl_SetFrequency(
1338         LPDIRECTSOUNDBUFFER iface,DWORD freq
1339 ) {
1340         ICOM_THIS(IDirectSoundBufferImpl,iface);
1341         TRACE("(%p,%ld)\n",This,freq);
1342
1343         /* You cannot set the frequency of the primary buffer */
1344         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY) ||
1345             (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER))
1346                 return DSERR_CONTROLUNAVAIL;
1347
1348         if (!freq) freq = This->wfx.nSamplesPerSec;
1349
1350         if ((freq < DSBFREQUENCY_MIN) || (freq > DSBFREQUENCY_MAX))
1351                 return DSERR_INVALIDPARAM;
1352
1353         /* **** */
1354         EnterCriticalSection(&(This->lock));
1355
1356         This->freq = freq;
1357         This->freqAdjust = (freq << DSOUND_FREQSHIFT) / primarybuf->wfx.nSamplesPerSec;
1358         This->nAvgBytesPerSec = freq * This->wfx.nBlockAlign;
1359         DSOUND_RecalcFormat(This);
1360
1361         LeaveCriticalSection(&(This->lock));
1362         /* **** */
1363
1364         return DS_OK;
1365 }
1366
1367 static HRESULT WINAPI IDirectSoundBufferImpl_Play(
1368         LPDIRECTSOUNDBUFFER iface,DWORD reserved1,DWORD reserved2,DWORD flags
1369 ) {
1370         ICOM_THIS(IDirectSoundBufferImpl,iface);
1371         TRACE("(%p,%08lx,%08lx,%08lx)\n",
1372                 This,reserved1,reserved2,flags
1373         );
1374
1375         /* **** */
1376         EnterCriticalSection(&(This->lock));
1377
1378         This->playflags = flags;
1379         if (This->state == STATE_STOPPED) {
1380                 This->leadin = TRUE;
1381                 This->startpos = This->buf_mixpos;
1382                 This->state = STATE_STARTING;
1383         } else if (This->state == STATE_STOPPING)
1384                 This->state = STATE_PLAYING;
1385         if (!(This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) && This->hwbuf) {
1386                 IDsDriverBuffer_Play(This->hwbuf, 0, 0, This->playflags);
1387                 This->state = STATE_PLAYING;
1388         }
1389
1390         LeaveCriticalSection(&(This->lock));
1391         /* **** */
1392
1393         return DS_OK;
1394 }
1395
1396 static HRESULT WINAPI IDirectSoundBufferImpl_Stop(LPDIRECTSOUNDBUFFER iface)
1397 {
1398         ICOM_THIS(IDirectSoundBufferImpl,iface);
1399         TRACE("(%p)\n",This);
1400
1401         /* **** */
1402         EnterCriticalSection(&(This->lock));
1403
1404         if (This->state == STATE_PLAYING)
1405                 This->state = STATE_STOPPING;
1406         else if (This->state == STATE_STARTING)
1407                 This->state = STATE_STOPPED;
1408         if (!(This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) && This->hwbuf) {
1409                 IDsDriverBuffer_Stop(This->hwbuf);
1410                 This->state = STATE_STOPPED;
1411         }
1412         DSOUND_CheckEvent(This, 0);
1413
1414         LeaveCriticalSection(&(This->lock));
1415         /* **** */
1416
1417         return DS_OK;
1418 }
1419
1420 static DWORD WINAPI IDirectSoundBufferImpl_AddRef(LPDIRECTSOUNDBUFFER iface) {
1421         ICOM_THIS(IDirectSoundBufferImpl,iface);
1422         DWORD ref;
1423
1424         TRACE("(%p) ref was %ld, thread is %lx\n",This, This->ref, GetCurrentThreadId());
1425
1426         ref = InterlockedIncrement(&(This->ref));
1427         if (!ref) {
1428                 FIXME("thread-safety alert! AddRef-ing with a zero refcount!\n");
1429         }
1430         return ref;
1431 }
1432 static DWORD WINAPI IDirectSoundBufferImpl_Release(LPDIRECTSOUNDBUFFER iface) {
1433         ICOM_THIS(IDirectSoundBufferImpl,iface);
1434         int     i;
1435         DWORD ref;
1436
1437         TRACE("(%p) ref was %ld, thread is %lx\n",This, This->ref, GetCurrentThreadId());
1438
1439         ref = InterlockedDecrement(&(This->ref));
1440         if (ref) return ref;
1441
1442         EnterCriticalSection(&(This->dsound->lock));
1443         for (i=0;i<This->dsound->nrofbuffers;i++)
1444                 if (This->dsound->buffers[i] == This)
1445                         break;
1446
1447         if (i < This->dsound->nrofbuffers) {
1448                 /* Put the last buffer of the list in the (now empty) position */
1449                 This->dsound->buffers[i] = This->dsound->buffers[This->dsound->nrofbuffers - 1];
1450                 This->dsound->nrofbuffers--;
1451                 This->dsound->buffers = HeapReAlloc(GetProcessHeap(),0,This->dsound->buffers,sizeof(LPDIRECTSOUNDBUFFER)*This->dsound->nrofbuffers);
1452                 TRACE("buffer count is now %d\n", This->dsound->nrofbuffers);
1453                 IDirectSound_Release((LPDIRECTSOUND)This->dsound);
1454         }
1455         LeaveCriticalSection(&(This->dsound->lock));
1456
1457         DeleteCriticalSection(&(This->lock));
1458         if (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER)
1459                 DSOUND_PrimaryClose(This);
1460         if (This->hwbuf) {
1461                 IDsDriverBuffer_Release(This->hwbuf);
1462         }
1463         if (This->ds3db)
1464                 IDirectSound3DBuffer_Release((LPDIRECTSOUND3DBUFFER)This->ds3db);
1465         if (This->parent)
1466                 /* this is a duplicate buffer */
1467                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->parent);
1468         else
1469                 /* this is a toplevel buffer */
1470                 HeapFree(GetProcessHeap(),0,This->buffer);
1471
1472         HeapFree(GetProcessHeap(),0,This);
1473         
1474         if (This == primarybuf)
1475                 primarybuf = NULL;
1476
1477         return 0;
1478 }
1479
1480 static DWORD DSOUND_CalcPlayPosition(IDirectSoundBufferImpl *This,
1481                                      DWORD state, DWORD pplay, DWORD pwrite, DWORD pmix, DWORD bmix)
1482 {
1483         DWORD bplay;
1484
1485         TRACE("primary playpos=%ld, mixpos=%ld\n", pplay, pmix);
1486         TRACE("this mixpos=%ld, time=%ld\n", bmix, GetTickCount());
1487
1488         /* the actual primary play position (pplay) is always behind last mixed (pmix),
1489          * unless the computer is too slow or something */
1490         /* we need to know how far away we are from there */
1491 #if 0 /* we'll never fill the primary entirely */
1492         if (pmix == pplay) {
1493                 if ((state == STATE_PLAYING) || (state == STATE_STOPPING)) {
1494                         /* wow, the software mixer is really doing well,
1495                          * seems the entire primary buffer is filled! */
1496                         pmix += primarybuf->buflen;
1497                 }
1498                 /* else: the primary buffer is not playing, so probably empty */
1499         }
1500 #endif
1501         if (pmix < pplay) pmix += primarybuf->buflen; /* wraparound */
1502         pmix -= pplay;
1503         /* detect buffer underrun */
1504         if (pwrite < pplay) pwrite += primarybuf->buflen; /* wraparound */
1505         pwrite -= pplay;
1506         if (pmix > (DS_SND_QUEUE_MAX * primarybuf->dsound->fraglen + pwrite + primarybuf->writelead)) {
1507                 WARN("detected an underrun: primary queue was %ld\n",pmix);
1508                 pmix = 0;
1509         }
1510         /* divide the offset by its sample size */
1511         pmix /= primarybuf->wfx.nBlockAlign;
1512         TRACE("primary back-samples=%ld\n",pmix);
1513         /* adjust for our frequency */
1514         pmix = (pmix * This->freqAdjust) >> DSOUND_FREQSHIFT;
1515         /* multiply by our own sample size */
1516         pmix *= This->wfx.nBlockAlign;
1517         TRACE("this back-offset=%ld\n", pmix);
1518         /* subtract from our last mixed position */
1519         bplay = bmix;
1520         while (bplay < pmix) bplay += This->buflen; /* wraparound */
1521         bplay -= pmix;
1522         if (This->leadin && ((bplay < This->startpos) || (bplay > bmix))) {
1523                 /* seems we haven't started playing yet */
1524                 TRACE("this still in lead-in phase\n");
1525                 bplay = This->startpos;
1526         }
1527         /* return the result */
1528         return bplay;
1529 }
1530
1531 static HRESULT WINAPI IDirectSoundBufferImpl_GetCurrentPosition(
1532         LPDIRECTSOUNDBUFFER iface,LPDWORD playpos,LPDWORD writepos
1533 ) {
1534         HRESULT hres; 
1535         ICOM_THIS(IDirectSoundBufferImpl,iface);
1536         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
1537         if (This->hwbuf) {
1538                 hres=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
1539                 if (hres)
1540                     return hres;
1541         }
1542         else if (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) {
1543                 if (playpos) {
1544                         MMTIME mtime;
1545                         mtime.wType = TIME_BYTES;
1546                         waveOutGetPosition(This->dsound->hwo, &mtime, sizeof(mtime));
1547                         mtime.u.cb = mtime.u.cb % This->buflen;
1548                         *playpos = mtime.u.cb;
1549                 }
1550                 if (writepos) {
1551                         /* the writepos should only be used by apps with WRITEPRIMARY priority,
1552                          * in which case our software mixer is disabled anyway */
1553                         *writepos = (This->dsound->pwplay + DS_HEL_MARGIN) * This->dsound->fraglen;
1554                         while (*writepos >= This->buflen)
1555                                 *writepos -= This->buflen;
1556                 }
1557         } else {
1558                 if (playpos && (This->state != STATE_PLAYING)) {
1559                         /* we haven't been merged into the primary buffer (yet) */
1560                         *playpos = This->buf_mixpos;
1561                 }
1562                 else if (playpos) {
1563                         DWORD pplay, pwrite, lplay, splay, pstate;
1564                         /* let's get this exact; first, recursively call GetPosition on the primary */
1565                         EnterCriticalSection(&(primarybuf->lock));
1566                         IDirectSoundBufferImpl_GetCurrentPosition((LPDIRECTSOUNDBUFFER)primarybuf, &pplay, &pwrite);
1567                         /* detect HEL mode underrun */
1568                         pstate = primarybuf->state;
1569                         if (!(primarybuf->hwbuf || primarybuf->dsound->pwqueue)) {
1570                                 TRACE("detected an underrun\n");
1571                                 /* pplay = ? */
1572                                 if (pstate == STATE_PLAYING)
1573                                         pstate = STATE_STARTING;
1574                                 else if (pstate == STATE_STOPPING)
1575                                         pstate = STATE_STOPPED;
1576                         }
1577                         /* get data for ourselves while we still have the lock */
1578                         pstate &= This->state;
1579                         lplay = This->primary_mixpos;
1580                         splay = This->buf_mixpos;
1581                         if ((This->dsbd.dwFlags & DSBCAPS_GETCURRENTPOSITION2) || primarybuf->hwbuf) {
1582                                 /* calculate play position using this */
1583                                 *playpos = DSOUND_CalcPlayPosition(This, pstate, pplay, pwrite, lplay, splay);
1584                         } else {
1585                                 /* (unless the app isn't using GETCURRENTPOSITION2) */
1586                                 /* don't know exactly how this should be handled...
1587                                  * the docs says that play cursor is reported as directly
1588                                  * behind write cursor, hmm... */
1589                                 /* let's just do what might work for Half-Life */
1590                                 DWORD wp;
1591                                 wp = (This->dsound->pwplay + DS_HEL_MARGIN) * This->dsound->fraglen;
1592                                 while (wp >= primarybuf->buflen)
1593                                         wp -= primarybuf->buflen;
1594                                 *playpos = DSOUND_CalcPlayPosition(This, pstate, wp, pwrite, lplay, splay);
1595                         }
1596                         LeaveCriticalSection(&(primarybuf->lock));
1597                 }
1598                 if (writepos) *writepos = This->buf_mixpos;
1599         }
1600         if (writepos) {
1601                 if (This->state != STATE_STOPPED)
1602                         /* apply the documented 10ms lead to writepos */
1603                         *writepos += This->writelead;
1604                 while (*writepos >= This->buflen) *writepos -= This->buflen;
1605         }
1606         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
1607         return DS_OK;
1608 }
1609
1610 static HRESULT WINAPI IDirectSoundBufferImpl_GetStatus(
1611         LPDIRECTSOUNDBUFFER iface,LPDWORD status
1612 ) {
1613         ICOM_THIS(IDirectSoundBufferImpl,iface);
1614         TRACE("(%p,%p), thread is %lx\n",This,status,GetCurrentThreadId());
1615
1616         if (status == NULL)
1617                 return DSERR_INVALIDPARAM;
1618
1619         *status = 0;
1620         if ((This->state == STATE_STARTING) || (This->state == STATE_PLAYING)) {
1621                 *status |= DSBSTATUS_PLAYING;
1622                 if (This->playflags & DSBPLAY_LOOPING)
1623                         *status |= DSBSTATUS_LOOPING;
1624         }
1625
1626         TRACE("status=%lx\n", *status);
1627         return DS_OK;
1628 }
1629
1630
1631 static HRESULT WINAPI IDirectSoundBufferImpl_GetFormat(
1632         LPDIRECTSOUNDBUFFER iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten
1633 ) {
1634         ICOM_THIS(IDirectSoundBufferImpl,iface);
1635         TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
1636
1637         if (wfsize>sizeof(This->wfx))
1638                 wfsize = sizeof(This->wfx);
1639         if (lpwf) {     /* NULL is valid */
1640                 memcpy(lpwf,&(This->wfx),wfsize);
1641                 if (wfwritten)
1642                         *wfwritten = wfsize;
1643         } else
1644                 if (wfwritten)
1645                         *wfwritten = sizeof(This->wfx);
1646                 else
1647                         return DSERR_INVALIDPARAM;
1648
1649         return DS_OK;
1650 }
1651
1652 static HRESULT WINAPI IDirectSoundBufferImpl_Lock(
1653         LPDIRECTSOUNDBUFFER iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
1654 ) {
1655         ICOM_THIS(IDirectSoundBufferImpl,iface);
1656         DWORD capf;
1657
1658         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
1659                 This,
1660                 writecursor,
1661                 writebytes,
1662                 lplpaudioptr1,
1663                 audiobytes1,
1664                 lplpaudioptr2,
1665                 audiobytes2,
1666                 flags,
1667                 GetTickCount()
1668         );
1669
1670         if (flags & DSBLOCK_FROMWRITECURSOR) {
1671                 DWORD writepos;
1672                 /* GetCurrentPosition does too much magic to duplicate here */
1673                 IDirectSoundBufferImpl_GetCurrentPosition(iface, NULL, &writepos);
1674                 writecursor += writepos;
1675         }
1676         if (flags & DSBLOCK_ENTIREBUFFER)
1677                 writebytes = This->buflen;
1678         if (writebytes > This->buflen)
1679                 writebytes = This->buflen;
1680
1681         assert(audiobytes1!=audiobytes2);
1682         assert(lplpaudioptr1!=lplpaudioptr2);
1683
1684         if ((writebytes == This->buflen) &&
1685             ((This->state == STATE_STARTING) ||
1686              (This->state == STATE_PLAYING)))
1687                 /* some games, like Half-Life, try to be clever (not) and
1688                  * keep one secondary buffer, and mix sounds into it itself,
1689                  * locking the entire buffer every time... so we can just forget
1690                  * about tracking the last-written-to-position... */
1691                 This->probably_valid_to = (DWORD)-1;
1692         else
1693                 This->probably_valid_to = writecursor;
1694
1695         if (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER)
1696                 capf = DSDDESC_DONTNEEDPRIMARYLOCK;
1697         else
1698                 capf = DSDDESC_DONTNEEDSECONDARYLOCK;
1699         if (!(This->dsound->drvdesc.dwFlags & capf) && This->hwbuf) {
1700                 IDsDriverBuffer_Lock(This->hwbuf,
1701                                      lplpaudioptr1, audiobytes1,
1702                                      lplpaudioptr2, audiobytes2,
1703                                      writecursor, writebytes,
1704                                      0);
1705         }
1706         else {
1707                 BOOL remix = FALSE;
1708                 if (writecursor+writebytes <= This->buflen) {
1709                         *(LPBYTE*)lplpaudioptr1 = This->buffer+writecursor;
1710                         *audiobytes1 = writebytes;
1711                         if (lplpaudioptr2)
1712                                 *(LPBYTE*)lplpaudioptr2 = NULL;
1713                         if (audiobytes2)
1714                                 *audiobytes2 = 0;
1715                         TRACE("->%ld.0\n",writebytes);
1716                 } else {
1717                         *(LPBYTE*)lplpaudioptr1 = This->buffer+writecursor;
1718                         *audiobytes1 = This->buflen-writecursor;
1719                         if (lplpaudioptr2)
1720                                 *(LPBYTE*)lplpaudioptr2 = This->buffer;
1721                         if (audiobytes2)
1722                                 *audiobytes2 = writebytes-(This->buflen-writecursor);
1723                         TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
1724                 }
1725                 /* if the segment between playpos and buf_mixpos is touched,
1726                  * we need to cancel some mixing */
1727                 if (This->buf_mixpos >= This->playpos) {
1728                         if (This->buf_mixpos > writecursor &&
1729                             This->playpos <= writecursor+writebytes)
1730                                 remix = TRUE;
1731                 }
1732                 else {
1733                         if (This->buf_mixpos > writecursor ||
1734                             This->playpos <= writecursor+writebytes)
1735                                 remix = TRUE;
1736                 }
1737                 if (remix) {
1738                         TRACE("locking prebuffered region, ouch\n");
1739                         DSOUND_MixCancelAt(This, writecursor);
1740                 }
1741         }
1742         return DS_OK;
1743 }
1744
1745 static HRESULT WINAPI IDirectSoundBufferImpl_SetCurrentPosition(
1746         LPDIRECTSOUNDBUFFER iface,DWORD newpos
1747 ) {
1748         ICOM_THIS(IDirectSoundBufferImpl,iface);
1749         TRACE("(%p,%ld)\n",This,newpos);
1750
1751         /* **** */
1752         EnterCriticalSection(&(This->lock));
1753
1754         This->buf_mixpos = newpos;
1755         if (This->hwbuf)
1756                 IDsDriverBuffer_SetPosition(This->hwbuf, This->buf_mixpos);
1757
1758         LeaveCriticalSection(&(This->lock));
1759         /* **** */
1760
1761         return DS_OK;
1762 }
1763
1764 static HRESULT WINAPI IDirectSoundBufferImpl_SetPan(
1765         LPDIRECTSOUNDBUFFER iface,LONG pan
1766 ) {
1767         ICOM_THIS(IDirectSoundBufferImpl,iface);
1768
1769         TRACE("(%p,%ld)\n",This,pan);
1770
1771         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT))
1772                 return DSERR_INVALIDPARAM;
1773
1774         /* You cannot set the pan of the primary buffer */
1775         /* and you cannot use both pan and 3D controls */
1776         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
1777             (This->dsbd.dwFlags & DSBCAPS_CTRL3D) ||
1778             (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER))
1779                 return DSERR_CONTROLUNAVAIL;
1780
1781         /* **** */
1782         EnterCriticalSection(&(This->lock));
1783
1784         This->volpan.lPan = pan;
1785
1786         DSOUND_RecalcVolPan(&(This->volpan));
1787
1788         if (This->hwbuf) {
1789                 IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
1790         }
1791
1792         LeaveCriticalSection(&(This->lock));
1793         /* **** */
1794
1795         return DS_OK;
1796 }
1797
1798 static HRESULT WINAPI IDirectSoundBufferImpl_GetPan(
1799         LPDIRECTSOUNDBUFFER iface,LPLONG pan
1800 ) {
1801         ICOM_THIS(IDirectSoundBufferImpl,iface);
1802         TRACE("(%p,%p)\n",This,pan);
1803
1804         if (pan == NULL)
1805                 return DSERR_INVALIDPARAM;
1806
1807         *pan = This->volpan.lPan;
1808
1809         return DS_OK;
1810 }
1811
1812 static HRESULT WINAPI IDirectSoundBufferImpl_Unlock(
1813         LPDIRECTSOUNDBUFFER iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
1814 ) {
1815         ICOM_THIS(IDirectSoundBufferImpl,iface);
1816         DWORD capf, probably_valid_to;
1817
1818         TRACE("(%p,%p,%ld,%p,%ld):stub\n", This,p1,x1,p2,x2);
1819
1820 #if 0
1821         /* Preprocess 3D buffers... */
1822
1823         /* This is highly experimental and liable to break things */
1824         if (This->dsbd.dwFlags & DSBCAPS_CTRL3D)
1825                 DSOUND_Create3DBuffer(This);
1826 #endif
1827
1828         if (This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER)
1829                 capf = DSDDESC_DONTNEEDPRIMARYLOCK;
1830         else
1831                 capf = DSDDESC_DONTNEEDSECONDARYLOCK;
1832         if (!(This->dsound->drvdesc.dwFlags & capf) && This->hwbuf) {
1833                 IDsDriverBuffer_Unlock(This->hwbuf, p1, x1, p2, x2);
1834         }
1835
1836         if (p2) probably_valid_to = (((LPBYTE)p2)-This->buffer) + x2;
1837         else probably_valid_to = (((LPBYTE)p1)-This->buffer) + x1;
1838         while (probably_valid_to >= This->buflen)
1839                 probably_valid_to -= This->buflen;
1840         if ((probably_valid_to == 0) && ((x1+x2) == This->buflen) &&
1841             ((This->state == STATE_STARTING) ||
1842              (This->state == STATE_PLAYING)))
1843                 /* see IDirectSoundBufferImpl_Lock */
1844                 probably_valid_to = (DWORD)-1;
1845         This->probably_valid_to = probably_valid_to;
1846
1847         return DS_OK;
1848 }
1849
1850 static HRESULT WINAPI IDirectSoundBufferImpl_Restore(
1851         LPDIRECTSOUNDBUFFER iface
1852 ) {
1853         ICOM_THIS(IDirectSoundBufferImpl,iface);
1854         FIXME("(%p):stub\n",This);
1855         return DS_OK;
1856 }
1857
1858 static HRESULT WINAPI IDirectSoundBufferImpl_GetFrequency(
1859         LPDIRECTSOUNDBUFFER iface,LPDWORD freq
1860 ) {
1861         ICOM_THIS(IDirectSoundBufferImpl,iface);
1862         TRACE("(%p,%p)\n",This,freq);
1863
1864         if (freq == NULL)
1865                 return DSERR_INVALIDPARAM;
1866
1867         *freq = This->freq;
1868         TRACE("-> %ld\n", *freq);
1869
1870         return DS_OK;
1871 }
1872
1873 static HRESULT WINAPI IDirectSoundBufferImpl_Initialize(
1874         LPDIRECTSOUNDBUFFER iface,LPDIRECTSOUND dsound,LPDSBUFFERDESC dbsd
1875 ) {
1876         ICOM_THIS(IDirectSoundBufferImpl,iface);
1877         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
1878         DPRINTF("Re-Init!!!\n");
1879         return DSERR_ALREADYINITIALIZED;
1880 }
1881
1882 static HRESULT WINAPI IDirectSoundBufferImpl_GetCaps(
1883         LPDIRECTSOUNDBUFFER iface,LPDSBCAPS caps
1884 ) {
1885         ICOM_THIS(IDirectSoundBufferImpl,iface);
1886         TRACE("(%p)->(%p)\n",This,caps);
1887   
1888         if (caps == NULL)
1889                 return DSERR_INVALIDPARAM;
1890
1891         /* I think we should check this value, not set it. See */
1892         /* Inside DirectX, p215. That should apply here, too. */
1893         caps->dwSize = sizeof(*caps);
1894
1895         caps->dwFlags = This->dsbd.dwFlags;
1896         if (This->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
1897         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
1898
1899         caps->dwBufferBytes = This->buflen;
1900
1901         /* This value represents the speed of the "unlock" command.
1902            As unlock is quite fast (it does not do anything), I put
1903            4096 ko/s = 4 Mo / s */
1904         /* FIXME: hwbuf speed */
1905         caps->dwUnlockTransferRate = 4096;
1906         caps->dwPlayCpuOverhead = 0;
1907
1908         return DS_OK;
1909 }
1910
1911 static HRESULT WINAPI IDirectSoundBufferImpl_QueryInterface(
1912         LPDIRECTSOUNDBUFFER iface,REFIID riid,LPVOID *ppobj
1913 ) {
1914         ICOM_THIS(IDirectSoundBufferImpl,iface);
1915
1916         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
1917
1918         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
1919                 IDirectSoundNotifyImpl  *dsn;
1920
1921                 dsn = (IDirectSoundNotifyImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(*dsn));
1922                 dsn->ref = 1;
1923                 dsn->dsb = This;
1924                 IDirectSoundBuffer_AddRef(iface);
1925                 ICOM_VTBL(dsn) = &dsnvt;
1926                 *ppobj = (LPVOID)dsn;
1927                 return S_OK;
1928         }
1929
1930 #ifdef USE_DSOUND3D
1931         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1932                 IDirectSound3DBufferImpl        *ds3db;
1933
1934                 *ppobj = This->ds3db;
1935                 if (*ppobj) {
1936                         IDirectSound3DBuffer_AddRef((LPDIRECTSOUND3DBUFFER)This->ds3db);
1937                         return S_OK;
1938                 }
1939
1940                 ds3db = (IDirectSound3DBufferImpl*)HeapAlloc(GetProcessHeap(),
1941                         0,sizeof(*ds3db));
1942                 ds3db->ref = 1;
1943                 ds3db->dsb = This;
1944                 ICOM_VTBL(ds3db) = &ds3dbvt;
1945                 InitializeCriticalSection(&ds3db->lock);
1946
1947                 IDirectSoundBuffer_AddRef(iface);
1948
1949                 ds3db->ds3db.dwSize = sizeof(DS3DBUFFER);
1950                 ds3db->ds3db.vPosition.u1.x = 0.0;
1951                 ds3db->ds3db.vPosition.u2.y = 0.0;
1952                 ds3db->ds3db.vPosition.u3.z = 0.0;
1953                 ds3db->ds3db.vVelocity.u1.x = 0.0;
1954                 ds3db->ds3db.vVelocity.u2.y = 0.0;
1955                 ds3db->ds3db.vVelocity.u3.z = 0.0;
1956                 ds3db->ds3db.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
1957                 ds3db->ds3db.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
1958                 ds3db->ds3db.vConeOrientation.u1.x = 0.0;
1959                 ds3db->ds3db.vConeOrientation.u2.y = 0.0;
1960                 ds3db->ds3db.vConeOrientation.u3.z = 0.0;
1961                 ds3db->ds3db.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;                ds3db->ds3db.flMinDistance = DS3D_DEFAULTMINDISTANCE;
1962                 ds3db->ds3db.flMaxDistance = DS3D_DEFAULTMAXDISTANCE;
1963                 ds3db->ds3db.dwMode = DS3DMODE_NORMAL;
1964                 ds3db->buflen = (This->buflen * primarybuf->wfx.nBlockAlign) /
1965                         This->wfx.nBlockAlign;
1966                 ds3db->buffer = HeapAlloc(GetProcessHeap(), 0, ds3db->buflen);
1967                 if (ds3db->buffer == NULL) {
1968                         ds3db->buflen = 0;
1969                         ds3db->ds3db.dwMode = DS3DMODE_DISABLE;
1970                 }
1971
1972                 ds3db->iks = (IKsPropertySetImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(*(ds3db->iks)));
1973                 ds3db->iks->ref = 1;
1974                 ds3db->iks->ds3db = ds3db;
1975                 ICOM_VTBL(ds3db->iks) = &iksvt;
1976
1977                 return S_OK;
1978         }
1979 #else
1980         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1981                 FIXME("%s: I know about this GUID, but don't support it yet\n",
1982                       debugstr_guid( riid ));
1983                 *ppobj = NULL;
1984                 return E_FAIL;
1985         }
1986 #endif
1987
1988 #if USE_DSOUND3D
1989         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1990                 IDirectSound3DListenerImpl* dsl;
1991
1992                 if (This->dsound->listener) {
1993                         *ppobj = This->dsound->listener;
1994                         IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)This->dsound->listener);
1995                         return DS_OK;
1996                 }
1997
1998                 dsl = (IDirectSound3DListenerImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(*dsl));
1999                 dsl->ref = 1;
2000                 ICOM_VTBL(dsl) = &ds3dlvt;
2001                 *ppobj = (LPVOID)dsl;
2002
2003                 dsl->ds3dl.dwSize = sizeof(DS3DLISTENER);
2004                 dsl->ds3dl.vPosition.u1.x = 0.0;
2005                 dsl->ds3dl.vPosition.u2.y = 0.0;
2006                 dsl->ds3dl.vPosition.u3.z = 0.0;
2007                 dsl->ds3dl.vVelocity.u1.x = 0.0;
2008                 dsl->ds3dl.vVelocity.u2.y = 0.0;
2009                 dsl->ds3dl.vVelocity.u3.z = 0.0;
2010                 dsl->ds3dl.vOrientFront.u1.x = 0.0;
2011                 dsl->ds3dl.vOrientFront.u2.y = 0.0;
2012                 dsl->ds3dl.vOrientFront.u3.z = 1.0;
2013                 dsl->ds3dl.vOrientTop.u1.x = 0.0;
2014                 dsl->ds3dl.vOrientTop.u2.y = 1.0;
2015                 dsl->ds3dl.vOrientTop.u3.z = 0.0;
2016                 dsl->ds3dl.flDistanceFactor = DS3D_DEFAULTDISTANCEFACTOR;
2017                 dsl->ds3dl.flRolloffFactor = DS3D_DEFAULTROLLOFFFACTOR;
2018
2019                 InitializeCriticalSection(&dsl->lock);
2020
2021                 dsl->dsb = This;
2022                 IDirectSoundBuffer_AddRef(iface);
2023
2024                 This->dsound->listener = dsl;
2025                 IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)dsl);
2026
2027                 return S_OK;
2028         }
2029 #else
2030         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
2031                 FIXME("%s: I know about this GUID, but don't support it yet\n",
2032                       debugstr_guid( riid ));
2033                 *ppobj = NULL;
2034                 return E_FAIL;
2035         }
2036 #endif
2037
2038         FIXME( "Unknown GUID %s\n", debugstr_guid( riid ) );
2039
2040         *ppobj = NULL;
2041
2042         return E_FAIL;
2043 }
2044
2045 static ICOM_VTABLE(IDirectSoundBuffer) dsbvt = 
2046 {
2047         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2048         IDirectSoundBufferImpl_QueryInterface,
2049         IDirectSoundBufferImpl_AddRef,
2050         IDirectSoundBufferImpl_Release,
2051         IDirectSoundBufferImpl_GetCaps,
2052         IDirectSoundBufferImpl_GetCurrentPosition,
2053         IDirectSoundBufferImpl_GetFormat,
2054         IDirectSoundBufferImpl_GetVolume,
2055         IDirectSoundBufferImpl_GetPan,
2056         IDirectSoundBufferImpl_GetFrequency,
2057         IDirectSoundBufferImpl_GetStatus,
2058         IDirectSoundBufferImpl_Initialize,
2059         IDirectSoundBufferImpl_Lock,
2060         IDirectSoundBufferImpl_Play,
2061         IDirectSoundBufferImpl_SetCurrentPosition,
2062         IDirectSoundBufferImpl_SetFormat,
2063         IDirectSoundBufferImpl_SetVolume,
2064         IDirectSoundBufferImpl_SetPan,
2065         IDirectSoundBufferImpl_SetFrequency,
2066         IDirectSoundBufferImpl_Stop,
2067         IDirectSoundBufferImpl_Unlock,
2068         IDirectSoundBufferImpl_Restore
2069 };
2070
2071 /*******************************************************************************
2072  *              IDirectSound
2073  */
2074
2075 static HRESULT WINAPI IDirectSoundImpl_SetCooperativeLevel(
2076         LPDIRECTSOUND iface,HWND hwnd,DWORD level
2077 ) {
2078         ICOM_THIS(IDirectSoundImpl,iface);
2079
2080         FIXME("(%p,%08lx,%ld):stub\n",This,(DWORD)hwnd,level);
2081
2082         This->priolevel = level;
2083
2084         return DS_OK;
2085 }
2086
2087 static HRESULT WINAPI IDirectSoundImpl_CreateSoundBuffer(
2088         LPDIRECTSOUND iface,LPDSBUFFERDESC dsbd,LPLPDIRECTSOUNDBUFFER ppdsb,LPUNKNOWN lpunk
2089 ) {
2090         ICOM_THIS(IDirectSoundImpl,iface);
2091         IDirectSoundBufferImpl** ippdsb=(IDirectSoundBufferImpl**)ppdsb;
2092         LPWAVEFORMATEX  wfex;
2093         HRESULT err = DS_OK;
2094
2095         TRACE("(%p,%p,%p,%p)\n",This,dsbd,ippdsb,lpunk);
2096         
2097         if ((This == NULL) || (dsbd == NULL) || (ippdsb == NULL))
2098                 return DSERR_INVALIDPARAM;
2099         
2100         if (TRACE_ON(dsound)) {
2101                 TRACE("(structsize=%ld)\n",dsbd->dwSize);
2102                 TRACE("(flags=0x%08lx:\n",dsbd->dwFlags);
2103                 _dump_DSBCAPS(dsbd->dwFlags);
2104                 DPRINTF(")\n");
2105                 TRACE("(bufferbytes=%ld)\n",dsbd->dwBufferBytes);
2106                 TRACE("(lpwfxFormat=%p)\n",dsbd->lpwfxFormat);
2107         }
2108
2109         wfex = dsbd->lpwfxFormat;
2110
2111         if (wfex)
2112                 TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
2113                    "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
2114                    wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
2115                    wfex->nAvgBytesPerSec, wfex->nBlockAlign, 
2116                    wfex->wBitsPerSample, wfex->cbSize);
2117
2118         if (dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER) {
2119                 if (primarybuf) {
2120                         IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)primarybuf);
2121                         *ippdsb = primarybuf;
2122                         primarybuf->dsbd.dwFlags = dsbd->dwFlags;
2123                         return DS_OK;
2124                 } /* Else create primary buffer */
2125         } else {
2126                 if (dsbd->dwBufferBytes < DSBSIZE_MIN || dsbd->dwBufferBytes > DSBSIZE_MAX) {
2127                         ERR("invalid sound buffer size %ld\n", dsbd->dwBufferBytes);
2128                         return DSERR_INVALIDPARAM; /* FIXME: which error? */
2129                 }
2130         }
2131
2132         *ippdsb = (IDirectSoundBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundBufferImpl));
2133         if (*ippdsb == NULL)
2134                 return DSERR_OUTOFMEMORY;
2135         ICOM_VTBL(*ippdsb) = &dsbvt;
2136         (*ippdsb)->ref = 1;
2137         (*ippdsb)->dsound = This;
2138         (*ippdsb)->parent = NULL;
2139         (*ippdsb)->buffer = NULL;
2140
2141         memcpy(&((*ippdsb)->dsbd),dsbd,sizeof(*dsbd));
2142         if (dsbd->lpwfxFormat)
2143                 memcpy(&((*ippdsb)->wfx), dsbd->lpwfxFormat, sizeof((*ippdsb)->wfx));
2144
2145         TRACE("Created buffer at %p\n", *ippdsb);
2146
2147         if (dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER) {
2148                 (*ippdsb)->buflen = dsound->wfx.nAvgBytesPerSec;
2149                 (*ippdsb)->freq = dsound->wfx.nSamplesPerSec;
2150
2151                 /* FIXME: verify that hardware capabilities (DSCAPS_PRIMARY flags) match */
2152
2153                 if (This->driver) {
2154                         err = IDsDriver_CreateSoundBuffer(This->driver,wfex,dsbd->dwFlags,0,
2155                                                           &((*ippdsb)->buflen),&((*ippdsb)->buffer),
2156                                                           (LPVOID*)&((*ippdsb)->hwbuf));
2157                 }
2158                 if (err == DS_OK)
2159                         err = DSOUND_PrimaryOpen(*ippdsb);
2160         } else {
2161                 DWORD capf = 0;
2162                 int use_hw;
2163
2164                 (*ippdsb)->buflen = dsbd->dwBufferBytes;
2165                 (*ippdsb)->freq = dsbd->lpwfxFormat->nSamplesPerSec;
2166
2167                 /* Check necessary hardware mixing capabilities */
2168                 if (wfex->nChannels==2) capf |= DSCAPS_SECONDARYSTEREO;
2169                 else capf |= DSCAPS_SECONDARYMONO;
2170                 if (wfex->wBitsPerSample==16) capf |= DSCAPS_SECONDARY16BIT;
2171                 else capf |= DSCAPS_SECONDARY8BIT;
2172                 use_hw = (This->drvcaps.dwFlags & capf) == capf;
2173
2174                 /* FIXME: check hardware sample rate mixing capabilities */
2175                 /* FIXME: check app hints for software/hardware buffer (STATIC, LOCHARDWARE, etc) */
2176                 /* FIXME: check whether any hardware buffers are left */
2177                 /* FIXME: handle DSDHEAP_CREATEHEAP for hardware buffers */
2178
2179                 /* Allocate system memory if applicable */
2180                 if ((This->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) || !use_hw) {
2181                         (*ippdsb)->buffer = (LPBYTE)HeapAlloc(GetProcessHeap(),0,(*ippdsb)->buflen);
2182                         if ((*ippdsb)->buffer == NULL)
2183                                 err = DSERR_OUTOFMEMORY;
2184                 }
2185
2186                 /* Allocate the hardware buffer */
2187                 if (use_hw && (err == DS_OK)) {
2188                         err = IDsDriver_CreateSoundBuffer(This->driver,wfex,dsbd->dwFlags,0,
2189                                                           &((*ippdsb)->buflen),&((*ippdsb)->buffer),
2190                                                           (LPVOID*)&((*ippdsb)->hwbuf));
2191                 }
2192         }
2193
2194         if (err != DS_OK) {
2195                 if ((*ippdsb)->buffer)
2196                         HeapFree(GetProcessHeap(),0,(*ippdsb)->buffer);
2197                 HeapFree(GetProcessHeap(),0,(*ippdsb));
2198                 *ippdsb = NULL;
2199                 return err;
2200         }
2201         /* calculate fragment size and write lead */
2202         DSOUND_RecalcFormat(*ippdsb);
2203
2204         /* It's not necessary to initialize values to zero since */
2205         /* we allocated this structure with HEAP_ZERO_MEMORY... */
2206         (*ippdsb)->playpos = 0;
2207         (*ippdsb)->buf_mixpos = 0;
2208         (*ippdsb)->state = STATE_STOPPED;
2209         DSOUND_RecalcVolPan(&((*ippdsb)->volpan));
2210
2211         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
2212                 (*ippdsb)->freqAdjust = ((*ippdsb)->freq << DSOUND_FREQSHIFT) /
2213                         primarybuf->wfx.nSamplesPerSec;
2214                 (*ippdsb)->nAvgBytesPerSec = (*ippdsb)->freq *
2215                         dsbd->lpwfxFormat->nBlockAlign;
2216         }
2217
2218         EnterCriticalSection(&(This->lock));
2219         /* register buffer */
2220         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
2221                 IDirectSoundBufferImpl **newbuffers = (IDirectSoundBufferImpl**)HeapReAlloc(GetProcessHeap(),0,This->buffers,sizeof(IDirectSoundBufferImpl*)*(This->nrofbuffers+1));
2222                 if (newbuffers) {
2223                         This->buffers = newbuffers;
2224                         This->buffers[This->nrofbuffers] = *ippdsb;
2225                         This->nrofbuffers++;
2226                         TRACE("buffer count is now %d\n", This->nrofbuffers);
2227                 } else {
2228                         ERR("out of memory for buffer list! Current buffer count is %d\n", This->nrofbuffers);
2229                         err = DSERR_OUTOFMEMORY;
2230                 }
2231         }
2232         LeaveCriticalSection(&(This->lock));
2233
2234         IDirectSound_AddRef(iface);
2235
2236         InitializeCriticalSection(&((*ippdsb)->lock));
2237
2238         if (err != DS_OK) {
2239                 /* oops... */
2240                 IDirectSoundBuffer_Release(*ppdsb);
2241                 *ippdsb = NULL;
2242                 return err;
2243         }
2244         
2245 #ifdef USE_DSOUND3D
2246         if (dsbd->dwFlags & DSBCAPS_CTRL3D) {
2247                 IDirectSound3DBufferImpl        *ds3db;
2248
2249                 ds3db = (IDirectSound3DBufferImpl*)HeapAlloc(GetProcessHeap(),
2250                         0,sizeof(*ds3db));
2251                 ICOM_VTBL(ds3db) = &ds3dbvt;
2252                 ds3db->ref = 1;
2253                 (*ippdsb)->ds3db = ds3db;
2254
2255                 ds3db->dsb = (*ippdsb);
2256                 IDirectSoundBufferImpl_AddRef((LPDIRECTSOUNDBUFFER)(*ippdsb));
2257
2258                 InitializeCriticalSection(&ds3db->lock);
2259
2260                 ds3db->ds3db.dwSize = sizeof(DS3DBUFFER);
2261                 ds3db->ds3db.vPosition.u1.x = 0.0;
2262                 ds3db->ds3db.vPosition.u2.y = 0.0;
2263                 ds3db->ds3db.vPosition.u3.z = 0.0;
2264                 ds3db->ds3db.vVelocity.u1.x = 0.0;
2265                 ds3db->ds3db.vVelocity.u2.y = 0.0;
2266                 ds3db->ds3db.vVelocity.u3.z = 0.0;
2267                 ds3db->ds3db.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
2268                 ds3db->ds3db.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
2269                 ds3db->ds3db.vConeOrientation.u1.x = 0.0;
2270                 ds3db->ds3db.vConeOrientation.u2.y = 0.0;
2271                 ds3db->ds3db.vConeOrientation.u3.z = 0.0;
2272                 ds3db->ds3db.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;
2273                 ds3db->ds3db.flMinDistance = DS3D_DEFAULTMINDISTANCE;
2274                 ds3db->ds3db.flMaxDistance = DS3D_DEFAULTMAXDISTANCE;
2275                 ds3db->ds3db.dwMode = DS3DMODE_NORMAL;
2276                 ds3db->buflen = ((*ippdsb)->buflen * primarybuf->wfx.nBlockAlign) /
2277                         (*ippdsb)->wfx.nBlockAlign;
2278                 ds3db->buffer = HeapAlloc(GetProcessHeap(), 0, ds3db->buflen);
2279                 if (ds3db->buffer == NULL) {
2280                         ds3db->buflen = 0;
2281                         ds3db->ds3db.dwMode = DS3DMODE_DISABLE;
2282                 }
2283                 ds3db->iks = (IKsPropertySetImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(*(ds3db->iks)));
2284                 ds3db->iks->ref = 1;
2285                 ds3db->iks->ds3db = ds3db;
2286                 ICOM_VTBL(ds3db->iks) = &iksvt;
2287
2288         }
2289 #endif
2290         return DS_OK;
2291 }
2292
2293 static HRESULT WINAPI IDirectSoundImpl_DuplicateSoundBuffer(
2294         LPDIRECTSOUND iface,LPDIRECTSOUNDBUFFER pdsb,LPLPDIRECTSOUNDBUFFER ppdsb
2295 ) {
2296         ICOM_THIS(IDirectSoundImpl,iface);
2297         IDirectSoundBufferImpl* ipdsb=(IDirectSoundBufferImpl*)pdsb;
2298         IDirectSoundBufferImpl** ippdsb=(IDirectSoundBufferImpl**)ppdsb;
2299         TRACE("(%p,%p,%p)\n",This,ipdsb,ippdsb);
2300
2301         if (ipdsb->hwbuf) {
2302                 FIXME("need to duplicate hardware buffer\n");
2303         }
2304
2305         *ippdsb = (IDirectSoundBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDirectSoundBufferImpl));
2306
2307         IDirectSoundBuffer_AddRef(pdsb);
2308         memcpy(*ippdsb, ipdsb, sizeof(IDirectSoundBufferImpl));
2309         (*ippdsb)->ref = 1;
2310         (*ippdsb)->state = STATE_STOPPED;
2311         (*ippdsb)->playpos = 0;
2312         (*ippdsb)->buf_mixpos = 0;
2313         (*ippdsb)->dsound = This;
2314         (*ippdsb)->parent = ipdsb;
2315         memcpy(&((*ippdsb)->wfx), &(ipdsb->wfx), sizeof((*ippdsb)->wfx));
2316         InitializeCriticalSection(&(*ippdsb)->lock);
2317         /* register buffer */
2318         EnterCriticalSection(&(This->lock));
2319         {
2320                 IDirectSoundBufferImpl **newbuffers = (IDirectSoundBufferImpl**)HeapReAlloc(GetProcessHeap(),0,This->buffers,sizeof(IDirectSoundBufferImpl**)*(This->nrofbuffers+1));
2321                 if (newbuffers) {
2322                         This->buffers = newbuffers;
2323                         This->buffers[This->nrofbuffers] = *ippdsb;
2324                         This->nrofbuffers++;
2325                         TRACE("buffer count is now %d\n", This->nrofbuffers);
2326                 } else {
2327                         ERR("out of memory for buffer list! Current buffer count is %d\n", This->nrofbuffers);
2328                         /* FIXME: release buffer */
2329                 }
2330         }
2331         LeaveCriticalSection(&(This->lock));
2332         IDirectSound_AddRef(iface);
2333         return DS_OK;
2334 }
2335
2336
2337 static HRESULT WINAPI IDirectSoundImpl_GetCaps(LPDIRECTSOUND iface,LPDSCAPS caps) {
2338         ICOM_THIS(IDirectSoundImpl,iface);
2339         TRACE("(%p,%p)\n",This,caps);
2340         TRACE("(flags=0x%08lx)\n",caps->dwFlags);
2341
2342         if (caps == NULL)
2343                 return DSERR_INVALIDPARAM;
2344
2345         /* We should check this value, not set it. See Inside DirectX, p215. */
2346         caps->dwSize = sizeof(*caps);
2347
2348         caps->dwFlags = This->drvcaps.dwFlags;
2349
2350         /* FIXME: copy caps from This->drvcaps */
2351         caps->dwMinSecondarySampleRate          = DSBFREQUENCY_MIN;
2352         caps->dwMaxSecondarySampleRate          = DSBFREQUENCY_MAX;
2353
2354         caps->dwPrimaryBuffers                  = 1;
2355
2356         caps->dwMaxHwMixingAllBuffers           = 0;
2357         caps->dwMaxHwMixingStaticBuffers        = 0;
2358         caps->dwMaxHwMixingStreamingBuffers     = 0;
2359
2360         caps->dwFreeHwMixingAllBuffers          = 0;
2361         caps->dwFreeHwMixingStaticBuffers       = 0;
2362         caps->dwFreeHwMixingStreamingBuffers    = 0;
2363
2364         caps->dwMaxHw3DAllBuffers               = 0;
2365         caps->dwMaxHw3DStaticBuffers            = 0;
2366         caps->dwMaxHw3DStreamingBuffers         = 0;
2367
2368         caps->dwFreeHw3DAllBuffers              = 0;
2369         caps->dwFreeHw3DStaticBuffers           = 0;
2370         caps->dwFreeHw3DStreamingBuffers        = 0;
2371
2372         caps->dwTotalHwMemBytes                 = 0;
2373
2374         caps->dwFreeHwMemBytes                  = 0;
2375
2376         caps->dwMaxContigFreeHwMemBytes         = 0;
2377
2378         caps->dwUnlockTransferRateHwBuffers     = 4096; /* But we have none... */
2379
2380         caps->dwPlayCpuOverheadSwBuffers        = 1;    /* 1% */
2381
2382         return DS_OK;
2383 }
2384
2385 static ULONG WINAPI IDirectSoundImpl_AddRef(LPDIRECTSOUND iface) {
2386         ICOM_THIS(IDirectSoundImpl,iface);
2387         return ++(This->ref);
2388 }
2389
2390 static ULONG WINAPI IDirectSoundImpl_Release(LPDIRECTSOUND iface) {
2391         ICOM_THIS(IDirectSoundImpl,iface);
2392         TRACE("(%p), ref was %ld\n",This,This->ref);
2393         if (!--(This->ref)) {
2394                 UINT i;
2395
2396                 timeKillEvent(This->timerID);
2397                 timeEndPeriod(DS_TIME_RES);
2398
2399                 if (primarybuf)
2400                         IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)primarybuf);
2401
2402                 if (This->buffers) {
2403                         for( i=0;i<This->nrofbuffers;i++)       
2404                                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->buffers[i]);
2405                 }
2406
2407                 if (This->primary)
2408                         IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->primary);
2409
2410                 DeleteCriticalSection(&This->lock);
2411                 if (This->driver) {
2412                         IDsDriver_Close(This->driver);
2413                 } else {
2414                         unsigned c;
2415                         for (c=0; c<DS_HEL_FRAGS; c++)
2416                                 HeapFree(GetProcessHeap(),0,This->pwave[c]);
2417                 }
2418                 if (This->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN) {
2419                         waveOutClose(This->hwo);
2420                 }
2421                 if (This->driver)
2422                         IDsDriver_Release(This->driver);
2423
2424                 HeapFree(GetProcessHeap(),0,This);
2425                 dsound = NULL;
2426                 return 0;
2427         }
2428         return This->ref;
2429 }
2430
2431 static HRESULT WINAPI IDirectSoundImpl_SetSpeakerConfig(
2432         LPDIRECTSOUND iface,DWORD config
2433 ) {
2434         ICOM_THIS(IDirectSoundImpl,iface);
2435         FIXME("(%p,0x%08lx):stub\n",This,config);
2436         return DS_OK;
2437 }
2438
2439 static HRESULT WINAPI IDirectSoundImpl_QueryInterface(
2440         LPDIRECTSOUND iface,REFIID riid,LPVOID *ppobj
2441 ) {
2442         ICOM_THIS(IDirectSoundImpl,iface);
2443
2444         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
2445
2446                 if (This->listener) {
2447                         *ppobj = This->listener;
2448                         IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)This->listener);
2449                         return DS_OK;
2450                 }
2451
2452                 This->listener = (IDirectSound3DListenerImpl*)HeapAlloc(
2453                         GetProcessHeap(), 0, sizeof(*(This->listener)));
2454                 This->listener->ref = 1;
2455                 ICOM_VTBL(This->listener) = &ds3dlvt;
2456                 *ppobj = (LPVOID)This->listener;
2457                 IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)*ppobj); 
2458
2459                 This->listener->dsb = NULL; 
2460
2461                 This->listener->ds3dl.dwSize = sizeof(DS3DLISTENER);
2462                 This->listener->ds3dl.vPosition.u1.x = 0.0;
2463                 This->listener->ds3dl.vPosition.u2.y = 0.0;
2464                 This->listener->ds3dl.vPosition.u3.z = 0.0;
2465                 This->listener->ds3dl.vVelocity.u1.x = 0.0;
2466                 This->listener->ds3dl.vVelocity.u2.y = 0.0;
2467                 This->listener->ds3dl.vVelocity.u3.z = 0.0;
2468                 This->listener->ds3dl.vOrientFront.u1.x = 0.0;
2469                 This->listener->ds3dl.vOrientFront.u2.y = 0.0;
2470                 This->listener->ds3dl.vOrientFront.u3.z = 1.0;
2471                 This->listener->ds3dl.vOrientTop.u1.x = 0.0;
2472                 This->listener->ds3dl.vOrientTop.u2.y = 1.0;
2473                 This->listener->ds3dl.vOrientTop.u3.z = 0.0;
2474                 This->listener->ds3dl.flDistanceFactor = DS3D_DEFAULTDISTANCEFACTOR;
2475                 This->listener->ds3dl.flRolloffFactor = DS3D_DEFAULTROLLOFFFACTOR;
2476                 This->listener->ds3dl.flDopplerFactor = DS3D_DEFAULTDOPPLERFACTOR;
2477
2478                 InitializeCriticalSection(&This->listener->lock);
2479
2480                 return DS_OK;
2481         }
2482
2483         FIXME("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
2484         return E_FAIL;
2485 }
2486
2487 static HRESULT WINAPI IDirectSoundImpl_Compact(
2488         LPDIRECTSOUND iface)
2489 {
2490         ICOM_THIS(IDirectSoundImpl,iface);
2491         TRACE("(%p)\n", This);
2492         return DS_OK;
2493 }
2494
2495 static HRESULT WINAPI IDirectSoundImpl_GetSpeakerConfig(
2496         LPDIRECTSOUND iface,
2497         LPDWORD lpdwSpeakerConfig)
2498 {
2499         ICOM_THIS(IDirectSoundImpl,iface);
2500         TRACE("(%p, %p)\n", This, lpdwSpeakerConfig);
2501         *lpdwSpeakerConfig = DSSPEAKER_STEREO | (DSSPEAKER_GEOMETRY_NARROW << 16);
2502         return DS_OK;
2503 }
2504
2505 static HRESULT WINAPI IDirectSoundImpl_Initialize(
2506         LPDIRECTSOUND iface,
2507         LPCGUID lpcGuid)
2508 {
2509         ICOM_THIS(IDirectSoundImpl,iface);
2510         TRACE("(%p, %p)\n", This, lpcGuid);
2511         return DS_OK;
2512 }
2513
2514 static ICOM_VTABLE(IDirectSound) dsvt = 
2515 {
2516         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
2517         IDirectSoundImpl_QueryInterface,
2518         IDirectSoundImpl_AddRef,
2519         IDirectSoundImpl_Release,
2520         IDirectSoundImpl_CreateSoundBuffer,
2521         IDirectSoundImpl_GetCaps,
2522         IDirectSoundImpl_DuplicateSoundBuffer,
2523         IDirectSoundImpl_SetCooperativeLevel,
2524         IDirectSoundImpl_Compact,
2525         IDirectSoundImpl_GetSpeakerConfig,
2526         IDirectSoundImpl_SetSpeakerConfig,
2527         IDirectSoundImpl_Initialize
2528 };
2529
2530
2531 static void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
2532 {
2533         int                     i;
2534         DWORD                   offset;
2535         LPDSBPOSITIONNOTIFY     event;
2536
2537         if (dsb->nrofnotifies == 0)
2538                 return;
2539
2540         TRACE("(%p) buflen = %ld, playpos = %ld, len = %d\n",
2541                 dsb, dsb->buflen, dsb->playpos, len);
2542         for (i = 0; i < dsb->nrofnotifies ; i++) {
2543                 event = dsb->notifies + i;
2544                 offset = event->dwOffset;
2545                 TRACE("checking %d, position %ld, event = %d\n",
2546                         i, offset, event->hEventNotify);
2547                 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
2548                 /* OK. [Inside DirectX, p274] */
2549                 /*  */
2550                 /* This also means we can't sort the entries by offset, */
2551                 /* because DSBPN_OFFSETSTOP == -1 */
2552                 if (offset == DSBPN_OFFSETSTOP) {
2553                         if (dsb->state == STATE_STOPPED) {
2554                                 SetEvent(event->hEventNotify);
2555                                 TRACE("signalled event %d (%d)\n", event->hEventNotify, i);
2556                                 return;
2557                         } else
2558                                 return;
2559                 }
2560                 if ((dsb->playpos + len) >= dsb->buflen) {
2561                         if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
2562                             (offset >= dsb->playpos)) {
2563                                 TRACE("signalled event %d (%d)\n", event->hEventNotify, i);
2564                                 SetEvent(event->hEventNotify);
2565                         }
2566                 } else {
2567                         if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
2568                                 TRACE("signalled event %d (%d)\n", event->hEventNotify, i);
2569                                 SetEvent(event->hEventNotify);
2570                         }
2571                 }
2572         }
2573 }
2574
2575 /* WAV format info can be found at: */
2576 /* */
2577 /*      http://www.cwi.nl/ftp/audio/AudioFormats.part2 */
2578 /*      ftp://ftp.cwi.nl/pub/audio/RIFF-format */
2579 /* */
2580 /* Import points to remember: */
2581 /* */
2582 /*      8-bit WAV is unsigned */
2583 /*      16-bit WAV is signed */
2584
2585 static inline INT16 cvtU8toS16(BYTE byte)
2586 {
2587         INT16   s = (byte - 128) << 8;
2588
2589         return s;
2590 }
2591
2592 static inline BYTE cvtS16toU8(INT16 word)
2593 {
2594         BYTE    b = (word + 32768) >> 8;
2595         
2596         return b;
2597 }
2598
2599
2600 /* We should be able to optimize these two inline functions */
2601 /* so that we aren't doing 8->16->8 conversions when it is */
2602 /* not necessary. But this is still a WIP. Optimize later. */
2603 static inline void get_fields(const IDirectSoundBufferImpl *dsb, BYTE *buf, INT *fl, INT *fr)
2604 {
2605         INT16   *bufs = (INT16 *) buf;
2606
2607         /* TRACE("(%p)\n", buf); */
2608         if ((dsb->wfx.wBitsPerSample == 8) && dsb->wfx.nChannels == 2) {
2609                 *fl = cvtU8toS16(*buf);
2610                 *fr = cvtU8toS16(*(buf + 1));
2611                 return;
2612         }
2613
2614         if ((dsb->wfx.wBitsPerSample == 16) && dsb->wfx.nChannels == 2) {
2615                 *fl = *bufs;
2616                 *fr = *(bufs + 1);
2617                 return;
2618         }
2619
2620         if ((dsb->wfx.wBitsPerSample == 8) && dsb->wfx.nChannels == 1) {
2621                 *fl = cvtU8toS16(*buf);
2622                 *fr = *fl;
2623                 return;
2624         }
2625
2626         if ((dsb->wfx.wBitsPerSample == 16) && dsb->wfx.nChannels == 1) {
2627                 *fl = *bufs;
2628                 *fr = *bufs;
2629                 return;
2630         }
2631
2632         FIXME("get_fields found an unsupported configuration\n");
2633         return;
2634 }
2635
2636 static inline void set_fields(BYTE *buf, INT fl, INT fr)
2637 {
2638         INT16 *bufs = (INT16 *) buf;
2639
2640         if ((primarybuf->wfx.wBitsPerSample == 8) && (primarybuf->wfx.nChannels == 2)) {
2641                 *buf = cvtS16toU8(fl);
2642                 *(buf + 1) = cvtS16toU8(fr);
2643                 return;
2644         }
2645
2646         if ((primarybuf->wfx.wBitsPerSample == 16) && (primarybuf->wfx.nChannels == 2)) {
2647                 *bufs = fl;
2648                 *(bufs + 1) = fr;
2649                 return;
2650         }
2651
2652         if ((primarybuf->wfx.wBitsPerSample == 8) && (primarybuf->wfx.nChannels == 1)) {
2653                 *buf = cvtS16toU8((fl + fr) >> 1);
2654                 return;
2655         }
2656
2657         if ((primarybuf->wfx.wBitsPerSample == 16) && (primarybuf->wfx.nChannels == 1)) {
2658                 *bufs = (fl + fr) >> 1;
2659                 return;
2660         }
2661         FIXME("set_fields found an unsupported configuration\n");
2662         return;
2663 }
2664
2665 /* Now with PerfectPitch (tm) technology */
2666 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
2667 {
2668         INT     i, size, ipos, ilen, fieldL, fieldR;
2669         BYTE    *ibp, *obp;
2670         INT     iAdvance = dsb->wfx.nBlockAlign;
2671         INT     oAdvance = primarybuf->wfx.nBlockAlign;
2672
2673         ibp = dsb->buffer + dsb->buf_mixpos;
2674         obp = buf;
2675
2676         TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
2677         /* Check for the best case */
2678         if ((dsb->freq == primarybuf->wfx.nSamplesPerSec) &&
2679             (dsb->wfx.wBitsPerSample == primarybuf->wfx.wBitsPerSample) &&
2680             (dsb->wfx.nChannels == primarybuf->wfx.nChannels)) {
2681                 DWORD bytesleft = dsb->buflen - dsb->buf_mixpos;
2682                 TRACE("(%p) Best case\n", dsb);
2683                 if (len <= bytesleft )
2684                         memcpy(obp, ibp, len);
2685                 else { /* wrap */
2686                         memcpy(obp, ibp, bytesleft );
2687                         memcpy(obp + bytesleft, dsb->buffer, len - bytesleft);
2688                 }
2689                 return len;
2690         }
2691         
2692         /* Check for same sample rate */
2693         if (dsb->freq == primarybuf->wfx.nSamplesPerSec) {
2694                 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
2695                         dsb->freq, primarybuf->wfx.nSamplesPerSec);
2696                 ilen = 0;
2697                 for (i = 0; i < len; i += oAdvance) {
2698                         get_fields(dsb, ibp, &fieldL, &fieldR);
2699                         ibp += iAdvance;
2700                         ilen += iAdvance;
2701                         set_fields(obp, fieldL, fieldR);
2702                         obp += oAdvance;
2703                         if (ibp >= (BYTE *)(dsb->buffer + dsb->buflen))
2704                                 ibp = dsb->buffer;      /* wrap */
2705                 }
2706                 return (ilen);  
2707         }
2708
2709         /* Mix in different sample rates */
2710         /* */
2711         /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
2712         /* Patent Pending :-] */
2713
2714         /* Patent enhancements (c) 2000 Ove KÃ¥ven,
2715          * TransGaming Technologies Inc. */
2716
2717         FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
2718                 dsb, dsb->freq, primarybuf->wfx.nSamplesPerSec);
2719
2720         size = len / oAdvance;
2721         ilen = 0;
2722         ipos = dsb->buf_mixpos;
2723         for (i = 0; i < size; i++) {
2724                 get_fields(dsb, (dsb->buffer + ipos), &fieldL, &fieldR);
2725                 set_fields(obp, fieldL, fieldR);
2726                 obp += oAdvance;
2727
2728                 dsb->freqAcc += dsb->freqAdjust;
2729                 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
2730                         ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
2731                         dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
2732                         ipos += adv; ilen += adv;
2733                         while (ipos >= dsb->buflen)
2734                                 ipos -= dsb->buflen;
2735                 }
2736         }
2737         return ilen;
2738 }
2739
2740 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
2741 {
2742         INT     i, inc = primarybuf->wfx.wBitsPerSample >> 3;
2743         BYTE    *bpc = buf;
2744         INT16   *bps = (INT16 *) buf;
2745         
2746         TRACE("(%p) left = %lx, right = %lx\n", dsb,
2747                 dsb->volpan.dwTotalLeftAmpFactor, dsb->volpan.dwTotalRightAmpFactor);
2748         if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
2749             (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
2750             !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
2751                 return;         /* Nothing to do */
2752
2753         /* If we end up with some bozo coder using panning or 3D sound */
2754         /* with a mono primary buffer, it could sound very weird using */
2755         /* this method. Oh well, tough patooties. */
2756
2757         for (i = 0; i < len; i += inc) {
2758                 INT     val;
2759
2760                 switch (inc) {
2761
2762                 case 1:
2763                         /* 8-bit WAV is unsigned, but we need to operate */
2764                         /* on signed data for this to work properly */
2765                         val = *bpc - 128;
2766                         val = ((val * (i & inc ? dsb->volpan.dwTotalRightAmpFactor : dsb->volpan.dwTotalLeftAmpFactor)) >> 16);
2767                         *bpc = val + 128;
2768                         bpc++;
2769                         break;
2770                 case 2:
2771                         /* 16-bit WAV is signed -- much better */
2772                         val = *bps;
2773                         val = ((val * ((i & inc) ? dsb->volpan.dwTotalRightAmpFactor : dsb->volpan.dwTotalLeftAmpFactor)) >> 16);
2774                         *bps = val;
2775                         bps++;
2776                         break;
2777                 default:
2778                         /* Very ugly! */
2779                         FIXME("MixerVol had a nasty error\n");
2780                 }
2781         }               
2782 }
2783
2784 #ifdef USE_DSOUND3D
2785 static void DSOUND_Mixer3D(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
2786 {
2787         BYTE    *ibp, *obp;
2788         DWORD   buflen, buf_mixpos;
2789
2790         buflen = dsb->ds3db->buflen;
2791         buf_mixpos = (dsb->buf_mixpos * primarybuf->wfx.nBlockAlign) / dsb->wfx.nBlockAlign;
2792         ibp = dsb->ds3db->buffer + buf_mixpos;
2793         obp = buf;
2794
2795         if (buf_mixpos > buflen) {
2796                 FIXME("Major breakage\n");
2797                 return;
2798         }
2799
2800         if (len <= (buf_mixpos + buflen))
2801                 memcpy(obp, ibp, len);
2802         else { /* wrap */
2803                 memcpy(obp, ibp, buflen - buf_mixpos);
2804                 memcpy(obp + (buflen - buf_mixpos),
2805                     dsb->buffer,
2806                     len - (buflen - buf_mixpos));
2807         }
2808         return;
2809 }
2810 #endif
2811
2812 static void *tmp_buffer;
2813 static size_t tmp_buffer_len = 0;
2814
2815 static void *DSOUND_tmpbuffer(size_t len)
2816 {
2817   if (len>tmp_buffer_len) {
2818     void *new_buffer = realloc(tmp_buffer, len);
2819     if (new_buffer) {
2820       tmp_buffer = new_buffer;
2821       tmp_buffer_len = len;
2822     }
2823     return new_buffer;
2824   }
2825   return tmp_buffer;
2826 }
2827
2828 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
2829 {
2830         INT     i, len, ilen, temp, field;
2831         INT     advance = primarybuf->wfx.wBitsPerSample >> 3;
2832         BYTE    *buf, *ibuf, *obuf;
2833         INT16   *ibufs, *obufs;
2834
2835         len = fraglen;
2836         if (!(dsb->playflags & DSBPLAY_LOOPING)) {
2837                 temp = MulDiv(primarybuf->wfx.nAvgBytesPerSec, dsb->buflen,
2838                         dsb->nAvgBytesPerSec) -
2839                        MulDiv(primarybuf->wfx.nAvgBytesPerSec, dsb->buf_mixpos,
2840                         dsb->nAvgBytesPerSec);
2841                 len = (len > temp) ? temp : len;
2842         }
2843         len &= ~3;                              /* 4 byte alignment */
2844
2845         if (len == 0) {
2846                 /* This should only happen if we aren't looping and temp < 4 */
2847
2848                 /* We skip the remainder, so check for possible events */
2849                 DSOUND_CheckEvent(dsb, dsb->buflen - dsb->buf_mixpos);
2850                 /* Stop */
2851                 dsb->state = STATE_STOPPED;
2852                 dsb->playpos = 0;
2853                 dsb->buf_mixpos = 0;
2854                 dsb->leadin = FALSE;
2855                 /* Check for DSBPN_OFFSETSTOP */
2856                 DSOUND_CheckEvent(dsb, 0);
2857                 return 0;
2858         }
2859
2860         /* Been seeing segfaults in malloc() for some reason... */
2861         TRACE("allocating buffer (size = %d)\n", len);
2862         if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
2863                 return 0;
2864
2865         TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
2866
2867         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
2868         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
2869             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
2870                 DSOUND_MixerVol(dsb, ibuf, len);
2871
2872         obuf = primarybuf->buffer + writepos;
2873         for (i = 0; i < len; i += advance) {
2874                 obufs = (INT16 *) obuf;
2875                 ibufs = (INT16 *) ibuf;
2876                 if (primarybuf->wfx.wBitsPerSample == 8) {
2877                         /* 8-bit WAV is unsigned */
2878                         field = (*ibuf - 128);
2879                         field += (*obuf - 128);
2880                         field = field > 127 ? 127 : field;
2881                         field = field < -128 ? -128 : field;
2882                         *obuf = field + 128;
2883                 } else {
2884                         /* 16-bit WAV is signed */
2885                         field = *ibufs;
2886                         field += *obufs;
2887                         field = field > 32767 ? 32767 : field;
2888                         field = field < -32768 ? -32768 : field;
2889                         *obufs = field;
2890                 }
2891                 ibuf += advance;
2892                 obuf += advance;
2893                 if (obuf >= (BYTE *)(primarybuf->buffer + primarybuf->buflen))
2894                         obuf = primarybuf->buffer;
2895         }
2896         /* free(buf); */
2897
2898         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY)
2899                 DSOUND_CheckEvent(dsb, ilen);
2900
2901         if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
2902                 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
2903                  * not the MIX position... but if the sound buffer is bigger than our prebuffering
2904                  * (which must be the case for the streaming buffers that need this hack anyway)
2905                  * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
2906                 dsb->leadin = FALSE;
2907         }
2908
2909         dsb->buf_mixpos += ilen;
2910         
2911         if (dsb->buf_mixpos >= dsb->buflen) {
2912                 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
2913                         dsb->state = STATE_STOPPED;
2914                         dsb->playpos = 0;
2915                         dsb->buf_mixpos = 0;
2916                         dsb->leadin = FALSE;
2917                         DSOUND_CheckEvent(dsb, 0);              /* For DSBPN_OFFSETSTOP */
2918                 } else {
2919                         /* wrap */
2920                         while (dsb->buf_mixpos >= dsb->buflen)
2921                                 dsb->buf_mixpos -= dsb->buflen;
2922                         if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
2923                                 dsb->leadin = FALSE; /* HACK: see above */
2924                 }
2925         }
2926
2927         return len;
2928 }
2929
2930 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
2931 {
2932         INT     i, ilen, field;
2933         INT     advance = primarybuf->wfx.wBitsPerSample >> 3;
2934         BYTE    *buf, *ibuf, *obuf;
2935         INT16   *ibufs, *obufs;
2936
2937         len &= ~3;                              /* 4 byte alignment */
2938
2939         TRACE("allocating buffer (size = %ld)\n", len);
2940         if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
2941                 return;
2942
2943         TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
2944
2945         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
2946         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
2947             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
2948                 DSOUND_MixerVol(dsb, ibuf, len);
2949
2950         /* subtract instead of add, to phase out premixed data */
2951         obuf = primarybuf->buffer + writepos;
2952         for (i = 0; i < len; i += advance) {
2953                 obufs = (INT16 *) obuf;
2954                 ibufs = (INT16 *) ibuf;
2955                 if (primarybuf->wfx.wBitsPerSample == 8) {
2956                         /* 8-bit WAV is unsigned */
2957                         field = (*ibuf - 128);
2958                         field -= (*obuf - 128);
2959                         field = field > 127 ? 127 : field;
2960                         field = field < -128 ? -128 : field;
2961                         *obuf = field + 128;
2962                 } else {
2963                         /* 16-bit WAV is signed */
2964                         field = *ibufs;
2965                         field -= *obufs;
2966                         field = field > 32767 ? 32767 : field;
2967                         field = field < -32768 ? -32768 : field;
2968                         *obufs = field;
2969                 }
2970                 ibuf += advance;
2971                 obuf += advance;
2972                 if (obuf >= (BYTE *)(primarybuf->buffer + primarybuf->buflen))
2973                         obuf = primarybuf->buffer;
2974         }
2975         /* free(buf); */
2976 }
2977
2978 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
2979 {
2980         DWORD   size, flen, len, npos, nlen;
2981         INT     iAdvance = dsb->wfx.nBlockAlign;
2982         INT     oAdvance = primarybuf->wfx.nBlockAlign;
2983         /* determine amount of premixed data to cancel */
2984         DWORD primary_done =
2985                 ((dsb->primary_mixpos < writepos) ? primarybuf->buflen : 0) +
2986                 dsb->primary_mixpos - writepos;
2987
2988         TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
2989
2990         /* backtrack the mix position */
2991         size = primary_done / oAdvance;
2992         flen = size * dsb->freqAdjust;
2993         len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
2994         flen &= (1<<DSOUND_FREQSHIFT)-1;
2995         while (dsb->freqAcc < flen) {
2996                 len += iAdvance;
2997                 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
2998         }
2999         len %= dsb->buflen;
3000         npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
3001                 dsb->buf_mixpos - len;
3002         if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
3003                 /* stop backtracking at startpos */
3004                 npos = dsb->startpos;
3005                 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
3006                         dsb->buf_mixpos - npos;
3007                 flen = dsb->freqAcc;
3008                 nlen = len / dsb->wfx.nBlockAlign;
3009                 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
3010                 nlen *= primarybuf->wfx.nBlockAlign;
3011                 writepos =
3012                         ((dsb->primary_mixpos < nlen) ? primarybuf->buflen : 0) +
3013                         dsb->primary_mixpos - nlen;
3014         }
3015
3016         dsb->freqAcc -= flen;
3017         dsb->buf_mixpos = npos;
3018         dsb->primary_mixpos = writepos;
3019
3020         TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
3021               dsb->buf_mixpos, dsb->primary_mixpos, len);
3022
3023         if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
3024 }
3025
3026 static void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
3027 {
3028 #if 0
3029         DWORD   i, size, flen, len, npos, nlen;
3030         INT     iAdvance = dsb->wfx.nBlockAlign;
3031         INT     oAdvance = primarybuf->wfx.nBlockAlign;
3032         /* determine amount of premixed data to cancel */
3033         DWORD buf_done =
3034                 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
3035                 dsb->buf_mixpos - buf_writepos;
3036 #endif
3037
3038         WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
3039         /* since this is not implemented yet, just cancel *ALL* prebuffering for now
3040          * (which is faster anyway when there's one a single secondary buffer) */
3041         primarybuf->need_remix = TRUE;
3042 }
3043
3044 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
3045 {
3046         DWORD len, slen;
3047         /* determine this buffer's write position */
3048         DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & primarybuf->state, writepos,
3049                                                      writepos, dsb->primary_mixpos, dsb->buf_mixpos);
3050         /* determine how much already-mixed data exists */
3051         DWORD buf_done =
3052                 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
3053                 dsb->buf_mixpos - buf_writepos;
3054         DWORD primary_done =
3055                 ((dsb->primary_mixpos < writepos) ? primarybuf->buflen : 0) +
3056                 dsb->primary_mixpos - writepos;
3057         DWORD adv_done =
3058                 ((primarybuf->buf_mixpos < writepos) ? primarybuf->buflen : 0) +
3059                 primarybuf->buf_mixpos - writepos;
3060         int still_behind;
3061
3062         TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
3063         TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
3064         TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
3065               mixlen);
3066         TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
3067
3068         /* save write position for non-GETCURRENTPOSITION2... */
3069         dsb->playpos = buf_writepos;
3070
3071         /* check whether CalcPlayPosition detected a mixing underrun */
3072         if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
3073                 /* it did, but did we have more to play? */
3074                 if ((dsb->playflags & DSBPLAY_LOOPING) ||
3075                     (dsb->buf_mixpos < dsb->buflen)) {
3076                         /* yes, have to recover */
3077                         ERR("underrun on sound buffer %p\n", dsb);
3078                         TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
3079                 }
3080                 dsb->primary_mixpos = writepos;
3081                 primary_done = 0;
3082         }
3083         /* determine how far ahead we should mix */
3084         if (((dsb->playflags & DSBPLAY_LOOPING) ||
3085              (dsb->leadin && (dsb->probably_valid_to != 0))) &&
3086             !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
3087                 /* if this is a streaming buffer, it typically means that
3088                  * we should defer mixing past probably_valid_to as long
3089                  * as we can, to avoid unnecessary remixing */
3090                 /* the heavy-looking calculations shouldn't be that bad,
3091                  * as any game isn't likely to be have more than 1 or 2
3092                  * streaming buffers in use at any time anyway... */
3093                 DWORD probably_valid_left =
3094                         (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
3095                         ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
3096                         dsb->probably_valid_to - buf_writepos;
3097                 /* check for leadin condition */
3098                 if ((probably_valid_left == 0) &&
3099                     (dsb->probably_valid_to == dsb->startpos) &&
3100                     dsb->leadin)
3101                         probably_valid_left = dsb->buflen;
3102                 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
3103                       dsb->probably_valid_to, probably_valid_left);
3104                 /* check whether the app's time is already up */
3105                 if (probably_valid_left < dsb->writelead) {
3106                         WARN("probably_valid_to now within writelead, possible streaming underrun\n");
3107                         /* once we pass the point of no return,
3108                          * no reason to hold back anymore */
3109                         dsb->probably_valid_to = (DWORD)-1;
3110                         /* we just have to go ahead and mix what we have,
3111                          * there's no telling what the app is thinking anyway */
3112                 } else {
3113                         /* adjust for our frequency and our sample size */
3114                         probably_valid_left = MulDiv(probably_valid_left,
3115                                                      1 << DSOUND_FREQSHIFT,
3116                                                      dsb->wfx.nBlockAlign * dsb->freqAdjust) *
3117                                               primarybuf->wfx.nBlockAlign;
3118                         /* check whether to clip mix_len */
3119                         if (probably_valid_left < mixlen) {
3120                                 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
3121                                 mixlen = probably_valid_left;
3122                         }
3123                 }
3124         }
3125         /* cut mixlen with what's already been mixed */
3126         if (mixlen < primary_done) {
3127                 /* huh? and still CalcPlayPosition didn't
3128                  * detect an underrun? */
3129                 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
3130                 return 0;
3131         }
3132         len = mixlen - primary_done;
3133         TRACE("remaining mixlen=%ld\n", len);
3134
3135         if (len < primarybuf->dsound->fraglen) {
3136                 /* smaller than a fragment, wait until it gets larger
3137                  * before we take the mixing overhead */
3138                 TRACE("mixlen not worth it, deferring mixing\n");
3139                 return 0;
3140         }
3141
3142         /* ok, we know how much to mix, let's go */
3143         still_behind = (adv_done > primary_done);
3144         while (len) {
3145                 slen = primarybuf->buflen - dsb->primary_mixpos;
3146                 if (slen > len) slen = len;
3147                 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
3148
3149                 if ((dsb->primary_mixpos < primarybuf->buf_mixpos) &&
3150                     (dsb->primary_mixpos + slen >= primarybuf->buf_mixpos))
3151                         still_behind = FALSE;
3152
3153                 dsb->primary_mixpos += slen; len -= slen;
3154                 while (dsb->primary_mixpos >= primarybuf->buflen)
3155                         dsb->primary_mixpos -= primarybuf->buflen;
3156
3157                 if ((dsb->state == STATE_STOPPED) || !slen) break;
3158         }
3159         TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, primarybuf->buf_mixpos);
3160         TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
3161         /* return how far we think the primary buffer can
3162          * advance its underrun detector...*/
3163         if (still_behind) return 0;
3164         if ((mixlen - len) < primary_done) return 0;
3165         slen = ((dsb->primary_mixpos < primarybuf->buf_mixpos) ?
3166                 primarybuf->buflen : 0) + dsb->primary_mixpos -
3167                 primarybuf->buf_mixpos;
3168         if (slen > mixlen) {
3169                 /* the primary_done and still_behind checks above should have worked */
3170                 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
3171                 slen = 0;
3172         }
3173         return slen;
3174 }
3175
3176 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
3177 {
3178         INT                     i, len, maxlen = 0;
3179         IDirectSoundBufferImpl  *dsb;
3180
3181         TRACE("(%ld,%ld,%ld)\n", playpos, writepos, mixlen);
3182         for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
3183                 dsb = dsound->buffers[i];
3184
3185                 if (!dsb || !(ICOM_VTBL(dsb)))
3186                         continue;
3187                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
3188                         TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
3189                         EnterCriticalSection(&(dsb->lock));
3190                         if (dsb->state == STATE_STOPPING) {
3191                                 DSOUND_MixCancel(dsb, writepos, TRUE);
3192                                 dsb->state = STATE_STOPPED;
3193                         } else {
3194                                 if ((dsb->state == STATE_STARTING) || recover)
3195                                         dsb->primary_mixpos = writepos;
3196                                 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
3197                                 if (dsb->state == STATE_STARTING)
3198                                         dsb->state = STATE_PLAYING;
3199                                 maxlen = (len > maxlen) ? len : maxlen;
3200                         }
3201                         LeaveCriticalSection(&(dsb->lock));
3202                 }
3203         }
3204         
3205         return maxlen;
3206 }
3207
3208 static void DSOUND_MixReset(DWORD writepos)
3209 {
3210         INT                     i;
3211         IDirectSoundBufferImpl  *dsb;
3212         int nfiller;
3213
3214         TRACE("(%ld)\n", writepos);
3215
3216         /* the sound of silence */
3217         nfiller = primarybuf->wfx.wBitsPerSample == 8 ? 128 : 0;
3218
3219         /* reset all buffer mix positions */
3220         for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
3221                 dsb = dsound->buffers[i];
3222
3223                 if (!dsb || !(ICOM_VTBL(dsb)))
3224                         continue;
3225                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
3226                         TRACE("Resetting %p\n", dsb);
3227                         EnterCriticalSection(&(dsb->lock));
3228                         if (dsb->state == STATE_STOPPING) {
3229                                 dsb->state = STATE_STOPPED;
3230                         }
3231                         else if (dsb->state == STATE_STARTING) {
3232                                 /* nothing */
3233                         } else {
3234                                 DSOUND_MixCancel(dsb, writepos, FALSE);
3235                         }
3236                         LeaveCriticalSection(&(dsb->lock));
3237                 }
3238         }
3239
3240         /* wipe out premixed data */
3241         if (primarybuf->buf_mixpos < writepos) {
3242                 memset(primarybuf->buffer + writepos, nfiller, primarybuf->buflen - writepos);
3243                 memset(primarybuf->buffer, nfiller, primarybuf->buf_mixpos);
3244         } else {
3245                 memset(primarybuf->buffer + writepos, nfiller, primarybuf->buf_mixpos - writepos);
3246         }
3247
3248         /* reset primary mix position */
3249         primarybuf->buf_mixpos = writepos;
3250 }
3251
3252 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
3253 {
3254         if (primarybuf->need_remix) {
3255                 DSOUND_MixReset(writepos);
3256                 primarybuf->need_remix = FALSE;
3257                 /* maximize Half-Life performance */
3258                 dsound->prebuf = DS_SND_QUEUE_MIN;
3259         } else {
3260                 /* if (dsound->prebuf < DS_SND_QUEUE_MAX) dsound->prebuf++; */
3261         }
3262         TRACE("premix adjust: %d\n", dsound->prebuf);
3263 }
3264
3265 static void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
3266 {
3267         if (mixq + dsound->pwqueue > DS_HEL_QUEUE) mixq = DS_HEL_QUEUE - dsound->pwqueue;
3268         TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
3269         for (; mixq; mixq--) {
3270                 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
3271                 dsound->pwwrite++;
3272                 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
3273                 dsound->pwqueue++;
3274         }
3275 }
3276
3277 /* #define SYNC_CALLBACK */
3278
3279 static void DSOUND_PerformMix(void)
3280 {
3281         int nfiller;
3282         BOOL forced;
3283         HRESULT hres;
3284
3285         EnterCriticalSection(&(dsound->lock));
3286
3287         if (!primarybuf || !primarybuf->ref) {
3288                 /* seems the primary buffer is currently being released */
3289                 LeaveCriticalSection(&(dsound->lock));
3290                 return;
3291         }
3292
3293         /* the sound of silence */
3294         nfiller = primarybuf->wfx.wBitsPerSample == 8 ? 128 : 0;
3295
3296         /* whether the primary is forced to play even without secondary buffers */
3297         forced = ((primarybuf->state == STATE_PLAYING) || (primarybuf->state == STATE_STARTING));
3298
3299         TRACE("entering at %ld\n", GetTickCount());
3300         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
3301                 BOOL paused = ((primarybuf->state == STATE_STOPPED) || (primarybuf->state == STATE_STARTING));
3302                 /* FIXME: document variables */
3303                 DWORD playpos, writepos, inq, maxq, frag;
3304                 if (primarybuf->hwbuf) {
3305                         hres = IDsDriverBuffer_GetPosition(primarybuf->hwbuf, &playpos, &writepos);
3306                         if (hres) {
3307                             LeaveCriticalSection(&(dsound->lock));
3308                             return;
3309                         }
3310                         /* Well, we *could* do Just-In-Time mixing using the writepos,
3311                          * but that's a little bit ambitious and unnecessary... */
3312                         /* rather add our safety margin to the writepos, if we're playing */
3313                         if (!paused) {
3314                                 writepos += primarybuf->writelead;
3315                                 while (writepos >= primarybuf->buflen)
3316                                         writepos -= primarybuf->buflen;
3317                         } else writepos = playpos;
3318                 }
3319                 else {
3320                         playpos = dsound->pwplay * dsound->fraglen;
3321                         writepos = playpos;
3322                         if (!paused) {
3323                                 writepos += DS_HEL_MARGIN * dsound->fraglen;
3324                                 while (writepos >= primarybuf->buflen)
3325                                         writepos -= primarybuf->buflen;
3326                         }
3327                 }
3328                 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld\n",
3329                       playpos,writepos,primarybuf->playpos,primarybuf->buf_mixpos);
3330                 /* wipe out just-played sound data */
3331                 if (playpos < primarybuf->playpos) {
3332                         memset(primarybuf->buffer + primarybuf->playpos, nfiller, primarybuf->buflen - primarybuf->playpos);
3333                         memset(primarybuf->buffer, nfiller, playpos);
3334                 } else {
3335                         memset(primarybuf->buffer + primarybuf->playpos, nfiller, playpos - primarybuf->playpos);
3336                 }
3337                 primarybuf->playpos = playpos;
3338
3339                 EnterCriticalSection(&(primarybuf->lock));
3340
3341                 /* reset mixing if necessary */
3342                 DSOUND_CheckReset(dsound, writepos);
3343
3344                 /* check how much prebuffering is left */
3345                 inq = primarybuf->buf_mixpos;
3346                 if (inq < writepos)
3347                         inq += primarybuf->buflen;
3348                 inq -= writepos;
3349
3350                 /* find the maximum we can prebuffer */
3351                 if (!paused) {
3352                         maxq = playpos;
3353                         if (maxq < writepos)
3354                                 maxq += primarybuf->buflen;
3355                         maxq -= writepos;
3356                 } else maxq = primarybuf->buflen;
3357
3358                 /* clip maxq to dsound->prebuf */
3359                 frag = dsound->prebuf * dsound->fraglen;
3360                 if (maxq > frag) maxq = frag;
3361
3362                 /* check for consistency */
3363                 if (inq > maxq) {
3364                         /* the playback position must have passed our last
3365                          * mixed position, i.e. it's an underrun, or we have
3366                          * nothing more to play */
3367                         TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
3368                         inq = 0;
3369                         /* stop the playback now, to allow buffers to refill */
3370                         if (primarybuf->state == STATE_PLAYING) {
3371                                 primarybuf->state = STATE_STARTING;
3372                         }
3373                         else if (primarybuf->state == STATE_STOPPING) {
3374                                 primarybuf->state = STATE_STOPPED;
3375                         }
3376                         else {
3377                                 /* how can we have an underrun if we aren't playing? */
3378                                 WARN("unexpected primary state (%ld)\n", primarybuf->state);
3379                         }
3380 #ifdef SYNC_CALLBACK
3381                         /* DSOUND_callback may need this lock */
3382                         LeaveCriticalSection(&(primarybuf->lock));
3383 #endif
3384                         DSOUND_PrimaryStop(primarybuf);
3385 #ifdef SYNC_CALLBACK
3386                         EnterCriticalSection(&(primarybuf->lock));
3387 #endif
3388                         if (primarybuf->hwbuf) {
3389                                 /* the Stop is supposed to reset play position to beginning of buffer */
3390                                 /* unfortunately, OSS is not able to do so, so get current pointer */
3391                                 hres = IDsDriverBuffer_GetPosition(primarybuf->hwbuf, &playpos, NULL);
3392                                 if (hres) {
3393                                         LeaveCriticalSection(&(dsound->lock));
3394                                         LeaveCriticalSection(&(primarybuf->lock));
3395                                         return;
3396                                 }
3397                         } else {
3398                                 playpos = dsound->pwplay * dsound->fraglen;
3399                         }
3400                         writepos = playpos;
3401                         primarybuf->playpos = playpos;
3402                         primarybuf->buf_mixpos = writepos;
3403                         inq = 0;
3404                         maxq = primarybuf->buflen;
3405                         if (maxq > frag) maxq = frag;
3406                         memset(primarybuf->buffer, nfiller, primarybuf->buflen);
3407                         paused = TRUE;
3408                 }
3409
3410                 /* do the mixing */
3411                 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
3412                 if (forced) frag = maxq - inq;
3413                 primarybuf->buf_mixpos += frag;
3414                 while (primarybuf->buf_mixpos >= primarybuf->buflen)
3415                         primarybuf->buf_mixpos -= primarybuf->buflen;
3416
3417                 if (frag) {
3418                         /* buffers have been filled, restart playback */
3419                         if (primarybuf->state == STATE_STARTING) {
3420                                 primarybuf->state = STATE_PLAYING;
3421                         }
3422                         else if (primarybuf->state == STATE_STOPPED) {
3423                                 /* the primarybuf is supposed to play if there's something to play
3424                                  * even if it is reported as stopped, so don't let this confuse you */
3425                                 primarybuf->state = STATE_STOPPING;
3426                         }
3427                         LeaveCriticalSection(&(primarybuf->lock));
3428                         if (paused) {
3429                                 DSOUND_PrimaryPlay(primarybuf);
3430                                 TRACE("starting playback\n");
3431                         }
3432                 }
3433                 else
3434                         LeaveCriticalSection(&(primarybuf->lock));
3435         } else {
3436                 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
3437                 if (primarybuf->state == STATE_STARTING) {
3438                         DSOUND_PrimaryPlay(primarybuf);
3439                         primarybuf->state = STATE_PLAYING;
3440                 } 
3441                 else if (primarybuf->state == STATE_STOPPING) {
3442                         DSOUND_PrimaryStop(primarybuf);
3443                         primarybuf->state = STATE_STOPPED;
3444                 }
3445         }
3446         TRACE("completed processing at %ld\n", GetTickCount());
3447         LeaveCriticalSection(&(dsound->lock));
3448 }
3449
3450 static void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
3451 {
3452         if (!dsound || !primarybuf) {
3453                 ERR("dsound died without killing us?\n");
3454                 timeKillEvent(timerID);
3455                 timeEndPeriod(DS_TIME_RES);
3456                 return;
3457         }
3458
3459         TRACE("entered\n");
3460         DSOUND_PerformMix();
3461 }
3462
3463 static void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
3464 {
3465         IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
3466         TRACE("entering at %ld, msg=%08x\n", GetTickCount(), msg);
3467         if (msg == MM_WOM_DONE) {
3468                 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
3469                 if (This->pwqueue == (DWORD)-1) {
3470                         TRACE("completed due to reset\n");
3471                         return;
3472                 }
3473 /* it could be a bad idea to enter critical section here... if there's lock contention,
3474  * the resulting scheduling delays might obstruct the winmm player thread */
3475 #ifdef SYNC_CALLBACK
3476                 EnterCriticalSection(&(primarybuf->lock));
3477 #endif
3478                 /* retrieve current values */
3479                 fraglen = dsound->fraglen;
3480                 buflen = primarybuf->buflen;
3481                 pwplay = dsound->pwplay;
3482                 playpos = pwplay * fraglen;
3483                 mixpos = primarybuf->buf_mixpos;
3484                 /* check remaining mixed data */
3485                 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
3486                 mixq = inq / fraglen;
3487                 if ((inq - (mixq * fraglen)) > 0) mixq++;
3488                 /* complete the playing buffer */
3489                 TRACE("done playing primary pos=%ld\n", playpos);
3490                 pwplay++;
3491                 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
3492                 /* write new values */
3493                 dsound->pwplay = pwplay;
3494                 dsound->pwqueue--;
3495                 /* queue new buffer if we have data for it */
3496                 if (inq>1) DSOUND_WaveQueue(This, inq-1);
3497 #ifdef SYNC_CALLBACK
3498                 LeaveCriticalSection(&(primarybuf->lock));
3499 #endif
3500         }
3501         TRACE("completed\n");
3502 }
3503
3504 /*******************************************************************************
3505  *              DirectSoundCreate (DSOUND.1)
3506  */
3507 HRESULT WINAPI DirectSoundCreate(REFGUID lpGUID,LPDIRECTSOUND *ppDS,IUnknown *pUnkOuter )
3508 {
3509         IDirectSoundImpl** ippDS=(IDirectSoundImpl**)ppDS;
3510         PIDSDRIVER drv = NULL;
3511         WAVEOUTCAPSA wcaps;
3512         unsigned wod, wodn;
3513         HRESULT err = DS_OK;
3514
3515         if (lpGUID)
3516                 TRACE("(%p,%p,%p)\n",lpGUID,ippDS,pUnkOuter);
3517         else
3518                 TRACE("DirectSoundCreate (%p)\n", ippDS);
3519
3520         if (ippDS == NULL)
3521                 return DSERR_INVALIDPARAM;
3522
3523         if (primarybuf) {
3524                 IDirectSound_AddRef((LPDIRECTSOUND)dsound);
3525                 *ippDS = dsound;
3526                 return DS_OK;
3527         }
3528
3529         /* Enumerate WINMM audio devices and find the one we want */
3530         wodn = waveOutGetNumDevs();
3531         if (!wodn) return DSERR_NODRIVER;
3532
3533         /* FIXME: How do we find the GUID of an audio device? */
3534         wod = 0; /* start at the first audio device */
3535
3536         /* Get output device caps */
3537         waveOutGetDevCapsA(wod, &wcaps, sizeof(wcaps));
3538         /* DRV_QUERYDSOUNDIFACE is a "Wine extension" to get the DSound interface */
3539         waveOutMessage(wod, DRV_QUERYDSOUNDIFACE, (DWORD)&drv, 0);
3540
3541         /* Allocate memory */
3542         *ippDS = (IDirectSoundImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDirectSoundImpl));
3543         if (*ippDS == NULL)
3544                 return DSERR_OUTOFMEMORY;
3545
3546         ICOM_VTBL(*ippDS)       = &dsvt;
3547         (*ippDS)->ref           = 1;
3548
3549         (*ippDS)->driver        = drv;
3550         (*ippDS)->fraglen       = 0;
3551         (*ippDS)->priolevel     = DSSCL_NORMAL; 
3552         (*ippDS)->nrofbuffers   = 0;
3553         (*ippDS)->buffers       = NULL;
3554         (*ippDS)->primary       = NULL; 
3555         (*ippDS)->listener      = NULL; 
3556
3557         (*ippDS)->prebuf        = DS_SND_QUEUE_MAX;
3558
3559         /* Get driver description */
3560         if (drv) {
3561                 IDsDriver_GetDriverDesc(drv,&((*ippDS)->drvdesc));
3562         } else {
3563                 /* if no DirectSound interface available, use WINMM API instead */
3564                 (*ippDS)->drvdesc.dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT;
3565                 (*ippDS)->drvdesc.dnDevNode = wod; /* FIXME? */
3566         }
3567
3568         /* Set default wave format (may need it for waveOutOpen) */
3569         (*ippDS)->wfx.wFormatTag        = WAVE_FORMAT_PCM;
3570         (*ippDS)->wfx.nChannels         = 2;
3571         (*ippDS)->wfx.nSamplesPerSec    = 22050;
3572         (*ippDS)->wfx.nAvgBytesPerSec   = 44100;
3573         (*ippDS)->wfx.nBlockAlign       = 2;
3574         (*ippDS)->wfx.wBitsPerSample    = 8;
3575
3576         /* If the driver requests being opened through MMSYSTEM
3577          * (which is recommended by the DDK), it is supposed to happen
3578          * before the DirectSound interface is opened */
3579         if ((*ippDS)->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN)
3580         {
3581                 /* FIXME: is this right? */
3582
3583                 (*ippDS)->drvdesc.dnDevNode = 0;
3584                 err = DSERR_ALLOCATED;
3585
3586                 /* if this device is busy try the next one */
3587                 while((err == DSERR_ALLOCATED) && 
3588                         ((*ippDS)->drvdesc.dnDevNode < wodn))
3589                 {
3590                   err = mmErr(waveOutOpen(&((*ippDS)->hwo), 
3591                         (*ippDS)->drvdesc.dnDevNode, &((*ippDS)->wfx),
3592                         (DWORD)DSOUND_callback, (DWORD)(*ippDS),
3593                         CALLBACK_FUNCTION | WAVE_DIRECTSOUND));
3594                   (*ippDS)->drvdesc.dnDevNode++; /* next wave device */
3595                 }
3596
3597                 (*ippDS)->drvdesc.dnDevNode--; /* take away last increment */
3598                 
3599         }
3600
3601         if (drv && (err == DS_OK))
3602                 err = IDsDriver_Open(drv);
3603
3604         /* FIXME: do we want to handle a temporarily busy device? */
3605         if (err != DS_OK) {
3606                 HeapFree(GetProcessHeap(),0,*ippDS);
3607                 *ippDS = NULL;
3608                 return err;
3609         }
3610
3611         /* the driver is now open, so it's now allowed to call GetCaps */
3612         if (drv) {
3613                 IDsDriver_GetCaps(drv,&((*ippDS)->drvcaps));
3614         } else {
3615                 unsigned c;
3616
3617                 /* FIXME: look at wcaps */
3618                 (*ippDS)->drvcaps.dwFlags =
3619                         DSCAPS_PRIMARY16BIT | DSCAPS_PRIMARYSTEREO;
3620                 if (DS_EMULDRIVER)
3621                     (*ippDS)->drvcaps.dwFlags |= DSCAPS_EMULDRIVER;
3622
3623                 /* Allocate memory for HEL buffer headers */
3624                 for (c=0; c<DS_HEL_FRAGS; c++) {
3625                         (*ippDS)->pwave[c] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(WAVEHDR));
3626                         if (!(*ippDS)->pwave[c]) {
3627                                 /* Argh, out of memory */
3628                                 while (c--) {
3629                                         HeapFree(GetProcessHeap(),0,(*ippDS)->pwave[c]);
3630                                         waveOutClose((*ippDS)->hwo);
3631                                         HeapFree(GetProcessHeap(),0,*ippDS);
3632                                         *ippDS = NULL;
3633                                         return DSERR_OUTOFMEMORY;
3634                                 }
3635                         }
3636                 }
3637         }
3638
3639         InitializeCriticalSection(&((*ippDS)->lock));
3640
3641         if (!dsound) {
3642                 dsound = (*ippDS);
3643                 if (primarybuf == NULL) {
3644                         DSBUFFERDESC    dsbd;
3645                         HRESULT         hr;
3646
3647                         dsbd.dwSize = sizeof(DSBUFFERDESC);
3648                         dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
3649                         dsbd.dwBufferBytes = 0;
3650                         dsbd.lpwfxFormat = &(dsound->wfx);
3651                         hr = IDirectSound_CreateSoundBuffer(*ppDS, &dsbd, (LPDIRECTSOUNDBUFFER*)&primarybuf, NULL);
3652                         if (hr != DS_OK)
3653                                 return hr;
3654
3655                         /* dsound->primary is NULL - don't need to Release */
3656                         dsound->primary = primarybuf;
3657                         IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)primarybuf);
3658                 }
3659                 timeBeginPeriod(DS_TIME_RES);
3660                 dsound->timerID = timeSetEvent(DS_TIME_DEL, DS_TIME_RES, DSOUND_timer,
3661                                                (DWORD)dsound, TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
3662         }
3663         return DS_OK;
3664 }
3665
3666 /***************************************************************************
3667  * DirectSoundCaptureCreate [DSOUND.6]
3668  *
3669  * Create and initialize a DirectSoundCapture interface
3670  *
3671  * RETURNS
3672  *    Success: DS_OK
3673  *    Failure: DSERR_NOAGGREGATION, DSERR_ALLOCATED, DSERR_INVALIDPARAM,
3674  *             DSERR_OUTOFMEMORY
3675  */
3676 HRESULT WINAPI DirectSoundCaptureCreate(
3677         LPCGUID lpcGUID,
3678         LPDIRECTSOUNDCAPTURE* lplpDSC,
3679         LPUNKNOWN pUnkOuter )
3680 {
3681         TRACE("(%s,%p,%p)\n", debugstr_guid(lpcGUID), lplpDSC, pUnkOuter);
3682
3683         if( pUnkOuter ) {
3684                 return DSERR_NOAGGREGATION;
3685         }
3686
3687         /* Default device? */
3688         if ( !lpcGUID ) {
3689                 return DSOUND_CreateDirectSoundCapture( (LPVOID*)lplpDSC );
3690         }
3691
3692         FIXME( "Unknown GUID %s\n", debugstr_guid(lpcGUID) );
3693         *lplpDSC = NULL;
3694
3695         return DSERR_OUTOFMEMORY;
3696 }
3697
3698 /***************************************************************************
3699  * DirectSoundCaptureEnumerateA [DSOUND.7]
3700  *
3701  * Enumerate all DirectSound drivers installed in the system
3702  *
3703  * RETURNS
3704  *    Success: DS_OK
3705  *    Failure: DSERR_INVALIDPARAM
3706  */
3707 HRESULT WINAPI DirectSoundCaptureEnumerateA(
3708         LPDSENUMCALLBACKA lpDSEnumCallback,
3709         LPVOID lpContext)
3710 {
3711         TRACE("(%p,%p)\n", lpDSEnumCallback, lpContext );
3712
3713         if ( lpDSEnumCallback )
3714                 lpDSEnumCallback(NULL,"WINE Primary Sound Capture Driver",
3715                     "SoundCap",lpContext);
3716
3717
3718         return DS_OK;
3719 }
3720
3721 /***************************************************************************
3722  * DirectSoundCaptureEnumerateW [DSOUND.8]
3723  *
3724  * Enumerate all DirectSound drivers installed in the system
3725  *
3726  * RETURNS
3727  *    Success: DS_OK
3728  *    Failure: DSERR_INVALIDPARAM
3729  */
3730 HRESULT WINAPI DirectSoundCaptureEnumerateW(
3731         LPDSENUMCALLBACKW lpDSEnumCallback,
3732         LPVOID lpContext)
3733 {
3734         FIXME("(%p,%p):stub\n", lpDSEnumCallback, lpContext );
3735         return DS_OK;
3736
3737
3738 static HRESULT
3739 DSOUND_CreateDirectSoundCapture( LPVOID* ppobj )
3740 {
3741         *ppobj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof( IDirectSoundCaptureImpl ) );
3742
3743         if ( *ppobj == NULL ) {
3744                 return DSERR_OUTOFMEMORY;
3745         }
3746
3747         {
3748                 ICOM_THIS(IDirectSoundCaptureImpl,*ppobj);
3749
3750                 This->ref = 1;
3751                 ICOM_VTBL(This) = &dscvt;
3752
3753                 InitializeCriticalSection( &This->lock );
3754         }
3755
3756         return S_OK;
3757 }
3758
3759 static HRESULT WINAPI
3760 IDirectSoundCaptureImpl_QueryInterface(
3761         LPDIRECTSOUNDCAPTURE iface,
3762         REFIID riid,
3763         LPVOID* ppobj )
3764 {
3765         ICOM_THIS(IDirectSoundCaptureImpl,iface);
3766
3767         FIXME( "(%p)->(%s,%p): stub\n", This, debugstr_guid(riid), ppobj );
3768
3769         return E_FAIL;
3770 }
3771
3772 static ULONG WINAPI
3773 IDirectSoundCaptureImpl_AddRef( LPDIRECTSOUNDCAPTURE iface )
3774 {
3775         ULONG uRef;
3776         ICOM_THIS(IDirectSoundCaptureImpl,iface);
3777
3778         EnterCriticalSection( &This->lock );
3779
3780         TRACE( "(%p) was 0x%08lx\n", This, This->ref );
3781         uRef = ++(This->ref);
3782
3783         LeaveCriticalSection( &This->lock );
3784
3785         return uRef;
3786 }
3787
3788 static ULONG WINAPI
3789 IDirectSoundCaptureImpl_Release( LPDIRECTSOUNDCAPTURE iface )
3790 {
3791         ULONG uRef;
3792         ICOM_THIS(IDirectSoundCaptureImpl,iface);
3793
3794         EnterCriticalSection( &This->lock );
3795
3796         TRACE( "(%p) was 0x%08lx\n", This, This->ref );
3797         uRef = --(This->ref);
3798
3799         LeaveCriticalSection( &This->lock );
3800
3801         if ( uRef == 0 ) {
3802                 DeleteCriticalSection( &This->lock );
3803                 HeapFree( GetProcessHeap(), 0, This );
3804         }
3805
3806         return uRef;
3807 }
3808
3809 static HRESULT WINAPI
3810 IDirectSoundCaptureImpl_CreateCaptureBuffer(
3811         LPDIRECTSOUNDCAPTURE iface,
3812         LPCDSCBUFFERDESC lpcDSCBufferDesc,
3813         LPDIRECTSOUNDCAPTUREBUFFER* lplpDSCaptureBuffer, 
3814         LPUNKNOWN pUnk )
3815 {
3816         HRESULT hr;
3817         ICOM_THIS(IDirectSoundCaptureImpl,iface);
3818
3819         TRACE( "(%p)->(%p,%p,%p)\n", This, lpcDSCBufferDesc, lplpDSCaptureBuffer, pUnk );
3820
3821         if ( pUnk ) {
3822                 return DSERR_INVALIDPARAM;
3823         }
3824
3825         hr = DSOUND_CreateDirectSoundCaptureBuffer( lpcDSCBufferDesc, (LPVOID*)lplpDSCaptureBuffer );
3826
3827         return hr;
3828 }
3829
3830 static HRESULT WINAPI
3831 IDirectSoundCaptureImpl_GetCaps(
3832         LPDIRECTSOUNDCAPTURE iface,
3833         LPDSCCAPS lpDSCCaps )
3834 {
3835         ICOM_THIS(IDirectSoundCaptureImpl,iface);
3836
3837         FIXME( "(%p)->(%p): stub\n", This, lpDSCCaps );
3838
3839         return DS_OK;
3840 }
3841
3842 static HRESULT WINAPI
3843 IDirectSoundCaptureImpl_Initialize(
3844         LPDIRECTSOUNDCAPTURE iface,
3845         LPCGUID lpcGUID )
3846 {
3847         ICOM_THIS(IDirectSoundCaptureImpl,iface);
3848
3849         FIXME( "(%p)->(%p): stub\n", This, lpcGUID );
3850
3851         return DS_OK;
3852 }
3853
3854
3855 static ICOM_VTABLE(IDirectSoundCapture) dscvt =
3856 {
3857         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
3858         /* IUnknown methods */
3859         IDirectSoundCaptureImpl_QueryInterface,
3860         IDirectSoundCaptureImpl_AddRef,
3861         IDirectSoundCaptureImpl_Release,
3862
3863         /* IDirectSoundCapture methods */
3864         IDirectSoundCaptureImpl_CreateCaptureBuffer,
3865         IDirectSoundCaptureImpl_GetCaps,
3866         IDirectSoundCaptureImpl_Initialize 
3867 };
3868
3869 static HRESULT
3870 DSOUND_CreateDirectSoundCaptureBuffer( LPCDSCBUFFERDESC lpcDSCBufferDesc, LPVOID* ppobj )
3871 {
3872
3873         FIXME( "(%p,%p): ignoring lpcDSCBufferDesc\n", lpcDSCBufferDesc, ppobj );
3874
3875         *ppobj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof( IDirectSoundCaptureBufferImpl ) );
3876
3877         if ( *ppobj == NULL ) {
3878                 return DSERR_OUTOFMEMORY;
3879         }
3880
3881         {
3882                 ICOM_THIS(IDirectSoundCaptureBufferImpl,*ppobj);
3883
3884                 This->ref = 1;
3885                 ICOM_VTBL(This) = &dscbvt;
3886
3887                 InitializeCriticalSection( &This->lock );
3888         }
3889
3890         return S_OK;
3891 }
3892
3893
3894 static HRESULT WINAPI
3895 IDirectSoundCaptureBufferImpl_QueryInterface(
3896         LPDIRECTSOUNDCAPTUREBUFFER iface,
3897         REFIID riid,
3898         LPVOID* ppobj )
3899 {
3900         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
3901
3902         FIXME( "(%p)->(%s,%p): stub\n", This, debugstr_guid(riid), ppobj );
3903
3904         return E_FAIL;
3905 }
3906
3907 static ULONG WINAPI
3908 IDirectSoundCaptureBufferImpl_AddRef( LPDIRECTSOUNDCAPTUREBUFFER iface )
3909 {
3910         ULONG uRef;
3911         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
3912
3913         EnterCriticalSection( &This->lock );
3914
3915         TRACE( "(%p) was 0x%08lx\n", This, This->ref );
3916         uRef = ++(This->ref);
3917
3918         LeaveCriticalSection( &This->lock );
3919
3920         return uRef;
3921 }
3922
3923 static ULONG WINAPI
3924 IDirectSoundCaptureBufferImpl_Release( LPDIRECTSOUNDCAPTUREBUFFER iface )
3925 {
3926         ULONG uRef;
3927         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
3928
3929         EnterCriticalSection( &This->lock );
3930
3931         TRACE( "(%p) was 0x%08lx\n", This, This->ref );
3932         uRef = --(This->ref);
3933
3934         LeaveCriticalSection( &This->lock );
3935
3936         if ( uRef == 0 ) {
3937                 DeleteCriticalSection( &This->lock );
3938                 HeapFree( GetProcessHeap(), 0, This );
3939         }
3940
3941         return uRef;
3942 }
3943
3944 static HRESULT WINAPI
3945 IDirectSoundCaptureBufferImpl_GetCaps(
3946         LPDIRECTSOUNDCAPTUREBUFFER iface,
3947         LPDSCBCAPS lpDSCBCaps )
3948 {
3949         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
3950
3951         FIXME( "(%p)->(%p): stub\n", This, lpDSCBCaps );
3952
3953         return DS_OK;
3954 }
3955
3956 static HRESULT WINAPI
3957 IDirectSoundCaptureBufferImpl_GetCurrentPosition(
3958         LPDIRECTSOUNDCAPTUREBUFFER iface,
3959         LPDWORD lpdwCapturePosition,
3960         LPDWORD lpdwReadPosition )
3961 {
3962         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
3963
3964         FIXME( "(%p)->(%p,%p): stub\n", This, lpdwCapturePosition, lpdwReadPosition );
3965
3966         return DS_OK;
3967 }
3968
3969 static HRESULT WINAPI
3970 IDirectSoundCaptureBufferImpl_GetFormat(
3971         LPDIRECTSOUNDCAPTUREBUFFER iface,
3972         LPWAVEFORMATEX lpwfxFormat, 
3973         DWORD dwSizeAllocated, 
3974         LPDWORD lpdwSizeWritten )
3975 {
3976         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
3977
3978         FIXME( "(%p)->(%p,0x%08lx,%p): stub\n", This, lpwfxFormat, dwSizeAllocated, lpdwSizeWritten );
3979
3980         return DS_OK;
3981 }
3982
3983 static HRESULT WINAPI
3984 IDirectSoundCaptureBufferImpl_GetStatus(
3985         LPDIRECTSOUNDCAPTUREBUFFER iface,
3986         LPDWORD lpdwStatus )
3987 {
3988         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
3989
3990         FIXME( "(%p)->(%p): stub\n", This, lpdwStatus );
3991
3992         return DS_OK;
3993 }
3994
3995 static HRESULT WINAPI
3996 IDirectSoundCaptureBufferImpl_Initialize(
3997         LPDIRECTSOUNDCAPTUREBUFFER iface,
3998         LPDIRECTSOUNDCAPTURE lpDSC, 
3999         LPCDSCBUFFERDESC lpcDSCBDesc )
4000 {
4001         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
4002
4003         FIXME( "(%p)->(%p,%p): stub\n", This, lpDSC, lpcDSCBDesc );
4004
4005         return DS_OK;
4006 }
4007
4008 static HRESULT WINAPI
4009 IDirectSoundCaptureBufferImpl_Lock(
4010         LPDIRECTSOUNDCAPTUREBUFFER iface,
4011         DWORD dwReadCusor, 
4012         DWORD dwReadBytes, 
4013         LPVOID* lplpvAudioPtr1, 
4014         LPDWORD lpdwAudioBytes1, 
4015         LPVOID* lplpvAudioPtr2, 
4016         LPDWORD lpdwAudioBytes2, 
4017         DWORD dwFlags )
4018 {
4019         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
4020
4021         FIXME( "(%p)->(%08lu,%08lu,%p,%p,%p,%p,0x%08lx): stub\n", This, dwReadCusor, dwReadBytes, lplpvAudioPtr1, lpdwAudioBytes1, lplpvAudioPtr2, lpdwAudioBytes2, dwFlags );
4022
4023         return DS_OK;
4024 }
4025
4026 static HRESULT WINAPI
4027 IDirectSoundCaptureBufferImpl_Start(
4028         LPDIRECTSOUNDCAPTUREBUFFER iface,
4029         DWORD dwFlags )
4030 {
4031         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
4032
4033         FIXME( "(%p)->(0x%08lx): stub\n", This, dwFlags );
4034
4035         return DS_OK;
4036 }
4037
4038 static HRESULT WINAPI
4039 IDirectSoundCaptureBufferImpl_Stop( LPDIRECTSOUNDCAPTUREBUFFER iface )
4040 {
4041         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
4042
4043         FIXME( "(%p): stub\n", This );
4044
4045         return DS_OK;
4046 }
4047
4048 static HRESULT WINAPI
4049 IDirectSoundCaptureBufferImpl_Unlock(
4050         LPDIRECTSOUNDCAPTUREBUFFER iface,
4051         LPVOID lpvAudioPtr1, 
4052         DWORD dwAudioBytes1, 
4053         LPVOID lpvAudioPtr2, 
4054         DWORD dwAudioBytes2 )
4055 {
4056         ICOM_THIS(IDirectSoundCaptureBufferImpl,iface);
4057
4058         FIXME( "(%p)->(%p,%08lu,%p,%08lu): stub\n", This, lpvAudioPtr1, dwAudioBytes1, lpvAudioPtr2, dwAudioBytes2 );
4059
4060         return DS_OK;
4061 }
4062
4063
4064 static ICOM_VTABLE(IDirectSoundCaptureBuffer) dscbvt =
4065 {
4066         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
4067         /* IUnknown methods */
4068         IDirectSoundCaptureBufferImpl_QueryInterface,
4069         IDirectSoundCaptureBufferImpl_AddRef,
4070         IDirectSoundCaptureBufferImpl_Release,
4071
4072         /* IDirectSoundCaptureBuffer methods */
4073         IDirectSoundCaptureBufferImpl_GetCaps,
4074         IDirectSoundCaptureBufferImpl_GetCurrentPosition,
4075         IDirectSoundCaptureBufferImpl_GetFormat,
4076         IDirectSoundCaptureBufferImpl_GetStatus,
4077         IDirectSoundCaptureBufferImpl_Initialize,
4078         IDirectSoundCaptureBufferImpl_Lock,
4079         IDirectSoundCaptureBufferImpl_Start,
4080         IDirectSoundCaptureBufferImpl_Stop,
4081         IDirectSoundCaptureBufferImpl_Unlock
4082 };
4083
4084 /*******************************************************************************
4085  * DirectSound ClassFactory
4086  */
4087 typedef struct
4088 {
4089     /* IUnknown fields */
4090     ICOM_VFIELD(IClassFactory);
4091     DWORD                       ref;
4092 } IClassFactoryImpl;
4093
4094 static HRESULT WINAPI 
4095 DSCF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
4096         ICOM_THIS(IClassFactoryImpl,iface);
4097
4098         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
4099         return E_NOINTERFACE;
4100 }
4101
4102 static ULONG WINAPI
4103 DSCF_AddRef(LPCLASSFACTORY iface) {
4104         ICOM_THIS(IClassFactoryImpl,iface);
4105         return ++(This->ref);
4106 }
4107
4108 static ULONG WINAPI DSCF_Release(LPCLASSFACTORY iface) {
4109         ICOM_THIS(IClassFactoryImpl,iface);
4110         /* static class, won't be  freed */
4111         return --(This->ref);
4112 }
4113
4114 static HRESULT WINAPI DSCF_CreateInstance(
4115         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
4116 ) {
4117         ICOM_THIS(IClassFactoryImpl,iface);
4118
4119         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
4120         if ( IsEqualGUID( &IID_IDirectSound, riid ) ) {
4121                 /* FIXME: reuse already created dsound if present? */
4122                 return DirectSoundCreate(riid,(LPDIRECTSOUND*)ppobj,pOuter);
4123         }
4124         return E_NOINTERFACE;
4125 }
4126
4127 static HRESULT WINAPI DSCF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
4128         ICOM_THIS(IClassFactoryImpl,iface);
4129         FIXME("(%p)->(%d),stub!\n",This,dolock);
4130         return S_OK;
4131 }
4132
4133 static ICOM_VTABLE(IClassFactory) DSCF_Vtbl = {
4134         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
4135         DSCF_QueryInterface,
4136         DSCF_AddRef,
4137         DSCF_Release,
4138         DSCF_CreateInstance,
4139         DSCF_LockServer
4140 };
4141 static IClassFactoryImpl DSOUND_CF = {&DSCF_Vtbl, 1 };
4142
4143 /*******************************************************************************
4144  * DllGetClassObject [DSOUND.5]
4145  * Retrieves class object from a DLL object
4146  *
4147  * NOTES
4148  *    Docs say returns STDAPI
4149  *
4150  * PARAMS
4151  *    rclsid [I] CLSID for the class object
4152  *    riid   [I] Reference to identifier of interface for class object
4153  *    ppv    [O] Address of variable to receive interface pointer for riid
4154  *
4155  * RETURNS
4156  *    Success: S_OK
4157  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
4158  *             E_UNEXPECTED
4159  */
4160 DWORD WINAPI DSOUND_DllGetClassObject(REFCLSID rclsid,REFIID riid,LPVOID *ppv)
4161 {
4162     TRACE("(%p,%p,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
4163     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
4164         *ppv = (LPVOID)&DSOUND_CF;
4165         IClassFactory_AddRef((IClassFactory*)*ppv);
4166     return S_OK;
4167     }
4168
4169     FIXME("(%p,%p,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
4170     return CLASS_E_CLASSNOTAVAILABLE;
4171 }
4172
4173
4174 /*******************************************************************************
4175  * DllCanUnloadNow [DSOUND.4]  Determines whether the DLL is in use.
4176  *
4177  * RETURNS
4178  *    Success: S_OK
4179  *    Failure: S_FALSE
4180  */
4181 DWORD WINAPI DSOUND_DllCanUnloadNow(void)
4182 {
4183     FIXME("(void): stub\n");
4184     return S_FALSE;
4185 }