3D buffer and listener reference counts should be fixed.
[wine] / dlls / dsound / buffer.c
1 /*                      DirectSound
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2002 TransGaming Technologies, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include <assert.h>
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h>
33
34 #define NONAMELESSSTRUCT
35 #define NONAMELESSUNION
36 #include "windef.h"
37 #include "winbase.h"
38 #include "wingdi.h"
39 #include "winuser.h"
40 #include "winerror.h"
41 #include "mmsystem.h"
42 #include "winternl.h"
43 #include "mmddk.h"
44 #include "wine/windef16.h"
45 #include "wine/debug.h"
46 #include "dsound.h"
47 #include "dsdriver.h"
48 #include "dsound_private.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
51
52 /*******************************************************************************
53  *              IDirectSoundNotify
54  */
55 static HRESULT WINAPI IDirectSoundNotifyImpl_QueryInterface(
56         LPDIRECTSOUNDNOTIFY iface,REFIID riid,LPVOID *ppobj
57 ) {
58         ICOM_THIS(IDirectSoundNotifyImpl,iface);
59         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
60
61         *ppobj = NULL;  /* assume error */
62
63         if ( IsEqualGUID(riid, &IID_IUnknown) || 
64              IsEqualGUID(riid, &IID_IDirectSoundNotify) ||
65              IsEqualGUID(riid, &IID_IDirectSoundNotify8) ) {
66                 IDirectSoundNotify_AddRef(iface);
67                 *ppobj = This;
68                 return DS_OK;
69         }
70
71         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
72         return E_NOINTERFACE;
73 }
74
75 static ULONG WINAPI IDirectSoundNotifyImpl_AddRef(LPDIRECTSOUNDNOTIFY iface) {
76         ICOM_THIS(IDirectSoundNotifyImpl,iface);
77         DWORD ref;
78
79         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
80
81         ref = InterlockedIncrement(&(This->ref));
82         return ref;
83 }
84
85 static ULONG WINAPI IDirectSoundNotifyImpl_Release(LPDIRECTSOUNDNOTIFY iface) {
86         ICOM_THIS(IDirectSoundNotifyImpl,iface);
87         DWORD ref;
88
89         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
90
91         ref = InterlockedDecrement(&(This->ref));
92         /* FIXME: A notification should be a part of a buffer rather than pointed 
93          * to from a buffer. Hence the -1 ref count */
94         if (ref == -1) {
95                 if (This->notifies != NULL)
96                         HeapFree(GetProcessHeap(), 0, This->notifies);
97
98                 HeapFree(GetProcessHeap(),0,This);
99                 return 0;
100         }
101         return ref;
102 }
103
104 static HRESULT WINAPI IDirectSoundNotifyImpl_SetNotificationPositions(
105         LPDIRECTSOUNDNOTIFY iface,DWORD howmuch,LPCDSBPOSITIONNOTIFY notify
106 ) {
107         ICOM_THIS(IDirectSoundNotifyImpl,iface);
108         TRACE("(%p,0x%08lx,%p)\n",This,howmuch,notify);
109
110         if (notify == NULL) {
111             WARN("invalid parameter: notify == NULL\n");
112             return DSERR_INVALIDPARAM;
113         }
114
115         if (TRACE_ON(dsound)) {
116             int i;
117             for (i=0;i<howmuch;i++)
118                 TRACE("notify at %ld to 0x%08lx\n",
119                     notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
120         }
121
122         if (This->hwnotify) {
123             HRESULT hres;
124             hres = IDsDriverNotify_SetNotificationPositions(This->hwnotify, howmuch, notify);
125             if (hres != DS_OK)
126                     WARN("IDsDriverNotify_SetNotificationPositions failed\n");
127             return hres;
128         } else {
129             /* Make an internal copy of the caller-supplied array.
130              * Replace the existing copy if one is already present. */
131             This->notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 
132                 This->notifies, howmuch * sizeof(DSBPOSITIONNOTIFY));
133             if (This->notifies == NULL) {
134                     WARN("out of memory\n");
135                     return DSERR_OUTOFMEMORY;
136             }
137             memcpy(This->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
138             This->nrofnotifies = howmuch;
139         }
140
141         return S_OK;
142 }
143
144 ICOM_VTABLE(IDirectSoundNotify) dsnvt =
145 {
146         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
147         IDirectSoundNotifyImpl_QueryInterface,
148         IDirectSoundNotifyImpl_AddRef,
149         IDirectSoundNotifyImpl_Release,
150         IDirectSoundNotifyImpl_SetNotificationPositions,
151 };
152
153 /*******************************************************************************
154  *              IDirectSoundBuffer
155  */
156
157 static HRESULT WINAPI IDirectSoundBufferImpl_SetFormat(
158         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX wfex
159 ) {
160         ICOM_THIS(IDirectSoundBufferImpl,iface);
161
162         TRACE("(%p,%p)\n",This,wfex);
163         /* This method is not available on secondary buffers */
164         WARN("invalid call\n");
165         return DSERR_INVALIDCALL;
166 }
167
168 static HRESULT WINAPI IDirectSoundBufferImpl_SetVolume(
169         LPDIRECTSOUNDBUFFER8 iface,LONG vol
170 ) {
171         ICOM_THIS(IDirectSoundBufferImpl,iface);
172         LONG oldVol;
173
174         TRACE("(%p,%ld)\n",This,vol);
175
176         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
177                 WARN("control unavailable: This->dsbd.dwFlags = 0x%08lx\n", This->dsbd.dwFlags);
178                 return DSERR_CONTROLUNAVAIL;
179         }
180
181         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
182                 WARN("invalid parameter: vol = %ld\n", vol);
183                 return DSERR_INVALIDPARAM;
184         }
185
186         /* **** */
187         EnterCriticalSection(&(This->lock));
188
189         if (This->dsbd.dwFlags & DSBCAPS_CTRL3D) {
190                 oldVol = This->ds3db_lVolume;
191                 This->ds3db_lVolume = vol;
192         } else {
193                 oldVol = This->volpan.lVolume;
194                 This->volpan.lVolume = vol;
195                 if (vol != oldVol) 
196                         DSOUND_RecalcVolPan(&(This->volpan));
197         }
198
199         if (vol != oldVol) {
200                 if (This->hwbuf) {
201                         HRESULT hres;
202                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
203                         if (hres != DS_OK)
204                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
205                 } else 
206                         DSOUND_ForceRemix(This);
207         }
208
209         LeaveCriticalSection(&(This->lock));
210         /* **** */
211
212         return DS_OK;
213 }
214
215 static HRESULT WINAPI IDirectSoundBufferImpl_GetVolume(
216         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol
217 ) {
218         ICOM_THIS(IDirectSoundBufferImpl,iface);
219         TRACE("(%p,%p)\n",This,vol);
220
221         if (vol == NULL) {
222                 WARN("invalid parameter: vol == NULL\n");
223                 return DSERR_INVALIDPARAM;
224         }
225
226         if (This->dsbd.dwFlags & DSBCAPS_CTRL3D)
227                 *vol = This->ds3db_lVolume;
228         else
229                 *vol = This->volpan.lVolume;
230         return DS_OK;
231 }
232
233 static HRESULT WINAPI IDirectSoundBufferImpl_SetFrequency(
234         LPDIRECTSOUNDBUFFER8 iface,DWORD freq
235 ) {
236         ICOM_THIS(IDirectSoundBufferImpl,iface);
237         DWORD oldFreq;
238
239         TRACE("(%p,%ld)\n",This,freq);
240
241         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
242                 WARN("control unavailable\n");
243                 return DSERR_CONTROLUNAVAIL;
244         }
245
246         if (freq == DSBFREQUENCY_ORIGINAL)
247                 freq = This->wfx.nSamplesPerSec;
248
249         if ((freq < DSBFREQUENCY_MIN) || (freq > DSBFREQUENCY_MAX)) {
250                 WARN("invalid parameter: freq = %ld\n", freq);
251                 return DSERR_INVALIDPARAM;
252         }
253
254         /* **** */
255         EnterCriticalSection(&(This->lock));
256
257         oldFreq = This->freq;
258         This->freq = freq;
259         if (freq != oldFreq) {
260                 This->freqAdjust = (freq << DSOUND_FREQSHIFT) / This->dsound->wfx.nSamplesPerSec;
261                 This->nAvgBytesPerSec = freq * This->wfx.nBlockAlign;
262                 DSOUND_RecalcFormat(This);
263                 if (!This->hwbuf) 
264                         DSOUND_ForceRemix(This);
265         }
266
267         LeaveCriticalSection(&(This->lock));
268         /* **** */
269
270         return DS_OK;
271 }
272
273 static HRESULT WINAPI IDirectSoundBufferImpl_Play(
274         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags
275 ) {
276         HRESULT hres = DS_OK;
277         ICOM_THIS(IDirectSoundBufferImpl,iface);
278         TRACE("(%p,%08lx,%08lx,%08lx)\n",This,reserved1,reserved2,flags);
279
280         /* **** */
281         EnterCriticalSection(&(This->lock));
282
283         This->playflags = flags;
284         if (This->state == STATE_STOPPED) {
285                 This->leadin = TRUE;
286                 This->startpos = This->buf_mixpos;
287                 This->state = STATE_STARTING;
288         } else if (This->state == STATE_STOPPING)
289                 This->state = STATE_PLAYING;
290         if (This->hwbuf) {
291                 hres = IDsDriverBuffer_Play(This->hwbuf, 0, 0, This->playflags);
292                 if (hres != DS_OK)
293                         WARN("IDsDriverBuffer_Play failed\n");
294                 else
295                         This->state = STATE_PLAYING;
296         }
297
298         LeaveCriticalSection(&(This->lock));
299         /* **** */
300
301         return hres;
302 }
303
304 static HRESULT WINAPI IDirectSoundBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
305 {
306         HRESULT hres = DS_OK;
307         ICOM_THIS(IDirectSoundBufferImpl,iface);
308         TRACE("(%p)\n",This);
309
310         /* **** */
311         EnterCriticalSection(&(This->lock));
312
313         if (This->state == STATE_PLAYING)
314                 This->state = STATE_STOPPING;
315         else if (This->state == STATE_STARTING)
316                 This->state = STATE_STOPPED;
317         if (This->hwbuf) {
318                 hres = IDsDriverBuffer_Stop(This->hwbuf);
319                 if (hres != DS_OK)
320                         WARN("IDsDriverBuffer_Stop failed\n");
321                 else
322                         This->state = STATE_STOPPED;
323         }
324         DSOUND_CheckEvent(This, 0);
325
326         LeaveCriticalSection(&(This->lock));
327         /* **** */
328
329         return hres;
330 }
331
332 static DWORD WINAPI IDirectSoundBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface) {
333         ICOM_THIS(IDirectSoundBufferImpl,iface);
334         DWORD ref;
335
336         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
337
338         ref = InterlockedIncrement(&(This->ref));
339         if (!ref) {
340                 FIXME("thread-safety alert! AddRef-ing with a zero refcount!\n");
341         }
342         return ref;
343 }
344
345 static DWORD WINAPI IDirectSoundBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface) {
346         ICOM_THIS(IDirectSoundBufferImpl,iface);
347         int     i;
348         DWORD ref;
349
350         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
351
352         ref = InterlockedDecrement(&(This->ref));
353         if (ref) return ref;
354
355         RtlAcquireResourceExclusive(&(This->dsound->lock), TRUE);
356         for (i=0;i<This->dsound->nrofbuffers;i++)
357                 if (This->dsound->buffers[i] == This)
358                         break;
359
360         if (i < This->dsound->nrofbuffers) {
361                 /* Put the last buffer of the list in the (now empty) position */
362                 This->dsound->buffers[i] = This->dsound->buffers[This->dsound->nrofbuffers - 1];
363                 This->dsound->nrofbuffers--;
364                 This->dsound->buffers = HeapReAlloc(GetProcessHeap(),0,This->dsound->buffers,sizeof(LPDIRECTSOUNDBUFFER8)*This->dsound->nrofbuffers);
365                 TRACE("buffer count is now %d\n", This->dsound->nrofbuffers);
366                 IDirectSound_Release((LPDIRECTSOUND)This->dsound);
367         }
368         RtlReleaseResource(&(This->dsound->lock));
369
370         DeleteCriticalSection(&(This->lock));
371
372         if (This->hwbuf) {
373                 IDsDriverBuffer_Release(This->hwbuf);
374                 if (This->dsound->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) {
375                         This->buffer->ref--;
376                         if (This->buffer->ref==0) {
377                                 HeapFree(GetProcessHeap(),0,This->buffer->memory);
378                                 HeapFree(GetProcessHeap(),0,This->buffer);
379                         }
380                 }
381         } else {
382                 This->buffer->ref--;
383                 if (This->buffer->ref==0) {
384                         HeapFree(GetProcessHeap(),0,This->buffer->memory);
385                         HeapFree(GetProcessHeap(),0,This->buffer);
386                 }
387         }
388
389         if (This->ds3db) {
390                 WARN("ds3db still has reference\n");
391                 EnterCriticalSection(&(This->ds3db->lock));
392                 This->ds3db->dsb = NULL;
393                 LeaveCriticalSection(&(This->ds3db->lock));
394         }
395
396         if (This->iks)
397                 IKsPropertySet_Release((LPKSPROPERTYSET)This->iks);
398
399         HeapFree(GetProcessHeap(),0,This);
400
401         return 0;
402 }
403
404 DWORD DSOUND_CalcPlayPosition(IDirectSoundBufferImpl *This,
405                               DWORD state, DWORD pplay, DWORD pwrite, DWORD pmix, DWORD bmix)
406 {
407         DWORD bplay;
408
409         TRACE("primary playpos=%ld, mixpos=%ld\n", pplay, pmix);
410         TRACE("this mixpos=%ld, time=%ld\n", bmix, GetTickCount());
411
412         /* the actual primary play position (pplay) is always behind last mixed (pmix),
413          * unless the computer is too slow or something */
414         /* we need to know how far away we are from there */
415 #if 0 /* we'll never fill the primary entirely */
416         if (pmix == pplay) {
417                 if ((state == STATE_PLAYING) || (state == STATE_STOPPING)) {
418                         /* wow, the software mixer is really doing well,
419                          * seems the entire primary buffer is filled! */
420                         pmix += This->dsound->buflen;
421                 }
422                 /* else: the primary buffer is not playing, so probably empty */
423         }
424 #endif
425         if (pmix < pplay) pmix += This->dsound->buflen; /* wraparound */
426         pmix -= pplay;
427         /* detect buffer underrun */
428         if (pwrite < pplay) pwrite += This->dsound->buflen; /* wraparound */
429         pwrite -= pplay;
430         if (pmix > (ds_snd_queue_max * This->dsound->fraglen + pwrite + This->dsound->writelead)) {
431                 WARN("detected an underrun: primary queue was %ld\n",pmix);
432                 pmix = 0;
433         }
434         /* divide the offset by its sample size */
435         pmix /= This->dsound->wfx.nBlockAlign;
436         TRACE("primary back-samples=%ld\n",pmix);
437         /* adjust for our frequency */
438         pmix = (pmix * This->freqAdjust) >> DSOUND_FREQSHIFT;
439         /* multiply by our own sample size */
440         pmix *= This->wfx.nBlockAlign;
441         TRACE("this back-offset=%ld\n", pmix);
442         /* subtract from our last mixed position */
443         bplay = bmix;
444         while (bplay < pmix) bplay += This->buflen; /* wraparound */
445         bplay -= pmix;
446         if (This->leadin && ((bplay < This->startpos) || (bplay > bmix))) {
447                 /* seems we haven't started playing yet */
448                 TRACE("this still in lead-in phase\n");
449                 bplay = This->startpos;
450         }
451         /* return the result */
452         return bplay;
453 }
454
455 static HRESULT WINAPI IDirectSoundBufferImpl_GetCurrentPosition(
456         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos
457 ) {
458         HRESULT hres;
459         ICOM_THIS(IDirectSoundBufferImpl,iface);
460         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
461         if (This->hwbuf) {
462                 hres=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
463                 if (hres != DS_OK) {
464                     WARN("IDsDriverBuffer_GetPosition failed\n");
465                     return hres;
466                 }
467         }
468         else {
469                 if (playpos && (This->state != STATE_PLAYING)) {
470                         /* we haven't been merged into the primary buffer (yet) */
471                         *playpos = This->buf_mixpos;
472                 }
473                 else if (playpos) {
474                         DWORD pplay, pwrite, lplay, splay, pstate;
475                         /* let's get this exact; first, recursively call GetPosition on the primary */
476                         EnterCriticalSection(&(This->dsound->mixlock));
477                         if (DSOUND_PrimaryGetPosition(This->dsound, &pplay, &pwrite) != DS_OK)
478                                 WARN("DSOUND_PrimaryGetPosition failed\n");
479                         /* detect HEL mode underrun */
480                         pstate = This->dsound->state;
481                         if (!(This->dsound->hwbuf || This->dsound->pwqueue)) {
482                                 TRACE("detected an underrun\n");
483                                 /* pplay = ? */
484                                 if (pstate == STATE_PLAYING)
485                                         pstate = STATE_STARTING;
486                                 else if (pstate == STATE_STOPPING)
487                                         pstate = STATE_STOPPED;
488                         }
489                         /* get data for ourselves while we still have the lock */
490                         pstate &= This->state;
491                         lplay = This->primary_mixpos;
492                         splay = This->buf_mixpos;
493                         if ((This->dsbd.dwFlags & DSBCAPS_GETCURRENTPOSITION2) || This->dsound->hwbuf) {
494                                 /* calculate play position using this */
495                                 *playpos = DSOUND_CalcPlayPosition(This, pstate, pplay, pwrite, lplay, splay);
496                         } else {
497                                 /* (unless the app isn't using GETCURRENTPOSITION2) */
498                                 /* don't know exactly how this should be handled...
499                                  * the docs says that play cursor is reported as directly
500                                  * behind write cursor, hmm... */
501                                 /* let's just do what might work for Half-Life */
502                                 DWORD wp;
503                                 wp = (This->dsound->pwplay + ds_hel_margin) * This->dsound->fraglen;
504                                 while (wp >= This->dsound->buflen)
505                                         wp -= This->dsound->buflen;
506                                 *playpos = DSOUND_CalcPlayPosition(This, pstate, wp, pwrite, lplay, splay);
507                         }
508                         LeaveCriticalSection(&(This->dsound->mixlock));
509                 }
510                 if (writepos) *writepos = This->buf_mixpos;
511         }
512         if (writepos) {
513                 if (This->state != STATE_STOPPED)
514                         /* apply the documented 10ms lead to writepos */
515                         *writepos += This->writelead;
516                 while (*writepos >= This->buflen) *writepos -= This->buflen;
517         }
518         if (playpos) This->last_playpos = *playpos;
519         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
520         return DS_OK;
521 }
522
523 static HRESULT WINAPI IDirectSoundBufferImpl_GetStatus(
524         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status
525 ) {
526         ICOM_THIS(IDirectSoundBufferImpl,iface);
527         TRACE("(%p,%p), thread is %04lx\n",This,status,GetCurrentThreadId());
528
529         if (status == NULL) {
530                 WARN("invalid parameter: status = NULL\n");
531                 return DSERR_INVALIDPARAM;
532         }
533
534         *status = 0;
535         if ((This->state == STATE_STARTING) || (This->state == STATE_PLAYING)) {
536                 *status |= DSBSTATUS_PLAYING;
537                 if (This->playflags & DSBPLAY_LOOPING)
538                         *status |= DSBSTATUS_LOOPING;
539         }
540
541         TRACE("status=%lx\n", *status);
542         return DS_OK;
543 }
544
545
546 static HRESULT WINAPI IDirectSoundBufferImpl_GetFormat(
547         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten
548 ) {
549         ICOM_THIS(IDirectSoundBufferImpl,iface);
550         TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
551
552         if (wfsize>sizeof(This->wfx))
553                 wfsize = sizeof(This->wfx);
554         if (lpwf) {     /* NULL is valid */
555                 memcpy(lpwf,&(This->wfx),wfsize);
556                 if (wfwritten)
557                         *wfwritten = wfsize;
558         } else {
559                 if (wfwritten)
560                         *wfwritten = sizeof(This->wfx);
561                 else {
562                         WARN("invalid parameter: wfwritten == NULL\n");
563                         return DSERR_INVALIDPARAM;
564                 }
565         }
566
567         return DS_OK;
568 }
569
570 static HRESULT WINAPI IDirectSoundBufferImpl_Lock(
571         LPDIRECTSOUNDBUFFER8 iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
572 ) {
573         HRESULT hres = DS_OK;
574         ICOM_THIS(IDirectSoundBufferImpl,iface);
575
576         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
577                 This,
578                 writecursor,
579                 writebytes,
580                 lplpaudioptr1,
581                 audiobytes1,
582                 lplpaudioptr2,
583                 audiobytes2,
584                 flags,
585                 GetTickCount()
586         );
587
588         if (flags & DSBLOCK_FROMWRITECURSOR) {
589                 DWORD writepos;
590                 /* GetCurrentPosition does too much magic to duplicate here */
591                 hres = IDirectSoundBufferImpl_GetCurrentPosition(iface, NULL, &writepos);
592                 if (hres != DS_OK) {
593                         WARN("IDirectSoundBufferImpl_GetCurrentPosition failed\n");
594                         return hres;
595                 }
596                 writecursor += writepos;
597         }
598         while (writecursor >= This->buflen)
599                 writecursor -= This->buflen;
600         if (flags & DSBLOCK_ENTIREBUFFER)
601                 writebytes = This->buflen;
602         if (writebytes > This->buflen)
603                 writebytes = This->buflen;
604
605         assert(audiobytes1!=audiobytes2);
606         assert(lplpaudioptr1!=lplpaudioptr2);
607
608         EnterCriticalSection(&(This->lock));
609
610         if ((writebytes == This->buflen) &&
611             ((This->state == STATE_STARTING) ||
612              (This->state == STATE_PLAYING)))
613                 /* some games, like Half-Life, try to be clever (not) and
614                  * keep one secondary buffer, and mix sounds into it itself,
615                  * locking the entire buffer every time... so we can just forget
616                  * about tracking the last-written-to-position... */
617                 This->probably_valid_to = (DWORD)-1;
618         else
619                 This->probably_valid_to = writecursor;
620
621         if (!(This->dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
622                 hres = IDsDriverBuffer_Lock(This->hwbuf,
623                                      lplpaudioptr1, audiobytes1,
624                                      lplpaudioptr2, audiobytes2,
625                                      writecursor, writebytes,
626                                      0);
627                 if (hres != DS_OK) {
628                         WARN("IDsDriverBuffer_Lock failed\n");
629                         LeaveCriticalSection(&(This->lock));
630                         return hres;
631                 }
632         } else {
633                 BOOL remix = FALSE;
634                 if (writecursor+writebytes <= This->buflen) {
635                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
636                         *audiobytes1 = writebytes;
637                         if (lplpaudioptr2)
638                                 *(LPBYTE*)lplpaudioptr2 = NULL;
639                         if (audiobytes2)
640                                 *audiobytes2 = 0;
641                         TRACE("->%ld.0\n",writebytes);
642                 } else {
643                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
644                         *audiobytes1 = This->buflen-writecursor;
645                         if (lplpaudioptr2)
646                                 *(LPBYTE*)lplpaudioptr2 = This->buffer->memory;
647                         if (audiobytes2)
648                                 *audiobytes2 = writebytes-(This->buflen-writecursor);
649                         TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
650                 }
651                 if (This->state == STATE_PLAYING) {
652                         /* if the segment between playpos and buf_mixpos is touched,
653                          * we need to cancel some mixing */
654                         /* we'll assume that the app always calls GetCurrentPosition before
655                          * locking a playing buffer, so that last_playpos is up-to-date */
656                         if (This->buf_mixpos >= This->last_playpos) {
657                                 if (This->buf_mixpos > writecursor &&
658                                     This->last_playpos < writecursor+writebytes)
659                                         remix = TRUE;
660                         }
661                         else {
662                                 if (This->buf_mixpos > writecursor ||
663                                     This->last_playpos < writecursor+writebytes)
664                                         remix = TRUE;
665                         }
666                         if (remix) {
667                                 TRACE("locking prebuffered region, ouch\n");
668                                 DSOUND_MixCancelAt(This, writecursor);
669                         }
670                 }
671         }
672
673         LeaveCriticalSection(&(This->lock));
674         return DS_OK;
675 }
676
677 static HRESULT WINAPI IDirectSoundBufferImpl_SetCurrentPosition(
678         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos
679 ) {
680         HRESULT hres = DS_OK;
681         ICOM_THIS(IDirectSoundBufferImpl,iface);
682         TRACE("(%p,%ld)\n",This,newpos);
683
684         /* **** */
685         EnterCriticalSection(&(This->lock));
686
687         while (newpos >= This->buflen)
688                 newpos -= This->buflen;
689         This->buf_mixpos = newpos;
690         if (This->hwbuf) {
691                 hres = IDsDriverBuffer_SetPosition(This->hwbuf, This->buf_mixpos);
692                 if (hres != DS_OK)
693                         WARN("IDsDriverBuffer_SetPosition failed\n");
694         }
695
696         LeaveCriticalSection(&(This->lock));
697         /* **** */
698
699         return hres;
700 }
701
702 static HRESULT WINAPI IDirectSoundBufferImpl_SetPan(
703         LPDIRECTSOUNDBUFFER8 iface,LONG pan
704 ) {
705         HRESULT hres = DS_OK;
706         ICOM_THIS(IDirectSoundBufferImpl,iface);
707         LONG oldPan;
708
709         TRACE("(%p,%ld)\n",This,pan);
710
711         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
712                 WARN("invalid parameter: pan = %ld\n", pan);
713                 return DSERR_INVALIDPARAM;
714         }
715
716         /* You cannot use both pan and 3D controls */
717         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
718             (This->dsbd.dwFlags & DSBCAPS_CTRL3D)) {
719                 WARN("control unavailable\n");
720                 return DSERR_CONTROLUNAVAIL;
721         }
722
723         /* **** */
724         EnterCriticalSection(&(This->lock));
725
726         oldPan = This->volpan.lPan;
727         This->volpan.lPan = pan;
728
729         if (pan != oldPan) {
730                 DSOUND_RecalcVolPan(&(This->volpan));
731
732                 if (This->hwbuf) {
733                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
734                         if (hres != DS_OK)
735                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
736                 } else 
737                         DSOUND_ForceRemix(This);
738         }
739
740         LeaveCriticalSection(&(This->lock));
741         /* **** */
742
743         return hres;
744 }
745
746 static HRESULT WINAPI IDirectSoundBufferImpl_GetPan(
747         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan
748 ) {
749         ICOM_THIS(IDirectSoundBufferImpl,iface);
750         TRACE("(%p,%p)\n",This,pan);
751
752         if (pan == NULL) {
753                 WARN("invalid parameter: pan = NULL\n");
754                 return DSERR_INVALIDPARAM;
755         }
756
757         *pan = This->volpan.lPan;
758
759         return DS_OK;
760 }
761
762 static HRESULT WINAPI IDirectSoundBufferImpl_Unlock(
763         LPDIRECTSOUNDBUFFER8 iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
764 ) {
765         ICOM_THIS(IDirectSoundBufferImpl,iface);
766         DWORD probably_valid_to;
767
768         TRACE("(%p,%p,%ld,%p,%ld)\n", This,p1,x1,p2,x2);
769
770         if (!(This->dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
771                 HRESULT hres;
772                 hres = IDsDriverBuffer_Unlock(This->hwbuf, p1, x1, p2, x2);
773                 if (hres != DS_OK) {
774                         WARN("IDsDriverBuffer_Unlock failed\n");
775                         return hres;
776                 }
777         }
778
779         if (p2) probably_valid_to = (((LPBYTE)p2)-This->buffer->memory) + x2;
780         else probably_valid_to = (((LPBYTE)p1)-This->buffer->memory) + x1;
781         while (probably_valid_to >= This->buflen)
782                 probably_valid_to -= This->buflen;
783         if ((probably_valid_to == 0) && ((x1+x2) == This->buflen) &&
784             ((This->state == STATE_STARTING) ||
785              (This->state == STATE_PLAYING)))
786                 /* see IDirectSoundBufferImpl_Lock */
787                 probably_valid_to = (DWORD)-1;
788         This->probably_valid_to = probably_valid_to;
789
790         return DS_OK;
791 }
792
793 static HRESULT WINAPI IDirectSoundBufferImpl_Restore(
794         LPDIRECTSOUNDBUFFER8 iface
795 ) {
796         ICOM_THIS(IDirectSoundBufferImpl,iface);
797         FIXME("(%p):stub\n",This);
798         return DS_OK;
799 }
800
801 static HRESULT WINAPI IDirectSoundBufferImpl_GetFrequency(
802         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq
803 ) {
804         ICOM_THIS(IDirectSoundBufferImpl,iface);
805         TRACE("(%p,%p)\n",This,freq);
806
807         if (freq == NULL) {
808                 WARN("invalid parameter: freq = NULL\n");
809                 return DSERR_INVALIDPARAM;
810         }
811
812         *freq = This->freq;
813         TRACE("-> %ld\n", *freq);
814
815         return DS_OK;
816 }
817
818 static HRESULT WINAPI IDirectSoundBufferImpl_SetFX(
819         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes
820 ) {
821         ICOM_THIS(IDirectSoundBufferImpl,iface);
822         DWORD u;
823
824         FIXME("(%p,%lu,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
825
826         if (pdwResultCodes)
827                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
828
829         WARN("control unavailable\n");
830         return DSERR_CONTROLUNAVAIL;
831 }
832
833 static HRESULT WINAPI IDirectSoundBufferImpl_AcquireResources(
834         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes
835 ) {
836         ICOM_THIS(IDirectSoundBufferImpl,iface);
837         DWORD u;
838
839         FIXME("(%p,%08lu,%lu,%p): stub\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
840
841         if (pdwResultCodes)
842                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
843
844         WARN("control unavailable\n");
845         return DSERR_CONTROLUNAVAIL;
846 }
847
848 static HRESULT WINAPI IDirectSoundBufferImpl_GetObjectInPath(
849         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject
850 ) {
851         ICOM_THIS(IDirectSoundBufferImpl,iface);
852
853         FIXME("(%p,%s,%lu,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
854
855         WARN("control unavailable\n");
856         return DSERR_CONTROLUNAVAIL;
857 }
858
859 static HRESULT WINAPI IDirectSoundBufferImpl_Initialize(
860         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND8 dsound,LPDSBUFFERDESC dbsd
861 ) {
862         ICOM_THIS(IDirectSoundBufferImpl,iface);
863         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
864         DPRINTF("Re-Init!!!\n");
865         WARN("already initialized\n");
866         return DSERR_ALREADYINITIALIZED;
867 }
868
869 static HRESULT WINAPI IDirectSoundBufferImpl_GetCaps(
870         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps
871 ) {
872         ICOM_THIS(IDirectSoundBufferImpl,iface);
873         TRACE("(%p)->(%p)\n",This,caps);
874
875         if (caps == NULL) {
876                 WARN("invalid parameter: caps == NULL\n");
877                 return DSERR_INVALIDPARAM;
878         }
879
880         if (caps->dwSize < sizeof(*caps)) {
881                 WARN("invalid parameter: caps->dwSize = %ld < %d\n",caps->dwSize, sizeof(*caps));
882                 return DSERR_INVALIDPARAM;
883         }
884
885         caps->dwFlags = This->dsbd.dwFlags;
886         if (This->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
887         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
888
889         caps->dwBufferBytes = This->buflen;
890
891         /* This value represents the speed of the "unlock" command.
892            As unlock is quite fast (it does not do anything), I put
893            4096 ko/s = 4 Mo / s */
894         /* FIXME: hwbuf speed */
895         caps->dwUnlockTransferRate = 4096;
896         caps->dwPlayCpuOverhead = 0;
897
898         return DS_OK;
899 }
900
901 static HRESULT WINAPI IDirectSoundBufferImpl_QueryInterface(
902         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj
903 ) {
904         ICOM_THIS(IDirectSoundBufferImpl,iface);
905
906         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
907
908         *ppobj = NULL;  /* assume failure */
909
910         if ( IsEqualGUID(riid, &IID_IUnknown) || 
911              IsEqualGUID(riid, &IID_IDirectSoundBuffer) || 
912              IsEqualGUID(riid, &IID_IDirectSoundBuffer8) ) {
913                 IDirectSoundBuffer8_AddRef((LPDIRECTSOUNDBUFFER8)This);
914                 *ppobj = This;
915                 return S_OK;
916         }
917
918         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ||
919              IsEqualGUID( &IID_IDirectSoundNotify8, riid ) ) {
920                 if (!This->notify) {
921                         This->notify = (IDirectSoundNotifyImpl*)HeapAlloc(GetProcessHeap(),
922                                 HEAP_ZERO_MEMORY,sizeof(*This->notify));
923                         if (This->notify) {
924                                 This->notify->ref = 0;  /* release when ref == -1 */
925                                 This->notify->lpVtbl = &dsnvt;
926                         }
927                 }
928                 if (This->notify) {
929                         IDirectSoundNotify_AddRef((LPDIRECTSOUNDNOTIFY)This->notify);
930                         *ppobj = (LPVOID)This->notify;
931                         return S_OK;
932                 }
933                 WARN("IID_IDirectSoundNotify\n");
934                 return E_NOINTERFACE;
935         }
936
937         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
938                 if (!This->ds3db)
939                         IDirectSound3DBufferImpl_Create(This, &This->ds3db);
940                 *ppobj = This->ds3db;
941                 if (*ppobj) {
942                         IDirectSound3DBuffer_AddRef((LPDIRECTSOUND3DBUFFER)*ppobj);
943                         return S_OK;
944                 }
945                 WARN("IID_IDirectSound3DBuffer\n");
946                 return E_NOINTERFACE;
947         }
948
949         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
950                 ERR("app requested IDirectSound3DListener on secondary buffer\n");
951                 return E_NOINTERFACE;
952         }
953
954         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
955                 if (!This->iks)
956                         IKsPropertySetImpl_Create(This, &This->iks);
957                 *ppobj = This->iks;
958                 if (*ppobj) {
959                         IKsPropertySet_AddRef((LPKSPROPERTYSET)*ppobj);
960                         return S_OK;
961                 }
962                 WARN("IID_IKsPropertySet\n");
963                 return E_NOINTERFACE;
964         }
965
966         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
967
968         return E_NOINTERFACE;
969 }
970
971 static ICOM_VTABLE(IDirectSoundBuffer8) dsbvt =
972 {
973         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
974         IDirectSoundBufferImpl_QueryInterface,
975         IDirectSoundBufferImpl_AddRef,
976         IDirectSoundBufferImpl_Release,
977         IDirectSoundBufferImpl_GetCaps,
978         IDirectSoundBufferImpl_GetCurrentPosition,
979         IDirectSoundBufferImpl_GetFormat,
980         IDirectSoundBufferImpl_GetVolume,
981         IDirectSoundBufferImpl_GetPan,
982         IDirectSoundBufferImpl_GetFrequency,
983         IDirectSoundBufferImpl_GetStatus,
984         IDirectSoundBufferImpl_Initialize,
985         IDirectSoundBufferImpl_Lock,
986         IDirectSoundBufferImpl_Play,
987         IDirectSoundBufferImpl_SetCurrentPosition,
988         IDirectSoundBufferImpl_SetFormat,
989         IDirectSoundBufferImpl_SetVolume,
990         IDirectSoundBufferImpl_SetPan,
991         IDirectSoundBufferImpl_SetFrequency,
992         IDirectSoundBufferImpl_Stop,
993         IDirectSoundBufferImpl_Unlock,
994         IDirectSoundBufferImpl_Restore,
995         IDirectSoundBufferImpl_SetFX,
996         IDirectSoundBufferImpl_AcquireResources,
997         IDirectSoundBufferImpl_GetObjectInPath
998 };
999
1000 HRESULT WINAPI SecondaryBuffer_Create(
1001         IDirectSoundImpl *This,
1002         IDirectSoundBufferImpl **pdsb,
1003         LPDSBUFFERDESC dsbd)
1004 {
1005         IDirectSoundBufferImpl *dsb;
1006         LPWAVEFORMATEX wfex = dsbd->lpwfxFormat;
1007         HRESULT err = DS_OK;
1008         DWORD capf = 0;
1009         int use_hw;
1010
1011         if (dsbd->dwBufferBytes < DSBSIZE_MIN || dsbd->dwBufferBytes > DSBSIZE_MAX) {
1012                 WARN("invalid parameter: dsbd->dwBufferBytes = %ld\n", dsbd->dwBufferBytes);
1013                 *pdsb = NULL;
1014                 return DSERR_INVALIDPARAM; /* FIXME: which error? */
1015         }
1016
1017         dsb = (IDirectSoundBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1018
1019         if (dsb == 0) {
1020                 WARN("out of memory\n");
1021                 *pdsb = NULL;
1022                 return DSERR_OUTOFMEMORY;
1023         }
1024         dsb->ref = 0;
1025         dsb->dsound = This;
1026         dsb->lpVtbl = &dsbvt;
1027
1028         memcpy(&dsb->dsbd, dsbd, sizeof(*dsbd));
1029         if (wfex)
1030                 memcpy(&dsb->wfx, wfex, sizeof(dsb->wfx));
1031
1032         TRACE("Created buffer at %p\n", dsb);
1033
1034         dsb->buflen = dsbd->dwBufferBytes;
1035         dsb->freq = dsbd->lpwfxFormat->nSamplesPerSec;
1036
1037         /* Check necessary hardware mixing capabilities */
1038         if (wfex->nChannels==2) capf |= DSCAPS_SECONDARYSTEREO;
1039         else capf |= DSCAPS_SECONDARYMONO;
1040         if (wfex->wBitsPerSample==16) capf |= DSCAPS_SECONDARY16BIT;
1041         else capf |= DSCAPS_SECONDARY8BIT;
1042         use_hw = (This->drvcaps.dwFlags & capf) == capf;
1043
1044         /* FIXME: check hardware sample rate mixing capabilities */
1045         /* FIXME: check app hints for software/hardware buffer (STATIC, LOCHARDWARE, etc) */
1046         /* FIXME: check whether any hardware buffers are left */
1047         /* FIXME: handle DSDHEAP_CREATEHEAP for hardware buffers */
1048
1049         /* Allocate system memory if applicable */
1050         if ((This->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) || !use_hw) {
1051                 dsb->buffer = HeapAlloc(GetProcessHeap(),0,sizeof(*(dsb->buffer)));
1052                 if (dsb->buffer == NULL) {
1053                         WARN("out of memory\n");
1054                         HeapFree(GetProcessHeap(),0,dsb);
1055                         *pdsb = NULL;
1056                         return DSERR_OUTOFMEMORY;
1057                 }
1058
1059                 dsb->buffer->memory = (LPBYTE)HeapAlloc(GetProcessHeap(),0,dsb->buflen);
1060                 if (dsb->buffer->memory == NULL) {
1061                         WARN("out of memory\n");
1062                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1063                         HeapFree(GetProcessHeap(),0,dsb);
1064                         *pdsb = NULL;
1065                         return DSERR_OUTOFMEMORY;
1066                 }
1067         }
1068
1069         /* Allocate the hardware buffer */
1070         if (use_hw) {
1071                 err = IDsDriver_CreateSoundBuffer(This->driver,wfex,dsbd->dwFlags,0,
1072                                                   &(dsb->buflen),&(dsb->buffer->memory),
1073                                                   (LPVOID*)&(dsb->hwbuf));
1074                 if (err != DS_OK) {
1075                         WARN("IDsDriver_CreateSoundBuffer failed\n");
1076                         if (dsb->buffer->memory)
1077                                 HeapFree(GetProcessHeap(),0,dsb->buffer->memory);
1078                         if (dsb->buffer)
1079                                 HeapFree(GetProcessHeap(),0,dsb->buffer);
1080                         HeapFree(GetProcessHeap(),0,dsb);
1081                         *pdsb = NULL;
1082                         return err;
1083                 }
1084         }
1085
1086         /* calculate fragment size and write lead */
1087         DSOUND_RecalcFormat(dsb);
1088
1089         /* It's not necessary to initialize values to zero since */
1090         /* we allocated this structure with HEAP_ZERO_MEMORY... */
1091         dsb->playpos = 0;
1092         dsb->buf_mixpos = 0;
1093         dsb->state = STATE_STOPPED;
1094
1095         dsb->freqAdjust = (dsb->freq << DSOUND_FREQSHIFT) /
1096                 This->wfx.nSamplesPerSec;
1097         dsb->nAvgBytesPerSec = dsb->freq *
1098                 dsbd->lpwfxFormat->nBlockAlign;
1099
1100         if (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D) {
1101                 dsb->ds3db_ds3db.dwSize = sizeof(DS3DBUFFER);
1102                 dsb->ds3db_ds3db.vPosition.u1.x = 0.0;
1103                 dsb->ds3db_ds3db.vPosition.u2.y = 0.0;
1104                 dsb->ds3db_ds3db.vPosition.u3.z = 0.0;
1105                 dsb->ds3db_ds3db.vVelocity.u1.x = 0.0;
1106                 dsb->ds3db_ds3db.vVelocity.u2.y = 0.0;
1107                 dsb->ds3db_ds3db.vVelocity.u3.z = 0.0;
1108                 dsb->ds3db_ds3db.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
1109                 dsb->ds3db_ds3db.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
1110                 dsb->ds3db_ds3db.vConeOrientation.u1.x = 0.0;
1111                 dsb->ds3db_ds3db.vConeOrientation.u2.y = 0.0;
1112                 dsb->ds3db_ds3db.vConeOrientation.u3.z = 0.0;
1113                 dsb->ds3db_ds3db.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;
1114                 dsb->ds3db_ds3db.flMinDistance = DS3D_DEFAULTMINDISTANCE;
1115                 dsb->ds3db_ds3db.flMaxDistance = DS3D_DEFAULTMAXDISTANCE;
1116                 dsb->ds3db_ds3db.dwMode = DS3DMODE_NORMAL;
1117
1118                 dsb->ds3db_need_recalc = FALSE;
1119                 DSOUND_Calc3DBuffer(dsb);
1120         } else
1121                 DSOUND_RecalcVolPan(&(dsb->volpan));
1122
1123         InitializeCriticalSection(&(dsb->lock));
1124
1125         /* register buffer */
1126         RtlAcquireResourceExclusive(&(This->lock), TRUE);
1127         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
1128                 IDirectSoundBufferImpl **newbuffers = (IDirectSoundBufferImpl**)HeapReAlloc(GetProcessHeap(),0,This->buffers,sizeof(IDirectSoundBufferImpl*)*(This->nrofbuffers+1));
1129                 if (newbuffers) {
1130                         This->buffers = newbuffers;
1131                         This->buffers[This->nrofbuffers] = dsb;
1132                         This->nrofbuffers++;
1133                         TRACE("buffer count is now %d\n", This->nrofbuffers);
1134                 } else {
1135                         ERR("out of memory for buffer list! Current buffer count is %d\n", This->nrofbuffers);
1136                         if (dsb->buffer->memory)
1137                                 HeapFree(GetProcessHeap(),0,dsb->buffer->memory);
1138                         if (dsb->buffer)
1139                                 HeapFree(GetProcessHeap(),0,dsb->buffer);
1140                         DeleteCriticalSection(&(dsb->lock));
1141                         RtlReleaseResource(&(This->lock));
1142                         HeapFree(GetProcessHeap(),0,dsb);
1143                         *pdsb = NULL;
1144                         return DSERR_OUTOFMEMORY;
1145                 }
1146         }
1147         RtlReleaseResource(&(This->lock));
1148         IDirectSound8_AddRef((LPDIRECTSOUND8)This);
1149         *pdsb = dsb;
1150         return S_OK;
1151 }